Search code examples
javascriptnode.jspostgresqlnode-postgres

Why is my query working on pgAdming but when I execute it from the server I get a query error (Error: Connection Terminated)?


I'm working on my Capstone project and it requires to store some telemetry data on a database. I'm using PostgreSQL 9.5 for the database and node for the server.

My problem is that when I try to send a query from the server I'm getting a query error [Error: Connection Terminated]. If I use JSON.stringify(err) I only see empty brackets as the result {}. What is interesting is that if I use pgAdmin client and execute the same query, the record is added successfully without any kind on error.

Here is the code I'm using in the server to send the query:

client.connect(function(err) {
    if(err){
        return console.error('could not connect to postgres', err);
    }

    //Checks if there is survey data to process
    if(surveyFlag){

        //Query to insert survey record
        //Returns survey record's auto-generated id to use it when creating or updating the             //telemetry record in the database 
        var query = 'INSERT INTO survey_response (perceived_risk, actual_risk) '+
                    'VALUES (' + telemetryRecord.survey.perceivedRisk +', ' +                   
                                 telemetryRecord.survey.actualRisk +') ' +
                    'RETURNING survey_id';

        client.query(query, function(err, result) {

        console.log("Query: " + query);

                if(err) {
                    console.log(err);
                    return console.error('error running survey query', err);
                }

                surveyID = result.rows[0].survey_id;    

                //Testing
                console.log ("Survey response added with ID: " + surveyID);


        });

            //Close the connection  
        client.end();
});

Solution

  • The code client.end() is put at the same level of the code client.query(). Since client.query() is asynchronous, the client.end() gets called immediately after you start the query. By the time the query comes back the client has already ended which is causing the problem.

    Try placing the client.end() code within the callback function of client.query().

    client.query(query, function(err, result) {
      console.log("Query: " + query);
    
      if(err) {
        console.log(err);
        return console.error('error running survey query', err);
      }
    
      surveyID = result.rows[0].survey_id;    
    
      //Testing
      console.log ("Survey response added with ID: " + surveyID);
    
      //Close the connection  
      client.end();
    
    });