summaryrefslogtreecommitdiff
path: root/database/db.js
diff options
context:
space:
mode:
authorJulien Dessaux2022-10-28 23:51:18 +0200
committerJulien Dessaux2022-10-28 23:51:18 +0200
commit4c42c4fda1616f2fc96bb566e1e2200ea756f0d5 (patch)
treede3e1e095b3e23523fbb837cb5dda613ecdb479c /database/db.js
parentBegan implementing middlewares, session and auth (diff)
downloadjeux-de-mots-4c42c4fda1616f2fc96bb566e1e2200ea756f0d5.tar.gz
jeux-de-mots-4c42c4fda1616f2fc96bb566e1e2200ea756f0d5.tar.bz2
jeux-de-mots-4c42c4fda1616f2fc96bb566e1e2200ea756f0d5.zip
Added a basic database schema and migration function
Diffstat (limited to '')
-rw-r--r--database/db.js26
1 files changed, 26 insertions, 0 deletions
diff --git a/database/db.js b/database/db.js
new file mode 100644
index 0000000..d849429
--- /dev/null
+++ b/database/db.js
@@ -0,0 +1,26 @@
+import fs from "fs";
+import Database from "better-sqlite3";
+
+const allMigrations = [
+ "database/000_init.sql",
+];
+
+const db = new Database("jdm.db");
+db.pragma("foreign_keys = ON");
+
+db.transaction(function migrate() {
+ let version;
+ try {
+ version = db.prepare("SELECT version FROM schema_version").all()[0].version;
+ } catch {
+ version = 0;
+ }
+ if (version === allMigrations.length) return;
+ while (version < allMigrations.length) {
+ db.exec(fs.readFileSync(allMigrations[version], "utf8"));
+ version++;
+ }
+ db.exec(`DELETE FROM schema_version; INSERT INTO schema_version (version) VALUES (${version});`);
+})();
+
+export default db;