K
Kysely9mo ago
kalil

Error when destructuring QueryCreator in withRecursive

I'm new to Kysely and attempting to migrate a Next app from prisma to kysely. I've generated types, successfully run some simple queries, and now I'm experiencing an error (in the title) that I'm unsure how to debug with a more complex recursive query. Here's a playground link to demonstrate: https://kyse.link/ZD1EV Can anyone help point me in the right direction? I cobbled this query together based on other examples I found but I haven't found anyone else with this error.
4 Replies
kalil
kalilOP9mo ago
I realize there's a lot in this playground link (including some extraneous comments, sorry!) so I don't necessarily expect a solution. But any advice about this kind of error would be very helpful! Okay well I've figured out how to fix this one but still don't really understand it. In the playground link above if you replace this code
const pub: FlatPub | undefined = await db
.withRecursive("children", ({ selectFrom }) => {
return selectFrom("pubs")
const pub: FlatPub | undefined = await db
.withRecursive("children", ({ selectFrom }) => {
return selectFrom("pubs")
with
const pub: FlatPub | undefined = await db
.withRecursive("children", (qc) => {
return qc.selectFrom("pubs")
const pub: FlatPub | undefined = await db
.withRecursive("children", (qc) => {
return qc.selectFrom("pubs")
Kysely is able to compile the query successfully. Can anyone help me understand why? Working query: https://kyse.link/+&11H
koskimas
koskimas9mo ago
You can't destructure it. It won't work. It's a class and the functions use this which will fail once you destructure. Try running this in:
class Foo {
#x
constructor(x) {
this.#x = x
}

print() {
console.log(this.#x)
}
}

const x = new Foo(42)
const { print } = x
print()
class Foo {
#x
constructor(x) {
this.#x = x
}

print() {
console.log(this.#x)
}
}

const x = new Foo(42)
const { print } = x
print()
kalil
kalilOP9mo ago
yeah, i understand now. in case anyone else makes the same mistake as me: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#function_context given that the documentation has plenty of examples of destructuring to assign selectFrom (e.g. https://kysely.dev/docs/examples/WHERE/complex-where-clause), I think it was a pretty reasonable assumption that I'd be able to use that same pattern in the withRecursive callback. Is it just the QueryCreator that I should be cautious about destructuring?
koskimas
koskimas9mo ago
You can't destructure any class. You can destructure ExpressionBuilder (not a class) that was specifically built for destructuring in mind.
Want results from more Discord servers?
Add your server