Exit cleanup functions, authentication polish, db polish

This commit is contained in:
MrFry 2020-04-07 14:09:34 +02:00
parent fb8e12f8d2
commit c764c4f402
10 changed files with 314 additions and 229 deletions

View file

@ -21,8 +21,8 @@ const utils = require('../utils/utils.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) => {
function GetSqlQuerry (conditions, type) {
const res = Object.keys(conditions).reduce((acc, key) => {
const item = conditions[key]
if (typeof item === 'string') {
acc.push(`${key} = '${conditions[key]}'`)
@ -30,14 +30,21 @@ function GetSqlQuerry (conditions) {
acc.push(`${key} = ${conditions[key]}`)
}
return acc
}, []).join(', ')
}, [])
if (type === 'where') {
return res.join(' AND ')
} else {
return res.join(', ')
}
}
// -------------------------------------------------------------------------
function GetDB (path) {
utils.CreatePath(path)
return new Sqlite(path)
const res = new Sqlite(path)
res.pragma('synchronous = OFF')
return res
}
function DebugLog (msg) {
@ -87,7 +94,7 @@ function TableInfo (db, table) {
function Update (db, table, newData, conditions) {
try {
const s = `UPDATE ${table} SET ${GetSqlQuerry(newData)} WHERE ${GetSqlQuerry(conditions)}`
const s = `UPDATE ${table} SET ${GetSqlQuerry(newData, 'set')} WHERE ${GetSqlQuerry(conditions, 'where')}`
DebugLog(s)
const stmt = db.prepare(s)
@ -99,7 +106,7 @@ function Update (db, table, newData, conditions) {
function Delete (db, table, conditions) {
try {
const s = `DELETE FROM ${table} WHERE ${GetSqlQuerry(conditions)}`
const s = `DELETE FROM ${table} WHERE ${GetSqlQuerry(conditions, 'where')}`
DebugLog(s)
const stmt = db.prepare(s)
@ -137,14 +144,16 @@ function CreateTable (db, name, columns, foreignKeys) {
return acc
}, []).join(', ')
let fKeys = ''
let fKeys = []
if (foreignKeys) {
const { keysFrom, table, keysTo } = foreignKeys
fKeys = `, FOREIGN KEY(${keysFrom.join(', ')}) REFERENCES ${table}(${keysTo.join(', ')})`
foreignKeys.forEach((f) => {
const { keysFrom, table, keysTo } = f
fKeys.push(`, FOREIGN KEY(${keysFrom.join(', ')}) REFERENCES ${table}(${keysTo.join(', ')})`)
})
}
// IF NOT EXISTS
const s = `CREATE TABLE ${name}(${cols}${fKeys})`
const s = `CREATE TABLE ${name}(${cols}${fKeys.join(', ')})`
DebugLog(s)
const stmt = db.prepare(s)
@ -168,7 +177,7 @@ function SelectAll (db, from) {
function Select (db, from, conditions) {
try {
const s = `SELECT * from ${from} WHERE ${GetSqlQuerry(conditions)}`
const s = `SELECT * from ${from} WHERE ${GetSqlQuerry(conditions, 'where')}`
DebugLog(s)
const stmt = db.prepare(s)