-
Notifications
You must be signed in to change notification settings - Fork 280
/
migration.ts
275 lines (240 loc) · 7.91 KB
/
migration.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import * as path from 'path'
import { promises as fs } from 'fs'
import { Kysely } from '../kysely.js'
import {
getLast,
isFunction,
isObject,
isString,
} from '../util/object-utils.js'
import { DialectAdapter } from '../dialect/dialect-adapter.js'
export const MIGRATION_TABLE = 'kysely_migration'
export const MIGRATION_LOCK_TABLE = 'kysely_migration_lock'
export const MIGRATION_LOCK_ID = 'migration_lock'
export class MigrationModule {
readonly #db: Kysely<any>
readonly #adapter: DialectAdapter
constructor(db: Kysely<any>, adapter: DialectAdapter) {
this.#db = db
this.#adapter = adapter
}
/**
* Runs all migrations that have not yet been run.
*
* The only argument must either be a file path to the folder that contains all migrations
* OR an object that contains all migrations (not just the ones that need to be run).
* The keys in the object must be the unique migration names.
*
* This method goes through all possible migrations (passed as the argument) and runs the
* ones whose names are alphabetically after the last migration that has been run. If the
* list of executed migrations doesn't match the list of possible migrations, and error
* is thrown.
*
* @example
* ```ts
* await db.migration.migrateToLatest(
* path.join(__dirname, 'migrations')
* )
* ```
*/
migrateToLatest(migrationsFolderPath: string): Promise<void>
migrateToLatest(allMigrations: Record<string, Migration>): Promise<void>
async migrateToLatest(
migrationsOrFolderPath: Record<string, Migration> | string
): Promise<void> {
await ensureMigrationTablesExists(this.#db)
const allMigrations = await this.#getAllMigrations(migrationsOrFolderPath)
await this.#migrateToLatest(allMigrations)
}
async #getAllMigrations(
migrationsOrFolderPath: Record<string, Migration> | string
): Promise<Record<string, Migration>> {
return isString(migrationsOrFolderPath)
? await readMigrationsFromFolder(migrationsOrFolderPath)
: migrationsOrFolderPath
}
async #migrateToLatest(
allMigrations: Record<string, Migration>
): Promise<void> {
const run = async (db: Kysely<any>) => {
try {
await this.#adapter.acquireMigrationLock(db)
await runNewMigrations(db, allMigrations)
} finally {
await this.#adapter.releaseMigrationLock(db)
}
}
if (this.#adapter.supportsTransactionalDdl) {
await this.#db.transaction().execute(run)
} else {
await this.#db.connection().execute(run)
}
}
}
export interface Migration {
up(db: Kysely<any>): Promise<void>
down(db: Kysely<any>): Promise<void>
}
async function ensureMigrationTablesExists(db: Kysely<any>): Promise<void> {
await ensureMigrationTableExists(db)
await ensureMigrationLockTableExists(db)
await ensureLockRowExists(db)
}
async function ensureMigrationTableExists(db: Kysely<any>): Promise<void> {
if (!(await doesTableExists(db, MIGRATION_TABLE))) {
try {
await db.schema
.createTable(MIGRATION_TABLE)
.ifNotExists()
.addColumn('name', 'varchar(255)', (col) => col.notNull().primaryKey())
// The migration run time as ISO string. This is not a real date type as we
// can't know which data type is supported by all future dialects.
.addColumn('timestamp', 'varchar(255)', (col) => col.notNull())
.execute()
} catch (error) {
// At least on postgres, `if not exists` doesn't guarantee the `create table`
// query doesn't throw if the table already exits. That's why we check if
// the table exist here and ignore the error if it does.
if (!(await doesTableExists(db, MIGRATION_TABLE))) {
throw error
}
}
}
}
async function ensureMigrationLockTableExists(db: Kysely<any>): Promise<void> {
if (!(await doesTableExists(db, MIGRATION_LOCK_TABLE))) {
try {
await db.schema
.createTable(MIGRATION_LOCK_TABLE)
.ifNotExists()
.addColumn('id', 'varchar(255)', (col) => col.notNull().primaryKey())
.addColumn('is_locked', 'integer', (col) => col.notNull().defaultTo(0))
.execute()
} catch (error) {
// At least on postgres, `if not exists` doesn't guarantee the `create table`
// query doesn't throw if the table already exits. That's why we check if
// the table exist here and ignore the error if it does.
if (!(await doesTableExists(db, MIGRATION_LOCK_TABLE))) {
throw error
}
}
}
}
async function ensureLockRowExists(db: Kysely<any>): Promise<void> {
if (!(await doesLockRowExists(db))) {
try {
await db
.insertInto(MIGRATION_LOCK_TABLE)
.values({ id: MIGRATION_LOCK_ID })
.execute()
} catch (error) {
if (!(await doesLockRowExists(db))) {
throw error
}
}
}
}
async function doesTableExists(
db: Kysely<any>,
tableName: string
): Promise<boolean> {
const metadata = await db.introspection.getMetadata({
withInternalKyselyTables: true,
})
return !!metadata.tables.find((it) => it.name === tableName)
}
async function doesLockRowExists(db: Kysely<any>): Promise<boolean> {
const lockRow = await db
.selectFrom(MIGRATION_LOCK_TABLE)
.where('id', '=', MIGRATION_LOCK_ID)
.select('id')
.executeTakeFirst()
return !!lockRow
}
async function readMigrationsFromFolder(
migrationsFolderPath: string
): Promise<Record<string, Migration>> {
const files = await fs.readdir(migrationsFolderPath)
const migrations: Record<string, Migration> = {}
for (const file of files) {
if (
(file.endsWith('.js') || file.endsWith('.ts')) &&
!file.endsWith('.d.ts')
) {
const migration = await import(path.join(migrationsFolderPath, file))
if (isMigration(migration)) {
migrations[file.substring(0, file.length - 3)] = migration
}
}
}
return migrations
}
async function runNewMigrations(
db: Kysely<any>,
allMigrations: Record<string, Migration>
) {
const sortedMigrations = Object.keys(allMigrations)
.sort()
.map((name) => ({
...allMigrations[name],
name,
}))
const executedMigrations = await db
.selectFrom(MIGRATION_TABLE)
.select('name')
.orderBy('name')
.execute()
const lastExecuted = getLast(executedMigrations)
const lastExecutedIndex = sortedMigrations.findIndex(
(it) => it.name === lastExecuted?.name
)
if (lastExecuted && lastExecutedIndex === -1) {
throw new Error(
`corrupted migrations: previously executed migration ${lastExecuted.name} is missing`
)
}
const oldMigrations = lastExecuted
? sortedMigrations.slice(0, lastExecutedIndex + 1)
: []
const newMigrations = lastExecuted
? sortedMigrations.slice(lastExecutedIndex + 1)
: sortedMigrations
ensureMigrationsAreNotCorrupted(
executedMigrations.map((it) => it.name),
oldMigrations.map((it) => it.name)
)
for (const migration of newMigrations) {
await migration.up(db)
await db
.insertInto(MIGRATION_TABLE)
.values({
name: migration.name,
timestamp: new Date().toISOString(),
})
.execute()
}
}
function ensureMigrationsAreNotCorrupted(
executedMigrationNames: string[],
oldMigrationNames: string[]
) {
const executedSet = new Set(executedMigrationNames)
const oldMigrationSet = new Set(oldMigrationNames)
for (const it of executedSet) {
if (!oldMigrationSet.has(it)) {
throw new Error(
`corrupted migrations: previously executed migration ${it} is missing`
)
}
}
for (const it of oldMigrationSet) {
if (!executedSet.has(it)) {
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.`
)
}
}
}
function isMigration(obj: unknown): obj is Migration {
return isObject(obj) && isFunction(obj.up) && isFunction(obj.down)
}