class HumanQL::PostgreSQLGenerator

Generate query strings suitable for passing to PostgreSQL's to_tsquery function, from a HumanQL abstract syntax tree (AST).

In order to guarantee valid output for any human input, the AST should be created using PostgreSQLCustomParser and normalized via TreeNormalizer (with minimal defaults).

Any scope's provided in the parser should have been handled and stripped out of the AST, as PostgreSQL is not expected to have a direct equivalent in tsquery syntax.

Constants

AND
NEAR
NOT
OR

Public Instance Methods

generate(node) click to toggle source

Given the root node of the AST, return a string in PostgreSQL tsquery syntax.

# File lib/human-ql/postgresql_generator.rb, line 45
def generate(node)
  op,*args = node
  if ! node.is_a?(Array)
    op
  elsif args.empty?
    nil
  else
    case op
    when :and
      terms_join(args, AND)
    when :or
      pwrap(terms_join(args, OR))
    when :not
      if args[0].is_a?(Array)
        NOT + pwrap(generate(args[0]))
      else
        NOT + args[0]
      end
    when :phrase
      terms_join(args, NEAR)
    else
      raise "Unsupported op: #{node.inspect}"
    end
  end
end

Protected Instance Methods

pwrap(inner) click to toggle source
# File lib/human-ql/postgresql_generator.rb, line 77
def pwrap(inner)
  '(' + inner + ')'
end
terms_join(args, op) click to toggle source
# File lib/human-ql/postgresql_generator.rb, line 73
def terms_join(args, op)
  args.map { |a| generate(a) }.join(op)
end