Converting a more complex query to Kysely
I wrote this query for my database, and I've been trying to convert it to use Kysely but can't seem to. I'd like to figure it out (rather than just use string SQL)
The query:
What I've got so far (WIP)
Any help is appreciated 🙂
15 Replies
Solution
Here you go https://kyse.link/?p=s&i=3wmZrPkueuX6dxgeZ0Lz
If you are absolutely sure
position_in_queue
can't be null, you can use this https://kyse.link/?p=s&i=uQMeXqMnIDdWbul02jGSThank you SO much, my biggest problems were that I didn't realize I could put the alias in
selectFrom
. Also not using whereRef
instead of where
You're welcome!
whereRef
is equal to where('foo', '=', eb.ref('bar'))
so you can use whichever you prefer.gotcha!
When I use
$narrowType
is that supposed to make the output of position_in_queue
a number?Kysely can't always correctly determine if something can be null or not. By default you get
number |Â null
for position_in_queue
in this query. But since the subquery is using count
, it can't return null
.
$narrowType
is used to cast away the null
$narrowType
is still very type-safe. You can't accidentally change the type of a column. You can only narrow it. You also can't accidentally add a column that doesn't exist.Ahhh I understand, for some reason it's giving me a string at the moment for
position_in_queue
. That's why I was a bit confused$narrowType
is only a type-level helper. It doesn't affect the runtime
You're probably using postgres. Postgres returns strings for numbers that could (in theory) be larger than the maximum integer the javascript number can represent (2^53-1)I'm using Planetscale which I believe uses MySQL
You can configure postgres to return numbers, but you need to do that for the
pg
driver
Well the same thing applies. You need to configure the driver. Kysely never touches the data. You need to modify the types to match the underlying driver.ah I see, thank you!
Most drivers have some way to make type transformations for cases like this
regardless, output type isn't too important. Thank you again so much
Hey 👋
The underlying planetscale driver used in the community dialect you're using has data transformation support
https://github.com/planetscale/database-js#custom-type-casting-function
GitHub
GitHub - planetscale/database-js: A Fetch API-compatible PlanetScal...
A Fetch API-compatible PlanetScale database driver - GitHub - planetscale/database-js: A Fetch API-compatible PlanetScale database driver
GitHub
GitHub - depot/kysely-planetscale: A Kysely dialect for PlanetScale...
A Kysely dialect for PlanetScale Serverless. Contribute to depot/kysely-planetscale development by creating an account on GitHub.