Good morning to everyone,
Please I would be so grateful if you could provide a little help for me. I am already stuck for long time with this issue.
I have a function which does not stop loading my localhost after this function is triggered. I did not figure out so far how to fix it.
Any help would be perfect.
This is my code:
// Copy scene
router.post('/copy', function(req,res,call) {
if( req.param('scene') !== undefined ){
db.serialize(function () {
db.run("CREATE TABLE temp_table as SELECT * FROM scene where id=?", req.param('scene'));
db.run("UPDATE temp_table SET id = NULL, user_id = (SELECT id FROM users WHERE email =?)",GLOBAL.email);
db.run("INSERT INTO scene SELECT * FROM temp_table");
db.run("DROP TABLE temp_table");
if(error) {
console.log(error);
}
});
db.close();
}
});
Thank you so much in advance
Whenever browser sends any request to a server it expects a response. if it doesn't get any response it will be stuck with the timeout.
You need to send the response to terminate the request if you are not doing next execution with callback call or if you are expecting next manipulation then replace res.send() to call(error parameter,success parameter).
router.post('/copy', function(req, res, call) {
if (req.param('scene') !== undefined) {
db.serialize(function() {
db.run("CREATE TABLE temp_table as SELECT * FROM scene where id=?", req.param('scene'));
db.run("UPDATE temp_table SET id = NULL, user_id = (SELECT id FROM users WHERE email =?)", GLOBAL.email);
db.run("INSERT INTO scene SELECT * FROM temp_table");
db.run("DROP TABLE temp_table");
if (error) {
console.log(error);
res.send(error);//send response if error
//or call(error);
}
res.send({message:'success'});//send response if success
//or call(null,whatever you want to pass)
});
db.close();
}
});
You must either call the callback call() to pass on control to next middleware, or render and end the response using res.end() once your middleware logic is done.
Please see: https://expressjs.com/en/guide/writing-middleware.html
Related
I'm using google Pub/sub to receive a message and trigger a cloud func, that func queries the data of the message in BigQuery, the problem is that in my message I receive UNIX timestamp, and I need to convert this time stamp for bigquery format, otherwise the function can not run my query...
In this part of the function:
exports.insertBigQuery = async (message, context) => {
// Decode base64 the PubSub message
let logData = Buffer.from(message.data, "base64").toString();
// Convert it in JSON
let logMessage = JSON.parse(logData);
const query = createQuery(logMessage);
const options = {
query: query,
location: "US",
};
const [job] = await bigquery.createQueryJob(options);
console.log(`Job ${job.id} started.`);
// Only wait the end of the job. Theere is no row as answer, it's only an insert
await job.getQueryResults();
};
I access the data in the message.
On this part of the function I query in my bigquery:
function createQuery() {
const queryString = `INSERT INTO \`mytable\`(myTS, userTS, registerTS)
VALUES ( #myTS, #userTS, #registerTS);`;
My problem is that I receive the message with UNIX time stamp and when the function runs my query gives me an error. I couldn't find any solution, any help is MUCH appreciated! Thanks in advance!
One way you cand handle this is using the TIMESTAMP_SECONDS function to wrap your values on the insert
INSERT INTO \`mytable\`(myTS, userTS, registerTS)
VALUES ( TIMESTAMP_SECONDS(#myTS), TIMESTAMP_SECONDS(#userTS), TIMESTAMP_SECONDS(#registerTS));
I am looking forward to know how can I run an Azure SQL stored procedure with multiple input parameters from Nodejs.
For example, if I have a stored procedure FIND_USERS(activity_status, color, gender) which runs a query
select * from users where isActive = activity_status and bay_color = color and userGender = gender;
I should be able to call this stored procedure from nodejs with the input parameters. The thing to understand here is that I want have a SQL transaction service that can take any CALL PROCEDURE type command along with the set of input parameters and call the procedure using those input parameters irrespective of the number of input parameters.
What I know is that for MySQL, there is a mysql library which lets me run procedures with multiple parameters. I have encapsulated it in MySQLConnector.js service as
var mysql = require('mysql');
exports.query = function(sql, values, next) {
if (arguments.length === 2) {
next = values;
values = null;
}
var connection = mysql.createConnection({
host:host,
user:user,
password:password,
database:database
});
connection.connect(function(err) {
if (err !== null) {
console.log("[MYSQL] Error connecting to mysql:" + err+'\n');
console.log(err == 'Error: ER_CON_COUNT_ERROR: Too many connections')
if(err == 'Error: ER_CON_COUNT_ERROR: Too many connections'){
connection.end();
}
}
});
connection.query(sql, values, function(err) {
connection.end();
if (err) {
throw err;
}
next.apply(this, arguments);
});
}
With this, I can call a stored procedure from nodejs with a function like
MySQLConnector.query('CALL FIND_USERS (?, ?, ?)', [1, 'blue', 'female'], function(err, userData) {
//do something with userData
});
How is it possible to do this for Azure MS SQL?
You can use tedious driver to connect to SQL Server. It supports both input+output parameter for statements and SPs, you can find the example in http://tediousjs.github.io/tedious/parameters.html
Feels free to raise an issue in GitHub if you need more assistance.
Make use of Edje.js and you should create a function and send the parameters when you call the function.
getHorarioFarmacia({pSede:'Sucursal Parrita'}, function (error, result){....
}
For more details, read the comments made by Luis Diego Pizarro here.
Currently working on an API which given an address returns information about is. Some of the rows in our tables are duplicates, however being as there is over 15 million I cant go and find the duplicates. Instead I have opted to use
var query = `SELECT TOP 1 * from my_TABLE where..conditions`;
This ensures that only one row of the duplicates are returned.
The problem is when this is sent back as a JSON it comes as an array with one object.
In the Server.js file
// create Request object
var request = new sql.Request();
// query to the database
request.query(query, function (err, result) {
if (err) {
console.log("Error while querying database :- " + err);
res.send(err);
}
else {
res.send(result)
}
Returns this:
[{
Address:'our info'
}]
is there a way to have it respond with
{
Address:'our info'
}
Because from DB you've get list of object anyway, even there is only 1 item.
It works as you expected when you try to return json with the first element of your array.
I have a 1.x AngularJS application, and need to perform 2 SQL queries synchronously (one after the other). The first does an update to a table, the second does a select against the same table to get the updated values. The problem I am encountering is that the queries are executed asynchronously, and occassionally the select is performed before the update completes, and I get back the "before" data rather than the "after" data. I put in a 500ms delay, and that works fine for me, but offshore folks with slower connections still encounter the problem intermittently. My code is below (simplified to make my point). Any thoughts as to how I can get the second query to wait until the first is complete?
$scope.saveUser = function(origuid, uid, name) {
$http.get('/ccrdb/updateAdmin?origuid=' + origuid + '&uid=' + uid + '&name=' + name);
setTimeout(function() {
$http.get('/ccrdb/getAdmins').then(function(response) {
$scope.users = response.data.detail;
});
return true;
}, 500);
};
$http returns promises that resolve when the request is done, so do:
$scope.saveUser = function(origuid, uid, name) {
$http.get('/ccrdb/updateAdmin?origuid=' + origuid + '&uid=' + uid + '&name=' + name)
.then(function() {
return $http.get('/ccrdb/getAdmins');
})
.then(function(response) {
$scope.users = response.data.detail;
});
};
I have a very strange error with dapper:
there is already an open DataReader associated with this Command
which must be closed first
But I don't use DataReader! I just call select query on my server application and take first result:
//How I run query:
public static T SelectVersion(IDbTransaction transaction = null)
{
return DbHelper.DataBase.Connection.Query<T>("SELECT * FROM [VersionLog] WHERE [Version] = (SELECT MAX([Version]) FROM [VersionLog])", null, transaction, commandTimeout: DbHelper.CommandTimeout).FirstOrDefault();
}
//And how I call this method:
public Response Upload(CommitRequest message) //It is calling on server from client
{
//Prepearing data from CommitRequest
using (var tr = DbHelper.DataBase.Connection.BeginTransaction(IsolationLevel.Serializable))
{
int v = SelectQueries<VersionLog>.SelectVersion(tr) != null ? SelectQueries<VersionLog>.SelectVersion(tr).Version : 0; //Call my query here
int newVersion = v + 1; //update version
//Saving changes from CommitRequest to db
//Updated version saving to base too, maybe it is problem?
return new Response
{
Message = String.Empty,
ServerBaseVersion = versionLog.Version,
};
}
}
}
And most sadly that this exception appearing in random time, I think what problem in concurrent access to server from two clients.
Please help.
This some times happens if the model and database schema are not matching and an exception is being raised inside Dapper.
If you really want to get into this, best way is to include dapper source in your project and debug.