Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/activerecord-import/synchronize.rb,
lib/activerecord-import/import.rb,
lib/activerecord-import.rb

Overview

:nodoc:

Constant Summary collapse

AREXT_RAILS_COLUMNS =
{
  :create => { "created_on" => tproc ,
               "created_at" => tproc },
  :update => { "updated_on" => tproc ,
               "updated_at" => tproc }
}
AREXT_RAILS_COLUMN_NAMES =
AREXT_RAILS_COLUMNS[:create].keys + AREXT_RAILS_COLUMNS[:update].keys

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.establish_connection_with_activerecord_import(*args) ⇒ Object



3
4
5
6
# File 'lib/activerecord-import.rb', line 3

def establish_connection_with_activerecord_import(*args)
  establish_connection_without_activerecord_import(*args)
  ActiveSupport.run_load_hooks(:active_record_connection_established, connection_pool)
end

.import(*args) ⇒ Object

Imports a collection of values to the database.

This is more efficient than using ActiveRecord::Base#create or ActiveRecord::Base#save multiple times. This method works well if you want to create more than one record at a time and do not care about having ActiveRecord objects returned for each record inserted.

This can be used with or without validations. It does not utilize the ActiveRecord::Callbacks during creation/modification while performing the import.

Usage

Model.import array_of_models
Model.import column_names, array_of_values
Model.import column_names, array_of_values, options

Model.import array_of_models

With this form you can call import passing in an array of model objects that you want updated.

Model.import column_names, array_of_values

The first parameter column_names is an array of symbols or strings which specify the columns that you want to update.

The second parameter, array_of_values, is an array of arrays. Each subarray is a single set of values for a new record. The order of values in each subarray should match up to the order of the column_names.

Model.import column_names, array_of_values, options

The first two parameters are the same as the above form. The third parameter, options, is a hash. This is optional. Please see below for what options are available.

Options

  • validate - true|false, tells import whether or not to use \

    ActiveRecord validations. Validations are enforced by default.
    
  • on_duplicate_key_update - an Array or Hash, tells import to \

    use MySQL's ON DUPLICATE KEY UPDATE ability. See On Duplicate\
    Key Update below.
    
  • synchronize - an array of ActiveRecord instances for the model that you are currently importing data into. This synchronizes existing model instances in memory with updates from the import.

  • timestamps - true|false, tells import to not add timestamps \ (if false) even if record timestamps is disabled in ActiveRecord::Base

  • +recursive - true|false, tells import to import all autosave association if the adapter supports setting the primary keys of the newly imported objects.

Examples

class BlogPost < ActiveRecord::Base ; end

# Example using array of model objects
posts = [ BlogPost.new :author_name=>'Zach Dennis', :title=>'AREXT',
          BlogPost.new :author_name=>'Zach Dennis', :title=>'AREXT2',
          BlogPost.new :author_name=>'Zach Dennis', :title=>'AREXT3' ]
BlogPost.import posts

# Example using column_names and array_of_values
columns = [ :author_name, :title ]
values = [ [ 'zdennis', 'test post' ], [ 'jdoe', 'another test post' ] ]
BlogPost.import columns, values

# Example using column_names, array_of_value and options
columns = [ :author_name, :title ]
values = [ [ 'zdennis', 'test post' ], [ 'jdoe', 'another test post' ] ]
BlogPost.import( columns, values, :validate => false  )

# Example synchronizing existing instances in memory
post = BlogPost.where(author_name: 'zdennis').first
puts post.author_name # => 'zdennis'
columns = [ :author_name, :title ]
values = [ [ 'yoda', 'test post' ] ]
BlogPost.import posts, :synchronize=>[ post ]
puts post.author_name # => 'yoda'

# Example synchronizing unsaved/new instances in memory by using a uniqued imported field
posts = [BlogPost.new(:title => "Foo"), BlogPost.new(:title => "Bar")]
BlogPost.import posts, :synchronize => posts, :synchronize_keys => [:title]
puts posts.first.persisted? # => true

On Duplicate Key Update (MySQL only)

The :on_duplicate_key_update option can be either an Array or a Hash.

Using an Array

The :on_duplicate_key_update option can be an array of column names. The column names are the only fields that are updated if a duplicate record is found. Below is an example:

BlogPost.import columns, values, :on_duplicate_key_update=>[ :date_modified, :content, :author ]

Using A Hash

The :on_duplicate_key_update option can be a hash of column name to model attribute name mappings. This gives you finer grained control over what fields are updated with what attributes on your model. Below is an example:

BlogPost.import columns, attributes, :on_duplicate_key_update=>{ :title => :title }

Returns

This returns an object which responds to failed_instances and num_inserts.

  • failed_instances - an array of objects that fails validation and were not committed to the database. An empty array if no validation is performed.

  • num_inserts - the number of insert statements it took to import the data

  • ids - the priamry keys of the imported ids, if the adpater supports it, otherwise and empty array.



240
241
242
243
244
245
246
247
248
249
250
# File 'lib/activerecord-import/import.rb', line 240

def import(*args)
  if args.first.is_a?( Array ) and args.first.first.is_a? ActiveRecord::Base
    options = {}
    options.merge!( args.pop ) if args.last.is_a?(Hash)

    models = args.first
    import_helper(models, options)
  else
    import_helper(*args)
  end
end

.import_from_table(options) ⇒ Object

TODO import_from_table needs to be implemented.



330
331
# File 'lib/activerecord-import/import.rb', line 330

def import_from_table( options ) # :nodoc:
end

.import_helper(*args) ⇒ Object



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/activerecord-import/import.rb', line 252

def import_helper( *args )
  options = { :validate=>true, :timestamps=>true, :primary_key=>primary_key }
  options.merge!( args.pop ) if args.last.is_a? Hash

  is_validating = options[:validate]
  is_validating = true unless options[:validate_with_context].nil?

  # assume array of model objects
  if args.last.is_a?( Array ) and args.last.first.is_a? ActiveRecord::Base
    if args.length == 2
      models = args.last
      column_names = args.first
    else
      models = args.first
      column_names = self.column_names.dup
    end

    array_of_attributes = models.map do |model|
      # this next line breaks sqlite.so with a segmentation fault
      # if model.new_record? || options[:on_duplicate_key_update]
        column_names.map do |name|
          model.read_attribute_before_type_cast(name.to_s)
        end
      # end
    end
    # supports empty array
  elsif args.last.is_a?( Array ) and args.last.empty?
    return ActiveRecord::Import::Result.new([], 0, []) if args.last.empty?
    # supports 2-element array and array
  elsif args.size == 2 and args.first.is_a?( Array ) and args.last.is_a?( Array )
    column_names, array_of_attributes = args
  else
    raise ArgumentError.new( "Invalid arguments!" )
  end

  # dup the passed in array so we don't modify it unintentionally
  array_of_attributes = array_of_attributes.dup

  # Force the primary key col into the insert if it's not
  # on the list and we are using a sequence and stuff a nil
  # value for it into each row so the sequencer will fire later
  if !column_names.include?(primary_key) && connection.prefetch_primary_key? && sequence_name
     column_names << primary_key
     array_of_attributes.each { |a| a << nil }
  end

  # record timestamps unless disabled in ActiveRecord::Base
  if record_timestamps && options.delete( :timestamps )
     add_special_rails_stamps column_names, array_of_attributes, options
  end

  return_obj = if is_validating
    import_with_validations( column_names, array_of_attributes, options )
  else
    (num_inserts, ids) = import_without_validations_or_callbacks( column_names, array_of_attributes, options )
    ActiveRecord::Import::Result.new([], num_inserts, ids)
  end

  if options[:synchronize]
    sync_keys = options[:synchronize_keys] || [self.primary_key]
    synchronize( options[:synchronize], sync_keys)
  end
  return_obj.num_inserts = 0 if return_obj.num_inserts.nil?

  # if we have ids, then set the id on the models and mark the models as clean.
  if support_setting_primary_key_of_imported_objects?
    set_ids_and_mark_clean(models, return_obj)

    # if there are auto-save associations on the models we imported that are new, import them as well
    if options[:recursive]
      import_associations(models, options)
    end
  end

  return_obj
end

.import_with_validations(column_names, array_of_attributes, options = {}) ⇒ Object

Imports the passed in column_names and array_of_attributes given the passed in options Hash with validations. Returns an object with the methods failed_instances and num_inserts. failed_instances is an array of instances that failed validations. num_inserts is the number of inserts it took to import the data. See ActiveRecord::Base.import for more information on column_names, array_of_attributes and options.



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'lib/activerecord-import/import.rb', line 340

def import_with_validations( column_names, array_of_attributes, options={} )
  failed_instances = []

  # create instances for each of our column/value sets
  arr = validations_array_for_column_names_and_attributes( column_names, array_of_attributes )

  # keep track of the instance and the position it is currently at. if this fails
  # validation we'll use the index to remove it from the array_of_attributes
  arr.each_with_index do |hsh,i|
    instance = new do |model|
      hsh.each_pair{ |k,v| model.send("#{k}=", v) }
    end
    if not instance.valid?(options[:validate_with_context])
      array_of_attributes[ i ] = nil
      failed_instances << instance
    end
  end
  array_of_attributes.compact!

  (num_inserts, ids) = if array_of_attributes.empty? || options[:all_or_none] && failed_instances.any?
                  [0,[]]
                else
                  import_without_validations_or_callbacks( column_names, array_of_attributes, options )
                end
  ActiveRecord::Import::Result.new(failed_instances, num_inserts, ids)
end

.import_without_validations_or_callbacks(column_names, array_of_attributes, options = {}) ⇒ Object

Imports the passed in column_names and array_of_attributes given the passed in options Hash. This will return the number of insert operations it took to create these records without validations or callbacks. See ActiveRecord::Base.import for more information on column_names, +array_of_attributes_ and options.



373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/activerecord-import/import.rb', line 373

def import_without_validations_or_callbacks( column_names, array_of_attributes, options={} )
  column_names = column_names.map(&:to_sym)
  scope_columns, scope_values = scope_attributes.to_a.transpose

  unless scope_columns.blank?
    scope_columns.zip(scope_values).each do |name, value|
      next if column_names.include?(name.to_sym)
      column_names << name.to_sym
      array_of_attributes.each { |attrs| attrs << value }
    end
  end

  columns = column_names.each_with_index.map do |name, i|
    column = columns_hash[name.to_s]

    raise ActiveRecord::Import::MissingColumnError.new(name.to_s, i) if column.nil?

    column
  end

  columns_sql = "(#{column_names.map{|name| connection.quote_column_name(name) }.join(',')})"
  insert_sql = "INSERT #{options[:ignore] ? 'IGNORE ':''}INTO #{quoted_table_name} #{columns_sql} VALUES "
  values_sql = values_sql_for_columns_and_attributes(columns, array_of_attributes)
  ids = []
  if not supports_import?
    number_inserted = 0
    values_sql.each do |values|
      connection.execute(insert_sql + values)
      number_inserted += 1
    end
  else
    # generate the sql
    post_sql_statements = connection.post_sql_statements( quoted_table_name, options )

    # perform the inserts
    (number_inserted,ids) = connection.insert_many( [ insert_sql, post_sql_statements ].flatten,
                                              values_sql,
                                              "#{self.class.name} Create Many Without Validations Or Callbacks" )
  end
  [number_inserted, ids]
end

.support_setting_primary_key_of_imported_objects?Boolean

returns true if the current database connection adapter supports setting the primary key of bulk imported models, otherwise returns false

Returns:

  • (Boolean)


125
126
127
# File 'lib/activerecord-import/import.rb', line 125

def support_setting_primary_key_of_imported_objects?
  connection.respond_to?(:support_setting_primary_key_of_imported_objects?) && connection.support_setting_primary_key_of_imported_objects?
end

.supports_import?(*args) ⇒ Boolean

Returns true if the current database connection adapter supports import functionality, otherwise returns false.

Returns:

  • (Boolean)


111
112
113
# File 'lib/activerecord-import/import.rb', line 111

def supports_import?(*args)
  connection.respond_to?(:supports_import?) && connection.supports_import?(*args)
end

.supports_on_duplicate_key_update?Boolean

Returns true if the current database connection adapter supports on duplicate key update functionality, otherwise returns false.

Returns:

  • (Boolean)


118
119
120
# File 'lib/activerecord-import/import.rb', line 118

def supports_on_duplicate_key_update?
  connection.respond_to?(:supports_on_duplicate_key_update?) && connection.supports_on_duplicate_key_update?
end

.synchronize(instances, keys = [self.primary_key]) ⇒ Object

Synchronizes the passed in ActiveRecord instances with data from the database. This is like calling reload on an individual ActiveRecord instance but it is intended for use on multiple instances.

This uses one query for all instance updates and then updates existing instances rather sending one query for each instance

Examples

# Synchronizing existing models by matching on the primary key field posts = Post.where(author: “Zach”).first <.. out of system changes occur to change author name from Zach to Zachary..> Post.synchronize posts posts.first.author # => “Zachary” instead of Zach

# Synchronizing using custom key fields posts = Post.where(author: “Zach”).first <.. out of system changes occur to change the address of author ‘Zach’ to 1245 Foo Ln ..> Post.synchronize posts, [:name] # queries on the :name column and not the :id column posts.first.address # => “1245 Foo Ln” instead of whatever it was



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/activerecord-import/synchronize.rb', line 24

def self.synchronize(instances, keys=[self.primary_key])
  return if instances.empty?

  conditions = {}
  order = ""

  key_values = keys.map { |key| instances.map(&"#{key}".to_sym) }
  keys.zip(key_values).each { |key, values| conditions[key] = values }
  order = keys.map{ |key| "#{key} ASC" }.join(",")

  klass = instances.first.class

  fresh_instances = klass.where(conditions).order(order)
  instances.each do |instance|
    matched_instance = fresh_instances.detect do |fresh_instance|
      keys.all?{ |key| fresh_instance.send(key) == instance.send(key) }
    end

    if matched_instance
      instance.clear_aggregation_cache
      instance.clear_association_cache
      instance.instance_variable_set :@attributes, matched_instance.instance_variable_get(:@attributes)

      if instance.respond_to?(:clear_changes_information)
        instance.clear_changes_information                  # Rails 4.1 and higher
      else
        instance.changed_attributes.clear                   # Rails 3.1, 3.2
      end

      # Since the instance now accurately reflects the record in
      # the database, ensure that instance.persisted? is true.
      instance.instance_variable_set '@new_record', false
      instance.instance_variable_set '@destroyed', false
    end
  end
end

Instance Method Details

#synchronize(instances, key = [ActiveRecord::Base.primary_key]) ⇒ Object

See ActiveRecord::ConnectionAdapters::AbstractAdapter.synchronize



62
63
64
# File 'lib/activerecord-import/synchronize.rb', line 62

def synchronize(instances, key=[ActiveRecord::Base.primary_key])
  self.class.synchronize(instances, key)
end