mrfrys-node-server/utils/dbtools.js
2020-04-03 08:54:48 +02:00

189 lines
3.8 KiB
JavaScript

// https://www.sqlitetutorial.net/sqlite-nodejs/
// https://github.com/JoshuaWise/better-sqlite3/blob/HEAD/docs/api.md
module.exports = {
GetDB,
AddColumn,
TableInfo,
UpdateRecord,
Delete,
CreateTable,
SelectAll,
Select,
Insert,
CloseDB
}
const Sqlite = require('better-sqlite3')
const logger = require('../utils/logger.js')
const debugLog = process.env.NS_SQL_DEBUG_LOG
// { asd: 'asd', basd: 4 } => asd = 'asd', basd = 4
function GetSqlQuerry (conditions) {
return Object.keys(conditions).reduce((acc, key) => {
const item = conditions[key]
if (typeof item === 'string') {
acc.push(`${key} = '${conditions[key]}'`)
} else {
acc.push(`${key} = ${conditions[key]}`)
}
return acc
}, []).join(', ')
}
// -------------------------------------------------------------------------
function GetDB (path) {
return new Sqlite(path)
}
function DebugLog (msg) {
if (debugLog) {
logger.DebugLog(msg, 'sql', 0)
}
}
function AddColumn (db, table, col) {
try {
const colName = Object.keys(col)[0]
const colType = col.type
const s = `ALTER TABLE ${table} ADD COLUMN ${colName} ${colType}`
DebugLog(s)
const stmt = db.prepare(s)
return stmt.run()
} catch (e) {
console.error(e)
}
}
function TableInfo (db, table) {
try {
} catch (e) {
console.error(e)
}
const s = `PRAGMA table_info(${table})`
DebugLog(s)
const stmt = db.prepare(s)
const infoRes = stmt.all()
const s2 = `SELECT COUNT(*) FROM ${table}`
DebugLog(s2)
const stmt2 = db.prepare(s2)
const countRes = stmt2.get()
return {
columns: infoRes,
dataCount: countRes[Object.keys(countRes)[0]]
}
}
function UpdateRecord (db, table, newData, conditions) {
try {
const s = `UPDATE ${table} SET ${GetSqlQuerry(newData)} WHERE ${GetSqlQuerry(conditions)}`
DebugLog(s)
const stmt = db.prepare(s)
return stmt.run()
} catch (e) {
console.error(e)
}
}
function Delete (db, table, conditions) {
try {
const s = `DELETE FROM ${table} WHERE ${GetSqlQuerry(conditions)}`
DebugLog(s)
const stmt = db.prepare(s)
return stmt.run()
} catch (e) {
console.error(e)
}
}
function CreateTable (db, name, columns) {
try {
const cols = Object.keys(columns).reduce((acc, key) => {
const item = columns[key]
const isPrimary = item.primary ? ' PRIMARY KEY' : ''
const isNotNull = item.notNull ? ' NOT NULL' : ''
acc.push(`${key} ${item.type}${isPrimary}${isNotNull}`)
return acc
}, []).join(', ')
const s = `CREATE TABLE IF NOT EXISTS ${name}(${cols})`
DebugLog(s)
const stmt = db.prepare(s)
return stmt.run()
} catch (e) {
console.error(e)
}
}
function SelectAll (db, from) {
try {
const s = `SELECT * from ${from}`
DebugLog(s)
const stmt = db.prepare(s)
return stmt.all()
} catch (e) {
console.error(e)
}
}
function Select (db, from, conditions) {
try {
const s = `SELECT * from ${from} WHERE ${GetSqlQuerry(conditions)}`
DebugLog(s)
const stmt = db.prepare(s)
return stmt.all()
} catch (e) {
console.error(e)
}
}
function Insert (db, table, data) {
try {
const cols = Object.keys(data).reduce((acc, key) => {
acc.push(`${key}`)
return acc
}, []).join(', ')
const values = Object.keys(data).reduce((acc, key) => {
const item = data[key]
if (typeof item === 'string') {
acc.push(`'${item}'`)
} else {
acc.push(`${item}`)
}
return acc
}, []).join(', ')
const s = `INSERT INTO ${table} (${cols}) VALUES (${values})`
DebugLog(s)
const stmt = db.prepare(s)
return stmt.run()
} catch (e) {
console.error(e)
}
}
function CloseDB (db) {
db.close((err) => {
if (err) {
return console.error(err.message)
}
DebugLog('Close the database connection.')
})
}