export { f as PostgresDoClient, P as PostgresDoDatabase, a as PostgresDoDriverOptions, c as PostgresDoPreparedQuery, h as PostgresDoQueryResultHKT, b as PostgresDoSession, g as PostgresDoSessionOptions, e as PostgresDoTransaction, d as drizzle, m as migrate } from '../migrator-JE7tseIA.cjs'; import { S as Sql } from '../types-YTdPe6Qz.cjs'; import 'drizzle-orm/migrator'; import 'drizzle-orm/entity'; import 'drizzle-orm/logger'; import 'drizzle-orm/pg-core/db'; import 'drizzle-orm/utils'; import 'drizzle-orm/pg-core/dialect'; import 'drizzle-orm/pg-core'; import 'drizzle-orm/pg-core/query-builders/select.types'; import 'drizzle-orm/pg-core/session'; import 'drizzle-orm/relations'; import 'drizzle-orm/sql/sql'; import '@dotdo/postgres-shared/errors'; /** * Drizzle Migrations Integration for postgres.do * * This module provides seamless integration between Drizzle Kit's migration * system and postgres.do's multi-database Durable Object model. * * Key Features: * - Convert Drizzle migrations to postgres.do format * - Auto-run migrations on DO initialization * - Support drizzle-kit generate workflow * - Sync Drizzle journal with DO version tracking * * @example * ```typescript * import { createDrizzleMigrator } from 'postgres.do/drizzle' * import bundledMigrations from './drizzle-bundle' * * const migrator = createDrizzleMigrator({ * migrations: bundledMigrations, * autoRun: true, * }) * * // In your DO * class PostgresDO { * async fetch(request: Request) { * await migrator.ensureMigrated(this.pglite) * // Handle request... * } * } * ``` */ /** * Drizzle journal entry format */ interface DrizzleJournalEntry { idx: number; version: string; when: number; tag: string; breakpoints?: boolean; } /** * Drizzle migrations journal format */ interface DrizzleJournal { version: string; dialect: 'postgresql' | 'mysql' | 'sqlite'; entries: DrizzleJournalEntry[]; } /** * Migration record for tracking applied migrations */ interface DrizzleMigrationRecord { /** Migration hash/ID */ hash: string; /** Timestamp when applied */ created_at: number; } /** * Bundled Drizzle migrations format for Cloudflare Workers * * Since file system access is not available in Workers, migrations * need to be bundled at build time. */ interface BundledDrizzleMigrations { /** The migrations journal */ journal: DrizzleJournal; /** SQL content keyed by folder name (e.g., '0000_init') */ migrations: Record; } /** * Migration result */ interface DrizzleMigrationResult { /** Whether all migrations succeeded */ success: boolean; /** Number of migrations applied */ appliedCount: number; /** Number of migrations skipped (already applied) */ skippedCount: number; /** Total duration in milliseconds */ durationMs: number; /** Applied migration hashes */ applied: string[]; /** Error if failed */ error?: string; } /** * Progress event for migrations */ interface DrizzleMigrationProgressEvent { /** Current migration being processed */ migration: { hash: string; tag: string; sql: string; }; /** Index of current migration */ index: number; /** Total migrations to process */ total: number; /** Phase of migration */ phase: 'starting' | 'executing' | 'completed' | 'failed' | 'skipped'; /** Duration in ms (on completion) */ durationMs?: number; /** Error message if failed */ error?: string; } /** * Configuration for Drizzle migrator */ interface DrizzleMigratorConfig { /** * Bundled migrations from drizzle-kit generate */ migrations: BundledDrizzleMigrations; /** * Name of the migrations tracking table * Default: '__drizzle_migrations' */ tableName?: string; /** * Whether to run migrations automatically on ensureMigrated() * Default: true */ autoRun?: boolean; /** * Validate migration checksums * Default: true */ checksumValidation?: boolean; /** * Callback for migration progress */ onProgress?: (event: DrizzleMigrationProgressEvent) => void; /** * Callback when all migrations complete */ onComplete?: (result: DrizzleMigrationResult) => void; /** * Callback on migration error */ onError?: (error: Error) => void; /** * Enable debug logging * Default: false */ debug?: boolean; } /** * Query executor interface matching postgres.do and PGLite */ interface QueryExecutor$2 { query(sql: string, params?: unknown[]): Promise<{ rows: T[]; }>; } /** * Migrator state */ type DrizzleMigratorState = 'idle' | 'running' | 'completed' | 'failed'; /** * Drizzle Migrator for postgres.do * * Provides automatic migration management for Drizzle ORM schemas * in postgres.do's Durable Object environment. */ declare class DrizzleMigrator { private config; private migrations; private onProgress?; private onComplete?; private onError?; private state; private migrationPromise; private lastResult; private lastError; constructor(config: DrizzleMigratorConfig); /** * Log debug message */ private log; /** * Get current state */ getState(): DrizzleMigratorState; /** * Get last migration result */ getLastResult(): DrizzleMigrationResult | null; /** * Get last error */ getLastError(): Error | null; /** * Get the ordered list of migrations to apply */ getMigrations(): Array<{ hash: string; tag: string; sql: string; idx: number; }>; /** * Initialize the migrations table */ private initializeTable; /** * Get list of already applied migrations */ private getAppliedMigrations; /** * Record a migration as applied */ private recordMigration; /** * Ensure migrations are applied * * Safe to call multiple times - will only run pending migrations. */ ensureMigrated(executor: QueryExecutor$2): Promise; /** * Run all pending migrations */ private runMigrations; /** * Force re-run of migrations * * Resets state and runs ensureMigrated again. * Already applied migrations will be skipped. */ forceMigrate(executor: QueryExecutor$2): Promise; /** * Get the current migration status */ getStatus(executor: QueryExecutor$2): Promise<{ initialized: boolean; appliedCount: number; pendingCount: number; appliedMigrations: string[]; pendingMigrations: string[]; }>; /** * Check if there are pending migrations */ needsMigration(executor: QueryExecutor$2): Promise; } /** * Create a Drizzle migrator instance * * @example * ```typescript * import { createDrizzleMigrator } from 'postgres.do/drizzle' * import bundledMigrations from './drizzle-bundle' * * const migrator = createDrizzleMigrator({ * migrations: bundledMigrations, * autoRun: true, * onProgress: (event) => console.log(`${event.phase}: ${event.migration.tag}`), * }) * ``` */ declare function createDrizzleMigrator(config: DrizzleMigratorConfig): DrizzleMigrator; /** * Parse a Drizzle migrations journal file */ declare function parseDrizzleJournal(content: string): DrizzleJournal; /** * Convert Drizzle migrations to bundled format * * This is useful for build-time bundling in a Node.js environment. * * @example * ```typescript * // In your build script * import { bundleDrizzleMigrations } from 'postgres.do/drizzle' * import fs from 'fs' * import path from 'path' * * const migrationsDir = './drizzle' * const bundled = bundleDrizzleMigrations(migrationsDir) * * fs.writeFileSync( * './src/drizzle-bundle.json', * JSON.stringify(bundled, null, 2) * ) * ``` */ declare function bundleDrizzleMigrations(journal: DrizzleJournal, sqlFiles: Record): BundledDrizzleMigrations; /** * Migration Bridge between Drizzle and postgres.do * * This module provides integration between Drizzle Kit's migration system * and postgres.do's migration infrastructure. It enables: * * 1. Converting Drizzle migrations to postgres.do format * 2. Syncing Drizzle journal with DO version tracking * 3. Supporting both migration systems simultaneously * * @example * ```typescript * import { createMigrationBridge } from 'postgres.do/drizzle' * import bundledMigrations from './drizzle-bundle' * * // Create a bridge that converts Drizzle migrations to postgres.do format * const bridge = createMigrationBridge(bundledMigrations) * * // Get migrations in postgres.do format * const migrations = bridge.getMigrations() * * // Or use with AutoMigrator * const migrator = createAutoMigrator({ * migrations: bridge.getMigrations(), * }) * ``` */ /** * postgres.do migration format */ interface PostgresDoMigration { /** Unique migration identifier */ id: string; /** Human-readable name */ name: string; /** Version number for ordering */ version: number; /** Forward migration SQL */ up: string; /** Rollback SQL (optional) */ down?: string; /** Whether this migration is reversible */ isReversible?: boolean; /** Tags for categorization */ tags?: string[]; /** Whether to run in a transaction */ transactional?: boolean; /** Original Drizzle metadata */ drizzle?: { idx: number; hash: string; tag: string; when: number; }; } /** * Migration bridge configuration */ interface MigrationBridgeConfig { /** * Bundled Drizzle migrations */ migrations: BundledDrizzleMigrations; /** * Optional down migrations keyed by migration tag * Drizzle doesn't generate down migrations by default, * but you can provide them manually. */ downMigrations?: Record | undefined; /** * Prefix for migration IDs * Default: empty (uses Drizzle's NNNN_tag format) */ idPrefix?: string | undefined; /** * Version offset for postgres.do versioning * Default: 0 */ versionOffset?: number | undefined; } /** * Migration Bridge * * Converts Drizzle migrations to postgres.do format, enabling * interoperability between both migration systems. */ declare class MigrationBridge { private config; private migrations; private downMigrations; private cachedMigrations; constructor(config: MigrationBridgeConfig); /** * Get all migrations in postgres.do format */ getMigrations(): PostgresDoMigration[]; /** * Get a specific migration by ID */ getMigration(id: string): PostgresDoMigration | undefined; /** * Get a migration by Drizzle tag */ getMigrationByTag(tag: string): PostgresDoMigration | undefined; /** * Get a migration by version */ getMigrationByVersion(version: number): PostgresDoMigration | undefined; /** * Get the latest version number */ getLatestVersion(): number; /** * Get migrations after a specific version */ getMigrationsAfter(version: number): PostgresDoMigration[]; /** * Get the Drizzle journal */ getJournal(): DrizzleJournal; /** * Export back to Drizzle journal format * * Useful for keeping Drizzle's journal in sync after manual changes. */ exportToJournal(): DrizzleJournal; /** * Validate that all migrations have SQL files */ validate(): { valid: boolean; errors: string[]; }; /** * Add down migrations */ addDownMigration(tagOrId: string, downSql: string): void; /** * Generate migration SQL statistics */ getStats(): { totalMigrations: number; reversibleCount: number; nonReversibleCount: number; totalSqlStatements: number; }; } /** * Create a migration bridge instance * * @example * ```typescript * import { createMigrationBridge } from 'postgres.do/drizzle' * * const bridge = createMigrationBridge({ * migrations: bundledMigrations, * downMigrations: { * 'create_users': 'DROP TABLE users;', * 'add_posts': 'DROP TABLE posts;', * }, * }) * * const postgresDoMigrations = bridge.getMigrations() * ``` */ declare function createMigrationBridge(config: MigrationBridgeConfig): MigrationBridge; /** * Quick conversion from Drizzle migrations to postgres.do format */ declare function convertDrizzleToPostgresDo(bundled: BundledDrizzleMigrations, downMigrations?: Record): PostgresDoMigration[]; /** * Create a combined migrator that uses both Drizzle and postgres.do tracking * * This is useful when you want to leverage Drizzle's migration generation * while using postgres.do's multi-database version tracking. * * @example * ```typescript * import { createCombinedMigrator } from 'postgres.do/drizzle' * import bundledMigrations from './drizzle-bundle' * * const migrator = createCombinedMigrator({ * drizzle: bundledMigrations, * tableName: '_combined_migrations', * }) * * // In your DO * await migrator.ensureMigrated(pglite) * ``` */ interface CombinedMigratorConfig { /** * Bundled Drizzle migrations */ drizzle: BundledDrizzleMigrations; /** * Optional down migrations */ downMigrations?: Record; /** * Table name for version tracking * Default: '_migrations' */ tableName?: string; /** * Enable debug logging */ debug?: boolean; /** * Callback on progress */ onProgress?: (event: { migration: PostgresDoMigration; index: number; total: number; phase: string; durationMs?: number; error?: string; }) => void; } /** * Query executor interface */ interface QueryExecutor$1 { query(sql: string, params?: unknown[]): Promise<{ rows: T[]; }>; } /** * Combined migrator that merges Drizzle and postgres.do tracking */ declare function runCombinedMigrations(executor: QueryExecutor$1, config: CombinedMigratorConfig): Promise<{ success: boolean; appliedCount: number; skippedCount: number; durationMs: number; error?: string; }>; /** * Auto Drizzle Migrator * * Seamlessly integrates Drizzle Kit migrations with postgres.do's AutoMigrator. * This provides automatic migration execution on DO initialization while * maintaining compatibility with both Drizzle's journal and postgres.do's * version tracking. * * @example * ```typescript * import { createAutoDrizzleMigrator } from 'postgres.do/drizzle' * import bundledMigrations from './drizzle-bundle' * * const migrator = createAutoDrizzleMigrator({ * drizzle: bundledMigrations, * autoRun: true, * journalTable: '__drizzle_migrations', * checksumValidation: true, * }) * * // In your DO * class PostgresDO { * async fetch(request: Request) { * await migrator.ensureMigrated(this.pglite) * // Handle request... * } * } * ``` */ /** * Query executor interface matching postgres.do and PGLite */ interface QueryExecutor { query(sql: string, params?: unknown[]): Promise<{ rows: T[]; }>; } /** * Configuration for Auto Drizzle Migrator * * This matches the proposed drizzle.config.ts format from the issue */ interface AutoDrizzleMigratorConfig { /** * Bundled Drizzle migrations from drizzle-kit generate */ drizzle: BundledDrizzleMigrations; /** * Optional down migrations keyed by migration tag * Drizzle doesn't generate down migrations by default, * but you can provide them manually for rollback support. */ downMigrations?: Record; /** * Run migrations automatically on first connection * Default: true */ autoRun?: boolean; /** * Name of the Drizzle migrations tracking table * Default: '__drizzle_migrations' */ journalTable?: string; /** * Name of the postgres.do migrations tracking table * Default: '_migrations' */ postgresDoTable?: string; /** * Validate migration checksums to detect modifications * Default: true */ checksumValidation?: boolean; /** * Sync Drizzle journal with postgres.do version tracking * Default: true */ syncJournals?: boolean; /** * Progress callback for migration events */ onProgress?: (event: DrizzleMigrationProgressEvent) => void; /** * Callback when all migrations complete */ onComplete?: (result: AutoDrizzleMigrationResult) => void; /** * Callback on migration error */ onError?: (error: Error) => void; /** * Enable debug logging * Default: false */ debug?: boolean; } /** * Result of auto Drizzle migration */ interface AutoDrizzleMigrationResult extends DrizzleMigrationResult { /** postgres.do migrations result */ postgresDoResult?: { fromVersion: number; toVersion: number; migrationsRun: number; migrationsSkipped: number; }; /** Whether journals were synced */ journalsSynced: boolean; } /** * Migrator state */ type AutoDrizzleMigratorState = 'idle' | 'running' | 'completed' | 'failed'; /** * Auto Drizzle Migrator * * Combines Drizzle Kit migrations with postgres.do's AutoMigrator * for seamless schema management in Durable Objects. */ declare class AutoDrizzleMigrator { private config; private drizzle; private downMigrations; private onProgress?; private onComplete?; private onError?; private state; private migrationPromise; private lastResult; private lastError; private cachedMigrations; constructor(config: AutoDrizzleMigratorConfig); /** * Log debug message */ private log; /** * Get current state */ getState(): AutoDrizzleMigratorState; /** * Get last result */ getLastResult(): AutoDrizzleMigrationResult | null; /** * Get last error */ getLastError(): Error | null; /** * Get migrations in postgres.do format */ getMigrations(): PostgresDoMigration[]; /** * Get the Drizzle journal */ getJournal(): DrizzleJournal; /** * Get latest version */ getLatestVersion(): number; /** * Initialize tables */ private initializeTables; /** * Get applied migrations from both systems */ private getAppliedMigrations; /** * Ensure migrations are applied */ ensureMigrated(executor: QueryExecutor): Promise; /** * Run all pending migrations */ private runMigrations; /** * Sync Drizzle journal with postgres.do tracking * * Ensures both tracking systems have consistent records */ private syncJournals; /** * Force re-run migrations */ forceMigrate(executor: QueryExecutor): Promise; /** * Get migration status */ getStatus(executor: QueryExecutor): Promise<{ initialized: boolean; appliedCount: number; pendingCount: number; appliedMigrations: Array<{ id: string; version: number; tag?: string | undefined; }>; pendingMigrations: Array<{ id: string; version: number; tag?: string | undefined; }>; journalsSynced: boolean; }>; /** * Check if there are pending migrations */ needsMigration(executor: QueryExecutor): Promise; /** * Rollback the last migration */ rollbackLast(executor: QueryExecutor): Promise<{ success: boolean; migration?: PostgresDoMigration; error?: string; }>; /** * Rollback to a specific version */ rollbackToVersion(executor: QueryExecutor, targetVersion: number): Promise<{ success: boolean; rolledBack: string[]; error?: string | undefined; }>; } /** * Create an auto Drizzle migrator instance * * @example * ```typescript * import { createAutoDrizzleMigrator } from 'postgres.do/drizzle' * import bundledMigrations from './drizzle-bundle' * * const migrator = createAutoDrizzleMigrator({ * drizzle: bundledMigrations, * autoRun: true, * onProgress: (event) => console.log(`${event.phase}: ${event.migration.tag}`), * }) * * // In your DO * await migrator.ensureMigrated(pglite) * ``` */ declare function createAutoDrizzleMigrator(config: AutoDrizzleMigratorConfig): AutoDrizzleMigrator; /** * Drizzle Schema Generator * * Generate Drizzle ORM schema definitions from: * 1. TypeScript interfaces/types * 2. Database introspection * * This module creates idiomatic Drizzle schemas that can be used * for type-safe database queries. * * @module drizzle/schema-generator */ /** * Supported PostgreSQL column types with Drizzle equivalents */ interface DrizzleColumnType { /** Drizzle function name (e.g., 'text', 'integer', 'timestamp') */ drizzleType: string; /** Whether it needs import from pg-core */ import: string; /** Additional type parameters (e.g., precision for numeric) */ params?: string; /** TypeScript type for the column */ tsType: string; } /** * Column definition for schema generation */ interface SchemaColumnDefinition { /** Column name in the database */ name: string; /** PostgreSQL data type */ pgType: string; /** Whether the column allows null */ nullable: boolean; /** Whether the column has a default value */ hasDefault: boolean; /** Default value expression */ defaultValue?: string | undefined; /** Whether this is a primary key */ isPrimaryKey: boolean; /** Whether this column is unique */ isUnique: boolean; /** Maximum length for string types */ maxLength?: number | undefined; /** Foreign key reference */ references?: { table: string; column: string; onDelete?: string | undefined; onUpdate?: string | undefined; } | undefined; /** Array type flag */ isArray: boolean; } /** * Index definition for schema generation */ interface SchemaIndexDefinition { /** Index name */ name: string; /** Columns in the index */ columns: string[]; /** Whether the index is unique */ isUnique: boolean; /** Index type (btree, hash, gin, gist, etc.) */ type?: string | undefined; /** WHERE clause for partial indexes */ where?: string | undefined; } /** * Table definition for schema generation */ interface SchemaTableDefinition { /** Table name */ name: string; /** Schema name (default: public) */ schema: string; /** Column definitions */ columns: SchemaColumnDefinition[]; /** Primary key columns (for composite keys) */ primaryKey?: string[] | undefined; /** Index definitions */ indexes: SchemaIndexDefinition[]; /** Check constraints */ checkConstraints?: Array<{ name: string; expression: string; }> | undefined; } /** * Enum definition for schema generation */ interface SchemaEnumDefinition { /** Enum name */ name: string; /** Enum values */ values: string[]; } /** * Complete database schema for generation */ interface DatabaseSchemaDefinition { /** Tables in the schema */ tables: SchemaTableDefinition[]; /** Enum types */ enums: SchemaEnumDefinition[]; /** Schema name */ schemaName: string; } /** * Options for schema generation */ interface SchemaGeneratorOptions { /** Database schema to introspect (default: 'public') */ schema?: string; /** Whether to include relations */ includeRelations?: boolean; /** Whether to include indexes */ includeIndexes?: boolean; /** Tables to include (if specified, only these tables are generated) */ includeTables?: string[]; /** Tables to exclude */ excludeTables?: string[]; /** Whether to generate types as well */ generateTypes?: boolean; /** Naming convention for table names */ tableNaming?: 'camelCase' | 'PascalCase' | 'snake_case'; /** Naming convention for column names */ columnNaming?: 'camelCase' | 'snake_case'; /** Whether to use singular table names */ singularTableNames?: boolean; } /** * TypeScript property definition for type-to-schema conversion */ interface TypeScriptProperty { /** Property name */ name: string; /** TypeScript type string */ type: string; /** Whether the property is optional */ optional: boolean; /** JSDoc comment if any */ comment?: string | undefined; } /** * TypeScript interface definition for schema conversion */ interface TypeScriptInterface { /** Interface name */ name: string; /** Properties */ properties: TypeScriptProperty[]; /** Extends clause */ extends?: string[] | undefined; /** JSDoc comment */ comment?: string | undefined; } /** * Introspect a PostgreSQL database and return schema definitions * * @example * ```typescript * const schema = await introspectDatabase(sql, { schema: 'public' }) * const drizzleCode = generateDrizzleSchema(schema) * ``` */ declare function introspectDatabase(client: Sql, options?: SchemaGeneratorOptions): Promise; /** * Parse TypeScript interface from source code string * * @example * ```typescript * const interfaces = parseTypeScriptInterfaces(` * interface User { * id: string; * email: string; * createdAt: Date; * } * `) * ``` */ declare function parseTypeScriptInterfaces(source: string): TypeScriptInterface[]; /** * Convert TypeScript interfaces to table definitions * * @example * ```typescript * const tables = convertInterfacesToTables(interfaces, { * singularTableNames: false, * }) * ``` */ declare function convertInterfacesToTables(interfaces: TypeScriptInterface[], options?: SchemaGeneratorOptions): SchemaTableDefinition[]; /** * Generate Drizzle schema code from database schema definition * * @example * ```typescript * const schema = await introspectDatabase(sql) * const code = generateDrizzleSchema(schema) * console.log(code) * ``` */ declare function generateDrizzleSchema(schema: DatabaseSchemaDefinition, options?: SchemaGeneratorOptions): string; /** * Generate Drizzle schema from TypeScript source code * * @example * ```typescript * const source = ` * interface User { * id: string; * email: string; * createdAt: Date; * metadata: Record; * } * ` * const schema = generateSchemaFromTypeScript(source) * console.log(schema) * ``` */ declare function generateSchemaFromTypeScript(source: string, options?: SchemaGeneratorOptions): string; /** * Generate Drizzle schema from database introspection * * @example * ```typescript * import postgres from 'postgres.do' * import { generateSchemaFromDatabase } from 'postgres.do/drizzle' * * const sql = postgres('postgres://...') * const schema = await generateSchemaFromDatabase(sql) * console.log(schema) * ``` */ declare function generateSchemaFromDatabase(client: Sql, options?: SchemaGeneratorOptions): Promise; /** * Generate TypeScript types alongside Drizzle schema * * @example * ```typescript * const { schema, types } = await generateSchemaWithTypes(sql) * ``` */ declare function generateSchemaWithTypes(client: Sql, options?: SchemaGeneratorOptions): Promise<{ schema: string; types: string; }>; /** * Schema Diff and Sync Tools * * Compare database schemas and generate migration SQL from differences. * Supports comparing: * - Two live databases * - Database vs Drizzle schema definition * - Two schema definitions * * @example Compare two databases * ```typescript * import { compareSchemas, generateMigrationSQL } from 'postgres.do/drizzle' * * const diff = await compareSchemas(sourceClient, targetClient) * const sql = generateMigrationSQL(diff) * ``` * * @example Diff local vs production * ```typescript * const localSchema = await introspectDatabase(localClient) * const prodSchema = await introspectDatabase(prodClient) * const diff = diffSchemas(localSchema, prodSchema) * console.log(formatSchemaDiff(diff)) * ``` * * @module drizzle/schema-diff */ /** * Types of changes that can occur in a schema diff */ type ChangeType = 'added' | 'removed' | 'modified'; /** * A single column change */ interface ColumnChange { /** Type of change */ changeType: ChangeType; /** Column name */ columnName: string; /** Column in source schema (undefined if added) */ source?: SchemaColumnDefinition; /** Column in target schema (undefined if removed) */ target?: SchemaColumnDefinition; /** Specific attribute changes (for modified columns) */ attributeChanges?: ColumnAttributeChange[]; } /** * Specific attribute change within a column */ interface ColumnAttributeChange { /** Attribute name */ attribute: 'type' | 'nullable' | 'default' | 'primaryKey' | 'unique' | 'references' | 'maxLength'; /** Value in source schema */ sourceValue: unknown; /** Value in target schema */ targetValue: unknown; } /** * A single index change */ interface IndexChange { /** Type of change */ changeType: ChangeType; /** Index name */ indexName: string; /** Index in source schema (undefined if added) */ source?: SchemaIndexDefinition; /** Index in target schema (undefined if removed) */ target?: SchemaIndexDefinition; } /** * A single table change */ interface TableChange { /** Type of change */ changeType: ChangeType; /** Table name */ tableName: string; /** Table in source schema (undefined if added) */ source?: SchemaTableDefinition; /** Table in target schema (undefined if removed) */ target?: SchemaTableDefinition; /** Column changes (for modified tables) */ columnChanges?: ColumnChange[]; /** Index changes (for modified tables) */ indexChanges?: IndexChange[]; /** Primary key changes */ primaryKeyChange?: { source?: string[]; target?: string[]; }; } /** * A single enum change */ interface EnumChange { /** Type of change */ changeType: ChangeType; /** Enum name */ enumName: string; /** Enum in source schema (undefined if added) */ source?: SchemaEnumDefinition; /** Enum in target schema (undefined if removed) */ target?: SchemaEnumDefinition; /** Values added */ addedValues?: string[]; /** Values removed */ removedValues?: string[]; } /** * Complete schema diff result */ interface SchemaDiff { /** Source schema name */ sourceSchema: string; /** Target schema name */ targetSchema: string; /** Table changes */ tableChanges: TableChange[]; /** Enum changes */ enumChanges: EnumChange[]; /** Whether schemas are identical */ isIdentical: boolean; /** Summary statistics */ summary: { tablesAdded: number; tablesRemoved: number; tablesModified: number; columnsAdded: number; columnsRemoved: number; columnsModified: number; indexesAdded: number; indexesRemoved: number; enumsAdded: number; enumsRemoved: number; enumsModified: number; }; } /** * Options for schema diff */ interface SchemaDiffOptions { /** Ignore case differences in names */ ignoreCase?: boolean; /** Ignore whitespace in default values */ ignoreDefaultWhitespace?: boolean; /** Tables to include (if specified, only these tables are compared) */ includeTables?: string[]; /** Tables to exclude from comparison */ excludeTables?: string[]; /** Whether to compare indexes */ compareIndexes?: boolean; /** Whether to detect column renames (vs add/remove) */ detectRenames?: boolean; } /** * Options for migration SQL generation */ interface MigrationSQLOptions { /** Whether to include comments in generated SQL */ includeComments?: boolean; /** Whether to wrap in transaction */ wrapInTransaction?: boolean; /** Target database type (for syntax variations) */ dialect?: 'postgresql' | 'postgres'; /** Schema name to use */ schema?: string; /** Generate IF EXISTS/IF NOT EXISTS clauses */ safeMode?: boolean; } /** * Generated migration result */ interface GeneratedMigration { /** The SQL statements for forward migration */ up: string[]; /** The SQL statements for rollback (if possible) */ down: string[]; /** Complete up migration as single string */ upSQL: string; /** Complete down migration as single string */ downSQL: string; /** Whether the migration is fully reversible */ isReversible: boolean; /** Warnings about potentially destructive changes */ warnings: string[]; /** Description of the migration */ description: string; } /** * Compare two database schemas by connecting to both databases * * @example * ```typescript * const diff = await compareSchemas(localClient, prodClient, { * compareIndexes: true, * excludeTables: ['_migrations'] * }) * ``` */ declare function compareSchemas(sourceClient: Sql, targetClient: Sql, options?: SchemaDiffOptions & SchemaGeneratorOptions): Promise; /** * Compare a database against a schema definition * * @example * ```typescript * const currentSchema = await introspectDatabase(client) * const diff = await compareDatabaseToSchema(client, desiredSchema) * ``` */ declare function compareDatabaseToSchema(client: Sql, targetSchema: DatabaseSchemaDefinition, options?: SchemaDiffOptions & SchemaGeneratorOptions): Promise; /** * Compare two schema definitions * * @example * ```typescript * const diff = diffSchemas(localSchema, prodSchema) * console.log(diff.summary) * ``` */ declare function diffSchemas(source: DatabaseSchemaDefinition, target: DatabaseSchemaDefinition, options?: SchemaDiffOptions): SchemaDiff; /** * Generate migration SQL from a schema diff * * @example * ```typescript * const diff = diffSchemas(localSchema, prodSchema) * const migration = generateMigrationSQL(diff, { * includeComments: true, * safeMode: true * }) * console.log(migration.upSQL) * ``` */ declare function generateMigrationSQL(diff: SchemaDiff, options?: MigrationSQLOptions): GeneratedMigration; /** * Format schema diff for CLI display * * @example * ```typescript * const diff = diffSchemas(localSchema, prodSchema) * console.log(formatSchemaDiff(diff)) * // Output: * // + Table: audit_logs (not in target) * // ~ Table: users * // + Column: last_login_at * // ~ Column: email: varchar(100) -> varchar(255) * // - Table: temp_data (not in source) * ``` */ declare function formatSchemaDiff(diff: SchemaDiff, options?: { color?: boolean; }): string; /** * Format schema diff as JSON */ declare function formatSchemaDiffJSON(diff: SchemaDiff): string; /** * Generate Drizzle schema migration file from diff * * @example * ```typescript * const diff = diffSchemas(localSchema, prodSchema) * const drizzleMigration = generateDrizzleMigration(diff, 'sync_to_production') * fs.writeFileSync('./migrations/0001_sync_to_production.ts', drizzleMigration) * ``` */ declare function generateDrizzleMigration(diff: SchemaDiff, name: string, options?: MigrationSQLOptions): string; export { type AutoDrizzleMigrationResult, AutoDrizzleMigrator, type AutoDrizzleMigratorConfig, type AutoDrizzleMigratorState, type BundledDrizzleMigrations, type ChangeType, type ColumnAttributeChange, type ColumnChange, type CombinedMigratorConfig, type DatabaseSchemaDefinition, type DrizzleColumnType, type DrizzleJournal, type DrizzleJournalEntry, type DrizzleMigrationProgressEvent, type DrizzleMigrationRecord, type DrizzleMigrationResult, DrizzleMigrator, type DrizzleMigratorConfig, type DrizzleMigratorState, type EnumChange, type GeneratedMigration, type IndexChange, MigrationBridge, type MigrationBridgeConfig, type MigrationSQLOptions, type PostgresDoMigration, type SchemaColumnDefinition, type SchemaDiff, type SchemaDiffOptions, type SchemaEnumDefinition, type SchemaGeneratorOptions, type SchemaIndexDefinition, type SchemaTableDefinition, type TableChange, type TypeScriptInterface, type TypeScriptProperty, bundleDrizzleMigrations, compareDatabaseToSchema, compareSchemas, convertDrizzleToPostgresDo, convertInterfacesToTables, createAutoDrizzleMigrator, createDrizzleMigrator, createMigrationBridge, diffSchemas, formatSchemaDiff, formatSchemaDiffJSON, generateDrizzleMigration, generateDrizzleSchema, generateMigrationSQL, generateSchemaFromDatabase, generateSchemaFromTypeScript, generateSchemaWithTypes, introspectDatabase, parseDrizzleJournal, parseTypeScriptInterfaces, runCombinedMigrations };