-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
98 lines (90 loc) · 3.29 KB
/
db.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
const sqlite3 = require('sqlite3')
const parser = require('./parser')
const db = new sqlite3.Database('./sql.db')
exports.createTables = () => {
return new Promise((resolve, reject) => {
db.get(`SELECT name FROM sqlite_master WHERE type='table' AND name='users'`, (err, row) => {
if (err) reject(err)
if (row == undefined){
console.log(`Creating db table 'users'`)
db.run(`CREATE TABLE users (
id INTEGER NOT NULL PRIMARY KEY,
lang STRING,
goalNotif INTEGER NOT NULL,
assistNotif INTEGER NOT NULL
)`, (err) => {if (err) reject(err)})
}
})
db.get(`SELECT name FROM sqlite_master WHERE type='table' AND name='messi_stats'`, async (err, row) => {
if (err) reject(err)
let currGoals, currAssists;
[currGoals, currAssists] = await parser.getStats()
if (row == undefined){
console.log(`Creating db table 'messi_stats' (goals - ${currGoals}, assists - ${currAssists})`)
db.run(`CREATE TABLE messi_stats (
goals INTEGER NOT NULL,
assists INTEGER NOT NULL
)`, (err) => {
if (err) reject(err)
db.run(`INSERT INTO messi_stats (goals, assists) VALUES (?, ?)`, [currGoals, currAssists], (err) => {
if (err) reject(err)
resolve()
})
})
}
else {
console.log(`Updating messi_stats (goals - ${currGoals}, assists - ${currAssists})`)
await exports.updateStats(currGoals, currAssists)
resolve()
}
})
})
}
exports.updateStats = (currGoals, currAssists) => {
return new Promise((resolve, reject) => {
db.run(`UPDATE messi_stats SET goals = ?, assists = ?`, [currGoals, currAssists], (err) => {
if (err) reject(err)
resolve()
})
})
}
exports.getStats = () => {
return new Promise((resolve, reject) => {
db.get(`SELECT goals, assists FROM messi_stats`, (err, row) => {
if (err) reject(err)
resolve([row?.goals, row?.assists])
})
})
}
exports.addUser = (id, lang) => {
return new Promise((resolve, reject) => {
db.run(`INSERT or IGNORE INTO users (id, lang, goalNotif, assistNotif) VALUES (?, ?, ?, ?)`, [id, lang, 0, 0], (err) => {
if (err) reject(err)
resolve()
})
})
}
exports.updateUser = (id, col, val) => {
return new Promise((resolve, reject) => {
db.run(`UPDATE users SET ${col} = ? WHERE id = ?`, [val, id], (err) => {
if (err) reject(err)
resolve()
})
})
}
exports.getUser = (id) => {
return new Promise((resolve, reject) => {
db.get(`SELECT * FROM users WHERE id = ${id}`, (err, row) => {
if (err) reject(err)
resolve(row)
})
})
}
exports.getUsers = (notif) => {
return new Promise((resolve, reject) => {
db.all(`SELECT * FROM users WHERE ${notif} = 1`, (err, rows) => {
if (err) reject(err)
resolve(rows)
})
})
}