Liam
DTDrizzle Team
•Created by Liam on 10/31/2024 in #help
RLS - Typesafety
And then an example working query:
return await ctx.rlsDb((tx) =>
tx.query.job.findFirst({
where: eq(job.id, input.id),
with: {
location: true,
mainPosition: true,
client: true,
placements: {
with: {
operative: true,
},
},
},
}),
);
return await ctx.rlsDb((tx) =>
tx.query.job.findFirst({
where: eq(job.id, input.id),
with: {
location: true,
mainPosition: true,
client: true,
placements: {
with: {
operative: true,
},
},
},
}),
);
5 replies
DTDrizzle Team
•Created by Liam on 10/31/2024 in #help
RLS - Typesafety
export function createDrizzle<
Database extends PostgresJsDatabase<typeof schema>, // Note the type here
Token extends SupabaseToken = SupabaseToken,
>(token: Token, { admin, client }: { admin: Database; client: Database }) {
return {
admin,
rls: (async (transaction, ...rest) => {
return client.transaction(
async (tx) => {
await tx.execute(sql`
-- auth.uid()
select set_config('request.jwt.claim.sub', '${sql.raw(token.sub ?? "")}', TRUE);
`);
await tx.execute(sql`
-- role
set local role postgres;
`);
await tx.execute(sql`
-- role
set local role ${sql.raw(token.role ?? "anon")};
`);
const result = await transaction(tx);
await tx.execute(sql`
-- reset
select set_config('request.jwt.claim.sub', NULL, TRUE);
`);
await tx.execute(sql`
-- reset
reset role;
`);
return result;
},
...rest,
);
}) as typeof client.transaction,
};
}
export function createDrizzle<
Database extends PostgresJsDatabase<typeof schema>, // Note the type here
Token extends SupabaseToken = SupabaseToken,
>(token: Token, { admin, client }: { admin: Database; client: Database }) {
return {
admin,
rls: (async (transaction, ...rest) => {
return client.transaction(
async (tx) => {
await tx.execute(sql`
-- auth.uid()
select set_config('request.jwt.claim.sub', '${sql.raw(token.sub ?? "")}', TRUE);
`);
await tx.execute(sql`
-- role
set local role postgres;
`);
await tx.execute(sql`
-- role
set local role ${sql.raw(token.role ?? "anon")};
`);
const result = await transaction(tx);
await tx.execute(sql`
-- reset
select set_config('request.jwt.claim.sub', NULL, TRUE);
`);
await tx.execute(sql`
-- reset
reset role;
`);
return result;
},
...rest,
);
}) as typeof client.transaction,
};
}
5 replies