A newer version of this documentation is available.

View Latest

Couchbase Transactions

  • how-to
    +
    How to create Couchbase transactions using N1QL.

    Introduction

    Couchbase transactions enable you to carry out ACID (atomic, consistent, isolated, and durable) actions on the database. This how-to guide covers N1QL support for Couchbase transactions. Some SDKs also support Couchbase transactions. Refer to Related Links for further details.

    Only DML (data modification language) statements are permitted within a transaction: INSERT, UPSERT, DELETE, UPDATE, MERGE, SELECT, EXECUTE FUNCTION, PREPARE, or EXECUTE.

    If you want to try out the examples in this section, follow the instructions given in Do a Quick Install to install Couchbase Server, configure a cluster, and load a sample dataset. Read the following for further information about the tools available for editing and executing queries:

    Please note that the examples in this guide will alter the data in your sample buckets. To restore your sample data, remove and reinstall the travel-sample bucket. Refer to Sample Buckets for details.

    Transaction Parameters

    You can specify various settings and parameters to control how transactions work. You can access transaction settings and parameters through any of the usual Query tools, such as the Query Workbench or the cbq shell.

    • Query Workbench

    • CBQ Shell

    To specify parameters for a Couchbase transaction, use the Query Run-Time Preferences window.

    1. Click the cog icon to display the Run-Time Preferences window.

    2. To specify the transaction scan consistency, open the Scan Consistency drop-down list and select an option.

    3. To specify the transaction timeout, enter a value in seconds in the Transaction Timeout box.

    4. To specify any other parameters, click the + button in the Named Parameters section. When the new named parameter appears, enter the name in the name box and a value in the value box.

    5. Choose Save Preferences to save the preferences and return to the Query Workbench.


    The following settings set the transaction parameters for the examples in the Multiple Statement Transactions section below.

    The Run-Time Preferences dialog, with Scan Consistency set to "not_bounded", Transaction Timeout set to "120", and named parameter "durability_level" set to "none"

    ① Set Scan Consistency to not_bounded.

    ② In the Named Parameters section, add a named parameter with name set to durability_level and value set to "none" (with double quotes).

    ③ Set Transaction Timeout to 120.

    To specify parameters for a Couchbase transaction, use the \SET command.


    The following settings set the transaction parameters for the examples in the Multiple Statement Transactions section below.

    \SET -txtimeout "2m"; (1)
    \SET -scan_consistency "not_bounded"; (2)
    \SET -durability_level "none"; (3)
    1 The transaction timeout.
    2 The transaction scan consistency.
    3 Durability level of all the mutations within the transaction.

    Click the GitHub button to view this code in context.

    For further details, refer to Transaction Settings and Parameters.

    Single Statement Transactions

    You can create a Couchbase transaction containing a single DML statement.

    • Query Workbench

    • CBQ Shell

    To execute a single statement as a transaction, simply enter the statement in the Query Editor and click Run as TX.

    UPDATE `travel-sample`.inventory.hotel
    SET price = "from £89"
    WHERE name = "Glasgow Grand Central";

    To execute a single statement as a transaction, set the tximplicit parameter to true.

    \SET -tximplicit true;
    
    UPDATE `travel-sample`.inventory.hotel
    SET price = "from £89"
    WHERE name = "Glasgow Grand Central";

    For further details, refer to Query Tools.

    Multiple Statement Transactions

    A Couchbase transaction may contain multiple DML statements. In this case, you must use N1QL transaction statements to support the transaction:

    • Query Workbench

    • CBQ Shell

    To execute a transaction containing multiple statements:

    1. Compose the sequence of statements in the Query Editor. Each statement must be terminated with a semicolon.

    2. After each statement, press Shift+Enter to start a new line without executing the query.

    3. When you have entered the entire transaction, click Execute to execute the transaction.


    The following example demonstrates a complete transaction using N1QL. Individual N1QL transaction statements are described in the sections below.

    Preparation

    First, specify the transaction settings, as shown in the section Transaction Parameters above.

    Second, create a primary index on `travel-sample`.tenant_agent_00.bookings so that you can query this collection.

    CREATE PRIMARY INDEX ON `travel-sample`.tenant_agent_00.bookings;
    Transaction

    Now copy the entire sequence below and paste it into the Query Workbench.

    -- Start the transaction
    BEGIN WORK;
    
    -- Specify transaction settings
    SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
    
    -- Create a booking document
    UPSERT INTO `travel-sample`.tenant_agent_00.bookings
    VALUES("bf7ad6fa-bdb9-4099-a840-196e47179f03", {
      "date": "07/24/2021",
      "flight": "WN533",
      "flighttime": 7713,
      "price": 964.13,
      "route": "63986"
    });
    
    -- Set a savepoint
    SAVEPOINT s1;
    
    -- Update the booking document to include a user
    UPDATE `travel-sample`.tenant_agent_00.bookings AS b
    SET b.`user` = "0"
    WHERE META(b).id = "bf7ad6fa-bdb9-4099-a840-196e47179f03";
    
    -- Check the content of the booking and user
    SELECT b.*, u.name
    FROM `travel-sample`.tenant_agent_00.bookings b
    JOIN `travel-sample`.tenant_agent_00.users u
    ON b.`user` = META(u).id
    WHERE META(b).id = "bf7ad6fa-bdb9-4099-a840-196e47179f03";
    
    -- Set a second savepoint
    SAVEPOINT s2;
    
    -- Update the booking documents to change the user
    UPDATE `travel-sample`.tenant_agent_00.bookings AS b
    SET b.`user` = "1"
    WHERE META(b).id = "bf7ad6fa-bdb9-4099-a840-196e47179f03";
    
    -- Check the content of the booking and user
    SELECT b.*, u.name
    FROM `travel-sample`.tenant_agent_00.bookings b
    JOIN `travel-sample`.tenant_agent_00.users u
    ON b.`user` = META(u).id
    WHERE META(b).id = "bf7ad6fa-bdb9-4099-a840-196e47179f03";
    
    -- Roll back the transaction to the second savepoint
    ROLLBACK TRAN TO SAVEPOINT s2;
    
    -- Check the content of the booking and user again
    SELECT b.*, u.name
    FROM `travel-sample`.tenant_agent_00.bookings b
    JOIN `travel-sample`.tenant_agent_00.users u
    ON b.`user` = META(u).id
    WHERE META(b).id = "bf7ad6fa-bdb9-4099-a840-196e47179f03";
    
    -- Commit the transaction
    COMMIT WORK;
    Result
    {
      "date": "07/24/2021",
      "flight": "WN533",
      "flighttime": 7713,
      "name": "Keon Hoppe",
      "price": 964.13,
      "route": "63986",
      "user": "0" (1)
    }
    1 When the transaction is committed, the document is added with the attributes that were present after rolling back to the second savepoint.

    To execute a transaction containing multiple statements, create the transaction one statement at a time.

    Once you have started a transaction, all statements within the cbq shell session are assumed to be part of the same transaction until you rollback or commit the transaction.

    You must be using cbq shell version 2.0 or above to use the automatic transaction ID functionality.

    The following example demonstrates a complete transaction using N1QL. Individual N1QL transaction statements are described in the sections below.

    Preparation

    First, specify the transaction settings, as shown in the section Transaction Parameters above.

    Second, create a primary index on `travel-sample`.tenant_agent_00.bookings so that you can query this collection.

    CREATE PRIMARY INDEX ON `travel-sample`.tenant_agent_00.bookings;
    Transaction

    Now copy the entire sequence below and paste it into the cbq shell.

    -- Start the transaction
    BEGIN WORK;
    
    -- Specify transaction settings
    SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
    
    -- Create a booking document
    UPSERT INTO `travel-sample`.tenant_agent_00.bookings
    VALUES("bf7ad6fa-bdb9-4099-a840-196e47179f03", {
      "date": "07/24/2021",
      "flight": "WN533",
      "flighttime": 7713,
      "price": 964.13,
      "route": "63986"
    });
    
    -- Set a savepoint
    SAVEPOINT s1;
    
    -- Update the booking document to include a user
    UPDATE `travel-sample`.tenant_agent_00.bookings AS b
    SET b.`user` = "0"
    WHERE META(b).id = "bf7ad6fa-bdb9-4099-a840-196e47179f03";
    
    -- Check the content of the booking and user
    SELECT b.*, u.name
    FROM `travel-sample`.tenant_agent_00.bookings b
    JOIN `travel-sample`.tenant_agent_00.users u
    ON b.`user` = META(u).id
    WHERE META(b).id = "bf7ad6fa-bdb9-4099-a840-196e47179f03";
    
    -- Set a second savepoint
    SAVEPOINT s2;
    
    -- Update the booking documents to change the user
    UPDATE `travel-sample`.tenant_agent_00.bookings AS b
    SET b.`user` = "1"
    WHERE META(b).id = "bf7ad6fa-bdb9-4099-a840-196e47179f03";
    
    -- Check the content of the booking and user
    SELECT b.*, u.name
    FROM `travel-sample`.tenant_agent_00.bookings b
    JOIN `travel-sample`.tenant_agent_00.users u
    ON b.`user` = META(u).id
    WHERE META(b).id = "bf7ad6fa-bdb9-4099-a840-196e47179f03";
    
    -- Roll back the transaction to the second savepoint
    ROLLBACK TRAN TO SAVEPOINT s2;
    
    -- Check the content of the booking and user again
    SELECT b.*, u.name
    FROM `travel-sample`.tenant_agent_00.bookings b
    JOIN `travel-sample`.tenant_agent_00.users u
    ON b.`user` = META(u).id
    WHERE META(b).id = "bf7ad6fa-bdb9-4099-a840-196e47179f03";
    
    -- Commit the transaction
    COMMIT WORK;
    Result
    {
      "date": "07/24/2021",
      "flight": "WN533",
      "flighttime": 7713,
      "name": "Keon Hoppe",
      "price": 964.13,
      "route": "63986",
      "user": "0" (1)
    }
    1 When the transaction is committed, the document is added with the attributes that were present after rolling back to the second savepoint.

    For further details, refer to Query Tools.

    Begin a Transaction

    To start a transaction, use the BEGIN TRANSACTION statement.

    The following statement begins a transaction.

    BEGIN WORK;

    Click the GitHub button to view this code in context.

    Result
    {
      "txid": "d81d9b4a-b758-4f98-b007-87ba262d3a51" (1)
    }
    1 Beginning a transaction returns the transaction ID.

    For further details, refer to BEGIN TRANSACTION.

    Specify Transaction Settings

    To specify transaction settings, use the SET TRANSACTION statement.

    Currently, the only available transaction setting is "isolation level read committed". This setting is enabled by default. The SET TRANSACTION statement is therefore optional and may be omitted.

    The following statement specifies transaction settings.

    SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

    Click the GitHub button to view this code in context.

    For further details, refer to SET TRANSACTION.

    Set a Savepoint

    To set a savepoint within a transaction, use the SAVEPOINT statement and specify a name for the savepoint.

    The following statement sets a savepoint.

    SAVEPOINT s1;

    Click the GitHub button to view this code in context.

    For further details, refer to SAVEPOINT.

    Roll Back a Transaction

    To roll back a transaction, use the ROLLBACK TRANSACTION statement.

    By default, this statement rolls back the entire transaction. If you want to roll back to a savepoint, use the TO SAVEPOINT keywords and specify the savepoint name.

    The following statement rolls back a transaction to a specified savepoint.

    ROLLBACK TRAN TO SAVEPOINT s2;

    Click the GitHub button to view this code in context.

    For further details, refer to ROLLBACK TRANSACTION.

    Commit a Transaction

    To commit a transaction, use the COMMIT TRANSACTION statement.

    The following statement commits a transaction.

    COMMIT WORK;

    Click the GitHub button to view this code in context.

    For further details, refer to COMMIT TRANSACTION.