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



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

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

#allObject



191
192
193
# File 'lib/groovy/query.rb', line 191

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



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

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



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

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

#group_by(column) ⇒ Object



182
183
184
185
# File 'lib/groovy/query.rb', line 182

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

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



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

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



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

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



152
153
154
155
# File 'lib/groovy/query.rb', line 152

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

#not(conditions = {}) ⇒ Object



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
149
150
# File 'lib/groovy/query.rb', line 120

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



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

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

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



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

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



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

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



195
196
197
# File 'lib/groovy/query.rb', line 195

def size
  results.size
end

#sort_by(hash) ⇒ Object

sort_by(title: :asc)



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

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



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

def to_a
  records
end

#total_entriesObject



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

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

#update_all(attrs) ⇒ Object



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

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
# 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|
        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