local-db.js
2.28 KB
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
"use strict";
const logger = require('komodo-sdk/logger');
const sqlite3 = require('sqlite3').verbose();
const moment = require('moment');
const cron = require('cron');
const db = new sqlite3.Database('data.sqlite', (err) => {
if (err) {
logger.warn('Error connecting to local database', {err: err});
process.exit(2);
}
logger.info('Local database connected');
initTables();
cleanup();
});
function getConnection() { return db; }
function initTables() {
logger.verbose('Preparing database tables');
db.serialize(function() {
db.run('CREATE TABLE IF NOT EXISTS ussd( created TEXT, created_date TEXT, direction TEXT, imsi TEXT, msg TEXT )');
db.run('CREATE INDEX IF NOT EXISTS idx_ussd_created ON ussd(created)');
db.run('CREATE INDEX IF NOT EXISTS idx_ussd_created_date_created ON ussd(created_date, created)');
db.run('CREATE TABLE IF NOT EXISTS sms( created TEXT, created_date TEXT, direction TEXT, imsi TEXT, partner TEXT, msg TEXT )');
db.run('CREATE INDEX IF NOT EXISTS idx_sms_created ON sms(created)');
db.run('CREATE INDEX IF NOT EXISTS idx_sms_created_date_created ON sms(created_date, created)');
db.run('CREATE TABLE IF NOT EXISTS pendingtrx ( created TEXT, created_date TEXT, trx_id TEXT, destination TEXT, product TEXT )');
db.run('CREATE INDEX IF NOT EXISTS idx_pendingtrx_created ON pendingtrx(created)');
db.run('CREATE UNIQUE INDEX IF NOT EXISTS idx_pendingtrx_trx_id ON pendingtrx(trx_id)');
db.run('CREATE INDEX IF NOT EXISTS idx_pendingtrx_created_date ON pendingtrx(created_date, destination, product)');
})
}
function cleanup(max_days) {
logger.info('Doing database cleanup');
if (!max_days) {
max_days = 31;
}
const oldest = moment().add(-1 * max_days, 'days').format('YYYY-MM-DD');
db.serialize(function() {
db.run('DELETE FROM ussd WHERE created < ?', oldest);
db.run('DELETE FROM sms WHERE created < ?', oldest);
db.run('DELETE FROM pendingtrx WHERE created_date < ?', oldest);
db.run('VACUUM');
});
}
const cleanCronJob = new cron.CronJob({
cronTime: '00 00 00 * * *',
onTick: function() { cleanup(); },
start: false
})
exports.getConnection = getConnection;
exports.cleanup = cleanup;