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.
Start and end a transaction
Section titled “Start and end a transaction”\begin starts a transaction. The statements after it run in the transaction:
\beginupdate products set price = price + 1;select name, price from products;\commit keeps the changes of the transaction. \rollback drops them:
\rollbackWhile a transaction is open, the prompt ends with =~ in place of =>.
The rules
Section titled “The rules”- usql has one transaction at a time. If a transaction is open,
\beginprintserror: previous transaction exists. - If no transaction is open,
\commitand\rollbackprinterror: no previous transaction exists. - You cannot connect to another database while a transaction is open. End the transaction first.
A read-only transaction
Section titled “A read-only transaction”\begin -read-only starts a transaction that only reads. After -read-only, you can give an isolation level, such as serializable:
\begin -read-only serializableThe 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.
Run a script in one transaction
Section titled “Run a script in one transaction”-1 (--single-transaction) starts a transaction before the first -c or -f, and commits it after the last one:
usql -1 -U on_error_stop=on -f migrate.sql shop.dbGive -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.
BEGIN and COMMIT in SQL
Section titled “BEGIN and COMMIT in SQL”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.
An open transaction at exit
Section titled “An open transaction at exit”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.