pg_query icon indicating copy to clipboard operation
pg_query copied to clipboard

How to add a column to a query

Open kduraiswami opened this issue 2 years ago • 3 comments

How is it possible to add a column to an existing query after we have converted it into a parsed tree

kduraiswami avatar Jul 05 '23 20:07 kduraiswami

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"

kduraiswami avatar Jul 05 '23 20:07 kduraiswami

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"

kduraiswami avatar Jul 05 '23 21:07 kduraiswami

Thanks for opening the issue as discussed & sharing the solution I've shared via email!

lfittl avatar Jul 05 '23 21:07 lfittl