Knex.js verifying query results in server side code - mysql

I have a function that is supposed to check if a license plate already exists in my MySQL database, but on the then-promise-return the result comes as:
result: [object Object]. How do you actually get the response of this knex query and parse it to check for a license plate existing?
var licensePlateExists = function(licensePlate){
knex.select('plate').from('licensePlates').where({'plate': licensePlate}).limit(1).then(function(result){
console.log("Result: " + result);
if(!result){
return true;
}
return false;
}).catch(function(error) {
console.error(error);
});
}
I think I might have an error related to the query itself, but I tested the raw query string in MySQL CLI and it outputs the row as expected. Maybe ordering matters in the knex query builder?
P.S. This doesn't error, it executes all the way through.

Try with
knex.select('plate').from('licensePlates').where('plate', licensePlate)
Actually using count query would be better

Related

Sequalize Insert query with transaction using multi threading in nodejs

I am facing an issue where I am getting frequent request and my code is getting struck for insert query..
Code is first checking whether records exists or not and as per output code is taking decision for insert OR update. But issue is this when my first request is coming it executes create query with transaction and later after 3-4 seconds that transaction is commit. But when second request is coming where first request is stll getting executed and checking if records exists then it is returning null due to which my code is again going into create whereas it should have gone in update case.
let data = await Model.findOne({
where: { code: variantCode }
});
if (!data) {
variant = await Model.create(body, {
transaction
});
} else {
await data.update(body);
}
I have already tried upsert, but that doesnt work.

How to build a dynamic SQL "WHERE" statement using a JSON input

I am trying to dynamically build my SQL statement using node. The where clause will be completely different for each of my cases.
const sql = `select columnName from tableName where ?`;
const whereClause = { "name": "Siri", "Age":20}
connection.query(sql, whereClause, (err, rows) { ... });
However, I keep getting SQL syntax error. The query node builds is select columnName from tableName where name = 'siri', age = 20. I figured the reason I get SQL syntax error is because the SQL statement is missing the AND part. I want to be able to construct the query by giving the JSON object for the where clause.
I don't want to build the query using string concatenation due to SQL injection risks. So, is there another way that I can build my SQL statement without manually adding the AND part?
I'm pretty sure you can't process column names like that. Write a helper function that processes the json object and escapes values.
function processValue(value) {
if(!isNaN(value)) {
return value;
}
if(typeof value === "string") {
return `"${mysql.escape(value)}"`;
}
throw new Error("Unsupported value type!");
}
function where(obj) {
return Object.entries(obj).reduce(function(statement, [key, value]) {
return statement.concat(["AND", key, "=", processValue(value)]);
}, []).slice(1).join(" ");
}
Your query now looks like this:
const sql = `select columnName from tableName where ?`;
connection.query(sql, where({ "name": "Siri", "Age":20 }), (err, rows) { ... });
On another note, just use an ORM or a query builder like Knex so that you don't have to do all this manually.

Passing variables through Node MySQL function

I've created a simple function that runs a query and fetches a field value from a MySQL database in Node. I'm using the normal 'mysql' library. For some reason though, I can't pass the resulting field value out to the function. What am I doing wrong?
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'mydb'
});
//This is my function to fetch the field
function getinfofromdb(inputID){
connection.query('SELECT * FROM `mytable` WHERE ? ORDER BY `ID` DESC LIMIT 1;', {identifierID: inputID}, function (err, rows, fields) {
if(rows[0]['filename'].length > 0){
console.log(rows[0]['filename']); // This works fine! I just can't pass it as response. :(
response = rows[0]['filename'];
}else{
response = 'none found';
}
});
return response;
}
//However, I always get that 'response' is undefined
console.log(getinfofromdb(1));
Furthermore, returning from the inner function also yields nothing.
There is no problem with the query, as I can console.log it just fine, but it just doesn't return it to the function.
if(rows[0]['filename']){
console.log(rows[0]['filename']); //This prints out just fine
return rows[0]['filename']; //Doesn't return anything
}
Update: Everything I'm trying is not yielding anything. Would someone please show me the proper way of writing a function in nodejs using the mysql library (https://github.com/mysqljs/mysql) that receives an input, runs a simple query using that input, and the value of a field in the response row? I'm going nuts.
I found the solution -- this is impossible to do.
Coming from a PHP background, not everything I'm used to write is asynchronous.
This Node JS MySQL library runs its queries asynchronously, and therefore the callback function cannot return anything. It just prints stuff such as console.log.
I guess I'm gonna revert to PHP.
How to return value from an asynchronous callback function?

nodejs blocking further mysql queries

I have a MySQL query that returns ~11,000 results that then need further queries run on each result. While the code is running it doesn't allow other users to log in to the website.
Potential problems I've seen are the use of callback functions or foreach loops but that doesn't seen to help.
code looks like this:
query(sql, params, function(err, result) {
result.foreach(
query(generate_sql(result), params, function(err, result) {
//do stuff
});
)
});
I recommend you using Promises
Then your code would be something like that:
var Promise = require('bluebird');
_query = Promise.promisify(query);
_query(sql, params)
.map(function(singleRow) {
// you get here every single row of your query
})
.then(function() {
// you are finished
});
Your problem is having that much queries. 11,001 query is a very large number, and I don't think that MySQL can handle that number of queries in parallel.
So another way is to use subqueries to handle your problem.

Breaking sql statement in Linq in 2 or more parts, depends on program condition

I'm a principiant of Linq so i need some help..
I don’t know if in Linq syntax by breaking a query in 2 or more parts,
just like the following example,
the records will be downloaded immediatly from sql server in each step,or they will be sent to server at the moment when I’ll start to see all the data?
for exemple when I bind some objects (a Datagrid for exemple)
System.Linq.IQueryable<Panorami> Result = db.Panorami;
byte FoundOneContion = 0;
//step 1
if (!string.IsNullOrEmpty(Title))
{
Result = Result.Where(p => SqlMethods.Like(p.Title, "%" + Title + "%"));
FoundOneContion = 1;
}
//step 2
if (!string.IsNullOrEmpty(Subject))
{
Result = Result.Where(p => SqlMethods.Like(p.Subject, "%" + Subject + "%"));
FoundOneContion = 1;
}
if (FoundOneContion == 0)
{
return null;
}
else
{
return Result.OrderBy(p => p.Title).Skip(PS * CP).Take(PS);
}
If unfortunatly Linq download immediately all the records
(Therefore such a doubt I have had was right!)
exist any syntax to round the problem?
For example: ternary operator ( condition ? true part : false part )
For any suggestions i would appreciate them a lot. thanks everyone!
The above method does not enumerate the query - therefore no database calls are made. The query is constructed and not executed.
You can enumerate the query by calling foreach, or calling some method that calls foreach (such as ToList, ToArray), or by calling GetEnumerator(). This will cause the query to execute.