Moe-Counter/db/sqlite.js

70 lines
1.6 KiB
JavaScript
Raw Permalink Normal View History

2020-08-05 05:37:12 +00:00
'use strict'
const path = require('path')
const Database = require('better-sqlite3')
2020-08-03 12:11:58 +00:00
const db = new Database(path.resolve(__dirname, '../count.db'))
2020-08-03 12:11:58 +00:00
db.exec(`CREATE TABLE IF NOT EXISTS tb_count (
2020-08-03 12:11:58 +00:00
id INTEGER PRIMARY KEY AUTOINCREMENT
NOT NULL
UNIQUE,
name VARCHAR (32) NOT NULL
UNIQUE,
num BIGINT NOT NULL
DEFAULT (0)
);`)
function getNum(name) {
return new Promise((resolve, reject) => {
const stmt = db.prepare('SELECT `name`, `num` from tb_count WHERE `name` = ?')
const row = stmt.get(name)
resolve(row || { name, num: 0 })
2020-08-03 12:11:58 +00:00
})
}
function getAll(name) {
return new Promise((resolve, reject) => {
const stmt = db.prepare('SELECT * from tb_count')
const rows = stmt.all()
resolve(rows)
2020-08-03 12:11:58 +00:00
})
}
function setNum(name, num) {
return new Promise((resolve, reject) => {
db.exec(`INSERT INTO tb_count(\`name\`, \`num\`)
2020-08-03 12:11:58 +00:00
VALUES($name, $num)
ON CONFLICT(name) DO
UPDATE SET \`num\` = $num;`
,
{ $name: name, $num: num }
)
resolve()
})
}
function setNumMulti(counters) {
return new Promise((resolve, reject) => {
const stmt = db.prepare(`INSERT INTO tb_count(\`name\`, \`num\`)
VALUES($name, $num)
ON CONFLICT(name) DO
UPDATE SET \`num\` = $num;`)
const setMany = db.transaction((counters) => {
for (const counter of counters) stmt.run(counter)
})
setMany(counters)
resolve()
2020-08-03 12:11:58 +00:00
})
}
module.exports = {
getNum,
getAll,
setNum,
setNumMulti
}