pganalyze / pg_query_go

Go library to parse and normalize SQL queries using the PostgreSQL query parser

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Question] can I use it to modify the limit clause of the given query?

vishalsngl opened this issue · comments

e.g. select * from sample limit 50 can be modified to select * from sample limit 100
Now this is just a simple case, I would like to achieve the same for complex queries and sub-queries, the intention is just to modify the limit for the outermost select query.

@vishalsngl Sure - that is what the deparser is for.

FWIW, it takes a bit of effort to walk the tree in Go currently, but technically anything is possible. For reference, here is an example of doing a tree walk to modify a statement in the Ruby library: https://github.com/pganalyze/pg_query#walking-the-parse-tree

If you are truly only interested in the top-level query, you may be able to just check whether the top-level statement is a SelectStmt, and then adjust the limit there. That should be easy without doing a tree walk.

@lfittl thanks for the quick response. Yes, I'm only interested in the top level query. So I was able to make some progress based on your suggestion

if tree.Stmts[0].Stmt.GetSelectStmt().GetLimitCount() != nil { // modify limit clause using pg_query_go existingLimit := tree.Stmts[0].Stmt.GetSelectStmt().GetLimitCount() tree.Stmts[0].Stmt.GetSelectStmt().LimitCount = pg_query.MakeAConstIntNode(int64(newLimit), existingLimit.GetAConst().Location) }

I'm still trying to figure out how to add a new limit clause if it's not there already, basically I want to add an else case to the above code. For a quick solution I'm simply appending a new limit clause to my raw string query, but I would like to do it using pg_query_go if possible.

Pardon me if this is a noob question, I'm a bit new to the Go world.

@lfittl On the similar lines, I've another requirement where I want to add/modify WHERE clause on the top-level Select query.

@vishalsngl Unfortunately I don't have the time available to provide more examples (we don't use the deparser with Go ourselves much currently, so coming up with examples is non-trivial).

If you want something easier to work with, the Ruby library might be a better choice, since there its a bit easier to work with the structs. You can also see the truncate function for some ideas on how to modify the tree there: https://github.com/pganalyze/pg_query/blob/main/lib/pg_query/truncate.rb

Okay @lfittl, thanks for the help. I'll check out the example and see if it helps me in writing the Go code for my use-case.