Skip to content

Run usql in CI

This recipe runs a SQL script in a CI job, such as a migration or a check of the data. CI is continuous integration: a service that runs your jobs on each change. The job fails when the script fails. Install usql on the runner first, as Install usql shows.

Terminal window
usql -X -w -1 -U on_error_stop=on -f migrate.sql
Option What it does in a job
-X runs no init.sql, so that no file of the runner changes the job
-w never asks for a password. If the server refuses the login, usql stops
-1 runs the script in one transaction
-U on_error_stop=on stops at the first error. With -1, usql rolls the transaction back
-f migrate.sql runs the script, then exits

The command names no database. usql opens the URL in the USQL_DSN environment variable.

A CI service keeps a password in a secret, and gives it to the job as an environment variable. Put the whole URL in the secret, and give it to usql as USQL_DSN. The password is then not on the command line, and not in the log of the job. In GitHub Actions, a step looks like this:

- name: Migrate the database
env:
USQL_DSN: ${{ secrets.DATABASE_URL }}
run: usql -X -w -1 -U on_error_stop=on -f migrate.sql

usql removes USQL_DSN from its environment after it reads it. Passwords shows the other ways to give a password.

A CI job fails when a command exits with a status that is not 0. usql exits with:

  • 0 when the script ran to its end.
  • 1 when usql cannot connect, cannot read the file, or a -c fails.
  • 3 when on_error_stop stops the script at an error.

Without on_error_stop, a statement that fails in a file of -f does not change the status, as in psql. The job then passes. Always turn on on_error_stop for a file. Run queries and scripts has the details.

When the script of the example runs a second time, its create table fails, and usql exits with 3:

error: sqlite3: 1: table orders already exists

To test a value in the shell, print it with no table around it. -A prints the unaligned format, and -t prints only the rows:

Terminal window
n=$(usql -X -w -A -t -c 'select count(*) from orders')
test "$n" -gt 0

test fails the job when the table has no rows.