Skip to content

Conversation

@abrookins
Copy link
Collaborator

Adds support for Redis NX (only set if not exists) and XX (only set if exists) semantics to the save() method.

Usage

# Insert-only: save only if key doesn't exist
result = await model.save(nx=True)
if result is None:
    print("Key already exists, nothing saved")

# Update-only: save only if key already exists  
result = await model.save(xx=True)
if result is None:
    print("Key doesn't exist, nothing saved")

Implementation

  • JsonModel: Uses JSON.SET's native NX/XX support (atomic)
  • HashModel: Uses EXISTS check before HSET (best-effort, not atomic)
  • Returns None if condition not met, the model instance otherwise
  • Raises ValueError if both nx and xx are True

Rationale

These flags are standard Redis semantics for conditional writes. Exposing them via save() follows the same pattern as the existing pipeline parameter - giving power users access to Redis performance features when needed.

Closes #703

abrookins and others added 5 commits December 24, 2025 11:44
Adds support for Redis NX (only set if not exists) and XX (only set if
exists) semantics to the save() method on both HashModel and JsonModel.

- save(nx=True): Only saves if the key does NOT exist (insert-only)
- save(xx=True): Only saves if the key already exists (update-only)
- Returns None if the condition is not met, the model instance otherwise

For JsonModel, this uses JSON.SET's native NX/XX support.
For HashModel, this uses an EXISTS check before HSET.

Closes #703
- HashModel raises ValueError when nx/xx used with pipeline (not atomic)
- JsonModel supports nx/xx with pipeline (JSON.SET is atomic)
- Added test coverage for these behaviors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

.save() downstream runs Redis SET with nx=False as the default, how do I run .save() such that downstream it runs a SET op with nx=True

2 participants