-
Notifications
You must be signed in to change notification settings - Fork 1
BeginTransaction, commit and rollback methods
The beginTransaction method must be used when making insertions, updates or deletes in more than one table.
beginTransaction is only effective if insert, update and deleteFrom called after beginTransaction have their own beginTransaction false.
The commit method should be used to commit the changes made by the insert, update or deleteFrom methods, while rollback should be used to revert the changes if an error occurs.
The three methods return an object with the following keys:
-
success: stores a boolean, true if commit, rollback or begin transaction was performed successfully, or false in case of error; -
error: stores the error message obtained during commit, rollback or begin transaction, stores false if the commit, rollback or begin transaction was executed successfully.
Is highly recommended that after using the beginTransaction method there is always a commit or rollback.
To make inserts, updates and deletes with begin transaction in only one table is recommended to use the beginTransaction of the method itself.
const connection = await query.startConnection();
if (connection.success)
{
query.beginTransaction()
const tableUsers = {
beginTransaction: false,
table: "users",
columns: {
age: {
value: "25",
type: "number",
},
},
where: {
id: {
operator: "=",
value: 132,
}
},
returning: ["*"],
}
const updateTableUsers = await query.update(tableUsers);
const tableClients = {
beginTransaction: false,
table: "clients",
columns: {
client_age: {
value: "32",
type: "number",
},
client_name: {
value: "Danielle",
type: "string",
}
},
where: {
id: {
operator: "=",
value: 2,
}
},
returning: ["*"],
}
const updateTableClients = await query.update(tableClients);
if (Array.isArray(updateTableUsers.data) && Array.isArray(updateTableClients.data))
{
console.table(updateTableUsers.data);
console.table(updateTableClients.data);
const commit = await query.commit();
if (commit.success)
{
console.log("commit successfully");
query.endConnection();
}
else
{
console.log(commit.error);
}
}
else
{
const rollback = await query.rollback();
if (rollback.success)
{
console.log("rollback successfully");
query.endConnection();
}
else
{
console.log(rollback.error);
}
}
}
else
{
console.log(connection);
}
© 2021-Ana Paula Oliveira de Lima
All rights reserved