Permalink
Browse files

PostgreSQL: insert looks up pk and sequence name if not given. [#384

…state:resolved]
  • Loading branch information...
1 parent 319941e commit a065144afb9e8b4666a5097e3e81de80251e86e6 @jeremy jeremy committed Jun 10, 2008
@@ -411,8 +411,23 @@ def select_rows(sql, name = nil)
# Executes an INSERT query and returns the new record's ID
def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
- table = sql.split(" ", 4)[2].gsub('"', '')
- super || pk && last_insert_id(table, sequence_name || default_sequence_name(table, pk))
+ if insert_id = super
+ insert_id
+ else
+ # Extract the table from the insert sql. Yuck.
+ table = sql.split(" ", 4)[2].gsub('"', '')
+
+ # If neither pk nor sequence name is given, look them up.
+ unless pk || sequence_name
+ pk, sequence_name = *pk_and_sequence_for(table)
+ end
+
+ # If a pk is given, fallback to default sequence name.
+ # Don't fetch last insert id for a table without a pk.
+ if pk && sequence_name ||= default_sequence_name(table, pk)
+ last_insert_id(table, sequence_name)
+ end
+ end
end
# create a 2D array representing the result set
@@ -0,0 +1,12 @@
+require "cases/helper"
+
+class DatabaseStatementsTest < ActiveRecord::TestCase
+ def setup
+ @connection = ActiveRecord::Base.connection
+ end
+
+ def test_insert_should_return_the_inserted_id
+ id = @connection.insert("INSERT INTO accounts (firm_id,credit_limit) VALUES (42,5000)")
+ assert_not_nil id
+ end
+end

0 comments on commit a065144

Please sign in to comment.