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