does something like followin exists? ('''select * from TABLE where ? in FIELD''',(VAR)) - python-3.x

does something like followin exist?
('''select * from TABLE where ? in FIELD''',(VAR))
I need to select all table rows where FIELD just contains the text of VAR (so not needed FIELD=VAR)
I'm using python3 and sqlite3.

You can use the function INSTR():
sql = "SELECT * FROM tablename WHERE INSTR(FIELD, ?)"
or the operator LIKE:
sql = "SELECT * FROM tablename WHERE FIELD LIKE '%' || ? || '%'"
to get the rows that contain the value of VAR:
execute(sql, (VAR,))

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.

Query which performs like and in operators

I am trying to run a Athena query which will match multiple values for a column. So the query is like this. So here the event name will be 'n' number of events in string with comma seperated.
eventname = "ExecuteQuery, ErrorOccured, RunningStatus, AbortStatus"
SELECT * FROM "db_name"."table_name" where account='123456' and year='2010' and month='04' and day = '1'
and (eventname like '%Execute%' or eventname like'%Error%' or eventname like '%Running%' or eventname like '%...%')
So basically I want query to perform LIKE and IN operator
How can I write the sql query with operator which has n number of events.
I tried with 'IN' operator. But didnt get desired output.
SELECT * FROM "db_name"."table_name" where account='123456' and year='2010' and month='04' and day = '1'
and (eventname in ('Execute%', '%Error%', 'Running%')
Also tried with below query and it throws error as Function any not registered
SELECT * FROM "db_name"."table_name" where account='123456' and and year='2020' and month='04' and day = '1'
and eventname LIKE ANY (ARRAY['%Execute%', 'Error%']);
you could use regexp_like, for example
select * from table where regexp_like(eventname, 'Execute|Error|Running' )

How to get a word from a sentence using regex nodejs

I have a use case where I need to get the table name from my sql query
like suppose I have
select * from schema.tableName
OR
select * from schema.tableName where id = 123
OR
select column1, column2, column3 from schema.tableName where id = 123
In need to get 'schema.tableName' from the sql query in above cases , how it can be done using regex in Node.
I have tried (?<=from)(\s+\w+\b)
but I am getting warning that look behind is not supported in javascript.
A RegEx that will match the table name from queries similar to the ones you provided as examples can be written easily.
Try this RegEx: /select .* from ([^ ]*)/i
See the complete code below:
var sql1 = "select * from tableName";
var sql2 = "select * from tableName where id = 123";
var sql3 = "select column1, column2, column3 from tableName where id = 123";
var t1 = sql1.match(/select .* from ([^ ]*)/i);
var t2 = sql2.match(/select .* from ([^ ]*)/i);
var t3 = sql3.match(/select .* from ([^ ]*)/i);
console.log(t1[1]);
console.log(t2[1]);
console.log(t3[1]);
However, the RegEx will get complex if you would need to match table name from all the possible valid select queries.
EDIT
You can use a stripped down version of the above RegEx to get the same results.
/ from ([^ ]*)/i
Maybe something like this:
var query = "select column1, column2, column3 from schema.tableName where id = 123"
var result = query.match(/from\s+([\.\w]+)+\s+/i);
var tableName = null;
if (result && result.length > 1) {
tableName = result[1];
}

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

OrmLite and Common table expressions

I'm trying to run a similar query:
sql = #"with t(id) as (select 1 )
select * from Project
where id > (select id from t)";
var projects = this.Db.Query<Project>(sql).ToArray();
For some reason the OrmLite decides to treat the sql as as "where" clause, so what ends up running is something like this:
select field1, field2 from project where with t(id) .....
Does it look for a "select" at a starting position of the query ?
Short of creating a view - is there a way to run query with CTE ?
Use the db.Sql* API's for raw SQL Queries, e.g:
var projects = db.SqlList<Project>(sql);

Resources