How to avoid duplicated random id selection in MySQL? - javascript

I need to select two unique random id from table nodes and insert it in parent column in edges table.
But problem is that they are sometimes duplicated and it need them to be always different, how could I avoid that, please?
the code:
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'DAGtest3'
});
connection.connect((err) => {
if (err) throw err;
console.log('Database Connected!');
});
var a = "INSERT INTO `edges` (`parent`, `child`) VALUES ((SELECT `id` FROM `nodes` ORDER BY rand() LIMIT 1 ) , (4) )";
connection.query(a, (err, res) => {
if(err) throw err;
console.log("1 edge inserted to previous data");
});
var b = "INSERT INTO `edges` (`parent`, `child`) VALUES ((SELECT `id` FROM `nodes` ORDER BY rand() LIMIT 1) , (4) )";
connection.query(b, (err, res) => {
if(err) throw err;
console.log("Another edge inserted to previous data");
});
code for the tables:
CREATE TABLE nodes (
id INTEGER NOT NULL AUTO_INCREMENT,
sensorvalue VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);
CREATE TABLE edges (
parent INTEGER NOT NULL REFERENCES nodes(id) ON UPDATE CASCADE ON DELETE CASCADE,
child INTEGER NOT NULL REFERENCES nodes(id) ON UPDATE CASCADE ON DELETE CASCADE,
PRIMARY KEY (parent, child)
);
CREATE INDEX parent_idx ON edges (parent);
CREATE INDEX child_idx ON edges (child);
Thanks in advance.

You don't want two sequential random selections, since there's a non-zero chance that the second random selection could return the same row as the first. I think you should just fetch both rows at once:
INSERT INTO `edges` (`parent`, `child`) SELECT `id`, 4 FROM `nodes` ORDER BY rand() LIMIT 2;
So, your code would just have one query to execute, instead of two:
var a = "INSERT INTO `edges` (`parent`, `child`) SELECT `id`, 4 FROM `nodes` ORDER BY rand() LIMIT 2";
connection.query(a, (err, res) => {
if(err) throw err;
console.log("2 edges inserted to previous data");
});
When I set up your DB locally and run the above code, I get a successful insert:
Database Connected!
2 edges inserted to previous data
When I query the DB in the console I get:
mysql> select * from edges;
+--------+-------+
| parent | child |
+--------+-------+
| 2 | 4 |
| 3 | 4 |
+--------+-------+
2 rows in set (0.00 sec)

Related

get the last insert id in node.js and pass it to a second query

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*/
}

Inserting multiple values in mysql using nodejs is causing parsing errors

I need to insert a record into mysql using nodejs. I am able to insert directly by typing values into the query just fine. I can insert using query + value syntax to concatenate the values but read this leaves open the risk of SQL injection.
let sql ="INSERT INTO gametypes (strGameType, intTeamSize, intMaxPlayers, intMinPlayers) Values ? ";
var gametype ="Solo Zonewars";
var teamSize =1;
var maxPlayers = 16;
var minPlayers = 10;
var values = [gametype, teamSize, maxPlayers, minPlayers];
console.log("connected as id '" + connection.threadId);
connection.query(sql, values, function(err, result, fields) {
connection.release();
if(!err) {
console.log(result);
}else console.log(err);
});
Below is the attached error I am getting from mysql. It seems like it is putting extra quotes around the gametype variable and not attempting to insert the rest into the query. Any ideas?
error from mysql
I would suggest you to not use an array and replace your query by this one
let sql ="INSERT INTO gametypes (strGameType, intTeamSize, intMaxPlayers, intMinPlayers) Values (?, ?, ?, ?) ";
then you will pass the values one by one
If you are having 4 value parameters to the query, you should have 4 question marks as well. Try with the first line changed to:
let sql ="INSERT INTO gametypes (strGameType, intTeamSize, intMaxPlayers, intMinPlayers) Values (?, ?, ?, ?) ";
You can try wrapping your values into an array, as this method is intended for inserting multiple rows:
let sql ="INSERT INTO gametypes (strGameType, intTeamSize, intMaxPlayers, intMinPlayers) Values ? ";
var gametype ="Solo Zonewars";
var teamSize =1;
var maxPlayers = 16;
var minPlayers = 10;
var values = [
[gametype, teamSize, maxPlayers, minPlayers]
];
console.log("connected as id '" + connection.threadId);
connection.query(sql, [values], function(err, result, fields) {
connection.release();
if(!err) {
console.log(result);
}else console.log(err);
});

what the best way to insert a relationship table in mysql using NodeJS

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();', ..)

Check if MySQL row exists - Node.JS

Previous post I will refer to later
I am making a Discord bot which uses MySQL, but that shouldn't matter, I am trying to do a blacklist database so users in it can't use my bot
This is what I got so far:
con.query("SELECT EXISTS( SELECT 1 FROM `blacklist` WHERE `id` = '"+message.author.id+"')", function(error, result, field) {
if(error) throw error;
});
And this kinda works, this is my output
[ RowDataPacket {
'EXISTS( SELECT 1 FROM `blacklist` WHERE `id` = \'227090776172134400\')': 1 } ]
And the last digit works like a boolean, 1 if the row exists, 0 if it does not
But my problem is, that I can't seem to figure out how to check if it's a zero or not because it's an object
Why can't you make the query string a variable that you can later query on. For example:
let conStr = "SELECT EXISTS( SELECT 1 FROM `blacklist` WHERE `id` = '"+message.author.id+"')";
con.query(conStr, function(error, result, field) {
if(error) throw error;
console.log(result[conStr]); //--> 1
});

Insert Value in Mysql via node.js

I use Node.js and i want to INSERT few value in my table.
like:
id | profile_id | user_id
1 | 2 | 7
2 | 2 | 3
3 | 2 | 4
4 | 2 | 6
i have an array (user_id) with all my date(ids), i have to do a foreach in my array for insert each user_id value like
foreach...
connection.query('INSERT INTO mytable SET ?', my_obj, function(error,risultato) { ...
or i can do a cycle inside mysql with one statement?
You can use the following syntax for multiple insterts in MySQL:
INSERT INTO mytable (id, profile_id, user_id) VALUES(?,?,?),(?,?,?),(?,?,?);
Therefore yor code would be:
connection.query("INSERT INTO mytable (id, profile_id, user_id) VALUES(?,?,?),(?,?,?),(?,?,?)",
[id1, profile_id1, user_id1, id2, profile_id2, user_id2, id3, profile_id3, user_id3],
function(err, result){ .... });
After answer #Mustafa i do it: (use sugar.js and felixge/node-mysql)
var place ="(";
rows.each(function(n) {
columns.add(n.profile_id);
columns.add(n.user_id);
columns.add(new Date());
place += '(?,?,?),';
});
place= place.slice(0,place.lastIndexOf(","));
var sql = 'INSERT INTO mytable (profile_id,user_id,created) VALUES '+place+' ON DUPLICATE KEY UPDATE id=id';
connection.query(sql,
columns
, function(error, rows) {
if (error) {
var err = "Error on " + error;
console.dir(err);
console.log('>>>>>ERROR<<<<< ' + err);
throw err;
}
connection.release();
callback(rows);
I hope to help someone

Categories