forked from bewcloud/bewcloud
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigrate-db.ts
More file actions
101 lines (76 loc) · 2.56 KB
/
migrate-db.ts
File metadata and controls
101 lines (76 loc) · 2.56 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
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
import '@std/dotenv/load';
import Database, { sql } from '/lib/interfaces/database.ts';
const migrationsDirectoryPath = `${Deno.cwd()}/db-migrations`;
const migrationsDirectory = Deno.readDir(migrationsDirectoryPath);
const db = new Database({ throwOnConnectionError: true });
interface Migration {
id: string;
name: string;
executed_at: Date;
}
async function getExecutedMigrations(): Promise<Set<string>> {
const executedMigrations = new Set(
Array.from(
(await db.query<Migration>(sql`SELECT * FROM "bewcloud_migrations" ORDER BY "name" ASC`)).map((migration) =>
migration.name
),
),
);
return executedMigrations;
}
async function getMissingMigrations(): Promise<string[]> {
const existingMigrations: Set<string> = new Set();
for await (const migrationFile of migrationsDirectory) {
// Skip non-files
if (!migrationFile.isFile) {
continue;
}
// Skip files not in the "001-blah.pgsql" format
if (!migrationFile.name.match(/^\d+-.*(\.pgsql)$/)) {
continue;
}
existingMigrations.add(migrationFile.name);
}
// Sort migrations
const sortedExistingMigrations = [...existingMigrations].sort();
// Add everything to run, by default
const migrationsToExecute = new Set([...sortedExistingMigrations]);
try {
const executedMigrations = await getExecutedMigrations();
// Remove any existing migrations that were executed, from the list of migrations to execute
for (const executedMigration of executedMigrations) {
migrationsToExecute.delete(executedMigration);
}
} catch (_error) {
// The table likely doesn't exist, so run everything.
}
return Array.from(migrationsToExecute).sort();
}
async function runMigrations(missingMigrations: string[]): Promise<void> {
for (const missingMigration of missingMigrations) {
console.log(`Running "${missingMigration}"...`);
try {
const migrationSql = await Deno.readTextFile(`${migrationsDirectoryPath}/${missingMigration}`);
await db.query(migrationSql);
await db.query(sql`INSERT INTO "public"."bewcloud_migrations" ("name", "executed_at") VALUES ($1, NOW())`, [
missingMigration,
]);
console.log('Success!');
} catch (error) {
console.log('Failed!');
console.error(error);
throw error;
}
}
}
try {
const missingMigrations = await getMissingMigrations();
await runMigrations(missingMigrations);
if (missingMigrations.length === 0) {
console.log('No migrations to run!');
}
Deno.exit(0);
} catch (error) {
console.error(error);
Deno.exit(1);
}