Class: OccamsRecord::Query
- Inherits:
-
Object
- Object
- OccamsRecord::Query
- Includes:
- Batches, EagerLoaders::Builder
- Defined in:
- lib/occams-record/query.rb
Overview
Represents a query to be run and eager associations to be loaded. Use OccamsRecord.query to create your queries instead of instantiating objects directly.
Instance Attribute Summary collapse
- #model ⇒ ActiveRecord::Base readonly
-
#scope ⇒ ActiveRecord::Relation
readonly
Scope for building the main SQL query.
Instance Method Summary collapse
-
#each {|OccamsRecord::Results::Row| ... } ⇒ Object
If you pass a block, each result row will be yielded to it.
-
#first ⇒ OccamsRecord::Results::Row
Run the query and return the first result (which could be nil).
-
#initialize(scope, use: nil, query_logger: nil, eager_loaders: []) { ... } ⇒ Query
constructor
Initialize a new query.
-
#run ⇒ Array<OccamsRecord::Results::Row>
(also: #to_a)
Run the query and return the results.
Methods included from EagerLoaders::Builder
#eager_load, #eager_load_many, #eager_load_one
Methods included from Batches
Constructor Details
#initialize(scope, use: nil, query_logger: nil, eager_loaders: []) { ... } ⇒ Query
Initialize a new query.
51 52 53 54 55 56 57 58 |
# File 'lib/occams-record/query.rb', line 51 def initialize(scope, use: nil, query_logger: nil, eager_loaders: [], &eval_block) @model = scope.klass @scope = scope @eager_loaders = eager_loaders @use = use @query_logger = query_logger instance_eval(&eval_block) if eval_block end |
Instance Attribute Details
#model ⇒ ActiveRecord::Base (readonly)
35 36 37 |
# File 'lib/occams-record/query.rb', line 35 def model @model end |
#scope ⇒ ActiveRecord::Relation (readonly)
Returns scope for building the main SQL query.
37 38 39 |
# File 'lib/occams-record/query.rb', line 37 def scope @scope end |
Instance Method Details
#each {|OccamsRecord::Results::Row| ... } ⇒ Object
If you pass a block, each result row will be yielded to it. If you don’t, an Enumerable will be returned.
94 95 96 97 98 99 100 |
# File 'lib/occams-record/query.rb', line 94 def each if block_given? to_a.each { |row| yield row } else to_a.each end end |
#first ⇒ OccamsRecord::Results::Row
Run the query and return the first result (which could be nil). This WILL append a LIMIT 1 to the query.
82 83 84 85 |
# File 'lib/occams-record/query.rb', line 82 def first scope.limit! 1 run[0] end |
#run ⇒ Array<OccamsRecord::Results::Row> Also known as: to_a
Run the query and return the results.
65 66 67 68 69 70 71 72 73 |
# File 'lib/occams-record/query.rb', line 65 def run sql = scope.to_sql @query_logger << sql if @query_logger result = model.connection.exec_query sql row_class = OccamsRecord::Results.klass(result.columns, result.column_types, @eager_loaders.map(&:name), model: model, modules: @use) rows = result.rows.map { |row| row_class.new row } eager_load! rows rows end |