Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Parameter Names from SQL Query

The backend is PostgreSQL server 9.1.

I am trying to build AdHoc XML reports. The report files will contain SQL queries, all of which must start with a SELECT statement. The SQL queries will have parameters. Depending upon the data type of the associated columns, these parameters will be accordingly presented to the user to provide value(s).

A rought SQL query:

SELECT * FROM customers
WHERE 
(
    customers.customer_code=@customer_code AND customers.location=@location
    AND customers.type=
    (
        SELECT type from types
        WHERE types.code=@type_code
        AND types.is_active = @type_is_active
    )
    AND customers.account_open_date BETWEEN @start_date AND @end_date
)
OR customers.flagged = @flagged;

I want to get list of the column names and parameters from the query string and put them into a string array and process later.

I am able to match only the parameters using the following regular expression:

@(?)(?<parameter>\w+)

Expected Matches:

customers.customer_code=@customer_code
customers.location=@location
types.code=@type_code
types.is_active = @type_is_active
customers.account_open_date BETWEEN @start_date AND @end_date
customers.flagged = @flagged

How to to match "@Parameter", "=", and "BETWEEN" right away?

like image 589
Nick Binnet Avatar asked Aug 01 '13 17:08

Nick Binnet


1 Answers

I know it's a little late, but for future researches' sake:

I think this Regex serves your purpose:

(\w+\.\w+(?:\s?\=\s?\@\w+|\sBETWEEN\s\@\w+\sAND\s\@\w+))

Check this Regex101 fiddle here, and read carefully the explanation for each part of it.

Basically, it first looks for your customer.xxx_yyy columns, and then either for = @variable or BETWEEN @variable1 AND @variable2.

Captured groups:

MATCH 1
1.  [37-75] 
`customers.customer_code=@customer_code`

MATCH 2
1.  [80-108]    
`customers.location=@location`

MATCH 3
1.  [184-205]   
`types.code=@type_code`

MATCH 4
1.  [218-251]   
`types.is_active = @type_is_active`

MATCH 5
1.  [266-327]   
`customers.account_open_date BETWEEN @start_date AND @end_date`

MATCH 6
1.  [333-361]   
`customers.flagged = @flagged`
like image 176
everton Avatar answered Oct 05 '22 00:10

everton