pg_query
pg_query copied to clipboard
How to add a column to a query
How is it possible to add a column to an existing query after we have converted it into a parsed tree
q = PgQuery.parse("SELECT a FROM tbl")
q.tree.stmts[0].stmt.select_stmt.target_list.push(
PgQuery::Node.new(
res_target: PgQuery::ResTarget.new(
val: PgQuery::Node.new(
column_ref: PgQuery::ColumnRef.new(
fields: [PgQuery::Node.new(string: PgQuery::String.new(sval: 'b'))]
)
)
)
)
)
q.deparse
=> "SELECT a, b FROM tbl"
Note that if you add two elements to the column_ref array it will qualify the name with a period:
column_ref: PgQuery::ColumnRef.new(
fields: [PgQuery::Node.new(string: PgQuery::String.new(sval: 'tbl'))],
fields: [PgQuery::Node.new(string: PgQuery::String.new(sval: 'b'))]
)
q.deparse
=> "SELECT a, tbl.b FROM tbl"
Thanks for opening the issue as discussed & sharing the solution I've shared via email!