Method: MassRecord::Actions#sort_save_operations

Defined in:
lib/mass_record.rb

#sort_save_operations(from: nil, for_table: nil, key: {}) ⇒ Object



318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/mass_record.rb', line 318

def sort_save_operations from:nil, for_table:nil, key:{}
	return {} if from.blank? or for_table.blank?
	table = for_table
	hashes = from.select{|o| o[key[:table]] == table}.collect{|x| x[key[:object]]}
	model = get_model from:for_table
	connection = model.connection
	pk = model.primary_key

	# organize hashes based on whether they exist (based on their primary key(s)) in the table or not
	if pk.is_a? Array
		ids = hashes.reject{|x| pk.any?{|k| x[k].blank?}}.collect{|x| x.select{|k,v| pk.include? k}}	# only accept full sets of pk's
		where_clauses = []
		ids.each do |id|
			equivalence_clauses = []
			id.each do |k,v|
				equivalence_clauses << "#{k} = #{connection.quote(connection.type_cast(v, model.column_types[k]))}"
			end
			where_clauses << "(#{equivalence_clauses.join ' and '})"
		end
		existing_id_sets = model.find_by_sql("SELECT #{pk.join ', '} FROM #{model.table_name} WHERE #{where_clauses.join ' OR '}").collect{|x| x.attributes}  #.collect{|x| Hash[x.map.with_index{|x,i| [pk[i],x]}]}
		insert_hashes = hashes.reject{|h| existing_id_sets.any?{|set| h == h.merge(set)}}
		update_hashes = hashes.select{|h| existing_id_sets.any?{|set| h == h.merge(set)}}
	else
		ids = hashes.reject{|x| x[pk].blank?}.collect{|x| x[pk]}	# should not include null values
		existing_ids = model.find_by_sql("SELECT #{pk} FROM #{model.table_name} WHERE #{pk} in ('#{ids.join "','"}')").collect{|x| x[pk]}	# for some reason model.connection.execute returns the count
		insert_hashes = hashes.reject{|x| existing_ids.include? x[pk].to_s}
		update_hashes = hashes.select{|x| existing_ids.include? x[pk].to_s}
	end

	return {insert:insert_hashes,update:update_hashes}
end