-
Notifications
You must be signed in to change notification settings - Fork 181
/
migration.ts
409 lines (349 loc) · 12.1 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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/*
A new Migration is instantiated for each migration file.
It is responsible for storing the name of the file and knowing how to execute
the up and down migrations defined in the file.
*/
import { glob } from 'glob';
import { createReadStream, createWriteStream } from 'node:fs';
import { mkdir, readdir } from 'node:fs/promises';
import { basename, extname, join, resolve } from 'node:path';
import { cwd } from 'node:process';
import type { QueryResult } from 'pg';
import type { DBConnection } from './db';
import MigrationBuilder from './migrationBuilder';
import type { ColumnDefinitions } from './operations/tables';
import type {
Logger,
MigrationAction,
MigrationBuilderActions,
MigrationDirection,
RunnerOption,
} from './types';
import { getMigrationTableSchema } from './utils';
export interface RunMigration {
readonly path: string;
readonly name: string;
readonly timestamp: number;
}
export enum FilenameFormat {
timestamp = 'timestamp',
utc = 'utc',
}
export interface CreateOptionsTemplate {
templateFileName: string;
}
export interface CreateOptionsDefault {
language?: 'js' | 'ts' | 'sql';
ignorePattern?: string;
}
export type CreateOptions = {
filenameFormat?: FilenameFormat | `${FilenameFormat}`;
} & (CreateOptionsTemplate | CreateOptionsDefault);
const SEPARATOR = '_';
function localeCompareStringsNumerically(a: string, b: string): number {
return a.localeCompare(b, undefined, {
usage: 'sort',
numeric: true,
sensitivity: 'variant',
ignorePunctuation: true,
});
}
function compareFileNamesByTimestamp(
a: string,
b: string,
logger?: Logger
): number {
const aTimestamp = getNumericPrefix(a, logger);
const bTimestamp = getNumericPrefix(b, logger);
return aTimestamp - bTimestamp;
}
interface LoadMigrationFilesOptions {
/**
* Regex pattern for file names to ignore (ignores files starting with `.` by default).
* Alternatively, provide a [glob](https://www.npmjs.com/package/glob) pattern or
* an array of glob patterns and set `isGlob = true`
*
* Note: enabling glob will read both, `dir` _and_ `ignorePattern` as glob patterns
*/
ignorePattern?: string | string[];
/**
* Use [glob](https://www.npmjs.com/package/glob) to find migration files.
* This will use `dir` _and_ `options.ignorePattern` to glob-search for migration files.
*
* @default: false
*/
useGlob?: boolean;
/**
* Redirect messages to this logger object, rather than `console`.
*/
logger?: Logger;
}
/**
* Reads files from `dir`, sorts them and returns an array of their absolute paths.
* When not using globs, files are sorted by their numeric prefix values first. 17 digit numbers are interpreted as utc date and converted to the number representation of that date.
* Glob matches are sorted via String.localeCompare with ignored punctuation.
*
* @param dir The directory containing your migration files. This path is resolved from `cwd()`.
* Alternatively, provide a [glob](https://www.npmjs.com/package/glob) pattern or
* an array of glob patterns and set `options.useGlob = true`
*
* Note: enabling glob will read both, `dir` _and_ `options.ignorePattern` as glob patterns
* @param options
* @returns Array of absolute paths
*/
export async function getMigrationFilePaths(
/**
* The directory containing your migration files. This path is resolved from `cwd()`.
* Alternatively, provide a [glob](https://www.npmjs.com/package/glob) pattern or
* an array of glob patterns and set `options.useGlob = true`
*
* Note: enabling glob will read both, `dir` _and_ `options.ignorePattern` as glob patterns
*/
dir: string | string[],
options: LoadMigrationFilesOptions = {}
): Promise<string[]> {
const { ignorePattern, useGlob = false, logger } = options;
if (useGlob) {
/**
* By default, a `**` in a pattern will follow 1 symbolic link if
* it is not the first item in the pattern, or none if it is the
* first item in the pattern, following the same behavior as Bash.
*
* Only want files, no dirs.
*/
const globMatches = await glob(dir, {
ignore: ignorePattern,
nodir: true,
absolute: true,
});
return globMatches.sort(localeCompareStringsNumerically);
}
if (Array.isArray(dir) || Array.isArray(ignorePattern)) {
throw new TypeError(
'Options "dir" and "ignorePattern" can only be arrays when "useGlob" is true'
);
}
const ignoreRegexp = new RegExp(
ignorePattern?.length ? `^${ignorePattern}$` : '^\\..*'
);
const dirContent = await readdir(`${dir}/`, { withFileTypes: true });
return dirContent
.filter(
(dirent) =>
(dirent.isFile() || dirent.isSymbolicLink()) &&
!ignoreRegexp.test(dirent.name)
)
.sort(
(a, b) =>
compareFileNamesByTimestamp(a.name, b.name, logger) ||
localeCompareStringsNumerically(a.name, b.name)
)
.map((dirent) => resolve(dir, dirent.name));
}
function getSuffixFromFileName(fileName: string): string {
return extname(fileName).slice(1);
}
async function getLastSuffix(
dir: string,
ignorePattern?: string
): Promise<string | undefined> {
try {
const files = await getMigrationFilePaths(dir, { ignorePattern });
return files.length > 0
? getSuffixFromFileName(files[files.length - 1])
: undefined;
} catch {
return undefined;
}
}
/**
* extracts numeric value from everything in `filename` before `SEPARATOR`.
* 17 digit numbers are interpreted as utc date and converted to the number representation of that date.
* @param filename filename to extract the prefix from
* @param logger Redirect messages to this logger object, rather than `console`.
* @returns numeric value of the filename prefix (everything before `SEPARATOR`).
*/
export function getNumericPrefix(
filename: string,
logger: Logger = console
): number {
const prefix = filename.split(SEPARATOR)[0];
if (prefix && /^\d+$/.test(prefix)) {
if (prefix.length === 13) {
// timestamp: 1391877300255
return Number(prefix);
}
if (prefix && prefix.length === 17) {
// utc: 20200513070724505
const year = prefix.slice(0, 4);
const month = prefix.slice(4, 6);
const date = prefix.slice(6, 8);
const hours = prefix.slice(8, 10);
const minutes = prefix.slice(10, 12);
const seconds = prefix.slice(12, 14);
const ms = prefix.slice(14, 17);
return new Date(
`${year}-${month}-${date}T${hours}:${minutes}:${seconds}.${ms}Z`
).valueOf();
}
}
logger.error(`Can't determine timestamp for ${prefix}`);
return Number(prefix) || 0;
}
async function resolveSuffix(
directory: string,
options: CreateOptionsDefault
): Promise<string> {
const { language, ignorePattern } = options;
return language || (await getLastSuffix(directory, ignorePattern)) || 'js';
}
export class Migration implements RunMigration {
// class method that creates a new migration file by cloning the migration template
static async create(
name: string,
directory: string,
options: CreateOptions = {}
): Promise<string> {
const { filenameFormat = FilenameFormat.timestamp } = options;
// ensure the migrations directory exists
await mkdir(directory, { recursive: true });
const now = new Date();
const time =
filenameFormat === FilenameFormat.utc
? now.toISOString().replace(/\D/g, '')
: now.valueOf();
const templateFileName =
'templateFileName' in options
? resolve(cwd(), options.templateFileName)
: resolve(
join('node_modules', 'node-pg-migrate', 'templates'),
`migration-template.${await resolveSuffix(directory, options)}`
);
const suffix = getSuffixFromFileName(templateFileName);
// file name looks like migrations/1391877300255_migration-title.js
const newFile = join(directory, `${time}${SEPARATOR}${name}.${suffix}`);
// copy the default migration template to the new file location
await new Promise((resolve, reject) => {
createReadStream(templateFileName)
.pipe(createWriteStream(newFile))
.on('close', resolve)
.on('error', reject);
});
return newFile;
}
public readonly db: DBConnection;
public readonly path: string;
public readonly name: string;
public readonly timestamp: number;
public up?: false | MigrationAction;
public down?: false | MigrationAction;
public readonly options: RunnerOption;
public readonly typeShorthands?: ColumnDefinitions;
public readonly logger: Logger;
constructor(
db: DBConnection,
migrationPath: string,
{ up, down }: MigrationBuilderActions,
options: RunnerOption,
typeShorthands?: ColumnDefinitions,
logger: Logger = console
) {
this.db = db;
this.path = migrationPath;
this.name = basename(migrationPath, extname(migrationPath));
this.timestamp = getNumericPrefix(this.name, logger);
this.up = up;
this.down = down;
this.options = options;
this.typeShorthands = typeShorthands;
this.logger = logger;
}
_getMarkAsRun(action: MigrationAction): string {
const schema = getMigrationTableSchema(this.options);
const { migrationsTable } = this.options;
const { name } = this;
switch (action) {
case this.down: {
this.logger.info(`### MIGRATION ${this.name} (DOWN) ###`);
return `DELETE FROM "${schema}"."${migrationsTable}" WHERE name='${name}';`;
}
case this.up: {
this.logger.info(`### MIGRATION ${this.name} (UP) ###`);
return `INSERT INTO "${schema}"."${migrationsTable}" (name, run_on) VALUES ('${name}', NOW());`;
}
default: {
throw new Error('Unknown direction');
}
}
}
async _apply(
action: MigrationAction,
pgm: MigrationBuilder
): Promise<unknown> {
if (action.length === 2) {
await new Promise<void>((resolve) => {
action(pgm, resolve);
});
} else {
await action(pgm);
}
const sqlSteps = pgm.getSqlSteps();
sqlSteps.push(this._getMarkAsRun(action));
if (!this.options.singleTransaction && pgm.isUsingTransaction()) {
// if not in singleTransaction mode we need to create our own transaction
sqlSteps.unshift('BEGIN;');
sqlSteps.push('COMMIT;');
} else if (this.options.singleTransaction && !pgm.isUsingTransaction()) {
// in singleTransaction mode we are already wrapped in a global transaction
this.logger.warn('#> WARNING: Need to break single transaction! <');
sqlSteps.unshift('COMMIT;');
sqlSteps.push('BEGIN;');
} else if (!this.options.singleTransaction || !pgm.isUsingTransaction()) {
this.logger.warn(
'#> WARNING: This migration is not wrapped in a transaction! <'
);
}
if (typeof this.logger.debug === 'function') {
this.logger.debug(`${sqlSteps.join('\n')}\n\n`);
}
return sqlSteps.reduce<Promise<unknown>>(
(promise, sql) =>
promise.then((): unknown => this.options.dryRun || this.db.query(sql)),
Promise.resolve()
);
}
_getAction(direction: MigrationDirection): MigrationAction {
if (direction === 'down' && this.down === undefined) {
this.down = this.up;
}
const action: MigrationAction | false | undefined = this[direction];
if (action === false) {
throw new Error(
`User has disabled ${direction} migration on file: ${this.name}`
);
}
if (typeof action !== 'function') {
throw new Error(
`Unknown value for direction: ${direction}. Is the migration ${this.name} exporting a '${direction}' function?`
);
}
return action;
}
apply(direction: MigrationDirection): Promise<unknown> {
const pgm = new MigrationBuilder(
this.db,
this.typeShorthands,
Boolean(this.options.decamelize),
this.logger
);
const action = this._getAction(direction);
if (this.down === this.up) {
// automatically infer the down migration by running the up migration in reverse mode...
pgm.enableReverseMode();
}
return this._apply(action, pgm);
}
markAsRun(direction: MigrationDirection): Promise<QueryResult> {
return this.db.query(this._getMarkAsRun(this._getAction(direction)));
}
}