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)



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

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
  }.merge(options)

  result = _light_record_execute_query(connection, sql, options.except(:set_const))

  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



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/light_record.rb', line 223

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
  }.merge(options)

  result = _light_record_execute_query(conn, sql, options.except(:set_const))

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

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

  if defined?(PG::Result) && result.is_a?(PG::Result)
    begin
      result.stream_each do |row|
        row.symbolize_keys!
        yield klass.new(row)
      end
    rescue => error
      conn.raw_connection.get_last_result
      throw error
    ensure
      result.clear
    end
  else
    result.each do |row|
      yield klass.new(row)
    end
  end
ensure
  ActiveRecord::Base.connection_pool.checkin(conn)
end