Skip to content

Commit

Permalink
Build valid SQL query for SQLite3 and PostgreSQL when updating record…
Browse files Browse the repository at this point in the history
…s with limited conditions
  • Loading branch information
miloops committed Jun 23, 2009
1 parent 3e6ad6e commit ae0c58f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 8 deletions.
20 changes: 18 additions & 2 deletions lib/arel/engines/sql/relations/writes.rb
Expand Up @@ -24,8 +24,7 @@ def to_sql(formatter = nil)
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
Expand All @@ -39,5 +38,22 @@ def assignment_sql
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"
quote_primary_key = engine.quote_column_name(table.name.classify.constantize.primary_key)
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
18 changes: 12 additions & 6 deletions spec/arel/engines/sql/unit/relations/update_spec.rb
@@ -1,5 +1,11 @@
require File.join(File.dirname(__FILE__), '..', '..', '..', '..', '..', 'spec_helper')

class User
def self.primary_key
"id"
end
end

module Arel
describe Update do
before do
Expand Down Expand Up @@ -45,17 +51,17 @@ module Arel

adapter_is :sqlite3 do
sql.should be_like(%Q{
UPDATE "users"
SET "name" = 'nick'
LIMIT 1
UPDATE "users" SET
"name" = 'nick'
WHERE "id" IN (SELECT "id" FROM "users" LIMIT 1)
})
end

adapter_is :postgresql do
sql.should be_like(%Q{
UPDATE "users"
SET "name" = E'nick'
LIMIT 1
UPDATE "users" SET
"name" = E'nick'
WHERE "id" IN (SELECT "id" FROM "users" LIMIT 1)
})
end
end
Expand Down

0 comments on commit ae0c58f

Please sign in to comment.