Class: Groovy::Query

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/groovy/query.rb

Constant Summary collapse

AND =
'+'.freeze
NOT =
'-'.freeze
PER_PAGE =
50.freeze
VALID_QUERY_CHARS =

ESCAPE_CHARS_REGEX = /([()/\])/.freeze

'a-zA-Z0-9_\.,&-'.freeze
REMOVE_INVALID_CHARS_REGEX =
Regexp.new('[^\s' + VALID_QUERY_CHARS + ']').freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, table, options = {}) ⇒ Query

Returns a new instance of Query.



23
24
25
26
27
28
# File 'lib/groovy/query.rb', line 23

def initialize(model, table, options = {})
  @model, @table, @options = model, table, options
  @parameters = options.delete(:parameters) || []
  @sorting = { limit: -1, offset: 0 }
  @default_sort_key = table.is_a?(Groonga::Hash) ? '_key' : '_id'
end

Instance Attribute Details

#parametersObject (readonly)

Returns the value of attribute parameters.



14
15
16
# File 'lib/groovy/query.rb', line 14

def parameters
  @parameters
end

#sortingObject (readonly)

Returns the value of attribute sorting.



14
15
16
# File 'lib/groovy/query.rb', line 14

def sorting
  @sorting
end

Class Method Details

.add_scope(name, obj) ⇒ Object



16
17
18
19
20
21
# File 'lib/groovy/query.rb', line 16

def self.add_scope(name, obj)
  define_method(name) do |*args|
    res = obj.respond_to?(:call) ? instance_exec(*args, &obj) : obj
    self
  end
end

Instance Method Details

#[](index) ⇒ Object



203
204
205
206
207
# File 'lib/groovy/query.rb', line 203

def [](index)
  if r = results[index]
    model.new_from_record(r)
  end
end

#allObject



189
190
191
# File 'lib/groovy/query.rb', line 189

def all
  @records || query
end

#as_json(options = {}) ⇒ Object

def inspect

"<#{self.class.name} #{parameters}>"

end



34
35
36
37
38
# File 'lib/groovy/query.rb', line 34

def as_json(options = {})
  Array.new.tap do |arr|
    each { |record| arr.push(record.as_json(options)) }
  end
end

#each(&block) ⇒ Object



209
210
211
212
213
214
# File 'lib/groovy/query.rb', line 209

def each(&block)
  # records.each { |r| block.call(r) }
  results.each_with_index do |r, index|
    yield model.new_from_record(r)
  end
end

#find(id) ⇒ Object



57
58
59
# File 'lib/groovy/query.rb', line 57

def find(id)
  find_by(_id: id)
end

#find_by(conditions) ⇒ Object



61
62
63
# File 'lib/groovy/query.rb', line 61

def find_by(conditions)
  where(conditions).limit(1).first
end

#first(num = 1) ⇒ Object



225
226
227
228
# File 'lib/groovy/query.rb', line 225

def first(num = 1)
  limit(num)
  num == 1 ? records.first : records
end

#group_by(column) ⇒ Object



180
181
182
183
# File 'lib/groovy/query.rb', line 180

def group_by(column)
  sorting[:group_by] = column
  self
end

#in_batches(of: 1000, from: nil, &block) ⇒ Object



240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/groovy/query.rb', line 240

def in_batches(of: 1000, from: nil, &block)
  puts "of: #{of}"
  sorting[:limit] = of
  sorting[:offset] = from || 0

  while results.any?
    yield to_a
    break if results.size < of

    sorting[:offset] += of
    @records = @results = nil # reset
  end
end

#last(num = 1) ⇒ Object



230
231
232
233
234
235
236
237
238
# File 'lib/groovy/query.rb', line 230

def last(num = 1)
  if sorting[:by]
    get_last(num)
  else # no sorting, so
    sort_by(_id: :desc).limit(num)
    # if last(2) or more, then re-sort by ascending ID
    num == 1 ? records.first : records.sort { |a,b| a.id <=> b.id }
  end
end

#limit(num) ⇒ Object



150
151
152
153
# File 'lib/groovy/query.rb', line 150

def limit(num)
  sorting[:limit] = num
  self
end

#not(conditions = {}) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/groovy/query.rb', line 118

def not(conditions = {})
  case conditions
    when String # "foo:bar"
      parameters.push(NOT + "(#{map_operator(conditions)})")
    when Hash # { foo: 'bar' }
      conditions.each do |key, val|
        if val.is_a?(Range)
          add_param(AND + [key, val.min].join(':<=')) if val.min > 0 # gte
          add_param(AND + [key, val.max].join(':>=')) if val.max # lte, nil if range.max is -1

        elsif val.is_a?(Regexp)
          str = val.source.gsub('/', '_slash_').gsub('(', '_openp_').gsub(')', '_closep_').gsub(REMOVE_INVALID_CHARS_REGEX, '')
          param = val.source[0] == '^' ? ':^' : val.source[-1] == '$' ? ':$' : ':~' # starts with or regexp
          add_param(NOT + [key, str.downcase].join(param)) # regex must be downcase

        elsif val.is_a?(Array) # { foo: [1,2,3] }
          str = "#{key}:!#{val.join(" #{AND}#{key}:!")}"
          add_param(AND + str)

        else
          str = val.nil? || val === false || val.to_s.strip == '' ? "\"\"" : escape_val(val)
          add_param(AND + [key, str].join(':!')) # not
        end
      end
    # when Array # ["foo:?", val]
      # parameters.push(conditions.first.sub('?', conditions.last))
    else
      raise 'not supported'
  end
  self
end

#offset(num) ⇒ Object



155
156
157
158
# File 'lib/groovy/query.rb', line 155

def offset(num)
  sorting[:offset] = num
  self
end

#paginate(page = 1, per_page: PER_PAGE) ⇒ Object



160
161
162
163
164
# File 'lib/groovy/query.rb', line 160

def paginate(page = 1, per_page: PER_PAGE)
  page = 1 if page.to_i < 1
  offset = ((page.to_i)-1) * per_page
  offset(offset).limit(per_page) # returns self
end

#queryObject



185
186
187
# File 'lib/groovy/query.rb', line 185

def query
  self
end

#search(obj) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/groovy/query.rb', line 40

def search(obj)
  obj.each do |col, q|
    # unless model.schema.index_columns.include?(col)
    #   raise "Not an index column, so cannot do fulltext search: #{col}"
    # end
    q.split(' ').each do |word|
      parameters.push(AND + "(#{col}:@#{word})")
    end if q.is_a?(String) && q.strip != ''
  end
  self
end

#select(&block) ⇒ Object



52
53
54
55
# File 'lib/groovy/query.rb', line 52

def select(&block)
  @select_block = block
  self
end

#sizeObject Also known as: count



193
194
195
# File 'lib/groovy/query.rb', line 193

def size
  results.size
end

#sort_by(hash) ⇒ Object

sort_by(title: :asc)



167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/groovy/query.rb', line 167

def sort_by(hash)
  if hash.is_a?(String) || hash.is_a?(Symbol) # e.g. 'title.desc', 'title desc' or :title (asc by default)
    param, dir = hash.to_s.split(/\s|\./)
    hash = {}
    hash[param] = dir || 'asc'
  end

  sorting[:by] = hash.keys.map do |key|
    { key: key.to_s, order: hash[key] }
  end
  self
end

#to_aObject



199
200
201
# File 'lib/groovy/query.rb', line 199

def to_a
  records
end

#total_entriesObject



220
221
222
223
# File 'lib/groovy/query.rb', line 220

def total_entries
  results # ensure query has been run
  @total_entries
end

#update_all(attrs) ⇒ Object



216
217
218
# File 'lib/groovy/query.rb', line 216

def update_all(attrs)
  each { |r| r.update_attributes(attrs) }
end

#where(conditions = nil) ⇒ Object

groonga.org/docs/reference/grn_expr/query_syntax.html TODO: support match_columns (search value in two or more columns)



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/groovy/query.rb', line 75

def where(conditions = nil)
  case conditions
    when String # "foo:bar"
      add_param(AND + "(#{map_operator(handle_timestamps(conditions))})")
    when Hash # { foo: 'bar' } or { views: 1..100 }
      conditions.each do |key, val|
        if val.is_a?(Range)
          add_param(AND + [key, val.min].join(':>=')) if val.min # lte
          add_param(AND + [key, val.max].join(':<=')) if val.max # gte

        elsif val.is_a?(Regexp)
          str = val.source.gsub('/', '_slash_').gsub('(', '_openp_').gsub(')', '_closep_').gsub(REMOVE_INVALID_CHARS_REGEX, '')
          param = val.source[0] == '^' ? ':^' : val.source[-1] == '$' ? ':$' : ':~' # starts with or regexp
          add_param(AND + [key, str.downcase].join(param)) # regex must be downcase

        elsif val.is_a?(Array) # { foo: [1,2,3] }
          str = "#{key}:#{val.join(" OR #{key}:")}"
          add_param(AND + str)

        elsif val.is_a?(Time)
           # The second, specify the timestamp as string in following format:
           # “(YEAR)/(MONTH)/(DAY) (HOUR):(MINUTE):(SECOND)”

          # date_str = val.utc.strftime("%Y/%m/%d %H\:%M\:%S")
          date_str = val.strftime("%Y/%m/%d %H\:%M\:%S")
          str = "#{key}:#{date_str}"
          add_param(AND + str)

        else
          str = val.nil? || val === false || val.to_s.strip == '' ? "\"\"" : escape_val(val)
          add_param(AND + [key, str].join(':'))
        end
      end
    # when Array # ["foo:?", val]
      # parameters.push(conditions.first.sub('?', conditions.last))
    when NilClass
      # doing where.not probably
    else
      raise 'not supported'
  end
  self
end