-
Notifications
You must be signed in to change notification settings - Fork 1
/
migrate.ts
executable file
·62 lines (53 loc) · 1.51 KB
/
migrate.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
import { join } from "https://deno.land/[email protected]/path/mod.ts";
import postgres from "https://deno.land/x/[email protected]/mod.js";
import { Migration, Options } from "./types.ts";
export async function migrate(
sql: postgres.Sql<Record<string | number | symbol, never>>,
options: Options = { path: "./migrations" } as Options,
) {
try {
await sql`select 'migrations'::regclass`;
} catch {
console.log("Migrations table creating");
await sql`create table migrations (
id serial primary key,
name text,
created_at timestamp with time zone not null default now()
)`;
}
const migrations: Array<Migration> = [];
for (const migration of Deno.readDirSync(options.path)) {
if (migration.isDirectory) {
continue;
}
migrations.push({
path: join(options.path, migration.name),
name: migration.name,
} as Migration);
}
const migrated = await sql`
select name from migrations
`;
const migrationsNew = migrations.sort((a, b) => a.name.localeCompare(b.name))
.filter(
(
migration,
) => !migrated.some((m) => m.name === migration.name),
);
console.log(
`Migrations detected (total: ${migrations.length}, new: ${migrationsNew.length})`,
);
for (const m of migrationsNew) {
console.log(`Migrations running, ${m.name}`);
await sql.file(m.path);
await sql`
insert into migrations (
name
) values (
${m.name}
)
`;
}
console.log("Migrations done");
console.log("");
}