Class: ActiveRecord::Base
- Inherits:
-
Object
- Object
- ActiveRecord::Base
- Defined in:
- lib/activerecord-import/synchronize.rb,
lib/activerecord-import/import.rb
Overview
:nodoc:
Class Method Summary collapse
-
.import(*args) ⇒ Object
:columns.
-
.import!(*args) ⇒ Object
Imports a collection of values if all values are valid.
- .import_helper(*args) ⇒ Object
-
.import_with_validations(column_names, array_of_attributes, options = {}) ⇒ Object
Imports the passed in
column_namesandarray_of_attributesgiven the passed inoptionsHash with validations. -
.import_without_validations_or_callbacks(column_names, array_of_attributes, options = {}) ⇒ Object
Imports the passed in
column_namesandarray_of_attributesgiven the passed inoptionsHash. -
.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.
-
.supports_import?(*args) ⇒ Boolean
Returns true if the current database connection adapter supports import functionality, otherwise returns false.
-
.supports_on_duplicate_key_update? ⇒ Boolean
Returns true if the current database connection adapter supports on duplicate key update functionality, otherwise returns false.
-
.synchronize(instances, keys = [primary_key]) ⇒ Object
Synchronizes the passed in ActiveRecord instances with data from the database.
Instance Method Summary collapse
-
#synchronize(instances, key = [ActiveRecord::Base.primary_key]) ⇒ Object
See ActiveRecord::ConnectionAdapters::AbstractAdapter.synchronize.
Class Method Details
.import(*args) ⇒ Object
:columns
The :columns attribute can be either an Array or a Hash.
Using an Array
The :columns attribute 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: { conflict_target: :slug, columns: [ :date_modified, :content, :author ] }
Using a Hash
The :columns option can be a hash of column names 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: { conflict_target: :slug, columns: { 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 primary keys of the imported ids if the adapter supports it, otherwise an empty array.
387 388 389 390 391 392 393 394 395 396 397 |
# File 'lib/activerecord-import/import.rb', line 387 def import(*args) if args.first.is_a?( Array ) && args.first.first.is_a?(ActiveRecord::Base) = {} .merge!( args.pop ) if args.last.is_a?(Hash) models = args.first import_helper(models, ) else import_helper(*args) end end |
.import!(*args) ⇒ Object
Imports a collection of values if all values are valid. Import fails at the first encountered validation error and raises ActiveRecord::RecordInvalid with the failed instance.
402 403 404 405 406 407 408 |
# File 'lib/activerecord-import/import.rb', line 402 def import!(*args) = args.last.is_a?( Hash ) ? args.pop : {} [:validate] = true [:raise_error] = true import(*args, ) end |
.import_helper(*args) ⇒ Object
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 |
# File 'lib/activerecord-import/import.rb', line 410 def import_helper( *args ) = { validate: true, timestamps: true } .merge!( args.pop ) if args.last.is_a? Hash # making sure that current model's primary key is used [:primary_key] = primary_key # Don't modify incoming arguments if [:on_duplicate_key_update] && [:on_duplicate_key_update].duplicable? [:on_duplicate_key_update] = [:on_duplicate_key_update].dup end is_validating = [:validate] is_validating = true unless [:validate_with_context].nil? # assume array of model objects if args.last.is_a?( Array ) && args.last.first.is_a?(ActiveRecord::Base) if args.length == 2 models = args.last column_names = args.first.dup else models = args.first column_names = self.column_names.dup end if models.first.id.nil? && column_names.include?(primary_key) && columns_hash[primary_key].type == :uuid column_names.delete(primary_key) end default_values = column_defaults stored_attrs = respond_to?(:stored_attributes) ? stored_attributes : {} serialized_attrs = if defined?(ActiveRecord::Type::Serialized) attrs = column_names.select { |c| type_for_attribute(c.to_s).class == ActiveRecord::Type::Serialized } Hash[attrs.map { |a| [a, nil] }] else serialized_attributes end array_of_attributes = models.map do |model| column_names.map do |name| if stored_attrs.key?(name.to_sym) || serialized_attrs.key?(name) || default_values.key?(name.to_s) model.read_attribute(name.to_s) else model.read_attribute_before_type_cast(name.to_s) end end end # supports array of hash objects elsif args.last.is_a?( Array ) && args.last.first.is_a?(Hash) if args.length == 2 array_of_hashes = args.last column_names = args.first.dup else array_of_hashes = args.first column_names = array_of_hashes.first.keys end array_of_attributes = array_of_hashes.map do |h| column_names.map do |key| h[key] end end # supports empty array elsif args.last.is_a?( Array ) && args.last.empty? return ActiveRecord::Import::Result.new([], 0, []) # supports 2-element array and array elsif args.size == 2 && args.first.is_a?( Array ) && args.last.is_a?( Array ) unless args.last.first.is_a?(Array) raise ArgumentError, "Last argument should be a two dimensional array '[[]]'. First element in array was a #{args.last.first.class}" end column_names, array_of_attributes = args # dup the passed args so we don't modify unintentionally column_names = column_names.dup array_of_attributes = array_of_attributes.map(&:dup) else raise ArgumentError, "Invalid arguments!" end # 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 symbolized_column_names = Array(column_names).map(&:to_sym) symbolized_primary_key = Array(primary_key).map(&:to_sym) if !symbolized_primary_key.to_set.subset?(symbolized_column_names.to_set) && connection.prefetch_primary_key? && sequence_name column_count = column_names.size column_names.concat(primary_key).uniq! columns_added = column_names.size - column_count new_fields = Array.new(columns_added) array_of_attributes.each { |a| a.concat(new_fields) } end = {} # record timestamps unless disabled in ActiveRecord::Base if && .delete( :timestamps ) = add_special_rails_stamps column_names, array_of_attributes, end return_obj = if is_validating if models import_with_validations( column_names, array_of_attributes, ) do |validator, failed| models.each_with_index do |model, i| model = model.dup if [:recursive] next if validator.valid_model? model raise(ActiveRecord::RecordInvalid, model) if [:raise_error] array_of_attributes[i] = nil failed << model end end else import_with_validations( column_names, array_of_attributes, ) end else (num_inserts, ids) = import_without_validations_or_callbacks( column_names, array_of_attributes, ) ActiveRecord::Import::Result.new([], num_inserts, ids) end if [:synchronize] sync_keys = [:synchronize_keys] || [primary_key] synchronize( [: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 models && support_setting_primary_key_of_imported_objects? set_attributes_and_mark_clean(models, return_obj, ) # if there are auto-save associations on the models we imported that are new, import them as well import_associations(models, .dup) if [:recursive] 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.
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 |
# File 'lib/activerecord-import/import.rb', line 556 def import_with_validations( column_names, array_of_attributes, = {} ) failed_instances = [] validator = ActiveRecord::Import::Validator.new() if block_given? yield validator, failed_instances else # 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 model = new arr.each_with_index do |hsh, i| hsh.each_pair { |k, v| model[k] = v } next if validator.valid_model? model raise(ActiveRecord::RecordInvalid, model) if [:raise_error] array_of_attributes[i] = nil failure = model.dup failure.errors.send(:initialize_dup, model.errors) failed_instances << failure end end array_of_attributes.compact! num_inserts, ids = if array_of_attributes.empty? || [:all_or_none] && failed_instances.any? [0, []] else import_without_validations_or_callbacks( column_names, array_of_attributes, ) 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.
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 |
# File 'lib/activerecord-import/import.rb', line 597 def import_without_validations_or_callbacks( column_names, array_of_attributes, = {} ) 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| name_as_sym = name.to_sym next if column_names.include?(name_as_sym) is_sti = (name_as_sym == inheritance_column.to_sym && self < base_class) value = value.first if is_sti column_names << name_as_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(',')})" pre_sql_statements = connection.pre_sql_statements( ) insert_sql = ['INSERT', pre_sql_statements, "INTO #{quoted_table_name} #{columns_sql} VALUES "] insert_sql = insert_sql.flatten.join(' ') values_sql = values_sql_for_columns_and_attributes(columns, array_of_attributes) number_inserted = 0 ids = [] if supports_import? # generate the sql post_sql_statements = connection.post_sql_statements( quoted_table_name, ) batch_size = [:batch_size] || values_sql.size values_sql.each_slice(batch_size) do |batch_values| # perform the inserts result = connection.insert_many( [insert_sql, post_sql_statements].flatten, batch_values, , "#{self.class.name} Create Many Without Validations Or Callbacks" ) number_inserted += result[0] ids += result[1] end else transaction(requires_new: true) do values_sql.each do |values| ids << connection.insert(insert_sql + values) number_inserted += 1 end end 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
170 171 172 |
# File 'lib/activerecord-import/import.rb', line 170 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.
156 157 158 |
# File 'lib/activerecord-import/import.rb', line 156 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.
163 164 165 |
# File 'lib/activerecord-import/import.rb', line 163 def supports_on_duplicate_key_update? connection.supports_on_duplicate_key_update? end |
.synchronize(instances, keys = [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
23 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 23 def self.synchronize(instances, keys = [primary_key]) return if instances.empty? conditions = {} 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 next unless matched_instance instance.send :clear_aggregation_cache instance.send :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.2 and higher else instance.instance_variable_set :@attributes_cache, {} # Rails 4.0, 4.1 instance.changed_attributes.clear # Rails 3.2 instance.previous_changes.clear 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 |
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 |