-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit_tables.ts
More file actions
82 lines (75 loc) · 2.45 KB
/
init_tables.ts
File metadata and controls
82 lines (75 loc) · 2.45 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
import { knexDb } from "@db/knexfile";
import { getLogger } from "@logtape/logtape";
import { GuildSeasonTable } from "@v1/guild/models";
import {
MatchCharacterTable,
MatchPlayerTable,
MatchTable,
SSBUCharTable,
} from "@v1/match/models";
import { MatchReportView, MatchWinnerView } from "@v1/match/views";
import { SeasonTable } from "@v1/season/models";
import type { Knex } from "knex";
const log = getLogger(["grindcord", "db"]);
const tables = [
MatchTable,
MatchPlayerTable,
MatchCharacterTable,
SSBUCharTable,
SeasonTable,
GuildSeasonTable,
];
const views = [MatchWinnerView, MatchReportView];
async function create_table_if_notexists(
db: Knex = knexDb,
tableName: string,
callback: (tableBuilder: Knex.CreateTableBuilder) => void,
): Promise<Knex.SchemaBuilder> {
const exists = await db.schema.hasTable(tableName);
if (!exists) {
log.info(`${tableName} table not found. Creating table for ${tableName}.`);
await db.schema.createTable(tableName, callback);
log.info(`${tableName} table successfully initialized.`);
} else {
log.info(
`Database already contains ${tableName} table. Skipping initialization.`,
);
}
}
export async function init_tables(db: Knex = knexDb): Promise<void> {
const trx = await db.transaction();
for (const table of tables) {
await create_table_if_notexists(trx, table.table_name, table.initialize);
}
await trx.seed.run();
await trx.commit();
}
export async function seed_db(
seedSource: Knex.SeedSource<unknown>,
db: Knex = knexDb,
): Promise<void> {
await db.seed.run({ seedSource });
}
export async function init_views(db: Knex = knexDb) {
const trx = await db.transaction();
for (const _view of views) {
const view = _view(db);
await trx.schema.createViewOrReplace(view.view_name, view.initialize);
log.info(`${view.view_name} view successfully initialized.`);
}
await trx.commit();
}
export async function teardown(db: Knex = knexDb) {
if (process.env.NODE_ENV === "production") {
log.error(
"`teardown` was called on a production database -- no action will be performed",
);
return;
}
const trx = await db.transaction();
for (const table of tables) {
await trx.schema.dropTableIfExists(table.table_name);
}
await trx.commit();
log.info("Successfully performed `teardown` on database");
}