Reputation: 2071
I have problem with executing multiple sql query on sails.js
I would like to run a script from a file on sails lift
.
I wrote a custom handling inside /config/bootstrap.js
module.exports.bootstrap = function(cb) {
fs.readFile('SQL\\StoredProcedures\\MyProcedure.sql', 'utf8', function (err,data) {
if (err) {
console.log(err);
}
console.log(data);
MyModel.query(data, function(err, records){
if(err){
console.log(err);
}
});
});
// It's very important to trigger this callback method when you are finished
// with the bootstrap! (otherwise your server will never lift, since it's waiting on the bootstrap)
cb();
};
The problem is, that .query()
function does not accept multiple queries inside. I mean, it does accept when in my file I have:
DROP PROCEDURE IF EXISTS `MyProcedure`;
But it won't accept while in my file I have:
DROP PROCEDURE IF EXISTS `MyProcedure`;
SELECT * FROM something;
Is there a way to execute this file?
Upvotes: 1
Views: 661
Reputation: 408
This can be done by setting up your config/datastores.js
like this:
module.exports = {
default: {
multipleStatements: true
}
}
By adding this into your configuration, you're letting Sails handle the parsing and execution of your queries.
The issue is that by default, the Node MySQL driver doesn't allow running multiple queries at once. This is to guard against SQL injection.
For more complete explanation, see @sgress454's comment here: https://github.com/balderdashy/sails/issues/4192
Upvotes: 2
Reputation: 5871
You could split the lines in your file, and run all the queries one by one?
var fs = require('fs');
module.exports = function (cb) {
fs.readFile('SQL\\StoredProcedures\\MyProcedure.sql', 'utf8', function (err,data) {
if (err) {
sails.log.error(err);
return cb(); // you have no queries to run
}
sails.log.info(data);
var queries = data.split('\n');
// async is injected into the global scope by sails, so no need to require it
// if you don't need your queries to run in order, then you can use async.each
// instead of async.eachSeries
// https://github.com/caolan/async#each
async.eachSeries(
queries,
function (query, cb) {
MyModel.query(query, function (err, records) {
if (err) {
sails.log.error(err);
return cb();
// If you don't want other queries to execute in case of an error, then
// return cb(err);
}
});
},
function (err) {
if (err) { sails.log.error(err); }
return cb();
}
);
});
};
Upvotes: 0