Skip to content

Commit

Permalink
Use a proper type casting for the DB
Browse files Browse the repository at this point in the history
Use a proper type casting for the DB, solution inspired by
ActiveRecord import gem.
  • Loading branch information
Ladas committed Jul 13, 2017
1 parent 723093c commit 80bafbf
Showing 1 changed file with 23 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -52,16 +52,17 @@ def save!(inventory_collection, association)
next unless assert_referential_integrity(hash, inventory_object)
inventory_object.id = record.id

if inventory_collection.use_ar_object?
record.assign_attributes(hash.except(:id, :type))
hash_for_update = record.instance_eval("@attributes").map(&:value_for_database)
.instance_eval("@attributes").symbolize_keys.except(:id, :type)
else
hash_for_update = hash.symbolize_keys.except(:id, :type)
assign_attributes_for_update!(hash_for_update, inventory_collection, update_time)
end

hashes_for_update << hash_for_update
hash_for_update = if inventory_collection.use_ar_object?
record.assign_attributes(hash.except(:id, :type))
values_for_database(inventory_collection.model_class,
all_attribute_keys,
record.attributes)
else
hash.symbolize_keys
end
assign_attributes_for_update!(hash_for_update, inventory_collection, update_time)

hashes_for_update << hash_for_update.except(:id, :type)
end
end

Expand Down Expand Up @@ -123,8 +124,10 @@ def create_records!(inventory_collection, all_attribute_keys, batch, attributes_
create_time = time_now
batch.each do |index, inventory_object|
hash = if inventory_collection.use_ar_object?
inventory_collection.model_class.new(attributes_index.delete(index))
.instance_eval("@attributes").map(&:value_for_database).instance_eval("@attributes").symbolize_keys
record = inventory_collection.model_class.new(attributes_index.delete(index))
values_for_database(inventory_collection.model_class,
all_attribute_keys,
record.attributes)
else
attributes_index.delete(index).symbolize_keys
end
Expand All @@ -149,6 +152,14 @@ def create_records!(inventory_collection, all_attribute_keys, batch, attributes_
end
end

def values_for_database(model_class, all_attribute_keys, attributes)
all_attribute_keys.each_with_object({}) do |attribute_name, db_values|
type = model_class.type_for_attribute(attribute_name.to_s)
raw_val = attributes[attribute_name.to_s]
db_values[attribute_name] = type.type == :boolean ? type.cast(raw_val) : type.serialize(raw_val)
end
end

def map_ids_to_inventory_objects(inventory_collection, indexed_inventory_objects, all_attribute_keys, hashes, result)
# The remote_data_timestamp is adding a WHERE condition to ON CONFLICT UPDATE. As a result, the RETURNING
# clause is not guaranteed to return all ids of the inserted/updated records in the result. In that case
Expand Down

0 comments on commit 80bafbf

Please sign in to comment.