2020-04-29 16:44:27 +01:00
|
|
|
const knex = require('knex');
|
2020-05-27 12:47:53 -05:00
|
|
|
const config = require('../../../shared/config');
|
2020-05-28 13:30:23 -05:00
|
|
|
const logging = require('../../../shared/logging');
|
2020-05-22 13:22:20 -05:00
|
|
|
const errors = require('@tryghost/errors');
|
2020-04-29 16:44:27 +01:00
|
|
|
let knexInstance;
|
2016-02-12 11:56:27 +00:00
|
|
|
|
2016-07-14 12:59:42 +02:00
|
|
|
// @TODO:
|
|
|
|
// - if you require this file before config file was loaded,
|
|
|
|
// - then this file is cached and you have no chance to connect to the db anymore
|
|
|
|
// - bring dynamic into this file (db.connect())
|
2016-03-24 12:49:06 +00:00
|
|
|
function configure(dbConfig) {
|
2020-04-29 16:44:27 +01:00
|
|
|
const client = dbConfig.client;
|
2016-03-24 12:49:06 +00:00
|
|
|
|
|
|
|
if (client === 'sqlite3') {
|
2019-07-05 13:40:43 +02:00
|
|
|
dbConfig.useNullAsDefault = Object.prototype.hasOwnProperty.call(dbConfig, 'useNullAsDefault') ? dbConfig.useNullAsDefault : true;
|
2016-03-24 12:49:06 +00:00
|
|
|
}
|
|
|
|
|
2016-06-03 09:06:18 +01:00
|
|
|
if (client === 'mysql') {
|
|
|
|
dbConfig.connection.timezone = 'UTC';
|
2016-09-20 16:52:43 +02:00
|
|
|
dbConfig.connection.charset = 'utf8mb4';
|
2017-10-04 10:40:59 +02:00
|
|
|
|
|
|
|
dbConfig.connection.loggingHook = function loggingHook(err) {
|
2020-05-22 13:22:20 -05:00
|
|
|
logging.error(new errors.InternalServerError({
|
2017-10-04 10:40:59 +02:00
|
|
|
code: 'MYSQL_LOGGING_HOOK',
|
|
|
|
err: err
|
|
|
|
}));
|
|
|
|
};
|
2016-06-03 09:06:18 +01:00
|
|
|
}
|
|
|
|
|
2016-03-24 12:49:06 +00:00
|
|
|
return dbConfig;
|
2016-02-12 11:56:27 +00:00
|
|
|
}
|
|
|
|
|
2016-09-13 17:41:14 +02:00
|
|
|
if (!knexInstance && config.get('database') && config.get('database').client) {
|
|
|
|
knexInstance = knex(configure(config.get('database')));
|
2016-02-12 11:56:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = knexInstance;
|