Search code examples
amazon-web-servicesaws-lambdamysql-workbenchdatabase-triggeramazon-aurora

Lambda function access by RDS trigger creates connection lost


I created 2 tables in RDS aurora:

  1. test-table in aurora db with values id(PK), tasknumber, status , contactid(FK)
  2. contact-table in same db with values contactid(PK), email, phone

I created a trigger in 'test-table' that whenever a 'status' changes, the trigger should call AWS-Lambda ARN.

The Lambda function and Aurora has all the permissions, and security cleared, still on testing from Lambda I get below image error and on updating the 'status' field manually in aurora(via Workbench Sql query) it shows:

Operation failed: There was an error while applying the SQL script to the database.

ERROR 2013: 2013: Lost connection to MySQL server during query

I have attached my Lambda Node.Js code too.

var AWS = require('aws-sdk');
AWS.config.update({ region: 'us-east-1' });
const mysql = require('mysql');

var con = mysql.createConnection({

  host: 'correct value',
  user: 'root',
  password: 'correct value',
  port: correct value,
  database: 'correct value'

});
exports.handler = (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;
  var fk = event.contact_id;
  console.log('FOREIGN KEY=', fk)

  con.connect(function(err) {
    if (err) throw err;
    var sql = `SELECT * FROM db.contacts where contact_id=${fk}`

    con.query(sql, function(err, result) {
     if (err) throw err;
     var email = result[0].email;
     console.log(email);

     var sns = new AWS.SNS();
    var params = {
     Message: email,
      Subject: "Test SNS From Lambda",
     TopicArn: "arn:correct value"
   };

      sns.publish(params, function(err, data) {
        if (err) console.log(err, err.stack); 
        else {
          console.log(data);
          callback(null, 'Success');
        }
      });

    });
  });
};

Also followed for NodeJs package: https://github.com/isaacs


Solution

  • you have to close the connection if you want the instant response otherwise it will take the default time to close the connection, please let me know if makes sense