Skip to content

Commit

Permalink
PostgreSQL: use 'INSERT ... RETURNING id' for 8.2 and later.
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremy committed Jul 15, 2008
1 parent 70a34cd commit 44363ba
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
2 changes: 2 additions & 0 deletions activerecord/CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@

* Add :validate option to associations to enable/disable the automatic validation of associated models. Resolves #301. [Jan De Poorter]

* PostgreSQL: use 'INSERT ... RETURNING id' for 8.2 and later. [Jeremy Kemper]

* Added SQL escaping for :limit and :offset in MySQL [Jonathan Wiess]


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,12 @@ def supports_standard_conforming_strings?
has_support
end

def supports_insert_with_returning?
@supports_insert_with_returning ||=
@connection.respond_to?(:server_version) &&
@connection.server_version >= 80200
end

# Returns the configured supported identifier length supported by PostgreSQL,
# or report the default of 63 on PostgreSQL 7.x.
def table_alias_length
Expand Down Expand Up @@ -419,12 +425,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)
# Extract the table from the insert sql. Yuck.
table = sql.split(" ", 4)[2].gsub('"', '')

# Try an insert with 'returning id' if available (PG >= 8.2)
if supports_insert_with_returning?
pk, sequence_name = *pk_and_sequence_for(table) unless pk
if pk
id = select_value("#{sql} RETURNING #{quote_column_name(pk)}")
clear_query_cache
return id
end
end

# Otherwise, insert then grab last_insert_id.
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)
Expand Down

0 comments on commit 44363ba

Please sign in to comment.