How Migrations Work

Every migration is a hand-written .sql file. On startup, Step 4 of start-velaris.sh creates the ledger table if absent, walks the migration directory in sorted filename order, skips any file already recorded in schema_migrations, applies the rest, and records each one as it succeeds. A failing migration stops the whole startup — the platform never boots on a half-applied schema.

DialectLocationShape
PostgreSQLmigrations/postgresql/Full incremental history, 001 > 155
MySQL / MariaDBmigrations/mysql/Frozen baseline 000_baseline_pg154.sql (a snapshot of PostgreSQL 001 > 154), the seed files 001 > 003, then one incremental file per PostgreSQL migration from 155 onward, sharing its sibling's number
Never regenerate the MySQL baseline for a schema change. The baseline is frozen. A schema change ships as a new numbered file beside it, sharing its PostgreSQL sibling's number — exactly as the PostgreSQL track works.

The reason is the ledger. On an existing install the baseline is already recorded in schema_migrations, so a regenerated baseline is silently skipped and the change reaches nobody — no error, no warning. Regeneration only ever serves installs that do not exist yet. It also cannot be both ways: a baseline regenerated from current models already contains every change, so an incremental file applied after it is a guaranteed duplicate-column failure.

The gap between 003 and 155 is intentional. Numbers 000–003 are the MySQL bootstrap; 004–154 are empty because the baseline already contains them.
Dialect drift is only caught by PostgreSQL. SQLite ignores column length constraints entirely, so a wrong VARCHAR(n) passes every SQLite test and fails only on PostgreSQL. Run the PostgreSQL test harness before declaring a migration done.

The Ledger Table

-- PostgreSQL
CREATE TABLE IF NOT EXISTS schema_migrations (
  filename   TEXT PRIMARY KEY,
  applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- MySQL variant (VARCHAR PK, DATETIME(6), INSERT IGNORE on record)
CREATE TABLE IF NOT EXISTS schema_migrations (
  filename   VARCHAR(255) PRIMARY KEY,
  applied_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6)
);

The ledger keys on filename, not a revision graph. Renaming an already-applied migration file makes the platform try to apply it a second time.

Common Commands

# Apply all pending migrations (normal path — part of platform startup)
./start-velaris.sh

# Container / user / database come from velaris.yaml — export them once
export DB_CONTAINER=docker-compose-velaris-db-1 DB_USER=velaris DB_NAME=velaris

# Show what has been applied
docker exec "$DB_CONTAINER" psql -U "$DB_USER" -d "$DB_NAME" \
  -c "SELECT filename, applied_at FROM schema_migrations ORDER BY filename DESC LIMIT 10;"

# Find pending files (on disk but not in the ledger)
docker exec "$DB_CONTAINER" psql -U "$DB_USER" -d "$DB_NAME" -tAq \
  -c "SELECT filename FROM schema_migrations" | sort > /tmp/applied.txt
ls migrations/postgresql | sort | comm -23 - /tmp/applied.txt

# Apply a single migration by hand (recovery only)
docker exec -i "$DB_CONTAINER" psql -U "$DB_USER" -d "$DB_NAME" \
  < migrations/postgresql/124_marketplace_containers.sql

# Apply the whole MySQL track to a throwaway server and check it against the models.
# This is what proves a MySQL migration works — the test suite builds its schema
# from ORM metadata and never executes these files.
for f in $(find migrations/mysql -maxdepth 1 -name '*.sql' | sort); do
  docker exec -i mysql-test mysql -uroot -p"$PW" velaris < "$f" || echo "FAILED: $f"
done

Writing a Migration

  1. Create migrations/postgresql/<next>_<feature>.sql, incrementing the number sequentially from the current head.

  2. Open with a comment block explaining why the table exists and what invariants it carries — every shipped migration does this, and it is the only schema documentation that lives next to the schema.

  3. Make it idempotent: CREATE TABLE IF NOT EXISTS, CREATE INDEX IF NOT EXISTS, ADD COLUMN IF NOT EXISTS. Startup re-runs are cheap; a migration that fails on second application blocks the platform.

  4. Size every VARCHAR deliberately. A sha256: digest needs VARCHAR(96), not VARCHAR(64) — the prefix counts.

  5. Write the matching migrations/mysql/<same number>_<feature>.sql. Same number as the PostgreSQL file, so the two tracks read side by side and a change that reached only one engine is obvious. Do not regenerate the baseline.

  6. Apply the whole MySQL track to a throwaway MySQL and MariaDB — the engines disagree on enough DDL that one passing is not evidence for the other, and the test suite builds its schema from ORM metadata rather than from these files.

  7. Add indexes in the same file as the table they serve; add indexes to existing large tables in their own migration so a slow build is isolated.

-- 125_example_feature.sql
-- One row per widget. Tenant-scoped; deleting the parent grant releases
-- the row rather than cascading, so audit history survives revocation.

CREATE TABLE IF NOT EXISTS example_widgets (
    id          UUID PRIMARY KEY,
    tenant_id   VARCHAR(255) NOT NULL,
    grant_id    UUID REFERENCES marketplace_capability_grants(id) ON DELETE SET NULL,
    status      VARCHAR(32) NOT NULL DEFAULT 'pending',
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_example_widgets_tenant
    ON example_widgets (tenant_id, status);

Production Checklist

  1. Back up the database before any migration that alters or drops data.

  2. Run on staging first against a copy of production data.

  3. Read the SQL end to end. There is no autogenerate step to blame — every statement was written by hand and should be reviewed by a second person.

  4. Monitor for lock waits using pg_stat_activity while the migration runs.

  5. Verify afterwards: the new filename appears in schema_migrations and the affected endpoints respond.

Never run migrations as a PostgreSQL superuser in production. Use a dedicated velaris user scoped to the Velaris schema — superuser writes silently bypass row-level security policies.
Dropping a column takes two deploys. Remove every code reference and deploy first; run the drop in the following deploy. Dropping while code still reads the column produces immediate 500s.
There is no automatic downgrade. Plain SQL files carry no downgrade(). Rolling back means restoring the backup or writing a compensating forward migration — plan the forward path before applying.

Migration History by Feature

Filenames follow <number>_<feature>.sql, with the number zero-padded to three digits from 060 onward.

RangeFeature
060–064HxCanvas, HxDocs, HxBranch, HxWork commits, story–branch links
065–071Real auth, payment execution, credential rotation, auth hardening, demo users, route permissions, superadmin
072–074Case-type migration audit, connector intelligence, HxDeploy delivery
075–077Customer accounts, scheduled releases, release versioning
078–079HxDB Manager and its security layer
080–086Versioned flags, refresh tokens, append-only chain, transactional outbox, PUO plans, audit anchors, WebAuthn devices
087–088Case Variables v2 and variable promotion
089–090HxGuard relationship tuples, HxVault per-tenant DEKs
091–093Test Suite, Marketplace conformance, AI-stale tracking
094–096Marketplace schema, HxCheckout, HxStorefront
097–099, 103HxDBMigrate — analysis, generation, costing hooks, polling sync
100–102HxReplay and case costing rate cards
104–105, 110HxEvolve, per-case-type config, cumulative drift baselines
106–109HxNexus Operator — idempotency, proposals, proposal tenancy, external token grants
111Case time entries (manual timers and timesheets)
112–114, 118–121HxMeet — sessions, participants, sealed recording, intelligence, live transcript, KYC, biometric consent
115–117Portal v2 — submission refs, case messages, CSAT feedback
122–124Marketplace execution — capability grants, grant drift, hardened containers
Current head: 124 (124_marketplace_containers.sql). The next migration is 125_. Always increment sequentially — the ledger applies files in sorted filename order, so a gap or a duplicate number changes the apply sequence.