setup sql framework

This commit is contained in:
SolPuffy 2024-12-27 22:45:04 +02:00 committed by ulysia
parent 14759592b8
commit c3badac626

68
src/sqlFunctions.js Normal file
View file

@ -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
}