-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdb.ts
More file actions
executable file
·49 lines (41 loc) · 1.21 KB
/
db.ts
File metadata and controls
executable file
·49 lines (41 loc) · 1.21 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
import Database = require("better-sqlite3")
import * as C from "./config"
import * as log from "./log"
export const DB = Database(C.get("db"))
const migrations = [
`
--whatever
`
]
const executeMigration = DB.transaction((i) => {
const migration = migrations[i]
DB.exec(migration)
DB.pragma(`user_version = ${i + 1}`)
log.info(`Migrated to schema ${i + 1}`)
})
const schemaVersion = DB.pragma("user_version", { simple: true })
if (schemaVersion < migrations.length) {
log.info(`Migrating DB - schema ${schemaVersion} used, schema ${migrations.length} available`)
for (let i = schemaVersion; i < migrations.length; i++) {
executeMigration(i)
}
}
DB.pragma("foreign_keys = 1")
const preparedStatements = new Map()
export const SQL = (strings, ...params) => {
const sql = strings.join("?")
let stmt
const cachedValue = preparedStatements.get(sql)
if (!cachedValue) {
stmt = DB.prepare(sql)
preparedStatements.set(sql, stmt)
} else {
stmt = cachedValue
}
return {
get: () => stmt.get.apply(stmt, params),
run: () => stmt.run.apply(stmt, params),
all: () => stmt.all.apply(stmt, params),
statement: stmt
}
}