Files
cloudron-box/src/database.js

160 lines
5.5 KiB
JavaScript
Raw Normal View History

'use strict';
exports = module.exports = {
2021-05-01 11:21:09 -07:00
initialize,
uninitialize,
query,
transaction,
2021-05-01 11:21:09 -07:00
importFromFile,
exportToFile,
_clear: clear
};
2021-05-02 21:12:38 -07:00
const assert = require('assert'),
async = require('async'),
2020-07-03 13:47:56 -07:00
BoxError = require('./boxerror.js'),
2016-09-20 14:07:39 -07:00
child_process = require('child_process'),
2019-07-25 16:12:37 -07:00
constants = require('./constants.js'),
debug = require('debug')('box:database'),
mysql = require('mysql'),
2016-09-20 14:07:39 -07:00
once = require('once'),
util = require('util');
2020-07-03 13:07:39 -07:00
var gConnectionPool = null;
2019-07-25 16:12:37 -07:00
const gDatabase = {
hostname: '127.0.0.1',
username: 'root',
password: 'password',
port: 3306,
name: 'box'
};
function initialize(callback) {
assert.strictEqual(typeof callback, 'function');
if (gConnectionPool !== null) return callback(null);
2019-07-25 16:12:37 -07:00
if (constants.TEST) {
// see setupTest script how the mysql-server is run
gDatabase.hostname = require('child_process').execSync('docker inspect -f "{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}" mysql-server').toString().trim();
}
2020-07-03 13:07:39 -07:00
// https://github.com/mysqljs/mysql#pool-options
gConnectionPool = mysql.createPool({
2020-07-03 13:07:39 -07:00
connectionLimit: 5,
2019-07-25 16:12:37 -07:00
host: gDatabase.hostname,
user: gDatabase.username,
password: gDatabase.password,
port: gDatabase.port,
database: gDatabase.name,
multipleStatements: false,
2020-07-03 13:07:39 -07:00
waitForConnections: true, // getConnection() will wait until a connection is avaiable
2019-03-22 15:12:30 -07:00
ssl: false,
timezone: 'Z' // mysql follows the SYSTEM timezone. on Cloudron, this is UTC
});
gConnectionPool.on('connection', function (connection) {
2020-07-02 15:10:05 -07:00
// connection objects are re-used. so we have to attach to the event here (once) to prevent crash
// note the pool also has an 'acquire' event but that is called whenever we do a getConnection()
2020-07-03 13:07:39 -07:00
connection.on('error', (error) => debug(`Connection ${connection.threadId} error: ${error.message} ${error.code}`));
2020-07-02 15:10:05 -07:00
2019-07-25 16:12:37 -07:00
connection.query('USE ' + gDatabase.name);
connection.query('SET SESSION sql_mode = \'strict_all_tables\'');
});
2020-07-03 13:47:56 -07:00
callback(null);
}
function uninitialize(callback) {
2020-07-03 13:07:39 -07:00
if (!gConnectionPool) return callback(null);
2020-07-03 13:07:39 -07:00
gConnectionPool.end(callback);
gConnectionPool = null;
}
function clear(callback) {
assert.strictEqual(typeof callback, 'function');
var cmd = util.format('mysql --host="%s" --user="%s" --password="%s" -Nse "SHOW TABLES" %s | grep -v "^migrations$" | while read table; do mysql --host="%s" --user="%s" --password="%s" -e "SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE $table" %s; done',
2019-07-25 16:12:37 -07:00
gDatabase.hostname, gDatabase.username, gDatabase.password, gDatabase.name,
gDatabase.hostname, gDatabase.username, gDatabase.password, gDatabase.name);
2016-09-20 14:07:39 -07:00
2020-02-06 16:57:33 +01:00
child_process.exec(cmd, callback);
}
function query() {
2021-05-02 21:12:38 -07:00
assert.notStrictEqual(gConnectionPool, null);
return new Promise((resolve, reject) => {
let args = Array.prototype.slice.call(arguments);
const callback = typeof args[args.length - 1] === 'function' ? args.pop() : null;
2021-05-02 21:12:38 -07:00
args.push(function queryCallback(error, result) {
if (error) return callback ? callback(error) : reject(new BoxError(BoxError.DATABASE_ERROR, error));
2020-07-03 13:47:56 -07:00
2021-05-02 21:12:38 -07:00
callback ? callback(null, result) : resolve(result);
});
gConnectionPool.query.apply(gConnectionPool, args); // this is same as getConnection/query/release
});
2020-06-11 09:50:49 -07:00
}
function transaction(queries, callback) {
2021-05-02 11:26:08 -07:00
assert(Array.isArray(queries));
assert.strictEqual(typeof callback, 'function');
callback = once(callback);
2020-07-03 13:07:39 -07:00
gConnectionPool.getConnection(function (error, connection) {
if (error) return callback(error);
2020-07-03 13:07:39 -07:00
const releaseConnection = (error) => { connection.release(); callback(error); };
connection.beginTransaction(function (error) {
if (error) return releaseConnection(error);
async.mapSeries(queries, function iterator(query, done) {
connection.query(query.query, query.args, done);
}, function seriesDone(error, results) {
if (error) return connection.rollback(() => releaseConnection(error));
2020-06-11 09:50:49 -07:00
2020-07-03 13:07:39 -07:00
connection.commit(function (error) {
if (error) return connection.rollback(() => releaseConnection(error));
2020-07-03 13:07:39 -07:00
connection.release();
2020-07-03 13:07:39 -07:00
callback(null, results);
});
2020-06-11 09:50:49 -07:00
});
});
});
}
function importFromFile(file, callback) {
assert.strictEqual(typeof file, 'string');
assert.strictEqual(typeof callback, 'function');
2019-07-25 16:12:37 -07:00
var cmd = `/usr/bin/mysql -h "${gDatabase.hostname}" -u ${gDatabase.username} -p${gDatabase.password} ${gDatabase.name} < ${file}`;
async.series([
query.bind(null, 'CREATE DATABASE IF NOT EXISTS box'),
child_process.exec.bind(null, cmd)
], callback);
}
2017-11-24 15:29:23 -08:00
function exportToFile(file, callback) {
assert.strictEqual(typeof file, 'string');
assert.strictEqual(typeof callback, 'function');
// latest mysqldump enables column stats by default which is not present in MySQL 5.7 server
// this option must not be set in production cloudrons which still use the old mysqldump
const disableColStats = (constants.TEST && require('fs').readFileSync('/etc/lsb-release', 'utf-8').includes('20.04')) ? '--column-statistics=0' : '';
var cmd = `/usr/bin/mysqldump -h "${gDatabase.hostname}" -u root -p${gDatabase.password} ${disableColStats} --single-transaction --routines --triggers ${gDatabase.name} > "${file}"`;
2017-11-24 15:29:23 -08:00
child_process.exec(cmd, callback);
}