Db tools extend

This commit is contained in:
mrfry 2021-05-26 16:09:51 +02:00
parent 4c03e05686
commit ca742fce80

View file

@ -2,16 +2,17 @@
// https://github.com/JoshuaWise/better-sqlite3/blob/HEAD/docs/api.md
export default {
GetDB,
AddColumn,
TableInfo,
Update,
Delete,
CreateTable,
SelectAll,
Select,
Insert,
CloseDB,
GetDB: GetDB,
AddColumn: AddColumn,
TableInfo: TableInfo,
Update: Update,
Delete: Delete,
CreateTable: CreateTable,
SelectAll: SelectAll,
Select: Select,
Insert: Insert,
CloseDB: CloseDB,
runStatement: runStatement,
}
import Sqlite from 'better-sqlite3'
@ -21,7 +22,7 @@ import utils from '../utils/utils'
const debugLog = process.env.NS_SQL_DEBUG_LOG
// { asd: 'asd', basd: 4 } => asd = 'asd', basd = 4
function GetSqlQuerry(conditions, type) {
function GetSqlQuerry(conditions: any, type: string, joiner?: string) {
const res = Object.keys(conditions).reduce((acc, key) => {
const item = conditions[key]
if (typeof item === 'string') {
@ -32,7 +33,11 @@ function GetSqlQuerry(conditions, type) {
return acc
}, [])
if (type === 'where') {
return res.join(' AND ')
if (joiner) {
return res.join(` ${joiner} `)
} else {
return res.join(' AND ')
}
} else {
return res.join(', ')
}
@ -158,7 +163,7 @@ function CreateTable(db: any, name: any, columns: any, foreignKeys: any): any {
}
// IF NOT EXISTS
const command = `CREATE TABLE ${name}(${cols}${fKeys.join(', ')})`
const command = `CREATE TABLE ${name}(${cols}${fKeys.join(' ')})`
const stmt = PrepareStatement(db, command)
return stmt.run()
} catch (err) {
@ -177,13 +182,21 @@ function SelectAll(db: any, from: any): any {
}
}
function Select(db: any, from: any, conditions: any): any {
// SELECT * FROM MyTable WHERE SomeColumn > LastValue ORDER BY SomeColumn LIMIT 100;
function Select(db: any, from: any, conditions: any, options: any = {}): any {
const { joiner, limit } = options
try {
const command = `SELECT * from ${from} WHERE ${GetSqlQuerry(
let command = `SELECT * from ${from} WHERE ${GetSqlQuerry(
conditions,
'where'
'where',
joiner
)}`
if (!isNaN(limit)) {
command += ` LIMIT ${limit}`
}
const stmt = PrepareStatement(db, command)
return stmt.all()
} catch (err) {
@ -221,6 +234,15 @@ function Insert(db: any, table: any, data: any): any {
}
}
function runStatement(db: any, command: string, runType?: string): any {
const stmt = PrepareStatement(db, command)
if (!runType) {
return stmt.all()
} else if (runType === 'run') {
return stmt.run()
}
}
function CloseDB(db: any): void {
db.close((err) => {
if (err) {