Skip to content
VibORM
Esc
↑↓navigate↵open⌘Jpreview
On this page

Push

Synchronize models directly with the live database without creating migration history

When to Use Push

  • Development environment - Rapid iteration without migration history
  • Prototyping - Quick schema experiments
  • CI test databases - Fresh schema for each test run
  • Non-versioned workflows - When you don’t need migration history

Basic Usage

# Push schema changes to database
npx viborm push
import { createMigrationClient } from "viborm/migrations";
import { client } from "./client";

const migrations = createMigrationClient(client);

const result = await migrations.push();

if (result.outcome === "applied") {
  console.log(`Applied ${result.operations.length} changes`);
}

Dry Run Mode

Preview changes without applying them:

# Preview changes without applying
npx viborm push --dry-run
const result = await migrations.push({ dryRun: true });

console.log("Would apply:");
for (const statement of result.statements) {
  console.log(statement.sql);
}
// result.outcome === "planned" | "noop"

Defaults on existing rows

Supported literal list, JSON, bigint and Date/DateTime defaults become database defaults, so adding their required columns can backfill existing rows. Temporal literals use the same physical representation as model writes. A function .default(() => value) or an application-only generator runs on new model writes; it does not fill stored rows. Push refuses to add such a required column to a populated table before executing migration effects. Use a reviewed manual migration to add it as nullable, fill the values explicitly, and then make it required. Generated migration preconditions require an empty table when a required added column has no physical default.

Push keeps no history, so the rows are its record of polymorphic stored values. Before executing migration effects it reads each to-one polymorphic slot once (LIMIT 1) for a stored discriminator the desired schema no longer declares, whether the value changed or its variant was removed. If one exists, push refuses with V11010, naming the slot and the value, as generation does for the same change. A value that no row stores, and a NULL slot, never block. Rewrite the stored values in a reviewed manual migration first; see schema evolution.

Selected generated columns, unsupported native indexes, SQLite custom CHECK constraints and mapped view collisions refuse synchronization when their physical semantics cannot be represented. Manage those tables outside the authenticated migrations.tables selection until a faithful declaration/manual workflow exists; an unrelated excluded object does not block the selected tables.

Resolving Changes

When push detects destructive changes (dropping tables/columns), ambiguous changes (potential renames), or enum value removals, it calls the resolve callback for each one.

# Configure migrations.resolve in viborm.config.ts for rename/enum decisions
npx viborm push --dry-run
# Review the plan before authorizing destructive execution
npx viborm push --accept-data-loss
const preview = await migrations.push({
  dryRun: true,
  resolve: async (change) => {
    console.log(change.description);

    if (change.type === "destructive") {
      // Destructive changes have: proceed(), reject()
      return confirm("Accept data loss?") ? change.proceed() : change.reject();
    }

    if (change.type === "ambiguous") {
      // Ambiguous changes have: rename(), addAndDrop(), reject()
      if (change.operation === "renameColumn") return change.rename();
      // Rename a table only by its named pair: the dropped table may belong
      // to another application sharing this database.
      if (change.oldName === "users" && change.newName === "accounts") {
        return change.rename();
      }
      return change.reject();
    }

    if (change.type === "enumValueRemoval") {
      // Enum value removals have: mapValues(), reject()
      return change.mapValues({
        'OLD_VALUE': 'NEW_VALUE',
        'DEPRECATED': null,  // Set to NULL
      });
    }
  },
});

// The callback's decisions are closed into this exact preview.
await migrations.push({ consent: preview.consent });

ResolveChange Interface

Each change type has specific methods available:

// Destructive changes (dropTable, dropColumn, alterColumn, required addColumn)
interface DestructiveResolveChange {
  type: "destructive";
  operation: "dropTable" | "dropColumn" | "alterColumn" | "addColumn";
  table: string;
  column?: string;
  description: string;

  proceed(): ResolveResult;  // Accept the data loss
  reject(): ResolveResult;   // Abort the operation
}

// Ambiguous changes (renameTable, renameColumn)
interface AmbiguousResolveChange {
  type: "ambiguous";
  operation: "renameTable" | "renameColumn";
  table: string;
  column?: string;
  oldName?: string;
  newName?: string;
  oldType?: string;
  newType?: string;
  description: string;

  rename(): ResolveResult;      // Treat as rename (preserves data)
  addAndDrop(): ResolveResult;  // Treat as separate add + drop (data loss)
  reject(): ResolveResult;      // Abort the operation
}

// Enum value removal changes (per-column)
interface EnumValueRemovalChange {
  type: "enumValueRemoval";
  enumName: string;
  tableName: string;            // Table containing the column
  columnName: string;           // Column using the enum
  isNullable: boolean;          // Whether the column is nullable
  removedValues: string[];      // Values being removed
  availableValues: string[];    // Values to map to
  description: string;

  mapValues(replacements: Record<string, string | null>): ResolveResult;
  useNull(): ResolveResult;     // Set all removed values to NULL (nullable columns only)
  reject(): ResolveResult;      // Abort the operation
}

Built-in Resolvers

The public package exports three reusable policies. Use them during preview; destructive decisions still require the preview’s exact consent before any effect:

import {
  lenientResolver,
  rejectAllResolver,
} from "viborm/migrations";

const preview = await migrations.push({
  dryRun: true,
  resolve: lenientResolver,
});

await migrations.push({ consent: preview.consent });

// In CI, this policy refuses as soon as a decision is required.
const ciPushOptions = {
  dryRun: true,
  resolve: rejectAllResolver,
} as const;
Resolver Destructive Ambiguous Removed enum values
rejectAllResolver Reject Reject Reject
lenientResolver Proceed Rename columns; leave table pairs undecided Set to NULL
addDropResolver Proceed Add and drop Set to NULL

The last two policies are intentionally data-destructive. Their enum policy is valid only when every affected column is nullable; otherwise the migration is refused. Prefer an explicit callback when the mapping depends on the column or the old value.

Push cannot tell whether a live table it does not declare was ever yours, so a dropped table paired with a new model table is never renamed by policy: lenientResolver leaves the pair undecided and the plan refuses. Rename a table with a callback that names both tables, as in the example above. Every table rename is reported as destructive, so it also needs the preview’s exact consent. On a database shared with another application, set migrations.tables so push never sees that application’s tables.

Managed tables and CLI decisions

migrations.tables selects exact physical table names, including junction tables. An omitted list manages the whole namespace. An explicit list is recorded in the estate identity, and a migration client’s list may only grow from it; include both old and new names before publishing a rename. Migration history commands select what the estate manages, never a name only the client lists, so a table you list before adopting it stays yours: see Adopt an Existing Table. A foreign key or PostgreSQL enum shared across the selected boundary is refused.

import { defineConfig } from "viborm/config";
import { client } from "./src/db";

export default defineConfig({
  client,
  migrations: {
    tables: ["users", "posts", "users_posts"],
    resolve: async (change) => {
      // Rename columns. A table pair is refused until you name it here.
      if (change.type === "ambiguous" && change.operation === "renameColumn") {
        return change.rename();
      }
      return change.reject();
    },
  },
});

The same callback resolves migrate generate decisions. A missing decision refuses the plan. Nullable enum removals still require mapValues() or useNull() explicitly. The CLI confirms the completed plan; it does not infer per-column rename or enum mappings. Non-interactive additive plans run without a prompt. A table rename is never additive: it needs --accept-data-loss like any destructive plan. --yes alone never authorizes a destructive plan.

The programmatic live client accepts the same scope without a storage writer: createMigrationClient(client, { tables: ["users", "posts"] }). For file-backed SQLite drivers, the CLI warns when PRAGMA database_list reports an in-memory main database.

Force Reset

Reset the database before pushing (drops all tables and pushes fresh schema):

# Drop all tables and push fresh schema
npx viborm push --force-reset
const preview = await migrations.push({
  dryRun: true,
  forceReset: true,
});

// Review preview.target, preview.operations, and preview.statements first.
await migrations.push({ consent: preview.consent });

CLI Options

Option Description
--dry-run Preview SQL without executing
--force-reset Plan a rebuild from empty; requires exact preview consent
-y, --yes Skip the confirmation prompt for a non-destructive preview
--accept-data-loss Explicitly authorize destructive execution of the exact displayed preview
--json Print machine-readable preview or result JSON; destructive apply requires --accept-data-loss
--config <path> Path to config file

API Options

Planning and consent are intentionally different calls. A consent call cannot also change forceReset, validation, or resolution decisions:

interface PushPlanningOptions {
  forceReset?: boolean;
  skipValidation?: boolean;
  resolve?: ResolveCallback;
}

type PushOptions =
  | (PushPlanningOptions & { dryRun: true })
  | (PushPlanningOptions & {
      dryRun?: false;
      consent?: never;
    })
  | {
      consent: PushConsent;
      dryRun?: false;
    };
Option Type Default Description
forceReset boolean false Drop managed tables, then rebuild from empty. Requires exact preview consent.
dryRun boolean false Preview SQL without executing
skipValidation boolean false Skip schema validation before pushing. Validation catches definition errors that would otherwise corrupt data silently — only skip it when deliberately pushing a shape the validator flags.
resolve ResolveCallback - Callback for resolving destructive or ambiguous changes.
consent PushConsent - The only option in the apply-after-preview arm. Required for destructive and force-reset work.

A safe non-destructive plan may execute directly. A destructive or force-reset plan always requires a dry preview followed by its exact consent. The second call reacquires the target lock, replans from the live catalog, and refuses if the target or plan changed.

The consent is not tied to a client instance: any client may confirm it, for example a second request after the first was evicted. On Postgres and MySQL it is bound to the database and namespace name plus the plan hash; on SQLite and D1, only to the plan hash. The plan hash covers the live schema fingerprint, the desired schema fingerprint and the exact statements. A changed live schema or plan refuses it with V11018. A consent previewed against one database therefore also confirms on another database with the same name (on SQLite and D1, any database) whose live schema is identical, and it runs exactly the reviewed statements there. Do not carry consents between environments.

API Result

interface PushPreview {
  outcome: "planned" | "noop";
  target: PushTargetIdentity;
  planHash: string;
  schemaHash: string;
  fingerprint: string;
  destructive: boolean;
  operations: readonly PushOperation[];
  statements: readonly PushStatementPreview[];
  consent: PushConsent;
}

interface PushApplyResult {
  outcome: "applied" | "noop";
  target: PushTargetIdentity;
  planHash: string;
  operations: readonly PushOperation[];
  statements: readonly PushStatementPreview[];
  attestation: {
    pathHash: string;
    planHash: string;
    schemaHash: string;
    fingerprint: string;
  };
}
Property Type Description
outcome "planned" | "noop" | "applied" Whether the plan would change the database, or did
operations PushOperation[] Review labels for the accepted plan
statements PushStatementPreview[] Structured SQL plus typed parameters
schemaHash, fingerprint string Desired-schema identity and preview-time live fingerprint
consent PushConsent Inert preview token; required to apply a destructive or force-reset plan
attestation PushAttestation Apply-time path, plan, schema, and final live-fingerprint proof

When one push removes several tables, a table is always dropped before the tables it references, whatever their names. The order comes from the foreign keys the database holds, so the preview, the consent and the executed program show the same order. Generated migrations use the same order, and their rollback recreates the removed tables before the keys between them: on SQLite, referenced tables first; on PostgreSQL and MySQL, every table first and then each key once.

PostgreSQL and MySQL drop every affected foreign key before the first table. SQLite keeps foreign keys inside each table and enforces them while a table is dropped: dropping a table deletes its rows first and applies each key’s onDelete action. Tables that reference each other are still removed when an action allows an order — a setNull key clears its column, and a cascade key deletes the referencing rows. Tables no order can drop — a cycle of restrict or noAction keys, a cycle whose cascade reaches rows a restrict key still guards, or a table whose restrict key references itself — are refused before any statement runs, naming each blocked table and the key that refuses it. The decision is made from the schema alone: no order that is safe for every row set can be established from it, so such a plan is refused whether or not the tables hold rows today (an empty restrict cycle would drop, and is refused all the same). Remove one of those relations, or change its action to setNull, in a separate push first, then remove the tables.

Enum Value Removal

When removing enum values, you must specify what to do with existing data. Each column using the enum is resolved separately, allowing different mappings per column:

const preview = await migrations.push({
  dryRun: true,
  resolve: async (change) => {
    if (change.type === "enumValueRemoval") {
      // Each call is for a specific column
      console.log(`Column: ${change.tableName}.${change.columnName}`);
      console.log(`Removing: ${change.removedValues.join(", ")}`);
      console.log(`Available: ${change.availableValues.join(", ")}`);

      // For nullable columns, can use useNull() for convenience
      if (change.isNullable) {
        return change.useNull();
      }

      // Map removed values to new values
      return change.mapValues({
        'PENDING': 'INACTIVE',    // Map to another value
        'OLD_STATUS': null,       // Set to NULL (only if column is nullable)
      });
    }

    // Handle other change types...
    if (change.type === "destructive") return change.proceed();
    if (change.type === "ambiguous" && change.operation === "renameColumn") {
      return change.rename();
    }
    return change.reject();
  },
});

await migrations.push({ consent: preview.consent });

See the ResolveChange interface above for the full EnumValueRemovalChange contract.

Next Steps

Was this page helpful?