Database¶
Viper provides two database types for persistence:
Type |
Use Case |
History |
|---|---|---|
|
Simple key-value storage |
No |
|
Versioned data |
Yes (DAG) |
This page covers the simple Database. For versioned storage,
see CommitDatabase.
Creating a Database¶
>>> from dsviper import *
# Create in memory
>>> db = Database.create_in_memory()
# Create on disk
>>> db = Database.create("data.vdb")
# Open existing
>>> db = Database.open("data.vdb")
Setting Up Definitions¶
# Load definitions from DSM
>>> builder = DSMBuilder.assemble("model.dsm")
>>> report, dsm_defs, defs = builder.parse()
# Extend database with definitions
>>> db.extend_definitions(defs)
>>> defs.inject()
CRUD Operations¶
# Create
>>> key = TUTO_A_USER_LOGIN.create_key()
>>> login = TUTO_A_USER_LOGIN.create_document()
>>> login.nickname = "alice"
# Write (requires transaction)
>>> db.begin_transaction()
>>> db.set(TUTO_A_USER_LOGIN, key, login)
>>> db.commit()
# Read
>>> result = db.get(TUTO_A_USER_LOGIN, key)
>>> result.unwrap()
{nickname='alice', password=''}
# Update
>>> db.begin_transaction()
>>> login.password = "secret"
>>> db.set(TUTO_A_USER_LOGIN, key, login)
>>> db.commit()
# Delete
>>> db.begin_transaction()
>>> db.delete(TUTO_A_USER_LOGIN, key)
>>> db.commit()
# List all keys
>>> db.keys(TUTO_A_USER_LOGIN)
[key1, key2, ...]
Transactions¶
All write operations require a transaction:
>>> db.begin_transaction()
>>> # ... mutations ...
>>> db.commit() # Apply changes
# Or rollback
>>> db.begin_transaction()
>>> # ... mutations ...
>>> db.rollback() # Discard changes
Safe transaction pattern - Always use try/finally to ensure cleanup:
db.begin_transaction()
try:
db.set(attachment, key, document)
db.commit()
except ViperError:
db.rollback()
raise
Choosing Between Database and CommitDatabase¶
Feature |
Database |
CommitDatabase |
|---|---|---|
Simple CRUD |
✓ |
✓ |
History |
✗ |
✓ |
Sync |
✗ |
✓ |
Embedded definitions |
✗ |
✓ |
Use case |
Caches, temp storage |
Application data |
What’s Next¶
CommitDatabase - Versioned database with history
Blobs - Binary data storage