Skip to content

Commit

Permalink
Increment @counter of prepared postgres statements prior to running t…
Browse files Browse the repository at this point in the history
…he query, so if the query gets interrupted without Rails knowledge we don't end up with a crashed app in a state of perpetual failure to prepare the next query.

This commit directly inspired by the conversation at rails#25827 (and by a late night crash of our app due to this issue).
  • Loading branch information
wbharding committed Jan 6, 2021
1 parent 5710128 commit 1d940f3
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
4 changes: 4 additions & 0 deletions activerecord/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
* Increment postgres prepared statement counter before making a prepared statement, so if the statement is aborted
without Rails knowledge (e.g., if app gets kill -9d during long-running query), app won't end
up in perpetual crash state for being inconsistent with Postgres.

* Add `FinderMethods#sole` and `#find_sole_by` to find and assert the
presence of exactly one record.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,12 +226,9 @@ def initialize(connection, max)
@counter = 0
end

def next_key
"a#{@counter + 1}"
end

def []=(sql, key)
super.tap { @counter += 1 }
def incremented_next_key
@counter += 1
"a#{@counter}"
end

private
Expand Down Expand Up @@ -746,7 +743,7 @@ def prepare_statement(sql, binds)
@lock.synchronize do
sql_key = sql_key(sql)
unless @statements.key? sql_key
nextkey = @statements.next_key
nextkey = @statements.incremented_next_key
begin
@connection.prepare nextkey, sql
rescue => e
Expand Down

0 comments on commit 1d940f3

Please sign in to comment.