before delete 3software
This commit is contained in:
@@ -4,38 +4,15 @@ const sqlite3 = require('better-sqlite3')
|
||||
|
||||
const db = sqlite3(`./data/db.sqlite`)
|
||||
db.pragma('journal_mode = WAL')
|
||||
db.pragma('foreign_keys = on')
|
||||
|
||||
db.exec(fs.readFileSync('./data/init.sql', 'utf8'))
|
||||
|
||||
/*
|
||||
db.exec(`attach database './data/backup.sqlite' as backup`)
|
||||
|
||||
db.function('backup', (tblname, ...values) => {
|
||||
db
|
||||
.prepare(`insert into backup.${tblname} select ` + values.map(e => '?').join(', '))
|
||||
.run(values)
|
||||
})
|
||||
|
||||
const backupQuery = db
|
||||
.prepare(`
|
||||
select group_concat(tbl || char(13) || trg, char(13) || char(13)) from (
|
||||
select 'create table if not exists backup.' || t.name || ' (' || group_concat(c.name || ' ' || c.type, ', ') || ', time integer);' tbl,
|
||||
'create trigger if not exists trg_' || t.name || '_delete after delete on ' || t.name || ' for each row begin ' ||
|
||||
' select backup (' || t.name || ',' || group_concat('OLD.' || c.name, ', ') || ', strftime(''%s'', ''now'')); end;' trg
|
||||
from sqlite_master t left join pragma_table_xinfo c on t.tbl_name = c.arg and c.schema = 'main'
|
||||
where t.sql is not null and t.type = 'table' and t.name <> 'sqlite_sequence'
|
||||
group by t.type, t.name order by t.type, t.name)
|
||||
`)
|
||||
.pluck(true)
|
||||
.get()
|
||||
db.exec(backupQuery)
|
||||
*/
|
||||
|
||||
db.function('generate_key', (id, time) => {
|
||||
return [
|
||||
'KEY',
|
||||
Buffer.from(time + '').toString('base64'),
|
||||
crypto.createHash('md5').update(`sa${time}-${id}lt`).digest('hex')
|
||||
crypto.createHash('md5').update(`sa${time}-${id}lty`).digest('hex')
|
||||
].join('-')
|
||||
})
|
||||
|
||||
@@ -54,4 +31,16 @@ db.prepareUpdate = function (table, columns, data, where) {
|
||||
` where ` + where.map(col => `"${col}" = :${col}`).join(' and '))
|
||||
}
|
||||
|
||||
db.prepareUpsert = function (table, columns, data, where) {
|
||||
const dataColumns = columns.filter(col => col in data)
|
||||
if (dataColumns.length == 0)
|
||||
throw Error('SQLite Error: No data to update')
|
||||
|
||||
return db.prepare(
|
||||
`insert into "${table}" (` + [...dataColumns, ...where].join(', ') + `) values (:` + [...dataColumns, ...where].join(', :') +
|
||||
`) on conflict (` + where.join(',') + `) do update ` +
|
||||
`set ` + dataColumns.map(col => `"${col}" = :${col}`).join(', ') +
|
||||
` where ` + where.map(col => `"${col}" = :${col}`).join(' and '))
|
||||
}
|
||||
|
||||
module.exports = db
|
||||
Reference in New Issue
Block a user