function testTimeOut(config){
    var pool = new pg.Pool(config.db);
    console.log('SIN CONEXIONES');
    return pool.connect().then(function(client){
        console.log('1 CONEXION');
        console.log('pool', pool.pool._inUseObjects.length, pool.pool._inUseObjects[0]);
        client.query("SELECT '1 year 11 days 13:45:15.12'::interval el_intervalo", function(err, result) {
            console.log(result.rows[0]);
            console.dir(result.rows[0].el_intervalo);
            console.log(result.rows[0].el_intervalo);
            console.log(JSON.stringify(result.rows[0].el_intervalo));
            console.log(''+result.rows[0].el_intervalo);
            console.log(result.rows[0].el_intervalo.toString());
            console.log('=========');
            for(var attr in result.rows[0].el_intervalo){
                console.log(attr, result.rows[0].el_intervalo[attr]);
            }
            client.release();
            console.log('pool release', pool.pool._inUseObjects.length, pool.pool.borrowed);
            [1000,2000,3000].forEach(function(time){
                sleep(time).then(function(){
                    console.log('FINALLY CONEXIONES');
                    console.log('pool',time,'sleep', pool.pool._inUseObjects.length, pool.pool.borrowed);
                }).catch(logErr);
            });
        });
    });
}
app.post('/uploadData',function(req,res){
    // note that we are using POST here as we are uploading data
    // so the parameters form part of the BODY of the request rather than the RESTful API
    console.dir(req.body);
    pool.connect(function(err,client,done) {
        if(err){
            console.log("not able to get connection "+ err);
            res.status(400).send(err);
        }
        var name = req.body.name;
        var surname = req.body.surname;
        var module = req.body.module;
        var portnum = req.body.port_id;
        var language = req.body.language;
        var modulelist = req.body.modulelist;
        var lecturetime = req.body.lecturetime;
        var geometrystring = "st_geomfromtext('POINT("+req.body.longitude + " "+ req.body.latitude + ")')";
        var querystring = "INSERT into formdata (name,surname,module, port_id,language, modulelist, lecturetime, geom) values ($1,$2,$3,$4,$5,$6,$7,";
        var querystring = querystring + geometrystring + ")";
        console.log(querystring);
        client.query( querystring,[name,surname,module, portnum, language, modulelist, lecturetime],function(err,result) {
            done();
            if(err){
                console.log(err);
                res.status(400).send(err);
            }
            res.status(200).send("row inserted");
        });
    });
}); 
Example #3
0
const accountFromToken = (token, req, next) => {
  pgPool.connect((err, client, done) => {
    if (err) {
      next(err)
      return
    }

    client.query('SELECT oauth_access_tokens.resource_owner_id, users.account_id FROM oauth_access_tokens INNER JOIN users ON oauth_access_tokens.resource_owner_id = users.id WHERE oauth_access_tokens.token = $1 LIMIT 1', [token], (err, result) => {
      done()

      if (err) {
        next(err)
        return
      }

      if (result.rows.length === 0) {
        err = new Error('Invalid access token')
        err.statusCode = 401

        next(err)
        return
      }

      req.accountId = result.rows[0].account_id

      next()
    })
  })
}
Example #4
0
app.post('/api/upload', upload.single('image'), function(req, res) {
	console.log(req.file.buffer);
	console.log(req.body.name);
	pool.connect(function(err, client, done) {
    if(err) {
      res.status(500).json({success: false, error: err});
      return;
    }
    createThumbnail(req.file.buffer, req.file.mimetype, 200, 200).then(thumbnail => {
      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;
        }
      });
    });
  });
});
Example #5
0
function addToUserCigars(data, callback){
  console.log('/models/cigar.js', data);
  pool.connect(function(err, client, done){
    if(err){
      done();
      return callback(err);
    }

    // client.query('INSERT INTO cigars (brand, name, origin, wrapper_color, wrapper_country, filler, body) VALUES ($1, $2, $3, $4, $5, $6, $7);',
    // [data.brand, data.name, data.origin.country, data.wrapperColor, data.wrapperCountry, data.filler, data.body],
    client.query('INSERT INTO users_cigars (user_id, cigars_id, date, quantity, '
    + 'sizes_id, gauges_id, condition, comments) VALUES ($1, $2, $3, $4, $5, $6, '
    + '$7, $8);',
    [data.user.id, data.name.id, data.date, data.quantity, data.size.id, data.gauge.id,
    data.condition, data.comments], function(err, result){
      if(err){
        done();
        return callback(err);
      }
      else{
        callback(null, result.rows[0]);
        done();
      }
    });
  });
};
Example #6
0
  arr.forEach(function(conn) {
    var id = conn.id;
    var name = conn.name;
    var constellation = conn.con;
    // doing it the ugly way to see if it works and save time:
    pool.connect(function (errorConnectingToDb, db, done) {
      if (errorConnectingToDb) {
        // There was an error and no connection was made
        console.log('Error connecting', errorConnectingToDb);
        res.sendStatus(500);
      } else {
        // We connected to the db!!!!! pool -1
        // console.log(star, "HI THERE");
        var queryText = 'INSERT INTO "' + constellation + '" ("") VALUES($1, $2);';
        db.query(queryText, [id, name], function (errorMakingQuery, result) {
          // We have received an error or result at this point
          done(); // pool +1
          if (errorMakingQuery) {
            // console.log('Error making query', errorMakingQuery);
            res.sendStatus(500);

          } else {
            // Send back success!
            res.sendStatus(201);

          }
        }); // END QUERY
      }
    }); // END POOL
  });
Example #7
0
app.post('/con', function(req, res) {
  console.log(req.body.name);
  pool.connect(function (errorConnectingToDb, db, done) {
    if (errorConnectingToDb) {
      // There was an error and no connection was made
      console.log('Error connecting', errorConnectingToDb);
      res.sendStatus(500);
    } else {
      // We connected to the db!!!!! pool -1
      // console.log(star, "HI THERE");
      var queryText = 'CREATE TABLE "' + req.body.name + '"(id serial PRIMARY KEY, start_pt varchar(40), end_pt varchar(40));';
      db.query(queryText, [], function (errorMakingQuery, result) {
        // We have received an error or result at this point
        done(); // pool +1
        if (errorMakingQuery) {
          // console.log('Error making query', errorMakingQuery);
          res.sendStatus(500);

        } else {
          // Send back success!
          res.sendStatus(201);

        }
      }); // END QUERY
    }
  }); // END POOL
});
Example #8
0
function setup(app, root, next) {
    if (process.env.USE_SECURE !== undefined && process.env.USE_SECURE === true) {
        console.log('Forcing HTTPS...');
        app.use(enforce.HTTPS());
    }

    app.use(bodyParser.json({ limit: '50mb' }));
    app.use(bodyParser.urlencoded({ extended: true }));

    pgPool = new pg.Pool(getPostgresConfig(process.env.PG_REMOTE_URL));
    pgPool.connect()
        .then(remoteClient => {
            console.log("Connected to remote postgres server.");
            client = remoteClient;
            setupDatabase(app, root, next);
        })
        .catch(err => {
            pgPool = new pg.Pool(getPostgresConfig(process.env.PG_LOCAL_URL));
            pgPool.connect().then(localClient => {
                console.log("Connected to local postgres server.");
                client = localClient;
                setupDatabase(app, root, next);
            })
            .catch(err => {
                console.log("No postgres server found.");
                setupDatabase(app, root, next);
            });
        });
}
Example #9
0
function saveConstellation(con) {
  pool.connect(function (errorConnectingToDb, db, done) {
    if (errorConnectingToDb) {
      // There was an error and no connection was made
      console.log('Error connecting', errorConnectingToDb);
    } else {
      // var queryText;
      // while (con.length > 0) {
      //
      // }
      // We connected to the db!!!!! pool -1
      // console.log(star, "HI THERE");
      var queryText = 'INSERT INTO "stars" ("star_id", "star_name", "vismag", "absmag", "distance", "ra", "dec", "spec", "ci", "constellation", "lum") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11);';
      db.query(queryText, [star.star_id, star.star_name, star.visMag, star.absMag, star.distance, star.ra, star.dec, star.spec, star.ci, star.constellation, star.lum], function (errorMakingQuery, result) {
        // We have received an error or result at this point
        done(); // pool +1
        if (errorMakingQuery) {
          console.log('Error making query', errorMakingQuery);
        } else {
          // Send back success!

        }
      }); // END QUERY
    }
  }); // END POOL
}
Example #10
0
function create(data, callback){
  // var sendData = {};
  console.log('/models/cigar.js', data);
  pool.connect(function(err, client, done){
    if(err){
      done();
      return callback(err);
    }

    // client.query('INSERT INTO cigars (brand, name, origin, wrapper_color, wrapper_country, filler, body) VALUES ($1, $2, $3, $4, $5, $6, $7);',
    // [data.brand, data.name, data.origin.country, data.wrapperColor, data.wrapperCountry, data.filler, data.body],
    client.query('INSERT INTO cigars (brand_id, name, body_id, wrapper_color_id, wrapper_country_id) VALUES '
    + '((SELECT brand_id FROM brand WHERE brand.brand = $1), '
    + '$2, (SELECT wrapper_color_id FROM wrapper_color WHERE wrapper_color.name = $3), '
    + '(SELECT wrapper_country_id FROM wrapper_country LEFT JOIN country ON wrapper_country.country_id = country.id WHERE country.country = $4));',
    [data.brand, data.name, data.body, data.origin.country, data.wrapperColor, data.wrapperCountry], function(err, result){
      if(err){
        done();
        return callback(err);
      }
      else{
        callback(null, result.rows[0]);
        done();
      }
    });
  });
};
Example #11
0
    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);
            };

            if (typeof values === 'function') {
                callback = values;
                client.query(query, handleResult);
            } else {
                client.query(query, values, handleResult);
            }
        };

        pool.connect(handleConnection);
    }
Example #12
0
app.get('/getQuestions', function (req,res) {
     pool.connect(function(err,client,done) {
       if(err){
           console.log("not able to get connection "+ err);
           res.status(400).send(err);
       } 
        // Use the inbuilt geoJSON functionality
        /* Create the required geoJSON format using a query adapted from here:
		http://www.postgresonline.com/journal/archives/267-Creating-GeoJSON-Feature-Collections-with-JSON-and-PostGIS-functions.html, accessed 4th January 2018 */

        	var querystring = " SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) As features  FROM ";
        	querystring = querystring + "(SELECT 'Feature' As type     , ST_AsGeoJSON(lg.question_location)::json As geometry, ";
        	querystring = querystring + "row_to_json((SELECT l FROM (SELECT location_name, question, answer_1, answer_2, answer_3, answer_4, answer_correct) As l      )) As properties";
        	querystring = querystring + "   FROM app_questions  As lg limit 100  ) As f ";
        	console.log(querystring);
        	client.query(querystring,function(err,result){

          //call `done()` to release the client back to the pool
           done(); 
           if(err){
               console.log(err);
               res.status(400).send(err);
           }
           res.status(200).send(result.rows);
       });
    });
});
Example #13
0
function createAndAdd(data, callback){
  console.log('/models/cigar.js', data);
  pool.connect(function(err, client, done){
    if(err){
      done();
      return callback(err);
    }

    // client.query('INSERT INTO cigars (brand, name, origin, wrapper_color, wrapper_country, filler, body) VALUES ($1, $2, $3, $4, $5, $6, $7);',
    // [data.brand, data.name, data.origin.country, data.wrapperColor, data.wrapperCountry, data.filler, data.body],
    client.query('WITH newcigar AS (INSERT INTO cigars (brand_id, name, body_id, '
    + 'origin_id, wrapper_color_id, wrapper_country_id) VALUES ($1, $2, '
    + '$3, $4, $5, $6) RETURNING id) INSERT INTO users_cigars (users_id, '
    + 'cigars_id, date, quantity, sizes_id, gauges_id, condition, comments) '
    + 'VALUES ($7, (SELECT newcigar.id from newcigar), $8, $9, $10, $11, $12, $13);',
    [data.brand.id, data.name.name, data.body.id, data.origin.id,
      data.wrapperColor.id, data.wrapperCountry.id, data.user.id, data.date,
    data.quantity, data.size.id, data.gauge.id, data.condition, data.comments],
    function(err, result){
      if(err){
        done();
        return callback(err);
      }
      else{
        callback(null, result.rows[0]);
        done();
      }
    });
  });
};
Example #14
0
app.get('/api/image/:id', function(req, res) {

	pool.connect(function(err, client, done) {
		if(err) {
			res.status(500).json({success: false, error: err});
      return;
		}
		client.query('SELECT image, mimetype FROM public.images WHERE id = $1', [req.params.id], function (err, result) {
			done();
			if(err) {
				res.status(500).json({success: false, error: err});
        return;
			}

			if(result.rows.length > 0) {
				var img = new Buffer(result.rows[0].image, 'binary');
				res.writeHead(200, {
					'Content-Type': result.rows[0].mimetype,
					'Content-Length': img.length
				});
				res.end(img);
			} else {
				res.json({success: false, error: "image not found!"});
        return;
			}
		});
	});
});
 co(function *() {
   var client = null;
   var result = null;
   var error = null;
   try {
     client = yield pool.connect();
     result = yield client.query(sqlCommand);
   } catch (err) {
     error = err;
     if (!opt_noLog) {
       if (client) {
         logger.error('sqlQuery error sqlCommand: %s:\r\n%s', sqlCommand.slice(0, 50), err.stack);
       } else {
         logger.error('pool.getConnection error: %s', err);
       }
     }
   } finally {
     if (client) {
       client.release();
     }
     if (callbackFunction) {
       var output = result;
       if (result && !opt_noModifyRes) {
         if ('SELECT' === result.command) {
           output = result.rows;
         } else {
           output = {affectedRows: result.rowCount};
         }
       }
       callbackFunction(error, output);
     }
   }
 });
Example #16
0
function addToBrand(data, callback){
  pool.connect(function(err, client, done){
    if(err){
      done();
      return callback(err);
    }
    client.query('WITH newbrand AS (INSERT INTO brand (brand) VALUES ($1) returning id), '
    + 'newcigar AS (INSERT INTO cigars(brand_id, name, body_id, wrapper_color_id, '
    + 'wrapper_country_id, origin_id, filler_combo_id) VALUES ((SELECT newbrand.id FROM '
    + 'newbrand), $2, $3, $4, $5, $6, $7) returning id), '
    + 'useful AS (INSERT INTO cigars(brand_id, name, body_id, wrapper_color_id, '
    + 'wrapper_country_id, origin_id, filler_combo_id) VALUES ((SELECT newbrand.id '
    + 'FROM newbrand), $8, $9, $10, $11, $12, $13) returning id) '
    + 'INSERT INTO users_cigars(users_id, cigars_id, date, quantity, sizes_id, gauges_id, '
    + 'condition, comments) VALUES($14,(SELECT newcigar.id FROM newcigar), $15, $16, '
    + '$17, $18, $19, $20);',
    [data.brand, data.name, data.body.id, data.wrapperColor.id, data.wrapperCountry.id,
    data.origin.id, null, 'other', null, null, null, null, null, data.user.id, data.date,
    data.quantity, data.size.id, data.gauge.id, data.condition, data.comments], function(err, result){
      if(err){
        done();
        return callback(err);
      }
      else{
        callback(null, result.rows[0]);
        done();
      }
    });
  });
};
Example #17
0
function updateAndAdd(data, callback){
  pool.connect(function(err, client, done){
    if(err){
      done();
      return callback(err);
    }

    client.query('WITH updated AS (UPDATE cigars SET body_id = $1, wrapper_color_id = '
    + '$2, wrapper_country_id = $3, origin_id = $4, filler_combo_id = $5 WHERE '
    + 'cigars.name = $6 RETURNING id) INSERT INTO users_cigars (users_id, '
    + 'cigars_id, date, quantity, sizes_id, gauges_id, condition, comments) VALUES '
    + '($7, (SELECT updated.id FROM updated), $8, $9, $10, $11, $12, $13);',
    [data.body.id, data.wrapperColor.id, wrapperCountry.id, data.origin.id, null,
    data.name.name, data.user.id, data.date, data.quantity, data.size.id, data.gauge.id,
    data.condition, data.comments], function(err, result){
      if(err){
        done();
        return callback(err);
      }
      else{
        callback(null, result.rows[0]);
        done();
      }
    });
  });
};
Example #18
0
pool.on('error', function (err, client) {
    console.error(err.message);
    pool.connect(function (err, client, done) {
        if (!err) {
            start(client);
        }
    });
});
Example #19
0
 return new Promise(function(resolve, reject) {
   pool.connect(function(err, client, done) {
     if (err) {
       reject(err);
     } else {
       resolve([client, done]);
     }
   });
 });
Example #20
0
function getCigarList(callback){
  var sendData = {};

  pool.connect(function(err, client, done){
    if(err){
      done();
      return callback(err);
    }

    // client.query('SELECT cigars.id as id, string_agg(brand.brand, ' '), cigars.name, string_agg(body.name, ' ') as body, '
    // + 'string_agg(wrapper_color.name, ' ') as wrapper_color_name, string_agg(wrapper_color.description, ' ') as wrapper_color_description, '
    // + 'string_agg(country.country, ' ') as origin_country, string_agg(wrapper.country, ' ') as wrapper_country, '
    // + 'string_agg(c_f.country, ' ') as filler_country '
    // + 'FROM cigars '
    // + 'LEFT OUTER JOIN body ON cigars.body_id = body.id '
    // + 'LEFT OUTER JOIN wrapper_color ON cigars.wrapper_color_id = wrapper_color.id '
    // + 'LEFT OUTER JOIN brand ON cigars.brand_id = brand.id '
    // + 'LEFT OUTER JOIN origin ON cigars.origin_id = origin.id '
    // + 'LEFT JOIN country ON origin.country_id = country.id '
    // + 'LEFT JOIN wrapper_country ON cigars.wrapper_country_id = wrapper_country.id '
    // + 'LEFT JOIN country as wrapper ON wrapper_country.country_id = wrapper.id '
    // + 'LEFT JOIN filler_combo ON filler_combo.cigars_id = cigars.id '
    // + 'LEFT JOIN filler ON filler_combo.filler_id = filler.id '
    // + 'LEFT JOIN country as c_f ON filler.country_id = c_f.id '
    // + 'GROUP BY cigar.id ORDER BY cigars.id;',
    client.query('SELECT cigars.id as id, brand.brand, cigars.name, body.name as body, '
    + 'wrapper_color.name as wrapper_color_name, wrapper_color.description as wrapper_color_description, '
    + 'country.country as origin_country, wrapper.country as wrapper_country, '
    + ' c_f.country as filler_country '
    + 'FROM cigars '
    + 'LEFT OUTER JOIN body ON cigars.body_id = body.id '
    + 'LEFT OUTER JOIN wrapper_color ON cigars.wrapper_color_id = wrapper_color.id '
    + 'LEFT OUTER JOIN brand ON cigars.brand_id = brand.id '
    + 'LEFT OUTER JOIN origin ON cigars.origin_id = origin.id '
    + 'LEFT JOIN country ON origin.country_id = country.id '
    + 'LEFT JOIN wrapper_country ON cigars.wrapper_country_id = wrapper_country.id '
    + 'LEFT JOIN country as wrapper ON wrapper_country.country_id = wrapper.id '
    + 'LEFT JOIN filler_combo ON filler_combo.cigars_id = cigars.id '
    + 'LEFT JOIN filler ON filler_combo.filler_id = filler.id '
    + 'LEFT JOIN country as c_f ON filler.country_id = c_f.id '
    + 'ORDER BY cigars.id;',
    function(err, result){
      sendData = result.rows;
      // console.log(sendData);
      if(err){
        console.log('query err', err);
        done();
        return callback(err);
      }
      else{
        // console.log(sendData);
        return callback(null, sendData);
      }
    });
  });
};
 return new Promise((resolve, reject) => {
   this.pool.connect((err, client, done) => {
     if (err) return reject(err);
     client.query(query, values, function (err, result) {
       //call `done()` to release the client back to the pool
       done();
       if (err) reject(err);
       resolve(result);
     });
   });
 });
Example #22
0
var queryFromPool = function(callback) {
  pool.connect(function(err, client, done) {
    if (err) {
      logger.crit('error fetching client from pool', err);
    }
    else {
      callback(client);
    }
    done();
});
}
 _writePgPool (chunk, env, cb) {
   const content = JSON.parse(chunk.toString())
   this.pool
     .connect()
     .then(client => {
       return this.writePgPool(client, content).then(result => {
         cb(null, result.rows)
         client.release()
       })
     })
     .catch(err => cb(err))
 }
Example #24
0
exports.CreateTables = function (callback) {
    pool.connect().then(client => {
        client.query('CREATE TABLE IF NOT EXISTS visit (date timestamptz)').then(res => {
            client.release()
            console.log('success')
        })
            .catch(e => {
                client.release()
                console.error('query error', e.message, e.stack)
            })
    })
}
Example #25
0
 .catch(err => {
     pgPool = new pg.Pool(getPostgresConfig(process.env.PG_LOCAL_URL));
     pgPool.connect().then(localClient => {
         console.log("Connected to local postgres server.");
         client = localClient;
         setupDatabase(app, root, next);
     })
     .catch(err => {
         console.log("No postgres server found.");
         setupDatabase(app, root, next);
     });
 });
Example #26
0
function runQuery(query, argsArray, callback) {
    pool.connect((err, client, done) => {
        if (err) {
            //likely a connection error that will print to console.
            done();
            throw err;
        }
        client.query(query, argsArray, (err, results) => {
            done(); //call done to release the client to the connection pool.
            callback(err, results); //make it the callers responsiblity for checking for query errors.
        });
    });
}
Example #27
0
const txDecorator = client => Future((reject, resolve) => {
	console.log('arquire connection')
	pool.connect((err, client, release) => {
		if (err) {
			reject('Error acquiring client')
		} else {
			console.log('connection open')
			resolve(client)
		}
	})
	// Cancellation:
	return () => release()
})
Example #28
0
export const createPoolConnection = (conf) => {
    const pool = new Pool(conf);
    return {
        query(q) {
            return pool.query(q);
        },
        connect() {
            return pool.connect();
        },
        stop() {
            return pool.end();
        }
    };
};
Example #29
0
function getUser(param, callback) {
    pool.connect((err,client,done)=>{
        if (err){
            return console.error('error fetching client from pool', err);
        }
        client.query('select * from public.user where email=$1',[param.email], (err,result)=>{
            done();
            if (err){
                return console.error('error running query', err);
            }
            callback(err,result.rows)
        })
    })

}
Example #30
0
function postAccommodation(data, callback) {
    pool.connect((err, client, done) => {
        if(err) {
            return console.error('error fetching client from pool', err);
        }
        client.query('INSERT INTO accommodation(title,icon,description) VALUES($1,$2,$3);',[data.title,data.icon,data.description], function(err, result) {
            debugger;
            done();
            if(err) {
                return console.error('error running query', err);
            }
            callback(err,result.rows);
        });
    });
}