How to get the type of transaction from a database?

I wanna pass a transaction to a function, how can I get the type for the function declaration?
4 Replies
tzezar
tzezar4mo ago
import { type PostgresJsDatabase } from "drizzle-orm/postgres-js";
jrydberg
jrydbergOP4mo ago
but how can i get the transaction type, enriched with the schema types? best i've come up with is:
export const db = drizzle(sqlite, { schema: { ...schema } });
export type Database = typeof db;

type ArgumentTypes<F extends Function> = F extends (...args: infer A) => any
? A
: never;
export type Transaction = ArgumentTypes<
ArgumentTypes<Database['transaction']>[0]
>[0];
export const db = drizzle(sqlite, { schema: { ...schema } });
export type Database = typeof db;

type ArgumentTypes<F extends Function> = F extends (...args: infer A) => any
? A
: never;
export type Transaction = ArgumentTypes<
ArgumentTypes<Database['transaction']>[0]
>[0];
tzezar
tzezar4mo ago
I did it like this:
export const dbDrizzle = drizzle(pool);

export type DbConn = typeof dbDrizzle;


const getUser = async (db: DbConn, id: number) => {
const [supplier] = await db.select().from(dostawca).where(eq(dostawca.id, id)).execute()
return supplier;
}


await dbDrizzle.transaction(async (db) => {
const user = await getUser(db, 1);
})

const user = await getUser(dbDrizzle, 1);
export const dbDrizzle = drizzle(pool);

export type DbConn = typeof dbDrizzle;


const getUser = async (db: DbConn, id: number) => {
const [supplier] = await db.select().from(dostawca).where(eq(dostawca.id, id)).execute()
return supplier;
}


await dbDrizzle.transaction(async (db) => {
const user = await getUser(db, 1);
})

const user = await getUser(dbDrizzle, 1);
it allows to pass regular db conn or transaction
Michael Schaufelberger
export const db = drizzlePg(pool, {
schema,
});

export type DB = typeof db;
export type TX = Parameters<Parameters<DB['transaction']>[0]>[0];
export type DbOrTx = DB | TX;
export const db = drizzlePg(pool, {
schema,
});

export type DB = typeof db;
export type TX = Parameters<Parameters<DB['transaction']>[0]>[0];
export type DbOrTx = DB | TX;
is my solution to this. A function can use either DB, TX or DbOrTx as their prop/arg.
Want results from more Discord servers?
Add your server