DynamoDB parameterized PartiQL query with executeStatement - node.js

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}]
})

Related

psycopg2 SELECT query with inbuilt functions

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.

In clause Nodejs snowflake not getting result set

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 })

Adding multiple inputs to query MS SQL Server instance using 'node-mssql' npm package

I would like to query MS SQL Server instance to serve a very simple POST request. I am using nodejs + express. The following code (async version) considers only first input types only and therefore returns error -
let pool = await sql.connect(dbCredentials);
let bookName = "string to be matched" ;
let ranksVal= 10
let result = await pool
.request()
.input("item", sql.VarChar, bookName)
.input("ranksVal", sql.Int , ranksVal)
.query(`select top #ranksVal * from dbTable where book = #item order by counts desc`);
Ideally, the above code should return a result for the following SQL query :
select top 10 * from dbTable where book = "string to be matched" order by counts desc
Alternatively, the following solution works :
let result = await pool
.request()
.input("item", sql.VarChar, bookName)
.query(`select top ${ranksVal} * from dbTable where book = #item order by counts desc`);
But I would like to understand how can we pass multiple values to req.input() method.
Thank you.
To use an expression or a parameter in a TOP values clause you must use parentheses. eg
.query(`select top (#ranksVal) * from dbTable where book = #item order by counts desc`);

How do I properly escape the single quote in node-postgres queries?

I need to execute the following query:
db.query("SELECT * FROM items WHERE name ILIKE '%$1%';", [ query ])
It seems like node-postgres doesn't replace the $1 parameter and I don't know why. My query works if I change the line to:
db.query(`SELECT * FROM items WHERE name ILIKE '%${query}%';`)
But now I have problems when the query contains single quotes (').
Should I replace all single quotes using regex (as in query.replace(/'/g, "''")) (I don't think that's recommended)?
Otherwise, how can I get node-postgres to accept my parameter? I think it has something to do with the encapsulating % symbols. I keep running into the same problem with this issue.
Your placeholder isn't replaced because '%$1%' is an SQL string literal that just happens to look like it contains a $1 placeholder. You can add the percents in JavaScript using string operations:
db.query("SELECT * FROM items WHERE name ILIKE $1", [ `%${query}%` ])
// ---------------------------------------------------^^^^^^^^^^^^
or in SQL using SQL's string operations:
db.query("SELECT * FROM items WHERE name ILIKE '%' || $1 || '%'", [ query ])
// --------------------------------------------^^^^^^----^^^^^^

Query Parameter Format for SELECT ... IN with Cassandra using Node.js Driver

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);

Resources