Is there a way to have a query- or transaction-level hook?

I want to: - for every transaction, before statements are run, issue a query against the database to set settings - for every query, if not in a transaction, open a transaction and set the setting, run the query, then close the transaction Is there any recommended way to do this with drizzle?
1 Reply
francis
francisOP17mo ago
for anyone else who finds this later, I figured out the first one:
export type ClaimsFunction = undefined | (() => Record<string, unknown>);
export function createRlsDrizzle(claimsFn: ClaimsFunction) {
return new Proxy<typeof rlsDb>(rlsDb, {
get(target, prop, receiver) {
if (prop === "transaction") {
return async (first: any, ...rest: any) => {
const claims = claimsFn ? JSON.stringify(claimsFn() || {}) : "";
return target.transaction(async (tx) => {
await tx.execute(sql.raw(`SELECT set_config('request.jwt.claims', '${claims}', TRUE)`));
return first(tx);
}, ...rest);
};
}
return Reflect.get(target, prop, receiver);
},
});
}
export type ClaimsFunction = undefined | (() => Record<string, unknown>);
export function createRlsDrizzle(claimsFn: ClaimsFunction) {
return new Proxy<typeof rlsDb>(rlsDb, {
get(target, prop, receiver) {
if (prop === "transaction") {
return async (first: any, ...rest: any) => {
const claims = claimsFn ? JSON.stringify(claimsFn() || {}) : "";
return target.transaction(async (tx) => {
await tx.execute(sql.raw(`SELECT set_config('request.jwt.claims', '${claims}', TRUE)`));
return first(tx);
}, ...rest);
};
}
return Reflect.get(target, prop, receiver);
},
});
}
Want results from more Discord servers?
Add your server