Mammoth
Search…
Transactions
Even though Mammoth does not include a database driver and thus is not responsible to manage transactions, transactions are a key construct in Postgres and it’s important to be able to use them. Luckily, it‘s fairly straightforward to add in your codebase when using Mammoth. The below shows a db instance (as previously constructed through the defineDb call) where everything is wrapped in a transaction.
1
await wrapInTransaction((db) => {
2
// This db instance and everything in this scope
3
// should be inside a transaction. So the below
4
// insert statements are all inside a single
5
// transaction.
6
await db.insertInto(db.foo).values({ name: `Test` });
7
8
await db.insertInto(db.bar).values({ name: `Test` });
9
});
Copied!
And the actual implementation to get this working is below.
1
const wrapInTransaction = (callback: (db: Db) => any) => {
2
const client = await pool.connect()
3
try {
4
await client.query('BEGIN');
5
6
const db = defineDb(tables, (query, parameters) => {
7
const result = client.query(query, parameters);
8
return {
9
affectedCount: result.rowCount,
10
rows: result.rows,
11
};
12
});
13
14
const result = await callback(db);
15
16
await client.query('COMMIT')
17
return result;
18
} catch (e) {
19
await client.query('ROLLBACK')
20
throw e
21
} finally {
22
client.release()
23
}
24
}
Copied!
This is just a quick example to get you started. Of course you can also decide to expose a rollback function to be able to programmatically rollback the transaction without having to rely on exceptions.
Last modified 1yr ago
Copy link