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
AlcaponeYou2y ago
Where is projectId defined?
Meexa
MeexaOP2y 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
AlcaponeYou2y 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
MeexaOP2y 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
AlcaponeYou2y 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
MeexaOP2y ago
Hmm it works for the frontend... just not in the transaction.
Want results from more Discord servers?
Add your server