how to use mysq transaction commit rollback in Lambda function using nodeJs - mysql

Hi i want to use Mysql's beginTransactio or transactio commit rollback functionality in my Lambda(Node) function.
I tried basic structure of mysql package but seems its not working in lambda
const mysql = require('mysql');
exports.handler = async (event) => {
const con = mysql.createConnection(
{
host: "host",
user: "user",
password: "*****",
database: "db"
}
);
con.beginTransaction(
function (err) {
con.query(
"query goes here",
function (err, status) {
if (err) {
con.rollback();
con.end();
return err;
} else {
con.commit();
con.end();
return true;
}
})
});
}

sorry for the delayed answer.
just needed to specify beginTransaction without callback
const mysql = require('mysql');
exports.handler = async (event) => {
const con = mysql.createConnection(
{
host: "host",
user: "user",
password: "*****",
database: "db"
}
);
con.beginTransaction(); //here i was declaring standard callback function with err parameter
con.query(
"query goes here",
function (err, status) {
if (err) {
con.rollback();
con.end();
return err;
} else {
con.commit();
con.end();
return true;
}
});
}

Related

How to make return wait for MySQL connection to end? Node.js

I'm new to Node.js I'm testing some code on Wix to check my database if a account name already exists prior to allowing a new one to be created (I'm purposely not using the WHERE tag at the moment for learning purposes).
Currently the method check account name returns before the connection finishes, not allowing the check to take place properly.
Any help appreciated.
export function tryToCreateAccount(login, password)
{
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'host',
user: 'user',
password: 'pass',
database: 'db'
});
if(checkAccountName(login, connection))
{
console.log("Name didn't exist.");
}
else
{
console.log("Name Existed.");
}
}
function checkAccountName(account_name, connection)
{
var accountNameAvailable = true;
connection.connect(function (err)
{
if(err) throw err;
connection.query("SELECT login FROM accounts", function (err, result)
{
if (err) throw err;
for(var i = 0; i < result.length ; i++)
{
if(result[i].login == account_name)
{
console.log("Should of been false");
connection.end;
accountNameAvailable = false;
}
}
});
connection.end;
});
return accountNameAvailable;
}
I figured out why it wasn't doing anything, the next was getting called too late since the connection ended and next was within the connection code block.
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'host',
user: 'user',
password: 'pass',
database: 'db'
});
export function tryToCreateAccount(login, password)
{
checkAccountName(login, connection, function(err, accountNameAvailable)
{
if(err || !accountNameAvailable){
console.log("Name didn't exist.");
}
else
{
console.log("Name Existed.");
}
})
}
function checkAccountName(login, connection, next)
{
var accountNameAvailable = false;
connection.connect(function (err)
{
if(err) next(err);
connection.query("SELECT login FROM accounts", function (err, result){
if (err) next(err);
for(var i = 0; i < result.length ; i++)
{
if(result[i].login == login)
{
accountNameAvailable = true;
}
}
next(null, accountNameAvailable);
connection.end();
});
});
}
Welcome to Node.js (and the world of Async functions (and Promises (and Callbacks)))
I've written this in the "callback" style, but I highly recommend looking into async/await for something like this, as well as understanding how "promises" fit into the picture.
// to test, call tryToCreateAccount('login','pass',function(err,data){console.log(err,data)});
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'host',
user: 'user',
password: 'pass',
database: 'db'
});
export function tryToCreateAccount(login, password, next)
{
checkAccountName(login, connection, function(err, accountNameAvailable){
if(err || !accountNameAvailable){
console.log("Name didn't exist.");
next(err || 'Name didn't exist.')
}
else
{
console.log("Name Existed.");
next(null, true)
}
})
}
function checkAccountName(account_name, connection, next)
{
var accountNameAvailable = false;
connection.connect(function (err)
{
if(err) next(err);
connection.query("SELECT login FROM accounts", function (err, result){
if (err) next(err);
for(var i = 0; i < result.length ; i++)
{
if(result[i].login == account_name)
{
console.log("Should of been false");
connection.end;
accountNameAvailable = true;
}
}
connection.end();
next(null, accountNameAvailable);
});
});
}

How to make a function to query MySQL in NodeJS?

I made this:
const mysql = require('mysql2/promise')
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'nodejs',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
})
async function query(query) {
const result = await pool.query(query)
return result[0]
}
console.log(query('SELECT * FROM `users`'))
and I got back
Promise { <pending> }
How do I get back my results from querying the database, just like PHP can do?
In PHP I never had to do such a thing like async/await and promises...
I also tried using mysql:
const mysql = require('mysql')
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'nodejs'
})
function query(query) {
db.query(query, (err, result) => {
if (err) throw err
return result
})
}
console.log(query('SELECT * FROM `users`'))
but I got an undefined result
try this:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
// function definition
function runQuery (con, sqlQuery) {
return new Promise((resolve, reject) => {
console.log("START");
if(con){
con.connect(function (err) {
if (err) throw err;
});
if (sqlQuery) {
con.query(sqlQuery, function (error, result, fields) {
connection.end(); // end connection
if (error) {
throw error;
} else {
return resolve(result);
}
});
} else {
connection.end(); // end connection
// code: handle the case
}
} else {
// code: handle the case
}
});
}
var sqlQuery = 'SELECT * FROM tableName';
// function call and pass the connection and sql query you want to execute
var p = runQuery(con, sqlQuery);
p.then((data)=>{ // promise and callback function
console.log('data :', data); // result
console.log("END");
});
I am not very familiar with MySQL and the libraries that you are using.
However, the Promise { <pending> } response that you are getting is because you didn't await your query execution.
Since the function is marked as async and is also performing an async action, it returns a Promise that needs to be awaited to be resolved.
The code below should work:
const mysql = require('mysql2/promise')
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'nodejs',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
})
async function query(query) {
const result = await pool.query(query)
return result[0]
}
(async () => {
const queryResult = await query('SELECT * FROM `users`');
console.log(queryResult);
} )();
To understand how async-await works, consider the code below:
console.log('I will get printed first');
const asyncFunction = async () => {
await setTimeout(()=> {}, 1000)
console.log('I will get printed third');
return 'hello'
}
(async () => {
const result = await asyncFunction();
console.log(`I will get printed last with result: ${result}`);
})();
console.log('I will get printed second');
The console.log statement I will get printed last with result will wait for the asyncFunction to complete execution before getting executed.
Try this:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});

Node exports MySQL Pool Cluster

I'm new to node and I'm trying to use a MySQL pool cluster in but I'm not exactly sure how to export it.
At the moment I have the following in /libs/mysql.js:
poolCluster.add('db1', {
host: config.databases.hostname,
user: config.databases.db1.username,
password: config.databases.db1.password,
database: config.databases.db1.database,
connectionLimit: config.databases.connectionLimit
});
poolCluster.add('db2', {
host: config.databases.hostname,
user: config.databases.db2.username,
password: config.databases.db2.password,
database: config.databases.db2.database,
connectionLimit: config.databases.connectionLimit
});
module.exports = {
getConnection: (callback) => {
return poolCluster.getConnection(callback);
}
};
I'm trying to use it in models/monitor.js as below:
let poolCluster = require('../libs/mysql');
let moment = require('moment');
exports.select = function (sql, values, callback) {
poolCluster.getConnection('db1', (err, connection) => {
if (err) {
callback(err);
} else {
connection.query(sql, values, (err, result) => {
connection.release();
if (err) {
console.log(err);
callback(err);
} else {
callback(null, result)
}
})
}
})
};
The issue now is I'm getting an error stating cb is not a function.
Is this the correct way to export a mysql pool cluster in node?
You are exporting as getConnection: (callback) => {} but you are calling the same function with getConnection(string, callback).
According to the doc:
You can call getConnection like:
// Target Group : ALL(anonymous, MASTER, SLAVE1-2), Selector : round-robin(default)
poolCluster.getConnection(function (err, connection) {});
// Target Group : MASTER, Selector : round-robin
poolCluster.getConnection('MASTER', function (err, connection) {});
So, basically you need to pass the arguments you are getting from YOUR getConnection function to mysql's getConnection function. So this should do the trick:
module.exports = {
getConnection: (...args) => {
return poolCluster.getConnection(...args);
}
};

Make synchronous MySQL queries in NodeJS

I have been doing google searches for 5 days, I hope to find the solution ... I know that it does not work because it is asynchronous, but I need the program (it is a Discord bot) to respond with a data that I get from a DB. I have tried Promises and callbacks, but I do not know if it is because I am a novice with asynchronous, that nothing works for me.
const con = mysql.createConnection({
host: datos.host,
user: datos.user,
password: datos.password,
database: datos.database
});
function leerPromesa() {
var promise = new Promise(function (resolve, reject) {
con.query('SELECT * from ranking;', function (err, rows, fields) {
if (err) {
reject(err);
return
}
resolve(rows);
rows.forEach(element => console.log(element));
})
});
return promise;
};
var promesa = leerPromesa();
promesa.then(
function (rows) {
rows.forEach(element => msg.reply(element));
},
function (err) {
msg.reply(err);
}
);
con.end();
What the bot does is respond with blank text.
First, you're not really connecting to database.
If you refer to docs https://github.com/mysqljs/mysql:
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
// then connect method
connection.connect();
So your code will never work..
Second, you are closing connection before any query execution:
con.end();
Correct is to close connection after leerPromesa function execution.
Finally, code could look something like this:
const con = mysql.createConnection({
host: datos.host,
user: datos.user,
password: datos.password,
database: datos.database
});
con.connect();
function leerPromesa() {
return new Promise(function(resolve, reject) {
con.query("SELECT * from ranking;", function(err, rows, fields) {
if (err) {
return reject(err);
}
return resolve(rows);
});
});
}
leerPromesa()
.then(
function(rows) {
rows.forEach(element => msg.reply(element));
},
function(err) {
msg.reply(err);
}
)
.finally(function() {
con.end();
});
I used finally method on Promise to close connection in every situation https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally

Unable to make persistent mysql connection in node

I have a node mysql connection that used to work properly but since traffic started coming i am getting a strange error
Error: Connection lost: The server closed the connection.
This is the class that i'm using
const mysql = require('mysql');
class Database {
constructor() {
this.connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: 3306,
debug: false,
multipleStatements: false
});
}
query(sql, args) {
return new Promise((resolve, reject) => {
this.connection.query(sql, args, (err, rows) => {
if (err)
return reject(err);
resolve(rows);
});
});
}
close() {
return new Promise((resolve, reject) => {
this.connection.end(err => {
if (err)
return reject(err);
resolve();
});
});
}
}
module.exports = Database;
Can someone help as to why this is happening?
Edit: this is how i call the code
const database = new Database();
database.query(`select * from users...
`, [req.user.id, parseInt(req.body.after)])
.then(rows => {
appData[".."] = rows['ddd']
res.status(200).json(appData);
database.close()
}, err => {
return database.close().then(() => { throw err; })
})
.catch(err => {
console.log(err);
res.status(500).json("Database Error");
})
first create file ex database.js
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 10,
host: conf_core_sys.dbConfig.host,
user: conf_core_sys.dbConfig.user,
dateStrings: true,
password: conf_core_sys.dbConfig.pass,
database: conf_core_sys.dbConfig.dbName,
port:conf_core_sys.dbConfig.port,
debug: false
});
module.exports = pool;
exports.executeQuery = function (query, callback) {
pool.getConnection(function (err, connection) {
if (err) {
connection.release();
throw err;
}
connection.query(query, function (err, rows) {
connection.release();
if (!err) {
callback(null, {
rows: rows
});
}
});
connection.on('error', function (err) {
throw err;
return;
});
});
}
second step :
let database = require("database")
let sql ="SELECT * from users";
database.query(sql, function (error, results, fields) {
if (error) {
callback(results)
} else {
callback(results)
}
})
some time ago i had the same problem, but at this time the probelm has not happened, maybe this solution helping you,
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 10,
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: 3306,
debug: false,
multipleStatements: false
});
module.exports = pool;
exports.executeQuery = function (query, callback) {
pool.getConnection(function (err, connection) {
if (err) {
connection.release();
throw err;
}
connection.query(query, function (err, rows) {
connection.release();
if (!err) {
callback(null, {
rows: rows
});
}
});
connection.on('error', function (err) {
throw err;
return;
});
});
}