Skip to content

Transactions

A transaction groups statements, so that the database keeps all of their changes or none of them. usql has three meta commands for a transaction. They work the same on every database that has transactions.

\begin starts a transaction. The statements after it run in the transaction:

\begin
update products set price = price + 1;
select name, price from products;

\commit keeps the changes of the transaction. \rollback drops them:

\rollback

While a transaction is open, the prompt ends with =~ in place of =>.

  • usql has one transaction at a time. If a transaction is open, \begin prints error: previous transaction exists.
  • If no transaction is open, \commit and \rollback print error: no previous transaction exists.
  • You cannot connect to another database while a transaction is open. End the transaction first.

\begin -read-only starts a transaction that only reads. After -read-only, you can give an isolation level, such as serializable:

\begin -read-only serializable

The driver of the database must support it. If it does not, \begin -read-only prints an error and starts no transaction. Neither SQLite nor DuckDB supports it. On SQLite, usql prints error: sqlite3: read-only transaction not supported by driver.

-1 (--single-transaction) starts a transaction before the first -c or -f, and commits it after the last one:

Terminal window
usql -1 -U on_error_stop=on -f migrate.sql shop.db

Give -1 together with -U on_error_stop=on. Then the first statement that fails stops the script, usql rolls the transaction back, and the database keeps none of the changes. usql exits with the status 3.

Without on_error_stop, usql goes on after a statement that fails, as psql does. At the end it sends COMMIT, and the database can keep the changes of the other statements.

-1 works only when usql does not read from a terminal. At the prompt, use \begin.

You can also send begin; and commit; as SQL. Then the database starts the transaction, and usql does not know about it. \commit and \rollback do not end it, and the prompt does not show it. On SQLite, a \begin after it fails, because the database already has a transaction. Use \begin so that usql knows that a transaction is open.

If a transaction is open when usql exits, usql rolls it back. The database keeps none of its changes. This happens when you type \q or press Ctrl-D, and at the end of a script that -f runs.

To keep the changes, end the transaction with \commit before you exit. In a script, put \commit at the end.