Kysely

K

Kysely

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

Join

help

query-showcase

announcements

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

select / groupBy combined helper

I realize this usecase looks awful, but our API takes an input of a list of fields to group by, which also means it will return those fields in the result. What I have works, but there's a lot of duplication: ```javascript .$if(isGroupedBy(STOP_ID), (qb) => qb.select('stopid as stopId').groupBy('stopid'),...
Solution:
But here's how you'd do it if you really really want to https://kyse.link/4PswR

How to delete and insert in one query

Hey! I wonder how with kysely make for example delete and insert in one query to reduce db roundtrips. ``` db.deleteFrom('a') .where('smthId', '=', a.id)...

.filterWhere inference

I have this in a select ```fn .coalesce( fn .jsonAgg(...
Solution:
You can use .$narrowType for this.

json object relation null problem

I am trying to make https://kysely.dev/docs/recipes/relations this helper work, but get error ``` Argument of type 'ExpressionWrapper<DB & { pozycja: DokumentPozycja; } & { rozbicie: DokumentPozycjaRozbicie; }, "dokument" | "pozycja" | "rozbicie", number | null>' is not assignable to parameter of type 'Expression<number>'. Types of property 'expressionType' are incompatible. Type 'number | null | undefined' is not assignable to type 'number | undefined'....
Solution:
Never use undefined or ? in your type interfaces.

How to narrow type from jsonArrayFrom

Hey! I need to narrow some types from table that works as Single Table Inheritance table. I believe this is possible, but after some fighting with api and syntax I am not sure how to make it. Here is my query: (sorry for polish, Ubiquitous Language with domain masters) ```...
Solution:
oh okey got it, .$narrowType<PrzyjecieZewnetrznePozycjaRozbicieSelect>() has to be straight after jsonArrayFrom not at the top level

How to narrow type in select

Is it possible to narrow type from enum company, person to just person in select query? ``` const results = await db .selectFrom('receiver') .where('type', '=', 'person')...
Solution:
See $narrowType

Subquery from a function

I want to reuse a sub-query that refers to one of the fields in the root query's result. I tried doing this: ```ts function queryIsFriendOf<DB extends DatabaseSchema, TB extends keyof DB>( eb: ExpressionBuilder<DB, TB>,...
Solution:
Don't pass in the expression builder. Its type easily becomes incompatible in other contexts. Don't use an explicit result type. The result type here is NOT boolean. It's { is_friend: boolean }. Yes, you can use that as a scalar in SQL and Kysely does handle that correctly. But don't explicitly set the wrong type. You always need to provide a name for selections using the as method. The name is dialect-specific if you leave it out. Since kysely types don't know which dialect you're using, providing a name for that column automatically is impossible....

why is WhereNode.where any operation node?

Hi. I'm working on a different query adapter (non-SQL), so I just want to ask why a WhereNode.where is simply any OperationNode and not a union of some operators (say boolean)
Solution:
It can be so many things that listing them as a union makes no sense.

are nested joins supported?

Like this one:
knex .select('*') .from('users') .join('accounts', function () { this.on(function () { this.on('accounts.id', '=', 'users.account_id'); this.orOn('accounts.owner_id', '=', 'users.id'); }); });
knex .select('*') .from('users') .join('accounts', function () { this.on(function () { this.on('accounts.id', '=', 'users.account_id'); this.orOn('accounts.owner_id', '=', 'users.id'); }); });
...

New dialect for snowflake - quotes and case sensitivity

Snowflake has different behavior compared to Postgres and other dialects currently in Kysely, I want to be able to control the casing of all identifiers / tables / schemas meaning that if I have query.selectFrom("table").select(["id"]) I want it to compile to the exact case as it is specified, and also to be able to control if with a configuration to the query compiler (this I imagine is just a simple amendment to the constructor) ...

Help with implementation of new dialect for snowflake

Hello, I am trying to create a new dialect for snowflake, I am focusing on the query compiling part. As I have read I saw that the snowflake dialect is supports standard SQL, however I don't know what does that mean when it comes to the DefaultQueryCompiler There are several things that snowflake does not support, such as indices....
Solution:
Hey πŸ‘‹ We avoid throwing in such situations in the core, as a design decision. Kysely always outputs something - "Bring Your Own SQL Knowledge". You can choose to throw in your compiler. It's perfectly fine!...

is there any helper to put all columns in json_build_object?

to avoid manuaΕ‚ typing all the columns?
Solution:
Nope.

Advice for debugging timeout/connection issues with Kysely

Hi everyone, We've been using Kysely with pg in prod in our startup for over a year now and everything has been mostly stable, however, we started encountering these random errors with no seemingly obvious reason. I am 99.9% sure that this is not a Kysely specific issue, but I'd be grateful if someone could advice us on how to debug these issues, as we don't have much experience in this. Googling revealed some stack overflow threads were timeout configs were discussed, but that didn't help us too much....