pganalyze / pg_query

Ruby extension to parse, deparse and normalize SQL queries using the PostgreSQL query parser
BSD 3-Clause "New" or "Revised" License
790 stars 85 forks source link

What is the best way to check if a query uses a star? #294

Open kduraiswami opened 1 year ago

kduraiswami commented 1 year ago

I am able to go all the way down into a query node like this

parsed_query.tree.stmts[0].stmt.select_stmt.target_list[0].res_target.val.column_ref.fields[0].respond_to?(:a_star)

but in ruby the method respond_to? is too loose because even if a query does not have a star in it the object itself does have this method.

Is this the most efficient way to traverse through the tree and ask if it has a star and try to access the property? Is there a risk this will return true even if it is not the case?

parsed_query.tree.stmts[0].stmt.select_stmt.target_list[0].res_target.val.column_ref.fields[0]["a_star"]

Thanks for the help, please let me know if I can clarify anything

lfittl commented 1 year ago

You can use .node to check the type of the field:

parsed_query = PgQuery.parse("SELECT * FROM test")

parsed_query.tree.stmts[0].stmt.select_stmt.target_list[0].res_target.val.column_ref.fields[0].node
=> :a_star