aboutsummaryrefslogtreecommitdiffstats
path: root/lib/arel/engines/sql/relations/writes.rb
diff options
context:
space:
mode:
Diffstat (limited to 'lib/arel/engines/sql/relations/writes.rb')
-rw-r--r--lib/arel/engines/sql/relations/writes.rb46
1 files changed, 38 insertions, 8 deletions
diff --git a/lib/arel/engines/sql/relations/writes.rb b/lib/arel/engines/sql/relations/writes.rb
index f1a9bfd2ac..d648a54d91 100644
--- a/lib/arel/engines/sql/relations/writes.rb
+++ b/lib/arel/engines/sql/relations/writes.rb
@@ -11,11 +11,17 @@ module Arel
class Insert < Compound
def to_sql(formatter = nil)
+ insertion_attributes_values_sql = if record.is_a?(Value)
+ record.value
+ else
+ build_query "(#{record.keys.collect { |key| engine.quote_column_name(key.name) }.join(', ')})",
+ "VALUES (#{record.collect { |key, value| key.format(value) }.join(', ')})"
+ end
+
build_query \
"INSERT",
"INTO #{table_sql}",
- "(#{record.keys.collect { |key| engine.quote_column_name(key.name) }.join(', ')})",
- "VALUES (#{record.collect { |key, value| key.format(value) }.join(', ')})"
+ insertion_attributes_values_sql
end
end
@@ -24,16 +30,40 @@ module Arel
build_query \
"UPDATE #{table_sql} SET",
assignment_sql,
- ("WHERE #{wheres.collect(&:to_sql).join('\n\tAND ')}" unless wheres.blank? ),
- ("LIMIT #{taken}" unless taken.blank? )
+ build_update_conditions_sql
end
protected
-
def assignment_sql
- assignments.collect do |attribute, value|
- "#{engine.quote_column_name(attribute.name)} = #{attribute.format(value)}"
- end.join(",\n")
+ if assignments.respond_to?(:collect)
+ assignments.collect do |attribute, value|
+ "#{engine.quote_column_name(attribute.name)} = #{attribute.format(value)}"
+ end.join(",\n")
+ else
+ assignments.value
+ end
+ end
+
+ def build_update_conditions_sql
+ conditions = ""
+ conditions << " WHERE #{wheres.collect(&:to_sql).join('\n\tAND ')}" unless wheres.blank?
+ conditions << " ORDER BY #{order_clauses.join(', ')}" unless orders.blank?
+
+ unless taken.blank?
+ conditions << " LIMIT #{taken}"
+
+ if engine.adapter_name != "MySQL"
+ begin
+ quote_primary_key = engine.quote_column_name(table.name.classify.constantize.primary_key)
+ rescue NameError
+ quote_primary_key = engine.quote_column_name("id")
+ end
+
+ conditions = "WHERE #{quote_primary_key} IN (SELECT #{quote_primary_key} FROM #{engine.connection.quote_table_name table.name} #{conditions})"
+ end
+ end
+
+ conditions
end
end
end