All docs pages
Docs

Database

Tables of records the app saves and searches, such as users, orders or posts.

In stackly.json and the CLI it is database. Its use, live or draft, is counted as database reads and database writes; see Live app prices.

database · optional · needs backend · D1 (SQLite) · binding APP_DATABASE

Tables of records the app saves, lists and searches: users, orders, posts. The draft and live each have their own.

Turn it on

"features": ["backend", "database"],
"bindings": ["APP_DATABASE"]

stackly features on database does both.

Use it

  1. Create tables with migration files in migrations/, one statement each:

    -- migrations/0001_create-messages.sql
    CREATE TABLE IF NOT EXISTS messages (id TEXT PRIMARY KEY, name TEXT NOT NULL, text TEXT NOT NULL, created_at INTEGER NOT NULL)
    
  2. Read and write in server code, always with parameters:

    import { env } from "cloudflare:workers";
    
    await env.APP_DATABASE.execute(
      "INSERT INTO messages (id, name, text, created_at) VALUES (?, ?, ?, ?)",
      [crypto.randomUUID(), data.name, data.text, Date.now()],
    );
    const { rows } = await env.APP_DATABASE.query("SELECT * FROM messages ORDER BY created_at DESC LIMIT ?", [50]);
    
  • Migration names: 4+ digits, _, kebab-case, .sql (0001_create-messages.sql). Allowed: CREATE TABLE IF NOT EXISTS, CREATE [UNIQUE] INDEX IF NOT EXISTS, ALTER TABLE … ADD COLUMN, INSERT OR IGNORE. Never drop or rename; expand, then contract. A new NOT NULL column needs a DEFAULT.
  • Sample rows for the draft go in samples/ (0001_messages.sql, one INSERT OR IGNORE each, stable ids). They never reach live.
  • Page every list query, index every foreign key and lookup column, and never query inside a loop.

Limits

One SQL statement per call. Publishing rehearses the migrations on a copy of the live data and blocks on lost rows.

Locally

stackly dev has its own database with the migrations and samples applied (--reset starts it over). stackly db lists tables; stackly db query "<sql>" runs SQL on the local database only.

Related

search for full-text search, backups for daily copies of the live database.

All app features