Can I .prepare() a transaction?

Surprisingly I can call prepare inside transaction callback but it doesn't make sense to me since we usually using prepare() as a variable out of block scope.
await db.transaction(async (tx) => {
const q1 = tx.update(...).set(...).where(...).prepare();
const q2 = tx.insert(...).values(...).prepare();

await q1.execute();
await q2.execute();
});
await db.transaction(async (tx) => {
const q1 = tx.update(...).set(...).where(...).prepare();
const q2 = tx.insert(...).values(...).prepare();

await q1.execute();
await q2.execute();
});
2 Replies
Angelelz
Angelelz12mo ago
This is something I've been wanting to dive into but I just haven't have time I would think it doesn't really make much sense to prepare statements inside a transaction, but preparing them outside, I'm not really sure they would use the same connection as the transaction I would need to investigate if calling db.<...>.prepare() outside the transaction sets up the connection from the pool or not
Bea dm
Bea dm4mo ago
Hi, is there any documentation about this? i just only found this https://github.com/ItzDerock/hostforge/blob/9798ab27fc7a1b960f7c94be46b3f3310c8cfc72/src/server/api/routers/projects/service/index.ts#L81C50-L81C72 but not sure, in my code session does not exist if i type it. I tried this with no luck could you help me a bit please?
const insertScoreCard = (db: DatabaseClient) => db.insert(scoreCards).values({ .. }).prepare('insert_score_card');
export const createScorecard = (dbClient: DatabaseClient) => async () => {
await dbClient.transaction(async (trx: PostgresTransaction) => {
const db: DatabaseClient = trx.session.client;
// Prepare the statements for scorecards
const insertStatement = insertScoreCard(db);
const insertedScoreCard = await insertStatement.run(newScoreCard);
...
};
const insertScoreCard = (db: DatabaseClient) => db.insert(scoreCards).values({ .. }).prepare('insert_score_card');
export const createScorecard = (dbClient: DatabaseClient) => async () => {
await dbClient.transaction(async (trx: PostgresTransaction) => {
const db: DatabaseClient = trx.session.client;
// Prepare the statements for scorecards
const insertStatement = insertScoreCard(db);
const insertedScoreCard = await insertStatement.run(newScoreCard);
...
};
Want results from more Discord servers?
Add your server