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);
            });
        });
    });
}
Example #2
0
        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));

            } else if (data.length === 3) {
                //Getting the values from the object
                var forceValue = data[Object.keys(data)[0]];
                var herokuValueNew = data[Object.keys(data)[1]];
                var CCIValueNew = data[Object.keys(data)[2]];
                console.log("About to insert:" + forceValue + herokuValueNew + CCIValueNew);

                pool.query('INSERT INTO APPLICATION(heroku_application, force_application, cci_level) VALUES($1, $2, $3)', [herokuValueNew, forceValue, CCIValueNew])
                    .then(res => resolve(res));

            } else {
                console.log("Problem" + data);
            }
        });
Example #3
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 #4
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 #5
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 #6
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);
     });
 });
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 #8
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 #9
0
function queryAll(queryString, values) {
	return pool.query(queryString, values)
		.then(result => result.rows)
		.catch((err) => {
			throw new PgError(err);
		});
}
Example #10
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 #11
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 #12
0
app.post('/login',function(req,res)
{
var username=req.body.username;
   var password=req.body.password;
   console.log(password);
   pool.query('SELECT * FROM "hashingdemo" WHERE username=$1',[username],function(err,result){
       if(err)
       {
           res.status(500).send(err.toString());
       }
       else
       {
           if(result.rows.length===0)
           {
               res.status(403).send('username/password invalid');
           }
           else
           {
               var dbString=result.rows[0].password;
               var salt=dbString.split('$')[2];
               var hashedPassword=hash(password,salt);
               if(hashedPassword===dbString)
               {
                   req.session.auth={userId:result.rows[0].id};
                   res.send('credentials correct');
               }
               else
               {
                   res.status(403).send('uname/pwd invalid');
               }
           }
       }
   });
});
Example #13
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 #14
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 #15
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 #16
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();
      }
    });
  });
};
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");
        });
    });
}); 
 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 #19
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;
			}
		});
	});
});
Example #20
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 #21
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 #22
0
router.get('/criteria', function(req, res) {
  // This is the first route that get called by the Front app to get the structure needed to display stuff.
  pool.query('SELECT * FROM public.criteria', function(err, result) {
    if (err) {return res.json(err);}
    res.json(result.rows);
  });
});
Example #23
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 #24
0
router.get('/result-per-dates', function(req, res, next) {
  pool.query('SELECT * FROM public.result-per-dates', function(err, result) {
    // handle an error from the query
    if(err) {return res.json(err);}
    res.json(result.rows);
  });
});
Example #25
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 #26
0
router.get('/top-failling-img', function(req, res, next) {
    pool.query('SELECT * FROM public.top-failling-img', function(err, result) {
      // handle an error from the query
      if(err) {return res.json(err);}
      res.json(result.rows);
    });
});
Example #27
0
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",
      "take1",
      null,
      null
    ];

      pool.query(text, values)
      .then((res) => {
        pool.end();
        const rows = res.rows;
        return res.status(201).send(rows[0]);
      })
      .catch((err) => {
        pool.end();
        return res.status(400).send(err);
      })
      
});
Example #28
0
router.get('/passfailresult', function(req, res, next) {
    pool.query('SELECT * FROM public.passfailresultcount', function(err, result) {
      // handle an error from the query
      if(err) {return res.json(err);}
      res.json(result.rows);
    });
});
Example #29
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 #30
0
app.post('/submit-comment/:articleName', function (req, res) {
   // Check if the user is logged in
    if (req.session && req.session.auth && req.session.auth.userId) {
        // First check if the article exists and get the article-id
        pool.query('SELECT * from article where title = $1', [req.params.articleName], function (err, result) {
            if (err) {
                res.status(500).send(err.toString());
            } else {
                if (result.rows.length === 0) {
                    res.status(400).send('Article not found');
                } else {
                    var articleId = result.rows[0].id;
                    // Now insert the right comment for this article
                    pool.query(
                        "INSERT INTO comment (comment, article_id, user_id) VALUES ($1, $2, $3)",
                        [req.body.comment, articleId, req.session.auth.userId],
                        function (err, result) {
                            if (err) {
                                res.status(500).send(err.toString());
                            } else {
                                res.status(200).send('Comment inserted!')
                            }
                        });
                }
            }
       });     
    } else {
        res.status(403).send('Only logged in users can comment');
    }
});