Currently, I am using string manipulation for passing value for multiple where clause.
Since docs for raw queries with replacements does not support multiple where clause and i cannot use simply use a find()
Since my requirement needs complex mysql queries which is not possible using find().
Is there any way of accomplish this basic task for multiple filtration in "Raw queries mode" ?
if(selector==""){
selector="where "+searchkey+" LIKE "+"'%"+searchvalue+"%'";
}
else
{
selector=selector+" and "+searchkey+' LIKE %' + searchvalue + '%';
}
sequelize.query('select ROLEID as RoleID,Rolename, CASE WHEN isactive = 1 THEN \'True\' ELSE \'False\' END as isactive , ' +
'GROUP_CONCAT(DISTINCT modID) ModID,' +
'GROUP_CONCAT(DISTINCT Modulename) Modulename,' +
'GROUP_CONCAT(DISTINCT Accestype) Accestype ' +
'from ' +
'( ' +
'select isactive,rl.roleid AS ROLEID,n.modnameID as modID, n.Mname as Modulename,rl.rolename as Rolename, r.Accestype as Accestype from mrole r ' +
'left join modname n ' +
'on r.modulename=n.modnameID ' +
'left join role rl ' +
'on rl.roleid=r.rolename '+
') as a '+selector+' GROUP BY ROLEID,Rolename,isactive '+
'limit :NUMBER_OF_ITEMS ' +
'offset :PAGE_NUMBER ', {
replacements: {
NUMBER_OF_ITEMS: parseInt(NUMBER_OF_ITEMS),
PAGE_NUMBER: parseInt(PAGE_NUMBER)
},
type: sequelize.QueryTypes.SELECT
}
).then(function(projects) {
var red = new Object();
red.rows = projects;
res.json(red);
})
Related
I have a problem order by column name(String) when i have more than one word, like " Kafka Streams" and "Kafka Connectors". The order should be "Kafka Connectors", "Kafka Streams" but it order "Kafka Streams" ,"Kafka Connectors". The first word is ok, but second not. How can i resolve this?
I tried use substring and charindex, but the last one dont work in sequelize RAW queries.
sequelize.query(
'SELECT `technology`.`business_unit_id`, `technology`.`unit_reference_data_technology_id`' +
'FROM `unit_reference_data_technology` AS `technology`' +
'WHERE (`technology`.`description` LIKE (:name) ') ' +
'ORDER BY `technology`.`description` ASC, LIMIT ' + limit + ' OFFSET ' + offset + '', { model: Models.unit_reference_data_technology, mapToModel: true, replacements: { business_unit_id, name: '%' + text + '%', limit: 10,}, type: sequelize.QueryTypes.SELECT })
Example
I m using MySQL and a Sequelize (nodeJS).
Can anyone help me? My solution is ORDER BY first word ASC, second word ASC ( If the string have always 2 words)
I'm currently trying to get the current date and try to save on my database but the only thing i get on my date column is 1982 , really strange ? Here is my code for the date and the mysql insertion :
DATE :
var dateTime = require('node-datetime')
var dt = dateTime.create();
var formatted = dt.format('Y-m-d');
console.log(formatted);
Mysql insertion :
pool.query(
'INSERT INTO jbets SET user = ' + pool.escape(tradingRequests[offer.id]['user']) +
', assetids = ' + pool.escape(assetidsSS) +
', value = ' + pool.escape(totalPrice) +
', minTicket = ' + pool.escape(minTicket) +
', maxTicket = ' + pool.escape(maxTicket) +
', total = ' + pool.escape(totalSkins) +
', jid = ' + pool.escape(jackpotRound) +
', token = ' + pool.escape(offer.id) +
',date =' + formatted
)
You should really be using placeholders.
You shouldn't be trying to convert the date object to that string format before inserting into a date field in the DB. The proper format would be YYYY-mm-dd HH:ii:ss, however you could let your MySQL library handle the conversion for you.
I suggest reading the Escaping Query Values section of the MySQL JS library documentation.
Try something like this:
pool.query('INSERT INTO jbets SET user = ?, assetids = ?, value = ?, ' +
'minTicket = ?, maxTicket = ?, total = ?, jid = ?, token = ?, date = ?',
[tradingRequests[offer.id]['user'], assetidsSS, totalPrice,
minTicket, maxTicket, totalSkins, jackpotRound, offer.id, dt]);
Use this code :
pool.query('INSERT INTO jbets (user, assetids, value, minTicket, maxTicket, total, jid, token, date) VALUES(pool.escape(tradingRequests[offer.id]['user']), pool.escape(assetidsSS), pool.escape(totalPrice), pool.escape(minTicket), pool.escape(maxTicket), pool.escape(totalSkins), pool.escape(jackpotRound), pool.escape(offer.id), NOW()));
Thanks for responding the problem was from my db i was need to change the ty to varchar
I want to make the ORDER BY dynamic in mysql query in node.js. But it's not working. I console.log the multiQuery variable and everything looks perfect but when ran it simply doesn't work. This is what I have:
var order,
multiQuery;
if(req.query.o){
order = req.query.o;
}else{
order = "views";
}
multiQuery = 'SELECT COUNT(Category) AS Count FROM posts;';
//PROBLEM LIES HERE IN THE SECOND ONE
multiQuery += 'SELECT ID, Title, Img_path, Category, Views FROM posts WHERE Category = ' + connection.escape(category) + ' ORDER BY' + connection.escape(order) + 'DESC LIMIT ' + start_from + ', 15;';
connection.query(multiQuery, function(err, result){
});
This does not work:
SELECT foo FROM bar ORDER BY 'baz';
This does work :
SELECT foo FROM bar ORDER BY baz;
Did you try removing the quotes that connection.escape adds?
Try using this:
function escapeSansQuotes(connection, criterion) {
return connection.escape(criterion).match(/^'(\w+)'$/)[1];
}
then use escapeSansQuotes(connection, order) instead of connection.escape(order).
try using a proper spacing for each token
//PROBLEM LIES HERE IN THE SECOND ONE
multiQuery += 'SELECT ID, Title, Img_path, Category, Views
FROM posts WHERE Category = ' + connection.escape(category) +
' ORDER BY ' + connection.escape(order) +
' DESC LIMIT ' + start_from + ', 15;';
Check if you did enabled the multi-query into your connection object.
http://nickolayconsulting.com/node-js-and-multiple-sql-calls-in-one-query/
Support for multiple statements are disabled by default for security
reasons (it allows for SQL injection attacks if values are not
properly escaped). To use this feature you have to enable it for your
connection:
var connection = mysql.createConnection({multipleStatements: true});
In my sqlobject implementation I have the following line:
members = Member.select("CONCAT_WS(' ', member.first_name, member.last_name, member.personal_code_number, member.mail) like " + Member.sqlrepr('%' + query + '%'))
I want to convert that to using sqlalchemy but haven't found a way to do that.
members = session.query(Member).filter(
func.CONCAT_WS(' ', Member.first_name, Member.last_name, Member.personal_code_number, Member.mail)
.like('%' + query + '%')
)
I am writing code to script CREATE TABLE statements for all tables across all databases on a server.The code below will work for a specific database. Would like some ideas on how to modify it, so it can script table schema for all the tables.
select 'create table [' + so.name + '] (' + o.list + ')' + CASE WHEN tc.Constraint_Name IS NULL THEN '' ELSE 'ALTER TABLE ' + so.Name + ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' END
from sysobjects so
cross apply
(SELECT
' ['+column_name+'] ' +
data_type + case data_type
when 'sql_variant' then ''
when 'text' then ''
when 'decimal' then '(' + cast(numeric_precision_radix as varchar) + ', ' + cast(numeric_scale as varchar) + ')'
else coalesce('('+case when character_maximum_length = -1 then 'MAX' else cast(character_maximum_length as varchar) end +')','') end + ' ' +
case when exists (
select id from syscolumns
where object_name(id)=so.name
and name=column_name
and columnproperty(id,name,'IsIdentity') = 1
) then
'IDENTITY(' +
cast(ident_seed(so.name) as varchar) + ',' +
cast(ident_incr(so.name) as varchar) + ')'
else ''
end + ' ' +
(case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' +
case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT ELSE '' END + ', '
from information_schema.columns where table_name = so.name
order by ordinal_position
FOR XML PATH('')) o (list)
left join
information_schema.table_constraints tc
on tc.Table_name = so.Name
AND tc.Constraint_Type = 'PRIMARY KEY'
cross apply
(select '[' + Column_Name + '], '
FROM information_schema.key_column_usage kcu
WHERE kcu.Constraint_Name = tc.Constraint_Name
ORDER BY
ORDINAL_POSITION
FOR XML PATH('')) j (list)
where xtype = 'U'
AND name NOT IN ('dtproperties')
Since you seem determined on TSQL, a quick and dirty solution would be to use the (undocumented) sp_foreachdb stored procedure. That will give you the name of every database on the sql instance, so you would just USE each database in turn and run TSQL that you posted (after escaping all the single qoutes in it).
Heres a shortened example:
EXECUTE sp_msforeachdb 'USE [?]
select ''create table ['' + so.name + ''] ''
from sysobjects so
-- the rest of your escaped TSQL goes here...
-- then finish with a closing quote:
'