Getting Started
Database Drivers
Schema Integrations
Seed Generators
Utilities and Testing
The following files were used as context for generating this wiki page:
The Drizzle Kit CLI Commands provide a bridge between local TypeScript schema definitions and remote database states. Its primary responsibility is schema reconciliation: computing the delta between an expected schema (defined in code) and an actual database schema, then generating the SQL migration statements necessary to align the two.
The system addresses the "state drift" problem common in ORM-driven development. By maintaining a journal of migrations and snapshot files (stored in an out folder), the CLI can reconstruct the history of the database schema. This allows it to perform sophisticated diffing, enabling operations like table renaming, column migrations, and schema evolution, while abstracting away the underlying SQL complexities for various dialects (PostgreSQL, MySQL, SQLite, etc.).
Architecturally, the CLI is composed of a command-parsing layer, a validation layer, and a transformation engine. It uses zod for strict configuration validation and a custom diffing engine (snapshotsDiffer) to produce a list of JsonStatement objects. These statements act as an intermediate representation, which are eventually compiled into final SQL strings through sqlgenerator.
Every CLI command lifecycle begins with configuration normalization. Whether triggered via drizzle.config.ts or CLI arguments, parameters pass through preparation functions (e.g., prepareGenerateConfig, preparePushConfig). These functions enforce invariants, such as ensuring the required schema paths and dialects are present.
The safeRegister mechanism is a load-bearing guard ensuring the environment is prepared before execution. It utilizes an InMemoryMutex to prevent concurrent modification or re-registration of the tsx environment.
// Example of how the CLI wraps execution in a mutex and registration
export const safeRegister = async <T>(fn: () => Promise<T>) => {
return registerMutex.withLock(async () => {
ensureTsxRegistered();
await assertES5();
return fn();
});
};Sources: drizzle-kit/src/cli/commands/utils.ts:95-101
When a schema drift is detected, the CLI often encounters ambiguous state changes (e.g., a table was deleted but a new one was added, potentially indicating a rename). The migrate.ts file defines a suite of "resolvers" that trigger interactive prompts using hanji.
The resolution logic prioritizes specific entity types:
promptNamedWithSchemasConflict: Resolves collisions for entities mapped to schemas (tables, views, enums).promptColumnsConflicts: Handles column-specific renames within a table.The mechanism uses a do-while loop to iterate through unresolved created items and maps them against missing items. If a user selects an item as a rename, the system tracks the mapping, ensuring the diffing engine accounts for the continuity of the entity.
Sources: drizzle-kit/src/cli/commands/migrate.ts:1066-1131
The core engine resides in snapshotsDiffer.ts. It takes two "squashed" schema objects (json1 as prev and json2 as cur) and computes the difference. The process is dialect-specific, utilizing applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, etc.
The mechanism follows a strict order of operations:
JsonStatement types.Note
The snapshotsDiffer utilizes a copy() utility before modifying the state during diffing. This ensures the original snapshots remain immutable while the intermediate "patched" snapshots are prepared for the SQL generation step.
Sources: drizzle-kit/src/snapshotsDiffer.ts:559-603
Once the JsonStatement array is finalized, the system converts these into executable SQL. The writeResult function is the final step in the migration generation pipeline. It generates the _snapshot.json to be stored in the meta folder and creates the .sql migration file.
The ordering of the generated SQL is critical. The system uses a specific precedence order to prevent constraint violations:
Sources: drizzle-kit/src/cli/commands/migrate.ts:1356-1458
For non-migration-based syncing (the push command), pgPushUtils.ts provides a safety-check mechanism. Before executing dangerous SQL operations (like dropping a table or column with data), it queries the database to count affected rows.
If data loss is detected, the utility sets shouldAskForApprove = true. This prevents accidental destruction of production data.
Sources: drizzle-kit/src/cli/commands/pgPushUtils.ts:59-269
The CLI uses the @drizzle-team/brocli library to define its interface. Each command follows a consistent transformation and handler pattern.
Sources: drizzle-kit/src/cli/schema.ts:50-481