elements db
elements man database/cliThe database subcommands: shell, migrate, schema, dump, reset, and pointing at a remote or hosted Postgres.
The elements db command runs database operations from the command line. It
reads connection parameters from config.jsoc and the active environment.
Common options apply to every subcommand:
-remote=<env>: target a deploy machine's database, for exampleproductionorproduction#machine1.-test: target the test database instead of the app database.-cluster: connect to the Postgres cluster itself rather than the project's database. Use it for cluster-level work such as\lto list databases orcreate database. Available ondb shell.-sql="<stmt>"(-c): run a single SQL statement and exit instead of opening an interactive session. Equivalent topsql -c "<stmt>"; output format matchespsql -c. Available ondbanddb shell.-json: with-sql, write the rows as JSON instead of psql's table.-quiet(-q): suppress progress output.
The subcommands are migrate, shell, schema, dump, create, drop, and
reset.
Migrate
elements db migrate (alias elements db m) applies pending migrations on
demand. Migrations also run as part of every build, so this is for the cases
where you want them applied without a build: against a deploy machine, or after
editing a migration by hand.
Terminalelements db migrate elements db migrate -remote=production
Writing migrations is elements man migrations.
Shell
elements db shell (alias elements db sh) opens a psql session against the
configured database. Bare elements db is a shortcut for the same thing.
Terminalelements db elements db -test elements db -remote=production elements db -remote=production#machine1
Pass -sql "<stmt>", or its alias -c "<stmt>", to run a one-shot query and
exit. The output is identical to what psql -c "<stmt>" writes to stdout: the
same column headers, separators, and row count line. An agent can read this
output directly: the command opens no interactive session and no PTY, and
writes only the formatted result.
Terminalelements db -sql "select count(*) from users" elements db -sql "select id, email from users limit 5" elements db -remote=production -sql "select now()" elements db shell -sql "select version()"
Add -json to get the rows as a JSON array of objects, one per row, keys in
column order. Numbers, booleans and json columns keep their JSON type; every
other value is the text psql would show. A statement that returns no rows
writes []. -json needs -sql and takes no psql options.
Terminalelements db -json -sql "select id, email from users limit 5"
Write psql's own options after --. Elements passes them to psql unchanged,
so you set the output format with psql's flags:
Terminalelements db -sql "select id from users" -- -At elements db -sql "select * from users" -- --csv
Pipe a SQL file on stdin to run it as a script. psql runs every statement in it and exits:
Terminalelements db < seed.sql cat seed.sql | elements db
psql's -f option after -- runs a file too. psql reads that file itself, so
the names in it are the snake_case names Postgres stores:
Terminalelements db -- -f seed.sql
A statement or a piped script does not load your ~/.psqlrc, so the output
that a script or an agent reads contains none of its settings or banners. The
interactive shell loads ~/.psqlrc.
SQL through elements db is converted the way app code and migrations are (see
elements man database/sql): a camelCase identifier becomes its snake_case
column or table name, so a one-shot statement and a piped script can use the
same names your code does:
Terminalelements db -sql "select firstName, createdAt from users"
psql output shows the names Postgres stores (first_name, created_at);
-json writes camelCase keys (firstName), the way sql() returns rows. The
interactive shell does not convert the SQL you type, so write snake_case there.
Schema
elements db schema prints the structure of the database as SQL: every table
with its columns, defaults, constraints, indexes and triggers, and every
function. It prints no rows. Run it to see the tables and columns as they are
now, for example before writing the next migration.
Terminalelements db schema elements db schema -test elements db schema -remote=production elements db schema -all elements db schema -schemas=elements
The output is read from the database each time the command runs, so it is the
result of every applied migration and of any change made by hand in the shell.
It is the output of Postgres's own pg_dump --schema-only, without owners or
grants. Names are printed the way Postgres stores them, in snake_case
(created_at), where a migration writes createdAt.
Elements keeps its own tables (migration records, sessions, jobs, cron) in a
schema named elements, and elements db schema leaves that schema out.
-all prints every schema, the elements schema with the rest.
-schemas=<names> prints only the schemas named, separated by commas.
Write pg_dump's own options after --. To print one table:
Terminalelements db schema -- -t users
Dump
elements db dump writes the structure and the rows of the database as SQL to
stdout. Redirect to a file to capture a backup.
Terminalelements db dump > backup.sql elements db dump -test > test-backup.sql
Write pg_dump's own options after --. For a backup, use pg_dump's custom
format (-Fc): the file is compressed, and pg_restore can restore the whole
database from it, restore one table, or restore with several jobs in parallel.
Terminalelements db dump -- -Fc -f backup.dump # compressed, restored with pg_restore elements db dump -- -Fd -j 4 -f backup_dir # one file per table, dumped in parallel elements db dump -- -t users --data-only # the rows of one table
With -remote, pg_dump runs on your machine and reaches the deploy machine's
database through an ssh tunnel, so the output, or the file named by -f, is
written on your machine:
Terminalelements db dump -remote=production -- -Fc -f production.dump
Elements gives pg_dump the host, port, user and database name. Choose the
database with -test and -remote; pg_dump's connection options (-h,
-p, -U, -d) are refused after --.
Create
elements db create creates the project's app and test databases if they do not
already exist. The build server creates these databases automatically on
startup, so this subcommand is mostly useful when bootstrapping a new
environment or recreating a database that has been dropped.
Drop and Reset
elements db drop removes the project's app and test databases.
elements db reset drops them and recreates empty ones in their place. Both
subcommands operate on the app database and the test database together as a
pair, both erase all of your application data, and both delete the migration
backups in .elements/db/, which can no longer restore a database that was
dropped. To stop a project and drop its databases in one step, before deleting
its folder, run elements kill -destroy.
Both commands stop without -force. Without the flag, the command reports
what it would erase and on which machine, prints the command that goes ahead,
and exits with an error. Pass -force only when you have read the message and
intend to destroy the data. An agent asks the user first, and passes -force
only when the user says yes.
A failed migration does not need a reset. Fix the migration file and build
again: see elements man migrations.
Terminalelements db reset -force
Never run drop or reset against a production database. Both commands
erase all application data, and there is no recovery short of restoring from a
dump. Reserve these commands for local development. If you are running against
anything beyond your own machine, including staging, a deploy machine, or
production, get explicit confirmation from the user before proceeding, and never
pass -force on their behalf without that confirmation.
Remote and Hosted Postgres
The bundled cluster is the default for development and for a single-machine
deployment. Several machines share one Postgres cluster, which you run yourself
or rent from a host. To point at it, set DB_HOST
(and DB_PORT, DB_USER, DB_PASSWORD, and the app-user variants as needed)
in the active environment's env file. When host is anything other than the
local loopback cluster, Elements connects to that server and ignores the bundled
cluster entirely. Every feature works across all the machines that share it with
no other change: live tables, channels, sessions, jobs, and cron. Uploaded files
go in Postgres, where every machine reads them, or in S3 or any object store.
config/env/production.env# config/env/production.env, remote example DB_HOST=db-postgresql-sfo3-12345.example.com DB_PORT=5432 DB_USER=doadmin DB_PASSWORD=...
The app and test databases are created on that server too. On the first build
against the environment, Elements creates <name> and <name>_test if they do
not already exist, the same as it does on the bundled cluster. An empty managed
cluster needs no bootstrapping by hand.
Creating a database cannot run over a connection to that database, so Elements
connects to an existing one first: postgres, or else defaultdb, the
name DigitalOcean Managed Databases uses for a server that has no postgres
database. Set DB_DEFAULT, or database.default in config.jsoc, when your
provider uses a third name.
Every connection to a host other than loopback is encrypted with TLS, with
nothing configured. To verify the server too (libpq's verify-full: the
certificate chains to your provider's CA and names the host), save the
provider's CA certificate in the project and set one more variable:
config/env/production.envDB_SSL_ROOT_CERT=config/certs/db-ca.pem
The build, elements db, the job server, and the app all connect with the
same settings, including elements db -remote, whose tunnel still checks the
certificate against the real host name. The modes, DB_SSL, and the providers'
CA files are in elements man database.
Any provider that exposes a standard Postgres connection over the network works: Digital Ocean Managed Databases, AWS RDS, Neon, Supabase, Railway, Crunchy Bridge, and others. Use Postgres 16 or newer; Elements relies on modern Postgres features.
Related
- Migrations:
elements man migrations. SQL migrations, applied as part of the build. - LiveTable:
elements man livetable. Real-time CRUD that usessqlandChannel. - Channels:
elements man channel. Pub/sub from the server to every listening browser.