Class: Devlin::Query

Inherits:
Object
  • Object
show all
Defined in:
lib/devlin/query.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent, q) ⇒ Query

Returns a new instance of Query.



5
6
7
8
9
10
11
12
13
14
# File 'lib/devlin/query.rb', line 5

def initialize(parent, q)
  @parent = parent
  @query = YAML.load(q)
  @scope = parent.scope(query['scope'])
  @scope_name = query['scope']
  @select = query['select']
  @conditions = query['conditions']
  @group = query['group']
  @order = query['order']
end

Instance Attribute Details

#queryObject (readonly)

Returns the value of attribute query.



3
4
5
# File 'lib/devlin/query.rb', line 3

def query
  @query
end

#scopeObject (readonly)

Returns the value of attribute scope.



3
4
5
# File 'lib/devlin/query.rb', line 3

def scope
  @scope
end

#scope_nameObject (readonly)

Returns the value of attribute scope_name.



3
4
5
# File 'lib/devlin/query.rb', line 3

def scope_name
  @scope_name
end

Instance Method Details

#conditionsObject

def select



49
50
51
# File 'lib/devlin/query.rb', line 49

def conditions
  @conditions || {}
end

#groupObject

def conditions



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

def group
  @group || []
end

#orderObject

def group



57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/devlin/query.rb', line 57

def order
  res = {}
  (@order || {}).each do |key, value|
    res[key] = case value.to_s.downcase
               when 'desc'
                 'DESC'
               else
                 'ASC'
               end
  end
  res
end

#resultObject

This method returns the resulting relation to calculate the given query



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/devlin/query.rb', line 18

def result
  res = @scope.relation
  res = res.select(self.select.map { |c| @scope.column(c).select_definition })
  self.conditions.each do |col, val|
    col, op = col.split('.')
    res = case op
    when 'g'
      res.where(["#{@scope.column(col).definition}>?", val])
    when 'geq'
      res.where(["#{@scope.column(col).definition}>=?", val])
    when 'l'
      res.where(["#{@scope.column(col).definition}<?", val])
    when 'leq'
      res.where(["#{@scope.column(col).definition}<=?", val])
    when 'in'
      res.where(["#{@scope.column(col).definition} IN (?)", val])
    else
      res.where(["#{@scope.column(col).definition}=?", val])
    end
  end
  res = res.group(self.group.map { |c| @scope.column(c).definition })
  self.order.each do |col, val|
    res = res.order("#{@scope.column(col).definition} #{val}")
  end
  res
end

#selectObject

def result



45
46
47
# File 'lib/devlin/query.rb', line 45

def select
  @select or raise "No selection columns given"
end