--- title: SQL Transactions --- For examples on how to submit SQL transactions in each client library, see the [individual driver documentation](/drivers). ## Transaction operations ### `INSERT` Inserts documents into a table. ```railroad const insertIntoTable = rr.Sequence("INSERT", "INTO", "") const colNames = rr.Sequence("(", rr.OneOrMore("", ","), ")") const doc = rr.Sequence("(", rr.OneOrMore("", ","), ")") const docs = rr.OneOrMore(doc, ",") const values = rr.Sequence(colNames, "VALUES", docs) const objs = rr.OneOrMore(rr.Choice(0, "", ""), ",") const records = rr.Sequence(rr.Optional(colNames, "skip"), "RECORDS", objs) const selectQuery = rr.Sequence(rr.Optional(colNames, "skip"), "
") const portionOf = rr.Optional(rr.Sequence("PORTION", "OF"), "skip") const forValidTime = rr.Choice(0, rr.Sequence("FOR", portionOf, "VALID_TIME", "FROM", "", rr.Optional(rr.Sequence("TO", ""), 'skip')), rr.Sequence("FOR", "ALL", "VALID_TIME"), rr.Sequence("FOR", "VALID_TIME", "ALL")) const setClause = rr.Sequence("SET", rr.OneOrMore(rr.Sequence("", "=", ""), ",")) const predicate = rr.Optional(rr.Sequence("WHERE", ""), "skip") return rr.Diagram(rr.Stack(updateTable, rr.Optional(forValidTime, "skip"), rr.Sequence(setClause, predicate))) ``` - If the valid-time range is not provided, the effective valid-time range of the update will be from now to the end of time. (SQL:2011 specifies that updates without this clause should be effective for all valid time; the now→end-of-time default is an XTDB deviation.) - The `_id` column cannot be updated - instead, users should delete this document and re-insert a new one. - The valid-time columns cannot be updated outside of the for-valid-time clause (i.e. not in the `SET` clause). ### `PATCH` Patches documents already in a table with the given document - updating those that exist, inserting any that don't (an 'upsert') - optionally for a period of valid-time. ```railroad const patchTable = rr.Sequence("PATCH", "INTO", "
") const portionOf = rr.Optional(rr.Sequence("PORTION", "OF"), "skip") const forValidTime = rr.Optional( rr.Sequence("FOR", portionOf, "VALID_TIME", "FROM", "", rr.Optional(rr.Sequence("TO", ""), 'skip'))) const objs = rr.OneOrMore(rr.Choice(0, "", ""), ",") const records = rr.Sequence("RECORDS", objs) return rr.Diagram(rr.Stack(patchTable, rr.Optional(forValidTime, "skip"), records)) ``` - If the valid-time range is not provided, the effective valid-time range of the update will be from now to the end of time. - The `_id` column cannot be patched - instead, users should delete this document and re-insert a new one. - The valid-time columns cannot be updated outside of the for-valid-time clause (i.e. not in the records themselves). - Documents are currently merged at the granularity of individual keys - e.g. if a key is present in the patch document, it will override the same key in the database document; if a key is absent or null, the key from the document already in the database will be preserved. ### `DELETE` Deletes documents from a table, optionally for a period of valid-time. ```railroad const deleteTable = rr.Sequence("DELETE", "FROM", "
") const portionOf = rr.Optional(rr.Sequence("PORTION", "OF"), "skip") const forValidTime = rr.Choice(0, rr.Sequence("FOR", portionOf, "VALID_TIME", "FROM", "", rr.Optional(rr.Sequence("TO", ""), 'skip')), rr.Sequence("FOR", "ALL", "VALID_TIME"), rr.Sequence("FOR", "VALID_TIME", "ALL")) const predicate = rr.Optional(rr.Sequence("WHERE", ""), "skip") return rr.Diagram(rr.Stack(deleteTable, rr.Optional(forValidTime, "skip"), predicate)) ``` - If the valid-time clause is not provided, the effective valid-time range of the delete will be from now to the end of time. (SQL:2011 specifies that deletes without this clause should be effective for all valid time; the now→end-of-time default is an XTDB deviation.) ### `ERASE` Irrevocably erases documents from a table, for all valid-time, for all system-time. While XTDB is immutable, in some cases it is legally necessary to irretrievably delete data (e.g. for a GDPR request). This operation removes data such that even queries as of a previous system-time no longer return the erased data. ```railroad const eraseTable = rr.Sequence("ERASE", "FROM", "
") const predicate = rr.Optional(rr.Sequence("WHERE", ""), "skip") return rr.Diagram(rr.Stack(eraseTable, predicate)) ``` ### `ASSERT` Rolls back the transaction if the provided predicate is false. This is used to enforce constraints on the data in a concurrent environment, such as ensuring that a document with a given ID does not already exist. ```railroad return rr.Diagram(rr.Sequence("ASSERT", "", rr.Optional(""))) ``` If the optional message string is provided, it replaces the default error message text "Assert failed", should the predicate fail. - We check to see whether the email address already exists in the database - if not, we can insert the new user. ``` sql ASSERT NOT EXISTS (SELECT 1 FROM users WHERE email = 'james@example.com'), 'Email already exists!' INSERT INTO users (_id, name, email) VALUES ('james', 'James', 'james@example.com') ``` - Check the `xt.txs` table for the transaction result to see if the assertion failed. ``` sql SELECT * FROM xt.txs; ``` ``` text _id | committed | error | system_time ------+-----------+-------------------------------+------------------------------- 0 | t | null | "2024-06-25T16:45:16.492255Z" 1 | t | null | "2024-06-25T16:45:26.985539Z" 2 | f | ... "Precondition failed" ... | "2024-06-25T16:45:32.577224Z" (3 rows) ``` ### `COPY` Copies data directly into an XTDB table - usually significantly more efficiently than the equivalent \`INSERT\`s. ```railroad const formatOpt = rr.Sequence("FORMAT", rr.Optional('=', 'skip'), rr.Choice(0, "'transit-json'", "'transit-msgpack'")) return rr.Diagram(rr.Stack( rr.Sequence("COPY", "
", "FROM", "STDIN"), rr.Sequence("WITH", "(", rr.ZeroOrMore(rr.Choice(0, formatOpt), ',', 'skip'), ")") )) ``` - A single `COPY` will atomically insert all of its documents within one transaction - if you're using Kafka, we recommend you split your documents into batches of ~1-10k so as not to exceed Kafka's message size limits. - If you're using `psql` (or a similar tool) to connect to XTDB, those tools also support other sources in addition to `STDIN` - please see their own documentation for more details. For example, `psql` has a [`copy`](https://www.postgresql.org/docs/current/app-psql.html#APP-PSQL-META-COMMANDS-COPY) command which supports loading from a file. - Currently, there are two accepted formats: `'transit-json'` and `'transit-msgpack'`. For more details on the Transit format, see the [available libraries](https://github.com/cognitect/transit-format?tab=readme-ov-file#implementations) for your language. - On the JVM, you can use Postgres's [`CopyManager`](https://jdbc.postgresql.org/documentation/publicapi/org/postgresql/copy/CopyManager.html) with an XTDB connection by calling `conn.unwrap(PGConnection.class).getCopyAPI()`. - In the Clojure API, `:put-docs` uses `COPY` commands on your behalf. ### BEGIN / COMMIT / ROLLBACK ```railroad const eq = rr.Optional('=') const tz = rr.Sequence(rr.Choice(0, 'TIMEZONE', rr.Sequence('TIME', 'ZONE')), eq, '') const roWith = rr.Sequence("READ", "ONLY", "WITH", '...') const rwOpts = rr.Choice(0, rr.Skip(), rr.Sequence('SYSTEM_TIME', eq, ''), rr.Sequence('ASYNC', eq, ''), rr.Sequence('METADATA', eq, ''), tz ) const rwWith = rr.Sequence("READ", "WRITE", "WITH", "(", rr.OneOrMore(rwOpts, ","), ")") const modes = rr.OneOrMore('', ',') const begin = rr.Sequence(rr.Choice(0, 'BEGIN', rr.Sequence('START', 'TRANSACTION')), rr.Optional(rr.Choice(0, modes, roWith, rwWith), 'skip')) const commit = rr.Sequence('COMMIT', rr.Optional(rr.Choice(0, 'SYNC', 'ASYNC'), 'skip')) return rr.Diagram(rr.Choice(0, begin, commit, 'ROLLBACK')) ``` * A transaction may be either `READ ONLY` or `READ WRITE`. If not specified, it will be inferred from the first statement in the transaction. Transactions must not mix query statements and [DML](https://en.wikipedia.org/wiki/Data_manipulation_language) statements. * `BEGIN`'s transaction modes are those of [`SET TRANSACTION`](#set-transaction-v22): `BEGIN READ WRITE, SYSTEM_TIME = ...` opens a transaction and applies `SET TRANSACTION READ WRITE, SYSTEM_TIME = ...` to it. * `BEGIN READ WRITE WITH (...)` takes the same options inside `WITH (...)`, `TIMEZONE` included. * `COMMIT` (v2.2+) optionally takes `SYNC` or `ASYNC`, choosing whether the connection waits for the transaction to be indexed before returning. `COMMIT SYNC` waits for indexing; `COMMIT ASYNC` returns as soon as the transaction is submitted to the log. When given, this takes precedence over the transaction's `ASYNC` option; otherwise that option applies, defaulting to `SYNC`. * N.B. `READ WRITE` is a misnomer in XTDB here - this is to align with standard SQL syntax. XTDB doesn't have interactive read-write transactions, so any attempt to (e.g.) `SELECT` in this transaction will error. * For read-only transactions, see the [query reference](/reference/main/sql/queries#begin--commit--rollback). * `BEGIN`, `COMMIT` and `ROLLBACK` are SQL statements over the Postgres wire protocol only - see the [query reference](/reference/main/sql/queries#begin--commit--rollback). ### SET TRANSACTION (v2.2+) ```railroad const eq = rr.Optional('=') const value = (v) => rr.Choice(0, v, 'DEFAULT') const ro = rr.Sequence("READ", "ONLY", '...') const rwMode = rr.Choice(0, rr.Sequence('READ', 'WRITE'), rr.Sequence('SYSTEM_TIME', eq, value('')), rr.Sequence('ASYNC', eq, value('')), rr.Sequence('METADATA', eq, value('')), rr.Sequence(rr.Choice(0, 'TIMEZONE', rr.Sequence('TIME', 'ZONE')), eq, value('')), rr.Sequence('ISOLATION', 'LEVEL', '') ) const rw = rr.OneOrMore(rwMode, ',') return rr.Diagram(rr.Sequence('SET', 'TRANSACTION', rr.Choice(0, ro, rw))) ``` * For how a list of transaction modes is read, how a later `SET TRANSACTION` merges into an earlier one, when it is accepted, `TIMEZONE`, and read-only transactions, see the [query reference](/reference/main/sql/queries#set-transaction-v22). * For read-write transactions: * `SYSTEM_TIME` overrides the system-time of the transaction, used for an initial backfill of the database. It must be strictly later than the system-time of the latest completed transaction — a backfill submitting several transactions gives each its own system-time rather than sharing one. A system-time that doesn't advance aborts the transaction, and the abort is recorded in `xt.txs`. The aborted transaction still takes a system-time of its own, 1µs past the latest completed one, so a retry has to advance on that rather than on the instant it asked for. Otherwise, the system-time of the transaction will be defined by the log. * `ASYNC` affects whether the connection will wait for the transaction to be indexed before returning from `COMMIT`. If not provided, it defaults to `false` - i.e. the connection will wait for the transaction to be indexed before returning. This can be overridden per-commit with `COMMIT SYNC` / `COMMIT ASYNC` (see [above](#begin--commit--rollback)). * `METADATA` (v2.1+) can provided to attach arbitrary metadata to the transaction. This is then added to the `xt.txs` table in the `user_metadata` column. For example, you might use this to attach upstream request IDs, correlation IDs, or other data lineage information.