Query Parsing

From PostgreSQL wiki
Jump to: navigation, search

Query Parsing

There are quite a few use cases where it'd be of great help if you could access the query tree Postgres uses internally for processing queries.

For example, when you need to do non-trivial operations on queries, like:

  • Filtering out queries containing specific tables
  • Reformatting & pretty-printing query strings
  • Modifying or removing parts of the query string, e.g. rename a column

The Postgres documentation gives a good overview how query execution is handled and what the intermediate tree representations of a query string are.


Using Postgres internals

Postgres already offers tooling to create a query tree from a given query string.

raw_parser takes a query statement as input and will return a parse tree. This parse tree can then be pretty-printed by using nodeToString.

An example can be seen here, this can be easily implemented in a Postgres extension as well as seen here.

   SELECT * FROM foo where bar = 42 ORDER BY id DESC LIMIT 23;
      :distinctClause <> 
      :intoClause <> 
      :targetList (
         :name <> 
         :indirection <> 
            :fields (
            :location 7
         :location 7
      :fromClause (
         :schemaname <> 
         :relname foo 
         :inhOpt 2 
         :relpersistence p 
         :alias <> 
         :location 14
         :name ("=")
            :fields ("bar")
            :location 24
            :val 42 
            :location 30
         :location 28
      :groupClause <> 
      :havingClause <> 
      :windowClause <> 
      :valuesLists <> 
      :sortClause (
            :fields ("id")
            :location 42
         :sortby_dir 2 
         :sortby_nulls 0 
         :useOp <> 
         :location -1
      :limitOffset <> 
         :val 23 
         :location 56
      :lockingClause <> 
      :withClause <> 
      :op 0 
      :all false 
      :larg <> 
      :rarg <>

This approach isn't without caveats though, since the nodeToString code is used only for printing out planned query trees. These trees are rewritten to contain only contain nodes ultimately needed by the Executor. This means that all nodes not expected in later stages of query execution can't be printed, for example INSERT/UPDATE/DELETE nodes - since later on these are all aggregated in a ModifyStmt node.


pg_query is a Ruby gem which can generate query trees in JSON representation. It accomplishes this by using a patched Postgres version which on one hand addresses the shortcomings outlined above, and on the other hand it provides a new function nodeToJSONString which turns a query tree into a JSON representation instead of the native Postgres format.

The Ruby bindings are just glue code around the Postgres code. More information can be found in this blog post

    @query="SELECT * FROM foo where bar = 42 ORDER BY id DESC LIMIT 23;",
              "val"=>{"COLUMNREF"=>{"fields"=>[{"A_STAR"=>{}}], "location"=>7}},
             "lexpr"=>{"COLUMNREF"=>{"fields"=>["bar"], "location"=>24}},
             "rexpr"=>{"A_CONST"=>{"val"=>42, "location"=>30}},
             {"node"=>{"COLUMNREF"=>{"fields"=>["id"], "location"=>42}},
         "limitCount"=>{"A_CONST"=>{"val"=>23, "location"=>56}},


pgpool-II is a middleware for Postgresql which in it's simplest use-case is an connection broker between client and database servers.

To be able to do advanced query routing it needs to understand the queries it gets sent form the query. To be able to do that, the pgpool project forked the parser and implemented their own node outFuncs to be able to recreated a query string from a given query tree.

If you want to create your own as correct as possible Postgres query pretty-printer this might be a good starting point.


sqlparse is a Python module which implements a non-validating SQL parser suitable for parsing, splitting and formatting SQL statements. It provides the backbone for http://sqlformat.org/ - a SQL pretty printer.

Introspection into the queries is quite limited and since it's not specifically targeted at Postgres it's capabilities are quite limited when it comes to drilling down into query trees.


To make life easier for people using query trees the following things need to be addressed in Postgres core:

  • Implement outFuncs for all node types and not only those seen in a post-planning state.
  • Ship alternate outFuncs suitable for generating e.g. JSON trees instead of the native Postgres tree format.