-
Notifications
You must be signed in to change notification settings - Fork 180
/
Copy pathsqlMigration.ts
50 lines (40 loc) · 1.33 KB
/
sqlMigration.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
import fs from 'fs';
import type { MigrationBuilderActions } from './types';
const { readFile } = fs.promises;
const createMigrationCommentRegex = (direction: 'up' | 'down') =>
new RegExp(`^\\s*--[\\s-]*${direction}\\s+migration`, 'im');
export const getActions = (content: string): MigrationBuilderActions => {
const upMigrationCommentRegex = createMigrationCommentRegex('up');
const downMigrationCommentRegex = createMigrationCommentRegex('down');
const upMigrationStart = content.search(upMigrationCommentRegex);
const downMigrationStart = content.search(downMigrationCommentRegex);
const upSql =
upMigrationStart >= 0
? content.substr(
upMigrationStart,
downMigrationStart < upMigrationStart ? undefined : downMigrationStart
)
: content;
const downSql =
downMigrationStart >= 0
? content.substr(
downMigrationStart,
upMigrationStart < downMigrationStart ? undefined : upMigrationStart
)
: undefined;
return {
up: (pgm) => {
pgm.sql(upSql);
},
down:
downSql === undefined
? false
: (pgm) => {
pgm.sql(downSql);
},
};
};
export default async (sqlPath: string): Promise<MigrationBuilderActions> => {
const content = await readFile(sqlPath, 'utf-8');
return getActions(content);
};