Class: Buhos::SearchParser

Inherits:
Object
  • Object
show all
Defined in:
lib/buhos/search_parser.rb

Defined Under Namespace

Classes: ParsingError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeSearchParser

Returns a new instance of SearchParser.



108
109
110
111
# File 'lib/buhos/search_parser.rb', line 108

def initialize
  Treetop.load "#{File.dirname(__FILE__)}/search_grammar.treetop"
  @parser=::SearchGrammarParser.new
end

Instance Attribute Details

#treeObject (readonly)

Returns the value of attribute tree.



103
104
105
# File 'lib/buhos/search_parser.rb', line 103

def tree
  @tree
end

#tree_processedObject (readonly)

Returns the value of attribute tree_processed.



104
105
106
# File 'lib/buhos/search_parser.rb', line 104

def tree_processed
  @tree_processed
end

Instance Method Details

#clean_tree(root_node) ⇒ Object



126
127
128
129
130
131
# File 'lib/buhos/search_parser.rb', line 126

def clean_tree(root_node)
  return if(root_node.elements.nil?)
  root_node.elements.delete_if{|node| node.text_value=='' or node.text_value=~/^\s+$/}
  root_node.elements.each {|node| self.clean_tree(node) }
  root_node
end

#parse(data) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/buhos/search_parser.rb', line 113

def parse(data)
  #$log.info("PARSING:#{data}")
  @tree=@parser.parse(data)
  if @tree.nil?
    raise ParsingError, "Parse error at offset: #{@parser.index}"
  end


  @tree=clean_tree(@tree)

  @tree_processed=@tree.to_array
end

#to_sql(or_union: false) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
# File 'lib/buhos/search_parser.rb', line 153

def to_sql(or_union:false)
  raise "First parse data" unless @tree
  @tree_processed.map { |f0|
    filter=f0.dup
    next if filter[0]!= :filter
    filter.shift
    field=filter.shift
    elements=filter
    to_sql_elements(field, elements)
  }.join( or_union ? " OR ": " AND ")
end

#to_sql_elements(field, e) ⇒ Object



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/buhos/search_parser.rb', line 133

def to_sql_elements(field,e)
  #p e
  if e.is_a? Array
    if e[0]==:string
      "INSTR(LOWER(#{field}), '#{::Sequel.lit e[1].gsub('"',"").gsub("'","").downcase}')>0 "
    elsif e[0]==:string_q
      "INSTR(LOWER(#{field}), '#{::Sequel.lit(e[1].gsub('"',"").gsub("'","").downcase)}')>0 "
    elsif e[0]==:boolean
      "(#{to_sql_elements(field,e[2])} #{e[1]} #{to_sql_elements(field,e[3])})"
    else
      if e.length==1
        to_sql_elements(field,e[0])
      else
        e.map {|v| "(#{to_sql_elements(field,v)})" }.join" AND "
      end
    end
  else
    "  "
  end
end