---
title: "CLI Commands"
description: "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 betwee..."
last_updated: "2026-07-02T09:35:18.614163+00:00"
canonical_url: "https://www.doc0.app/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/drizzle-kit/cli-commands"
---

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [drizzle-kit/src/cli/commands/migrate.ts](https://github.com/blade47/drizzle-orm/blob/main/drizzle-kit/src/cli/commands/migrate.ts)
- [drizzle-kit/src/cli/commands/utils.ts](https://github.com/blade47/drizzle-orm/blob/main/drizzle-kit/src/cli/commands/utils.ts)
- [drizzle-kit/src/cli/commands/pgPushUtils.ts](https://github.com/blade47/drizzle-orm/blob/main/drizzle-kit/src/cli/commands/pgPushUtils.ts)
- [drizzle-kit/src/cli/schema.ts](https://github.com/blade47/drizzle-orm/blob/main/drizzle-kit/src/cli/schema.ts)
- [drizzle-kit/src/snapshotsDiffer.ts](https://github.com/blade47/drizzle-orm/blob/main/drizzle-kit/src/snapshotsDiffer.ts)
</details>

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`.

## Initialization and Configuration Lifecycle

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.

```typescript
// 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](https://github.com/blade47/drizzle-orm/blob/main/drizzle-kit/src/cli/commands/utils.ts#L95-L101)

## Conflict Resolution and User Interaction

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](https://github.com/blade47/drizzle-orm/blob/main/drizzle-kit/src/cli/commands/migrate.ts#L1066-L1131)

## Snapshot Diffing Mechanism

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:
1. **Schema Diffing:** Identify additions, deletions, and renames at the schema level.
2. **Entity Patches:** Iteratively resolve conflicts for enums, sequences, and roles.
3. **Table Diffing:** Perform deep comparisons of columns, indexes, and constraints.
4. **Statement Generation:** The results of these diffs are translated into an array of `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](https://github.com/blade47/drizzle-orm/blob/main/drizzle-kit/src/snapshotsDiffer.ts#L559-L603)

## SQL Migration Generation

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:
- Drop indexes → Drop/Alter constraints → Alter columns → Add/Drop tables.

```mermaid
flowchart TD
    A["Prepare Migration Folder"] --> B["Compute Snapshot Diff"]
    B --> C{"Conflict Resolved?"}
    C -->|Yes| D["Map Entity Changes"]
    D --> E["Generate JsonStatements"]
    E --> F["Compile SQL from Statements"]
    F --> G["Write .sql file & _journal.json"]
```
Sources: [drizzle-kit/src/cli/commands/migrate.ts:1356-1458](https://github.com/blade47/drizzle-orm/blob/main/drizzle-kit/src/cli/commands/migrate.ts#L1356-L1458)

## Database Push Utilities

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.

| Statement Type | Check Performed | Action Triggered |
| :--- | :--- | :--- |
| `drop_table` | `SELECT count(*)` | Trigger prompt if count > 0 |
| `alter_table_drop_column` | `SELECT count(*)` | Trigger prompt if count > 0 |
| `create_unique_constraint` | `SELECT count(*)` | Offer truncation option if count > 0 |

Sources: [drizzle-kit/src/cli/commands/pgPushUtils.ts:59-269](https://github.com/blade47/drizzle-orm/blob/main/drizzle-kit/src/cli/commands/pgPushUtils.ts#L59-L269)

## Command Structure

The CLI uses the `@drizzle-team/brocli` library to define its interface. Each command follows a consistent transformation and handler pattern.

| Command | Entry point | Purpose |
| :--- | :--- | :--- |
| `generate` | `schema.ts:generate` | Creates migration SQL from schema changes |
| `migrate` | `schema.ts:migrate` | Applies local SQL migrations to the remote DB |
| `push` | `schema.ts:push` | Directly syncs schema changes to the remote DB |
| `introspect` | `schema.ts:pull` | Pulls remote schema into local code files |

Sources: [drizzle-kit/src/cli/schema.ts:50-481](https://github.com/blade47/drizzle-orm/blob/main/drizzle-kit/src/cli/schema.ts#L50-L481)

## Related

- [Kit Overview](https://www.doc0.app/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/technical/drizzle-kit/kit-overview)


## Sitemap

See the full [sitemap](https://www.doc0.app/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/llms.txt) for all pages in this wiki.
