Class: DB::Model::Statement::Select

Inherits:
Object
  • Object
show all
Defined in:
lib/db/model/statement/select.rb

Instance Method Summary collapse

Constructor Details

#initialize(source, fields: nil, where: nil, limit: nil) ⇒ Select

Returns a new instance of Select.



10
11
12
13
14
15
# File 'lib/db/model/statement/select.rb', line 10

def initialize(source, fields: nil, where: nil, limit: nil)
  @source = source
  @fields = fields
  @where = where
  @limit = limit
end

Instance Method Details

#append_to(statement, limit: @limit) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/db/model/statement/select.rb', line 17

def append_to(statement, limit: @limit)
  statement = statement.clause("SELECT")
  
  if @fields
    @fields.append_to(statement)
  else
    statement.clause("*")
  end
  
  statement.clause("FROM")
  statement.identifier(@source.type)
  
  if @where
    statement.clause "WHERE"
    @where.append_to(statement)
  end
  
  limit&.append_to(statement)
  
  return statement
end

#apply(context, result, cache = nil) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/db/model/statement/select.rb', line 51

def apply(context, result, cache = nil)
  keys = result.field_names.map(&:to_sym)
  
  result.map do |row|
    @source.new(context, keys.zip(row).to_h, cache)
  end
end

#each(context, cache = nil) ⇒ Object



59
60
61
62
63
64
65
66
67
68
# File 'lib/db/model/statement/select.rb', line 59

def each(context, cache = nil)
  to_sql(context).call do |connection|
    result = connection.next_result
    keys = result.field_names.map(&:to_sym)
    
    result.each do |row|
      yield @source.new(context, keys.zip(row).to_h, cache)
    end
  end
end

#first(context, count, cache = nil) ⇒ Object



70
71
72
73
74
75
76
77
78
# File 'lib/db/model/statement/select.rb', line 70

def first(context, count, cache = nil)
  limit = @limit&.first(count) || Limit.new(count)
  
  append_to(context, limit: limit).call do |connection|
    result = connection.next_result
    
    return apply(context, result, cache)
  end
end

#to_a(context, cache = nil) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/db/model/statement/select.rb', line 43

def to_a(context, cache = nil)
  to_sql(context).call do |connection|
    result = connection.next_result
    
    return apply(context, result, cache)
  end
end

#to_sql(context) ⇒ Object



39
40
41
# File 'lib/db/model/statement/select.rb', line 39

def to_sql(context)
  self.append_to(context)
end