const fs = require('fs'); const databaseFile = "mytest.db" fs.readFile(databaseFile, (err, data) => { if (err) { fs.openSync(databaseFile, 'w'); const db = require('better-sqlite3')(databaseFile); // Bootstrap the db db.exec(` CREATE TABLE IF NOT EXISTS accounts ( number integer NOT NULL, name text NOT NULL, qualifiedName text NOT NULL UNIQUE, parentAccount text, description text NOT NULL, type TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS transactions ( transaction_id integer PRIMARY KEY, postingDate text NOT NULL, valueDate text, title text NOT NULL ); CREATE TABLE IF NOT EXISTS transaction_entries ( transaction_id int, account_name text NOT NULL, amount float, label text, FOREIGN KEY (transaction_id) REFERENCES transactions (transaction_id) FOREIGN KEY (account_name) REFERENCES accounts (qualifiedName) PRIMARY KEY (transaction_id, account_name) ); `) create_initial_accounts() } }) // DB const db = require('better-sqlite3')(databaseFile); function create_initial_accounts() { fs.readFile("accounts.json", "utf8", (err, jsonString) => { if (err) { console.log("Error reading the JSON file:", err); response.send("error") } try { account_data = JSON.parse(jsonString); for (let i = 0; i < account_data.length; i++) { account = account_data[i] console.log(account_data[i]["qualifiedName"]) parentAccount = account["qualifiedName"].split(":") parentAccount.pop() parentAccount = parentAccount.join(":") if (parentAccount == "") { parentAccount = undefined } const new_acc = db .prepare( `INSERT INTO accounts (number, name, qualifiedName, description, type, parentAccount) VALUES (?, ?, ? ,?, ?, ?)`, ) .run(account["number"], account["name"], account["qualifiedName"], "Initial Account", account["type"], parentAccount); } } catch (err) { console.log("Error parsing JSON string:", err); } }); } module.exports = { db, create_initial_accounts }