I'm trying to create a filter for a findAll function that filters by name. The other filters in this function work fine but I can't get the name filter to work.
The function below accepts filter parameters (if any) and adds on to the WHERE query based on any passed in filters. Right now, when I pass in a name, it returns nothing unless the query matches a name in the database but I'm trying to return results that contain whatever the value of name is (i.e. a name query for 'net' would get you 'Neural Networks')
Here is what I have so far:
static async findAll(searchFilters = {}) {
let query = `SELECT handle, name, description, num_employees AS "numEmployees", logo_url AS "logoUrl"
FROM companies`;
let whereStatement = []
let values = []
const {name, minEmployees, maxEmployees} = searchFilters
if (minEmployees > maxEmployees) throw new BadRequestError('minEmployees cannot be greater than maxEmployees!')
if (!!minEmployees) {
values.push(minEmployees)
whereStatement.push(`num_employees >= $${values.length}`)
}
if (!!maxEmployees) {
values.push(maxEmployees)
whereStatement.push(`num_employees <= $${values.length}`)
}
if (!!name) {
values.push(name)
whereStatement.push(`name ILIKE $${values.length}`)
}
if (whereStatement.length > 0) {
query += ` WHERE ${whereStatement.join(" AND ")}`
}
query += ' ORDER BY name'
const companiesRes = await db.query(query, values)
return companiesRes.rows;
}
I tried typing it like this:
name ILIKE '%$${values.length}%'
but I got this message:
"error": {
"message": "bind message supplies 1 parameters, but prepared statement \"\" requires 0",
"status": 500
}
Is there a specific way to sanitize ILIKE queries in Node-pg or is my syntax just off?
I think your code in place where you append the name filter should look like:
...
if (!!name) {
values.push(`%${name}%`)
whereStatement.push(`name ILIKE $${values.length}`)
}
...
see 503#issuecomment-32055380
I'm trying to save the information I get from my inmatefirst column with my SQL query into the variable "first'. I was wondering what the correct syntax/approach was to doing this.
let sql = `SELECT * FROM inmates WHERE inmatefirst = ? AND inmatelast = ? AND dob = ?`;
let query = db.query(sql, [search.first, search.last, search.dob], (err, result) => {
if (err) throw err;
if (result.length != 0) {
res.render(path.resolve('./myviews/modify'), {
good: 'Person Found - Please Enter Updated Information',
first: result.inmatefirst,
last: result.last,
dob: result.dob,
sex: result.sex
});
});
});
Your SQL says, in part, this:
SELECT * FROM inmates WHERE inma...
You've asked for every column from the table. That can make life confusing.
Instead, spell out the columns you want. Your Javascript indicates that you want these ones:
SELECT inmatefirst, last, dob, sex FROM inmates WHERE inma...
(It's possible that is the wrong set of columns. Check it.
Then, as #barmar pointed out, use result[0].first etc, because result is an array of objects, one for each row of your resultset.
I have in my sql database 2 tables, a table called club and a table called players, they are connected by one to many relationships, the query in node.js works fine but i can not get the last insert of table club , i need to it for insert in the foreign key in the table players
here what i have tried in node.js:
module.exports={
create:(data,callback)=>{
var myArray = new Array();
/* for(let item of data.players) {
console.log(item.firstname);
}*/
data.players.forEach((player) => {
console.log(player.id);
console.log(player);
var playerModel ={
id : player.id,
firstname : player.firstname,
lastname : player.lastname,
position : player.position,
price : player.price,
appearences : player.appearences,
goals : player.goals,
assists : player.assists,
cleansheets : player.cleansheets,
redcards : player.redcards,
yellowcards : player.yellowcards,
image : player.image,
clubid : player.clubid,
};
console.log("model"+playerModel.position);
myArray.push(playerModel);
});
var id;
pool.query(
'insert into club(userid,name,price) values(?,?,?)',
[
data.userid,
data.name,
data.price
],
(error,result) => {
if(error){
callback(error);
}
/* id = result.insertId;
console.error(result);
console.log(result+" result");*/
console.log(result.insertId);
return callback(null,result.insertId);
},
);
for(var item of myArray){
pool.query(
'insert into players(id,firstname,lastname,position,price,appearences,goals,assists,cleansheets,redcards,yellowcards,image,clubid) values (?,?,?,?,?,?,?,?,?,?,?,?,?)',
[
item.id,
item.firstname,
item.lastname,
item.position,
item.price,
item.appearences,
item.goals,
item.assists,
item.cleansheets,
item.redcards,
item.yellowcards,
item.image,
(
'select top 1 id from club order by id desc'
)
],
(error,results,fields)=>{
if(error){
callback(error);
}
return callback(null,results);
},
);
}
},
no idea about how to do this
If I understand this correctly, a subquery should work here.
-- first insert the club from paraterized query
insert into club (clubid, name, price)
values (? , ? , ?);
-- then use a subquery to find the last inserted club id
insert into
players (id, firstname, lastname, position, price, appearences, goals, assists, cleansheets, redcards, yellowcards, image, clubid)
values
(
? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? ,
(
select clubid
from club
order by clubid desc
limit 1
)
)
;
Apart from that, an insert statement doesn't give you any data back. If you are looking to get the ID from the first call in NodeJS, you need to run a batch statement. 1 insert and 1 select, in the same batch of statements that is sent to the SQL server. See more for multi statement config here. node-mysql multiple statements in one query
const pool = mysql.createConnection({multipleStatements: true});
pool.query(`
insert into club(userid,name,price) values(?,?,?);
select clubid from club order by clubid desc limit 1;
`
, params
, function(err, results) {
if (err) throw err;
// now the id will be the second item of the batch statement result
const myId = results[1]
});
)
Based on both things, you could combine them, actually.
pool.query(`
insert into club(userid,name,price) values(?,?,?);
insert into players (id, firstname, lastname, position, price, appearences, goals, assists, cleansheets, redcards, yellowcards, image, clubid)
values
(
? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? ,
(
select clubid
from club
order by clubid desc
limit 1
)
);
`
, params
)
You could also create yourself a stored procedure for this purpose.
Create a multi-query batch, like
INSERT INTO table1 (column1, column2, column3) VALUES (?, ?, ?);
INSERT INTO table2 (column1, reference_column, column3) VALUES (?, LAST_INSERT_ID(), ?);
Execute using a method which:
supports multi-query batch execution
executes the batch as a transaction
The parameters are provided to this method as one solid data array (for shown code it will contain 5 values, first 3 will be inserted into 1st query and all another toi 2nd one). id value assigned by 1st query will be automatically retrieved by the function and inserted into 2nd query.
I don't know what is the method with described properties in Node.JS. But it must exist..
An alternate way to figure this out was placing the initial query holding the first INSERT statement into a variable:
const first_insert = db.query('INSERT')...
Then returning the variable at the end of the first promise, and then finding the property values of the variable (since it returns a javascript object afterall):
.then((first_insert) => {
console.log(Object.entries(first_insert)); //returns array
console.log(first_insert[0]);
/*returns contents of first index of previously returned array, you'll see an object with a insertId property, thats what you need*/
console.log(first_insert[0].insertId)
/*this is the value you need to pass to each following statement*/
/*store that value in a variable that you declarre before any of the db methods, I named mine pk*/
pk = first_insert[0].insertId
/*Now use that variable for the foreign key and to correspond with the placeholder in whatever queries you use*/
}
I have a JSON like this:
{"name":[{"tag":"Peter"}]}
And I'm dynamically building a prepared statement with multiple wildcards like this:
var sqlVar;
sqlVar += existParams.map(field => {
if (field === 'name') {
function getValues(item, index) {
var getVal = [item.tag];
return `${field} LIKE ?`;
}
return '('+name.map(getValues).join(' OR ')+')';
} else {
return `(${field} = ?)`
}
}).join(" AND ");
var sql = "SELECT * FROM names "+sqlVar+"";
connection.query(sql,
...
function getValues(item, index) {
var getVal = [item.tag];
return '%' + getVal + '%';
}
return name.map(getValues);
//Further attempts
//var getResult = name.map(getValues);
//return getResult.split(",");
//return name.map(getValues).join(', ');
, function(err, rows) {
...
});
If I have one value it works just fine. In console.log (SQL) I can see:
SELECT * FROM names WHERE (name LIKE ?)
BUT... if I have multiple values like:
{"name":[{"tag":"Peter"},{"tag":"Jack"}]}
I'm getting an SQL Error:
sql: 'SELECT * FROM names WHERE (name LIKE \'%Peter%\', \'%Jack%\' OR name LIKE ?) }
... So the second value is not going to the second position.
... but the result should be:
sql: 'SELECT * FROM names WHERE (name LIKE \'%Jack%\' OR name LIKE \'%Peter%\') }
... so in the console.log(sql):
SELECT * FROM names WHERE (name LIKE ? OR name LIKE ?)
What am I missing and how can I get the second value to the second LIKE and so on?!
Here is a similar example but with only one value: nodejs throws error with mysql like query via prepared statements
The only reason here for the resulting statement to be 'SELECT * FROM names WHERE (name LIKE \'%Peter%\', \'%Jack%\' OR name LIKE ?)
is that you have passed a nested array with value [['%Peter%', '%Jack%']] instead of a flat one.
Using the given object say,
const source = {"name":[{"tag":"Peter"}, {"tag":"Jack"}]}
Then the query values for the prepared statement should be
const queryValues = source.name.map(({tag}) => `%${tag}%`);
// [ '%Peter%', '%Jack%' ]
connect.query(sql, queryValues, (err, rows) => {
});
First of all I have to say I'm totally newbi in NodeJS technologies.
But, I've tried to do something to try to learn it.
This is the problem:
I have 3 tables (PARTICIPANT, ADDRESS_PARTICIPANT and INSCRIPTION).
The ADDRESS_PARTICIPANT contains participant_id (it's the participant's address).
The INSCRIPTION contains participant_id
So, to store a inscription row, at first I need to save the PARTICIPANT and the ADDRESS_PARTICIPANT. Only after this I could insert INSCRIPTION
I'm doing this in the way i've learn, but I think there are a lot of nested ifs.
How could I improve this code? Someone told me with Promise i'll well.. but I don't know. Someone could help me? Thanks
Here is the code:
this.save = function(data, retur) {
var con = db();
const SQL_INSERT_PARTICIPANT =
`INSERT INTO participant (nome_completo, tipo_funcionario, data_nascimento, sexo, unidade, cpf, email, telefone, telefone_emergencia) VALUES( ? )` ;
const SQL_INSERT_ADDRESS_PARTICIPANT =
`INSERT INTO endereco_participante (participant_id, cep, estado, cidade, bairro, endereco, numero) values( ? )`;
const SQL_INSERT_INSCRIPTIONS = `......`
var values = [
data.nome_completo, data.tipo_funcionario, new Date(dateToEN(data.data_nascimento)), data.sexo, data.unidade, data.cpf_funcionario, data.email, data.telefone, data.telefone_emergencia
]
const insertParticipante = con.query(SQL_INSERT_PARTICIPANT , [values], function (err, result) {
if (err) throw err;
var values_end = [
result.insertId, data.cep, data.estado, data.cidade, data.bairro, data.endereco, data.numero
]
if (result.affectedRows > 0 ) {
const insertEndPart = con.query(SQL_INSERT_ADDRESS_PARTICIPANT , [values_end], function(err, result2 ) {
if (err) throw err;
console.log('Number of records inserted in ADDRESS_PARTICIPANT table: ' + result2.affectedRows);
console.log('insertId.: ' + result2.insertId)
if (result.affectedRows > 0 ) {
const insertInscricao = con.query(SQL_INSERT_INSCRIPTIONS, [values_ins], function(err, result3) {
console.log(`Inscription recorded! id: `+resul3.insertId)
})
}
})
}
})
}
You can use MySQL's LAST_INSERT_ID i assume every table has a primray key column with a auto_increment option.
With no argument, LAST_INSERT_ID() returns a BIGINT UNSIGNED (64-bit)
value representing the first automatically generated value
successfully inserted for an AUTO_INCREMENT column as a result of the
most recently executed INSERT statement. The value of LAST_INSERT_ID()
remains unchanged if no rows are successfully inserted.
https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_last-insert-id
Then you can use these INSERT's in NodeJS instead.
INSERT INTO participant (nome_completo, tipo_funcionario, data_nascimento, sexo, unidade, cpf, email, telefone, telefone_emergencia) VALUES( <other columns> )
This insert below will use LAST_INSERT_ID() to get the participant.id
INSERT INTO endereco_participante (participant_id, cep, estado, cidade, bairro, endereco, numero) values( LAST_INSERT_ID(), <other columns> )
With three table the problem gets more complex.
Then you can use MySQL's user variables.
INSERT INTO participant (nome_completo, tipo_funcionario, data_nascimento, sexo, unidade, cpf, email, telefone, telefone_emergencia) VALUES( <other columns> )
SET #participant_id = LAST_INSERT_ID();
INSERT INTO endereco_participante (participant_id, cep, estado, cidade, bairro, endereco, numero) values( #participant_id, <other columns> )
SET #endereco_participante_id = LAST_INSERT_ID();
Then you can use #participant_id and #endereco_participante_id in the third insert query. (which seams you didn't provided in your question).
Note the SET queries are separated queries so you need to execute them also with con.query('SET #participant_id = LAST_INSERT_ID();', ..)