Versatile functions with transaction support

Used to be able to add tx = db as the last argument of a function. I find I'm no longer able to do that. Is there an updated pattern I should use if I want the ability to use any query I've already written inside of a transaction?
1 Reply
html_extraordinaire
Here's how I "solved" it but I'm not completely satisfied. I'm not sure if the 2nd argument of NeonTransaction is correct or not. Would love someone to tell me if this is close to the correct answer.
import { TablesRelationalConfig } from "drizzle-orm";
import { NeonTransaction } from "drizzle-orm/neon-serverless";
import { db } from "@/db";

export type DbExecutor =
| NeonTransaction<typeof db._.fullSchema, TablesRelationalConfig>
| typeof db;
import { TablesRelationalConfig } from "drizzle-orm";
import { NeonTransaction } from "drizzle-orm/neon-serverless";
import { db } from "@/db";

export type DbExecutor =
| NeonTransaction<typeof db._.fullSchema, TablesRelationalConfig>
| typeof db;
After importing this type I can do this in a function again where the final argument is optional:
async function insertUser(user: InsertUser, tx: DbExecutor = db) {
await tx.insert(userTable).values(user);
}
async function insertUser(user: InsertUser, tx: DbExecutor = db) {
await tx.insert(userTable).values(user);
}

Did you find this page helpful?