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.



25
26
27
28
29
30
# File 'lib/groovy/query.rb', line 25

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.



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

def parameters
  @parameters
end

#sortingObject (readonly)

Returns the value of attribute sorting.



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

def sorting
  @sorting
end

Class Method Details

.add_scope(name, obj) ⇒ Object



18
19
20
21
22
23
# File 'lib/groovy/query.rb', line 18

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



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

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

#allObject



197
198
199
# File 'lib/groovy/query.rb', line 197

def all
  @records || query
end

#as_json(options = {}) ⇒ Object

def inspect

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

end



36
37
38
39
40
# File 'lib/groovy/query.rb', line 36

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

#each(&block) ⇒ Object



217
218
219
220
221
222
# File 'lib/groovy/query.rb', line 217

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



59
60
61
# File 'lib/groovy/query.rb', line 59

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

#find_by(conditions) ⇒ Object



63
64
65
# File 'lib/groovy/query.rb', line 63

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

#first(num = 1) ⇒ Object



233
234
235
236
# File 'lib/groovy/query.rb', line 233

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

#group_by(column) ⇒ Object



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

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

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



248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/groovy/query.rb', line 248

def in_batches(of: 1000, from: nil, &block)
  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



238
239
240
241
242
243
244
245
246
# File 'lib/groovy/query.rb', line 238

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



158
159
160
161
# File 'lib/groovy/query.rb', line 158

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

#not(conditions = {}) ⇒ Object



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/groovy/query.rb', line 126

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



163
164
165
166
# File 'lib/groovy/query.rb', line 163

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

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



168
169
170
171
172
# File 'lib/groovy/query.rb', line 168

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



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

def query
  self
end

#search(obj) ⇒ Object



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

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



54
55
56
57
# File 'lib/groovy/query.rb', line 54

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

#sizeObject Also known as: count



201
202
203
# File 'lib/groovy/query.rb', line 201

def size
  results.size
end

#sort_by(hash) ⇒ Object

sort_by(title: :asc)



175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/groovy/query.rb', line 175

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



207
208
209
# File 'lib/groovy/query.rb', line 207

def to_a
  records
end

#total_entriesObject



228
229
230
231
# File 'lib/groovy/query.rb', line 228

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

#update_all(attrs) ⇒ Object



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

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)



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
117
118
119
120
121
122
123
124
# File 'lib/groovy/query.rb', line 77

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|
        case val
        when Model
          raise "Object not persisted yet!" unless val.persisted?
          str = "#{key}:#{val.id}"
          add_param(AND + str)

        when Range
          add_param(AND + [key, val.min].join(':>=')) if val.min # lte
          add_param(AND + [key, val.max].join(':<=')) if val.max # gte

        when 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

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

        when 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