Kysely

K

Kysely

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

Join

help

query-showcase

announcements

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....

problem with nested jsonArrayFrom and jsonObjectFrom

Typescript raise error when attempt to reference to relations in nested json helpers is made. Is this syntax error or kysely limitation? https://kyse.link/SL7ct...
Solution:
Hey 👋 You can't just use the same eb for all depths. The one you've used doesn't have line nor subline in its query context. This works:...

Is there way to select every field from table using `select` instead of `selectAll`?

I have very wide table and writing every field by hand is time consuming. selectAll does the job, but I also need to populate some relations and build json_aggs. Is there way to either select every column from table (and then build jsonObject) or extend selectAll with some extra fields? ``` db .selectFrom('document') .select((eb)=> [...
Solution:
.selectAll('document')
.select(eb => ...)
.selectAll('document')
.select(eb => ...)
...