31 lines
2.2 KiB
TypeScript
31 lines
2.2 KiB
TypeScript
import type Database from 'better-sqlite3';
|
|
|
|
export function installReportRevisions(handle: Database.Database) {
|
|
handle.exec(`CREATE TABLE IF NOT EXISTS report_revisions (topic TEXT PRIMARY KEY, revision INTEGER NOT NULL DEFAULT 0);
|
|
INSERT OR IGNORE INTO report_revisions(topic) VALUES ('metrics'), ('leaderboard');`);
|
|
for (const table of ['metric_samples', 'servers']) for (const action of ['INSERT', 'UPDATE', 'DELETE']) {
|
|
const condition = table === 'servers' && action === 'UPDATE' ? 'WHEN OLD.destroyed_at IS NOT NEW.destroyed_at OR OLD.name IS NOT NEW.name' : '';
|
|
handle.exec(`CREATE TRIGGER IF NOT EXISTS report_${table}_${action} AFTER ${action} ON ${table} ${condition}
|
|
BEGIN UPDATE report_revisions SET revision=revision+1 WHERE topic='metrics'; END;`);
|
|
}
|
|
if (handle.prepare("SELECT 1 FROM settings WHERE key='completed_report_revisions_v1'").get()) return;
|
|
handle.transaction(() => {
|
|
for (const table of ['leaderboard_matches', 'leaderboard_match_players', 'leaderboard_players']) {
|
|
for (const action of ['INSERT', 'UPDATE', 'DELETE']) {
|
|
const name = `report_${table}_${action}`;
|
|
const versions = action === 'INSERT' ? ['NEW'] : action === 'DELETE' ? ['OLD'] : ['OLD', 'NEW'];
|
|
const condition = table === 'leaderboard_matches'
|
|
? `WHEN ${versions.map(row => `${row}.status='completed'`).join(' OR ')}`
|
|
: table === 'leaderboard_match_players'
|
|
? `WHEN ${versions.map(row => `(SELECT status FROM leaderboard_matches WHERE id=${row}.match_id)='completed'`).join(' OR ')}`
|
|
: action === 'UPDATE' ? 'WHEN OLD.name IS NOT NEW.name' : '';
|
|
const event = table === 'leaderboard_players' && action === 'UPDATE' ? 'UPDATE OF name' : action;
|
|
handle.exec(`DROP TRIGGER IF EXISTS ${name};
|
|
CREATE TRIGGER ${name} AFTER ${event} ON ${table} ${condition}
|
|
BEGIN UPDATE report_revisions SET revision=revision+1 WHERE topic='leaderboard'; END;`);
|
|
}
|
|
}
|
|
handle.exec("INSERT INTO settings(key,value) VALUES('completed_report_revisions_v1','1')");
|
|
})();
|
|
}
|