kysely 0.12.2 → 0.13.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.
Files changed (36) hide show
  1. package/README.md +34 -10
  2. package/dist/cjs/dialect/mysql/mysql-adapter.d.ts +2 -2
  3. package/dist/cjs/dialect/mysql/mysql-adapter.js +2 -1
  4. package/dist/cjs/dialect/postgres/postgres-adapter.d.ts +2 -2
  5. package/dist/cjs/dialect/postgres/postgres-adapter.js +2 -1
  6. package/dist/cjs/dialect/sqlite/sqlite-adapter.d.ts +2 -2
  7. package/dist/cjs/index.d.ts +1 -1
  8. package/dist/cjs/migration/migration.d.ts +154 -11
  9. package/dist/cjs/migration/migration.js +256 -135
  10. package/dist/cjs/operation-node/column-definition-node.d.ts +6 -5
  11. package/dist/cjs/operation-node/column-definition-node.js +0 -4
  12. package/dist/cjs/operation-node/operation-node-transformer.js +2 -1
  13. package/dist/cjs/plugin/camel-case/camel-case-plugin.d.ts +2 -2
  14. package/dist/cjs/query-compiler/default-query-compiler.js +4 -1
  15. package/dist/cjs/schema/alter-table-builder.d.ts +12 -0
  16. package/dist/cjs/schema/alter-table-builder.js +12 -0
  17. package/dist/cjs/schema/column-definition-builder.d.ts +12 -0
  18. package/dist/cjs/schema/column-definition-builder.js +4 -1
  19. package/dist/esm/dialect/mysql/mysql-adapter.d.ts +2 -2
  20. package/dist/esm/dialect/mysql/mysql-adapter.js +2 -1
  21. package/dist/esm/dialect/postgres/postgres-adapter.d.ts +2 -2
  22. package/dist/esm/dialect/postgres/postgres-adapter.js +2 -1
  23. package/dist/esm/dialect/sqlite/sqlite-adapter.d.ts +2 -2
  24. package/dist/esm/index.d.ts +1 -1
  25. package/dist/esm/migration/migration.d.ts +154 -11
  26. package/dist/esm/migration/migration.js +255 -134
  27. package/dist/esm/operation-node/column-definition-node.d.ts +6 -5
  28. package/dist/esm/operation-node/column-definition-node.js +0 -4
  29. package/dist/esm/operation-node/operation-node-transformer.js +2 -1
  30. package/dist/esm/plugin/camel-case/camel-case-plugin.d.ts +2 -2
  31. package/dist/esm/query-compiler/default-query-compiler.js +4 -1
  32. package/dist/esm/schema/alter-table-builder.d.ts +12 -0
  33. package/dist/esm/schema/alter-table-builder.js +12 -0
  34. package/dist/esm/schema/column-definition-builder.d.ts +12 -0
  35. package/dist/esm/schema/column-definition-builder.js +4 -1
  36. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
- import { DialectAdapter } from '../dialect-adapter.js';
2
- export declare class SqliteAdapter implements DialectAdapter {
1
+ import { DialectAdapterBase } from '../dialect-adapter-base.js';
2
+ export declare class SqliteAdapter implements DialectAdapterBase {
3
3
  /**
4
4
  * Whether or not this dialect supports transactional DDL.
5
5
  *
@@ -140,7 +140,7 @@ export * from './introspection/database-introspector.js';
140
140
  export * from './util/compilable.js';
141
141
  export * from './util/log.js';
142
142
  export { AnyColumn, UnknownRow, AnySelectQueryBuilder, } from './util/type-utils.js';
143
- export { SelectExpression, SelectExpressionOrList, } from './parser/select-parser.js';
143
+ export { SelectExpression, SelectExpressionOrList, Selection, } from './parser/select-parser.js';
144
144
  export { ReferenceExpression, ReferenceExpressionOrList, } from './parser/reference-parser.js';
145
145
  export { ValueExpression, ValueExpressionOrList, } from './parser/value-parser.js';
146
146
  export { FilterValueExpression, FilterValueExpressionOrList, ExistsExpression, FilterOperator, } from './parser/filter-parser.js';
@@ -3,6 +3,73 @@ import { DialectAdapter } from '../dialect/dialect-adapter.js';
3
3
  export declare const MIGRATION_TABLE = "kysely_migration";
4
4
  export declare const MIGRATION_LOCK_TABLE = "kysely_migration_lock";
5
5
  export declare const MIGRATION_LOCK_ID = "migration_lock";
6
+ export declare const NO_MIGRATIONS: NoMigrations;
7
+ export declare type MigrationsOrFolderPath = Record<string, Migration> | string;
8
+ export interface Migration {
9
+ up(db: Kysely<any>): Promise<void>;
10
+ down?(db: Kysely<any>): Promise<void>;
11
+ }
12
+ /**
13
+ * Type for the NO_MIGRATIONS constant. Never create one of these.
14
+ */
15
+ export interface NoMigrations {
16
+ readonly __noMigrations__: true;
17
+ }
18
+ /**
19
+ * All migration methods ({@link MigrationModule.migrateTo | migrateTo},
20
+ * {@link MigrationModule.migrateToLatest | migrateToLatest} etc.) never
21
+ * throw but return this object instead.
22
+ */
23
+ export interface MigrationResultSet {
24
+ /**
25
+ * This is defined if something went wrong.
26
+ *
27
+ * An error may have occurred in one of the migrations in which case the
28
+ * {@link results} list contains an item with `status === 'Error'` to
29
+ * indicate which migration failed.
30
+ *
31
+ * An error may also have occurred before Kysely was able to figure out
32
+ * which migrations should be executed, in which case the {@link results}
33
+ * list is undefined.
34
+ */
35
+ readonly error?: unknown;
36
+ /**
37
+ * {@link MigrationResult} for each individual migration that was supposed
38
+ * to be executed by the operation.
39
+ *
40
+ * If all went well, each result's `status` is `Success`. If some migration
41
+ * failed, the failed migration's result's `status` is `Error` and all
42
+ * results after that one have `status` ´NotExecuted`.
43
+ *
44
+ * This property can be undefined if an error occurred before Kysely was
45
+ * able to figure out which migrations should be executed.
46
+ *
47
+ * If this list is empty, there were no migrations to execute.
48
+ */
49
+ readonly results?: MigrationResult[];
50
+ }
51
+ export interface MigrationResult {
52
+ readonly migrationName: string;
53
+ /**
54
+ * The direction in which this migration was executed.
55
+ */
56
+ readonly direction: 'Up' | 'Down';
57
+ /**
58
+ * The execution status.
59
+ *
60
+ * - `Success` means the migration was successfully executed. Note that
61
+ * if any of the later migrations in the {@link MigrationResult.results}
62
+ * list failed (have status `Error`) AND the dialect supports transactional
63
+ * DDL, even the successfull migrations were rolled back.
64
+ *
65
+ * - `Error` means the migration failed. In this case the
66
+ * {@link MigrationResult.error} contains the error.
67
+ *
68
+ * - `NotExecuted` means that the migration was supposed to be executed
69
+ * but wasn't because an earlier migration failed.
70
+ */
71
+ readonly status: 'Success' | 'Error' | 'NotExecuted';
72
+ }
6
73
  export declare class MigrationModule {
7
74
  #private;
8
75
  constructor(db: Kysely<any>, adapter: DialectAdapter);
@@ -10,26 +77,45 @@ export declare class MigrationModule {
10
77
  * Runs all migrations that have not yet been run.
11
78
  *
12
79
  * The only argument must either be a file path to the folder that contains all migrations
13
- * OR an object that contains all migrations (not just the ones that need to be run).
80
+ * OR an object that contains all migrations (not just the ones that need to be executed).
14
81
  * The keys in the object must be the unique migration names.
15
82
  *
83
+ * This method returns a {@link MigrationResultSet} instance and _never_ throws.
84
+ * {@link MigrationResultSet.error} holds the error if something went wrong.
85
+ * {@link MigrationResultSet.results} contains information about which migrations
86
+ * were executed and which failed. See the examples below.
87
+ *
16
88
  * This method goes through all possible migrations (passed as the argument) and runs the
17
89
  * ones whose names are alphabetically after the last migration that has been run. If the
18
- * list of executed migrations doesn't match the list of possible migrations, and error
19
- * is thrown.
90
+ * list of executed migrations doesn't match the beginning of the list of possible migrations
91
+ * an error is thrown.
20
92
  *
21
93
  * ### Examples
22
94
  *
23
95
  * ```ts
24
- * await db.migration.migrateToLatest(
96
+ * const { error, results } = await db.migration.migrateToLatest(
25
97
  * path.join(__dirname, 'migrations')
26
98
  * )
99
+ *
100
+ * results?.forEach((it) => {
101
+ * if (it.status === 'Success') {
102
+ * console.log(`migration "${it.migrationName}" was executed successfully`)
103
+ * } else if (it.status === 'Error') {
104
+ * console.error(`failed to execute migration "${it.migrationName}"`)
105
+ * }
106
+ * })
107
+ *
108
+ * if (error) {
109
+ * console.error('failed to run `migrateToLatest`')
110
+ * console.error(error)
111
+ * }
27
112
  * ```
28
113
  *
29
114
  * In the next example, we use a record of migration objects instead of file folder path.
30
115
  * The keys in the object are migration names that can be anything you want. The order of
31
116
  * the migrations is determined based on the alphabetical order of the keys in the record.
32
- * This can be useful if you are using a bundler like webpack or esbuild.
117
+ * This version of the `migrateToLatest` method can be useful if you are using a bundler
118
+ * like webpack or esbuild.
33
119
  *
34
120
  * ```ts
35
121
  * await db.migration.migrateToLatest({
@@ -57,10 +143,67 @@ export declare class MigrationModule {
57
143
  * })
58
144
  * ```
59
145
  */
60
- migrateToLatest(migrationsFolderPath: string): Promise<void>;
61
- migrateToLatest(allMigrations: Record<string, Migration>): Promise<void>;
62
- }
63
- export interface Migration {
64
- up(db: Kysely<any>): Promise<void>;
65
- down?(db: Kysely<any>): Promise<void>;
146
+ migrateToLatest(migrationsFolderPath: string): Promise<MigrationResultSet>;
147
+ migrateToLatest(allMigrations: Record<string, Migration>): Promise<MigrationResultSet>;
148
+ /**
149
+ * Migrate up/down to a specific migration.
150
+ *
151
+ * Otherwise works just like {@link migrateToLatest}. The first argument
152
+ * behaves the same, the output is the same etc.
153
+ *
154
+ * ### Examples
155
+ *
156
+ * ```ts
157
+ * await db.migration.migrateTo(
158
+ * path.join(__dirname, 'migrations'),
159
+ * 'some_migration'
160
+ * )
161
+ * ```
162
+ *
163
+ * If you specify the name of the first migration, this method migrates
164
+ * down to the first migration, but doesn't run the `down` migration for
165
+ * the first migration. In case you want to migrate down ALL migrations
166
+ * you can use a special constant `NO_MIGRATIONS`:
167
+ *
168
+ * ```ts
169
+ * await db.migration.migrateTo(
170
+ * path.join(__dirname, 'migrations'),
171
+ * NO_MIGRATIONS,
172
+ * )
173
+ * ```
174
+ */
175
+ migrateTo(migrationsFolderPath: string, targetMigrationName: string | NoMigrations): Promise<MigrationResultSet>;
176
+ migrateTo(allMigrations: Record<string, Migration>, targetMigrationName: string | NoMigrations): Promise<MigrationResultSet>;
177
+ /**
178
+ * Migrate one step up.
179
+ *
180
+ * Otherwise works just like {@link migrateToLatest}. The only argument
181
+ * behaves the same, the output is the same etc.
182
+ *
183
+ * ### Examples
184
+ *
185
+ * ```ts
186
+ * await db.migration.migrateUp(
187
+ * path.join(__dirname, 'migrations'),
188
+ * )
189
+ * ```
190
+ */
191
+ migrateUp(migrationsFolderPath: string): Promise<MigrationResultSet>;
192
+ migrateUp(allMigrations: Record<string, Migration>): Promise<MigrationResultSet>;
193
+ /**
194
+ * Migrate one step down.
195
+ *
196
+ * Otherwise works just like {@link migrateToLatest}. The only argument
197
+ * behaves the same, the output is the same etc.
198
+ *
199
+ * ### Examples
200
+ *
201
+ * ```ts
202
+ * await db.migration.migrateDown(
203
+ * path.join(__dirname, 'migrations'),
204
+ * )
205
+ * ```
206
+ */
207
+ migrateDown(migrationsFolderPath: string): Promise<MigrationResultSet>;
208
+ migrateDown(allMigrations: Record<string, Migration>): Promise<MigrationResultSet>;
66
209
  }
@@ -1,9 +1,10 @@
1
1
  import * as path from 'path';
2
2
  import { promises as fs } from 'fs';
3
- import { getLast, isFunction, isObject, isString, } from '../util/object-utils.js';
3
+ import { freeze, getLast, isFunction, isObject, isString, } from '../util/object-utils.js';
4
4
  export const MIGRATION_TABLE = 'kysely_migration';
5
5
  export const MIGRATION_LOCK_TABLE = 'kysely_migration_lock';
6
6
  export const MIGRATION_LOCK_ID = 'migration_lock';
7
+ export const NO_MIGRATIONS = freeze({ __noMigrations__: true });
7
8
  export class MigrationModule {
8
9
  #db;
9
10
  #adapter;
@@ -12,170 +13,290 @@ export class MigrationModule {
12
13
  this.#adapter = adapter;
13
14
  }
14
15
  async migrateToLatest(migrationsOrFolderPath) {
15
- await ensureMigrationTablesExists(this.#db);
16
- const allMigrations = await this.#getAllMigrations(migrationsOrFolderPath);
17
- await this.#migrateToLatest(allMigrations);
16
+ return this.#migrate(migrationsOrFolderPath, ({ migrations }) => migrations.length - 1);
18
17
  }
19
- async #getAllMigrations(migrationsOrFolderPath) {
20
- return isString(migrationsOrFolderPath)
21
- ? await readMigrationsFromFolder(migrationsOrFolderPath)
22
- : migrationsOrFolderPath;
18
+ async migrateTo(migrationsOrFolderPath, targetMigrationName) {
19
+ return this.#migrate(migrationsOrFolderPath, ({ migrations }) => {
20
+ if (targetMigrationName === NO_MIGRATIONS) {
21
+ return -1;
22
+ }
23
+ const index = migrations.findIndex((it) => it.name === targetMigrationName);
24
+ if (index === -1) {
25
+ throw new Error(`migration "${targetMigrationName}" doesn't exist`);
26
+ }
27
+ return index;
28
+ });
29
+ }
30
+ async migrateUp(migrationsOrFolderPath) {
31
+ return this.#migrate(migrationsOrFolderPath, ({ currentIndex, migrations }) => Math.min(currentIndex + 1, migrations.length - 1));
32
+ }
33
+ async migrateDown(migrationsOrFolderPath) {
34
+ return this.#migrate(migrationsOrFolderPath, ({ currentIndex }) => Math.max(currentIndex - 1, -1));
35
+ }
36
+ async #migrate(migrationsOrFolderPath, getTargetMigration) {
37
+ try {
38
+ await this.#ensureMigrationTablesExists();
39
+ return await this.#runMigrations(migrationsOrFolderPath, getTargetMigration);
40
+ }
41
+ catch (error) {
42
+ if (error instanceof MigrationResultSetError) {
43
+ return error.resultSet;
44
+ }
45
+ return { error };
46
+ }
47
+ }
48
+ async #ensureMigrationTablesExists() {
49
+ await this.#ensureMigrationTableExists();
50
+ await this.#ensureMigrationLockTableExists();
51
+ await this.#ensureLockRowExists();
52
+ }
53
+ async #ensureMigrationTableExists() {
54
+ if (!(await this.#doesTableExists(MIGRATION_TABLE))) {
55
+ try {
56
+ await this.#db.schema
57
+ .createTable(MIGRATION_TABLE)
58
+ .ifNotExists()
59
+ .addColumn('name', 'varchar(255)', (col) => col.notNull().primaryKey())
60
+ // The migration run time as ISO string. This is not a real date type as we
61
+ // can't know which data type is supported by all future dialects.
62
+ .addColumn('timestamp', 'varchar(255)', (col) => col.notNull())
63
+ .execute();
64
+ }
65
+ catch (error) {
66
+ // At least on PostgreSQL, `if not exists` doesn't guarantee the `create table`
67
+ // query doesn't throw if the table already exits. That's why we check if
68
+ // the table exist here and ignore the error if it does.
69
+ if (!(await this.#doesTableExists(MIGRATION_TABLE))) {
70
+ throw error;
71
+ }
72
+ }
73
+ }
74
+ }
75
+ async #ensureMigrationLockTableExists() {
76
+ if (!(await this.#doesTableExists(MIGRATION_LOCK_TABLE))) {
77
+ try {
78
+ await this.#db.schema
79
+ .createTable(MIGRATION_LOCK_TABLE)
80
+ .ifNotExists()
81
+ .addColumn('id', 'varchar(255)', (col) => col.notNull().primaryKey())
82
+ .addColumn('is_locked', 'integer', (col) => col.notNull().defaultTo(0))
83
+ .execute();
84
+ }
85
+ catch (error) {
86
+ // At least on PostgreSQL, `if not exists` doesn't guarantee the `create table`
87
+ // query doesn't throw if the table already exits. That's why we check if
88
+ // the table exist here and ignore the error if it does.
89
+ if (!(await this.#doesTableExists(MIGRATION_LOCK_TABLE))) {
90
+ throw error;
91
+ }
92
+ }
93
+ }
23
94
  }
24
- async #migrateToLatest(allMigrations) {
95
+ async #ensureLockRowExists() {
96
+ if (!(await this.#doesLockRowExists())) {
97
+ try {
98
+ await this.#db
99
+ .insertInto(MIGRATION_LOCK_TABLE)
100
+ .values({ id: MIGRATION_LOCK_ID })
101
+ .execute();
102
+ }
103
+ catch (error) {
104
+ if (!(await this.#doesLockRowExists())) {
105
+ throw error;
106
+ }
107
+ }
108
+ }
109
+ }
110
+ async #doesTableExists(tableName) {
111
+ const metadata = await this.#db.introspection.getMetadata({
112
+ withInternalKyselyTables: true,
113
+ });
114
+ return !!metadata.tables.find((it) => it.name === tableName);
115
+ }
116
+ async #doesLockRowExists() {
117
+ const lockRow = await this.#db
118
+ .selectFrom(MIGRATION_LOCK_TABLE)
119
+ .where('id', '=', MIGRATION_LOCK_ID)
120
+ .select('id')
121
+ .executeTakeFirst();
122
+ return !!lockRow;
123
+ }
124
+ async #runMigrations(migrationsOrFolderPath, getTargetMigration) {
25
125
  const run = async (db) => {
26
126
  try {
27
127
  await this.#adapter.acquireMigrationLock(db);
28
- await runNewMigrations(db, allMigrations);
128
+ const state = await this.#getState(db, migrationsOrFolderPath);
129
+ if (state.migrations.length === 0) {
130
+ return { results: [] };
131
+ }
132
+ const targetIndex = getTargetMigration(state);
133
+ if (targetIndex === undefined) {
134
+ return { results: [] };
135
+ }
136
+ if (targetIndex < state.currentIndex) {
137
+ return await this.#migrateDown(db, state, targetIndex);
138
+ }
139
+ else if (targetIndex > state.currentIndex) {
140
+ return await this.#migrateUp(db, state, targetIndex);
141
+ }
142
+ return { results: [] };
29
143
  }
30
144
  finally {
31
145
  await this.#adapter.releaseMigrationLock(db);
32
146
  }
33
147
  };
34
148
  if (this.#adapter.supportsTransactionalDdl) {
35
- await this.#db.transaction().execute(run);
149
+ return this.#db.transaction().execute(run);
36
150
  }
37
151
  else {
38
- await this.#db.connection().execute(run);
152
+ return this.#db.connection().execute(run);
39
153
  }
40
154
  }
41
- }
42
- async function ensureMigrationTablesExists(db) {
43
- await ensureMigrationTableExists(db);
44
- await ensureMigrationLockTableExists(db);
45
- await ensureLockRowExists(db);
46
- }
47
- async function ensureMigrationTableExists(db) {
48
- if (!(await doesTableExists(db, MIGRATION_TABLE))) {
49
- try {
50
- await db.schema
51
- .createTable(MIGRATION_TABLE)
52
- .ifNotExists()
53
- .addColumn('name', 'varchar(255)', (col) => col.notNull().primaryKey())
54
- // The migration run time as ISO string. This is not a real date type as we
55
- // can't know which data type is supported by all future dialects.
56
- .addColumn('timestamp', 'varchar(255)', (col) => col.notNull())
57
- .execute();
58
- }
59
- catch (error) {
60
- // At least on PostgreSQL, `if not exists` doesn't guarantee the `create table`
61
- // query doesn't throw if the table already exits. That's why we check if
62
- // the table exist here and ignore the error if it does.
63
- if (!(await doesTableExists(db, MIGRATION_TABLE))) {
64
- throw error;
155
+ async #getState(db, migrationsOrFolderPath) {
156
+ const migrations = await this.#resolveMigrations(migrationsOrFolderPath);
157
+ const executedMigrations = await this.#getExecutedMigrations(db);
158
+ this.#ensureMigrationsNotCorrupted(migrations, executedMigrations);
159
+ return freeze({
160
+ migrations,
161
+ currentIndex: migrations.findIndex((it) => it.name === getLast(executedMigrations)),
162
+ });
163
+ }
164
+ async #resolveMigrations(migrationsOrFolderPath) {
165
+ const allMigrations = isString(migrationsOrFolderPath)
166
+ ? await this.#readMigrationsFromFolder(migrationsOrFolderPath)
167
+ : migrationsOrFolderPath;
168
+ return Object.keys(allMigrations)
169
+ .sort()
170
+ .map((name) => ({
171
+ ...allMigrations[name],
172
+ name,
173
+ }));
174
+ }
175
+ async #readMigrationsFromFolder(migrationsFolderPath) {
176
+ const files = await fs.readdir(migrationsFolderPath);
177
+ const migrations = {};
178
+ for (const file of files) {
179
+ if ((file.endsWith('.js') || file.endsWith('.ts')) &&
180
+ !file.endsWith('.d.ts')) {
181
+ const migration = await import(path.join(migrationsFolderPath, file));
182
+ if (isMigration(migration)) {
183
+ migrations[file.substring(0, file.length - 3)] = migration;
184
+ }
65
185
  }
66
186
  }
187
+ return migrations;
67
188
  }
68
- }
69
- async function ensureMigrationLockTableExists(db) {
70
- if (!(await doesTableExists(db, MIGRATION_LOCK_TABLE))) {
71
- try {
72
- await db.schema
73
- .createTable(MIGRATION_LOCK_TABLE)
74
- .ifNotExists()
75
- .addColumn('id', 'varchar(255)', (col) => col.notNull().primaryKey())
76
- .addColumn('is_locked', 'integer', (col) => col.notNull().defaultTo(0))
77
- .execute();
189
+ async #getExecutedMigrations(db) {
190
+ const executedMigrations = await db
191
+ .selectFrom(MIGRATION_TABLE)
192
+ .select('name')
193
+ .orderBy('name')
194
+ .execute();
195
+ return executedMigrations.map((it) => it.name);
196
+ }
197
+ #ensureMigrationsNotCorrupted(migrations, executedMigrations) {
198
+ for (const executed of executedMigrations) {
199
+ if (!migrations.some((it) => it.name === executed)) {
200
+ throw new Error(`corrupted migrations: previously executed migration ${executed} is missing`);
201
+ }
78
202
  }
79
- catch (error) {
80
- // At least on PostgreSQL, `if not exists` doesn't guarantee the `create table`
81
- // query doesn't throw if the table already exits. That's why we check if
82
- // the table exist here and ignore the error if it does.
83
- if (!(await doesTableExists(db, MIGRATION_LOCK_TABLE))) {
84
- throw error;
203
+ // Now we know all executed migrations exist in the `migrations` list.
204
+ // Next we need to make sure that the executed migrations are the first
205
+ // ones in the migration list.
206
+ for (let i = 0; i < executedMigrations.length; ++i) {
207
+ if (migrations[i].name !== executedMigrations[i]) {
208
+ throw new Error(`corrupted migrations: expected previously executed migration ${executedMigrations[i]} to be at index ${i} but ${migrations[i].name} was found in its place. New migrations must always have a name that comes alphabetically after the last executed migration.`);
85
209
  }
86
210
  }
87
211
  }
88
- }
89
- async function ensureLockRowExists(db) {
90
- if (!(await doesLockRowExists(db))) {
91
- try {
92
- await db
93
- .insertInto(MIGRATION_LOCK_TABLE)
94
- .values({ id: MIGRATION_LOCK_ID })
95
- .execute();
212
+ async #migrateDown(db, state, targetIndex) {
213
+ const results = [];
214
+ for (let i = state.currentIndex; i > targetIndex; --i) {
215
+ results.push({
216
+ migrationName: state.migrations[i].name,
217
+ direction: 'Down',
218
+ status: 'NotExecuted',
219
+ });
96
220
  }
97
- catch (error) {
98
- if (!(await doesLockRowExists(db))) {
99
- throw error;
221
+ for (let i = 0; i < results.length; ++i) {
222
+ const migration = state.migrations.find((it) => it.name === results[i].migrationName);
223
+ try {
224
+ if (migration.down) {
225
+ await migration.down(db);
226
+ await db
227
+ .deleteFrom(MIGRATION_TABLE)
228
+ .where('name', '=', migration.name)
229
+ .execute();
230
+ results[i] = {
231
+ migrationName: migration.name,
232
+ direction: 'Down',
233
+ status: 'Success',
234
+ };
235
+ }
236
+ }
237
+ catch (error) {
238
+ results[i] = {
239
+ migrationName: migration.name,
240
+ direction: 'Down',
241
+ status: 'Error',
242
+ };
243
+ throw new MigrationResultSetError({
244
+ error,
245
+ results,
246
+ });
100
247
  }
101
248
  }
249
+ return { results };
102
250
  }
103
- }
104
- async function doesTableExists(db, tableName) {
105
- const metadata = await db.introspection.getMetadata({
106
- withInternalKyselyTables: true,
107
- });
108
- return !!metadata.tables.find((it) => it.name === tableName);
109
- }
110
- async function doesLockRowExists(db) {
111
- const lockRow = await db
112
- .selectFrom(MIGRATION_LOCK_TABLE)
113
- .where('id', '=', MIGRATION_LOCK_ID)
114
- .select('id')
115
- .executeTakeFirst();
116
- return !!lockRow;
117
- }
118
- async function readMigrationsFromFolder(migrationsFolderPath) {
119
- const files = await fs.readdir(migrationsFolderPath);
120
- const migrations = {};
121
- for (const file of files) {
122
- if ((file.endsWith('.js') || file.endsWith('.ts')) &&
123
- !file.endsWith('.d.ts')) {
124
- const migration = await import(path.join(migrationsFolderPath, file));
125
- if (isMigration(migration)) {
126
- migrations[file.substring(0, file.length - 3)] = migration;
251
+ async #migrateUp(db, state, targetIndex) {
252
+ const results = [];
253
+ for (let i = state.currentIndex + 1; i <= targetIndex; ++i) {
254
+ results.push({
255
+ migrationName: state.migrations[i].name,
256
+ direction: 'Up',
257
+ status: 'NotExecuted',
258
+ });
259
+ }
260
+ for (let i = 0; i < results.length; ++i) {
261
+ const migration = state.migrations.find((it) => it.name === results[i].migrationName);
262
+ try {
263
+ await migration.up(db);
264
+ await db
265
+ .insertInto(MIGRATION_TABLE)
266
+ .values({
267
+ name: migration.name,
268
+ timestamp: new Date().toISOString(),
269
+ })
270
+ .execute();
271
+ results[i] = {
272
+ migrationName: migration.name,
273
+ direction: 'Up',
274
+ status: 'Success',
275
+ };
276
+ }
277
+ catch (error) {
278
+ results[i] = {
279
+ migrationName: migration.name,
280
+ direction: 'Up',
281
+ status: 'Error',
282
+ };
283
+ throw new MigrationResultSetError({
284
+ error,
285
+ results,
286
+ });
127
287
  }
128
288
  }
289
+ return { results };
129
290
  }
130
- return migrations;
131
291
  }
132
- async function runNewMigrations(db, allMigrations) {
133
- const sortedMigrations = Object.keys(allMigrations)
134
- .sort()
135
- .map((name) => ({
136
- ...allMigrations[name],
137
- name,
138
- }));
139
- const executedMigrations = await db
140
- .selectFrom(MIGRATION_TABLE)
141
- .select('name')
142
- .orderBy('name')
143
- .execute();
144
- const lastExecuted = getLast(executedMigrations);
145
- const lastExecutedIndex = sortedMigrations.findIndex((it) => it.name === lastExecuted?.name);
146
- if (lastExecuted && lastExecutedIndex === -1) {
147
- throw new Error(`corrupted migrations: previously executed migration ${lastExecuted.name} is missing`);
148
- }
149
- const oldMigrations = lastExecuted
150
- ? sortedMigrations.slice(0, lastExecutedIndex + 1)
151
- : [];
152
- const newMigrations = lastExecuted
153
- ? sortedMigrations.slice(lastExecutedIndex + 1)
154
- : sortedMigrations;
155
- ensureMigrationsAreNotCorrupted(executedMigrations.map((it) => it.name), oldMigrations.map((it) => it.name));
156
- for (const migration of newMigrations) {
157
- await migration.up(db);
158
- await db
159
- .insertInto(MIGRATION_TABLE)
160
- .values({
161
- name: migration.name,
162
- timestamp: new Date().toISOString(),
163
- })
164
- .execute();
292
+ class MigrationResultSetError extends Error {
293
+ #resultSet;
294
+ constructor(result) {
295
+ super();
296
+ this.#resultSet = result;
165
297
  }
166
- }
167
- function ensureMigrationsAreNotCorrupted(executedMigrationNames, oldMigrationNames) {
168
- const executedSet = new Set(executedMigrationNames);
169
- const oldMigrationSet = new Set(oldMigrationNames);
170
- for (const it of executedSet) {
171
- if (!oldMigrationSet.has(it)) {
172
- throw new Error(`corrupted migrations: previously executed migration ${it} is missing`);
173
- }
174
- }
175
- for (const it of oldMigrationSet) {
176
- if (!executedSet.has(it)) {
177
- throw new Error(`corrupted migrations: new migration ${it} comes alphabetically before the last executed migration. New migrations must always have a name that comes alphabetically after the last executed migration.`);
178
- }
298
+ get resultSet() {
299
+ return this.#resultSet;
179
300
  }
180
301
  }
181
302
  function isMigration(obj) {