Skip to content

MONGOID-5144 Add a deprecation warning when using the legacy query cache #5042

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Aug 26, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion lib/mongoid/query_cache.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,14 @@ module Mongoid

# A cache of database queries on a per-request basis.
module QueryCache
class << self
# @api private
LEGACY_WARNING = <<~DOC
You are using the legacy Mongoid query cache which has known issues.
Please upgrade the `mongo' gem to at least 2.14.0 to use the improved driver query cache.
Refer to: https://docs.mongodb.com/mongoid/current/tutorials/mongoid-queries/#the-improved-driver-query-cache
DOC

class << self
# Get the cached queries.
#
# @example Get the cached queries from the current thread.
Expand Down Expand Up @@ -73,6 +79,10 @@ def cache(&block)
if defined?(Mongo::QueryCache)
Mongo::QueryCache.cache(&block)
else
@legacy_query_cache_warned ||= begin
Mongoid.logger.warn(LEGACY_WARNING)
true
end
enabled = QueryCache.enabled?
QueryCache.enabled = true
begin
Expand Down
24 changes: 24 additions & 0 deletions spec/mongoid/query_cache_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,27 @@
SessionRegistry.instance.verify_sessions_ended!
end

let(:reset_legacy_qc_warning) do
begin
Mongoid::QueryCache.remove_instance_variable('@legacy_query_cache_warned')
rescue NameError
# raised if the instance variable wasn't set
end
end

describe '#cache' do
context 'with driver query cache' do
min_driver_version '2.14'

it 'does not log a deprecation warning' do
reset_legacy_qc_warning

expect_any_instance_of(Logger).to_not receive(:warn).with(
described_class::LEGACY_WARNING
)
described_class.cache { }
end

context 'when query cache is not enabled' do
before do
Mongoid::QueryCache.enabled = false
Expand Down Expand Up @@ -179,6 +196,13 @@
context 'with mongoid query cache' do
max_driver_version '2.13'

it 'logs a deprecation warning' do
reset_legacy_qc_warning

expect_any_instance_of(Logger).to receive(:warn).with(described_class::LEGACY_WARNING)
described_class.cache { }
end

context 'when query cache is not enabled' do
before do
Mongoid::QueryCache.enabled = false
Expand Down