-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
93 lines (73 loc) · 1.89 KB
/
index.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
import Database from "bun:sqlite";
import KV from "bun-kv";
import { exists, readdir } from "node:fs/promises";
import { join } from "node:path";
export type Migration = {
id: number;
name: string;
content: string;
};
export type MigrateOptions = {
migrations: string | Migration[];
log?: boolean;
};
export function withoutComments(str: String) {
let result = "";
let omit = false;
let char: string;
for (let i = 0; i < str.length; i++) {
char = str.charAt(i);
if (char == "#") {
omit = true;
} else if (char == "\n") {
omit = false;
}
if (!omit) {
result += char;
}
}
return result;
}
export async function migrations(path: string) {
if (!(await exists(path))) return [];
const filenames = await readdir(path);
return await Promise.all(
filenames.map(async (filename) => {
const file = Bun.file(join(path, filename));
return {
id: Number(filename.split(".")[0]),
name: filename,
content: withoutComments(await file.text()),
} as Migration;
})
);
}
export async function migrate(database: Database, options?: MigrateOptions) {
const kv = new KV(database, "__migrations__");
let last = Number(kv.get("last")) || -1;
if (!options) {
options = {
migrations: await migrations("./migrations"),
log: true,
};
}
if (typeof options.migrations === "string") {
options.migrations = await migrations(options.migrations);
}
if (options.migrations.length == 0) return;
if (options.log) {
console.log("🌩️ Running migrations...");
}
database.transaction((migrations: Migration[], log?: boolean) => {
for (let i = 0; i < migrations.length; i++) {
const migration = migrations[i];
if (migration.id > last) {
if (log) {
console.log(` ⚡ ${migration.name}`);
}
database.run(migration.content);
}
}
})(options.migrations, options.log);
kv.set("last", `${options.migrations[options.migrations.length - 1].id}`);
}