I have two tables that follow and profile, and follow in the table insert id of the profile below (foreign keys)
How can I be sure before inserting into my table foreign keys that match a profile id of the table?
var o_segui = {
seguace_id: profilo,
seguito_id: data.profilo_da_seguire,
created: new Date()
};
connection.query('INSERT INTO follow SET ?', o_segui, function(error, rows) {
if (error) {
var err = "Error on 'seguiAction': " + error;
console.error(err);
throw err;
}
now i check that now exists with a query before insert like:
connection.query('SELECT count(*) as n FROM profile WHERE id =' + connection.escape(profilo_da_seguire), function(error, rows) {
if (error) {
var err = "Error on 'verifico Profilo': " + error;
console.error(err);
throw err;
}
console.log(rows);
if (rows.shift().n > 0) { then OK
UPDATE in my Insert i do throw err...if i comment throw err server node dosen't go down...i have to comment this line and close connection ?
Check-before-set is usually not a good approach while using database. Mostly because you will have to take into account possible concurrent access to your tables.
Anyway, concerning foreign key constraints, if you use InnoDB, the engine will check for you at insert-time.
So, I think it is better to be optimistic by trying to insert. But be prepared to handle gracefully a possible failure.
EDIT: I build an example in order to "prove" that integrity constraints are enforced by the DB engine InnoDB: http://sqlfiddle.com/#!2/f372d/1
As you will see, faulty data are not inserted in the DB. In your program you will have to deal with the corresponding exception/error.
Related
I have used one signle connection object of MYSQL in node JS to serve for multiple users.
I mean to say that MySQL connection will be created upon starting the script & it will remain same until the life of the node script/server.
Practically, this is possible to do & i have done the same. Please take a look at below code of NodeJS/MySQL script.
#################################
var http = require('http');
var mysql = require('mysql');
var con = mysql.createConnection({
host: "192.168.1.105",
user: "root",
password: "XXXXXX",
database: "mydb"
});
con.connect(function(err) {
if (err) {
console.error('error: ' + err.message);
process.exit(1);
}
http.createServer(function (req, res) {
continueExecution(req,res);
}).listen(8082);
});
async function continueExecution(req,res){
res.write('calledddd\n');
for (let step = 0; step < 50; step++) {
// Runs 5 times, with values of step 0 through 4.
var bar = `Company Inc ${step}`;
var sql = `INSERT INTO customers (name, address) VALUES ('${bar}', 'Highway 37')`;
res.write(sql + "\n");
con.query(sql, function (err, result) {
if (err) throw err;
res.write("1 record inserted\n");
});
}
res.write('reached\n');
for (let ste = 0; ste < 50; ste++) {
res.write('started Update\n');
var bar = `Company Inc ${ste}`;
var sql = `UPDATE customers SET name = 'UPDATE RECORD' WHERE name = '${bar}'`;
con.query(sql, function (err, result) {
if (err) throw err;
res.write(result.affectedRows + " record(s) updated\n");
if(ste == 50) {
res.writeHead(200, {'Content-Type': 'text/html\n'});
res.write('Databse connected\n');
res.end();
}
});
}
}
#################################
I have several questions in my mind as i am technical expert. But i didn't find any resources over my questions. Please help me on this
Q1. Are there any type of consequences of using one single MySQL connection to provide response to multiple users?
Q2. Let's take an example.
100 users wants to access table name "users_data" at the same time. 25 users are updating their records on the same table with unique primary key. 50 users are selecting their records. another 25 users deleting their records.
All these operations are being done at the same time via parallel Node Script calls from remote device.
To complete all these MySQL transactions, system is using only 1 database connection.
What will happen in this case?
To answer your questions, one of the consequences of using a unique connection is that it can lead to slower request execution.
In fact, even if node will make the requests asynchronously, your database will execute all those requests synchronously, so one after the other in the order they came. As node makes the requests asynchronously, the order in which they are executed by your database is not granted, and the issue you are referencing to might happen.
One easy way to avoid this is to use a connection pool which will create a given number of connection, using the same db user. Here are some links that might help you with this :
using a connection pool with node.js
connect a mysql database with node.js
Is it possible to use sql package in node js to lock mysql table in order to update it and then unlock? I'm writing an API and there will be numerous concurrent connections which will update the database. I tried something like the code below, but after locking the table no further action could be taken on my database.
sql.query("LOCK TABLES customers WRITE;", (err, res) => {
if(err) {
console.log("error locking: ", err)
}
console.log("locked: ", res)
})
user_id=3;
//Delete from table query working perfect
db.query("DELETE FROM table WHERE user_id=" + user_id, function(dberr,dbres){
addUserInventories(detail, req, function(err,invres){
getHomePageDataWithInvntory(req, function(request, response){
callback(null, response);
});
});
});
//Here add record in table
function addUserInventories(detail, req, callback){
//After insertion called following and working perfect
return callback(null, null);
});
//Here retrieve record from table but not getting result after delete and insert operation
function getHomePageDataWithInvntory(req, callback){
user_id=3;
db.query("SELECT * FROM table WHERE user_id=" + user_id, function(err, results){
callback(null, results); //Here result getting empty array
});
});
In above code Delete record and Insert record work perfect but Retrieving record is not working.
Note : There is no any syntax error in SQL Query and In log file it print SELECT * FROM table WHERE user_id=3
When I got this kind of error, I always save them with the same process :
console.log your query string before using it
Use a database client like Sequel Pro, MySQL Workbench for sql
Copy paste your query manually in the client and run it
Generally, you'll get a syntax error, just solve it in the database client and your solution should work
Database client is not mandatory as you can run the query with command line, but the client will be a simpler interface for you and is more likely to give you more details on your syntax error.
Can you try this process ? If you don't succeed in solving the syntax error in the database client, you can put the query here so we can help you
Just in case : with your example, I'll use this pattern to log the query if you have trouble to do it, this give you an idea of how to do it in your code
//Here retrieve record from table but not getting result after delete and insert operation
function getHomePageDataWithInvntory(req, callback){
user_id=3;
var queryString = "SELECT * FROM table WHERE user_id=" + user_id;
console.log(queryString);
db.query(queryString, function(err, results){
callback(null, results); //Here result getting empty array
});
});
Good day,
I am willing to retrieve the id value of a freshly inserted row in Mysql.
I know there is mysqli_insert_id function, but:
I can't specify the table
Maybe there would be a risk of retrieving the wrong id, if a query is made in the meanwhile.
I am using node.js MySQL
I don't want to take the risk to query the highest id since there are a lot of queries, it could give me the wrong one...
(My id column is on auto-increment)
https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row
describes the solution perfectly well:
connection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result, fields) {
if (err) throw err;
console.log(result.insertId);
});
var table_data = {title: 'test'};
connection_db.query('INSERT INTO tablename SET ?', table_data , function(err, result, fields) {
if (err) {
// handle error
}else{
// Your row is inserted you can view
console.log(result.insertId);
}
});
You can also view by visiting this link https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row
I think you misunderstood the use of mysqli_insert_id() method. This method must be executed immediately after the insert statement to obtain the last inserted id. if you do it my MySQL directly
INSERT INTO(a,b)values(1,'test');
SELECT LAST_INSERT_ID(); -- this will display the last inserted id
I am trying to use redis to store a list of users and weather or not they are online or offline and displaying that information to other users.
I am fairly new to node and I believe that I need to use either a list or sorted sets.
when it gets to the console.log(reply); line it only shows "Object"
I think I need to loop through the results of the query to build the list but I am not really sure 1) how to loop through the results directly in the server application and 2) how to build the list or sorted set based on that query.
Any advice or suggestions would be greatly appreciated.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'users'
});
var redis = require('redis')
, client = redis.createClient();
connection.connect();
connection.query('SELECT * FROM user_profile', function(err, rows, fields)
{
if (err) throw err;
client.set('string key', rows[0], redis.print);
client.get("string key", function (err, reply) {
console.log(reply);
});
});
connection.end();
1) I assume rows contains an array of objects, each object representing a user data record.
client.set('string key', rows[0], redis.print);
is storing the whole first object of rows array, you can use a foreach statement to loop over all values returned.
You are saving the whole object in redis, but you only need the online/offline state 1 or 0. Besides, you can store only strings in redis keys (see Redis Keys Docs and Redis Set Docs)
2) You don't need a list or sorted sets only for online/offline state of a user, unless you need some sorting operations later.
You can use simple keys, I suggest using a pattern like this for key name: "user:".
// assuming that user_name property exists, holds username data "david" and it's unique
client.set("user:"+row[0].user_name, 0, redis.print); // stores key "user:david" = "0";`
Then to retrieve it use:
client.get("user:"+row[0].user_name);
So, your sql query callback function could look like this:
function(err, rows, fields) {
if (err) throw err;
rows.forEach(function(element, index, array){
client.set('user:'+element.user_name, 0, redis.print);
client.get("user:"+element.user_name, function (err, reply) {
console.log(reply);
});
});
}
Please note that the user name must be unique. You can use user ID's if not