Kysely

K

Kysely

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

Join

help

query-showcase

announcements

Can't figure out how to add a unique index on (foo, LOWER(bar)) for a table

Sorry chaps if this is obvious but can't seem to see any mention of this in the docs. I need to create a unique index on a tuple of columns - with the caveat that the second column is "case insensitive" - i achieve this by lowercasing the second column. I believe this is quite normal to do in vanilla pg but am unsure what the idiomatic way to do this in kysely is...
Solution:
Answer: When constructing an index, you can daisy chain .column and .expression. Thus, you would do: ```typescript...

Using AsyncLocalStorage to Propagate Transaction Context

I'm trying to implement a pattern where I can use AsyncLocalStorage to automatically propagate a transaction context without having to explicitly pass a transaction object throughout my codebase. The goal is to be able to write code like this: ```ts const updateUsername = async (username: string) => {...

Joining multiple separate CTE's

I am working on a complex query. I can get it to run efficiently using multiple CTE's(Atleast in RAW SQL) but I want to port all this over to Kysely due to the typesafety. What I want is something like this: const cteOne = kyselyDb...
Solution:
conditionally added CTEs are not supported - too much type complexity involved. you could union with a subquery conditionally tho, as the result shape is already established, and union can be added to existing builder instances, outside of chain (but also with $call)....

Is this a correct situation to use $castTo (jsonArrayFrom + Left Join)

```ts // snippet from main query: jsonArrayFrom( eb .selectFrom('address')...

Inconsistent Typing of NUMERIC Fields with jsonBuildObject

https://kyse.link/wxJiK I came across an issue on GitHub (link) where JSON fields in PostgreSQL aren't automatically typed correctly due to everything being returned as a string. This means that when using jsonObjectFrom, the returned type is string, rather than the expected data type like Date. What's puzzling is that this behavior isn't consistent across all data types. For instance, NUMERIC values at the root level are returned as strings (which is fine), but when those same values appear inside a nested JSON object, their type is inferred as number instead. I would prefer to have NUMERIC values inside JSON objects returned as string to keep it consistent with how they are handled at the root level....
Solution:
So, you either need those explicit casts, or allow the DB to cast the value to JSON number and fix your types.

AggregateFunctionBuilder inside a SUM

Hi there, I'm trying to build
SUM(CASE WHEN IsNoShow = 0 AND IsDNA = 0 THEN 1 ELSE 0 END)
SUM(CASE WHEN IsNoShow = 0 AND IsDNA = 0 THEN 1 ELSE 0 END)
...
Solution:
Here you go https://kyse.link/X1Vxc Our types are a bit too strict and give the type 100 instead of number for eb.lit(100)...

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