These guides are primarily for agent readers. They explain how agents use Sails. If you are a person, start at sails.app or Add Sails.

Keep app data in a database

App records live in a .db directory bundle (sqlite by default, or foreign Postgres), not in a page glob and not in sails.data.json. --db PATH.db is required on every sql call.

A collection (glob: pages/blog/**) only indexes other pages at compile time. See Collections.

Done looks like

sql --db app.db "SELECT * FROM contacts" prints JSON with a rows array. A later --exec insert shows up in the next SELECT. sql list, run in the folder that holds the bundle, prints its path.

Worked example: the CRM template

Job: copy a working app, let first use provision the database, then insert and read one row.

cp -r /templates/crm-app ./app
sql --db ./app/app.db "SELECT 1"

First use writes app/app.db/connection (one line: sqlite), runs migrations/, then seeds/. The first call can take several seconds. Output:

{
  "columns": ["1"],
  "rows": [{ "1": 1 }]
}

The bundle now holds three things. There is no data.sqlite file:

$ ls app/app.db
connection
migrations
seeds

The seed loads four contacts:

sql --db ./app/app.db "SELECT id, name, email FROM contacts ORDER BY name LIMIT 3"
{
  "columns": ["id", "name", "email"],
  "rows": [
    { "email": "jordan@brightline.example", "id": "019f7518-fe05-71eb-8f41-8db241904ad1", "name": "Jordan Lee" },
    { "email": "maya@acme.example", "id": "019f7518-fe06-71a2-b800-65653d9c5b37", "name": "Maya Chen" },
    { "email": "riley@independent.example", "id": "019f7518-fe07-7cd0-80be-8d17cbd759a0", "name": "Riley Park" }
  ]
}

Bind values with ? and trailing arguments. Do not paste user input into the SQL string. One statement per call; sql: multi-statement SQL is not allowed is the error for more.

sql --db ./app/app.db --exec \
  "INSERT INTO contacts (id, name, email) VALUES (?, ?, ?)" \
  "c_demo" "Ada Lovelace" "ada@example.com"
# { "affected": 1 }

sql --db ./app/app.db "SELECT name, email FROM contacts WHERE id = ?" "c_demo"
# { "columns": ["name", "email"], "rows": [{ "email": "ada@example.com", "name": "Ada Lovelace" }] }

Add RETURNING to get the row back with the count:

sql --db ./app/app.db --exec "INSERT INTO notes (id, body) VALUES (?, ?) RETURNING id" "n_demo" "Called back"
# { "affected": 1, "columns": ["id"], "rows": [{ "id": "n_demo" }] }

The CRM template already has a notes table. CREATE TABLE notes fails with table notes already exists. Pick another name or add a migration.

What a .db bundle is

app.db/
  connection      # written on first use; missing in templates (sqlite | ssec_… | postgres://…)
  migrations/     # NNNN_description.sql
  seeds/          # ordered *.sql, idempotent by convention

sqlite rows are not a workspace file. They live in a per-branch storage sidecar next to the repo. Do not cp or read_file the database. Two things follow:

  • repo restore rewinds connection, migrations, and seeds, but not the rows.
  • A work branch or change-request preview writes to its own copy, so it cannot clobber main.

The sqlite cap is 64 MiB. Keep large files (photos, PDFs) as workspace files and store their paths in a column. Move to foreign Postgres when you outgrow it.

Create a bundle by hand when you are not starting from a template:

$ createdb app.db
Created database `/ryan/home/app.db` (sqlite)

Foreign Postgres (you already have a DSN):

secret set --origin https://db.example.com --as app-db "postgres://…"
# prints ssec_…
createdb app.db --url ssec_…

--url attaches; it does not CREATE DATABASE. Put ssec_… in connection, not the DSN. A leftover sails-db:// handle errors; recreate as sqlite or with --url. See Store a secret.

dropdb app.db deletes connection and, for sqlite, every row. migrations/ and seeds/ stay, so the next sql --db app.db provisions a fresh database and reseeds it. For foreign Postgres it only removes the connection file.

Commands you will actually run

sql help
sql list                         # bundles in the current folder only
sql show --db app.db
sql migrate --db app.db [--dry-run]
sql migrate status --db app.db
sql seed --db app.db [--dry-run]
sql --db app.db "SELECT 1"
sql --db app.db --exec "INSERT INTO contacts (id, name) VALUES (?, ?)" "c1" "Ada"
sql --db app.db --params '["team"]' "SELECT * FROM notes WHERE visibility = ?"
sql --db app.db --rls "SELECT * FROM memos"
sql --db app.db --explain "SELECT * FROM contacts WHERE email = ?" "x"
sql transaction --db app.db --exec "INSERT …" … --query "SELECT …"
sql reload --db app.db

What they print, from a real run:

$ sql list
/ryan/home/app/app.db

$ sql show --db app.db
path: /ryan/home/app/app.db
kind: sqlite
handle: sqlite
in_transaction: false
row_owner: none

$ sql migrate status --db app.db
Dry run: 0 pending, 1 already applied

sql list does not search subfolders. From the folder above app/ it prints No `.db` bundles in this directory.

CommandResult
Query{ "columns": […], "rows": […] }
--exec{ "affected": N }, plus columns and rows with RETURNING
sql transactionA JSON array with one result per --exec or --query, in order
--explainsqlite bytecode rows (addr, opcode, p1 to p5, comment), not a query plan summary

JSON columns are TEXT in sqlite, but query output parses them. In the CRM notes table, links comes back as an object such as { "contactId": "…" }.

Workspace also has sql begin / commit / rollback. Published handlers may run query, exec, and sql transaction only. Blocked on a published mount: createdb, dropdb, migrate, seed, owner, begin / commit / rollback, reload.

From a form handler

A *.api.sh on the published site talks to the same bundle. Prefer invoker (the default) when the visitor is signed in. Use security: definer only for anonymous public writes.

---
methods: [POST]
auth: required
body:
  type: object
  required: [title]
  properties:
    title: { type: string, minLength: 1 }
---
title="$(request param title)"
sql --db app.db --exec "INSERT INTO todos (title) VALUES (?)" "$title"
respond redirect /todos

Dry-run without hitting the live URL:

handler-test pages/api/tasks/create.api.sh \
  --method POST --json '{"title":"Ship"}' --auth '{"signed_in":true}'

--auth only toggles signed_in. You cannot forge sub. See Put a form on a site.

A handler write is saved before the visitor gets the response. Your next workspace sql read picks it up on its own. Run sql reload --db app.db only for foreign Postgres or a stuck transaction.

Row ownership

ContextIdentityOwner-scoped tables
Workspace sqlNoneEvery row
Workspace sql --rlsYouOnly your rows; inserts stamp your id
Published sql (invoker)Signed-in visitor, or NULL if anonymousSame as --rls
Published sql (definer)PublisherEvery row

Opt a table in. The owner column must already exist (--column defaults to owner_id):

$ sql --db app.db --exec "CREATE TABLE memos (id text PRIMARY KEY, body text NOT NULL, owner_id text)"
$ sql --db app.db --exec "INSERT INTO memos (id, body) VALUES (?, ?)" m1 orphan
$ sql owner enable --db app.db memos
Owner-scoped: memos (owner_id)
warning: 1 row(s) have NULL owner_id and will be invisible to invoker / --rls queries. Re-run with --assign-null-to <id> to stamp them, or update them from workspace sql.

$ sql owner status --db app.db
table   owner_column
memos   owner_id

Now an --rls insert stamps your id, and an --rls read hides the orphan row:

sql --db app.db --rls --exec "INSERT INTO memos (id, body) VALUES (?, ?)" m2 mine
# { "affected": 1 }
sql --db app.db --rls "SELECT id, body, owner_id FROM memos"
# rows: [{ "id": "m2", "body": "mine", "owner_id": "019f…" }]
sql --db app.db "SELECT id, owner_id FROM memos"
# rows: m1 (owner_id null) and m2

Rules that bite:

  • Invoker and --rls SQL reject any unquoted REPLACE, including INSERT OR REPLACE. Use INSERT OR IGNORE. ON CONFLICT DO UPDATE and ON CONFLICT DO NOTHING fail too.
  • Prefer uuid v7 ids. A UNIQUE collision can reveal that another caller's key exists.
  • Foreign keys into an owner-scoped table do not work from invoker SQL.
  • Tables you never opt in return every row to whoever can query them. Templates do not enable ownership for you.
  • sql owner disable --db app.db memos turns it off.

See SQL.

Failure modes

What you seeWhat it meansWhat to do
sql: --db PATH.db is requiredFlag is missingsql --db app.db "SELECT 1"
No `.db` bundles in this directory.sql list only looks in the current foldercd into the folder that holds app.db, or copy /templates/crm-app / createdb app.db
sql: multi-statement SQL is not allowedOne statement per callSeparate calls, or sql transaction
table notes already existsThe CRM template ships notesUse another table name, or a migration
sql: column "owner_id" does not exist on table "memos"owner enable needs the column firstAdd it in a migration, then enable
owner-scoped SQL cannot use REPLACEINSERT OR REPLACE under invoker or --rlsINSERT OR IGNORE, or an UPDATE
Rows vanished after dropdbdropdb deletes sqlite rowsNext sql --db reseeds; rows you added are gone
You queried a glob / collection queryCollections are pages, not rowssql --db
Handler cannot migrate / createdb / ownerWorkspace-only commandsRun them in the workspace, then publish
Statement timeoutWorkspace 5s / 8s, published 2s / 3s, migrate and seed 30s / 45sSmaller query. Add indexes in migrations/
sails-db:// errorOld platform Postgres handleRecreate as sqlite or createdb --url …
You committed postgres://…Wrong storecreatedb app.db --url ssec_…
Empty rows after insertDifferent --db path, or you looked at a globSame PATH.db on insert and select

See SQL for the feature reference, Filter when the job is JSON files, Collections when the job is a list of pages, and Put a form on a site when the job is POST, write, redirect.