How to eliminate all queries if one failed - mysql

app.post('/transfer', (req,res) => {
db.query('SELECT * FROM bank.user_info where acc_no = ?',
[req.body.from],(err, result) => {
if(err){
res.send({err: err,id: 0});
}else{
if(req.body.Amount>result[0].acc_bal){
res.send({err: "Insufficient Balance !!!",id: 1})
return 0;
}else{
const senderNew = {};
senderNew.amount = req.body.Amount;
senderNew.transaction = 'sent';
senderOld.push(senderNew);
const freshSend = JSON.stringify(senderOld);
const senderBal = result[0].acc_bal-req.body.Amount;
db.query('UPDATE user_info SET transactions = ?, acc_bal = ? WHERE acc_no = ?',
[freshSend, senderBal, req.body.from], (err,result) => {
if(err){
res.send({err: err,id: 2})
}else{
db.query('SELECT * from user_info WHERE acc_no = ?',
[req.body.to], (err, result) => {
if(err){
res.send({err: err,id: 3});
}else{
const receiverOld = JSON.parse(result[0].transactions);
const receiverNew = {};
receiverNew.amount = req.body.Amount;
receiverNew.transaction = 'received';
receiverOld.push(receiverNew);
const freshReceive = JSON.stringify(receiverOld);
const receiverBal = parseInt(result[0].acc_bal) + req.body.Amount;
db.query('UPDATE user_info SET transactions = ?, acc_bal = ? WHERE acc_no = ?',
[freshReceive, receiverBal, req.body.to], (err, result) => {
if(err){
res.send({err: err,id: 4});
}else{
db.query('SELECT * FROM user_info WHERE acc_no = ?',
[req.body.from], (err, final) => {
if(err){
res.send({err: err, id: 5});
}else{
res.send(final);
console.log(final);
}
})
}
})
}
})
}
})
}
}
})
});
Now in this code, if the initial block fails, the others don't execute but if the last ones fail, the initial block still gets passed, how can I improve the code so that if any query fails, the ithers fail too...
I've checked this but it didn't helped as I need a Node.js tutorial
How to stop all DB queries if one fails

Related

Increment a value on MYSQL with react node.js

Why does this doesn't work
const increment = 'votes + 1'
db.query("UPDATE president SET votes = ? WHERE nickname = ?",
[increment, president], (err, result) => {
if (err) {
console.log(err)
} else {
console.log(result)
}
})
but this code below works
db.query("UPDATE president SET votes = votes + 1 WHERE nickname = ?",
[president], (err, result) => {
if (err) {
console.log(err)
} else {
console.log(result)
}
})
I just want to do the incrementing of mysql columns with votes = ?
I wanted to do it with the votes = ? way. Does anyone know the proper syntax of incrementing a value in mysql with react node js?

Max Users Connections problem with express js server & Mysql database on o2switch withtout privilege

I made a application , i need just to do 1 big query in database / minute.
I dont know if my code is not optimized or if i have a problem with server configuration.
Anyone can help me ?
here my index.js express server :
const app = express();
const fileUpload = require('express-fileupload');
const morgan = require('morgan');
const compression = require('compression');
const cors = require('cors');
const _ = require('lodash');
const programmingLanguagesRouter = require("./routes/programmingLanguages");
const usersRouter = require("./routes/users")
const fileRouter = require("./routes/file")
const findville = require("./routes/findville")
const promotion = require("./routes/promotion");
const config = require("./routes/config");
app.use(express.static('uploads'));
app.use(compression());
app.use(cors({
origin: "*",
credentials: true,
}))
app.use(fileUpload({
createParentPath: true
}));
app.use(morgan('tiny'));
app.use(express.json())
app.use(
express.urlencoded({
extended: true,
})
);
app.get("/", (req, res) => {
res.json({ message: "ok o2switch" })
})
app.use("/config", config)
app.use('/static', express.static('uploads'));
app.use("/programming-languages", programmingLanguagesRouter)
app.use("/users", usersRouter)
app.use("/file", fileRouter)
app.use("/ville", findville)
app.use("/promotion", promotion)
app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500
console.error('Mon message', err.message, err.stack);
res.status(statusCode).json({ 'message': err.message })
return
})
app.listen(() => console.log('Server is running !'));```
**My principal query route:**
router.get('/getallcouvbyeta/', async function(req, res, next) {
try {
res.json(await promotion.getallcouvbyeta(req.body))
next()
} catch (err) {
console.error(`Error 500`, err.message)
next(err)
}
});
**And the query service:**
async function getallcouvbyeta(info){
const eta0 = await db.query(
`SELECT * FROM users CROSS JOIN couvertures on users.JWT = couvertures.client_api_key WHERE couvertures.eta=0`
);
const awaited = helper.emptyOrRows(eta0)
const eta1 = await db.query(
`SELECT * FROM users CROSS JOIN couvertures on users.JWT = couvertures.client_api_key WHERE couvertures.eta=1`
);
const done = helper.emptyOrRows(eta1)
const eta2 = await db.query(
`SELECT * FROM users CROSS JOIN couvertures on users.JWT = couvertures.client_api_key WHERE couvertures.eta=2`
);
const refused = helper.emptyOrRows(eta2)
const eta4 = await db.query(
`SELECT * FROM users CROSS JOIN couvertures on users.JWT = couvertures.client_api_key WHERE couvertures.eta=4`
);
const solded = helper.emptyOrRows(eta4)
const userlist = await db.query(
`SELECT users.*, (SELECT COUNT(*) FROM couvertures WHERE couvertures.client_api_key = users.JWT AND couvertures.notified = false) AS Total, (SELECT COUNT(*) FROM couvertures WHERE couvertures.client_api_key = users.JWT AND couvertures.eta = 0) AS attente FROM users WHERE role!="super" `
);
const users = helper.emptyOrRows(userlist)
const alert = await db.query(
`SELECT * FROM couvertures INNER JOIN users on couvertures.client_api_key = users.JWT where couvertures.new_counter=false AND couvertures.notified=false OR couvertures.notified=false AND livraison_estime < NOW() + INTERVAL 2 DAY AND livraison_estime > NOW() OR couvertures.notified=false AND couvertures.new=true`
);
const alertArray = helper.emptyOrRows(alert)
const closes = await db.query(
`SELECT * FROM couvertures INNER JOIN users on couvertures.client_api_key = users.JWT where livraison_estime < NOW() + INTERVAL 2 DAY AND livraison_estime > NOW()`
);
const closesArray = helper.emptyOrRows(closes)
return {
awaited, done, refused, solded, users, alertArray, closesArray
}
}
**VueJs Request (in vueX):**
export const actions = {
async updateData(context, data) {
let rnd = Math.floor(Math.random() * 5);
rnd === 0 ? (rnd = 1) : (rnd = rnd);
const ip = await this.$axios.$get(
`https://cover${rnd}.mywebsite.fr/promotion/getallcouvbyeta`
);
context.commit('refreshCovers', ip)
}
}
So i really dont understand why i have so much query after 4 requests i got the max user limit connections problem every time.
I dont have any privilege on db so i cant change variables .
I never found a solution for that problem. So i made 5 users and switch between them with 5 sub domain.. Is like barbare solution and it not work well .

How do I post data from form to a particular row?

My nodejs code...
app.post('/src/grades-form', function(req, res){
var daa = req.body.daa;
var os = req.body.os;
var dldm = req.body.dldm;
var ptrp = req.body.ptrp;
var bhr = req.body.bhr;
var prn = req.query.prn;
var sql = "INSERT INTO grades (daa, os, dldm, ptrp, bhr) VALUES ('"+daa+"','"+ os+"','"+ dldm+"','"+ ptrp+"','"+ bhr+"') WHERE prn = ?";
connection.query(sql, [prn], function(error, results){
if(error) throw error;
res.send(`Data stored successfully !!<br>Return to dashboard.`);
});
});
Error I'm getting...
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near 'WHERE prn = '1'' at line 1
How do I overcome it?
I will provide more info if this isn't sufficient... Thank you
What you could do is perform a SELECT to check if the row is present in the database, if so perform an update, otherwise insert a new row:
app.post('/src/grades-form', function (req, res) {
const { daa, os, dldm, ptrp, bhr } = req.body;
var prn = req.query.prn;
const sqlSelect = 'SELECT * FROM grades WHERE prn = ?';
connection.query(sqlSelect, [prn], (err, result) => {
if (err) throw err;
if (result.length === 0) {
// Not found, insert new value
var sqlInsert =
'INSERT INTO grades (daa, os, dldm, ptrp, bhr) VALUES (?, ?, ?, ?, ?)';
connection.query(
sqlInsert,
[daa, os, dldm, ptrp, bhr],
function (error, results) {
if (error) throw error;
res.send(
`Data inserted successfully !!<br>Return to dashboard.`
);
}
);
} else {
// Value is present, update existing one
var sqlUpdate =
'UPDATE grades SET daa = ?, os = ?, dldm = ?, ptrp = ?, bhr = ? WHERE prn = ?';
connection.query(
sqlUpdate,
[daa, os, dldm, ptrp, bhr, prn],
function (error, results) {
if (error) throw error;
res.send(
`Data updated successfully !!<br>Return to dashboard.`
);
}
);
}
});
});
The INSERT INTO statement cannot have a WHERE clause.
If you're trying to update an existing row, use:
UPDATE grades SET daa=value, os=value, etc=value WHERE prn = 1

Getting a function out of a query

I'm trying to get a variable out of a query as shown below, thanks in advance
var deutsch_meund_note = "";
connection.query(
'SELECT count(*) as sum FROM noten WHERE id = ? and fach = ?',
[id, "mathe"],
function(error, results, fields) {
if (error) {
console.log("no deutsch_schr for id: "+ id);
} else {
const deutsch_meund_viel = results[0].sum;
connection.query(
'SELECT SUM(note) as sum FROM noten WHERE id = ? and fach = ?',
[id, "deutsch_meund"],
function(error, results, fields) {
const deutsch_meund_insge = results[0].sum;
const deutsch_meund_note = deutsch_meund_insge / deutsch_meund_viel;
//this variable: **var deutsch_meund_note = deutsch_meund_note;**
});
}
});
I need to get the variable out of the "connection.query" function but when I try it like the example above it just says "undefined"

perform async multiple Mysql queries on Node

I'm using node with Mysql and here's my problem.
I'm trying to add new photos on my database and return it as an array
here is my function :
function addNewPhotos(_id, files) {
var deferred = Q.defer();
var new_photos = []
_.each(files, function (one) {
var data = [
one.path,
_id,
0
]
var sql = 'INSERT INTO photos(photo_link, id_user, isProfil) VALUES (?, ?, ?)';
db.connection.query(sql, data, function (err, result) {
if (err)
deferred.reject(err.name + ': ' + err.message);
var sql = 'SELECT id_user, photo_link, isProfil FROM `photos` WHERE id = ?';
if (result){
db.connection.query(sql, [result.insertId], function(err, photo) {
if (err) deferred.reject(err.name + ': ' + err.message);
if (photo) {
new_photos.push(photo[0]);
}
});
}
})
})
deferred.resolve(Array.prototype.slice.call(new_photos));
return deferred.promise}
The Insert works well but i can't retrieve the results to send them back to the client. (my array is empty)
Thanks.
Always promisify at the lowest level, in this case db.connection.query().
if(!db.connection.queryAsync) {
db.connection.queryAsync = function(sql, data) {
return Q.Promise(function(resolve, reject) { // or possibly Q.promise (with lower case p), depending on version
db.connection.query(sql, data, function(err, result) {
if(err) {
reject(err);
} else {
resolve(result);
}
});
});
};
}
Now the higher level code becomes very simple :
function addNewPhotos(_id, files) {
var sql_1 = 'INSERT INTO photos(photo_link, id_user, isProfil) VALUES (?, ?, ?)',
sql_2 = 'SELECT id_user, photo_link, isProfil FROM `photos` WHERE id = ?';
return Q.all(files.map(function(one) {
return db.connection.queryAsync(sql_1, [one.path, _id, 0]).then(function(result) {
return db.connection.queryAsync(sql_2, [result.insertId]);
});
}));
};
To prevent a single failure scuppering the whole thing, you might choose to catch individual errors and inject some kind of default ;
function addNewPhotos(_id, files) {
var sql_1 = 'INSERT INTO photos(photo_link, id_user, isProfil) VALUES (?, ?, ?)',
sql_2 = 'SELECT id_user, photo_link, isProfil FROM `photos` WHERE id = ?',
defaultPhoto = /* whatever you want as a default string/object in case of error */;
return Q.all(files.map(function(one) {
return db.connection.queryAsync(sql_1, [one.path, _id, 0]).then(function(result) {
return db.connection.queryAsync(sql_2, [result.insertId]);
}).catch(function() {
return defaultPhoto;
});
}));
};
Do the return in your async loop function when all has been done
function addNewPhotos(_id, files) {
var deferred = Q.defer();
var new_photos = [];
var todo = files.length;
var done = 0;
_.each(files, function (one) {
var data = [
one.path,
_id,
0
]
var sql = 'INSERT INTO photos(photo_link, id_user, isProfil) VALUES (?, ?, ?)';
db.connection.query(sql, data, function (err, result) {
if (err)
deferred.reject(err.name + ': ' + err.message);
var sql = 'SELECT id_user, photo_link, isProfil FROM `photos` WHERE id = ?';
if (result){
db.connection.query(sql, [result.insertId], function(err, photo) {
if (err) deferred.reject(err.name + ': ' + err.message);
if (photo) {
new_photos.push(photo[0]);
}
if(++done >= todo){
deferred.resolve(Array.prototype.slice.call(new_photos));
return deferred.promise
}
});
}
else
{
if(++done >= todo){
deferred.resolve(Array.prototype.slice.call(new_photos));
return deferred.promise;
}
}
})
})
}