Kysely

K

Kysely

Join the community to ask questions about Kysely and get answers from other members.

Join

help

query-showcase

announcements

I’m well versed in SQL and priority #1 is performance. Can Kysely still make sense for me?

The TLDR is, I am impressed by Kysely and it seems like a great library… but I also don’t want to use it just because it looks wonderful 😉 I am brand new to the ORM / query builder world. We are migrating a project to SQLite and my decision is coming down to raw SQL (which I am very comfortable with and is my natural inclination) vs Kysely. Here are some questions I have: 1. Could / should I use Kysely and just use the sql template literal tags which is comfortable for me given my raw SQL experience? 2. Are there performance considerations? I know with full blown ORM the answer is obviously yes but wondering with Kysely if there are many performance trade offs in comparison to writing raw sql?...
Solution:
1. If you only use raw SQL, Kysely offers very little to no type-safety for you. 2. With other dialects, not really. With sqlite, Kysely wraps the better-sqlite synchronous API to an async API that can decrease performance. I haven't measured it, but there could be an impact. 3. Yes. 4. You can think of Kysely just as a type-safe way to write raw SQL. That's all it tries to do and that's pretty much the only benefit....

Creating helper functions

I've gotten to the point in my application where a lot of the objects I'm building in my queries are returning in other queries. In the following example I'd like to extract the module (with color) into something I can use in other queries. I've been trying to find the correct (and working) way to this...
Solution:
```ts function moduleWithColor(moduleId: Expression<string>) { const eb = expressionBuilder<Database, never>() return jsonObjectFrom(...

how to union two queries with json_build_object?

i would like to union two queries to get a result of type QueryA | QueryB. this query fails the type checker but the generated query seems to work as intended. is there a type hint i can provide somehow? https://kyse.link/2TBLF...
Solution:
The unioned expressions need to have the same type. You used first_name in the first one an name in the second one. If both have the same property name it works. https://kyse.link/Bc300 When you use different keys, the correct type of the JSON object would be { name: string | undefined, first_name: string | undefined } but Kysely isn't able to infer it....

bulk-insert with constant variable as one column

Hey, I'm basically trying to mirror https://stackoverflow.com/questions/6937442/in-postgres-is-it-possible-to-insert-a-constant-combined-with-the-result-of-sel. I can't figure out how I'd achieve this with Kysely. I'm currently here: ```ts await trx...
Solution:
<#1239624163682029690> Had me covered! ```ts await trx .insertInto("mapped_groups") .columns(["group_id_fk", "mapped_id_fk"])...

Making CTE's reusable

I wanted to make certain cte's in my project reusable and came up with the following solution. Is there a "kysely" way to do this? ```ts...
Solution:
Hey 👋 There isn't a "kysely way" to do this....

pg migration raw sql CREATE FUNCTION gets error: "TypeError: Cannot redefine property: then"

When I try: `` await sql CREATE FUNCTION universal_history_trigger_function()...
Solution:
So took a bit of searching every possible previous issue/thread and finally stumbled across this answer from @koskimas in another thread last year: https://discord.com/channels/890118421587578920/1108366659707736154/1108386004232060938
You have two (or more) incompatible versions of Kysely and you are mixing parts of them.
In my case this somehow occurred from kysely v0.27.3 + kysely-ctl 0.8.7. Bumped to v.0.27.4 + 0.9.0 respectively fixed it....

Roll back transaction prematurely

Given a Transaction, how do I roll it back without throwing an Error inside the execution callback method? ```ts return this._db.transaction().execute(async trx => { const entryType = await this._db...
Solution:
I managed to solve it with a wrapper function. Here it is, for anyone who may need it in the future: ``ts /** * Wraps a Kysely transaction such that any Err` returned from the callback results in a rollback....

Dynamic query parts based on user input

Based on certain user input (REST API), I need to filter and/or sort by provided fields. This could mean that some joins need to be added as well. The fields to filter and sort are not always a 1-1 mapping to a database column, the names can deviate. ...

Unable to use table name with 3 dots in selectFrom

Hey I am using the bigquery dialect adapter and I am trying to query the information schema. it has the following structure <DATASET>.INFORMATION_SCHEMA.COLUMNS but when I pass a string with this structure to the "selectFrom" it just takes the first two...

Updateable primary key question & .set() type safety

Do you all wrap your Updateable versions of tables to omit id? Or am I doing something unconventional here. Also how do you get typesafety on set() calls to prevent it accepting an item with id (or whatever primary key) from being updated?...
Solution:
Hey 👋 To define a column that's never updated, you can use ColumnType with never in the 3rd generic value. ```ts...

Error: don't await SelectQueryBuilder instances directly.

To execute the query you need to call execute or executeTakeFirst. I'm trying to create a function that enhances the query (SelectQueryBuilder) with pagination, sorting and filtering options that are derived from a HTTP request. This function looks like:...
Solution:
If you return a thenable object from an async function its then method gets called. Kysely query builders all have a then method that throws that exception. It's there because many other query builders and ORMs allow you to do stuff like
const result = await db.selectFrom('person').selectAll()
const result = await db.selectFrom('person').selectAll()
...

JSON Object Traversal

Hi everyone, new user of Kysely. I have the following json object inside a sess column: ```json { "cookie": {...
Solution:
Just use ->> for all of them?

express-session store

Hi, I'm a new user of Kysely. I'm wondering if there is a way to connect kysely with express-session. For example, to use in combination with passport. For example, I was wondering if Kysely somehow exposes a pg compatible pg.Pool, which would allow me to use something like connect-pg-simple to have an adapter from the Kysely world to the pg world....
Solution:
I just realized that I can reuse the pg.Pool that Kysely uses when I added the Postgres dialect, so that solves that problem 😄

Synchronous queries to SQLite?

Is there any way to make synchronous queries to SQLite? As I understand it, better-sqlite3 is a synchronous library and Kysely's SQLite dialect uses better-sqlite3, so is there a way to make synchronous queries?
Solution:
There's no way to do that. The only dialect where a synchronous API would make sense is sqlite and we'd need to add a synchronous alternative of EVERYTHING for that tho work. If I'm not mistaken, the reason why better-sqlite3 is faster is that it's synchronous internally greatly reducing mutex thrashing. We're just wrapping that same API to a couple of layers of async javascript code. I haven't run any performance benchmarks, but the performance might not be affected too much....

Return type when fields are conditional

Probably more of a TypeScript question than a Kysely question, but how would I type the output of a wrapper function that allows the conditional specification of fields. E.g. ```ts export function selectActivitiesByActivityId(activityIds: number[], fields: Array<keyof ActivityHistoryTable> = []) { const db = createKysely();...

What's the best way to use Pick with Selectable/Insertable/Updatable?

I am newer to typescript so fully possible missing something obvious here. But if I try to Pick from a table schema wrapped in Selectable/Insertable/Updateable it doesn't seem to infer the actual type of the column. Example (first screenshot): x has no typescript issue here (just warns its unused in this fake code). "test" type shows resolving as: ``` type test = {...
Solution:
Actually I think this is environmental - I found there is a kysely sandbox and I couldn't repro there - it works perfect there in how I showed/you showed in the "better yet". I am going to close this and thanks again @koskimas
No description

Issue with select

How would I handle doing what I'm doing in the raw part during the select? ``` const result = await db .with("townhallDistribution", (qb) =>...

Issue with migrating from knex

I've recently learned about Kysely and how it is very compatible with TS compared to Knex. I'm also very new to coding in general and have been following the structure I was taught at school earlier this year but I'm struggling right now to migrate the file that initializes data and shuts it down. If anyone would be so kind to help me figure out how to move this from Knex to Kysely!...

how to decode a point to `{x: number, y: number}` when selected inside `jsonBuildObject`?

when i select a column of type point the basic way i get it decoded to {x: number, y: number}, but when i wrap it in jsonBuildObject i get it as the raw string. example: ```ts...
Solution:
The only way to detect those columns inside JSON is regex or similar. There's no type info. In JSON, that's just a string.

need advice how to configure driver to return prefixed or drizzle style selections

Ideally I would like to get shape with a query like drizzle offers, meaning each table has its own object (eg. products joined with tax would return multiple rows as {product:{}, tax:{}}) or at least add a prefix to the columns. From what I read yesterday, this is beyond the scope of kysely, and more of a db driver task. Has anyone done something similar in combination with kysely and could give me a hint, because I don't really know how to go about it. Thanks!
Solution:
That is an ORM task. You can't get something like that in the general case without thousands of lines of code. That code includes modifying the SQL to get foreign keys selected if you don't manually select them, figuring out which row goes with which row, renaming selections and all kinds of crap. All of which will fuck up the rest of the query. You can't build the rest of the query using arbitary SQL anymore since the query has been mangled into unrecognizable abomination. The selection you try to reference no longer exists, you can't use group by since the query structure is completely differenet from what you think etc. At that point, you need more higher level ORM concepts that are able to deal with the mangled query....
Next