From efdf50a55a32c18c3563b883563f271531a6c38b Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Sun, 14 May 2023 01:50:19 +0200 Subject: Implemented a basic extraction loop --- database/000_init.sql | 8 ++++++++ database/config.js | 23 +++++++++++++++++++++++ database/db.js | 29 +++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 database/000_init.sql create mode 100644 database/config.js create mode 100644 database/db.js (limited to 'database') diff --git a/database/000_init.sql b/database/000_init.sql new file mode 100644 index 0000000..ecda95a --- /dev/null +++ b/database/000_init.sql @@ -0,0 +1,8 @@ +CREATE TABLE schema_version ( + version INTEGER NOT NULL +); +CREATE TABLE config ( + id INTEGER PRIMARY KEY, + key TEXT NOT NULL UNIQUE, + value TEXT NOT NULL +); diff --git a/database/config.js b/database/config.js new file mode 100644 index 0000000..6db856e --- /dev/null +++ b/database/config.js @@ -0,0 +1,23 @@ +import db from './db.js'; + +const getTokenStatement = db.prepare(`SELECT value from config where key = 'token';`); +const registerAgentStatement = db.prepare(`INSERT INTO config(key, value) VALUES ('symbol', ?), ('faction', ?), ('token', ?);`); + +export function getToken() { + try { + return getTokenStatement.get().value; + } catch (err) { + console.log(err); + return null; + } +} + +export function registerAgent(symbol, faction, token) { + try { + registerAgentStatement.run(symbol, faction, token); + return true; + } catch (err) { + console.log(err); + return false; + } +} diff --git a/database/db.js b/database/db.js new file mode 100644 index 0000000..db71080 --- /dev/null +++ b/database/db.js @@ -0,0 +1,29 @@ +import fs from 'fs'; +import Database from 'better-sqlite3'; + +const allMigrations = [ + 'database/000_init.sql', +]; + +const db = new Database( + process.env.NODE_ENV === 'test' ? 'test.db' : 'spacetraders.db', + process.env.NODE_ENV === 'development' ? { verbose: console.log } : null +); +db.pragma('foreign_keys = ON'); + +db.transaction(function migrate() { + let version; + try { + version = db.prepare('SELECT version FROM schema_version').get().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; -- cgit v1.2.3