How to use the pg.on function in pg

To help you get started, we’ve selected a few pg examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ozum / sequelize-pg-generator / test / util / db.js View on Github external
var lodash          = require('lodash');
var dbConfig        = { host: 'localhost', port: 5432, user: 'user', password: 'password', database: 'pg_generator_test_625393' };
var generator       = require('../../lib/index.js');

var conString           = 'postgres://' + dbConfig.user + ':' + dbConfig.password + '@' + dbConfig.host + ':' + dbConfig.port + '/'; //'postgres://user:pass@host:port/'
var conStringTest       = conString + dbConfig.database;                                                                //'postgres://user:pass@host:port/db'
var conStringTemplate   = conString + 'template1';                                                                      //'postgres://user:pass@host:port/db'

var sql = {
    createDB        : "CREATE DATABASE pg_generator_test_625393 WITH ENCODING = 'UTF8' TEMPLATE = template0;",
    dropDB          : "DROP DATABASE IF EXISTS pg_generator_test_625393;",
    createSchema    : function (sqlID) { return fs.readFileSync(path.join(__dirname, 'create-test-db-' + sqlID  + '.sql')).toString(); },
    dropConnection  : "SELECT pg_terminate_backend(pid) FROM pg_stat_activity where datname='pg_generator_test_625393';"
};

pg.on('error', function (err) {
    // Do nothing on termination due to admin command. We do this to drop previously created test db.
    if (!err.message.match('terminating connection due to administrator command')) { console.log('Database error!', err); }
});

module.exports.dbConfig = dbConfig;

module.exports.generate = function generate(sqlId, options, callback) {
    module.exports.resetDB(sqlId, function () {
        generator(function (err) {
            if (err) { callback(err); return; }
            callback();
        }, lodash.defaults(options, {
            database: 'pg_generator_test_625393',
            user: dbConfig.user,
            password: dbConfig.password,
            output: path.join(__dirname, '..', 'model'),
github ozum / pg-structure / test / util / db.js View on Github external
var async           = require('async');
var dbConfig        = { host: 'localhost', port: 5432, user: 'user', password: 'password'  };


var conString           = 'postgres://' + dbConfig.user + ':' + dbConfig.password + '@' + dbConfig.host + ':' + dbConfig.port + '/'; //'postgres://user:pass@host:port/'
var conStringTest       = conString + 'pg_generator_test_724839';                                                       //'postgres://user:pass@host:port/db'
var conStringTemplate   = conString + 'template1';                                                                      //'postgres://user:pass@host:port/db'

var sql = {
    createDB        : "CREATE DATABASE pg_generator_test_724839 WITH ENCODING = 'UTF8' TEMPLATE = template0;",
    dropDB          : "DROP DATABASE IF EXISTS pg_generator_test_724839;",
    createSchema    : function (sqlID) { return fs.readFileSync(path.join(__dirname, 'create-test-db-' + sqlID  + '.sql')).toString(); },
    dropConnection  : "SELECT pg_terminate_backend(pid) FROM pg_stat_activity where datname='pg_generator_test_724839';"
};

pg.on('error', function (err) {
    // Do nothing on termination due to admin command. We do this to drop previously created test db.
    if (!err.message.match('terminating connection due to administrator command')) { console.log('Database error!', err); }
});

module.exports.dbConfig = dbConfig;

module.exports.resetDB = function resetDB(sqlID, callback) {
    if (sqlID === undefined) { sqlID = 1; }
    var client = new pg.Client(conStringTemplate);

    client.connect(function () {
        async.series([
            client.query.bind(client, sql.dropConnection),
            client.query.bind(client, sql.dropDB),
            client.query.bind(client, sql.createDB),
            function (next) {
github usecanvas / realtime-v2 / sharedb / lib / sharedb-postgres-canvas.js View on Github external
'use strict';

/* eslint id-length: ["off"], newline-per-chained-call: ["off"] */

const Pg = require('pg');
const URL = require('url');
const ShareDBDB = require('sharedb').DB;

Pg.on('end', onPgEnd);

const pgPool = new Pg.Pool(parseDatabaseURL());

class ShareDBPGCanvas extends ShareDBDB {
  commit(orgID, canvasID, op, snapshot, options, cb) {
    return pgPool.connect().then(client => {
      return client.query('BEGIN').then(_ => {
        return this.doGetSnapshot(client, orgID, canvasID, [], options)
          .then(existingSnap => {
            if (snapshot.v !== existingSnap.v + 1) return false;
            return this.doCommit(client, canvasID, op, snapshot);
          }).then(success => {
            return client.query('COMMIT').then(_ => {
              return resolveQuery(success, cb, client);
            });
          }).catch(err => {
github CartoDB / Windshaft / lib / windshaft / psql.js View on Github external
var _      = require('underscore')
    , Step   = require('step')
    , pg     = require('pg');//.native; // disabled for now due to: https://github.com/brianc/node-postgres/issues/48

var global_settings = global.settings || {};
// Max database connections in the pool
// Subsequent connections will block waiting for a free slot
pg.defaults.poolSize = global_settings.db_pool_size || 16;

// Milliseconds of idle time before removing connection from pool
pg.defaults.poolIdleTimeout = global_settings.db_pool_idleTimeout || 30000;

// Frequency to check for idle clients within the pool, ms
pg.defaults.reapIntervalMillis = global_settings.db_pool_reapInterval || 1000;

pg.on('error', function(err, client) {
  console.log("PostgreSQL connection error: " + err);
});

// Workaround for https://github.com/Vizzuality/CartoDB-SQL-API/issues/100
var types = pg.types;
var arrayParser = require(__dirname + '/../../node_modules/pg/lib/types/arrayParser');
var floatParser = function(val) {
  return parseFloat(val);
};
var floatArrayParser = function(val) {
  if(!val) { return null; }
  var p = arrayParser.create(val, function(entry) {
    return floatParser(entry);
  });
  return p.parse();
};
github voxpelli / webpage-webmentions / lib / db.js View on Github external
/*jslint node: true, white: true, indent: 2 */

"use strict";

var pg = require('pg'),
  ff = require('ff'),
  options = require('./config');

pg.on('error', function (err) {
  console.log('Database error!', err);
});

module.exports = function () {
  var args = arguments, f;

  Array.prototype.unshift.call(args, function () {
    pg.connect(options.db, f.slotMulti(2));
  }, function (client, done) {
    f.pass(client);
    f.onComplete(done);
  });

  f = ff.apply(undefined, args);

  return f;
github will123195 / oreo / lib / platforms / pg.js View on Github external
pg.end = function(cb) {
  PG.on('end', cb)
  PG.end()
}
github usecanvas / livedb-postgresql / index.js View on Github external
'use strict';

var async    = require('async');
var fmt      = require('util').format;
var inherits = require('util').inherits;
var knex     = require('knex');
var pg       = require('pg');

pg.on('end', function onPgEnd() {
  LivePg.willClose = true;
});

/**
 * Get a livedb client for connecting to a PostgreSQL database.
 *
 * @classdesc A PostgreSQL adapter for livedb
 * @class
 * @param {object} opts An object of options
 * @param {string} opts.conn A PostgreSQL connection URL
 * @param {string} opts.db An optional existing Knex database client
 * @param {string} opts.table A database table name
 */
function LivePg(opts) {
  this.conn  = required(opts, 'conn');
  this.table = required(opts, 'table');