From 7e5c0176541c1839a7a54c2850cab30fea155887 Mon Sep 17 00:00:00 2001 From: Nick Krecklow Date: Sat, 1 Aug 2020 14:46:04 -0500 Subject: [PATCH] add: named daily database copies for automating exports --- lib/database.js | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/lib/database.js b/lib/database.js index ee7481a..c0bfe7c 100644 --- a/lib/database.js +++ b/lib/database.js @@ -1,5 +1,6 @@ const sqlite = require('sqlite3') +const config = require('../config') const { TimeTracker } = require('./time') class Database { @@ -8,6 +9,32 @@ class Database { 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 () { this._sql.serialize(() => { 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) { - 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.finalize() }