kroltan
kroltan
Explore posts from servers
KKysely
Created by kroltan on 7/23/2024 in #help
Subquery from a function
I want to reuse a sub-query that refers to one of the fields in the root query's result. I tried doing this:
function queryIsFriendOf<DB extends DatabaseSchema, TB extends keyof DB>(
eb: ExpressionBuilder<DB, TB>,
on: AnyColumn<DB, TB>,
): AliasableExpression<boolean> {
return eb.selectFrom("friendship as check_is_friend")
.whereRef("check_is_friend.target_id", "=", on) // using field name from parent query
.select((eb) =>
eb.or([
eb("check_is_friend.target_id", "is", null),
eb("check_is_friend.target_id", "=", this.userId),
])
);
}
function queryIsFriendOf<DB extends DatabaseSchema, TB extends keyof DB>(
eb: ExpressionBuilder<DB, TB>,
on: AnyColumn<DB, TB>,
): AliasableExpression<boolean> {
return eb.selectFrom("friendship as check_is_friend")
.whereRef("check_is_friend.target_id", "=", on) // using field name from parent query
.select((eb) =>
eb.or([
eb("check_is_friend.target_id", "is", null),
eb("check_is_friend.target_id", "=", this.userId),
])
);
}
However, I get a bunch o' errors I don't quite understand:
TS2345 [ERROR]: Argument of type 'string' is not assignable to parameter of type 'ReferenceExpression<DB & ("friendship" extends keyof DB ? { check_is_friend: DB[keyof DB & "friendship"]; } : never), "check_is_friend" | TB>'.
TS2345 [ERROR]: Argument of type 'string' is not assignable to parameter of type 'ReferenceExpression<DB & ("friendship" extends keyof DB ? { check_is_friend: DB[keyof DB & "friendship"]; } : never), "check_is_friend" | TB>'.
If I pick that exact expression and paste it directly in the .select(eb => [/* here */]) of the parent query, then there are no errors. I assume that it's trying to tell me that check_is_friend might collide with the parent's scope or something like that? Am I doing something silly, is there a better way to do this?
16 replies