How to get a word from a sentence using regex nodejs - node.js

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

Related

How to use a date in Python variable with a SQL query in pandas

I have a python code which looks like this( snippets)
.....
lastCheckTime = datetime.datetime.strptime(strDate, "%Y-%m-%d %H:%M:%S")
connection_url = URL.create("mssql+pyodbc", query={"odbc_connect": connection_string})
engine = create_engine(connection_url)
sqldf = pd.read_sql_query(
"""\
SELECT * from ABC, XYZ, LMN, PQR
WHERE ABC.id = XYZ.id
AND XYZ.TO_CLASS != '827'
ORDER BY ABC.creation_date desc
""",
engine,
)
This works fine but I want to execute the query with a check for date ABC.creation_date > lastCheckTime.
Unable to figure out how to execute this query.
The original query was in oracle . Please see below how it looks.
What should be the equivalent of to_char(ABC.creation_date) > :lastCheckTime in my query
SELECT * from ABC, XYZ, LMN, PQR
WHERE ABC.id = XYZ.id
AND XYZ.TO_CLASS != '827'
AND to_char(ABC.creation_date) > :lastCheckTime
ORDER BY PCREATION_DATE desc
The query should be as follows for it to work, use ? as placeholder and name the variable in params
sqldf = pd.read_sql_query("SELECT * from ABC, XYZ, LMN, PQR WHERE ABC.id = XYZ.id AND XYZ.TO_CLASS != '827'AND ABC.creation_date > ? ORDER BY ABC.creation_date desc", engine,params={lastCheckTime})

does something like followin exists? ('''select * from TABLE where ? in FIELD''',(VAR))

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

How to get table names from Presto query using presto-parser?

Not able to extract table names used within with clause, I'm using presto-parser version 0.226.
SqlParser sqlParser = new SqlParser();
String sql = "WITH dataset AS ( SELECT ROW('Bob', 38) AS users from tabb ) SELECT * FROM dataset";
Query query = (Query)sqlParser.createStatement(sql, ParsingOptions.builder().build());
QuerySpecification body = (QuerySpecification)query.getQueryBody();
System.out.println("From = " + body.getFrom().get());
/* Output
From = Table{dataset}
*/
Expected output
From = Table{dataset, tabb}

Pyspark : Dynamically prepare pyspark-sql query using parameters

What are the different ways to dynamicaly bind parameters and prepare pyspark-sql statament.
Example:
Dynamic Query
query = '''SELECT column1, column2
FROM ${db_name}.${table_name}
WHERE column1 = ${filter_value}'''
Above dynamic query have ${db_name}, ${table_name} and ${filter_value} variables, These variables will get values from run time parameters.
Parameter Details:
db_name = 'your_db_name'
table_name = 'your_table_name'
filter_value = 'some_value'
Expected Query after Binding Parameters in Dynamic Query
SELECT column1, column2
FROM your_db_name.your_table_name
WHERE column1 = some_value
Here are few options to prepare pyspark-sql through binding parameter.
Option#1 - Using String Interpolation / f-Strings (Python 3.6+)
db_name = 'your_db_name'
table_name = 'your_table_name'
filter_value = 'some_value'
query = f'''SELECT column1, column2
FROM {db_name}.{table_name}
WHERE column1 = {filter_value}'''
Option#2 - Using String Formatting (str.format)
query = '''SELECT column1, column2
FROM {}.{}
WHERE column1 = {}'''
db_name = 'your_db_name'
table_name = 'your_table_name'
filter_value = 'some_value'
query.format(db_name, table_name, filter_value)
Option#3 - Using Template String
query = '''SELECT column1, column2
FROM ${db_name}.${table_name}
WHERE column1 = ${filter_value}'''
db_name = 'your_db_name'
table_name = 'your_table_name'
filter_value = 'some_value'
from string import Template
t = Template(query)
t.substitute(db_name=db_name, table_name=table_name, filter_value=filter_value)
String Interpolation/f-Strings (Option#1) is recommended if you have
python 3.6+ else use String Formatting str.format (Option#2)
Template String are more useful to handle user supplied string
(Option#3)

Insert the data into the remote table from # temp table in the stored procedure

I have a stored procedure in AZURE SQL database.In that there is a requirement to insert the records into the remote table from #temp table.
As xxxx_table is in the remote database used sp_execute_remote.
below is the scenario:
Create Procedure SP1 parameter1, Parameter2
As
select Distinct B.column1, B.Column2
into #A
from (Query1
Union
Query2) B
if (select count(1) from #A) > 0
Begin
Exec sp_execute_remote #data_source_name = N'Remotedatabase',
#stmt = N'INSERT INTO [dbo].[xxxx_table]
SELECT DISTINCT
'xxx' AS 'column1',
'xxx as 'Column2',
'xxx' AS 'Column3',
'xxx' AS 'Column4',
'xxx' AS Column4
FROM #A A INNER JOIN table1 on A.Column1 = Table1.Column2'
End
)
Getting the syntax error as below:
Incorrect syntax near 'xxx'.
Where am i going wrong? or let me know if there is another way to achieve this.
If you need to dynamically build a string in SQL single-quote the whole sentence, or use 'some text' + 'another text' to concat sentences. If you must add single quote use a double single quote ''
Example:
DECLARE #param1 int;
DECLARE #param1 VARCHAR(10);
SET #param1 = 10;
SET #param2 = 'CCDOS87'
#Stmt = 'SELECT Field1 FROM TableName WHERE Field1 = '
+ CAST(#param1 AS VARCHAR(100))
+ ' AND Field1 = '''
+ param2
+ ''''; <- This is a single '
#stmt = N'INSERT INTO [dbo].[Error_table]
SELECT DISTINCT
xxx AS column1,
xxx as Column2,
xxx AS Column3,
xxx AS Column4,
xxx AS Environment
FROM #A A INNER JOIN table1 on A.Column1 = Table1.Column2'
update
If your tables are in different databases but in the same server use:
INSERT INTO SERVER.SCHEMA.TABLE_NAME
SELECT Something
FROM SERVER.SCHEMA.TABLE_NAME

Resources