CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-unqlite

Fast Python bindings for the UnQLite embedded NoSQL database.

Overview
Eval results
Files

key-value.mddocs/

Key-Value Storage

Core database operations for storing, retrieving, and managing key-value pairs in UnQLite. Provides both explicit method calls and Python dictionary-style interface for natural data access patterns.

Capabilities

Basic Storage Operations

Store, retrieve, and delete key-value pairs with automatic type handling.

def store(self, key, value):
    """Store key-value pair in database."""
    ...

def fetch(self, key):
    """Retrieve value at given key. Raises KeyError if key not found."""
    ...

def delete(self, key):
    """Delete the value stored at the given key."""
    ...

def append(self, key, value):
    """Append to the value stored in the given key."""
    ...

Usage Example:

db = UnQLite(':mem:')

# Store data
db.store('user:1', '{"name": "Alice", "age": 30}')
db.store('counter', '0')

# Retrieve data
user_data = db.fetch('user:1')
print(user_data)  # '{"name": "Alice", "age": 30}'

# Append to existing value
db.append('counter', '1')
counter_value = db.fetch('counter')
print(counter_value)  # '01'

# Delete data
db.delete('user:1')

Dictionary-Style Interface

Python dictionary-like operations for natural data access.

def __setitem__(self, key, value):
    """Store key-value pair using db[key] = value syntax."""
    ...

def __getitem__(self, key):
    """Retrieve value using db[key] syntax. Raises KeyError if not found."""
    ...

def __delitem__(self, key):
    """Delete key using del db[key] syntax."""
    ...

def __contains__(self, key):
    """Check if key exists using 'key in db' syntax."""
    ...

Usage Example:

db = UnQLite(':mem:')

# Dictionary-style operations
db['name'] = 'UnQLite Database'
db['version'] = '1.1.9'
db['features'] = ['key-value', 'json', 'transactions']

# Check existence
if 'name' in db:
    print(f"Database name: {db['name']}")

# Iterate over all items
for key in db:
    print(f"{key}: {db[key]}")

# Delete items
del db['version']

Existence Checking

Check if keys exist in the database without retrieving values.

def exists(self, key):
    """Check if key exists in database. Returns boolean."""
    ...

Usage Example:

db = UnQLite(':mem:')
db['test_key'] = 'test_value'

# Explicit existence check
if db.exists('test_key'):
    print("Key exists")

# Using 'in' operator (equivalent)
if 'test_key' in db:
    print("Key exists")

Bulk Operations

Update multiple key-value pairs efficiently.

def update(self, dict values):
    """Update database with multiple key-value pairs from dictionary."""
    ...

Iteration Methods

Efficiently iterate through database keys, values, or key-value pairs.

def keys(self):
    """Efficiently iterate through the database's keys."""
    ...

def values(self):
    """Efficiently iterate through the database's values."""
    ...

def items(self):
    """Efficiently iterate through the database's key/value pairs."""
    ...

def range(self, start_key, end_key, include_end_key=True):
    """Iterate through a range of keys."""
    ...

def __len__(self):
    """Return the total number of records in the database."""
    ...

def __iter__(self):
    """Return iterator over database keys."""
    ...

Usage Example:

db = UnQLite(':mem:')

# Add test data
for i in range(5):
    db[f'key{i:02d}'] = f'value{i}'

# Iterate over keys
print("Keys:")
for key in db.keys():
    print(f"  {key}")

# Iterate over values  
print("Values:")
for value in db.values():
    print(f"  {value}")

# Iterate over key-value pairs
print("Items:")
for key, value in db.items():
    print(f"  {key}: {value}")

# Range iteration
print("Range key01 to key03:")
for key, value in db.range('key01', 'key03'):
    print(f"  {key}: {value}")

# Get total count
print(f"Total records: {len(db)}")

# Use iterator protocol
print("Using iterator:")
for key in db:
    print(f"  {key}: {db[key]}")

Data Encoding

UnQLite automatically handles encoding between Python strings and bytes. String data is encoded as UTF-8 for storage and decoded back to strings when retrieved. Binary data can be stored as bytes objects.

db = UnQLite(':mem:')

# Bulk update
user_data = {
    'user:1': '{"name": "Alice", "email": "alice@example.com"}',
    'user:2': '{"name": "Bob", "email": "bob@example.com"}',
    'settings': '{"theme": "dark", "notifications": true}'
}

db.update(user_data)

# Verify data was stored
for key in user_data:
    print(f"{key}: {db[key]}")

Data Encoding

UnQLite automatically handles encoding between Python strings and bytes. String data is encoded as UTF-8 for storage and decoded back to strings when retrieved. Binary data can be stored as bytes objects.

db = UnQLite(':mem:')

# String data (automatically encoded/decoded)
db['text'] = 'Hello, 世界!'
text = db['text']  # Returns string

# Binary data  
db['binary'] = b'\x00\x01\x02\x03'
binary = db['binary']  # Returns bytes

# JSON data (stored as strings)
import json
db['json_data'] = json.dumps({'key': 'value'})
data = json.loads(db['json_data'])

Error Handling

Key-value operations raise standard Python exceptions:

  • KeyError: Raised when trying to fetch or delete non-existent keys
  • UnQLiteError: Raised for database-level errors
  • MemoryError: Raised when out of memory
  • NotImplementedError: Raised for unsupported operations
db = UnQLite(':mem:')

try:
    value = db['nonexistent_key']
except KeyError:
    print("Key not found")

try:
    db.store('key', 'value')
except UnQLiteError as e:
    print(f"Database error: {e}")

Install with Tessl CLI

npx tessl i tessl/pypi-unqlite

docs

cursors.md

database-management.md

index.md

json-collections.md

jx9-scripting.md

key-value.md

transactions.md

utilities.md

tile.json