Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
/**
* Interface to PostgreSQL client
* */
const pg = require('pg');
const knex = require('knex');
const config = require('../config');
// remember: all values returned from the server are either NULL or a string
pg.types.setTypeParser(20, val => (val === null ? null : parseInt(val, 10)));
console.log('connecting %s', config.POSTGRES_URL);
const db = knex({
client: 'pg',
connection: config.POSTGRES_URL,
pool: {
afterCreate: (conn, done) => {
// Set the minimum similarity for pg_trgm
conn.query('SELECT set_limit(0.6);', (err) => {
// if err is not falsy, connection is discarded from pool
done(err, conn);
});
},
},
});
db.on('query-error', (err) => {
throw err;
'use strict'
const objection = require('objection')
// -- Knex/PG issue: https://github.com/tgriesser/knex/issues/927
const pg = require('pg')
pg.types.setTypeParser(20, 'text', parseInt)
pg.types.setTypeParser(1700, 'text', parseFloat)
// -- end --
const knexLib = require('knex')
const R = require('ramda')
const config = require('../config')
const knexEnvConfig = require('./knexfile')[config.env]
const knexConfig = R.mergeDeepWith({}, knexEnvConfig, objection.knexSnakeCaseMappers())
const knex = knexLib(knexConfig)
const Model = objection.Model
Model.knex(knex)
const transaction = objection.transaction
function connect() {
// Knex does not have an explicit `.connect()` method so we issue a query and consider the
// connection to be open once we get the response back.
import pg from 'pg'
import config from '../../config.js'
// Our DATETIME columns are all in UTC, so we mark the strings postgres returns this way so the
// parsed dates are correct
pg.types.setTypeParser(1114, stringValue => new Date(Date.parse(stringValue + '+0000')))
// Similar to above, we must also parse input dates as UTC so the servers running on different time
// zones work correctly
pg.defaults.parseInputDatesAsUTC = true
const connectionString = config.db.connString
if (!connectionString) throw new Error('db.connString must be set in config.js')
const pool = new pg.Pool({ connectionString })
// TODO(tec27): I think it might be better to wrap the query functions instead of just wrapping the
// client pool getter, but since I don't know how we'll be using this too much yet I'm just
// keeping it simple for now
export default function() {
return new Promise((resolve, reject) => {
pool.connect((err, client, done) => {
require('pg-parse-float')(pg);
var mod_cueball = require('cueball');
var VError = require('verror');
var dtrace = require('./dtrace');
var mod_errors = require('./errors');
var ConnectTimeoutError = mod_errors.ConnectTimeoutError;
var InternalError = mod_errors.InternalError;
var InvalidIndexDefinitionError = mod_errors.InvalidIndexDefinitionError;
var NoDatabasePeersError = mod_errors.NoDatabasePeersError;
var QueryTimeoutError = mod_errors.QueryTimeoutError;
var UniqueAttributeError = mod_errors.UniqueAttributeError;
var parsePgDate = pg.types.getTypeParser(1082, 'text');
var TYPES = require('./types').TYPES;
// --- Globals
var CLIENT_ID = 0;
var DBNAME = process.env.MORAY_DB_NAME || 'moray';
var SERIALIZERS = {
pool: function _serializePool(p) {
try {
var s = p.getStats();
return s;
} catch (_) {
return undefined;
}
export default (url, opt={}) => {
// fix issues with pg types
pg.types.setTypeParser(20, 'text', pg.types.getTypeParser(23, 'text')) // bigint = int
pg.types.setTypeParser(1016, 'text', pg.types.getTypeParser(1007, 'text')) // bigint[] = int[]
pg.types.setTypeParser(1700, 'text', pg.types.getTypeParser(701, 'text')) // numeric = float8
pg.types.setTypeParser(1231, 'text', pg.types.getTypeParser(1022, 'text')) // numeric[] = float8[]
// fix bugs with sequelize
Sequelize.useInflection({
pluralize: plural,
singularize: singular,
underscore
})
// See https://github.com/sequelize/sequelize/issues/1500
Sequelize.Validator.notNull = function (item) {
return !this.isNull(item)
}
const conn = typeof url === 'object'
? new Sequelize({
'use strict';
// Overwrite node-pg-types date parser. See https://github.com/tgriesser/knex/issues/1750
const pgTypes = require('pg').types;
const DATE_OID = 1082;
const DATE_ARRAY_OID = 1182;
function parseDate(value) {
if (!value) {
return null;
}
return new Date(Date.parse(value));
}
function parseDateArray(value) {
if (!value) {
return null;
}
constructor(private appConfig: AppConfig,
private logger: ILogger,
private versionBuild: string,
private genesisBlock: SignedAndChainedBlockType,
private constants: typeof constantsType,
private excCreators: Array<(ex: ExceptionsManager) => Promise>) {
this.appConfig.nethash = genesisBlock.payloadHash.toString('hex');
// this.container.applyMiddleware(theLogger);
// Sets the int8 (64bit integer) to be parsed as int instead of being returned as text
pg.types.setTypeParser(20, 'text', parseInt);
}
constructor(
private appConfig: AppConfig,
private logger: ILogger,
private versionBuild: string,
private genesisBlock: SignedAndChainedBlockType,
private modules: Array>
) {
this.appConfig.nethash = genesisBlock.payloadHash.toString('hex');
// this.container.applyMiddleware(theLogger);
// Sets the int8 (64bit integer) to be parsed as int instead of being returned as text
pg.types.setTypeParser(20, 'text', (a: string) => BigInt(a));
}
const arrayParser = (typeParser: TypeParser) => (input: string) =>
pg.types.arrayParser.create(input, typeParser).parse();
map((type: PgType) => {
const parser = parserSet[type.typname];
pg.types.setTypeParser(type.oid, parser);
if (type.typarray) {
pg.types.setTypeParser(type.typarray, arrayParser(parser));
}
}),
)