Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to add WHERE clause to a query #295

Open
kduraiswami opened this issue Jul 7, 2023 · 1 comment
Open

How to add WHERE clause to a query #295

kduraiswami opened this issue Jul 7, 2023 · 1 comment
Labels

Comments

@kduraiswami
Copy link

kduraiswami commented Jul 7, 2023

I am trying to inject my own where clauses into a SQL statement

I can access the node here:  parsed_query.tree.stmts[0].stmt.select_stmt.where_clause 

next_item = condition_items.shift

I am trying to understand, is it always an :a_expr if it is one where_clause and a :bool_expr if it has an "AND"?

Am I correct that I would have to create my own new where_clause node this:

<PgQuery::Node.new 
    bool_expr: <PgQuery::BoolExpr.new boolop: :AND_EXPR 

And then put my own clauses in there using the and? Would there happen to be any code sample for creating a new where_clause? Thank you for the help!

@lfittl
Copy link
Member

lfittl commented Jul 7, 2023

Yup, you got that right - typically you would have an a_expr in the WHERE clause if its a single expression, and a bool_expr if its multiple expressions. I don't have an example handy, but I think you're on the right track here.

If you want to know all the different variants, you could look at the gram.y file in Postgres, which all of this is based on. Specifically the a_expr rules would be relevant to understand the structure better:

https://github.com/postgres/postgres/blob/REL_15_STABLE/src/backend/parser/gram.y#L14381

For example, the bool_expr gets created here via makeAndExpr:

https://github.com/postgres/postgres/blob/REL_15_STABLE/src/backend/parser/gram.y#L14444
https://github.com/postgres/postgres/blob/REL_15_STABLE/src/backend/parser/gram.y#L18111

@lfittl lfittl added the question label Jan 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants