How do I get the values of an insert inside a transaction?

I have this transaction where I create a project and add variables and a history of those variables. I need the IDs of the variables for variables_history. How can I get those values?
await db.transaction(async (tx) => {
// Add project to DB
await tx.insert(projects).values({
// ...
});

// Add variables to DB
await tx.insert(variables).values(
repoVariables.data
.filter((v) => v.variable_type === 'env_var')
.map((v) => ({
// ...
})),
);

// Add variables history to DB
const projectVariables = await getProjectVariables(projectId);

console.log(projectVariables); // <-- empty array

await tx.insert(variablesHistory).values(
projectVariables.map((v) => ({
// ...
})),
);
});
await db.transaction(async (tx) => {
// Add project to DB
await tx.insert(projects).values({
// ...
});

// Add variables to DB
await tx.insert(variables).values(
repoVariables.data
.filter((v) => v.variable_type === 'env_var')
.map((v) => ({
// ...
})),
);

// Add variables history to DB
const projectVariables = await getProjectVariables(projectId);

console.log(projectVariables); // <-- empty array

await tx.insert(variablesHistory).values(
projectVariables.map((v) => ({
// ...
})),
);
});
6 Replies
AlcaponeYou
AlcaponeYou15mo ago
Where is projectId defined?
Meexa
Meexa15mo ago
Outside of the transaction
const projectId = crypto.randomBytes(16).toString('hex');
const projectId = crypto.randomBytes(16).toString('hex');
I guess I can do this but idk if this is what is usually done in these situations
const newVariables = repoVariables.data
.filter((v) => v.variable_type === 'env_var')
.map((v) => ({
id: crypto.randomBytes(16).toString('hex'),
// ...
}));

await tx.insert(variables).values(newVariables);

await tx.insert(variablesHistory).values(
newVariables.map((v) => ({
id: crypto.randomBytes(16).toString('hex'),
variable_id: v.id,
// ...
})),
);
const newVariables = repoVariables.data
.filter((v) => v.variable_type === 'env_var')
.map((v) => ({
id: crypto.randomBytes(16).toString('hex'),
// ...
}));

await tx.insert(variables).values(newVariables);

await tx.insert(variablesHistory).values(
newVariables.map((v) => ({
id: crypto.randomBytes(16).toString('hex'),
variable_id: v.id,
// ...
})),
);
AlcaponeYou
AlcaponeYou15mo ago
insert returns insertId, try logging that out. It works for serial type, but not sure if it works for uuids I'm assuming projects items have their projectId already generated?
Meexa
Meexa15mo ago
Yeah these projects are coming from an API with an id which is the projectId. Is serial just an incremental ID or a random number?
AlcaponeYou
AlcaponeYou15mo ago
0 increment by 1 ur getProjectVariables is broken if it's returning empty after you insert into your projects table assuming the records were successfully inserted, you should have gotten data back
Meexa
Meexa15mo ago
Hmm it works for the frontend... just not in the transaction.