Neon Migrations
Better Auth schema generation, migrations, the quickback canary rehearsal on a Neon branch, and pg-core for raw Drizzle interop tables on Neon.
Generate and apply migrations for a Neon project, including the Better Auth tables, rehearsing a migration on a Neon branch with quickback canary <target> --required, and the Drizzle import raw interop tables must use. Start at Neon for configuration.
Better Auth schema generation
src/auth/schema.ts is a compiler-owned artifact derived with the Better Auth
CLI during quickback build. The generated build script is deliberately
read-only with respect to generated source:
quickback build # regenerates src/auth/schema.ts and the project output
npm run build # runs tsc only; does not rewrite generated filesFor schema-generator diagnostics, the explicit auth:schema command expands
to:
npx better-auth generate --config ./src/lib/auth.ts --output ./src/auth/schema.ts --yes \
&& node scripts/quickback-qualify-auth-schema.mjsThe better-auth executable comes from the auth devDependency in the
generated package.json — that's the Better Auth CLI package (the
better-auth runtime package ships no bin).
The qualifier script adjusts the CLI output for Postgres schema placement.
auth:schema produces the intermediate Better Auth output and may remove
Quickback's generated-file envelope. Do not commit that intermediate file;
rerun quickback build to restore the canonical project bytes. Don't
hand-edit src/auth/schema.ts.
Recompiling also replaces previously generated package.json lifecycle
commands with their current definitions. An existing project whose build
script still runs auth:schema therefore converges to the TypeScript-only
build, while unrelated custom scripts remain intact.
Better Auth's tables stay vanilla Better Auth
Better Auth's own API is the authorization gate for its tables. Quickback does
not reimplement that gate in SQL — no policy re-derives membership, checks a
role, or splits by verb. What the compiler adds is the same backstop every
feature table gets, so a leaked DATABASE_URL or a mis-scoped handle cannot
read another user's or another organization's auth rows:
| Policy | Kind | On which tables |
|---|---|---|
<table>_deny_anon | RESTRICTIVE FOR ALL | Every managed table |
quickback_service_role_all | permissive FOR ALL | Every table in the auth schema, created by the role bootstrap |
<table>_scope | permissive FOR SELECT | Only tables with a caller-readable scope column |
Reads are tenant/self scoped; writes go through Better Auth only. The scope
policy is FOR SELECT with a USING clause and no WITH CHECK, so the caller
lane can read these rows and change none of them — a handle cannot set its own
member.role. Better Auth's adapter always stamps the service marker, so every
write it makes runs on the service lane. The predicate:
| Table | Scope |
|---|---|
user | id = auth.user_id() |
session, account, passkey | user_id = auth.user_id() |
apikey | reference_id = auth.user_id() — Better Auth's apikey table has no user_id |
organization | id = public.get_active_org_id() |
member, invitation, team | organization_id = public.get_active_org_id() |
team_member | team_id = public.get_active_team_id() |
Everything else is service-only — deny-anon plus the bootstrap lane is the
entire policy set, and no caller-scoped handle can read a row either: verification,
jwks, the Better Auth rate-limit counters, device_code, the
oauth_* provider tables, the agent_* / approval_request agent-auth
tables, two_factor (the twoFactor plugin's TOTP secrets and backup codes),
and wallet_address (siwe). Better Auth's own adapter always stamps the service marker, so its
reads and writes never consult any of this; the policies exist for the handles
that are not Better Auth.
A table with no obvious scope column is service-only by construction. The compiler will not invent a predicate for one — it fails closed.
Migrations
Neon uses PostgreSQL migrations, distinct from D1's SQLite migrations. One Drizzle journal covers auth tables, feature tables, indexes, FK/cascade semantics, and the RLS layer:
quickback build # generates migrations under quickback/drizzle/
npm run db:migrate # applies schema AND the RLS layer, in orderThe RLS layer (helper functions, policies, triggers) rides the same
journaled migration set as your schema: the compiler appends a
content-addressed <idx>_quickback_rls_<hash> migration, so one
db:migrate applies everything in order. The RLS migration is idempotent
(DROP POLICY IF EXISTS + re-create) and only a changed security config
appends a new entry — recompiles with unchanged security append nothing. No
manual SQL application step exists.
Run the first db:migrate with the database owner credential (Neon's
neondb_owner); later runs can use quickback_admin through
DATABASE_MIGRATION_URL. The three Postgres roles and which credential each
run needs are on Neon Environments.
The default index set
Indexes are Drizzle's, not the security migration's: the compiler writes the
default set (tenant composite, FK columns, filtered columns, view-sortable
columns) into the schema source, so drizzle-kit generates and diffs them under
<table>_<column>_idx names. See
The default index set for the rules and
the ...q.indexes(t) placeholder.
Older projects also carry idx_<table>_<column> copies the security migration
used to create. Those are dropped in the security migration's trailing
"retired indexes" section, which the journal runs after the schema migration
that created the replacements. Only idx_* names are dropped.
Quickback also dependency-orders Drizzle's standalone constraint replacements.
When a composite unique or primary key and its consuming foreign key are both
replaced, the generated migration drops the dependent foreign key first, drops
and recreates the referenced key, then recreates the foreign key. This avoids
Postgres 2BP01 dependency failures without CASCADE and without requiring a
hand-edited migration. Already-correct migrations remain byte-identical.
Cross-schema and composite relationships that cannot live in one generated
Drizzle schema may be declared with
compiler.migrations.foreignKeys.
Quickback appends them to that same content-addressed migration after the
schema tables and target unique keys exist. Declarations are deterministic and
replay-safe: an existing constraint must match exactly, while existing orphan
rows fail the VALIDATE CONSTRAINT step. Foreign keys enforce integrity only;
keep authorization and business state transitions in the API action layer.
Required migration canaries
quickback canary dev --required
quickback canary prod --required --applyCanary takes the logical target key and reads its branch from top-level
environments or legacy providers.database.environments. Declaring both
placements or naming an unknown target is an error. It only accepts the
neon provider: another Postgres provider cannot use Neon APIs even when
NEON_API_KEY and NEON_PROJECT_ID are set.
Set NEON_API_KEY and NEON_PROJECT_ID (or neon.projectId). --required
fails when credentials or branch mapping are missing; without it, an
unconfigured Neon canary deliberately skips. Use --required for CI gates.
Both rehearsal and parent apply request connection strings for the same
neon.database and neon.role. These select the migration database and
actor; the runtime quickback role is not a suitable routine migration actor.
The existing defaults remain neondb and neondb_owner. Set
neon.role: "quickback_admin" for routine migrations after bootstrap; first
bootstrap and security/RLS migrations still require the setup-owner capability
described in Upgrading an existing database. Connection strings go to the Drizzle subprocess environment.
The command fingerprints the entire local quickback/drizzle/ inventory
before rehearsal, rechecks it after rehearsal, and checks again immediately
before parent apply. A changed journal, SQL file or other migration-state file
aborts parent apply and attempts canary cleanup. Keep migration files unchanged
throughout the command; this check does not freeze the working directory while
Drizzle runs. Cleanup failure returns a nonzero exit status even after successful
verification. --apply migrates the parent; it does not deploy the Worker.
Raw Drizzle interop tables must use pg-core
Internal child tables authored as raw Drizzle (a table file with no
export default defineTable(...)) are not dialect-translated by the
compiler — on Neon they must be written with pgTable from
drizzle-orm/pg-core. A sqliteTable interop source on a Postgres target
is a compile-time error: the mechanical sqlite→pg rewrite would leave
SQLite-shaped audit columns (text ISO strings instead of timestamptz,
which the RLS audit triggers stamp) and SQLite-only column options in the
Postgres schema.
// quickback/features/interviews/interview_scores.ts
// @quickback-internal — child table, no CRUD routes
import { integer, pgTable, text, timestamp } from 'drizzle-orm/pg-core';
export const interviewScores = pgTable('interview_scores', {
id: text('id').primaryKey(),
interviewId: text('interview_id').notNull(),
rating: integer('rating').notNull(),
// ── quickback:audit (compiler-managed — edits are validated, not merged) ──
createdAt: timestamp('created_at', { withTimezone: true, precision: 3 }).notNull().defaultNow(),
modifiedAt: timestamp('modified_at', { withTimezone: true, precision: 3 }).notNull().defaultNow().$onUpdate(() => new Date()),
createdBy: text('created_by'),
modifiedBy: text('modified_by'),
deletedAt: timestamp('deleted_at', { withTimezone: true, precision: 3 }),
deletedBy: text('deleted_by'),
});Interop tables are not exempt from the visible managed-column rule. The
validator runs over every table file in a feature directory
(compiler.ts:1210-1230 iterates feature.tables, which
raw-input/organize.ts:394 populates regardless of whether the file has a
resource config), so the six columns must be declared literally in Drizzle
form — ...q.audit() is a q-DSL spread and is not expanded in raw Drizzle
source. A child table with no crud config soft-deletes by default, so
deletedAt / deletedBy are required too.
Tables with defineTable(...) are unaffected — existing sqliteTable
sources with a resource config still compile to the Postgres dialect
automatically. Managed audit timestamps declared in the SQLite shape
(createdAt / modifiedAt / deletedAt as text) are emitted as
timestamptz(3), like every other Postgres table — the audit wrapper and the RLS
audit triggers both stamp timestamps, not strings. API responses carry the same
ISO-8601 string as on D1.
Managed audit timestamps are stored at millisecond precision (timestamptz(3)),
and the audit triggers stamp date_trunc('milliseconds', now()), so keyset
cursors page them exactly. Projects last compiled by 0.69.0 or earlier get a
type-change migration on the next compile that rounds existing values — see
How auto-injection works.