add: named daily database copies for automating exports

This commit is contained in:
Nick Krecklow 2020-08-01 14:46:04 -05:00
parent 68e01a62bb
commit 7e5c017654
No known key found for this signature in database
GPG Key ID: 5F149FDE156FFA94

@ -1,5 +1,6 @@
const sqlite = require('sqlite3') const sqlite = require('sqlite3')
const config = require('../config')
const { TimeTracker } = require('./time') const { TimeTracker } = require('./time')
class Database { class Database {
@ -8,6 +9,32 @@ class Database {
this._sql = new sqlite.Database('database.sql') this._sql = new sqlite.Database('database.sql')
} }
getDailyDatabase () {
if (!config.createDailyDatabaseCopy) {
return
}
const date = new Date()
const fileName = `database_copy_${date.getDate()}-${date.getMonth() + 1}-${date.getFullYear()}.sql`
if (fileName !== this._currentDatabaseCopyFileName) {
if (this._currentDatabaseCopyInstance) {
this._currentDatabaseCopyInstance.close()
}
this._currentDatabaseCopyInstance = new sqlite.Database(fileName)
this._currentDatabaseCopyFileName = fileName
// Ensure the initial tables are created
// This does not created indexes since it is only inserted to
this._currentDatabaseCopyInstance.serialize(() => {
this._currentDatabaseCopyInstance.run('CREATE TABLE IF NOT EXISTS pings (timestamp BIGINT NOT NULL, ip TINYTEXT, playerCount MEDIUMINT)')
})
}
return this._currentDatabaseCopyInstance
}
ensureIndexes () { ensureIndexes () {
this._sql.serialize(() => { this._sql.serialize(() => {
this._sql.run('CREATE TABLE IF NOT EXISTS pings (timestamp BIGINT NOT NULL, ip TINYTEXT, playerCount MEDIUMINT)') this._sql.run('CREATE TABLE IF NOT EXISTS pings (timestamp BIGINT NOT NULL, ip TINYTEXT, playerCount MEDIUMINT)')
@ -122,7 +149,18 @@ class Database {
} }
insertPing (ip, timestamp, unsafePlayerCount) { insertPing (ip, timestamp, unsafePlayerCount) {
const statement = this._sql.prepare('INSERT INTO pings (timestamp, ip, playerCount) VALUES (?, ?, ?)') this._insertPingTo(ip, timestamp, unsafePlayerCount, this._sql)
// Push a copy of the data into the database copy, if any
// This creates an "insert only" copy of the database for archiving
const dailyDatabase = this.getDailyDatabase()
if (dailyDatabase) {
this._insertPingTo(ip, timestamp, unsafePlayerCount, dailyDatabase)
}
}
_insertPingTo (ip, timestamp, unsafePlayerCount, db) {
const statement = db.prepare('INSERT INTO pings (timestamp, ip, playerCount) VALUES (?, ?, ?)')
statement.run(timestamp, ip, unsafePlayerCount) statement.run(timestamp, ip, unsafePlayerCount)
statement.finalize() statement.finalize()
} }