Skip to content

The database: settings and the migration approach

Owner: @zuki · Written by the Backend Engineer · Last reviewed: 2026-10-12 · Conforms to the decisions through D32

How the v2 Supabase projects are set up, what to follow when you add to schema V13, and how the data moves from v1 to v2 once. The Backend Engineer keeps this guide; the decisions and the rules outrank it (how we work).

It moved here on 2026-10-12 from the Google doc [Spec] Database v2 migration plan (#50, D28). On the way, the parts other pages already hold became links, and the To do marks for P15, error keys and the test harness were dropped: packs B to E built them (D10, D12, D14, D30).

What v2 should do is in the rules; what it is today is in the generated reference (D27). Neither is repeated here.

Old section Now
Context, the approach, the module plan Plan: modules M0 to M7
Fixed decisions (Q1 to Q9, P1 to P16) D2 and D9, and the rules that carry each one
Environments and the stack Architecture
Schema V13: tables, links, enums Data model, and the generated tables and enums
Conventions and the rules the database enforces The rule pages, starting with Conventions
Views The generated views, and the rule that defines each
Settings and their defaults Settings
Access: the model, helper functions, roles and permissions Access, and the generated row-level security, functions and roles and permissions
Storage: buckets, paths, policies Files and the generated storage page
Error keys The Refusal line of each rule, and the generated error keys (D30)
The domain steps of the migration Plan: data phase
Cutover and rollback Cutover weekend and rollback
Testing the database The testing guide, moving under #55
Day-to-day changes, local stack to staging The database workflow guide, moving under #51

Each environment is its own Supabase project on Postgres 17, in Singapore like v1 (D5, D12). Staging is rebuilt from main every night; production stays empty until the cutover run, and only zuki pushes to it (D11). The table of environments is on Architecture.

Schema Holds Reached through the Data API
public Tables, views, the error_key enum and the RPCs the app calls Yes, under RLS
app Rule and helper functions and trigger functions, mostly security definer with a fixed search_path No. authenticated and service_role have usage on it.
extensions citext (emails) and postgis (GPS positions) No
v1_live, legacy, migration The migration only: v1's foreign tables, the snapshot, the steps. Not built yet; the data phase adds them. No. Dropped after cutover.

supabase/config.toml exposes public and graphql_public only. Never add app or a migration schema to it.

  • Extensions. gen_random_uuid() is built into Postgres 17, so pgcrypto isn't needed. postgres_fdw arrives with the migration. Whether scheduled jobs run on pg_cron or elsewhere is OQ4.
  • anon has nothing in public: no table, sequence or function. Public pages that need data (the queue join page, /bastk/ links already sent on WhatsApp) will go through narrow security-definer RPCs, in M3 and M4.
  • authenticated gets table privileges, and RLS decides the rows. A few tables take more away: nobody writes audit_log, nobody reads document_sequences, app users can't change permissions, and charges is granted column by column (D31). The exact grants are at the end of supabase/migrations/20261006001100_rls.sql.
  • service_role bypasses RLS.
  • Keys (D13): the app uses the publishable key, which is public by design. Jobs, the migration and admin scripts use the secret key, which acts as service_role, only on a server. anon, authenticated and service_role are Postgres role names, never key names.
  • Login is email and password, as in v1. app.handle_new_user() gives each new login a profiles row.
  • Permissions are never read from the token or app_metadata. They come from the access tables on every query, so a role change applies at once. proxy.ts checks each session with getClaims() (D13).
  • Public sign-up is off in the local config.toml. Whether staff are invited on staging and production is OQ2; until it is decided, set it off by hand in each project's Dashboard.
  • Still open: moving v1's password hashes or a reset on first login (OQ1); password policy, session length and the SMTP sender (OQ12). MFA is required for super_admin (D16).
  • The driver app, later: a driver signs up, drivers.profile_id is set, and a membership with a driver role lets RLS show them their own rentals, charges and payments.
  • Timestamps are timestamptz. Business dates use the pool's time zone through app.pool_today(), default Asia/Jakarta (R-CONV-10).
  • Production gets a nightly pg_dump to a bucket the company owns, beside Supabase's own backups; no point-in-time recovery for now (D16).
  • Realtime for the queue TV screen is OQ13.

The order is the rule in apps/docs, then a pgTAP test whose description starts with the rule's ID, then the SQL (D27, D19). The schema changes only through supabase/migrations (D4). Until cutover the files are edited in place (D11); from cutover on, a change is a new file, written in the order add the new column, copy the data and switch the app, then remove the old column in a later release (D32).

A new table or column follows the conventions. In practice:

  • RLS on every table, with its policies in the spec of tools/db/gen_rls.py, never written by hand (below).
  • Uniques per organization, and foreign keys that restrict. Cascade only for pure children such as photos and items.
  • Statuses change only through functions, which write their history and check permissions.
  • File columns use the public.storage_path domain: a bucket-relative path, never a URL or base64 (D14).
  • Money is bigint whole rupiah.
  • A column, not jsonb, for anything filtered, joined, ruled on, summed or hidden. jsonb only for raw outside payloads, snapshots and logs, configuration with a checked shape, and client-defined custom fields once that feature exists. The Backend Engineer checks every new jsonb column against this list in its pull request (D32).
  • An enum when the list only changes with a release; add a value with alter type … add value in a migration. A lookup table when staff extend the list (charge types, lead sources, checklist items, body panels).
  • A new refusal adds its key with alter type public.error_key add value, raises it through app.refuse() or app.deny(), and gets a pgTAP test that asserts it (D10, D30). A key is never removed or reused.

The policies live in one file, supabase/migrations/20261006001100_rls.sql, written by tools/db/gen_rls.py from a table-to-scope spec. Change the spec, run the generator from the repository root, and commit both:

Terminal window
python3 tools/db/gen_rls.py

Every policy has this shape:

-- simplified: the real vehicles_select lists every read permission and adds the partner filter
create policy vehicles_select on public.vehicles for select to authenticated
using (home_pool_id = any ((select app.pools_with_any(array['vehicle:read']))::uuid[]));
  • Always = any ((select app.…(array[…]))::uuid[]). The sub-select makes Postgres run the helper once per query instead of once per row. Without the ::uuid[] cast, Postgres reads it as a subquery and fails with uuid = uuid[].
  • To authenticated only; there are no anon policies.
  • No policy means no access. That is how a write nobody may make is refused, such as deleting money rows, and how an open question is held until its rule exists.
  • The file ends with an assertion that fails if a public table lacks RLS or is missing from the generator's spec.
  • The generator stays the source of the file until cutover. After cutover, a policy change is a new migration file (D11).

The CI database job (TL-M0-18) will fail when the committed file differs from the generator's output. Until it lands, run the generator before you commit.

The script runs inside the v2 database: the same every night on staging, and once for real at cutover (D2). The data phase builds it in tools/migration, one domain step at a time (D17); the steps and what each reconciles are on Plan: data phase, and its runbook steps will be on the backend runbook's data phase page. The calls below are the shape it is built to; their final names come with those steps.

-- once per environment: postgres_fdw to v1 with a read-only user (its password from secrets, never in the repository)
import foreign schema public from server v1 into v1_live;
-- every night, and once at cutover
call migration.snapshot(); -- legacy.* becomes a copy of v1_live.*, from one moment
select * from migration.unmapped_values(); -- must be empty, or the run stops
call migration.run('access'); call migration.run('master_data');
call migration.run('vehicles'); call migration.run('drivers');
call migration.run('rentals'); call migration.run('operations');
call migration.run('money');
select check_name, rows from migration.reconcile() where rows > 0; -- must be empty

A full night, once the rehearsal job exists:

  1. Rebuild v2 staging from main: every migration on an empty database, then seed.sql (D11). This also proves the migrations still apply from nothing.
  2. Take the snapshot, then check for unmapped values.
  3. Run each domain step in its own transaction, logged with its row counts and duration.
  4. Reconcile, copy the new photos, and run the smoke tests.
  5. Report the result to the team.

It runs in GitHub Actions and reports to Slack, or email if Slack costs anything (D36, which closes CR1 and OQ4). It climbs to L2 only after zuki has logged clean L0 and L1 runs; until then zuki runs each night by hand from a runbook step.

  • Every distinct old value goes through value_map. There is no default mapping, so a value nobody mapped stops the run.
  • Old ids map to new uuids through id_map: lid to driver, unit_id and every plate (former plates too) to vehicle, and so on. Rows are inserted with those ids, so a rerun gives the same uuids and old links (/bastk/ links, QR codes) keep resolving.
  • The script runs as the database owner, so RLS doesn't apply and the status guards allow it. It sets app.source to system.
  • Nothing is dropped silently. A row that can't be placed goes to migration.unmatched with a reason, and reconcile counts it.
  • The audit log during the bulk load is OQ5. The suggestion is to turn the audit triggers off for the load and write one "migrated" entry per table.

Each check returns the rows that differ, minus those signed in migration.accepted_differences (the check, the row key, the reason, who signed and when). A clean night is zero unexplained rows on every check (D18).

  • Row counts per table, minus documented drops
  • Unmapped and unmatched values
  • Drivers by stage
  • Active rentals, car by car
  • Status per car
  • Checkpoints due
  • Clearance against v1's background check status
  • Balance per driver against v1's balance of record, to the rupiah; which figure that is is OQ19
  • Payments per day and per bank account
  • Contract and BASTK numbers present and unique
  • Photos expected against photos copied

Ten clean nights in a row are part of the cutover gate (D20, the gate).

  • v1 keeps some images as base64 inside jsonb, and another developer is moving them into v1 Storage. The migration copies each object from v1 Storage into the v2 bucket at its D14 path and stores that path. It keeps a base64 branch until reconcile shows none left in v1 (OQ16).
  • The copy script skips what it has already copied, by source key and checksum. The bulk goes up weeks before cutover; cutover night copies only the difference.

The repository is the list; this page doesn't repeat it.

  • Migrations: supabase/migrations, one file per area, numbered in the order they apply.
  • Tests: supabase/tests/database, pgTAP.
  • Seed: supabase/seed.sql, the sealed E2E organization; never on production.
  • Generators and scripts: tools/db: gen_rls.py, gen_seed.py, the E2E logins, the reference generator behind pnpm docs:reference.
  • The migration: tools/migration, from the data phase.
  • Background only: the delivered M0 (mop-fleet-v2-M0.zip) is read, never copied in (D25); the design canvas boards are history (how we work).

OQ1 password hashes or a reset · OQ2 public sign-up · OQ4 and CR1 what runs the rehearsal · OQ5 the audit log during the load · OQ7 v_driver_clearance · OQ12 password policy and SMTP · OQ13 Realtime · OQ16 v1 after the base64 fix · OQ19 the balance of record · OQ21 who regenerates db-types