Kysely

K

Kysely

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

Join

help

query-showcase

announcements

How can I join 2 tables where 1 side is a JSON property in a JSON column?

I am trying this: ``` db.selectFrom('my_table') .selectAll(['my_table']) .innerJoin(...
Solution:
Hey 👋 ```ts const rows = await db .selectFrom("my_table")...

2-Way transforming of types

My front-end wants UUIDs in a shortened format (i.e. base-64'd encode of the uuid bytes). In order to minimize workload, I was hoping I could write some sort of transformer that I could plug into kysely that would inflate shortened UUIDs when going into the DB and deflate them to the shortened format when they go out. I can't see anything obvious that would serve me to this end. Any suggestions?...

Pagination

Hi everyone, I have a question. I'm working with a database in mssql and I'm creating a function to paginate the data in a table. For this I was doing something like the following: const person = await db .selectFrom('person') .selectAll() .where('id', '=', '1') .offset(0)...
Solution:
Kysely never "translates" anything.

[Bug] innerJoinLateral selectAll prepends schema

apologies for the hastily written bug report. i found a workaround so im not super concerned. writing this down in case it's helpful: 1. have a postgres db variable that's instantiated withSchema pointed at my_schema 2. selectFrom my_table with an innerJoinLateral on my_computed_object 3. select jsonObjectFrom(eb.selectFrom('my_computed_object').selectAll('my_computed_object'))...
Solution:
Use withSchema('public') for the subquery

Executing stored procedure in MS SQL

Hello, I've used Kysely for PG DB and love it, now I have a MSS SQL project and need to execute some Stored Procedures, how would one do this?
Solution:
Hey 👋 Kysely has nothing for Stored Procedure execution. Wrap each execution with a type-safe function. Use sql under the hood. If these things can be introspected, there is potential in generating these type-safe functions....

Flatten type of single column select?

Hi! I have helpers that look roughly like this: ``` function ownerId(organizationId: Expression<number>) { eb.selectFrom('organization')...
Solution:
Hey 👋 There's a $asScalar() utility method that's probably landing in v0.28. https://github.com/kysely-org/kysely/blob/v0.28/src/query-builder/select-query-builder.ts#L1938-L1986...

Is there a way to execute parameterized SQL (with paremeters) within a kysely migration?

I have a third party library that requires I make some changes to the database. I want to run this as part of my other kysely migrations. This library gives me an array of [sql : string, parameters : unknown[]]. Any idea how best I should run these as part of a kysely migration?

Typing enums

First of all, I still really enjoy using Kysely, great library! I have the following pattern for enums. I create the role table as an "enum" table (which I got from another help post I was reading earlier) and add it as an foreign key to the teacher table. ```ts...

Any update on all migrations in single-transaction?

Is there anything new with the single-transaction for all migrations? Need something like this: ```typescript...

V0.28 Type Issues

Hey i've been trying to use v0.28 branch, but whenever i install this branch from pnpm all the kysely types break, is there another way for me to use this branch. I tried locally cloning and building but seem to have the same type issues. Typescript just can't find kysely package at all.
Solution:
npm i https://pkg.pr.new/kysely-org/kysely@1278

Unioning an array of sql`{SQL_QUERY}`

Hey chaps, I'm doing some really heinous shit with triggers etc (hence why I'm not using Kysely's default query builder syntax). I have an array of SQL queries that I'd like to UNION ALL together - any idea how best to do that? Note - the length of the query array is dynamic - Thanks!!

Identically named columns in multiple tables - How to use innerJoin.selectAll()?

Hey, I am new to using kysely, and also relatively new to using PostgreSQL. I have trouble with the following query: ```js...
Solution:
Hey 👋🏻 You have 3 options: 1. use table scoped selectAll on 1 table (selectAll('tables')) and then select the other table/s columns while aliasing columns that exist multiple "tables"....

Type safe discriminated union query

I am looking for a way to make this query more type safe. The generated SQL gives me the result I want, which adheres to the specified union type, but typescript needs some convincing and the $castTo assertions I have added are hurting type safety. If I remove .$castTo<unknown>() in the task query I get this error in the event query Property 'description' is missing in type '{ event_name: string; }' but required in type '{ description: string; }', and similar in the note query....

Improving TS compile speed with multiple conditional selects?

Hi, I have API endpoints that query Postgres via Kysely. The API endpoints accept an include object that determines whether to include various optional fields. Some endpoints have grown to accept 5-10 optional fields. Each of these optional fields results in an additional $if branch in the Kysely query. And this seems to harm TS compile speed -- I'm now waiting 1-3min for each compilation. What are the best ways to mitigate the compile speed downsides of using many $if calls?...

Type safety in checkExpression in addCheckConstraint

Hi, is it possible somehow utilise kysely to create type-safe checkExpression and avoid writing stuff like this: ```typescript .addCheckConstraint( 'constraint-name',...

Trouble with dynamically allocating table name via string

Hello! I am having some trouble trying to allocate a table name dynamically via a string. I used the sql.table command in my SelectFrom statement but no such luck. Passing in a direct string also does not work as hoped. I have read a few posts which indicate this is not possible, if not I can work around it, if it is however how might I achieve this?...

Dynamic expression builder using raw SQL for WHERE column LIKE string% OR

Hello! We switched over to using Kysely in our project and it's going great so far! But I found a bit of a hitch with writing an old dynamic WHERE LIKE query. I need to get the results of file paths stored in our system that start with a directory path. Previously in pure SQL we would generate an expression like this:...
Solution:
@Igal that works great. Leaving the full solution here for others who come looking
const condition = dirPaths.map((dir) =>
sql<boolean>`file_path LIKE ${dir + '%'}`)
.reduce((acc, condition) => sql<boolean>`${acc} OR ${condition}`);
const condition = dirPaths.map((dir) =>
sql<boolean>`file_path LIKE ${dir + '%'}`)
.reduce((acc, condition) => sql<boolean>`${acc} OR ${condition}`);
...

How to define multiple configs in a NX monorepo?

Hi, we have multiple applications in a NX monorepo and I need separate configs for migrations and seeders. How would you recommend to do it? When using kysely init it creates the kysely.config.ts in the root ./config. Should I use conditional app selection by env variables?

Making Updateable<X> fields required

Excuse me if this has already been posted, but I recently turned on strict mode after completing my migration to TS and I'm struggling to make certain fields required when updating an entity. When I hover over UpdateableActivity it shows: ```ts...
Solution:
You can't make them required by kysely. In SQL update statements, every column is optional. You can have your own interface that makes some fields required and use that as an input for your own update functions that use kysely....

ilike with reference

Hey there, I'm looking to perform the following SQL operation:
WHERE groups.group_name ILIKE '%' || users.first_name || '%'
WHERE groups.group_name ILIKE '%' || users.first_name || '%'
but unfortunately I'm having trouble doing this in Kysely. Here is my current attempt:...
Solution:
Using
sql`'%'`,
sql`'%'`,
Seemed to do the trick, instead of eb.val("%"). Any other ways to make this more ergonomic?...