How to escape it properly? - javascript

I have sql string written with template string syntax:
const sql = `select * from tbl_name where smth=$1 name like '%$2%'`;
const data = await execute(sql, [something, someName]);
I have problems with binding second param - $2 because of single quote. How should I write it properly ?
Error: Error: Query failed: bind message supplies 2 parameters, but prepared statement "" requires 1

I think you're supposed to use wildcards this way:
const sql = `select * from tbl_name where smth=$1 name like $2`;
const data = await execute(sql, [something, `%${someName}%`]);

Related

SQL assign infinite params

Usually we will use SQL queries like below, we will pass params with predifined number $1
queryRunner.query('SELECT * FROM sample_data WHERE code IN ($1)', ['1'])
But I want to pass multiple params without predifined $1. Any way to resolve this?
queryRunner.query('SELECT * FROM sample_data WHERE code IN ($$)', ['1','2','3'])
One approach dynamically builds the IN clause based on the expected number of parameters. Consider:
var params = ['1','2','3'];
var inClause = '?' + ', ?'.repeat(params.length - 1);
var sql = 'SELECT * FROM sample_data WHERE code IN (' + inClause + ')';
console.log(sql);
Once we have a statement with the right number of placeholders, we can simply bind the collection or array with no trouble.

Snowflake Javascript executing more than one sql

Snowflake Javascript executing more than one sql
Multiple SQL statements in a single API call are not supported; use one API call per statement instead.
Used stmt.executemany() instead of execute() but no luck, another error "executemany() is not a function"
Please help
CREATE OR REPLACE PROCEDURE GrantSchemaTablePermissions ()
returns varchar
language javascript
AS
$$
var table_control = " SELECT DISTINCT TABLE_SCHEMA FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA LIKE 'ABCD%' ";
var sql_statement = snowflake.createStatement({sqlText: table_control});
var resultSet = sql_statement.execute();
while (resultSet.next()) {
var key_column_name = resultSet.getColumnValue(1);
var InsertSelect = "USE ROLE OPS; GRANT OWNERSHIP on all tables in schema ABCD." + resultSet.getColumnValue(1) + " TO ROLE LOADER;"
//return InsertSelect
var stmt = snowflake.createStatement(
{
sqlText: InsertSelect
}
);
var res = stmt.execute(); //tried executemany() but no luck
//Cursor.executemany()
return InsertSelect
//return stmt.getSqlText();
}
$$
;
CALL GrantSchemaTablePermissions();
If a function doesn't exist such as executemany, you can write it.
function executemany(statements) {
let statements = statements.split(';');
for (let i = 0; i < statements.length; i++) {
if (statements[i].trim().length > 0)
try {
getResultSet(statements[i]);
} catch (err){
return {Error: err.message, statement: statements[i]};
}
}
}
You can add that to the very bottom of your SP and try running it.
I just wrote that for someone who wanted to put a large section of SQL statements into the body of a stored procedure and run them one at a time.
A couple of notes: 1) This does NOT check for semicolons inside of single quotes. It assumes that a semicolon separates one statement from another. 2) You can use backticks ` to open and close the string. This will let you put the statements in a multi-line block. When I did this with ~20 statements with the semicolons on a line by themselves between lines (the user's preference), it confused the web UI's parser between what was the body of the SP and what was outside it. I fixed that by escaping the single line semicolons with a backslash like this:
GRANT ROLE IDENTIFIER($ROLENAME) TO USER IDENTIFIER($USERNAME)
\;
GRANT ROLE IDENTIFIER($ROLENAME) TO ROLE ACCOUNTADMIN
\;

Using BQ Command line create View with UDF in BigQuery

I want to create View in BigQuery using UDF and BQ command line.
BQ command :
bq query --use_legacy_sql=false --project_id="myProject" \
'CREATE OR REPLACE FUNCTION udfFunc(str STRING) RETURNS STRING LANGUAGE js AS
"""
data = fromLib(str);
return JSON.stringify(data);
""" OPTIONS(library = "gs://<bucket>/lib_file.js");
SELECT'
col1,
col2,
udfFunc(col2) as new_col
FROM
`myProject:mySataset.table`'
I am getting an error
Invalid value: Routine name "udfFunc" missing dataset while
no default dataset is set in the request.
From your query (and the comment on the question), it seems that you only need a temp function during the query time, this is the query that you:
define a temp function which is only visible in this query
use the temp function immediately in the query
CREATE TEMP FUNCTION udfFunc(str STRING) RETURNS STRING LANGUAGE js AS
"""
data = fromLib(str);
return JSON.stringify(data);
""" OPTIONS(library = "gs://<bucket>/lib_file.js");
SELECT
col1,
col2,
udfFunc(col2) as new_col
FROM
`myProject:mySataset.table`

How to use IN with a query parameter?

I have a query like this.
SELECT * FROM player_details where name in ('messi','neymar','suarez','alves')
I want to execute this query in titanium.
I tried like this
var in = ['messi','neymar','suarez','alves'];
db.execute('SELECT * FROM player_details where name in ?',in);
But above code producing error.
How can i add IN and NOT IN condition in sqlite in titanium ?
A single parameter ? replaces a single expression.
When you have four values, you need four parameters:
db.execute('SELECT * FROM player_details where name in (?,?,?,?)', in);
If the length of the array is dynamic try something like this:
var params = ["messi", "neymar", "suarez", "alves"],
qMarks = new Array(params.length).join("?,") + "?";
db.execute("SELECT * FROM player_details WHERE name in (" + qMarks + ");", params);

Node MySQL escape LIKE statement

How do escape a MySQL LIKE statement in node-mysql?
Something along the lines of
"SELECT * FROM card WHERE name LIKE '%" + connection.escape(req.body.search) + "%'"
Results in
'SELECT * FROM card WHERE name LIKE \'%\'hello\'%\''
Which is a syntax error. If I use the alternative syntax of
connection.query("SELECT * FROM card WHERE name LIKE '%?%'", req.body.search, function () {});
Results in a similar syntax error. I've also tried
connection.query("SELECT * FROM card WHERE name LIKE ?", '%' + req.body.search + '%', function () {});
Which just ends up escaping the '%' sign.
Not sure why it's escaping the % in your last example, because that works fine for me:
// lifted from my code:
var value = 'ee20e966289cd7';
connection.query('SELECT * from django_session where session_key like ?', '%' + value + '%', ...)
// Result:
[ { session_key: '713ee20e966289cd71b936084a1e613e', ... } ]
When I turn on debugging in the driver (pass debug:true as argument to mysql.createConnection), it doesn't escape the percent sign:
{ command: 3,
sql: 'SELECT * from django_session where session_key like \'%ee20e966289cd7%\'' }
(it does escape the single quote, but that's for display purposes only)
(using mysql#2.0.0-alpha8)
i've had success with something like
"SELECT * FROM card WHERE name LIKE " + connection.escape('%'+req.body.search+'%')
How about
mysql.format("SELECT * FROM card WHERE name LIKE CONCAT('%', ?, '%')", req.body.search)
?
you can always do
variable = '%${variable}%'
"SELECT * FROM 'table' WHERE ('foo' LIKE ?);",
[variable], callback =>
I had the same problem and solved it like this:
function search(searchTerm) {
let replacement = `'%${searchTerm}%'`;
let sqlStatement = `SELECT * from clients where firstName LIKE ${replacement}`;
const [rows, fields, error] = connection.query(sqlStatement);
return rows;
}
Simple and easy way:
`SELECT * FROM card WHERE name LIKE ` + connection.escape(`%${req.body.search}%`)

Categories