Reuse subquery selects

Hello, I am trying to correctly type a select subquery to use in different other queries:
export const myUnion =
() => (eb: ExpressionBuilder<KyselyDB, keyof KyselyDB>) => {
return eb
.selectFrom('profile')
.innerJoin('account', 'account.id', 'profile.account_id')
.select((eb) => [
eb.fn.coalesce('account.name', sql.lit('')).as('name'),
eb
.ref('profile.ids', '->>')
.key('value')
.as('code'),
'user_id',
]);
.union((eb) =>
eb.parens(
eb.selectFrom('invitees').select(['name', 'code', 'user_id']),
),
);
};

const x = await kysely
.selectFrom(myUnion())
.select(['name', 'code'])
.execute()
export const myUnion =
() => (eb: ExpressionBuilder<KyselyDB, keyof KyselyDB>) => {
return eb
.selectFrom('profile')
.innerJoin('account', 'account.id', 'profile.account_id')
.select((eb) => [
eb.fn.coalesce('account.name', sql.lit('')).as('name'),
eb
.ref('profile.ids', '->>')
.key('value')
.as('code'),
'user_id',
]);
.union((eb) =>
eb.parens(
eb.selectFrom('invitees').select(['name', 'code', 'user_id']),
),
);
};

const x = await kysely
.selectFrom(myUnion())
.select(['name', 'code'])
.execute()
However when I use the expression in another query I get a typing error
Type 'SelectQueryBuilder<KyselyDB, keyof KyselyDB, { government_id: string | null; name: string; code: string | null; }>' is missing the following properties from type 'AliasedExpression<any, any>': expression, alias
Type 'SelectQueryBuilder<KyselyDB, keyof KyselyDB, { government_id: string | null; name: string; code: string | null; }>' is missing the following properties from type 'AliasedExpression<any, any>': expression, alias
Solution:
You need to give an alias for the table. myUnion().as('u')
Jump to solution
1 Reply
Solution
koskimas
koskimas13mo ago
You need to give an alias for the table. myUnion().as('u')
Want results from more Discord servers?
Add your server