-
Notifications
You must be signed in to change notification settings - Fork 0
transactions
Person edited this page Nov 16, 2023
·
1 revision
libsql-stateless
does not have an explicit transaction
function
but you can build them with libsqlBatch
- set the 1st step in the batch to one of:
- "BEGIN IMMEDIATE" for "write" mode
- "BEGIN TRANSACTION READONLY" for "read" mode
- "BEGIN DEFERRED" for "deferred" mode
- now add the statements (steps) you want to execute in the transaction
- make sure to set each of these steps' condition to:
{ {type: "and", conds: [ {type: "ok", step: <the-0-index-of-the-step-above-this-step>}, //replace <the-0-index-of-the-step-above-this-step> with appropriate number {type: "not", cond: {type: "is_autocommit"}} ]} }
- now add "COMMIT" as the 2nd-last step with no conditions
- end with last step as "ROLLBACK" with condition set to:
{type: "not", cond: {type: "ok", step: <the-0-index-of-the-commit-step>}} //replace <the-0-index-of-the-commit-step> with appropriate number
const transaction_response = await libsqlBatch(conf, [
{stmt: {sql: "BEGIN DEFERRED"}},
{stmt: {sql: "select * from contacts where contact_id = ?;", args: [{type: "integer", value: "3"}]},
condition: {type: "and", conds: [
{type: "ok", step: 0},
{type: "not", cond: {type: "is_autocommit"}}
]}
},
{stmt: {sql: "select first_name, last_name, email from contacts where contact_id = 2;"},
condition: {type: "and", conds: [
{type: "ok", step: 1},
{type: "not", cond: {type: "is_autocommit"}}
]}
},
{stmt: {sql: `insert into contacts (contact_id,first_name,last_name,email,phone) values (7,"glomm","feru","moca@doro.co","001");`},
condition: {type: "and", conds: [
{type: "ok", step: 2},
{type: "not", cond: {type: "is_autocommit"}}
]}
},
{stmt: {sql: `delete from contacts where contact_id = 7;`},
condition: {type: "and", conds: [
{type: "ok", step: 3},
{type: "not", cond: {type: "is_autocommit"}}
]}
},
{stmt: {sql: "COMMIT"}},
{stmt: {sql: "ROLLBACK"}, condition: {type: "not", cond: {type: "ok", step: 5}}}
]);