Skip to content
Open
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
16 changes: 9 additions & 7 deletions packages/google-cloud-ndb/google/cloud/ndb/_datastore_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,7 @@ def delete(key, options):
use_global_cache = context._use_global_cache(key, options)
use_datastore = context._use_datastore(key, options)
transaction = context.transaction
lock = None

if use_global_cache:
cache_key = _cache.global_cache_key(key)
Expand All @@ -450,17 +451,18 @@ def delete(key, options):
yield batch.delete(key)

if use_global_cache:
if transaction:
if lock:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since lock is initialized to None to represent the absence of an acquired lock, it is safer and more explicit to check if lock is not None: instead of if lock:. This prevents potential issues if a valid lock representation ever evaluates to falsy (e.g., an empty string or integer 0).

Suggested change
if lock:
if lock is not None:

if transaction:

def callback():
_cache.global_unlock_for_write(cache_key, lock).result()
def callback():
_cache.global_unlock_for_write(cache_key, lock).result()

context.call_on_transaction_complete(callback)
context.call_on_transaction_complete(callback)

elif use_datastore:
yield _cache.global_unlock_for_write(cache_key, lock)
else:
yield _cache.global_unlock_for_write(cache_key, lock)

else:
elif not use_datastore:
yield _cache.global_delete(cache_key)


Expand Down
25 changes: 25 additions & 0 deletions packages/google-cloud-ndb/tests/unit/test__datastore_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -921,6 +921,31 @@ def test_without_datastore(Batch, global_cache):

assert global_cache.get([cache_key]) == [None]

@staticmethod
@mock.patch("google.cloud.ndb._datastore_api._NonTransactionalCommitBatch")
def test_without_datastore_with_transaction(Batch, global_cache):
context = context_module.get_context()
callbacks = []

with context.new(
transaction=b"abc123", transaction_complete_callbacks=callbacks
).use():
key = key_module.Key("SomeKind", 1)
cache_key = _cache.global_cache_key(key._key)
global_cache.set({cache_key: b"foo"})

batch = Batch.return_value
batch.delete.side_effect = Exception("Shouldn't use Datastore")

future = _api.delete(
key._key,
_options.Options(use_datastore=False),
)
assert future.result() is None

assert callbacks == []
assert global_cache.get([cache_key]) == [None]

@staticmethod
@mock.patch("google.cloud.ndb._datastore_api._NonTransactionalCommitBatch")
def test_cache_disabled(Batch, global_cache):
Expand Down
Loading