Kysely

K

Kysely

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

Join

help

query-showcase

announcements

sql literal string in binary expression builder

Hi, I want the following: ```sql SELECT sum("ChargeAmount" * "1.0") AS "TotalChargeAmount" FROM...
Solution:
You definitely don't want "1.0" since that means you're referencing a column named 1.0

Query result type mismatch

For unknown to me reason kysely adds categoryId to nested object built with jsonObjectFrom or maybe it does not take related table, but copies selectFrom table. Why does it happen? https://kyse.link/0sjoX...
Solution:
Use selectAll('product_category') instead of selectAll() in the subquery
No description

Getting the underlying connection pool/client from a kysely wrapper

Hi guys, I have a migration script that takes a raw PgClient object. Was wondering if it would be possible to extract said object from the Kysely<any> that is passed into the migration functions (up down) thanks!...

Dynamic callbackURL on login

Hi guys, I wonder if it's possible to have a dynamic Dynamic callbackURL on login if the user is admin or not? Have a nice day....

Replicate ORM results

Hi guys, I wanted this result: `findPersonsWithPets: [...
Solution:
Hey 👋 Have you read https://kysely.dev/docs/recipes/relations ?...

postgres helper wrapping to_json referencing CTE?

is there a way to create a type safe postgres helper (recordToJson) that is similar to jsonObjectFrom, but that references an existing CTE. in essence i want to be able to do something like this ```typescript db .selectFrom('foo')...
Solution:
It's as simple as this https://kyse.link/t2h2a

Is it okay to repeatedly wrap a PG connection pool with kysely?

Chaps, my understanding is that it is safe to repeatedly wrap a postgres connection pool with kysely a la "new Kysely<DB>({dialect: new PostgresDialect({ pool }) })", and I can just let those kysely wrappers get garbage collected. Is this correct?

Convert record from Function call (RPC) to JSON

Hello, I am using raw SQL to run a function that returns a record, but it is returning it to the TS domain as a string like this:
"(b38ed355-c2b0-4998-aff9-8c8dc429ffe5,My_Test_Key,valid,aead-det,22,\"\\\\x7067736f6469756d\",\"2025-01-19 02:09:04.392092+00\",,\"\")"
"(b38ed355-c2b0-4998-aff9-8c8dc429ffe5,My_Test_Key,valid,aead-det,22,\"\\\\x7067736f6469756d\",\"2025-01-19 02:09:04.392092+00\",,\"\")"
instead of a JSON object with those values in key/value pairs. ...

Generating dynamic raw query help

Hello, we are trying to create a function utility to call RPCs, we want to dynamically generate the following SQL query:
SELECT my_function(arg1 => 'some_value', arg2 => 123);
SELECT my_function(arg1 => 'some_value', arg2 => 123);
...

could not determine data type of parameter $1

I am trying to nest PG functions array_agg and json_build_object I tried like this ```js select(({ fn, eb, val }) => { return fn...
Solution:
Ok, perplexity gave me the answer. You have to cast the key names à string with cast(val("foo_col"), "text")...

Overcoming issue with `withSchema` and `forUpdate`

Hi chaps, I just posted a github issue: https://github.com/kysely-org/kysely/issues/1324 w.r.t. Kysely using qualified table names in the forUpdate if withSchema is used. Postgres doesn't like this and will error - I wonder if there is anything I can do short-term/now to skirt this issue that doesn't cause the typechecker to complain? Thanks!
Solution:
For now, you can install a plugin like this to your Kysely instance. Unfortunately there's no other workaround before we fix the bug https://kyse.link/mj9c1

Performance impact of "$if" ?

According to the documentation, $if "has an impact on typescript performance and it should only be used when necessary". I would like to use it for conditional selects. How bad is the performance impact? Thanks in advance!
Solution:
It's impossible to predict. But if you start seeing long pauses before you get intellisense, try to reduce the $if calls to see if it helps. The impact is much smaller now than it was when I wrote that doc.

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