Merge pull request 'setup sql framework' (#2) from experimental into main
Reviewed-on: #2
This commit is contained in:
commit
6cd6dd559d
1 changed files with 68 additions and 0 deletions
68
src/sqlFunctions.js
Normal file
68
src/sqlFunctions.js
Normal 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
|
||||
}
|
Loading…
Reference in a new issue