Moe-Counter/utils/db.js

60 lines
1.3 KiB
JavaScript
Raw Normal View History

2020-08-05 05:37:12 +00:00
'use strict'
const path = require('path')
2020-08-03 12:11:58 +00:00
const sqlite3 = require('sqlite3')
2020-08-05 05:37:12 +00:00
const db = new sqlite3.Database(path.resolve(__dirname, '../count.db'))
2020-08-03 12:11:58 +00:00
db.run(`CREATE TABLE IF NOT EXISTS tb_count (
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) => {
db.get('SELECT `name`, `num` from tb_count WHERE `name` = ?', name, (err, row) => {
if (err) reject(err)
resolve(row || { name, num: 0 })
})
})
}
function getAll(name) {
return new Promise((resolve, reject) => {
db.get('SELECT * from tb_count', (err, row) => {
if (err) reject(err)
resolve(row)
})
})
}
function setNum(name, num) {
return new Promise((resolve, reject) => {
db.run(`INSERT INTO tb_count(\`name\`, \`num\`)
VALUES($name, $num)
ON CONFLICT(name) DO
UPDATE SET \`num\` = $num;`
, {
$name: name,
$num: num
}
, (err, row) => {
if (err) reject(err)
resolve(row)
})
})
}
module.exports = {
getNum,
getAll,
setNum
}