Reputation: 3081
I am creating some test AWS Lambda functions and I am using the npm mysql package to connect to the RDS database. I have the following code, which DOES work. However, every other hit to the function results in an error.
Code:
exports.handler = (event, context, callback) => {
connection.query("SELECT * FROM `cubes`", function (error, results, fields) {
if (error) {
connection.destroy();
throw error;
} else {
// connected!
console.log(results);
callback(null, results);
connection.end(function (err) { callback(err, results);});
}
return context.logStreamName
});
};
Error:
{"errorType":"Error","errorMessage":"Cannot enqueue Query after invoking quit.","trace":> ["Error: Cannot enqueue Query after invoking quit."," at Protocol._validateEnqueue (/var/task/node_modules/mysql/lib/protocol/Protocol.js:215:16)"," at Protocol._enqueue (/var/task/node_modules/mysql/lib/protocol/Protocol.js:138:13)"," at Connection.query (/var/task/node_modules/mysql/lib/Connection.js:201:25)"," at Runtime.exports.handler (/var/task/index.js:10:16)"," at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"]}
I have been looking around for a solution for this but haven't found one that works. I have even tried commented out the connection.end()
piece, but then the function just times out entirely. Based on posts such as https://stackoverflow.com/a/15267082/1015214, it would seem that simply having connection.end() anywhere in the code should be fine, since it always gets fired at the end anyways, but perhaps something is different with the AWS Lambda setup?...
Upvotes: 1
Views: 1159
Reputation: 409
I had this exact issue. I was creating my connection var connection = mysql.createConnection({ ... });
outside of the exports.handler
function. According to https://gitmemory.com/issue/mysqljs/mysql/1296/491553221. The global variable remains across all lambda executions. Therefore I moved the connection creation inside the exports.handler
function and problem solved. I am novice to lambda however, so there could be a better implementation.
Upvotes: 1