Class: DB::Model::Statement::Select
- Inherits:
-
Object
- Object
- DB::Model::Statement::Select
- Defined in:
- lib/db/model/statement/select.rb
Instance Method Summary collapse
- #append_to(statement, limit: @limit) ⇒ Object
- #apply(context, result, cache = nil) ⇒ Object
- #each(context, cache = nil) ⇒ Object
- #first(context, count, cache = nil) ⇒ Object
-
#initialize(source, fields: nil, where: nil, limit: nil) ⇒ Select
constructor
A new instance of Select.
- #to_a(context, cache = nil) ⇒ Object
- #to_sql(context) ⇒ Object
Constructor Details
#initialize(source, fields: nil, where: nil, limit: nil) ⇒ Select
Returns a new instance of Select.
27 28 29 30 31 32 |
# File 'lib/db/model/statement/select.rb', line 27 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
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/db/model/statement/select.rb', line 34 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
68 69 70 71 72 73 74 |
# File 'lib/db/model/statement/select.rb', line 68 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
76 77 78 79 80 81 82 83 84 85 |
# File 'lib/db/model/statement/select.rb', line 76 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
87 88 89 90 91 92 93 94 95 |
# File 'lib/db/model/statement/select.rb', line 87 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
60 61 62 63 64 65 66 |
# File 'lib/db/model/statement/select.rb', line 60 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
56 57 58 |
# File 'lib/db/model/statement/select.rb', line 56 def to_sql(context) self.append_to(context) end |