Skip to content

Commit

Permalink
PostgreSQL: insert looks up pk and sequence name if not given. [#384
Browse files Browse the repository at this point in the history
…state:resolved]
  • Loading branch information
jeremy committed Jun 10, 2008
1 parent 319941e commit a065144
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions activerecord/test/cases/database_statements_test.rb
@@ -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.