0

I am using Heroku Postgres and every time I run a query in my application the connection remains open. This leads to too many simultaneous connections and hence errors.

When in deployment, after I use my application for a bit I get this error:

{"name":"error","length":109,"severity":"FATAL","code":"53300","file":"miscinit.c","line":"551","routine":"InitializeSessionUserId"} 

When I am running locally I get this error:

{"name":"error","length":109,"severity":"FATAL","code":"53300","file":"miscinit.c","line":"551","routine":"InitializeSessionUserId"}

This is the way I am handle queries every time I need to query the database:

router.route('/campaigns')
    .get(restrictTo('advertiser'), function(req, res) {
        pg.defaults.ssl = true;
        pg.connect(`DATABASE_URL`, function(err, client, done) {
            if (err) {
                console.log('Connection issue when retrieving data, error will be thrown: ' + JSON.stringify(err));
                throw err;
            } else {
                client.query(`SELECT * FROM campaign WHERE agentid = ${req.user.agentid};`,
                    function (err, result) {
                        if(err)
                            console.log(err.toString());
                        res.render('console/campaigns', result);
                    });
            }

        })
    })

I am doing something wrong because the connections are not closing I believe. How can I solve it?

ocram
  • 1,384
  • 6
  • 20
  • 36
  • If you use [pg-promise](https://github.com/vitaly-t/pg-promise), you will never have this kind of problem, because you won't need to do a manual connection at all. – vitaly-t Jul 23 '16 at 17:58
  • yes that's what i did but it took me a full day before I figured this out. – ocram Jul 23 '16 at 19:04
  • @vitaly-t I would have a question on `pg-promise`: http://stackoverflow.com/questions/38545958/return-in-pg-promise – ocram Jul 23 '16 at 20:05

1 Answers1

0

I think you're supposed to use client.end(); after each query is done to close the connection.

Mankind1023
  • 7,198
  • 16
  • 56
  • 86