DT
Drizzle Team•6mo ago
titongo

nesting db calls in transactions without using the callback argument

What is the point of the trx argument when calling db.transaction()? when using raw sql, a transaction looks something like
BEGIN TRANSACTION
INSERT into whatever values something returning id;
INSERT into otherWhatever values somertinhElse;
COMMIT;
BEGIN TRANSACTION
INSERT into whatever values something returning id;
INSERT into otherWhatever values somertinhElse;
COMMIT;
so the queries don't really have to "know" that they are inside a transaction, so my question is, is this possible?
const insertedPropId = await db.transaction(async (trx) => {
// insertPlaceDetails calls the db DIRECTLY, instead of something like
// trx.insert()
const insertedPlaceData = await insertPlaceDetails([
location.latitude,
location.longitude,
]);
const [insertedProperty] = await db
.insert(propertiesTable)
.values(propertyData)
.returning({ id: propertiesTable.id });
return insertedProperty.id;
});
return insertedPropId;
};

const insertedPropId = await db.transaction(async (trx) => {
// insertPlaceDetails calls the db DIRECTLY, instead of something like
// trx.insert()
const insertedPlaceData = await insertPlaceDetails([
location.latitude,
location.longitude,
]);
const [insertedProperty] = await db
.insert(propertiesTable)
.values(propertyData)
.returning({ id: propertiesTable.id });
return insertedProperty.id;
});
return insertedPropId;
};

if this is not possible: is there any way of nesting inserts without passing the trx argument around? I'd rather keep those things outside functions like insertPlaceDetails, which would now need to "know" about its context. Thanks!
4 Replies
titongo
titongoOP•5mo ago
bump I guess? 🤔
rphlmr âš¡
rphlmr ⚡•5mo ago
You need to use tx in the transaction to guarantee atomicity of the transaction. This is tx that will wrap everything and handle rollback on error
rphlmr âš¡
rphlmr ⚡•5mo ago
You could look at https://drizzle.run/lt295lgldz4avpzwdee7ddhd if you want functions that can take a tx or default to db
titongo
titongoOP•4mo ago
Thanks a lot!
Want results from more Discord servers?
Add your server