How to use the pg.Pool 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 huncwotjs / huncwot / db.js View on Github external
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

const config = require('config');

const Logger = require('./logger');

const pg = require('pg');
const sqorn = require('@sqorn/pg');

const connection = config.get('db');

const pool = new pg.Pool(connection);

pool.connect(error => {
  if (error) {
    Logger.printError(error, 'Data Layer');

    process.exit(1);
  }
});

module.exports = sqorn({ pg, pool });
github ptarmiganlabs / butler-sos / src / globals.js View on Github external
winston.format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`),
  ),
});

// Function to get current logging level
getLoggingLevel = () => {
  return logTransports.find(transport => {
    return transport.name == 'console';
  }).level;
};

// Get info on what servers to monitor
const serverList = config.get('Butler-SOS.serversToMonitor.servers');

// Set up connection pool for accessing Qlik Sense log db
const pgPool = new Pool({
  host: config.get('Butler-SOS.logdb.host'),
  database: 'QLogs',
  user: config.get('Butler-SOS.logdb.qlogsReaderUser'),
  password: config.get('Butler-SOS.logdb.qlogsReaderPwd'),
  port: config.get('Butler-SOS.logdb.port'),
});

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

// Get list of standard and user configurable tags
// ..begin with standard tags
github open-horizon / examples / cloud / sdr / data-processing / ibm-functions / actions / msgreceive.js View on Github external
function connect2db(connectionString) {
  console.log(`Connecting (eventually) to ${connectionString}`);
  const db = new Pool({ connectionString: connectionString });
  // Verify the connection to the db. Since db.query() is a promise, this will happen asynchronously to the rest of the code analyzing the data and updating tables.
  db.query('SELECT NOW()')
      .then((res) => console.log('Connected to db: ' + res.rows[0].now))
      .catch((e) => setImmediate(() => { throw e; }));
  return db;
}
github graphile / postgraphile / src / postgraphile / postgraphile.ts View on Github external
function toPgPool(poolOrConfig: any): Pool {
  if (quacksLikePgPool(poolOrConfig)) {
    // If it is already a `Pool`, just use it.
    return poolOrConfig;
  }

  if (typeof poolOrConfig === 'string') {
    // If it is a string, let us parse it to get a config to create a `Pool`.
    return new Pool({ connectionString: poolOrConfig });
  } else if (!poolOrConfig) {
    // Use an empty config and let the defaults take over.
    return new Pool({});
  } else if (isPlainObject(poolOrConfig)) {
    // The user handed over a configuration object, pass it through
    return new Pool(poolOrConfig);
  } else {
    throw new Error('Invalid connection string / Pool ');
  }
}
github evoluteur / evolutility-server-node / js / setup / database.js View on Github external
function createSchema(runSQL = true, logFile = true){
    let { sql, sqlData } = sqlSchemaWithData()

    if(runSQL){
        const dbConfig = parseConnection(config.connectionString)
        dbConfig.max = 10; // max number of clients in the pool 
        dbConfig.idleTimeoutMillis = 30000; // max client idle time before being closed
        const pool = new pg.Pool(dbConfig);
        
        if(logFile) {
            logToFile(sql, false)
        }
        pool.connect(function(err, client, done) {
            // - Create schema and tables
            client.query(sql, function(err, data) {
                if(err){ 
                    done();
                    throw err;
                }
                // - Populate tables
                if(logFile) {
                    logToFile(sqlData, true)
                }
                client.query(sqlData, function(err, data) {
github sqorn / sqorn / examples / postgres / main.js View on Github external
async function main() {
  // connect to admin database
  let pool = new pg.Pool(adminConnection)
  let sq = sqorn({ pg, pool })
  // delete app database if it exists
  await sq.sql`drop database if exists $${appDatabase}`
  // create app database
  await sq.sql`create database $${appDatabase}`
  // disconnect from admin database
  await sq.end()
  // connect to created database
  pool = new pg.Pool(appConnection)
  sq = sqorn({ pg, pool })
  // create author table
  await sq.sql`create table author (
    id              serial primary key,
    first_name      text,
    last_name       text,
    birthday        date
  )`
  // create book table
  await sq.sql`create table book (
    id              serial primary key,
    title           text,
    genre           text,
    publish_year    integer,
    author_id       integer,
                    foreign key (author_id) references author (id)
github metarhia / globalstorage / test / pg.cursor.raw.js View on Github external
'use strict';

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

const { PostgresCursor } = require('../lib/pg.cursor');

const { pgOptions } = require('./utils');

const tableName = 'GSTestTable';

const pool = new Pool(pgOptions);

const now = Date.now();
const rowData = [
  { id: 1, text: 'aaa', date: new Date(now - 1000) },
  { id: 2, text: 'aaa', date: new Date(now - 1000) },
  { id: 3, text: 'bbb', date: new Date(now - 5000) },
  { id: 4, text: 'bbb', date: new Date(now - 5000) },
  { id: 5, text: 'ccc', date: new Date(now - 1000) },
];

test('PostgresCursor test', async test => {
  try {
    await pool.query(`DROP TABLE IF EXISTS "${tableName}"`);
    await pool.query(
      `CREATE TABLE "${tableName}" (
         id int,
github oslabs-beta / protographql / src / pg-import / pgQuery.js View on Github external
const constraintQuery = `
    SELECT table_name,
    column_name,
    constraint_name
    FROM information_schema.constraint_column_usage
    WHERE table_schema not in ('information_schema', 'pg_catalog') AND
    table_name not in ('pg_stat_statements')
    ORDER BY table_name;`
    
    let tableColumns = {};
    
    //this is not updating!!
    const URI = process.env.DB_URI
    
    const pool = new Pool({
      connectionString: URI,
      ssl: true,
    })
    console.log('db uri pre pool.connect:', URI)
    
    pool.connect((err, client, done) => {
      if (err) return console.log(`Error connecting to db, ${err}`);
      console.log('Connected to db šŸ˜„')
      done();
    })
    
    let queryResults = await pool.query(tableQuery)
    .then(res => {
        console.log("pool: ",pool)
        console.log('db URI: ', URI)
        console.log('tableQuery: ',res.rows)
github malerey / No-Gluten / server / db / index.js View on Github external
const { Pool } = require('pg')
const { HOSTINDEX, PASSINDEX } = process.env


const pool = new Pool({
    user: 'male',
    host: HOSTINDEX,
    database: 'male',
    password: PASSINDEX,
    port: 5432,
  })

module.exports = {
  query: (text, params) => pool.query(text, params)
}
github OriginProtocol / origin / origin-discovery / lib / db.js View on Github external
const { Pool } = require('pg')

/*
  Module to interface with Postgres database.
 */

const pool = new Pool(
  {
    host: process.env.DATABASE_HOST || 'postgres',
    port: process.env.DATABASE_PORT || 5432,
    database: process.env.DATABASE_NAME || 'origin-indexing',
    user: process.env.DATABASE_USERNAME || 'origin',
    password: process.env.DATABASE_PASSWORD || 'origin',
  })


class Listing {
  /*
  * Returns the row from the listing table with the specified id.
  * @throws Throws an error if the read operation failed.
  * @returns A row or undefined if no row found with the specified listingId.
  */
  static async get(listingId) {