Use Transactions
A transaction is an operation that contains one or more SQL statements. A commit makes the successful writes visible together. If a statement fails, the transaction can still contain earlier successful writes. Roll back the transaction if the entire workflow must fail together.
Understand transaction boundaries
Queries and DDL execute as individual statements outside explicit write transactions. Explicit multi-statement transactions do not accept standalone queries or DDL. By default, each individual write is an implicit transaction, and multiple writes can be combined into an explicit transaction. VeloDB Cloud does not currently support nested transactions.
Begin transactions explicitly
An explicit transaction requires the user to actively begin, commit, or roll back the transaction. DDL and query statements are not currently supported inside one.
BEGIN;
[INSERT, UPDATE, DELETE statement]
COMMIT; / ROLLBACK;
Commit individual statements implicitly
An implicit transaction is one in which the user does not explicitly add statements to begin and commit the transaction before and after the executed SQL statement or statements.
In VeloDB Cloud, except for Group Commit, every load statement opens a transaction when it starts to execute. The transaction is automatically committed after the statement completes successfully, or automatically rolled back when the statement fails. Run standalone queries and DDL outside the explicit write transaction.
Understand READ COMMITTED isolation
The only isolation level currently supported by VeloDB Cloud is READ COMMITTED. Under the READ COMMITTED isolation level, a statement can only see data that was committed before the statement began executing; it cannot see uncommitted data.
When a single statement runs, it captures a snapshot of the tables it touches at the start of the statement. That is, a single statement can only see commits from other transactions that completed before the statement started; commits made by other transactions during the statement's execution are not visible.
When a statement runs inside a multi-statement transaction:
- It can only see data that was committed before the statement began executing. If another transaction commits between the first and second statements, two consecutive statements in the same transaction may see different data.
- It cannot currently see changes made by previous statements in the same transaction.
Coordinate retries and commits
Transaction labels make retries idempotent while the label is retained. Two-phase commit lets a connector coordinate a prepared load with an upstream checkpoint. End-to-end exactly-once behavior also depends on the source, connector, stable batch labels, retries, and successful commit coordination.
Deduplicate retries with labels
A VeloDB Cloud transaction or load can have a Label set on it. This Label is usually a user-defined string with some business-logic meaning; if it is not set, an internal UUID string is generated. The main purpose of the Label is to uniquely identify a transaction or load task and to ensure that transactions or loads with the same Label are executed successfully only once. Retry the same logical batch with the same label, check the existing transaction status, and do not assume a timeout means the load failed. Label deduplication alone does not prevent data loss or guarantee end-to-end exactly-once processing. A Label is unique within a database.
Labels are retained for a finite, service-managed period. Retention depends on the loading interface and warehouse service configuration. After a label expires or is cleared, the same name can be used for a new successful load, so it no longer protects a replay of the old batch. Keep durable source checkpoints and contact VeloDB Cloud support when designing a retry window that depends on label retention.
A Label is typically set in the format business logic + time, such as my_business1_20220330_125000. This Label is generally used to indicate: a batch of data produced by the business my_business1 at 2022-03-30 12:50:00. With this kind of Label scheme, the business can query the load task status by Label to clearly determine whether the data for that batch and time has already been loaded successfully. If it has not committed, reconcile the transaction state before retrying the same batch with the same label.
Coordinate Stream Load commits
Stream Load 2PC is mainly used to support exactly-once checkpoint coordination when a compatible Flink connector writes to VeloDB Cloud.
Control explicit transactions
Begin a transaction
BEGIN;
BEGIN WITH LABEL txn_example_001;
If this statement is executed while the current Session is already in the middle of a transaction, VeloDB Cloud ignores the statement. In other words, transactions cannot be nested.
Commit a transaction
COMMIT;
This is used to commit all modifications made in the current transaction.
Roll back a transaction
ROLLBACK;
This is used to undo all modifications in the current transaction.
A transaction is at the Session level. If the Session is aborted or closed, the transaction is automatically rolled back as well.
Write multiple SQL statements
VeloDB Cloud currently supports two ways to write within a transaction.
Insert multiple value batches into one table
Insert multiple value batches into one table
Suppose the table structure is:
CREATE TABLE `dt` (
`id` INT(11) NOT NULL,
`name` VARCHAR(50) NULL,
`score` INT(11) NULL
) ENGINE=OLAP
UNIQUE KEY(`id`)
DISTRIBUTED BY HASH(`id`) BUCKETS 1;
Write data:
mysql> BEGIN;
Query OK, 0 rows affected (0.01 sec)
{'label':'txn_insert_b55db21aad7451b-b5b6c339704920c5', 'status':'PREPARE', 'txnId':''}
mysql> INSERT INTO dt (id, name, score) VALUES (1, "Emily", 25), (2, "Benjamin", 35), (3, "Olivia", 28), (4, "Alexander", 60), (5, "Ava", 17);
Query OK, 5 rows affected (0.08 sec)
{'label':'txn_insert_b55db21aad7451b-b5b6c339704920c5', 'status':'PREPARE', 'txnId':'10013'}
mysql> INSERT INTO dt VALUES (6, "William", 69), (7, "Sophia", 32), (8, "James", 64), (9, "Emma", 37), (10, "Liam", 64);
Query OK, 5 rows affected (0.00 sec)
{'label':'txn_insert_b55db21aad7451b-b5b6c339704920c5', 'status':'PREPARE', 'txnId':'10013'}
mysql> COMMIT;
Query OK, 0 rows affected (1.02 sec)
{'label':'txn_insert_b55db21aad7451b-b5b6c339704920c5', 'status':'VISIBLE', 'txnId':'10013'}
This mode groups the value batches into one commit. Its throughput depends on batch sizes and the warehouse workload.
If the user enables both Group Commit and transactional writes, transactional writes take effect.
Write across tables in one database
Write across tables in one database
In a fresh database, create three tables with the schema above and seed the source tables. Run this setup outside a transaction:
CREATE TABLE dt1 LIKE dt;
CREATE TABLE dt2 LIKE dt;
CREATE TABLE dt3 LIKE dt;
INSERT INTO dt1 VALUES (1, "Emily", 25), (2, "Benjamin", 35), (3, "Olivia", 28), (4, "Alexander", 60), (5, "Ava", 17);
INSERT INTO dt2 VALUES (6, "William", 69), (7, "Sophia", 32), (8, "James", 64), (9, "Emma", 37), (10, "Liam", 64);
The following transcripts illustrate the initial data and transaction results. Transaction IDs, timing, and row order can differ:
mysql> SELECT * FROM dt1;
+------+-----------+-------+
| id | name | score |
+------+-----------+-------+
| 1 | Emily | 25 |
| 2 | Benjamin | 35 |
| 3 | Olivia | 28 |
| 4 | Alexander | 60 |
| 5 | Ava | 17 |
+------+-----------+-------+
5 rows in set (0.04 sec)
mysql> SELECT * FROM dt2;
+------+---------+-------+
| id | name | score |
+------+---------+-------+
| 6 | William | 69 |
| 7 | Sophia | 32 |
| 8 | James | 64 |
| 9 | Emma | 37 |
| 10 | Liam | 64 |
+------+---------+-------+
5 rows in set (0.03 sec)
mysql> SELECT * FROM dt3;
Empty set (0.03 sec)
Perform a transactional write that loads data from dt1 and dt2 into dt3, while also updating the scores in table dt1 and deleting data from table dt2:
mysql> BEGIN;
Query OK, 0 rows affected (0.00 sec)
{'label':'txn_insert_442a6311f6c541ae-b57d7f00fa5db028', 'status':'PREPARE', 'txnId':''}
# The status of the load task is PREPARE
mysql> INSERT INTO dt3 SELECT * FROM dt1;
Query OK, 5 rows affected (0.07 sec)
{'label':'txn_insert_442a6311f6c541ae-b57d7f00fa5db028', 'status':'PREPARE', 'txnId':'11024'}
mysql> INSERT INTO dt3 SELECT * FROM dt2;
Query OK, 5 rows affected (0.08 sec)
{'label':'txn_insert_442a6311f6c541ae-b57d7f00fa5db028', 'status':'PREPARE', 'txnId':'11025'}
mysql> UPDATE dt1 SET score = score + 10 WHERE id >= 4;
Query OK, 2 rows affected (0.07 sec)
{'label':'txn_insert_442a6311f6c541ae-b57d7f00fa5db028', 'status':'PREPARE', 'txnId':'11026'}
mysql> DELETE FROM dt2 WHERE id >= 9;
Query OK, 0 rows affected (0.01 sec)
{'label':'txn_insert_442a6311f6c541ae-b57d7f00fa5db028', 'status':'PREPARE', 'txnId':'11027'}
mysql> COMMIT;
Query OK, 0 rows affected (0.03 sec)
{'label':'txn_insert_442a6311f6c541ae-b57d7f00fa5db028', 'status':'VISIBLE', 'txnId':'11024'}
Query the data:
# Scores for rows with id >= 4 are increased by 10
mysql> SELECT * FROM dt1;
+------+-----------+-------+
| id | name | score |
+------+-----------+-------+
| 1 | Emily | 25 |
| 2 | Benjamin | 35 |
| 3 | Olivia | 28 |
| 4 | Alexander | 70 |
| 5 | Ava | 27 |
+------+-----------+-------+
5 rows in set (0.01 sec)
# Rows with id >= 9 are deleted
mysql> SELECT * FROM dt2;
+------+---------+-------+
| id | name | score |
+------+---------+-------+
| 6 | William | 69 |
| 7 | Sophia | 32 |
| 8 | James | 64 |
+------+---------+-------+
3 rows in set (0.02 sec)
# The committed data from dt1 and dt2 is written into dt3
mysql> SELECT * FROM dt3;
+------+-----------+-------+
| id | name | score |
+------+-----------+-------+
| 1 | Emily | 25 |
| 2 | Benjamin | 35 |
| 3 | Olivia | 28 |
| 4 | Alexander | 60 |
| 5 | Ava | 17 |
| 6 | William | 69 |
| 7 | Sophia | 32 |
| 8 | James | 64 |
| 9 | Emma | 37 |
| 10 | Liam | 64 |
+------+-----------+-------+
10 rows in set (0.01 sec)
Understand READ COMMITTED isolation
The isolation level provided by VeloDB Cloud transactional writes is READ COMMITTED. Note the following two points:
-
For multiple statements in a transaction, each statement reads the data that was committed at the time the statement starts executing. For example:
timestamp | ------------ Session 1 ------------ | ------------ Session 2 ------------t1 | BEGIN; |t2 | # read n rows from dt1 table || INSERT INTO dt3 SELECT * FROM dt1; |t3 | | # write 2 rows to dt1 table| | INSERT INTO dt1 VALUES(...), (...);t4 | # read n + 2 rows from dt1 table || INSERT INTO dt3 SELECT * FROM dt1; |t5 | COMMIT; | -
For multiple statements in a transaction, each statement cannot read modifications made by other statements within the same transaction. For example:
Suppose that before the transaction begins, table
dt1has 5 rows, tabledt2has 5 rows, and tabledt3is empty. The following syntax sketch shows the transaction shape (the runnable script that creates the tables and loads the seed rows first appears in the concrete example below):BEGIN;# 5 rows are written into dt2; after the transaction commits, dt2 has 10 rows in totalINSERT INTO dt2 SELECT * FROM dt1;# 5 rows are written into dt3; the rows newly written to dt2 in the previous step cannot be read hereINSERT INTO dt3 SELECT * FROM dt2;COMMIT;A concrete, end-to-end runnable example:
# Run this independent example in a fresh database.# Create tables and write dataCREATE TABLE `dt1` (`id` INT(11) NOT NULL,`name` VARCHAR(50) NULL,`score` INT(11) NULL) ENGINE=OLAPDUPLICATE KEY(`id`)DISTRIBUTED BY HASH(`id`) BUCKETS 1;CREATE TABLE dt2 LIKE dt1;CREATE TABLE dt3 LIKE dt1;INSERT INTO dt1 VALUES (1, "Emily", 25), (2, "Benjamin", 35), (3, "Olivia", 28), (4, "Alexander", 60), (5, "Ava", 17);INSERT INTO dt2 VALUES (6, "William", 69), (7, "Sophia", 32), (8, "James", 64), (9, "Emma", 37), (10, "Liam", 64);# Transactional writesBEGIN;INSERT INTO dt2 SELECT * FROM dt1;INSERT INTO dt3 SELECT * FROM dt2;COMMIT;# Querymysql> SELECT * FROM dt2;+------+-----------+-------+| id | name | score |+------+-----------+-------+| 6 | William | 69 || 7 | Sophia | 32 || 8 | James | 64 || 9 | Emma | 37 || 10 | Liam | 64 || 1 | Emily | 25 || 2 | Benjamin | 35 || 3 | Olivia | 28 || 4 | Alexander | 60 || 5 | Ava | 17 |+------+-----------+-------+10 rows in set (0.01 sec)mysql> SELECT * FROM dt3;+------+---------+-------+| id | name | score |+------+---------+-------+| 6 | William | 69 || 7 | Sophia | 32 || 8 | James | 64 || 9 | Emma | 37 || 10 | Liam | 64 |+------+---------+-------+5 rows in set (0.01 sec)
Handle failed statements
When a statement in a transaction fails, that operation has already been automatically rolled back. However, other statements in the transaction that executed successfully can still be committed or rolled back. After the transaction is committed successfully, the modifications from the successfully executed statements take effect.
The following illustrative transcript assumes a separate test setup in which dt3 is empty and some rows of dt2 violate the target schema in strict mode. The row with id=7 remains valid. The earlier identical-schema setup does not produce this error. Roll back instead of committing if any failed statement should cancel the entire workflow.
mysql> BEGIN;
Query OK, 0 rows affected (0.00 sec)
{'label':'txn_insert_c5940d31bf364f57-a48b628886415442', 'status':'PREPARE', 'txnId':''}
mysql> INSERT INTO dt3 SELECT * FROM dt1;
Query OK, 5 rows affected (0.07 sec)
{'label':'txn_insert_c5940d31bf364f57-a48b628886415442', 'status':'PREPARE', 'txnId':'11058'}
# A failed write is automatically rolled back
mysql> INSERT INTO dt3 SELECT * FROM dt2;
ERROR 5025 (HY000): Insert has filtered data in strict mode, tracking_url=<error-log-url>
mysql> INSERT INTO dt3 SELECT * FROM dt2 WHERE id = 7;
Query OK, 1 row affected (0.07 sec)
mysql> COMMIT;
Query OK, 0 rows affected (0.02 sec)
{'label':'txn_insert_c5940d31bf364f57-a48b628886415442', 'status':'VISIBLE', 'txnId':'11058'}
Query:
# The data from dt1 is written into dt3, the row with id = 7 from dt2 is written successfully, and the other writes failed
mysql> SELECT * FROM dt3;
+------+----------+-------+
| id | name | score |
+------+----------+-------+
| 1 | Emily | 25 |
| 2 | Benjamin | 35 |
| 3 | Olivia | 28 |
| 4 | Alexander | 60 |
| 5 | Ava | 17 |
| 7 | Sophia | 32 |
+------+----------+-------+
6 rows in set (0.01 sec)
Resolve transaction errors
-
Multiple tables written to must belong to the same Database, otherwise the error
Transaction insert must be in the same databasewill be raised. -
The two transactional write modes,
INSERT INTO SELECT/UPDATE/DELETEandINSERT INTO VALUES, cannot be mixed, otherwise the errorTransaction insert can not insert into values and insert into select at the same timewill be raised. -
The Delete operation provides two ways to delete: by predicate and using the Using clause. To preserve the isolation level, within a transaction, deletions on the same table must occur before writes; otherwise the error
Can not delete because there is a insert operation for the same tablewill be raised. -
When a load that started from
BEGINexceeds the timeout configured in VeloDB Cloud, the transaction is rolled back and the load fails. Check the session variablesinsert_timeoutandquery_timeoutwhen planning the transaction duration. -
When using JDBC to connect to VeloDB Cloud for transactional operations, add
useLocalSessionState=truein the JDBC URL; otherwise the errorThis is in a transaction, only insert, update, delete, commit, rollback is acceptable.may be raised.
Commit Stream Load in two phases
Prepare a load
Set two_phase_commit:true to prepare the load without making it visible. Replace <endpoint> with the HTTPS HTTP endpoint, including its port, from warehouse connection settings, and replace the user, database, and table. curl prompts for the SQL password. The responses below are illustrative.
curl --location-trusted -u '<sql-user>' -H "two_phase_commit:true" -T test.txt '<endpoint>/api/<database>/<table>/_stream_load'
{
"TxnId": 18036,
"Label": "55c8ffc9-1c40-4d51-b75e-f2265b3602ef",
"TwoPhaseCommit": "true",
"Status": "Success",
"Message": "OK",
"NumberTotalRows": 100,
"NumberLoadedRows": 100,
"NumberFilteredRows": 0,
"NumberUnselectedRows": 0,
"LoadBytes": 1031,
"LoadTimeMs": 77,
"BeginTxnTimeMs": 1,
"StreamLoadPutTimeMs": 1,
"ReadDataTimeMs": 0,
"WriteDataTimeMs": 58,
"CommitAndPublishTimeMs": 0
}
Commit the prepared load
Choose one of the following identifiers to commit transaction 18036. Prepared data becomes visible only after commit and publication succeed.
-
The transaction can be specified by transaction id:
curl -X PUT --location-trusted -u '<sql-user>' -H "txn_id:18036" -H "txn_operation:commit" '<endpoint>/api/<database>/<table>/_stream_load_2pc'{"status": "Success","msg": "transaction [18036] commit successfully."} -
The transaction can also be specified by label:
curl -X PUT --location-trusted -u '<sql-user>' -H "label:55c8ffc9-1c40-4d51-b75e-f2265b3602ef" -H "txn_operation:commit" '<endpoint>/api/<database>/<table>/_stream_load_2pc'{"status": "Success","msg": "label [55c8ffc9-1c40-4d51-b75e-f2265b3602ef] commit successfully."}
Abort a separate prepared load
Aborting is an alternative to committing. The following examples assume a different prepared transaction, 18037, with label delete_txn_18037. Do not abort transaction 18036 after committing it. Choose one identifier:
-
The transaction can be specified by transaction id:
curl -X PUT --location-trusted -u '<sql-user>' -H "txn_id:18037" -H "txn_operation:abort" '<endpoint>/api/<database>/<table>/_stream_load_2pc'{"status": "Success","msg": "transaction [18037] abort successfully."} -
The transaction can also be specified by label:
curl -X PUT --location-trusted -u '<sql-user>' -H "label:delete_txn_18037" -H "txn_operation:abort" '<endpoint>/api/<database>/<table>/_stream_load_2pc'{"status": "Success","msg": "label [delete_txn_18037] abort successfully."}
Load multiple tables atomically
All Broker Load load tasks take effect atomically. Loads into multiple tables within the same load task are also guaranteed to be atomic. Use a stable label for each batch and reconcile its status on retries within the retention window.
Select a cluster and prepare both target tables in example_db, including partition p1 on my_table1. The following HDFS example uses built-in readers, with no separately deployed Broker. Replace the HDFS endpoint, path, and user, and configure source authentication as described in Broker Load. Wildcards match two file batches for the two target tables.
LOAD LABEL example_db.label2
(
DATA INFILE("hdfs://<hdfs-host>:<hdfs-port>/input/file-10*")
INTO TABLE `my_table1`
PARTITION (p1)
COLUMNS TERMINATED BY ","
(k1, tmp_k2, tmp_k3)
SET (
k2 = tmp_k2 + 1,
k3 = tmp_k3 + 1
),
DATA INFILE("hdfs://<hdfs-host>:<hdfs-port>/input/file-20*")
INTO TABLE `my_table2`
COLUMNS TERMINATED BY ","
(k1, k2, k3)
)
WITH HDFS
(
"fs.defaultFS" = "hdfs://<hdfs-host>:<hdfs-port>",
"hadoop.username" = "<hdfs-user>"
);
Wildcards are used to match and load two batches of files, file-10* and file-20*, into two tables, my_table1 and my_table2, respectively. Among them, my_table1 is loaded into partition p1, with the values from the second and third columns of the source file incremented by 1 before being loaded.