Module: LightRecord::RelationMethods

Defined in:
lib/light_record.rb

Instance Method Summary collapse

Instance Method Details

#light_records(options = {}) ⇒ Object

Executes query and return array of light object (model class extended by LightRecord)


166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/light_record.rb', line 166

def light_records(options = {})
  sql = self.to_sql

  options = {
    stream: false, symbolize_keys: true, cache_rows: false, as: :hash,
    database_timezone: ActiveRecord::Base.default_timezone
  }
  result = _light_record_execute_query(connection, sql, options)

  klass = LightRecord.build_for_class(self.klass, result.fields)

  if options[:set_const]
    self.klass.const_set(:"LR_#{Time.now.to_i}", klass)
  end

  need_symbolize_keys = defined?(PG::Result) && result.is_a?(PG::Result)

  records = []
  result.each do |row|
    row.symbolize_keys! if need_symbolize_keys
    records << klass.new(row)
  end

  return records
end

#light_records_each(options = {}) ⇒ Object

Same as `#light_records` but iterates through result set and call block for each object this uses less memroy because it creates objects one-by-one it uses stream feature of mysql client


195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/light_record.rb', line 195

def light_records_each(options = {})
  conn = ActiveRecord::Base.connection_pool.checkout
  sql = self.to_sql

  options = {
    stream: true, symbolize_keys: true, cache_rows: false, as: :hash,
    database_timezone: ActiveRecord::Base.default_timezone
  }
  result = _light_record_execute_query(conn, sql, options)

  klass = LightRecord.build_for_class(self.klass, result.fields)

  if options[:set_const]
    self.klass.const_set(:"LR_#{Time.now.to_i}", klass)
  end

  need_symbolize_keys = defined?(PG::Result) && result.is_a?(PG::Result)

  result.each do |row|
    row.symbolize_keys! if need_symbolize_keys
    yield klass.new(row)
  end
ensure
  ActiveRecord::Base.connection_pool.checkin(conn)
end