-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathmigrator.ts
More file actions
60 lines (47 loc) · 1.52 KB
/
migrator.ts
File metadata and controls
60 lines (47 loc) · 1.52 KB
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
import crypto from 'node:crypto';
import fs from 'node:fs';
export interface KitConfig {
out: string;
schema: string;
}
export interface MigrationConfig {
migrationsFolder: string;
migrationsTable?: string;
migrationsSchema?: string;
}
export interface MigrationMeta {
sql: string[];
folderMillis: number;
hash: string;
bps: boolean;
}
export function readMigrationFiles(config: MigrationConfig): MigrationMeta[] {
const migrationFolderTo = config.migrationsFolder;
const migrationQueries: MigrationMeta[] = [];
const journalPath = `${migrationFolderTo}/meta/_journal.json`;
if (!fs.existsSync(journalPath)) {
throw new Error(`Can't find meta/_journal.json file`);
}
const journalAsString = fs.readFileSync(`${migrationFolderTo}/meta/_journal.json`).toString();
const journal = JSON.parse(journalAsString) as {
entries: { idx: number; when: number; tag: string; breakpoints: boolean }[];
};
for (const journalEntry of journal.entries) {
const migrationPath = `${migrationFolderTo}/${journalEntry.tag}.sql`;
try {
const query = fs.readFileSync(`${migrationFolderTo}/${journalEntry.tag}.sql`).toString();
const result = query.split('--> statement-breakpoint').map((it) => {
return it;
});
migrationQueries.push({
sql: result,
bps: journalEntry.breakpoints,
folderMillis: journalEntry.when,
hash: crypto.createHash('sha256').update(query).digest('hex'),
});
} catch {
throw new Error(`No file ${migrationPath} found in ${migrationFolderTo} folder`);
}
}
return migrationQueries;
}