Skip to content

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

How To

  1. set the 1st step in the batch to one of:
    1. "BEGIN IMMEDIATE" for "write" mode
    2. "BEGIN TRANSACTION READONLY" for "read" mode
    3. "BEGIN DEFERRED" for "deferred" mode
  2. 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"}}
            ]}
        }
  3. now add "COMMIT" as the 2nd-last step with no conditions
  4. 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

Example

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}}}
]);
Clone this wiki locally