Example #1
0
module.exports = function (config) {
    var params, auth, pool, query;
    if (typeof config === 'string') {
        params = url.parse(config);
        auth = params.auth ? params.auth.split(':') : [];
        config = {
            host: params.hostname,
            port: params.port,
            database: params.pathname.split('/')[1],
            ssl: true
        };
        if (auth.length > 0) {
            config.user = auth[0];
            config.password = auth[1];
        }
    }
    if (config.validationQuery) {
        query = typeof config.validationQuery == 'string' ? config.validationQuery : 'SELECT 1';
        config.validateAsync = function (con, cb) {
            con.query(query, function (err, res) {
                cb(!err && res);
            });
        };
        delete config.validationQuery;
    }
    pool = new pg.Pool(config);
    pool.on('error', console.log);
    return api(pool);
};
Example #2
0
exports.init = function(config) {
  PG_POOL = new pg.Pool(config);

  PG_POOL.on('error', (err, client) => {
    console.error('idle client error', err.message, err.stack);
  });

  // PG_POOL.on('connect', (client) => {
  //   console.log("connect");
  // });
};
Example #3
0
File: db.js Project: timgit/pg-boss
  constructor(config){
    super();

    this.config = config;

    if(config.poolSize)
      config.max = config.poolSize;

    config.application_name = config.application_name || 'pgboss'

    this.pool = new pg.Pool(config);

    this.pool.on('error', error => this.emit('error', error));
  }
Example #4
0
postgresModule.connect = function (options, callback) {
	var Pool = require('pg').Pool;

	var connOptions = postgresModule.getConnectionOptions(options);

	const db = new Pool(connOptions);

	db.on('connect', function (client) {
		var realQuery = client.query;
		client.query = function () {
			var args = Array.prototype.slice.call(arguments, 0);
			if (dbNamespace.active && typeof args[args.length - 1] === 'function') {
				args[args.length - 1] = dbNamespace.bind(args[args.length - 1]);
			}
			return realQuery.apply(client, args);
		};
	});

	db.connect(function (err) {
		callback(err, db);
	});
};
Example #5
0
const cors = require('cors');

const app = express();
app.use(cors());
app.use(bodyParser.json());

// Postgres Client Setup
const { Pool } = require('pg');
const pgClient = new Pool({
  user: keys.pgUser,
  host: keys.pgHost,
  database: keys.pgDatabase,
  password: keys.pgPassword,
  port: keys.pgPort
});
pgClient.on('error', () => console.log('Lost PG connection'));

pgClient
  .query('CREATE TABLE IF NOT EXISTS values (number INT)')
  .catch(err => console.log(err));

// Redis Client Setup
const redis = require('redis');
const redisClient = redis.createClient({
  host: keys.redisHost,
  port: keys.redisPort,
  retry_strategy: () => 1000
});
const redisPublisher = redisClient.duplicate();

// Express route handlers
Example #6
0
var Pool = require('pg').Pool;
//Client Credentials to connect to the Postgres database
var pool = new Pool({
    user: process.env.DB_USER,
    password: process.env.DB_PASS,
    database: process.env.DB_Database,
    port: 5432,
    host: process.env.DB_HOST,
    ssl: true,
    max: 10, // max number of clients in the pool
    idleTimeoutMillis: 30000, // how long a client is allowed to remain idle before being closed
});

pool.on('error', function(e, client) {
    console.log(e);
    console.log(client);
});

module.exports = {

    insertData: function(data) {
        return new Promise((resolve) => {

            if (data.length === 2) {
                //Getting the values from the object
                var herokuValue = data[Object.keys(data)[0]];
                var CCIValue = data[Object.keys(data)[1]];
                console.log("Heroku Value:" + herokuValue + "CCI Value:" + CCIValue);

                pool.query('INSERT INTO APPLICATION(heroku_application, cci_level) VALUES($1, $2)', [herokuValue, CCIValue])
                    .then(res => resolve(res));
Example #7
0
const express = require('express')
const app = express();

const bodyParser = require('body-parser');
var rp = require('request-promise');
const pg = require('pg');

const { Pool } = require('pg');

const pool = new Pool({
  connectionString: process.env.DATABASE_URL
});

pool.on('connect', () => {
  console.log('connected to the db');
});


app.get('/', function(req, res) {
    res.send('Hello Psycap!');
});

app.get('/insert', function(req, res) {
    const text = `INSERT INTO
      reflections(id, success, low_point, take_away, created_date, modified_date)
      VALUES($1, $2, $3, $4, $5, $6)
      returning *`;
    const values = [
      1,
      "sucess1",
      "lo1",
Example #8
0
  const callback = cb

  pool.connect().then(client => {
    client.query(query, params).then(res => {
      client.release()
      callback(noErr, res)
    })
    .catch(e => {
      client.release()
      logger.error('error running query', e.message, e.stack)
      callback(e, null)
    })
  })
  .catch(e => {
    console.error('error fetching client from pool', e.message, e.stack )
    callback(e)
  })
}

pool.on('error', function (err, client) {
  // if an error is encountered by a client while it sits idle in the pool
  // the pool itself will emit an error event with both the error and
  // the client which emitted the original error
  // this is a rare occurrence but can happen if there is a network partition
  // between your application and the database, the database restarts, etc.
  // and so you might want to handle it and at least log it out
  console.error('idle client error', err.message, err.stack)
})

export default queryDb
Example #9
0
var pg = require('pg');

var config = {
    user: 'lunchroulette',
    password: 'lunchroulette',
    database: 'lunchroulette',
    max: 100,
    idleTimeoutMillis: 30000
};

var pool = new pg.Pool(config);

pool.on('error', function (err, client) {
    // Rare case of a DB side issue, should log it.
    console.error('Idle client error: ', err.message, err.stack)
});

module.exports = {
    query: function (query, values, callback) {
        var handleConnection = function (err, client, done) {
            if (err) {
                return console.error('Error fetching client from pool: ', err);
            }

            var handleResult = function (err, result) {
                done();

                if (err) {
                    return console.error('Error running query: ', err);
                }
                callback(result);
Example #10
0
const pg = require('pg')
const config = require('../../../config.json')

const pool = new pg.Pool(config.db)

pool.on('error', err => {
  /* eslint-disable */
  console.error('idle client error', err.message, err.stack)
})

export default {
  query(text, values, callback) {
    // log queries in dev environment
    if (process.env.NODE_ENV !== 'production') {
      /* eslint-disable */
      console.log('query: ', text)
      if (values) {
        console.log('query with values: ', values)
      }
    }

    return pool.query(text, values, callback)
  },
  connect(fn) {
    return pool.connect(fn)
  },
  end() {
    return pool.end()
  }
}
Example #11
0
          " + m.pokemon_id + "::smallint, \
          " + m.longitude_jittered + "::double precision, \
          " + m.latitude_jittered + "::double precision, \
          " + m.pokemon_go_era + "::integer \
        ) \
        ON CONFLICT (encounter_id) \
        DO UPDATE \
          SET last_modified_time = EXCLUDED.last_modified_time, \
          time_until_hidden_ms = EXCLUDED.time_until_hidden_ms, \
          hidden_time_unix_s = EXCLUDED.hidden_time_unix_s, \
          hidden_time_utc = EXCLUDED.hidden_time_utc;";

        log.info("Pokemon with ID " + m.pokemon_id + " found.")
        log.debug(query_string);

        client.query(query_string,
        function(err, result) {
          done();

          if(err) {
            return log.error("Error running query", err);
          }
        });
      });
    }
});

pool.on('error', function(err, client) {
  log.error('Idle client error', err.message, err.stack);
});
Example #12
0
      client.query('INSERT INTO public.images (name, image, thumbnail, mimetype) VALUES ($1, $2, $3, $4) RETURNING id', [req.body.name, req.file.buffer, thumbnail, req.file.mimetype], function(err, result) {
        done();
        if(err) {
          res.status(500).json({success: false, error: err});
          return;
        }
        if(result.rowCount > 0) {
          res.json({success: true, id: result.rows[0].id});
				  return;
        } else {
          res.status(500).json({success: false, error: err});
          return;
        }
      });
    });
  });
});

//placeholder form
var content = '<html><body><form method="post" enctype="multipart/form-data" action="/api/upload"><p><input type="text" name="name" placeholder="Name" /></p><p><input type="file" name="image" /></p><p><input type="submit" /></body></html>';
app.get('/api/upload', function(req, res) {
	res.send(content);
});

app.listen(process.env.PORT || 8080);

pool.on('error', function (err, client) {

  console.error('idle client error', err.message, err.stack)
})
    database: params.pathname.split('/')[1],
    ssl: true, // heroku requires ssl to be true
    max: 10, // max number of clients in the pool
    idleTimeoutMillis: 30000, // how long a client is allowed to remain idle before being closed
  };
} else {
  config = {
    host: 'localhost', // Server hosting the postgres database
    port: 5432, // env var: PGPORT
    database: 'message_board', // CHANGE THIS LINE! env var: PGDATABASE, this is likely the one thing you need to change to get up and running
    max: 10, // max number of clients in the pool
    idleTimeoutMillis: 30000, // how long a client is allowed to remain idle before being closed
  };
}

// this creates the pool that will be shared by all other modules
const pool = new pg.Pool(config);

// the pool will log when it connects to the database
pool.on('connect', () => {
  console.log('Postgesql connected');
});

// the pool with emit an error on behalf of any idle clients
// it contains if a backend error or network partition happens
pool.on('error', (err) => {
  console.log('Unexpected error on idle client', err);
  process.exit(-1);
});

module.exports = pool;
Example #14
0
                winston.log('info', resultsObj.message, resultsObj);
            } else {
                winston.log('error', err);

            }
        });

    });
    client.query("LISTEN _gc2_notify_transaction");
};
/**
 * @type {pg.Pool}
 */
var pool = new pg.Pool(config);

pool.connect(function (err, client, done) {
    if (err) {
        console.log(err);
    } else {
        start(client);
    }
});

pool.on('error', function (err, client) {
    console.error(err.message);
    pool.connect(function (err, client, done) {
        if (!err) {
            start(client);
        }
    });
});
Example #15
0
postgresModule.init = function (callback) {
	callback = callback || function () { };

	var Pool = require('pg').Pool;

	var connOptions = postgresModule.getConnectionOptions();

	const db = new Pool(connOptions);

	db.on('connect', function (client) {
		var realQuery = client.query;
		client.query = function () {
			var args = Array.prototype.slice.call(arguments, 0);
			if (dbNamespace.active && typeof args[args.length - 1] === 'function') {
				args[args.length - 1] = dbNamespace.bind(args[args.length - 1]);
			}
			return realQuery.apply(client, args);
		};
	});

	db.connect(function (err, client, release) {
		if (err) {
			winston.error('NodeBB could not connect to your PostgreSQL database. PostgreSQL returned the following error: ' + err.message);
			return callback(err);
		}

		postgresModule.pool = db;
		Object.defineProperty(postgresModule, 'client', {
			get: function () {
				return (dbNamespace.active && dbNamespace.get('db')) || db;
			},
			configurable: true,
		});

		var wrappedDB = {
			connect: function () {
				return postgresModule.pool.connect.apply(postgresModule.pool, arguments);
			},
			query: function () {
				return postgresModule.client.query.apply(postgresModule.client, arguments);
			},
		};

		checkUpgrade(client, function (err) {
			release();
			if (err) {
				return callback(err);
			}

			require('./postgres/main')(wrappedDB, postgresModule);
			require('./postgres/hash')(wrappedDB, postgresModule);
			require('./postgres/sets')(wrappedDB, postgresModule);
			require('./postgres/sorted')(wrappedDB, postgresModule);
			require('./postgres/list')(wrappedDB, postgresModule);
			require('./postgres/transaction')(db, dbNamespace, postgresModule);

			postgresModule.async = require('../promisify')(postgresModule, ['client', 'sessionStore', 'pool']);

			callback();
		});
	});
};
Example #16
0
const config = require("./config").getProperties();

const pg = require("pg");
const mozlog = require("./logging").mozlog("db");
const logQueryLimit = config.db.logQueryLimit;

const user = encodeURIComponent(config.db.user);
const dbname = encodeURIComponent(config.db.dbname || config.db.user);
const credentials = config.db.password ? `${user}:${encodeURIComponent(config.db.password)}` : user;
const constr = `postgres://${credentials}@${config.db.host}/${dbname}`;

const pool = new pg.Pool(Object.assign({connectionString: constr}, config.db.pool));

pool.on("error", function(error) {
  mozlog.error("db-error", {
    msg: "Error in database:",
    err: error
  });
});

function getConnection() {
  return new Promise(function(resolve, reject) {
    pool.connect(function(err, client, done) {
      if (err) {
        reject(err);
      } else {
        resolve([client, done]);
      }
    });
  });
}
Example #17
0
 _pool = new Promise(resolve => {
   const p = new Pool(server)
   p.on('error', (...args) => handleError(...args))
   resolve(p)
 })
Example #18
0
//postgress pool connection
var pg = require('pg');
var Pool = require('pg').Pool;

pg.defaults.ssl = true;
var pool = new Pool ({
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  host: process.env.DB_HOST,
  database: process.env.DB_DATABASE,
  max: process.env.DB_CONNECTION_LIMIT,
  idleTimeoutMillis: 1000
});

pool.on('error', function(e, client) {
    console.log('|| Error in DB pool: ',e );
});

  function logConversation(msgLog) {
    pool.query('insert into conversation (smoochid, received, usermessage, role, message_id, sourcetype, receivedtime, responsemessage, responsetype, responsetime) values ($1,$2, $3, $4, $5,$6, $7, $8, $9, $10);',
      [msgLog.smoochId, msgLog.received, msgLog.usermessage, msgLog.role, msgLog.message_id, msgLog.sourcetype, msgLog.receivedtime, msgLog.responsemessage, msgLog.responsetype, msgLog.responsetime],
      function(err){
        if(err) console.log("|| error in log ",err);
      }
    );
  }

    function adhocConv(newBot, message, response) {
      pool.connect(function(err, client, release) {
        if (err) {
          console.error("pool error: ",err);