Skip to content

Commit

Permalink
Fix unprepared_statement to work it when nesting
Browse files Browse the repository at this point in the history
I've been reported a problem by @osyo-manga, preloading queries in
`unprepared_statement` doesn't work as expected in main branch (queries
are executed as prepared statements).

It is caused by #41385, due to `scope.to_sql` in `grouping_key` depends
on `unprepared_statement` which has an issue when nesting.

To fix the issue, don't add/delete object_id in the prepared statements
disabled cache if that is already disabled.
  • Loading branch information
kamipo committed Feb 12, 2021
1 parent a82df4c commit da26910
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
Expand Up @@ -160,9 +160,10 @@ def schema_migration # :nodoc:
end
end

def prepared_statements
def prepared_statements?
@prepared_statements && !prepared_statements_disabled_cache.include?(object_id)
end
alias :prepared_statements :prepared_statements?

def prepared_statements_disabled_cache # :nodoc:
Thread.current[:ar_prepared_statements_disabled_cache] ||= Set.new
Expand Down Expand Up @@ -256,7 +257,7 @@ def seconds_idle # :nodoc:
end

def unprepared_statement
cache = prepared_statements_disabled_cache.add(object_id) if @prepared_statements
cache = prepared_statements_disabled_cache.add?(object_id) if @prepared_statements
yield
ensure
cache&.delete(object_id)
Expand Down
16 changes: 16 additions & 0 deletions activerecord/test/cases/bind_parameter_test.rb
Expand Up @@ -173,6 +173,22 @@ def test_bind_params_to_sql_with_unprepared_statements
end
end

def test_nested_unprepared_statements
assert_predicate @connection, :prepared_statements?

@connection.unprepared_statement do
assert_not_predicate @connection, :prepared_statements?

@connection.unprepared_statement do
assert_not_predicate @connection, :prepared_statements?
end

assert_not_predicate @connection, :prepared_statements?
end

assert_predicate @connection, :prepared_statements?
end

private
def assert_bind_params_to_sql
table = Author.quoted_table_name
Expand Down

0 comments on commit da26910

Please sign in to comment.