DT
Drizzle Team•13mo ago
frankscp

Having CRUD functions and Transaction Support

Hello all, I'm using Supabase as my DB and SvelteKit both for the frontend and backend. I decided to create some "CRUD" files, to manage creations and deletions. The purpose would be to set the values of variables such as created_at, created_by (which is a foreign key to user_id), updated_at and updated_by. I was creating my function like this:
import { db } from "$lib/server/connections/drizzle/drizzleClient";
import { person } from "$lib/server/connections/drizzle/schema";
import type { Person } from "$lib/types/database/databaseTypes";

export async function createOrUpdatePerson(inputPerson: Person) {
try {

let response;
// Check if it is update (if the id is already filled)
{
const currentTimestamp = new Date().getTime();
inputPerson.updatedAt= new Date(currentTimestamp).toString();
response = await db.update(person).set(inputPerson).returning({personId: person.id})
}
// If not, it is a creation
else{
const currentTimestamp = new Date().getTime();
inputPerson.createdAt= new Date(currentTimestamp).toString();
response = await db.insert(person).values(inputPerson).returning({personId: person.id})
}
return {success: true}

}
catch(error){
return {success: false, errorMessage: error}
}
}
import { db } from "$lib/server/connections/drizzle/drizzleClient";
import { person } from "$lib/server/connections/drizzle/schema";
import type { Person } from "$lib/types/database/databaseTypes";

export async function createOrUpdatePerson(inputPerson: Person) {
try {

let response;
// Check if it is update (if the id is already filled)
{
const currentTimestamp = new Date().getTime();
inputPerson.updatedAt= new Date(currentTimestamp).toString();
response = await db.update(person).set(inputPerson).returning({personId: person.id})
}
// If not, it is a creation
else{
const currentTimestamp = new Date().getTime();
inputPerson.createdAt= new Date(currentTimestamp).toString();
response = await db.insert(person).values(inputPerson).returning({personId: person.id})
}
return {success: true}

}
catch(error){
return {success: false, errorMessage: error}
}
}
However, I now realized that by doing this, I'll not be able to use transactions. Is there any way I can define that 'updatedAt' should be set to the current timestamp and still use transactions? Thank you!
2 Replies
frankscp
frankscpOP•13mo ago
Ok I think I found a potential solution. Instead of using the drizzle client directly, I added it as an input. This way, I can pass either the drizzle client or the client in the context of the transaction. Rollbacks are working as expected 🙂
Angelelz
Angelelz•13mo ago
Dependency injection baby
Want results from more Discord servers?
Add your server