@kysera/migrations 0.4.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +443 -1046
- package/dist/index.d.ts +234 -24
- package/dist/index.js +1 -14
- package/dist/index.js.map +1 -1
- package/dist/schemas.d.ts +138 -0
- package/dist/schemas.js +2 -0
- package/dist/schemas.js.map +1 -0
- package/package.json +24 -11
package/dist/index.d.ts
CHANGED
|
@@ -1,26 +1,36 @@
|
|
|
1
1
|
import { Kysely } from 'kysely';
|
|
2
|
+
import { KyseraLogger, DatabaseError } from '@kysera/core';
|
|
3
|
+
export { BadRequestError, DatabaseError, KyseraLogger, NotFoundError, silentLogger } from '@kysera/core';
|
|
4
|
+
export { MigrationDefinitionInput, MigrationDefinitionOutput, MigrationDefinitionSchema, MigrationPluginInput, MigrationPluginOptionsInput, MigrationPluginOptionsOutput, MigrationPluginOptionsSchema, MigrationPluginOutput, MigrationPluginSchema, MigrationResultSchema, MigrationResultType, MigrationRunnerOptionsInput, MigrationRunnerOptionsOutput, MigrationRunnerOptionsSchema, MigrationRunnerWithPluginsOptionsInput, MigrationRunnerWithPluginsOptionsOutput, MigrationRunnerWithPluginsOptionsSchema, MigrationStatusSchema, MigrationStatusType, parseMigrationDefinition, parseMigrationRunnerOptions, safeParseMigrationDefinition, safeParseMigrationRunnerOptions } from './schemas.js';
|
|
5
|
+
import 'zod';
|
|
2
6
|
|
|
3
7
|
/**
|
|
4
|
-
* Migration interface
|
|
8
|
+
* Migration interface - the core building block
|
|
9
|
+
* Generic DB type allows type-safe migrations when schema is known,
|
|
10
|
+
* defaults to unknown for maximum flexibility
|
|
5
11
|
*/
|
|
6
|
-
interface Migration {
|
|
12
|
+
interface Migration<DB = unknown> {
|
|
7
13
|
/** Unique migration name (e.g., '001_create_users') */
|
|
8
14
|
name: string;
|
|
9
15
|
/** Migration up function - creates/modifies schema */
|
|
10
|
-
up: (db: Kysely<
|
|
16
|
+
up: (db: Kysely<DB>) => Promise<void>;
|
|
11
17
|
/** Optional migration down function - reverts changes */
|
|
12
|
-
down?: (db: Kysely<
|
|
18
|
+
down?: (db: Kysely<DB>) => Promise<void>;
|
|
13
19
|
}
|
|
14
20
|
/**
|
|
15
|
-
* Migration metadata for tracking
|
|
21
|
+
* Migration with metadata for enhanced logging and tracking
|
|
22
|
+
* Generic DB type allows type-safe migrations when schema is known,
|
|
23
|
+
* defaults to unknown for maximum flexibility
|
|
16
24
|
*/
|
|
17
|
-
interface MigrationWithMeta extends Migration {
|
|
18
|
-
/** Human-readable description */
|
|
25
|
+
interface MigrationWithMeta<DB = unknown> extends Migration<DB> {
|
|
26
|
+
/** Human-readable description shown during migration */
|
|
19
27
|
description?: string;
|
|
20
|
-
/** Whether this is a breaking change */
|
|
28
|
+
/** Whether this is a breaking change - shows warning before execution */
|
|
21
29
|
breaking?: boolean;
|
|
22
|
-
/** Estimated duration in milliseconds */
|
|
30
|
+
/** Estimated duration in milliseconds for progress indication */
|
|
23
31
|
estimatedDuration?: number;
|
|
32
|
+
/** Tags for categorization (e.g., ['schema', 'data', 'index']) */
|
|
33
|
+
tags?: string[];
|
|
24
34
|
}
|
|
25
35
|
/**
|
|
26
36
|
* Migration status result
|
|
@@ -30,69 +40,269 @@ interface MigrationStatus {
|
|
|
30
40
|
executed: string[];
|
|
31
41
|
/** List of pending migration names */
|
|
32
42
|
pending: string[];
|
|
43
|
+
/** Total migration count */
|
|
44
|
+
total: number;
|
|
33
45
|
}
|
|
34
46
|
/**
|
|
35
47
|
* Migration runner options
|
|
36
48
|
*/
|
|
37
49
|
interface MigrationRunnerOptions {
|
|
38
|
-
/** Enable dry run mode (
|
|
50
|
+
/** Enable dry run mode (preview only, no changes) */
|
|
39
51
|
dryRun?: boolean;
|
|
40
|
-
/**
|
|
41
|
-
|
|
52
|
+
/**
|
|
53
|
+
* Logger for migration operations.
|
|
54
|
+
* Uses KyseraLogger interface from @kysera/core.
|
|
55
|
+
*
|
|
56
|
+
* @default silentLogger (no output)
|
|
57
|
+
*/
|
|
58
|
+
logger?: KyseraLogger;
|
|
59
|
+
/** Wrap each migration in a transaction (default: false) */
|
|
60
|
+
useTransactions?: boolean;
|
|
61
|
+
/** Stop on first error (default: true) */
|
|
62
|
+
stopOnError?: boolean;
|
|
63
|
+
/** Show detailed metadata in logs (default: true) */
|
|
64
|
+
verbose?: boolean;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Object-based migration definition for Level 2 DX
|
|
68
|
+
* Generic DB type allows type-safe migrations when schema is known,
|
|
69
|
+
* defaults to unknown for maximum flexibility
|
|
70
|
+
*/
|
|
71
|
+
interface MigrationDefinition<DB = unknown> {
|
|
72
|
+
up: (db: Kysely<DB>) => Promise<void>;
|
|
73
|
+
down?: (db: Kysely<DB>) => Promise<void>;
|
|
74
|
+
description?: string;
|
|
75
|
+
breaking?: boolean;
|
|
76
|
+
estimatedDuration?: number;
|
|
77
|
+
tags?: string[];
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Migration definitions map for defineMigrations()
|
|
81
|
+
* Generic DB type allows type-safe migrations when schema is known,
|
|
82
|
+
* defaults to unknown for maximum flexibility
|
|
83
|
+
*/
|
|
84
|
+
type MigrationDefinitions<DB = unknown> = Record<string, MigrationDefinition<DB>>;
|
|
85
|
+
/**
|
|
86
|
+
* Result of a migration run
|
|
87
|
+
*/
|
|
88
|
+
interface MigrationResult {
|
|
89
|
+
/** Successfully executed migrations */
|
|
90
|
+
executed: string[];
|
|
91
|
+
/** Migrations that were skipped (already executed) */
|
|
92
|
+
skipped: string[];
|
|
93
|
+
/** Migrations that failed */
|
|
94
|
+
failed: string[];
|
|
95
|
+
/** Total duration in milliseconds */
|
|
96
|
+
duration: number;
|
|
97
|
+
/** Whether the run was in dry-run mode */
|
|
98
|
+
dryRun: boolean;
|
|
99
|
+
}
|
|
100
|
+
/** Error codes for migration operations */
|
|
101
|
+
type MigrationErrorCode = 'MIGRATION_UP_FAILED' | 'MIGRATION_DOWN_FAILED' | 'MIGRATION_VALIDATION_FAILED';
|
|
102
|
+
/**
|
|
103
|
+
* Migration-specific error extending DatabaseError from @kysera/core
|
|
104
|
+
* Provides structured error information with code, migration context, and cause tracking
|
|
105
|
+
*/
|
|
106
|
+
declare class MigrationError extends DatabaseError {
|
|
107
|
+
readonly migrationName: string;
|
|
108
|
+
readonly operation: 'up' | 'down';
|
|
109
|
+
constructor(message: string, migrationName: string, operation: 'up' | 'down', cause?: Error);
|
|
110
|
+
toJSON(): Record<string, unknown>;
|
|
42
111
|
}
|
|
43
112
|
/**
|
|
44
113
|
* Setup migrations table in database
|
|
114
|
+
* Idempotent - safe to run multiple times
|
|
115
|
+
* Uses Kysely<unknown> as migrations work with any database schema
|
|
45
116
|
*/
|
|
46
|
-
declare function setupMigrations(db: Kysely<
|
|
117
|
+
declare function setupMigrations(db: Kysely<unknown>): Promise<void>;
|
|
47
118
|
/**
|
|
48
|
-
* Migration runner with state tracking
|
|
119
|
+
* Migration runner with state tracking and metadata support
|
|
120
|
+
* Generic DB type allows type-safe migrations when schema is known,
|
|
121
|
+
* defaults to unknown for maximum flexibility
|
|
49
122
|
*/
|
|
50
|
-
declare class MigrationRunner {
|
|
123
|
+
declare class MigrationRunner<DB = unknown> {
|
|
51
124
|
private db;
|
|
52
125
|
private migrations;
|
|
53
|
-
private options;
|
|
54
126
|
private logger;
|
|
55
|
-
|
|
127
|
+
private options;
|
|
128
|
+
constructor(db: Kysely<DB>, migrations: Migration<DB>[], options?: MigrationRunnerOptions);
|
|
56
129
|
/**
|
|
57
130
|
* Get list of executed migrations from database
|
|
131
|
+
* Note: Uses type assertions for migrations table as it's not part of the user schema
|
|
58
132
|
*/
|
|
59
133
|
getExecutedMigrations(): Promise<string[]>;
|
|
60
134
|
/**
|
|
61
135
|
* Mark a migration as executed
|
|
136
|
+
* Note: Uses type assertions for migrations table as it's not part of the user schema
|
|
62
137
|
*/
|
|
63
138
|
markAsExecuted(name: string): Promise<void>;
|
|
64
139
|
/**
|
|
65
140
|
* Mark a migration as rolled back (remove from executed list)
|
|
141
|
+
* Note: Uses type assertions for migrations table as it's not part of the user schema
|
|
66
142
|
*/
|
|
67
143
|
markAsRolledBack(name: string): Promise<void>;
|
|
144
|
+
/**
|
|
145
|
+
* Log migration metadata if available
|
|
146
|
+
*/
|
|
147
|
+
private logMigrationMeta;
|
|
148
|
+
/**
|
|
149
|
+
* Execute a single migration with optional transaction wrapping
|
|
150
|
+
*/
|
|
151
|
+
private executeMigration;
|
|
68
152
|
/**
|
|
69
153
|
* Run all pending migrations
|
|
70
154
|
*/
|
|
71
|
-
up(): Promise<
|
|
155
|
+
up(): Promise<MigrationResult>;
|
|
72
156
|
/**
|
|
73
157
|
* Rollback last N migrations
|
|
74
158
|
*/
|
|
75
|
-
down(steps?: number): Promise<
|
|
159
|
+
down(steps?: number): Promise<MigrationResult>;
|
|
76
160
|
/**
|
|
77
161
|
* Show migration status
|
|
78
162
|
*/
|
|
79
163
|
status(): Promise<MigrationStatus>;
|
|
80
164
|
/**
|
|
81
165
|
* Reset all migrations (dangerous!)
|
|
166
|
+
* In dry run mode, shows what would be rolled back
|
|
82
167
|
*/
|
|
83
|
-
reset(): Promise<
|
|
168
|
+
reset(): Promise<MigrationResult>;
|
|
84
169
|
/**
|
|
85
170
|
* Run migrations up to a specific migration (inclusive)
|
|
86
171
|
*/
|
|
87
|
-
upTo(targetName: string): Promise<
|
|
172
|
+
upTo(targetName: string): Promise<MigrationResult>;
|
|
88
173
|
}
|
|
89
174
|
/**
|
|
90
175
|
* Create a migration runner instance
|
|
176
|
+
* Options are validated using Zod schema
|
|
177
|
+
* Generic DB type allows type-safe migrations when schema is known,
|
|
178
|
+
* defaults to unknown for maximum flexibility
|
|
91
179
|
*/
|
|
92
|
-
declare function createMigrationRunner(db: Kysely<
|
|
180
|
+
declare function createMigrationRunner<DB = unknown>(db: Kysely<DB>, migrations: Migration<DB>[], options?: MigrationRunnerOptions): MigrationRunner<DB>;
|
|
93
181
|
/**
|
|
94
182
|
* Helper to create a simple migration
|
|
183
|
+
* Generic DB type allows type-safe migrations when schema is known,
|
|
184
|
+
* defaults to unknown for maximum flexibility
|
|
185
|
+
*/
|
|
186
|
+
declare function createMigration<DB = unknown>(name: string, up: (db: Kysely<DB>) => Promise<void>, down?: (db: Kysely<DB>) => Promise<void>): Migration<DB>;
|
|
187
|
+
/**
|
|
188
|
+
* Helper to create a migration with metadata
|
|
189
|
+
* Generic DB type allows type-safe migrations when schema is known,
|
|
190
|
+
* defaults to unknown for maximum flexibility
|
|
191
|
+
*/
|
|
192
|
+
declare function createMigrationWithMeta<DB = unknown>(name: string, options: {
|
|
193
|
+
up: (db: Kysely<DB>) => Promise<void>;
|
|
194
|
+
down?: (db: Kysely<DB>) => Promise<void>;
|
|
195
|
+
description?: string;
|
|
196
|
+
breaking?: boolean;
|
|
197
|
+
estimatedDuration?: number;
|
|
198
|
+
tags?: string[];
|
|
199
|
+
}): MigrationWithMeta<DB>;
|
|
200
|
+
/**
|
|
201
|
+
* Define migrations using an object-based syntax for cleaner code
|
|
202
|
+
* Generic DB type allows type-safe migrations when schema is known,
|
|
203
|
+
* defaults to unknown for maximum flexibility
|
|
204
|
+
*/
|
|
205
|
+
declare function defineMigrations<DB = unknown>(definitions: MigrationDefinitions<DB>): MigrationWithMeta<DB>[];
|
|
206
|
+
/**
|
|
207
|
+
* Run all pending migrations - one-liner convenience function
|
|
208
|
+
* Generic DB type allows type-safe migrations when schema is known,
|
|
209
|
+
* defaults to unknown for maximum flexibility
|
|
210
|
+
*/
|
|
211
|
+
declare function runMigrations<DB = unknown>(db: Kysely<DB>, migrations: Migration<DB>[], options?: MigrationRunnerOptions): Promise<MigrationResult>;
|
|
212
|
+
/**
|
|
213
|
+
* Rollback migrations - one-liner convenience function
|
|
214
|
+
* Generic DB type allows type-safe migrations when schema is known,
|
|
215
|
+
* defaults to unknown for maximum flexibility
|
|
216
|
+
*/
|
|
217
|
+
declare function rollbackMigrations<DB = unknown>(db: Kysely<DB>, migrations: Migration<DB>[], steps?: number, options?: MigrationRunnerOptions): Promise<MigrationResult>;
|
|
218
|
+
/**
|
|
219
|
+
* Get migration status - one-liner convenience function
|
|
220
|
+
* Generic DB type allows type-safe migrations when schema is known,
|
|
221
|
+
* defaults to unknown for maximum flexibility
|
|
222
|
+
*/
|
|
223
|
+
declare function getMigrationStatus<DB = unknown>(db: Kysely<DB>, migrations: Migration<DB>[], options?: Pick<MigrationRunnerOptions, 'logger' | 'verbose'>): Promise<MigrationStatus>;
|
|
224
|
+
/**
|
|
225
|
+
* Migration plugin interface - consistent with @kysera/repository Plugin
|
|
226
|
+
* Provides lifecycle hooks for migration execution
|
|
227
|
+
* Generic DB type allows type-safe plugins when schema is known,
|
|
228
|
+
* defaults to unknown for maximum flexibility
|
|
229
|
+
*/
|
|
230
|
+
interface MigrationPlugin<DB = unknown> {
|
|
231
|
+
/** Plugin name */
|
|
232
|
+
name: string;
|
|
233
|
+
/** Plugin version */
|
|
234
|
+
version: string;
|
|
235
|
+
/** Called once when the runner is initialized (consistent with repository Plugin.onInit) */
|
|
236
|
+
onInit?(runner: MigrationRunner<DB>): Promise<void> | void;
|
|
237
|
+
/** Called before migration execution */
|
|
238
|
+
beforeMigration?(migration: Migration<DB>, operation: 'up' | 'down'): Promise<void> | void;
|
|
239
|
+
/** Called after successful migration execution */
|
|
240
|
+
afterMigration?(migration: Migration<DB>, operation: 'up' | 'down', duration: number): Promise<void> | void;
|
|
241
|
+
/** Called on migration error (unknown type for consistency with repository Plugin.onError) */
|
|
242
|
+
onMigrationError?(migration: Migration<DB>, operation: 'up' | 'down', error: unknown): Promise<void> | void;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Extended migration runner options with plugin support
|
|
246
|
+
* Generic DB type allows type-safe plugins when schema is known,
|
|
247
|
+
* defaults to unknown for maximum flexibility
|
|
248
|
+
*/
|
|
249
|
+
interface MigrationRunnerWithPluginsOptions<DB = unknown> extends MigrationRunnerOptions {
|
|
250
|
+
/** Plugins to apply */
|
|
251
|
+
plugins?: MigrationPlugin<DB>[];
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Create a migration runner with plugin support
|
|
255
|
+
* Async factory to properly initialize plugins (consistent with @kysera/repository createORM)
|
|
256
|
+
* Generic DB type allows type-safe migrations when schema is known,
|
|
257
|
+
* defaults to unknown for maximum flexibility
|
|
258
|
+
*/
|
|
259
|
+
declare function createMigrationRunnerWithPlugins<DB = unknown>(db: Kysely<DB>, migrations: Migration<DB>[], options?: MigrationRunnerWithPluginsOptions<DB>): Promise<MigrationRunnerWithPlugins<DB>>;
|
|
260
|
+
/**
|
|
261
|
+
* Extended migration runner with plugin support
|
|
262
|
+
* Generic DB type allows type-safe migrations when schema is known,
|
|
263
|
+
* defaults to unknown for maximum flexibility
|
|
264
|
+
*/
|
|
265
|
+
declare class MigrationRunnerWithPlugins<DB = unknown> extends MigrationRunner<DB> {
|
|
266
|
+
private plugins;
|
|
267
|
+
constructor(db: Kysely<DB>, migrations: Migration<DB>[], options?: MigrationRunnerWithPluginsOptions<DB>);
|
|
268
|
+
/**
|
|
269
|
+
* Execute plugin hooks before migration
|
|
270
|
+
* Can be called by consumers extending this class
|
|
271
|
+
*/
|
|
272
|
+
protected runBeforeHooks(migration: Migration<DB>, operation: 'up' | 'down'): Promise<void>;
|
|
273
|
+
/**
|
|
274
|
+
* Execute plugin hooks after migration
|
|
275
|
+
* Can be called by consumers extending this class
|
|
276
|
+
*/
|
|
277
|
+
protected runAfterHooks(migration: Migration<DB>, operation: 'up' | 'down', duration: number): Promise<void>;
|
|
278
|
+
/**
|
|
279
|
+
* Execute plugin hooks on error
|
|
280
|
+
* Can be called by consumers extending this class
|
|
281
|
+
*/
|
|
282
|
+
protected runErrorHooks(migration: Migration<DB>, operation: 'up' | 'down', error: unknown): Promise<void>;
|
|
283
|
+
/**
|
|
284
|
+
* Get the list of registered plugins
|
|
285
|
+
*/
|
|
286
|
+
getPlugins(): MigrationPlugin<DB>[];
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Logging plugin - logs migration events with timing
|
|
290
|
+
* Works with any DB type (generic plugin)
|
|
291
|
+
*/
|
|
292
|
+
declare function createLoggingPlugin<DB = unknown>(logger?: KyseraLogger): MigrationPlugin<DB>;
|
|
293
|
+
/**
|
|
294
|
+
* Metrics plugin - collects migration metrics
|
|
295
|
+
* Works with any DB type (generic plugin)
|
|
95
296
|
*/
|
|
96
|
-
declare function
|
|
297
|
+
declare function createMetricsPlugin<DB = unknown>(): MigrationPlugin<DB> & {
|
|
298
|
+
getMetrics(): {
|
|
299
|
+
migrations: Array<{
|
|
300
|
+
name: string;
|
|
301
|
+
operation: string;
|
|
302
|
+
duration: number;
|
|
303
|
+
success: boolean;
|
|
304
|
+
}>;
|
|
305
|
+
};
|
|
306
|
+
};
|
|
97
307
|
|
|
98
|
-
export { type Migration, MigrationRunner, type MigrationRunnerOptions, type MigrationStatus, type MigrationWithMeta, createMigration, createMigrationRunner, setupMigrations };
|
|
308
|
+
export { type Migration, type MigrationDefinition, type MigrationDefinitions, MigrationError, type MigrationErrorCode, type MigrationPlugin, type MigrationResult, MigrationRunner, type MigrationRunnerOptions, MigrationRunnerWithPlugins, type MigrationRunnerWithPluginsOptions, type MigrationStatus, type MigrationWithMeta, createLoggingPlugin, createMetricsPlugin, createMigration, createMigrationRunner, createMigrationRunnerWithPlugins, createMigrationWithMeta, defineMigrations, getMigrationStatus, rollbackMigrations, runMigrations, setupMigrations };
|
package/dist/index.js
CHANGED
|
@@ -1,15 +1,2 @@
|
|
|
1
|
-
import {sql}from'kysely';async function a(r){await r.schema.createTable("migrations").ifNotExists().addColumn("name","varchar(255)",i=>i.primaryKey()).addColumn("executed_at","timestamp",i=>i.notNull().defaultTo(sql`CURRENT_TIMESTAMP`)).execute();}var g=class{constructor(i,e,t={}){this.db=i;this.migrations=e;this.options=t;this.logger=t.logger||console.log;}logger;async getExecutedMigrations(){return (await this.db.selectFrom("migrations").select("name").orderBy("executed_at","asc").execute()).map(e=>e.name)}async markAsExecuted(i){await this.db.insertInto("migrations").values({name:i}).execute();}async markAsRolledBack(i){await this.db.deleteFrom("migrations").where("name","=",i).execute();}async up(){await a(this.db);let i=await this.getExecutedMigrations();if(this.migrations.filter(t=>!i.includes(t.name)).length===0){this.logger("\u2705 No pending migrations");return}this.options.dryRun&&this.logger(`
|
|
2
|
-
\u{1F50D} DRY RUN - No changes will be made
|
|
3
|
-
`);for(let t of this.migrations){if(i.includes(t.name)){this.logger(`\u2713 ${t.name} (already executed)`);continue}try{this.logger(`\u2191 Running ${t.name}...`),this.options.dryRun||(await t.up(this.db),await this.markAsExecuted(t.name)),this.logger(`\u2713 ${t.name} completed`);}catch(o){throw this.logger(`\u2717 ${t.name} failed: ${o}`),o}}this.options.dryRun||this.logger(`
|
|
4
|
-
\u2705 All migrations completed successfully`);}async down(i=1){let e=await this.getExecutedMigrations();if(e.length===0){this.logger("\u26A0\uFE0F No executed migrations to rollback");return}let t=e.slice(-i).reverse();this.options.dryRun&&this.logger(`
|
|
5
|
-
\u{1F50D} DRY RUN - No changes will be made
|
|
6
|
-
`);for(let o of t){let n=this.migrations.find(s=>s.name===o);if(!n){this.logger(`\u26A0\uFE0F Migration ${o} not found in codebase`);continue}if(!n.down){this.logger(`\u26A0\uFE0F Migration ${o} has no down method`);continue}try{this.logger(`\u2193 Rolling back ${o}...`),this.options.dryRun||(await n.down(this.db),await this.markAsRolledBack(o)),this.logger(`\u2713 ${o} rolled back`);}catch(s){throw this.logger(`\u2717 ${o} rollback failed: ${s}`),s}}this.options.dryRun||this.logger(`
|
|
7
|
-
\u2705 Rollback completed successfully`);}async status(){await a(this.db);let i=await this.getExecutedMigrations(),e=this.migrations.filter(t=>!i.includes(t.name)).map(t=>t.name);return this.logger(`
|
|
8
|
-
\u{1F4CA} Migration Status:`),this.logger(` \u2705 Executed: ${i.length}`),this.logger(` \u23F3 Pending: ${e.length}`),i.length>0&&(this.logger(`
|
|
9
|
-
Executed migrations:`),i.forEach(t=>{this.logger(` \u2713 ${t}`);})),e.length>0&&(this.logger(`
|
|
10
|
-
Pending migrations:`),e.forEach(t=>{this.logger(` - ${t}`);})),{executed:i,pending:e}}async reset(){if(this.options.dryRun){this.logger(`
|
|
11
|
-
\u{1F50D} DRY RUN - Would rollback all migrations`);return}let i=await this.getExecutedMigrations();this.logger(`
|
|
12
|
-
\u26A0\uFE0F Resetting ${i.length} migrations...`),await this.down(i.length),this.logger(`
|
|
13
|
-
\u2705 All migrations reset`);}async upTo(i){await a(this.db);let e=await this.getExecutedMigrations(),t=this.migrations.findIndex(n=>n.name===i);if(t===-1)throw new Error(`Migration ${i} not found`);let o=this.migrations.slice(0,t+1);for(let n of o){if(e.includes(n.name)){this.logger(`\u2713 ${n.name} (already executed)`);continue}try{this.logger(`\u2191 Running ${n.name}...`),this.options.dryRun||(await n.up(this.db),await this.markAsExecuted(n.name)),this.logger(`\u2713 ${n.name} completed`);}catch(s){throw this.logger(`\u2717 ${n.name} failed: ${s}`),s}}this.logger(`
|
|
14
|
-
\u2705 Migrated up to ${i}`);}};function c(r,i,e){return new g(r,i,e)}function h(r,i,e){let t={name:r,up:i};return e!==void 0&&(t.down=e),t}export{g as MigrationRunner,h as createMigration,c as createMigrationRunner,a as setupMigrations};//# sourceMappingURL=index.js.map
|
|
1
|
+
import {sql}from'kysely';import {silentLogger,DatabaseError,BadRequestError,NotFoundError}from'@kysera/core';export{BadRequestError,DatabaseError,NotFoundError,silentLogger}from'@kysera/core';import {z as z$1}from'zod';var d=z$1.object({dryRun:z$1.boolean().default(false),logger:z$1.any().optional(),useTransactions:z$1.boolean().default(false),stopOnError:z$1.boolean().default(true),verbose:z$1.boolean().default(true)}),m=z$1.object({name:z$1.string().min(1,"Migration name is required"),description:z$1.string().optional(),breaking:z$1.boolean().default(false),tags:z$1.array(z$1.string()).default([]),estimatedDuration:z$1.string().optional()}),x=z$1.object({logger:z$1.any().optional()}),D=z$1.object({name:z$1.string().min(1,"Plugin name is required"),version:z$1.string().min(1,"Plugin version is required"),onInit:z$1.any().optional(),beforeMigration:z$1.any().optional(),afterMigration:z$1.any().optional(),onMigrationError:z$1.any().optional()}),b=z$1.object({executed:z$1.array(z$1.string()),pending:z$1.array(z$1.string()),total:z$1.number().int().nonnegative()}),P=z$1.object({executed:z$1.array(z$1.string()),skipped:z$1.array(z$1.string()),failed:z$1.array(z$1.string()),duration:z$1.number().nonnegative(),dryRun:z$1.boolean()}),B=d.extend({plugins:z$1.array(D).optional()});function k(e){return d.parse(e)}function O(e){return d.safeParse(e)}function E(e){return m.parse(e)}function v(e){return m.safeParse(e)}var f=class extends DatabaseError{migrationName;operation;constructor(n,i,t,o){let a=t==="up"?"MIGRATION_UP_FAILED":"MIGRATION_DOWN_FAILED";super(n,a,i),this.name="MigrationError",this.migrationName=i,this.operation=t,o&&(this.cause=o);}toJSON(){let n=this.cause instanceof Error?this.cause:void 0;return {...super.toJSON(),migrationName:this.migrationName,operation:this.operation,cause:n?.message}}};async function c(e){await e.schema.createTable("migrations").ifNotExists().addColumn("name","varchar(255)",n=>n.primaryKey()).addColumn("executed_at","timestamp",n=>n.notNull().defaultTo(sql`CURRENT_TIMESTAMP`)).execute();}function h(e){return "description"in e||"breaking"in e||"tags"in e}function M(e){return e instanceof Error?e.message:String(e)}function N(e){let n=new Set;for(let i of e){if(n.has(i.name))throw new BadRequestError(`Duplicate migration name: ${i.name}`);n.add(i.name);}}var p=class{constructor(n,i,t={}){this.db=n;this.migrations=i;let o=d.safeParse(t);if(!o.success)throw new BadRequestError(`Invalid migration runner options: ${o.error.message}`);this.logger=t.logger??silentLogger,this.options={dryRun:o.data.dryRun,logger:this.logger,useTransactions:o.data.useTransactions,stopOnError:o.data.stopOnError,verbose:o.data.verbose},N(i);}logger;options;async getExecutedMigrations(){return await c(this.db),(await this.db.selectFrom("migrations").select("name").orderBy("executed_at","asc").execute()).map(i=>i.name)}async markAsExecuted(n){await this.db.insertInto("migrations").values({name:n}).execute();}async markAsRolledBack(n){await this.db.deleteFrom("migrations").where("name","=",n).execute();}logMigrationMeta(n){if(!this.options.verbose||!h(n))return;let i=n;if(i.description&&this.logger.info(` Description: ${i.description}`),i.breaking&&this.logger.warn(" BREAKING CHANGE - Review carefully before proceeding"),i.tags&&i.tags.length>0&&this.logger.info(` Tags: ${i.tags.join(", ")}`),i.estimatedDuration){let t=(i.estimatedDuration/1e3).toFixed(1);this.logger.info(` Estimated: ${t}s`);}}async executeMigration(n,i){let t=i==="up"?n.up:n.down;t&&(this.options.useTransactions?await this.db.transaction().execute(async o=>{await t(o);}):await t(this.db));}async up(){let n=Date.now(),i={executed:[],skipped:[],failed:[],duration:0,dryRun:this.options.dryRun};await c(this.db);let t=await this.getExecutedMigrations();if(this.migrations.filter(a=>!t.includes(a.name)).length===0)return this.logger.info("No pending migrations"),i.skipped=t,i.duration=Date.now()-n,i;this.options.dryRun&&this.logger.info("DRY RUN - No changes will be made");for(let a of this.migrations){if(t.includes(a.name)){this.logger.info(`${a.name} (already executed)`),i.skipped.push(a.name);continue}try{this.logger.info(`Running ${a.name}...`),this.logMigrationMeta(a),this.options.dryRun||(await this.executeMigration(a,"up"),await this.markAsExecuted(a.name)),this.logger.info(`${a.name} completed`),i.executed.push(a.name);}catch(g){let s=M(g);if(this.logger.error(`${a.name} failed: ${s}`),i.failed.push(a.name),this.options.stopOnError)throw new f(`Migration ${a.name} failed: ${s}`,a.name,"up",g instanceof Error?g:void 0)}}return this.options.dryRun?this.logger.info("Dry run completed - no changes made"):this.logger.info("All migrations completed successfully"),i.duration=Date.now()-n,i}async down(n=1){let i=Date.now(),t={executed:[],skipped:[],failed:[],duration:0,dryRun:this.options.dryRun};await c(this.db);let o=await this.getExecutedMigrations();if(o.length===0)return this.logger.warn("No executed migrations to rollback"),t.duration=Date.now()-i,t;let a=o.slice(-n).reverse();this.options.dryRun&&this.logger.info("DRY RUN - No changes will be made");for(let g of a){let s=this.migrations.find(u=>u.name===g);if(!s){this.logger.warn(`Migration ${g} not found in codebase`),t.skipped.push(g);continue}if(!s.down){this.logger.warn(`Migration ${g} has no down method - skipping`),t.skipped.push(g);continue}try{this.logger.info(`Rolling back ${g}...`),this.logMigrationMeta(s),this.options.dryRun||(await this.executeMigration(s,"down"),await this.markAsRolledBack(g)),this.logger.info(`${g} rolled back`),t.executed.push(g);}catch(u){let l=M(u);if(this.logger.error(`${g} rollback failed: ${l}`),t.failed.push(g),this.options.stopOnError)throw new f(`Rollback of ${g} failed: ${l}`,g,"down",u instanceof Error?u:void 0)}}return this.options.dryRun?this.logger.info("Dry run completed - no changes made"):this.logger.info("Rollback completed successfully"),t.duration=Date.now()-i,t}async status(){await c(this.db);let n=await this.getExecutedMigrations(),i=this.migrations.filter(t=>!n.includes(t.name)).map(t=>t.name);if(this.logger.info("Migration Status:"),this.logger.info(` Executed: ${n.length}`),this.logger.info(` Pending: ${i.length}`),this.logger.info(` Total: ${this.migrations.length}`),n.length>0){this.logger.info("Executed migrations:");for(let t of n){let o=this.migrations.find(a=>a.name===t);o&&h(o)&&o.description?this.logger.info(` ${t} - ${o.description}`):this.logger.info(` ${t}`);}}if(i.length>0){this.logger.info("Pending migrations:");for(let t of i){let o=this.migrations.find(a=>a.name===t);if(o&&h(o)){let a=o,g=a.breaking?" BREAKING":"",s=a.description?` - ${a.description}`:"";this.logger.info(` ${t}${s}${g}`);}else this.logger.info(` ${t}`);}}return {executed:n,pending:i,total:this.migrations.length}}async reset(){let n=Date.now();await c(this.db);let i=await this.getExecutedMigrations();if(i.length===0)return this.logger.warn("No migrations to reset"),{executed:[],skipped:[],failed:[],duration:Date.now()-n,dryRun:this.options.dryRun};if(this.logger.warn(`Resetting ${i.length} migrations...`),this.options.dryRun){this.logger.info("DRY RUN - Would rollback the following migrations:");for(let o of [...i].reverse())this.migrations.find(g=>g.name===o)?.down?this.logger.info(` ${o}`):this.logger.warn(` ${o} (no down method - would be skipped)`);return this.logger.info("Dry run completed - no changes made"),{executed:[],skipped:i,failed:[],duration:Date.now()-n,dryRun:true}}let t=await this.down(i.length);return this.logger.info("All migrations reset"),t}async upTo(n){let i=Date.now(),t={executed:[],skipped:[],failed:[],duration:0,dryRun:this.options.dryRun};await c(this.db);let o=await this.getExecutedMigrations(),a=this.migrations.findIndex(s=>s.name===n);if(a===-1)throw new NotFoundError("Migration",{name:n});let g=this.migrations.slice(0,a+1);this.options.dryRun&&this.logger.info("DRY RUN - No changes will be made");for(let s of g){if(o.includes(s.name)){this.logger.info(`${s.name} (already executed)`),t.skipped.push(s.name);continue}try{this.logger.info(`Running ${s.name}...`),this.logMigrationMeta(s),this.options.dryRun||(await this.executeMigration(s,"up"),await this.markAsExecuted(s.name)),this.logger.info(`${s.name} completed`),t.executed.push(s.name);}catch(u){let l=M(u);throw this.logger.error(`${s.name} failed: ${l}`),t.failed.push(s.name),new f(`Migration ${s.name} failed: ${l}`,s.name,"up",u instanceof Error?u:void 0)}}return this.options.dryRun?this.logger.info(`Dry run completed - would migrate up to ${n}`):this.logger.info(`Migrated up to ${n}`),t.duration=Date.now()-i,t}};function z(e,n,i){return new p(e,n,i)}function _(e,n,i){let t={name:e,up:n};return i!==void 0&&(t.down=i),t}function F(e,n){let i={name:e,up:n.up};return n.down!==void 0&&(i.down=n.down),n.description!==void 0&&(i.description=n.description),n.breaking!==void 0&&(i.breaking=n.breaking),n.estimatedDuration!==void 0&&(i.estimatedDuration=n.estimatedDuration),n.tags!==void 0&&(i.tags=n.tags),i}function j(e){return Object.entries(e).map(([n,i])=>{let t={name:n,up:i.up};return i.down!==void 0&&(t.down=i.down),i.description!==void 0&&(t.description=i.description),i.breaking!==void 0&&(t.breaking=i.breaking),i.estimatedDuration!==void 0&&(t.estimatedDuration=i.estimatedDuration),i.tags!==void 0&&(t.tags=i.tags),t})}async function G(e,n,i){return new p(e,n,i).up()}async function q(e,n,i=1,t){return new p(e,n,t).down(i)}async function C(e,n,i){return new p(e,n,i).status()}async function U(e,n,i){let t=new y(e,n,i);if(i?.plugins){for(let o of i.plugins)if(o.onInit){let a=o.onInit(t);a instanceof Promise&&await a;}}return t}var y=class extends p{plugins;constructor(n,i,t={}){super(n,i,t),this.plugins=t.plugins??[];}async runBeforeHooks(n,i){for(let t of this.plugins)t.beforeMigration&&await t.beforeMigration(n,i);}async runAfterHooks(n,i,t){for(let o of this.plugins)o.afterMigration&&await o.afterMigration(n,i,t);}async runErrorHooks(n,i,t){for(let o of this.plugins)o.onMigrationError&&await o.onMigrationError(n,i,t);}getPlugins(){return [...this.plugins]}};function H(e=silentLogger){return {name:"@kysera/migrations/logging",version:"0.5.1",beforeMigration(n,i){e.info(`Starting ${i} for ${n.name}`);},afterMigration(n,i,t){e.info(`Completed ${i} for ${n.name} in ${t}ms`);},onMigrationError(n,i,t){let o=t instanceof Error?t.message:String(t);e.error(`Error during ${i} for ${n.name}: ${o}`);}}}function Y(){let e=[];return {name:"@kysera/migrations/metrics",version:"0.5.1",afterMigration(n,i,t){e.push({name:n.name,operation:i,duration:t,success:true});},onMigrationError(n,i){e.push({name:n.name,operation:i,duration:0,success:false});},getMetrics(){return {migrations:[...e]}}}}export{m as MigrationDefinitionSchema,f as MigrationError,x as MigrationPluginOptionsSchema,D as MigrationPluginSchema,P as MigrationResultSchema,p as MigrationRunner,d as MigrationRunnerOptionsSchema,y as MigrationRunnerWithPlugins,B as MigrationRunnerWithPluginsOptionsSchema,b as MigrationStatusSchema,H as createLoggingPlugin,Y as createMetricsPlugin,_ as createMigration,z as createMigrationRunner,U as createMigrationRunnerWithPlugins,F as createMigrationWithMeta,j as defineMigrations,C as getMigrationStatus,E as parseMigrationDefinition,k as parseMigrationRunnerOptions,q as rollbackMigrations,G as runMigrations,v as safeParseMigrationDefinition,O as safeParseMigrationRunnerOptions,c as setupMigrations};//# sourceMappingURL=index.js.map
|
|
15
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":["setupMigrations","db","col","sql","MigrationRunner","migrations","options","r","name","executed","m","migration","error","steps","toRollback","pending","targetName","targetIndex","migrationsToRun","createMigrationRunner","createMigration","up","down"],"mappings":"yBAkDA,eAAsBA,CAAAA,CAAgBC,EAAgC,CACpE,MAAMA,CAAAA,CAAG,MAAA,CACN,YAAY,YAAY,CAAA,CACxB,WAAA,EAAY,CACZ,UAAU,MAAA,CAAQ,cAAA,CAAgBC,CAAAA,EAAOA,CAAAA,CAAI,YAAY,CAAA,CACzD,SAAA,CAAU,aAAA,CAAe,YAAaA,CAAAA,EACrCA,CAAAA,CAAI,OAAA,EAAQ,CAAE,UAAUC,GAAAA,CAAAA,iBAAAA,CAAsB,CAChD,EACC,OAAA,GACL,CAKO,IAAMC,CAAAA,CAAN,KAAsB,CAG3B,YACUH,CAAAA,CACAI,CAAAA,CACAC,CAAAA,CAAkC,GAC1C,CAHQ,IAAA,CAAA,EAAA,CAAAL,CAAAA,CACA,IAAA,CAAA,UAAA,CAAAI,EACA,IAAA,CAAA,OAAA,CAAAC,CAAAA,CAER,KAAK,MAAA,CAASA,CAAAA,CAAQ,QAAU,OAAA,CAAQ,IAC1C,CARQ,MAAA,CAaR,MAAM,qBAAA,EAA2C,CAO/C,OAAA,CANa,MAAM,KAAK,EAAA,CACrB,UAAA,CAAW,YAAmB,CAAA,CAC9B,OAAO,MAAa,CAAA,CACpB,QAAQ,aAAA,CAAsB,KAAK,EACnC,OAAA,EAAQ,EAEC,GAAA,CAAKC,CAAAA,EAAWA,EAAE,IAAI,CACpC,CAKA,MAAM,eAAeC,CAAAA,CAA6B,CAChD,MAAM,IAAA,CAAK,GACR,UAAA,CAAW,YAAmB,EAC9B,MAAA,CAAO,CAAE,KAAAA,CAAK,CAAQ,CAAA,CACtB,OAAA,GACL,CAKA,MAAM,gBAAA,CAAiBA,CAAAA,CAA6B,CAClD,MAAM,IAAA,CAAK,EAAA,CACR,UAAA,CAAW,YAAmB,CAAA,CAC9B,KAAA,CAAM,OAAe,GAAA,CAAKA,CAAI,EAC9B,OAAA,GACL,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AAK,MAAA,CAAO,CAAA,OAAA,EAAKD,CAAAA,CAAU,IAAI,CAAA,SAAA,EAAYC,CAAK,CAAA,CAAE,CAAA,CAC5CA,CACR,CACF,CAEA,IAAA,CAAK,MAAA,CAAO;AAAA,sBAAA,EAAsBI,CAAU,CAAA,CAAE,EAChD,CACF,EAKO,SAASG,CAAAA,CACdlB,CAAAA,CACAI,CAAAA,CACAC,CAAAA,CACiB,CACjB,OAAO,IAAIF,EAAgBH,CAAAA,CAAII,CAAAA,CAAYC,CAAO,CACpD,CAKO,SAASc,CAAAA,CACdZ,EACAa,CAAAA,CACAC,CAAAA,CACW,CACX,IAAMX,CAAAA,CAAuB,CAAE,IAAA,CAAAH,CAAAA,CAAM,EAAA,CAAAa,CAAG,EACxC,OAAIC,CAAAA,GAAS,SACXX,CAAAA,CAAU,IAAA,CAAOW,GAEZX,CACT","file":"index.js","sourcesContent":["import type { Kysely } from 'kysely'\nimport { sql } from 'kysely'\n\n/**\n * Migration interface\n */\nexport interface Migration {\n /** Unique migration name (e.g., '001_create_users') */\n name: string\n /** Migration up function - creates/modifies schema */\n up: (db: Kysely<any>) => Promise<void>\n /** Optional migration down function - reverts changes */\n down?: (db: Kysely<any>) => Promise<void>\n}\n\n/**\n * Migration metadata for tracking purposes\n */\nexport interface MigrationWithMeta extends Migration {\n /** Human-readable description */\n description?: string\n /** Whether this is a breaking change */\n breaking?: boolean\n /** Estimated duration in milliseconds */\n estimatedDuration?: number\n}\n\n/**\n * Migration status result\n */\nexport interface MigrationStatus {\n /** List of executed migration names */\n executed: string[]\n /** List of pending migration names */\n pending: string[]\n}\n\n/**\n * Migration runner options\n */\nexport interface MigrationRunnerOptions {\n /** Enable dry run mode (don't execute, just show what would run) */\n dryRun?: boolean\n /** Logger function */\n logger?: (message: string) => void\n}\n\n/**\n * Setup migrations table in database\n */\nexport async function setupMigrations(db: Kysely<any>): Promise<void> {\n await db.schema\n .createTable('migrations')\n .ifNotExists()\n .addColumn('name', 'varchar(255)', col => col.primaryKey())\n .addColumn('executed_at', 'timestamp', col =>\n col.notNull().defaultTo(sql`CURRENT_TIMESTAMP`)\n )\n .execute()\n}\n\n/**\n * Migration runner with state tracking\n */\nexport class MigrationRunner {\n private logger: (message: string) => void\n\n constructor(\n private db: Kysely<any>,\n private migrations: Migration[],\n private options: MigrationRunnerOptions = {}\n ) {\n this.logger = options.logger || console.log\n }\n\n /**\n * Get list of executed migrations from database\n */\n async getExecutedMigrations(): Promise<string[]> {\n const rows = await this.db\n .selectFrom('migrations' as any)\n .select('name' as any)\n .orderBy('executed_at' as any, 'asc')\n .execute()\n\n return rows.map((r: any) => r.name)\n }\n\n /**\n * Mark a migration as executed\n */\n async markAsExecuted(name: string): Promise<void> {\n await this.db\n .insertInto('migrations' as any)\n .values({ name } as any)\n .execute()\n }\n\n /**\n * Mark a migration as rolled back (remove from executed list)\n */\n async markAsRolledBack(name: string): Promise<void> {\n await this.db\n .deleteFrom('migrations' as any)\n .where('name' as any, '=', name)\n .execute()\n }\n\n /**\n * Run all pending migrations\n */\n async up(): Promise<void> {\n await setupMigrations(this.db)\n const executed = await this.getExecutedMigrations()\n\n const pending = this.migrations.filter(m => !executed.includes(m.name))\n\n if (pending.length === 0) {\n this.logger('✅ No pending migrations')\n return\n }\n\n if (this.options.dryRun) {\n this.logger('\\n🔍 DRY RUN - No changes will be made\\n')\n }\n\n for (const migration of this.migrations) {\n if (executed.includes(migration.name)) {\n this.logger(`✓ ${migration.name} (already executed)`)\n continue\n }\n\n try {\n this.logger(`↑ Running ${migration.name}...`)\n\n if (!this.options.dryRun) {\n await migration.up(this.db)\n await this.markAsExecuted(migration.name)\n }\n\n this.logger(`✓ ${migration.name} completed`)\n } catch (error) {\n this.logger(`✗ ${migration.name} failed: ${error}`)\n throw error\n }\n }\n\n if (!this.options.dryRun) {\n this.logger('\\n✅ All migrations completed successfully')\n }\n }\n\n /**\n * Rollback last N migrations\n */\n async down(steps = 1): Promise<void> {\n const executed = await this.getExecutedMigrations()\n\n if (executed.length === 0) {\n this.logger('⚠️ No executed migrations to rollback')\n return\n }\n\n const toRollback = executed.slice(-steps).reverse()\n\n if (this.options.dryRun) {\n this.logger('\\n🔍 DRY RUN - No changes will be made\\n')\n }\n\n for (const name of toRollback) {\n const migration = this.migrations.find(m => m.name === name)\n\n if (!migration) {\n this.logger(`⚠️ Migration ${name} not found in codebase`)\n continue\n }\n\n if (!migration.down) {\n this.logger(`⚠️ Migration ${name} has no down method`)\n continue\n }\n\n try {\n this.logger(`↓ Rolling back ${name}...`)\n\n if (!this.options.dryRun) {\n await migration.down(this.db)\n await this.markAsRolledBack(name)\n }\n\n this.logger(`✓ ${name} rolled back`)\n } catch (error) {\n this.logger(`✗ ${name} rollback failed: ${error}`)\n throw error\n }\n }\n\n if (!this.options.dryRun) {\n this.logger('\\n✅ Rollback completed successfully')\n }\n }\n\n /**\n * Show migration status\n */\n async status(): Promise<MigrationStatus> {\n await setupMigrations(this.db)\n const executed = await this.getExecutedMigrations()\n const pending = this.migrations\n .filter(m => !executed.includes(m.name))\n .map(m => m.name)\n\n this.logger('\\n📊 Migration Status:')\n this.logger(` ✅ Executed: ${executed.length}`)\n this.logger(` ⏳ Pending: ${pending.length}`)\n\n if (executed.length > 0) {\n this.logger('\\nExecuted migrations:')\n executed.forEach(name => { this.logger(` ✓ ${name}`); })\n }\n\n if (pending.length > 0) {\n this.logger('\\nPending migrations:')\n pending.forEach(name => { this.logger(` - ${name}`); })\n }\n\n return { executed, pending }\n }\n\n /**\n * Reset all migrations (dangerous!)\n */\n async reset(): Promise<void> {\n if (this.options.dryRun) {\n this.logger('\\n🔍 DRY RUN - Would rollback all migrations')\n return\n }\n\n const executed = await this.getExecutedMigrations()\n this.logger(`\\n⚠️ Resetting ${executed.length} migrations...`)\n\n await this.down(executed.length)\n this.logger('\\n✅ All migrations reset')\n }\n\n /**\n * Run migrations up to a specific migration (inclusive)\n */\n async upTo(targetName: string): Promise<void> {\n await setupMigrations(this.db)\n const executed = await this.getExecutedMigrations()\n\n const targetIndex = this.migrations.findIndex(m => m.name === targetName)\n if (targetIndex === -1) {\n throw new Error(`Migration ${targetName} not found`)\n }\n\n const migrationsToRun = this.migrations.slice(0, targetIndex + 1)\n\n for (const migration of migrationsToRun) {\n if (executed.includes(migration.name)) {\n this.logger(`✓ ${migration.name} (already executed)`)\n continue\n }\n\n try {\n this.logger(`↑ Running ${migration.name}...`)\n\n if (!this.options.dryRun) {\n await migration.up(this.db)\n await this.markAsExecuted(migration.name)\n }\n\n this.logger(`✓ ${migration.name} completed`)\n } catch (error) {\n this.logger(`✗ ${migration.name} failed: ${error}`)\n throw error\n }\n }\n\n this.logger(`\\n✅ Migrated up to ${targetName}`)\n }\n}\n\n/**\n * Create a migration runner instance\n */\nexport function createMigrationRunner(\n db: Kysely<any>,\n migrations: Migration[],\n options?: MigrationRunnerOptions\n): MigrationRunner {\n return new MigrationRunner(db, migrations, options)\n}\n\n/**\n * Helper to create a simple migration\n */\nexport function createMigration(\n name: string,\n up: (db: Kysely<any>) => Promise<void>,\n down?: (db: Kysely<any>) => Promise<void>\n): Migration {\n const migration: Migration = { name, up }\n if (down !== undefined) {\n migration.down = down\n }\n return migration\n}"]}
|
|
1
|
+
{"version":3,"sources":["../src/schemas.ts","../src/index.ts"],"names":["MigrationRunnerOptionsSchema","z","MigrationDefinitionSchema","MigrationPluginOptionsSchema","MigrationPluginSchema","MigrationStatusSchema","MigrationResultSchema","MigrationRunnerWithPluginsOptionsSchema","parseMigrationRunnerOptions","options","safeParseMigrationRunnerOptions","parseMigrationDefinition","definition","safeParseMigrationDefinition","MigrationError","DatabaseError","message","migrationName","operation","cause","code","causeError","setupMigrations","db","col","sql","hasMeta","migration","formatError","error","validateMigrations","migrations","names","BadRequestError","MigrationRunner","parsed","silentLogger","r","name","meta","seconds","fn","trx","startTime","result","executed","m","errorMsg","steps","toRollback","pending","suffix","desc","targetName","targetIndex","NotFoundError","migrationsToRun","createMigrationRunner","createMigration","up","down","createMigrationWithMeta","defineMigrations","definitions","def","runMigrations","rollbackMigrations","getMigrationStatus","createMigrationRunnerWithPlugins","runner","MigrationRunnerWithPlugins","plugin","duration","createLoggingPlugin","logger","createMetricsPlugin","metrics"],"mappings":"2NAUO,IAAMA,CAAAA,CAA+BC,GAAAA,CAAE,MAAA,CAAO,CAEnD,MAAA,CAAQA,GAAAA,CAAE,OAAA,EAAQ,CAAE,OAAA,CAAQ,KAAK,EAEjC,MAAA,CAAQA,GAAAA,CAAE,GAAA,EAAI,CAAE,QAAA,EAAS,CAEzB,eAAA,CAAiBA,GAAAA,CAAE,OAAA,EAAQ,CAAE,OAAA,CAAQ,KAAK,CAAA,CAE1C,WAAA,CAAaA,GAAAA,CAAE,OAAA,EAAQ,CAAE,OAAA,CAAQ,IAAI,CAAA,CAErC,OAAA,CAASA,GAAAA,CAAE,OAAA,EAAQ,CAAE,OAAA,CAAQ,IAAI,CACnC,CAAC,CAAA,CAUYC,CAAAA,CAA4BD,GAAAA,CAAE,MAAA,CAAO,CAEhD,IAAA,CAAMA,GAAAA,CAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAA,CAAG,4BAA4B,CAAA,CAEpD,WAAA,CAAaA,GAAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS,CAEjC,QAAA,CAAUA,GAAAA,CAAE,OAAA,EAAQ,CAAE,OAAA,CAAQ,KAAK,CAAA,CAEnC,IAAA,CAAMA,GAAAA,CAAE,KAAA,CAAMA,GAAAA,CAAE,MAAA,EAAQ,CAAA,CAAE,OAAA,CAAQ,EAAE,CAAA,CAEpC,kBAAmBA,GAAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAChC,CAAC,CAAA,CAUYE,CAAAA,CAA+BF,GAAAA,CAAE,MAAA,CAAO,CAEnD,MAAA,CAAQA,GAAAA,CAAE,GAAA,EAAI,CAAE,QAAA,EAClB,CAAC,CAAA,CAUYG,CAAAA,CAAwBH,GAAAA,CAAE,MAAA,CAAO,CAE5C,IAAA,CAAMA,GAAAA,CAAE,MA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gBAAA,CAAiB7C,CAAAA,CAAWT,CAAAA,CAAWW,CAAAA,CAAO,CAC5C,IAAMb,EAAUa,CAAAA,YAAiB,KAAA,CAAQA,CAAAA,CAAM,OAAA,CAAU,MAAA,CAAOA,CAAK,CAAA,CACrE6C,CAAAA,CAAO,KAAA,CAAM,CAAA,aAAA,EAAgBxD,CAAS,CAAA,KAAA,EAAQS,CAAAA,CAAU,IAAI,CAAA,EAAA,EAAKX,CAAO,EAAE,EAC5E,CACF,CACF,CAMO,SAAS2D,CAAAA,EAEd,CACA,IAAMC,CAAAA,CAA0F,EAAC,CAEjG,OAAO,CACL,IAAA,CAAM,4BAAA,CACN,OAAA,CAAS,OAAA,CACT,cAAA,CAAejD,CAAAA,CAAWT,CAAAA,CAAWsD,CAAAA,CAAU,CAC7CI,CAAAA,CAAQ,IAAA,CAAK,CAAE,IAAA,CAAMjD,CAAAA,CAAU,IAAA,CAAM,SAAA,CAAAT,CAAAA,CAAW,QAAA,CAAAsD,CAAAA,CAAU,QAAS,IAAK,CAAC,EAC3E,CAAA,CACA,gBAAA,CAAiB7C,CAAAA,CAAWT,CAAAA,CAAW,CACrC0D,CAAAA,CAAQ,IAAA,CAAK,CAAE,IAAA,CAAMjD,CAAAA,CAAU,IAAA,CAAM,SAAA,CAAAT,CAAAA,CAAW,SAAU,CAAA,CAAG,OAAA,CAAS,KAAM,CAAC,EAC/E,CAAA,CACA,UAAA,EAAa,CACX,OAAO,CAAE,UAAA,CAAY,CAAC,GAAG0D,CAAO,CAAE,CACpC,CACF,CACF","file":"index.js","sourcesContent":["import { z } from 'zod';\n\n// ============================================================================\n// Migration Runner Options Schema\n// ============================================================================\n\n/**\n * Schema for MigrationRunnerOptions\n * Validates configuration options for the migration runner\n */\nexport const MigrationRunnerOptionsSchema = z.object({\n /** Enable dry run mode (preview only, no changes) */\n dryRun: z.boolean().default(false),\n /** Logger function - validated as any since function schemas are complex in Zod v4 */\n logger: z.any().optional(),\n /** Wrap each migration in a transaction */\n useTransactions: z.boolean().default(false),\n /** Stop on first error */\n stopOnError: z.boolean().default(true),\n /** Show detailed metadata in logs */\n verbose: z.boolean().default(true),\n});\n\n// ============================================================================\n// Migration Definition Schema\n// ============================================================================\n\n/**\n * Schema for MigrationDefinition\n * Validates migration definition objects used with defineMigrations()\n */\nexport const MigrationDefinitionSchema = z.object({\n /** Migration name - must be non-empty */\n name: z.string().min(1, 'Migration name is required'),\n /** Human-readable description shown during migration */\n description: z.string().optional(),\n /** Whether this is a breaking change - shows warning before execution */\n breaking: z.boolean().default(false),\n /** Tags for categorization (e.g., ['schema', 'data', 'index']) */\n tags: z.array(z.string()).default([]),\n /** Estimated duration as human-readable string (e.g., '30s', '2m') */\n estimatedDuration: z.string().optional(),\n});\n\n// ============================================================================\n// Migration Plugin Options Schema\n// ============================================================================\n\n/**\n * Schema for MigrationPluginOptions\n * Validates options passed to migration plugins\n */\nexport const MigrationPluginOptionsSchema = z.object({\n /** Optional logger for the plugin */\n logger: z.any().optional(),\n});\n\n// ============================================================================\n// Migration Plugin Schema\n// ============================================================================\n\n/**\n * Schema for MigrationPlugin\n * Validates migration plugin structure\n */\nexport const MigrationPluginSchema = z.object({\n /** Plugin name */\n name: z.string().min(1, 'Plugin name is required'),\n /** Plugin version */\n version: z.string().min(1, 'Plugin version is required'),\n /** Called once when the runner is initialized */\n onInit: z.any().optional(),\n /** Called before migration execution */\n beforeMigration: z.any().optional(),\n /** Called after successful migration execution */\n afterMigration: z.any().optional(),\n /** Called on migration error */\n onMigrationError: z.any().optional(),\n});\n\n// ============================================================================\n// Migration Status Schema\n// ============================================================================\n\n/**\n * Schema for MigrationStatus\n * Validates migration status results\n */\nexport const MigrationStatusSchema = z.object({\n /** List of executed migration names */\n executed: z.array(z.string()),\n /** List of pending migration names */\n pending: z.array(z.string()),\n /** Total migration count */\n total: z.number().int().nonnegative(),\n});\n\n// ============================================================================\n// Migration Result Schema\n// ============================================================================\n\n/**\n * Schema for MigrationResult\n * Validates results from migration runs\n */\nexport const MigrationResultSchema = z.object({\n /** Successfully executed migrations */\n executed: z.array(z.string()),\n /** Migrations that were skipped (already executed) */\n skipped: z.array(z.string()),\n /** Migrations that failed */\n failed: z.array(z.string()),\n /** Total duration in milliseconds */\n duration: z.number().nonnegative(),\n /** Whether the run was in dry-run mode */\n dryRun: z.boolean(),\n});\n\n// ============================================================================\n// Extended Runner Options Schema (with plugins)\n// ============================================================================\n\n/**\n * Schema for MigrationRunnerWithPluginsOptions\n * Extends MigrationRunnerOptionsSchema with plugin support\n */\nexport const MigrationRunnerWithPluginsOptionsSchema = MigrationRunnerOptionsSchema.extend({\n /** Plugins to apply */\n plugins: z.array(MigrationPluginSchema).optional(),\n});\n\n// ============================================================================\n// Type Exports\n// ============================================================================\n\n/** Input type for MigrationRunnerOptions - before defaults are applied */\nexport type MigrationRunnerOptionsInput = z.input<typeof MigrationRunnerOptionsSchema>;\n\n/** Output type for MigrationRunnerOptions - after defaults are applied */\nexport type MigrationRunnerOptionsOutput = z.output<typeof MigrationRunnerOptionsSchema>;\n\n/** Input type for MigrationDefinition - before defaults are applied */\nexport type MigrationDefinitionInput = z.input<typeof MigrationDefinitionSchema>;\n\n/** Output type for MigrationDefinition - after defaults are applied */\nexport type MigrationDefinitionOutput = z.output<typeof MigrationDefinitionSchema>;\n\n/** Input type for MigrationPluginOptions */\nexport type MigrationPluginOptionsInput = z.input<typeof MigrationPluginOptionsSchema>;\n\n/** Output type for MigrationPluginOptions */\nexport type MigrationPluginOptionsOutput = z.output<typeof MigrationPluginOptionsSchema>;\n\n/** Input type for MigrationPlugin */\nexport type MigrationPluginInput = z.input<typeof MigrationPluginSchema>;\n\n/** Output type for MigrationPlugin */\nexport type MigrationPluginOutput = z.output<typeof MigrationPluginSchema>;\n\n/** Type for MigrationStatus */\nexport type MigrationStatusType = z.infer<typeof MigrationStatusSchema>;\n\n/** Type for MigrationResult */\nexport type MigrationResultType = z.infer<typeof MigrationResultSchema>;\n\n/** Input type for MigrationRunnerWithPluginsOptions */\nexport type MigrationRunnerWithPluginsOptionsInput = z.input<typeof MigrationRunnerWithPluginsOptionsSchema>;\n\n/** Output type for MigrationRunnerWithPluginsOptions */\nexport type MigrationRunnerWithPluginsOptionsOutput = z.output<typeof MigrationRunnerWithPluginsOptionsSchema>;\n\n// ============================================================================\n// Validation Helpers\n// ============================================================================\n\n/**\n * Validate and parse MigrationRunnerOptions with defaults\n */\nexport function parseMigrationRunnerOptions(\n options: unknown\n): MigrationRunnerOptionsOutput {\n return MigrationRunnerOptionsSchema.parse(options);\n}\n\n/**\n * Safely validate MigrationRunnerOptions without throwing\n * Returns result with success boolean and either data or error\n */\nexport function safeParseMigrationRunnerOptions(options: unknown) {\n return MigrationRunnerOptionsSchema.safeParse(options);\n}\n\n/**\n * Validate and parse MigrationDefinition with defaults\n */\nexport function parseMigrationDefinition(\n definition: unknown\n): MigrationDefinitionOutput {\n return MigrationDefinitionSchema.parse(definition);\n}\n\n/**\n * Safely validate MigrationDefinition without throwing\n * Returns result with success boolean and either data or error\n */\nexport function safeParseMigrationDefinition(definition: unknown) {\n return MigrationDefinitionSchema.safeParse(definition);\n}\n","import type { Kysely } from 'kysely';\nimport { sql } from 'kysely';\nimport type { KyseraLogger } from '@kysera/core';\nimport { DatabaseError, NotFoundError, BadRequestError, silentLogger } from '@kysera/core';\n\n// ============================================================================\n// Schema Exports\n// ============================================================================\n\nexport {\n // Schemas\n MigrationRunnerOptionsSchema,\n MigrationDefinitionSchema,\n MigrationPluginOptionsSchema,\n MigrationPluginSchema,\n MigrationStatusSchema,\n MigrationResultSchema,\n MigrationRunnerWithPluginsOptionsSchema,\n // Type exports\n type MigrationRunnerOptionsInput,\n type MigrationRunnerOptionsOutput,\n type MigrationDefinitionInput,\n type MigrationDefinitionOutput,\n type MigrationPluginOptionsInput,\n type MigrationPluginOptionsOutput,\n type MigrationPluginInput,\n type MigrationPluginOutput,\n type MigrationStatusType,\n type MigrationResultType,\n type MigrationRunnerWithPluginsOptionsInput,\n type MigrationRunnerWithPluginsOptionsOutput,\n // Validation helpers\n parseMigrationRunnerOptions,\n safeParseMigrationRunnerOptions,\n parseMigrationDefinition,\n safeParseMigrationDefinition,\n} from './schemas.js';\n\nimport { MigrationRunnerOptionsSchema } from './schemas.js';\n\n// ============================================================================\n// Types and Interfaces\n// ============================================================================\n\n/**\n * Migration interface - the core building block\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport interface Migration<DB = unknown> {\n /** Unique migration name (e.g., '001_create_users') */\n name: string;\n /** Migration up function - creates/modifies schema */\n up: (db: Kysely<DB>) => Promise<void>;\n /** Optional migration down function - reverts changes */\n down?: (db: Kysely<DB>) => Promise<void>;\n}\n\n/**\n * Migration with metadata for enhanced logging and tracking\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport interface MigrationWithMeta<DB = unknown> extends Migration<DB> {\n /** Human-readable description shown during migration */\n description?: string;\n /** Whether this is a breaking change - shows warning before execution */\n breaking?: boolean;\n /** Estimated duration in milliseconds for progress indication */\n estimatedDuration?: number;\n /** Tags for categorization (e.g., ['schema', 'data', 'index']) */\n tags?: string[];\n}\n\n/**\n * Migration status result\n */\nexport interface MigrationStatus {\n /** List of executed migration names */\n executed: string[];\n /** List of pending migration names */\n pending: string[];\n /** Total migration count */\n total: number;\n}\n\n/**\n * Migration runner options\n */\nexport interface MigrationRunnerOptions {\n /** Enable dry run mode (preview only, no changes) */\n dryRun?: boolean;\n /**\n * Logger for migration operations.\n * Uses KyseraLogger interface from @kysera/core.\n *\n * @default silentLogger (no output)\n */\n logger?: KyseraLogger;\n /** Wrap each migration in a transaction (default: false) */\n useTransactions?: boolean;\n /** Stop on first error (default: true) */\n stopOnError?: boolean;\n /** Show detailed metadata in logs (default: true) */\n verbose?: boolean;\n}\n\n/**\n * Object-based migration definition for Level 2 DX\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport interface MigrationDefinition<DB = unknown> {\n up: (db: Kysely<DB>) => Promise<void>;\n down?: (db: Kysely<DB>) => Promise<void>;\n description?: string;\n breaking?: boolean;\n estimatedDuration?: number;\n tags?: string[];\n}\n\n/**\n * Migration definitions map for defineMigrations()\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport type MigrationDefinitions<DB = unknown> = Record<string, MigrationDefinition<DB>>;\n\n/**\n * Result of a migration run\n */\nexport interface MigrationResult {\n /** Successfully executed migrations */\n executed: string[];\n /** Migrations that were skipped (already executed) */\n skipped: string[];\n /** Migrations that failed */\n failed: string[];\n /** Total duration in milliseconds */\n duration: number;\n /** Whether the run was in dry-run mode */\n dryRun: boolean;\n}\n\n// ============================================================================\n// Error Classes (extending @kysera/core)\n// ============================================================================\n\n/** Error codes for migration operations */\nexport type MigrationErrorCode = 'MIGRATION_UP_FAILED' | 'MIGRATION_DOWN_FAILED' | 'MIGRATION_VALIDATION_FAILED';\n\n/**\n * Migration-specific error extending DatabaseError from @kysera/core\n * Provides structured error information with code, migration context, and cause tracking\n */\nexport class MigrationError extends DatabaseError {\n public readonly migrationName: string;\n public readonly operation: 'up' | 'down';\n\n constructor(\n message: string,\n migrationName: string,\n operation: 'up' | 'down',\n cause?: Error\n ) {\n const code: MigrationErrorCode = operation === 'up' ? 'MIGRATION_UP_FAILED' : 'MIGRATION_DOWN_FAILED';\n super(message, code, migrationName);\n this.name = 'MigrationError';\n this.migrationName = migrationName;\n this.operation = operation;\n if (cause) {\n this.cause = cause;\n }\n }\n\n override toJSON(): Record<string, unknown> {\n const causeError = this.cause instanceof Error ? this.cause : undefined;\n return {\n ...super.toJSON(),\n migrationName: this.migrationName,\n operation: this.operation,\n cause: causeError?.message,\n };\n }\n}\n\n// ============================================================================\n// Setup Functions\n// ============================================================================\n\n/**\n * Setup migrations table in database\n * Idempotent - safe to run multiple times\n * Uses Kysely<unknown> as migrations work with any database schema\n */\nexport async function setupMigrations(db: Kysely<unknown>): Promise<void> {\n await db.schema\n .createTable('migrations')\n .ifNotExists()\n .addColumn('name', 'varchar(255)', (col) => col.primaryKey())\n .addColumn('executed_at', 'timestamp', (col) => col.notNull().defaultTo(sql`CURRENT_TIMESTAMP`))\n .execute();\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Check if migration has metadata\n * Type guard to narrow Migration<DB> to MigrationWithMeta<DB>\n */\nfunction hasMeta<DB>(migration: Migration<DB>): migration is MigrationWithMeta<DB> {\n return 'description' in migration || 'breaking' in migration || 'tags' in migration;\n}\n\n/**\n * Format error message for logging\n */\nfunction formatError(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n}\n\n/**\n * Validate migrations for duplicate names\n * @throws {BadRequestError} When duplicate migration names are found\n */\nfunction validateMigrations<DB>(migrations: Migration<DB>[]): void {\n const names = new Set<string>();\n for (const migration of migrations) {\n if (names.has(migration.name)) {\n throw new BadRequestError(`Duplicate migration name: ${migration.name}`);\n }\n names.add(migration.name);\n }\n}\n\n// ============================================================================\n// Migration Runner Class\n// ============================================================================\n\n/**\n * Migration runner with state tracking and metadata support\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport class MigrationRunner<DB = unknown> {\n private logger: KyseraLogger;\n private options: Required<Omit<MigrationRunnerOptions, 'logger'>> & { logger: KyseraLogger };\n\n constructor(\n private db: Kysely<DB>,\n private migrations: Migration<DB>[],\n options: MigrationRunnerOptions = {}\n ) {\n // Validate and apply defaults using Zod schema\n const parsed = MigrationRunnerOptionsSchema.safeParse(options);\n if (!parsed.success) {\n throw new BadRequestError(`Invalid migration runner options: ${parsed.error.message}`);\n }\n\n this.logger = options.logger ?? silentLogger;\n this.options = {\n dryRun: parsed.data.dryRun,\n logger: this.logger,\n useTransactions: parsed.data.useTransactions,\n stopOnError: parsed.data.stopOnError,\n verbose: parsed.data.verbose,\n };\n\n // Validate migrations on construction\n validateMigrations(migrations);\n }\n\n /**\n * Get list of executed migrations from database\n * Note: Uses type assertions for migrations table as it's not part of the user schema\n */\n async getExecutedMigrations(): Promise<string[]> {\n // Cast to any for migrations table operations - it's internal and not part of user schema\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await setupMigrations(this.db as any);\n\n // The migrations table is internal and not part of the generic DB schema\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const rows = await (this.db as any)\n .selectFrom('migrations')\n .select('name')\n .orderBy('executed_at', 'asc')\n .execute() as Array<{ name: string }>;\n\n return rows.map((r) => r.name);\n }\n\n /**\n * Mark a migration as executed\n * Note: Uses type assertions for migrations table as it's not part of the user schema\n */\n async markAsExecuted(name: string): Promise<void> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await (this.db as any)\n .insertInto('migrations')\n .values({ name })\n .execute();\n }\n\n /**\n * Mark a migration as rolled back (remove from executed list)\n * Note: Uses type assertions for migrations table as it's not part of the user schema\n */\n async markAsRolledBack(name: string): Promise<void> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await (this.db as any)\n .deleteFrom('migrations')\n .where('name', '=', name)\n .execute();\n }\n\n /**\n * Log migration metadata if available\n */\n private logMigrationMeta(migration: Migration<DB>): void {\n if (!this.options.verbose || !hasMeta(migration)) return;\n\n const meta = migration;\n\n if (meta.description) {\n this.logger.info(` Description: ${meta.description}`);\n }\n\n if (meta.breaking) {\n this.logger.warn(` BREAKING CHANGE - Review carefully before proceeding`);\n }\n\n if (meta.tags && meta.tags.length > 0) {\n this.logger.info(` Tags: ${meta.tags.join(', ')}`);\n }\n\n if (meta.estimatedDuration) {\n const seconds = (meta.estimatedDuration / 1000).toFixed(1);\n this.logger.info(` Estimated: ${seconds}s`);\n }\n }\n\n /**\n * Execute a single migration with optional transaction wrapping\n */\n private async executeMigration(\n migration: Migration<DB>,\n operation: 'up' | 'down'\n ): Promise<void> {\n const fn = operation === 'up' ? migration.up : migration.down;\n if (!fn) return;\n\n if (this.options.useTransactions) {\n await this.db.transaction().execute(async (trx) => {\n await fn(trx);\n });\n } else {\n await fn(this.db);\n }\n }\n\n /**\n * Run all pending migrations\n */\n async up(): Promise<MigrationResult> {\n const startTime = Date.now();\n const result: MigrationResult = {\n executed: [],\n skipped: [],\n failed: [],\n duration: 0,\n dryRun: this.options.dryRun,\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await setupMigrations(this.db as any);\n const executed = await this.getExecutedMigrations();\n\n const pending = this.migrations.filter((m) => !executed.includes(m.name));\n\n if (pending.length === 0) {\n this.logger.info('No pending migrations');\n result.skipped = executed;\n result.duration = Date.now() - startTime;\n return result;\n }\n\n if (this.options.dryRun) {\n this.logger.info('DRY RUN - No changes will be made');\n }\n\n for (const migration of this.migrations) {\n if (executed.includes(migration.name)) {\n this.logger.info(`${migration.name} (already executed)`);\n result.skipped.push(migration.name);\n continue;\n }\n\n try {\n this.logger.info(`Running ${migration.name}...`);\n this.logMigrationMeta(migration);\n\n if (!this.options.dryRun) {\n await this.executeMigration(migration, 'up');\n await this.markAsExecuted(migration.name);\n }\n\n this.logger.info(`${migration.name} completed`);\n result.executed.push(migration.name);\n } catch (error) {\n const errorMsg = formatError(error);\n this.logger.error(`${migration.name} failed: ${errorMsg}`);\n result.failed.push(migration.name);\n\n if (this.options.stopOnError) {\n throw new MigrationError(\n `Migration ${migration.name} failed: ${errorMsg}`,\n migration.name,\n 'up',\n error instanceof Error ? error : undefined\n );\n }\n }\n }\n\n if (!this.options.dryRun) {\n this.logger.info('All migrations completed successfully');\n } else {\n this.logger.info('Dry run completed - no changes made');\n }\n\n result.duration = Date.now() - startTime;\n return result;\n }\n\n /**\n * Rollback last N migrations\n */\n async down(steps = 1): Promise<MigrationResult> {\n const startTime = Date.now();\n const result: MigrationResult = {\n executed: [],\n skipped: [],\n failed: [],\n duration: 0,\n dryRun: this.options.dryRun,\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await setupMigrations(this.db as any);\n const executed = await this.getExecutedMigrations();\n\n if (executed.length === 0) {\n this.logger.warn('No executed migrations to rollback');\n result.duration = Date.now() - startTime;\n return result;\n }\n\n const toRollback = executed.slice(-steps).reverse();\n\n if (this.options.dryRun) {\n this.logger.info('DRY RUN - No changes will be made');\n }\n\n for (const name of toRollback) {\n const migration = this.migrations.find((m) => m.name === name);\n\n if (!migration) {\n this.logger.warn(`Migration ${name} not found in codebase`);\n result.skipped.push(name);\n continue;\n }\n\n if (!migration.down) {\n this.logger.warn(`Migration ${name} has no down method - skipping`);\n result.skipped.push(name);\n continue;\n }\n\n try {\n this.logger.info(`Rolling back ${name}...`);\n this.logMigrationMeta(migration);\n\n if (!this.options.dryRun) {\n await this.executeMigration(migration, 'down');\n await this.markAsRolledBack(name);\n }\n\n this.logger.info(`${name} rolled back`);\n result.executed.push(name);\n } catch (error) {\n const errorMsg = formatError(error);\n this.logger.error(`${name} rollback failed: ${errorMsg}`);\n result.failed.push(name);\n\n if (this.options.stopOnError) {\n throw new MigrationError(\n `Rollback of ${name} failed: ${errorMsg}`,\n name,\n 'down',\n error instanceof Error ? error : undefined\n );\n }\n }\n }\n\n if (!this.options.dryRun) {\n this.logger.info('Rollback completed successfully');\n } else {\n this.logger.info('Dry run completed - no changes made');\n }\n\n result.duration = Date.now() - startTime;\n return result;\n }\n\n /**\n * Show migration status\n */\n async status(): Promise<MigrationStatus> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await setupMigrations(this.db as any);\n const executed = await this.getExecutedMigrations();\n const pending = this.migrations.filter((m) => !executed.includes(m.name)).map((m) => m.name);\n\n this.logger.info('Migration Status:');\n this.logger.info(` Executed: ${executed.length}`);\n this.logger.info(` Pending: ${pending.length}`);\n this.logger.info(` Total: ${this.migrations.length}`);\n\n if (executed.length > 0) {\n this.logger.info('Executed migrations:');\n for (const name of executed) {\n const migration = this.migrations.find((m) => m.name === name);\n if (migration && hasMeta(migration) && (migration as MigrationWithMeta).description) {\n this.logger.info(` ${name} - ${(migration as MigrationWithMeta).description}`);\n } else {\n this.logger.info(` ${name}`);\n }\n }\n }\n\n if (pending.length > 0) {\n this.logger.info('Pending migrations:');\n for (const name of pending) {\n const migration = this.migrations.find((m) => m.name === name);\n if (migration && hasMeta(migration)) {\n const meta = migration as MigrationWithMeta;\n const suffix = meta.breaking ? ' BREAKING' : '';\n const desc = meta.description ? ` - ${meta.description}` : '';\n this.logger.info(` ${name}${desc}${suffix}`);\n } else {\n this.logger.info(` ${name}`);\n }\n }\n }\n\n return { executed, pending, total: this.migrations.length };\n }\n\n /**\n * Reset all migrations (dangerous!)\n * In dry run mode, shows what would be rolled back\n */\n async reset(): Promise<MigrationResult> {\n const startTime = Date.now();\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await setupMigrations(this.db as any);\n const executed = await this.getExecutedMigrations();\n\n if (executed.length === 0) {\n this.logger.warn('No migrations to reset');\n return {\n executed: [],\n skipped: [],\n failed: [],\n duration: Date.now() - startTime,\n dryRun: this.options.dryRun,\n };\n }\n\n this.logger.warn(`Resetting ${executed.length} migrations...`);\n\n if (this.options.dryRun) {\n this.logger.info('DRY RUN - Would rollback the following migrations:');\n for (const name of [...executed].reverse()) {\n const migration = this.migrations.find((m) => m.name === name);\n if (!migration?.down) {\n this.logger.warn(` ${name} (no down method - would be skipped)`);\n } else {\n this.logger.info(` ${name}`);\n }\n }\n this.logger.info('Dry run completed - no changes made');\n return {\n executed: [],\n skipped: executed,\n failed: [],\n duration: Date.now() - startTime,\n dryRun: true,\n };\n }\n\n const result = await this.down(executed.length);\n this.logger.info('All migrations reset');\n return result;\n }\n\n /**\n * Run migrations up to a specific migration (inclusive)\n */\n async upTo(targetName: string): Promise<MigrationResult> {\n const startTime = Date.now();\n const result: MigrationResult = {\n executed: [],\n skipped: [],\n failed: [],\n duration: 0,\n dryRun: this.options.dryRun,\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await setupMigrations(this.db as any);\n const executed = await this.getExecutedMigrations();\n\n const targetIndex = this.migrations.findIndex((m) => m.name === targetName);\n if (targetIndex === -1) {\n throw new NotFoundError('Migration', { name: targetName });\n }\n\n const migrationsToRun = this.migrations.slice(0, targetIndex + 1);\n\n if (this.options.dryRun) {\n this.logger.info('DRY RUN - No changes will be made');\n }\n\n for (const migration of migrationsToRun) {\n if (executed.includes(migration.name)) {\n this.logger.info(`${migration.name} (already executed)`);\n result.skipped.push(migration.name);\n continue;\n }\n\n try {\n this.logger.info(`Running ${migration.name}...`);\n this.logMigrationMeta(migration);\n\n if (!this.options.dryRun) {\n await this.executeMigration(migration, 'up');\n await this.markAsExecuted(migration.name);\n }\n\n this.logger.info(`${migration.name} completed`);\n result.executed.push(migration.name);\n } catch (error) {\n const errorMsg = formatError(error);\n this.logger.error(`${migration.name} failed: ${errorMsg}`);\n result.failed.push(migration.name);\n\n throw new MigrationError(\n `Migration ${migration.name} failed: ${errorMsg}`,\n migration.name,\n 'up',\n error instanceof Error ? error : undefined\n );\n }\n }\n\n if (!this.options.dryRun) {\n this.logger.info(`Migrated up to ${targetName}`);\n } else {\n this.logger.info(`Dry run completed - would migrate up to ${targetName}`);\n }\n\n result.duration = Date.now() - startTime;\n return result;\n }\n}\n\n// ============================================================================\n// Factory Functions\n// ============================================================================\n\n/**\n * Create a migration runner instance\n * Options are validated using Zod schema\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport function createMigrationRunner<DB = unknown>(\n db: Kysely<DB>,\n migrations: Migration<DB>[],\n options?: MigrationRunnerOptions\n): MigrationRunner<DB> {\n return new MigrationRunner(db, migrations, options);\n}\n\n/**\n * Helper to create a simple migration\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport function createMigration<DB = unknown>(\n name: string,\n up: (db: Kysely<DB>) => Promise<void>,\n down?: (db: Kysely<DB>) => Promise<void>\n): Migration<DB> {\n const migration: Migration<DB> = { name, up };\n if (down !== undefined) {\n migration.down = down;\n }\n return migration;\n}\n\n/**\n * Helper to create a migration with metadata\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport function createMigrationWithMeta<DB = unknown>(\n name: string,\n options: {\n up: (db: Kysely<DB>) => Promise<void>;\n down?: (db: Kysely<DB>) => Promise<void>;\n description?: string;\n breaking?: boolean;\n estimatedDuration?: number;\n tags?: string[];\n }\n): MigrationWithMeta<DB> {\n const migration: MigrationWithMeta<DB> = {\n name,\n up: options.up,\n };\n if (options.down !== undefined) {\n migration.down = options.down;\n }\n if (options.description !== undefined) {\n migration.description = options.description;\n }\n if (options.breaking !== undefined) {\n migration.breaking = options.breaking;\n }\n if (options.estimatedDuration !== undefined) {\n migration.estimatedDuration = options.estimatedDuration;\n }\n if (options.tags !== undefined) {\n migration.tags = options.tags;\n }\n return migration;\n}\n\n// ============================================================================\n// Level 2: Developer Experience APIs\n// ============================================================================\n\n/**\n * Define migrations using an object-based syntax for cleaner code\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport function defineMigrations<DB = unknown>(definitions: MigrationDefinitions<DB>): MigrationWithMeta<DB>[] {\n return Object.entries(definitions).map(([name, def]) => {\n const migration: MigrationWithMeta<DB> = {\n name,\n up: def.up,\n };\n if (def.down !== undefined) {\n migration.down = def.down;\n }\n if (def.description !== undefined) {\n migration.description = def.description;\n }\n if (def.breaking !== undefined) {\n migration.breaking = def.breaking;\n }\n if (def.estimatedDuration !== undefined) {\n migration.estimatedDuration = def.estimatedDuration;\n }\n if (def.tags !== undefined) {\n migration.tags = def.tags;\n }\n return migration;\n });\n}\n\n/**\n * Run all pending migrations - one-liner convenience function\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport async function runMigrations<DB = unknown>(\n db: Kysely<DB>,\n migrations: Migration<DB>[],\n options?: MigrationRunnerOptions\n): Promise<MigrationResult> {\n const runner = new MigrationRunner(db, migrations, options);\n return runner.up();\n}\n\n/**\n * Rollback migrations - one-liner convenience function\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport async function rollbackMigrations<DB = unknown>(\n db: Kysely<DB>,\n migrations: Migration<DB>[],\n steps = 1,\n options?: MigrationRunnerOptions\n): Promise<MigrationResult> {\n const runner = new MigrationRunner(db, migrations, options);\n return runner.down(steps);\n}\n\n/**\n * Get migration status - one-liner convenience function\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport async function getMigrationStatus<DB = unknown>(\n db: Kysely<DB>,\n migrations: Migration<DB>[],\n options?: Pick<MigrationRunnerOptions, 'logger' | 'verbose'>\n): Promise<MigrationStatus> {\n const runner = new MigrationRunner(db, migrations, options);\n return runner.status();\n}\n\n// ============================================================================\n// Level 3: Ecosystem Integration\n// ============================================================================\n\n/**\n * Migration plugin interface - consistent with @kysera/repository Plugin\n * Provides lifecycle hooks for migration execution\n * Generic DB type allows type-safe plugins when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport interface MigrationPlugin<DB = unknown> {\n /** Plugin name */\n name: string;\n /** Plugin version */\n version: string;\n /** Called once when the runner is initialized (consistent with repository Plugin.onInit) */\n onInit?(runner: MigrationRunner<DB>): Promise<void> | void;\n /** Called before migration execution */\n beforeMigration?(migration: Migration<DB>, operation: 'up' | 'down'): Promise<void> | void;\n /** Called after successful migration execution */\n afterMigration?(migration: Migration<DB>, operation: 'up' | 'down', duration: number): Promise<void> | void;\n /** Called on migration error (unknown type for consistency with repository Plugin.onError) */\n onMigrationError?(migration: Migration<DB>, operation: 'up' | 'down', error: unknown): Promise<void> | void;\n}\n\n/**\n * Extended migration runner options with plugin support\n * Generic DB type allows type-safe plugins when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport interface MigrationRunnerWithPluginsOptions<DB = unknown> extends MigrationRunnerOptions {\n /** Plugins to apply */\n plugins?: MigrationPlugin<DB>[];\n}\n\n/**\n * Create a migration runner with plugin support\n * Async factory to properly initialize plugins (consistent with @kysera/repository createORM)\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport async function createMigrationRunnerWithPlugins<DB = unknown>(\n db: Kysely<DB>,\n migrations: Migration<DB>[],\n options?: MigrationRunnerWithPluginsOptions<DB>\n): Promise<MigrationRunnerWithPlugins<DB>> {\n const runner = new MigrationRunnerWithPlugins(db, migrations, options);\n\n // Initialize plugins (consistent with repository Plugin.onInit pattern)\n if (options?.plugins) {\n for (const plugin of options.plugins) {\n if (plugin.onInit) {\n const result = plugin.onInit(runner);\n if (result instanceof Promise) {\n await result;\n }\n }\n }\n }\n\n return runner;\n}\n\n/**\n * Extended migration runner with plugin support\n * Generic DB type allows type-safe migrations when schema is known,\n * defaults to unknown for maximum flexibility\n */\nexport class MigrationRunnerWithPlugins<DB = unknown> extends MigrationRunner<DB> {\n private plugins: MigrationPlugin<DB>[];\n\n constructor(\n db: Kysely<DB>,\n migrations: Migration<DB>[],\n options: MigrationRunnerWithPluginsOptions<DB> = {}\n ) {\n super(db, migrations, options);\n this.plugins = options.plugins ?? [];\n }\n\n /**\n * Execute plugin hooks before migration\n * Can be called by consumers extending this class\n */\n protected async runBeforeHooks(migration: Migration<DB>, operation: 'up' | 'down'): Promise<void> {\n for (const plugin of this.plugins) {\n if (plugin.beforeMigration) {\n await plugin.beforeMigration(migration, operation);\n }\n }\n }\n\n /**\n * Execute plugin hooks after migration\n * Can be called by consumers extending this class\n */\n protected async runAfterHooks(\n migration: Migration<DB>,\n operation: 'up' | 'down',\n duration: number\n ): Promise<void> {\n for (const plugin of this.plugins) {\n if (plugin.afterMigration) {\n await plugin.afterMigration(migration, operation, duration);\n }\n }\n }\n\n /**\n * Execute plugin hooks on error\n * Can be called by consumers extending this class\n */\n protected async runErrorHooks(\n migration: Migration<DB>,\n operation: 'up' | 'down',\n error: unknown\n ): Promise<void> {\n for (const plugin of this.plugins) {\n if (plugin.onMigrationError) {\n await plugin.onMigrationError(migration, operation, error);\n }\n }\n }\n\n /**\n * Get the list of registered plugins\n */\n getPlugins(): MigrationPlugin<DB>[] {\n return [...this.plugins];\n }\n}\n\n// ============================================================================\n// Built-in Plugins\n// ============================================================================\n\n/**\n * Logging plugin - logs migration events with timing\n * Works with any DB type (generic plugin)\n */\nexport function createLoggingPlugin<DB = unknown>(\n logger: KyseraLogger = silentLogger\n): MigrationPlugin<DB> {\n return {\n name: '@kysera/migrations/logging',\n version: '0.5.1',\n beforeMigration(migration, operation) {\n logger.info(`Starting ${operation} for ${migration.name}`);\n },\n afterMigration(migration, operation, duration) {\n logger.info(`Completed ${operation} for ${migration.name} in ${duration}ms`);\n },\n onMigrationError(migration, operation, error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Error during ${operation} for ${migration.name}: ${message}`);\n },\n };\n}\n\n/**\n * Metrics plugin - collects migration metrics\n * Works with any DB type (generic plugin)\n */\nexport function createMetricsPlugin<DB = unknown>(): MigrationPlugin<DB> & {\n getMetrics(): { migrations: Array<{ name: string; operation: string; duration: number; success: boolean }> };\n} {\n const metrics: Array<{ name: string; operation: string; duration: number; success: boolean }> = [];\n\n return {\n name: '@kysera/migrations/metrics',\n version: '0.5.1',\n afterMigration(migration, operation, duration) {\n metrics.push({ name: migration.name, operation, duration, success: true });\n },\n onMigrationError(migration, operation) {\n metrics.push({ name: migration.name, operation, duration: 0, success: false });\n },\n getMetrics() {\n return { migrations: [...metrics] };\n },\n };\n}\n\n// ============================================================================\n// Re-exports from @kysera/core for convenience\n// ============================================================================\n\nexport { DatabaseError, NotFoundError, BadRequestError, silentLogger } from '@kysera/core';\nexport type { KyseraLogger } from '@kysera/core';\n"]}
|