Skip to content

Commit

Permalink
add: named daily database copies for automating exports
Browse files Browse the repository at this point in the history
  • Loading branch information
Cryptkeeper committed Aug 1, 2020
1 parent 68e01a6 commit 7e5c017
Showing 1 changed file with 39 additions and 1 deletion.
40 changes: 39 additions & 1 deletion lib/database.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const sqlite = require('sqlite3')

const config = require('../config')
const { TimeTracker } = require('./time')

class Database {
Expand All @@ -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)')
Expand Down Expand Up @@ -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()
}
Expand Down

0 comments on commit 7e5c017

Please sign in to comment.