I am working on snowflake with nodejs. I have used snowflake-sdk.
My raw query is
select * from xyz where x in ('1','2','3').
For this, in node.js, i had written query as connection.execute({ sqlText: select * from xyz where x in (:1), binds: [] })
what should I pass in binds and in which format, I am not getting an idea for it?
Please review the node.js driver documentation which provides a sample for the bind operations : https://docs.snowflake.com/en/user-guide/nodejs-driver-use.html#binding-statement-parameters
Note: not compiled or tested the below, but it's based on a technique we've used
It isn't possible to directly bind the array of values, but the following works:
var params = ['1', '2', '3'];
var statement = select * from xyz where id in (${params.map(x => '?').join()});
// statement will now be:
// select * from xyz where id in (?, ?, ?)
connection.execute({ sqlText: statements, binds: params })
Related
I have the following SQL statement where i am reading the database to get the records for 1 day. Here is what i tried in pgAdmin console -
SELECT * FROM public.orders WHERE createdat >= now()::date AND type='t_order'
I want to convert this to the syntax of psycopg2but somehow it throws me errors -
Database connection failed due to invalid input syntax for type timestamp: "now()::date"
Here is what i am doing -
query = f"SELECT * FROM {table} WHERE (createdat>=%s AND type=%s)"
cur.execute(query, ("now()::date", "t_order"))
records = cur.fetchall()
Any help is deeply appreciated.
DO NOT use f strings. Use proper Parameter Passing
now()::date is better expressed as current_date. See Current Date/Time.
You want:
query = "SELECT * FROM public.orders WHERE (createdat>=current_date AND type=%s)"
cur.execute(query, ["t_order"])
If you want dynamic identifiers, table/column names then:
from psycopg2 import sql
query = sql.SQL("SELECT * FROM {} WHERE (createdat>=current_date AND type=%s)").format(sql.Identifier(table))
cur.execute(query, ["t_order"])
For more information see sql.
I have the following query with the aws sdk in nodejs and running in aws lamdba that doesn't work when using the parameters array:
executeStatement({
Statement: `select * from "myTable"."myIndex" where "pk" = '?' and "sortKey5" >= 50 ORDER BY "sortKey5" DESC`,
Parameters: [{"S": pk}] })
the same query with the parameter directly inline works
executeStatement({
Statement: `select * from "myTable"."myIndex" where "pk" = 'xxx' and "sortKey5" >= 50 ORDER BY "sortKey5" DESC` })
it's probably the syntax with '?' that is wrong but I couldn't find any sample with an other syntax.
does any one knows how to write the statement so that it uses the parameter?
It seems that, at least in a SELECT statement, one needs to omit the single-quotes around the ?, e.g. foobar = ? rather than foobar = '?'.
So your query would be:
executeStatement({
Statement: `select * from "myTable"."myIndex" where "pk" = ? and "sortKey5" >= 50 ORDER BY "sortKey5" DESC`,
Parameters: [{"S": pk}]
})
I want the statement to search a number of Ids. Like so.
const idsStr = "41, 42, 43";
const sqlStr = `SELECT * FROM table where id IN (${idsStr})`;
session.sql(sqlStr).execute()
But if I use bind method, it only captures the first instance of the string, the remaining values are ignored.
const idsStr = "41, 42, 43";
const sqlStr = `SELECT * FROM table where id IN (?)`;
session.sql(sqlStr).bind(idsStr).execute()
I want to make prepared statement according to the API currently support so as to avoid SQL injection.
This is a limitation of the API (and the X Plugin itself) and a byproduct of the fact that CRUD expressions support an alternative syntax such as IN [41, 42, 43]. Right now, the only way to do what you want is for the SQL statement itself to contain placeholders for all those ids:
const sqlStr = `SELECT * FROM table where id IN (?, ?, ?)
await session.sql(sqlStr).bind(41, 42, 43).execute()
Of course this does not work if you need a dynamic number of elements in the filtering criteria. In that case, you can resort to something like:
const ids = [41, 42, 43]
const sqlStr = `SELECT * FROM table where id IN (${ids.map(() => '?').join(',')})`
await session.sql(sqlStr).bind(ids).execute()
This is probably a bit convoluted but it's the smartest workaround I can think of at the moment.
In the meantime, maybe you can open a bug report at https://bugs.mysql.com/ using the Connector for Node.js category.
Disclaimer: I'm the lead dev of the MySQL X DevAPI Connector for Node.js
I am trying to write a simple query using the pgp-promise library. My original implementation looks like:
var bar = function(orderBy){
var qs = 'select * from mytable order by ${orderBy};';
return db.many(qs,{orderBy:orderBy});
}
...
bar('id').then(...)
But this gives an error of non-integer constant in ORDER BY
I have also tried adding quotes aroung ${orderBy} and adding double quotes to the orderBy paramater to no avail. I have a working solution by doing var qs = 'select * from mytable order by "' + orderBy + '";' though it should be obvious why I don't want code like that in the project.
My question: Is there a way to get pg-promise to build a query with an order by clause that isn't vulnerable to sql injection?
Is there a way to get pg-promise to build a query with an order by clause that isn't vulnerable to sql injection?
The value for ORDER BY clause is an SQL name, and it is to be formatted using SQL Names:
const bar = function(orderBy) {
const qs = 'select * from mytable order by ${orderBy:name}';
return db.many(qs, {orderBy});
}
whereas :raw / ^ is injecting raw text, which is vulnerable to SQL injections when it comes from outside, and to be used only for strings that have been created and pre-formatted inside the server.
I have a Cassandra SELECT query with an IN parameter that I want to run via the Node driver, but can't figure out the syntax.
On the cqlsh console, I can run this select and get a correct result:
SELECT * FROM sourcedata WHERE company_id = 4 AND item_id in (ac943b6f-0143-0e1f-5282-2d39209f3a7a,bff421a0-c465-0434-8806-f128612b6850,877ddb6d-a164-1152-da77-1ec4c4468258);
However, trying to run this query using an array of IDs using the Cassandra Node driver, I get various errors depending on the format. Here's what I've tried:
client.execute("SELECT * FROM sourcedata WHERE company_id = ? AND item_id in (?)", [id, item_ids], function(err, rs) { ...
The error is:
ResponseError: Invalid list literal for item_id of type uuid
With this:
client.execute("SELECT * FROM sourcedata WHERE company_id = ? AND item_id in (?)", [id, item_ids], function(err, rs) { ...
The error is:
ResponseError: line 1:72 no viable alternative at input '[' (...WHERE company_id = 4 AND [item_id] in...)
item_ids is an array of string objects, and they were acquired via a select on another Cassandra table.
This is a working app, and other queries that don't use "SELECT .. IN" work fine.
I can also do make it work the "ugly" way, but would prefer not to:
client.execute("SELECT * FROM sourcedata WHERE company_id = ? AND item_id in (" + item_ids.toString() + ")", [id,], function(err, rs) { ...
You should use IN ? without parenthesis, to provide a list:
const query = 'SELECT * FROM sourcedata WHERE company_id = ? AND item_id in ?';
client.execute(query, [ id, item_ids ], { prepare: true }, callback);