File: deparse.rb

package info (click to toggle)
ruby-pg-query 5.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 18,248 kB
  • sloc: ansic: 149,767; ruby: 865; makefile: 3
file content (28 lines) | stat: -rw-r--r-- 1,016 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
module PgQuery
  class ParserResult
    def deparse
      PgQuery.deparse(@tree)
    end
  end

  # Reconstruct all of the parsed queries into their original form
  def self.deparse(tree)
    if PgQuery::ParseResult.method(:encode).arity == 1
      PgQuery.deparse_protobuf(PgQuery::ParseResult.encode(tree)).force_encoding('UTF-8')
    elsif PgQuery::ParseResult.method(:encode).arity == -1
      PgQuery.deparse_protobuf(PgQuery::ParseResult.encode(tree, recursion_limit: 1_000)).force_encoding('UTF-8')
    else
      raise ArgumentError, 'Unsupported protobuf Ruby API'
    end
  end

  # Convenience method for deparsing a statement of a specific type
  def self.deparse_stmt(stmt)
    deparse(PgQuery::ParseResult.new(version: PG_VERSION_NUM, stmts: [PgQuery::RawStmt.new(stmt: PgQuery::Node.from(stmt))]))
  end

  # Convenience method for deparsing an expression
  def self.deparse_expr(expr)
    deparse_stmt(PgQuery::SelectStmt.new(where_clause: expr, op: :SETOP_NONE)).gsub('SELECT WHERE ', '')
  end
end