Skip to content

Commit 4cd038f

Browse files
committed
fix: fix multiple schema init bug
1 parent 7d0589e commit 4cd038f

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

src/db/schema.js

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
module.exports = (db) => {
22
// Create schema in database
33

4-
const sqlInit = `
4+
const { user_version: userVersion } = db.prepare("PRAGMA user_version").get()
5+
6+
if (userVersion === 0) {
7+
const sqlInit = `
58
CREATE TABLE IF NOT EXISTS session_state (
69
session_state_id INTEGER PRIMARY KEY AUTOINCREMENT,
710
short_id TEXT NOT NULL,
@@ -48,10 +51,13 @@ module.exports = (db) => {
4851
4952
CREATE INDEX IF NOT EXISTS short_id_idx ON session_state(short_id);
5053
CREATE INDEX IF NOT EXISTS previous_session_state_id_idx ON session_state(previous_session_state_id);
51-
CREATE INDEX IF NOT EXISTS sample_short_id_idx ON sample_state(session_short_id);`
52-
try {
53-
db.exec(sqlInit)
54-
} catch (e) {
55-
throw new Error(`Database failed to initialize: ${e.toString()}`)
54+
CREATE INDEX IF NOT EXISTS sample_short_id_idx ON sample_state(session_short_id);
55+
56+
PRAGMA user_version = 1;`
57+
try {
58+
db.exec(sqlInit)
59+
} catch (e) {
60+
throw new Error(`Database failed to initialize: ${e.toString()}`)
61+
}
5662
}
5763
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
const test = require("ava")
2+
const getDB = require("../src/db")
3+
const applySchema = require("../src/db/schema.js")
4+
5+
test("multiple schema initializations", async (t) => {
6+
const db = await getDB({ testDB: true })
7+
applySchema(db)
8+
applySchema(db)
9+
t.pass("didn't error reapplying schema")
10+
})

0 commit comments

Comments
 (0)