2018-03-09 22:59:12 +02:00
|
|
|
const { Logger } = require('lib/logger.js');
|
|
|
|
const { time } = require('lib/time-utils.js');
|
2018-03-16 19:39:44 +02:00
|
|
|
const Mutex = require('async-mutex').Mutex;
|
2017-05-07 23:02:17 +02:00
|
|
|
|
|
|
|
class Database {
|
2017-06-11 23:11:14 +02:00
|
|
|
constructor(driver) {
|
2017-05-11 22:14:01 +02:00
|
|
|
this.debugMode_ = false;
|
2017-06-11 23:11:14 +02:00
|
|
|
this.driver_ = driver;
|
2017-06-23 23:32:24 +02:00
|
|
|
this.logger_ = new Logger();
|
2017-10-07 18:30:27 +02:00
|
|
|
this.logExcludedQueryTypes_ = [];
|
2018-03-16 22:17:52 +02:00
|
|
|
this.batchTransactionMutex_ = new Mutex();
|
2017-10-07 18:30:27 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
setLogExcludedQueryTypes(v) {
|
|
|
|
this.logExcludedQueryTypes_ = v;
|
2017-06-23 23:32:24 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Converts the SQLite error to a regular JS error
|
|
|
|
// so that it prints a stacktrace when passed to
|
|
|
|
// console.error()
|
2017-07-04 20:09:47 +02:00
|
|
|
sqliteErrorToJsError(error, sql = null, params = null) {
|
2017-07-05 23:29:00 +02:00
|
|
|
return this.driver().sqliteErrorToJsError(error, sql, params);
|
2017-06-23 23:32:24 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
setLogger(l) {
|
|
|
|
this.logger_ = l;
|
|
|
|
}
|
|
|
|
|
|
|
|
logger() {
|
|
|
|
return this.logger_;
|
2017-05-11 22:14:01 +02:00
|
|
|
}
|
2017-05-07 23:02:17 +02:00
|
|
|
|
2017-06-11 23:11:14 +02:00
|
|
|
driver() {
|
|
|
|
return this.driver_;
|
|
|
|
}
|
|
|
|
|
2017-07-04 20:09:47 +02:00
|
|
|
async open(options) {
|
|
|
|
await this.driver().open(options);
|
2018-03-09 22:59:12 +02:00
|
|
|
this.logger().info('Database was open successfully');
|
2017-06-11 23:11:14 +02:00
|
|
|
}
|
|
|
|
|
2017-06-25 14:49:46 +02:00
|
|
|
escapeField(field) {
|
2018-03-09 22:59:12 +02:00
|
|
|
if (field == '*') return '*';
|
|
|
|
let p = field.split('.');
|
2019-09-19 23:51:18 +02:00
|
|
|
if (p.length == 1) return `\`${field}\``;
|
|
|
|
if (p.length == 2) return `${p[0]}.\`${p[1]}\``;
|
2019-07-29 15:43:53 +02:00
|
|
|
|
2019-09-19 23:51:18 +02:00
|
|
|
throw new Error(`Invalid field format: ${field}`);
|
2017-06-25 14:49:46 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
escapeFields(fields) {
|
2018-03-09 22:59:12 +02:00
|
|
|
if (fields == '*') return '*';
|
2017-07-03 20:58:01 +02:00
|
|
|
|
2017-06-25 14:49:46 +02:00
|
|
|
let output = [];
|
|
|
|
for (let i = 0; i < fields.length; i++) {
|
|
|
|
output.push(this.escapeField(fields[i]));
|
|
|
|
}
|
|
|
|
return output;
|
|
|
|
}
|
|
|
|
|
2017-07-03 20:58:01 +02:00
|
|
|
async tryCall(callName, sql, params) {
|
2018-03-09 22:59:12 +02:00
|
|
|
if (typeof sql === 'object') {
|
2017-07-02 17:46:03 +02:00
|
|
|
params = sql.params;
|
|
|
|
sql = sql.sql;
|
|
|
|
}
|
|
|
|
|
2017-06-27 01:20:01 +02:00
|
|
|
let waitTime = 50;
|
|
|
|
let totalWaitTime = 0;
|
|
|
|
while (true) {
|
|
|
|
try {
|
|
|
|
this.logQuery(sql, params);
|
2017-07-03 20:58:01 +02:00
|
|
|
let result = await this.driver()[callName](sql, params);
|
|
|
|
return result; // No exception was thrown
|
2017-06-27 01:20:01 +02:00
|
|
|
} catch (error) {
|
2018-03-09 22:59:12 +02:00
|
|
|
if (error && (error.code == 'SQLITE_IOERR' || error.code == 'SQLITE_BUSY')) {
|
2017-07-03 20:58:01 +02:00
|
|
|
if (totalWaitTime >= 20000) throw this.sqliteErrorToJsError(error, sql, params);
|
2017-11-28 00:50:46 +02:00
|
|
|
// NOTE: don't put logger statements here because it might log to the database, which
|
|
|
|
// could result in an error being thrown again.
|
|
|
|
// this.logger().warn(sprintf('Error %s: will retry in %s milliseconds', error.code, waitTime));
|
|
|
|
// this.logger().warn('Error was: ' + error.toString());
|
2017-06-27 01:20:01 +02:00
|
|
|
await time.msleep(waitTime);
|
|
|
|
totalWaitTime += waitTime;
|
|
|
|
waitTime *= 1.5;
|
|
|
|
} else {
|
|
|
|
throw this.sqliteErrorToJsError(error, sql, params);
|
2017-07-03 20:58:01 +02:00
|
|
|
}
|
2017-06-27 01:20:01 +02:00
|
|
|
}
|
|
|
|
}
|
2017-06-11 23:11:14 +02:00
|
|
|
}
|
2017-05-07 23:02:17 +02:00
|
|
|
|
2017-07-03 20:58:01 +02:00
|
|
|
async selectOne(sql, params = null) {
|
2018-03-09 22:59:12 +02:00
|
|
|
return this.tryCall('selectOne', sql, params);
|
2017-07-03 20:58:01 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
async selectAll(sql, params = null) {
|
2018-03-09 22:59:12 +02:00
|
|
|
return this.tryCall('selectAll', sql, params);
|
2017-07-03 20:58:01 +02:00
|
|
|
}
|
|
|
|
|
2019-03-02 19:35:57 +02:00
|
|
|
async selectAllFields(sql, params, field) {
|
|
|
|
const rows = await this.tryCall('selectAll', sql, params);
|
|
|
|
const output = [];
|
|
|
|
for (let i = 0; i < rows.length; i++) {
|
|
|
|
const v = rows[i][field];
|
2019-09-19 23:51:18 +02:00
|
|
|
if (!v) throw new Error(`No such field: ${field}. Query was: ${sql}`);
|
2019-03-02 19:35:57 +02:00
|
|
|
output.push(rows[i][field]);
|
|
|
|
}
|
|
|
|
return output;
|
|
|
|
}
|
|
|
|
|
2017-07-03 20:58:01 +02:00
|
|
|
async exec(sql, params = null) {
|
2018-03-09 22:59:12 +02:00
|
|
|
return this.tryCall('exec', sql, params);
|
2017-07-03 20:58:01 +02:00
|
|
|
}
|
|
|
|
|
2017-12-20 21:45:25 +02:00
|
|
|
async transactionExecBatch(queries) {
|
|
|
|
if (queries.length <= 0) return;
|
2017-06-15 01:14:15 +02:00
|
|
|
|
|
|
|
if (queries.length == 1) {
|
2017-06-25 01:19:11 +02:00
|
|
|
let q = this.wrapQuery(queries[0]);
|
2017-12-20 21:45:25 +02:00
|
|
|
await this.exec(q.sql, q.params);
|
|
|
|
return;
|
2017-06-15 01:14:15 +02:00
|
|
|
}
|
|
|
|
|
2018-03-16 19:39:44 +02:00
|
|
|
// There can be only one transaction running at a time so use a mutex
|
2018-03-16 22:17:52 +02:00
|
|
|
const release = await this.batchTransactionMutex_.acquire();
|
2017-06-15 01:14:15 +02:00
|
|
|
|
2018-03-16 19:39:44 +02:00
|
|
|
try {
|
2018-03-16 22:17:52 +02:00
|
|
|
await this.exec('BEGIN TRANSACTION');
|
2017-06-14 21:59:46 +02:00
|
|
|
|
2018-03-16 19:39:44 +02:00
|
|
|
for (let i = 0; i < queries.length; i++) {
|
|
|
|
let query = this.wrapQuery(queries[i]);
|
|
|
|
await this.exec(query.sql, query.params);
|
|
|
|
}
|
2018-03-16 22:17:52 +02:00
|
|
|
|
|
|
|
await this.exec('COMMIT');
|
|
|
|
} catch (error) {
|
|
|
|
await this.exec('ROLLBACK');
|
|
|
|
throw error;
|
2018-03-16 19:39:44 +02:00
|
|
|
} finally {
|
|
|
|
release();
|
2017-06-11 23:11:14 +02:00
|
|
|
}
|
2017-05-12 22:17:23 +02:00
|
|
|
}
|
|
|
|
|
2017-05-20 00:16:50 +02:00
|
|
|
static enumId(type, s) {
|
2018-03-09 22:59:12 +02:00
|
|
|
if (type == 'settings') {
|
|
|
|
if (s == 'int') return 1;
|
|
|
|
if (s == 'string') return 2;
|
2017-05-12 22:17:23 +02:00
|
|
|
}
|
2018-03-09 22:59:12 +02:00
|
|
|
if (type == 'fieldType') {
|
2017-12-12 23:58:57 +02:00
|
|
|
if (s) s = s.toUpperCase();
|
2018-03-09 22:59:12 +02:00
|
|
|
if (s == 'INTEGER') s = 'INT';
|
2019-09-19 23:51:18 +02:00
|
|
|
if (!(`TYPE_${s}` in this)) throw new Error(`Unkonwn fieldType: ${s}`);
|
|
|
|
return this[`TYPE_${s}`];
|
2017-05-20 00:16:50 +02:00
|
|
|
}
|
2018-03-09 22:59:12 +02:00
|
|
|
if (type == 'syncTarget') {
|
|
|
|
if (s == 'memory') return 1;
|
|
|
|
if (s == 'filesystem') return 2;
|
|
|
|
if (s == 'onedrive') return 3;
|
2017-07-16 14:53:59 +02:00
|
|
|
}
|
2019-09-19 23:51:18 +02:00
|
|
|
throw new Error(`Unknown enum type or value: ${type}, ${s}`);
|
2017-05-07 23:02:17 +02:00
|
|
|
}
|
|
|
|
|
2017-12-07 20:12:46 +02:00
|
|
|
static enumName(type, id) {
|
2018-03-09 22:59:12 +02:00
|
|
|
if (type === 'fieldType') {
|
|
|
|
if (id === Database.TYPE_UNKNOWN) return 'unknown';
|
|
|
|
if (id === Database.TYPE_INT) return 'int';
|
|
|
|
if (id === Database.TYPE_TEXT) return 'text';
|
|
|
|
if (id === Database.TYPE_NUMERIC) return 'numeric';
|
2019-09-19 23:51:18 +02:00
|
|
|
throw new Error(`Invalid type id: ${id}`);
|
2017-12-07 20:12:46 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-05-20 00:16:50 +02:00
|
|
|
static formatValue(type, value) {
|
|
|
|
if (value === null || value === undefined) return null;
|
|
|
|
if (type == this.TYPE_INT) return Number(value);
|
|
|
|
if (type == this.TYPE_TEXT) return value;
|
|
|
|
if (type == this.TYPE_NUMERIC) return Number(value);
|
2019-09-19 23:51:18 +02:00
|
|
|
throw new Error(`Unknown type: ${type}`);
|
2017-05-20 00:16:50 +02:00
|
|
|
}
|
|
|
|
|
2017-05-07 23:02:17 +02:00
|
|
|
sqlStringToLines(sql) {
|
|
|
|
let output = [];
|
2019-07-29 15:43:53 +02:00
|
|
|
let lines = sql.split('\n');
|
2018-03-09 22:59:12 +02:00
|
|
|
let statement = '';
|
2017-05-07 23:02:17 +02:00
|
|
|
for (var i = 0; i < lines.length; i++) {
|
|
|
|
var line = lines[i];
|
2018-03-09 22:59:12 +02:00
|
|
|
if (line == '') continue;
|
2019-07-29 15:43:53 +02:00
|
|
|
if (line.substr(0, 2) == '--') continue;
|
2017-07-19 21:15:55 +02:00
|
|
|
statement += line.trim();
|
2018-03-09 22:59:12 +02:00
|
|
|
if (line[line.length - 1] == ',') statement += ' ';
|
|
|
|
if (line[line.length - 1] == ';') {
|
2017-05-07 23:02:17 +02:00
|
|
|
output.push(statement);
|
2018-03-09 22:59:12 +02:00
|
|
|
statement = '';
|
2017-05-07 23:02:17 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return output;
|
|
|
|
}
|
|
|
|
|
2017-05-11 22:14:01 +02:00
|
|
|
logQuery(sql, params = null) {
|
2017-10-07 18:30:27 +02:00
|
|
|
if (this.logExcludedQueryTypes_.length) {
|
|
|
|
const temp = sql.toLowerCase();
|
|
|
|
for (let i = 0; i < this.logExcludedQueryTypes_.length; i++) {
|
|
|
|
if (temp.indexOf(this.logExcludedQueryTypes_[i].toLowerCase()) === 0) return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-06-25 13:39:42 +02:00
|
|
|
this.logger().debug(sql);
|
2017-06-25 14:49:46 +02:00
|
|
|
if (params !== null && params.length) this.logger().debug(JSON.stringify(params));
|
2017-05-18 22:31:40 +02:00
|
|
|
}
|
|
|
|
|
2017-05-11 22:14:01 +02:00
|
|
|
static insertQuery(tableName, data) {
|
2018-03-09 22:59:12 +02:00
|
|
|
if (!data || !Object.keys(data).length) throw new Error('Data is empty');
|
2017-06-18 01:49:52 +02:00
|
|
|
|
2019-07-29 15:43:53 +02:00
|
|
|
let keySql = '';
|
2018-03-09 22:59:12 +02:00
|
|
|
let valueSql = '';
|
2017-05-11 22:14:01 +02:00
|
|
|
let params = [];
|
2017-05-10 21:51:43 +02:00
|
|
|
for (let key in data) {
|
2017-05-11 22:14:01 +02:00
|
|
|
if (!data.hasOwnProperty(key)) continue;
|
2018-03-09 22:59:12 +02:00
|
|
|
if (key[key.length - 1] == '_') continue;
|
|
|
|
if (keySql != '') keySql += ', ';
|
|
|
|
if (valueSql != '') valueSql += ', ';
|
2019-09-19 23:51:18 +02:00
|
|
|
keySql += `\`${key}\``;
|
2018-03-09 22:59:12 +02:00
|
|
|
valueSql += '?';
|
2017-05-11 22:14:01 +02:00
|
|
|
params.push(data[key]);
|
2017-05-10 21:51:43 +02:00
|
|
|
}
|
2017-05-11 22:14:01 +02:00
|
|
|
return {
|
2019-09-19 23:51:18 +02:00
|
|
|
sql: `INSERT INTO \`${tableName}\` (${keySql}) VALUES (${valueSql})`,
|
2017-05-11 22:14:01 +02:00
|
|
|
params: params,
|
|
|
|
};
|
2017-05-10 21:51:43 +02:00
|
|
|
}
|
|
|
|
|
2017-05-12 21:54:06 +02:00
|
|
|
static updateQuery(tableName, data, where) {
|
2018-03-09 22:59:12 +02:00
|
|
|
if (!data || !Object.keys(data).length) throw new Error('Data is empty');
|
2017-06-18 01:49:52 +02:00
|
|
|
|
2018-03-09 22:59:12 +02:00
|
|
|
let sql = '';
|
2017-05-12 21:54:06 +02:00
|
|
|
let params = [];
|
|
|
|
for (let key in data) {
|
|
|
|
if (!data.hasOwnProperty(key)) continue;
|
2018-03-09 22:59:12 +02:00
|
|
|
if (key[key.length - 1] == '_') continue;
|
|
|
|
if (sql != '') sql += ', ';
|
2019-09-19 23:51:18 +02:00
|
|
|
sql += `\`${key}\`=?`;
|
2017-05-12 21:54:06 +02:00
|
|
|
params.push(data[key]);
|
|
|
|
}
|
|
|
|
|
2018-03-09 22:59:12 +02:00
|
|
|
if (typeof where != 'string') {
|
2017-07-13 20:47:31 +02:00
|
|
|
let s = [];
|
|
|
|
for (let n in where) {
|
|
|
|
if (!where.hasOwnProperty(n)) continue;
|
|
|
|
params.push(where[n]);
|
2019-09-19 23:51:18 +02:00
|
|
|
s.push(`\`${n}\`=?`);
|
2017-07-13 20:47:31 +02:00
|
|
|
}
|
2018-03-09 22:59:12 +02:00
|
|
|
where = s.join(' AND ');
|
2017-05-12 21:54:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
2019-09-19 23:51:18 +02:00
|
|
|
sql: `UPDATE \`${tableName}\` SET ${sql} WHERE ${where}`,
|
2017-05-12 21:54:06 +02:00
|
|
|
params: params,
|
|
|
|
};
|
|
|
|
}
|
2017-07-25 23:55:26 +02:00
|
|
|
|
2017-07-26 19:49:01 +02:00
|
|
|
alterColumnQueries(tableName, fields) {
|
|
|
|
let fieldsNoType = [];
|
|
|
|
for (let n in fields) {
|
|
|
|
if (!fields.hasOwnProperty(n)) continue;
|
|
|
|
fieldsNoType.push(n);
|
|
|
|
}
|
|
|
|
|
|
|
|
let fieldsWithType = [];
|
|
|
|
for (let n in fields) {
|
|
|
|
if (!fields.hasOwnProperty(n)) continue;
|
2019-09-19 23:51:18 +02:00
|
|
|
fieldsWithType.push(`${this.escapeField(n)} ${fields[n]}`);
|
2019-07-29 15:43:53 +02:00
|
|
|
}
|
2017-07-26 19:49:01 +02:00
|
|
|
|
2017-07-25 23:55:26 +02:00
|
|
|
let sql = `
|
2017-07-26 19:49:01 +02:00
|
|
|
CREATE TEMPORARY TABLE _BACKUP_TABLE_NAME_(_FIELDS_TYPE_);
|
|
|
|
INSERT INTO _BACKUP_TABLE_NAME_ SELECT _FIELDS_NO_TYPE_ FROM _TABLE_NAME_;
|
2017-07-25 23:55:26 +02:00
|
|
|
DROP TABLE _TABLE_NAME_;
|
2017-07-26 19:49:01 +02:00
|
|
|
CREATE TABLE _TABLE_NAME_(_FIELDS_TYPE_);
|
|
|
|
INSERT INTO _TABLE_NAME_ SELECT _FIELDS_NO_TYPE_ FROM _BACKUP_TABLE_NAME_;
|
2017-07-25 23:55:26 +02:00
|
|
|
DROP TABLE _BACKUP_TABLE_NAME_;
|
|
|
|
`;
|
|
|
|
|
2019-09-19 23:51:18 +02:00
|
|
|
sql = sql.replace(/_BACKUP_TABLE_NAME_/g, this.escapeField(`${tableName}_backup`));
|
2017-07-25 23:55:26 +02:00
|
|
|
sql = sql.replace(/_TABLE_NAME_/g, this.escapeField(tableName));
|
2018-03-09 22:59:12 +02:00
|
|
|
sql = sql.replace(/_FIELDS_NO_TYPE_/g, this.escapeFields(fieldsNoType).join(','));
|
|
|
|
sql = sql.replace(/_FIELDS_TYPE_/g, fieldsWithType.join(','));
|
2017-07-25 23:55:26 +02:00
|
|
|
|
2019-07-29 15:43:53 +02:00
|
|
|
return sql.trim().split('\n');
|
2017-07-25 23:55:26 +02:00
|
|
|
}
|
2019-07-29 15:43:53 +02:00
|
|
|
|
2017-06-11 23:11:14 +02:00
|
|
|
wrapQueries(queries) {
|
|
|
|
let output = [];
|
|
|
|
for (let i = 0; i < queries.length; i++) {
|
|
|
|
output.push(this.wrapQuery(queries[i]));
|
|
|
|
}
|
|
|
|
return output;
|
|
|
|
}
|
|
|
|
|
|
|
|
wrapQuery(sql, params = null) {
|
2019-09-19 23:51:18 +02:00
|
|
|
if (!sql) throw new Error(`Cannot wrap empty string: ${sql}`);
|
2017-06-11 23:11:14 +02:00
|
|
|
|
|
|
|
if (sql.constructor === Array) {
|
|
|
|
let output = {};
|
|
|
|
output.sql = sql[0];
|
|
|
|
output.params = sql.length >= 2 ? sql[1] : null;
|
|
|
|
return output;
|
2018-03-09 22:59:12 +02:00
|
|
|
} else if (typeof sql === 'string') {
|
2017-06-11 23:11:14 +02:00
|
|
|
return { sql: sql, params: params };
|
|
|
|
} else {
|
|
|
|
return sql; // Already wrapped
|
|
|
|
}
|
2017-05-12 22:17:23 +02:00
|
|
|
}
|
2017-05-07 23:02:17 +02:00
|
|
|
}
|
|
|
|
|
2017-12-05 00:58:42 +02:00
|
|
|
Database.TYPE_UNKNOWN = 0;
|
2017-06-06 22:58:19 +02:00
|
|
|
Database.TYPE_INT = 1;
|
|
|
|
Database.TYPE_TEXT = 2;
|
2017-06-15 20:18:48 +02:00
|
|
|
Database.TYPE_NUMERIC = 3;
|
2017-06-06 22:58:19 +02:00
|
|
|
|
2019-07-29 15:43:53 +02:00
|
|
|
module.exports = { Database };
|