Select For Update query from Node JS - sql

Currently i use below code to select details from SQL for my Node JS server. Now i have a requirement where i want to use 'SELECT FOR UPDATE' and i am sure how to proceed with that?
pool.connect((err, db) => {
if(err) {
console.log("Failed connection to mysql");
errHandler(err);
}
let sql1 = 'select * from user where email = ? and role_number = ? ';
db.query( sql1 , [ email, role ], (err, result) => {
if(err) {
console.log("Error in checking existing email");
errHandler(err);
}
else {
console.log(result);
if( result.length > 0 ) {

Related

Insert session data into postgres database in Nodejs Expess app

I have an Nodejs express function where I am trying to insert data that is stored in the browser session into my postgres database. When I have the insert statement like this, the insert works but the session-stored customer_id isn't inserted and is just left null.
On the line with "var sql = INSERT INTO journal....", the values $1 and $2 are from user input and work correctly.
How can I get value 3 of the customer_id stored in the session to insert correctly? I would appreciate any advice or greater understanding.
app.post("/addJournalEntry", addJournalEntry);
function addJournalEntry(req, res) {
console.log("Posting data");
// var id = req.query.id;
//body is for post, query is for get
const customer_id = req.session.customer_id;
const journal_entry_date = req.body.journal_entry_date;
const journal_entry = req.body.journal_entry;
const params = [journal_entry, journal_entry_date, customer_id];
addEntryFromDataLayer(params, function (error, addEntry) {
console.log("Back From the addEntryFromDataLayer:", addEntry);
if (error || addEntry == null) {
res.status(500).json({
success: false,
data: error
});
}
else {
// res.json(result);
res.status(200).json(addEntry);
}
});
}
function addEntryFromDataLayer(params, callback) {
console.log("addEntryFromDataLayer called with id");
var sql = "INSERT INTO journal (journal_entry, journal_entry_date, customer_id) VALUES($1::text, $2::text, $3)";
// var params = [id];
pool.query(sql, params, function (err, addEntry) {
if (err) {
console.log("error in database connection");
console.log(err);
callback(err, null);
}
console.log("Found DB result:" + JSON.stringify(addEntry));
callback(null, addEntry);
});
}

getting blank array when consoled logged out results in nodejs mysql

I have this code where I want to check for existing email but I am not able to get the array of all the data containing matched row by SQL.
var email = req.body.email;
var fullname = req.body.fullname;
var userPassword = req.body.userPassword
const saltRounds = 10
let sql = 'SELECT * FROM registeredusers WHERE id = ?'
pool.query(sql, email, (err, results) => {
console.log(JSON.stringify(results))
if (err) {
return res.status(500).json({
message: 'Internal server error. Retry... '
})
}
else if (results === 1) {
return res.status(500).json({
message: 'Email already exist.',
res: results
})
}
just use
let sql = 'SELECT COUNT(*) AS cnt FROM registeredusers WHERE email = ?'
pool.query(sql, [req.body.email], (err, results) => {
if (err) {
return res.status(500).json({
message: 'Internal server error. Retry... '
})
}
else if (results[0].cnt > 0) {
return res.status(500).json({
message: 'Email already exist.',
})
}

Reading from one db into another

I am trying to right a function that copies some fields from several company databases into my own database once a day. What I have so far is below. I am wondering if where I console.log(rs) I can open another sql connection to my database and write the data or if I have to store the results somewhere and then open a new connection and send the stored results.
function updateJobs() {
var query = "SELECT JobStart, JobEnd FROM JobData";
sql.connect(Config, (err) => {
if (err) {
console.log("Error while connecting database :- " + err);
} else {
var request = new sql.Request();
request.query(query, function (err, rs) {
if (err) {
console.log("Error while querying database :- " + err);
sql.close();
} else {
console.log(rs);
sql.close();
}
})
}
})
}
This might help
// Source Database
sourceDB.each(`select * from ${Sourcetable}`, (error, row) => {
console.log(row);
const keys = Object.keys(row); // ['columnA', 'columnB']
const columns = keys.toString(); // 'columnA,columnB'
let parameters = {};
let values = '';
// Generate values and named parameters
Object.keys(row).forEach((r) => {
var key = '$' + r;
// Generates '$columnA,$columnB'
values = values.concat(',', key);
// Generates { $columnA: 'ABC', $columnB: 'GHK' }
parameters[key] = row[r];
});
// Insert into another database into OneTable (columnA,columnB) values ($columnA,$columnB)
// Parameters: { $columnA: 'ABC', $columnB: 'GHK' }
destDB.run(`insert into ${Desttable} (${columns}) values (${values})`, parameters);
})
})

Filter sql request with WHERE and ORDER express js API

I don't know why this syntax doesn't work, I just want to get back my data throw this little API;
when I delete the 'ORDER by points DESC', it works.
This is the code :
.get((req, res) => {
if (req.query.max != undefined && req.query.max > 0){
db.query('SELECT * FROM rank WHERE id_championship = ?', [req.params.id] 'ORDER by points DESC', (err, result) => {
if(err){
res.json(error(err.message))
}
else{
res.json(success(result.slice(0, req.query.max)))
}
})
}
Thanks for your help !
I have tried to do it like this but it still not working...
sql = "SELECT * FROM rank WHERE id_championship = " + req.params.id + "ORDER BY id DESC";
db.query(sql, (err, result) => {
if(err){
res.json(error('Fail database connection'))
}
else{
res.json(success(result))
}
})

SQL tedious add array as parameter

I'm running this SQL query with tedious.js using parameters:
var query = "select * from table_name where id in (#ids)";
request = new sql.Request(query, function(err, rowCount) {
if (err) {
}
});
request.on('row', function(columns) {
});
var id = [1, 2, 3];
request.addParameters('ids', TYPES.Int, id);
connection.execSql(request);
because I am looking for items that matches the ID provided with where ... in ... clause, I need to pass in an array. However, there is no TYPES.Array. How do I this properly?
for this query, i think you'll just have to manually build the entire sql string. the TYPES enum values are for the datatypes in the database, not in your JavaScript code.
//you can like this:
var userIds = result.map(function (el) {
return el.UserId;
}).join(',');
var params = [{
name: 'userIds',
type: TYPES.VarChar,
value: userIds,
options: null}];
var querySql = ['SELECT COUNT([MomentId]) FROM [T_Moment]',
'WHERE [RecordStatus] = ', sysConst.recordStatus.activation, " AND CHARINDEX(','+RTRIM([UserId])+',' , ','+ #userIds +',')>0 "].join(' ');
dbHelper.count(querySql, params, function (err, result) {
if (err) {
callback('error--');
} else {
callback(null, result);
}
});
Try creating the in clause parameters for query dynamically.
// create connection
let ids = [1, 2, 3];
let inClauseParamters = createInClauseParameters();
let query = `select * from table_name where id in (${inClauseParamters})`;
let request = new Request(query, (err, rowCount) => {
if (err) { /* handle error */ }
});
request.on('row', (columns) => { /* get row */});
request = addRequestParameters(ids, request);
connection.execSql(request);
function createInClauseParameters(values) {
return values.map((val, index) => `#Value${index}`).join(',');
}
function addRequestParameters(values, request) {
values.forEach((val, index) => {
request.addParameter(`Value${index}`, TYPES.VarChar, val);
});
return request;
}