2020-08-05 07:37:12 +02:00
|
|
|
'use strict'
|
|
|
|
|
|
|
|
const path = require('path')
|
2023-03-06 11:57:41 +01:00
|
|
|
const Database = require('better-sqlite3')
|
2020-08-03 14:11:58 +02:00
|
|
|
|
2023-03-06 11:57:41 +01:00
|
|
|
const db = new Database(path.resolve(__dirname, '../count.db'))
|
2020-08-03 14:11:58 +02:00
|
|
|
|
2023-03-06 11:57:41 +01:00
|
|
|
db.exec(`CREATE TABLE IF NOT EXISTS tb_count (
|
2020-08-03 14:11:58 +02: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) => {
|
2023-03-06 11:57:41 +01:00
|
|
|
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 14:11:58 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
function getAll(name) {
|
|
|
|
return new Promise((resolve, reject) => {
|
2023-03-06 11:57:41 +01:00
|
|
|
const stmt = db.prepare('SELECT * from tb_count')
|
|
|
|
const rows = stmt.all()
|
|
|
|
resolve(rows)
|
2020-08-03 14:11:58 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
function setNum(name, num) {
|
|
|
|
return new Promise((resolve, reject) => {
|
2023-03-06 11:57:41 +01:00
|
|
|
db.exec(`INSERT INTO tb_count(\`name\`, \`num\`)
|
2020-08-03 14:11:58 +02:00
|
|
|
VALUES($name, $num)
|
|
|
|
ON CONFLICT(name) DO
|
|
|
|
UPDATE SET \`num\` = $num;`
|
2023-03-06 11:57:41 +01:00
|
|
|
,
|
|
|
|
{ $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 14:11:58 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
getNum,
|
|
|
|
getAll,
|
2023-03-06 11:57:41 +01:00
|
|
|
setNum,
|
|
|
|
setNumMulti
|
|
|
|
}
|