From e890e349fb041b593602a26e0a422160e6b63482 Mon Sep 17 00:00:00 2001 From: Reenly <69853981+Reenly@users.noreply.github.com> Date: Fri, 27 Dec 2024 22:45:04 +0200 Subject: [PATCH] setup sql framework --- src/sqlFunctions.js | 68 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 src/sqlFunctions.js diff --git a/src/sqlFunctions.js b/src/sqlFunctions.js new file mode 100644 index 0000000..0dc6c02 --- /dev/null +++ b/src/sqlFunctions.js @@ -0,0 +1,68 @@ +const sqlite3 = require('sqlite3').verbose(); + +//TODO +// MUTEX functions for adding/removing/upsert +// basic read function by id +// complex read function by value range + +async function InitTable() { + const db = new sqlite3.Database('bot_data'); + try{ + await runQuery(db,'CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)') + console.log('Table created successfully.'); + + // Insert data + await runQuery(db, 'INSERT INTO users (name) VALUES (?)', ['Alice']); + console.log('Data inserted successfully.'); + + // Retrieve a single row + const row = await getQuery(db, 'SELECT * FROM users WHERE name = ?', ['Alice']); + console.log('Retrieved row:', row); + + // Retrieve all rows + const rows = await allQuery(db, 'SELECT * FROM users'); + console.log('All rows:', rows); + } catch (err) { + console.error('Database error:', err.message); + } finally { + db.close(); + } +} +function runQuery(db, query , params = []) { + return new Promise((resolve,reject) => { + db.run(query, params, function (err) { + if(err){ + reject(err); + } + else{ + resolve(this); + } + }); + }); +} +function getQuery(db, query, params = []) { + return new Promise((resolve, reject) => { + db.get(query, params, (err, row) => { + if (err) { + reject(err); + } else { + resolve(row); + } + }); + }); +} +function allQuery(db, query, params = []) { + return new Promise((resolve, reject) => { + db.all(query, params, (err, rows) => { + if (err) { + reject(err); + } else { + resolve(rows); + } + }); + }); +} + +module.exports = { + InitTable +} \ No newline at end of file