dbzero.get_state_num(prefix=None, finalized=False)
Returns the state number for a given data prefix. The state number is an integer that increments with each transaction commit, acting as a version identifier for the database state.
This method is crucial for tracking changes, creating dbzero.snapshot() instances of specific states, and for synchronization tasks like dbzero.async_wait().
Parameters
prefix(str, optional): The name of the prefix to get the state number for. IfNoneor omitted, it defaults to the current prefix.finalized(bool, optional):- If
False(default), returns the pending state number. This number reflects the state after the most recent modifications, even if they haven't been committed. - If
True, returns the last finalized state number, which represents the state after the last successful commit.
- If
Returns
(int): The integer state number.
Examples
Basic Usage
The state number increases after modifications are committed. By default, dbzero uses autocommit.
# Initial state
state_1 = db0.get_state_num()
print(state_1) # e.g., 1
# Modify an object
obj = MemoTestClass(100)
obj.value = 200
# Wait for autocommit to trigger
import time
time.sleep(0.3)
# The state number has increased
state_2 = db0.get_state_num()
print(state_2 > state_1) # TruePending vs. Finalized State
You can distinguish between the pending state (including uncommitted changes) and the last saved state.
db0.commit()
finalized_state = db0.get_state_num(finalized=True)
pending_state = db0.get_state_num(finalized=False)
# Before any new changes, pending equals finalized
assert pending_state > finalized_state
# Modify an object
obj = MemoTestClass(123)
obj.value = 456
# The pending state number for the next transaction is now available,
# but the finalized state remains the same until a commit.
new_pending_state = db0.get_state_num()
assert new_pending_state == pending_state
assert db0.get_state_num(finalized=True) == finalized_state
# After commit, the finalized state catches up
db0.commit()
new_finalized_state = db0.get_state_num(finalized=True)
assert new_finalized_state == new_pending_stateGetting State for a Specific Prefix
If your application uses multiple data prefixes, you can retrieve the state number for each one individually.
# Assume 'data-prefix-A' and 'data-prefix-B' are open
state_A = db0.get_state_num(prefix="data-prefix-A")
state_B = db0.get_state_num(prefix="data-prefix-B")
print(f"State of A: {state_A}, State of B: {state_B}")
# Modify an object only in prefix B
obj_B = MemoScopedClass(1, prefix="data-prefix-B")
obj_B.value = 2
db0.commit()
# Only state_B will change
assert db0.get_state_num(prefix="data-prefix-A") == state_A
assert db0.get_state_num(prefix="data-prefix-B") > state_B