2016-06-03 11:06:18 +03:00
|
|
|
var knex = require('knex'),
|
|
|
|
config = require('../../config'),
|
2016-02-12 14:56:27 +03:00
|
|
|
knexInstance;
|
|
|
|
|
2016-07-14 13:59:42 +03: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 15:49:06 +03:00
|
|
|
function configure(dbConfig) {
|
|
|
|
var client = dbConfig.client,
|
|
|
|
pg;
|
2016-02-12 14:56:27 +03:00
|
|
|
|
2016-06-03 11:06:18 +03:00
|
|
|
dbConfig.isPostgreSQL = function () {
|
|
|
|
return client === 'pg' || client === 'postgres' || client === 'postgresql';
|
|
|
|
};
|
|
|
|
|
|
|
|
if (dbConfig.isPostgreSQL()) {
|
2016-02-12 14:56:27 +03:00
|
|
|
try {
|
|
|
|
pg = require('pg');
|
|
|
|
} catch (e) {
|
|
|
|
pg = require('pg.js');
|
|
|
|
}
|
|
|
|
|
|
|
|
// By default PostgreSQL returns data as strings along with an OID that identifies
|
|
|
|
// its type. We're setting the parser to convert OID 20 (int8) into a javascript
|
|
|
|
// integer.
|
|
|
|
pg.types.setTypeParser(20, function (val) {
|
|
|
|
return val === null ? null : parseInt(val, 10);
|
|
|
|
});
|
2016-06-03 11:06:18 +03:00
|
|
|
|
|
|
|
// https://github.com/tgriesser/knex/issues/97
|
|
|
|
// this sets the timezone to UTC only for the connection!
|
|
|
|
dbConfig.pool = {
|
|
|
|
afterCreate: function (connection, callback) {
|
|
|
|
connection.query('set timezone=\'UTC\'', function (err) {
|
|
|
|
callback(err, connection);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
2016-02-12 14:56:27 +03:00
|
|
|
}
|
2016-03-24 15:49:06 +03:00
|
|
|
|
|
|
|
if (client === 'sqlite3') {
|
2016-03-24 19:33:16 +03:00
|
|
|
dbConfig.useNullAsDefault = dbConfig.useNullAsDefault || false;
|
2016-03-24 15:49:06 +03:00
|
|
|
}
|
|
|
|
|
2016-06-03 11:06:18 +03:00
|
|
|
if (client === 'mysql') {
|
|
|
|
dbConfig.connection.timezone = 'UTC';
|
|
|
|
}
|
|
|
|
|
2016-03-24 15:49:06 +03:00
|
|
|
return dbConfig;
|
2016-02-12 14:56:27 +03:00
|
|
|
}
|
|
|
|
|
2016-06-10 08:08:02 +03:00
|
|
|
if (!knexInstance && config.database && config.database.client) {
|
|
|
|
knexInstance = knex(configure(config.database));
|
2016-02-12 14:56:27 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = knexInstance;
|