Fast Python bindings for the UnQLite embedded NoSQL database.
Database lifecycle management including connection handling, configuration, and database-wide operations. UnQLite supports both file-based and in-memory databases with flexible configuration options.
Initialize and manage database connections with various configuration options.
def __init__(self, filename=':mem:', flags=UNQLITE_OPEN_CREATE, open_database=True, thread_safe=True):
"""Initialize UnQLite database connection.
Args:
filename: Database file path or ':mem:' for in-memory database
flags: Open mode flags (UNQLITE_OPEN_*)
open_database: Whether to open database immediately
thread_safe: Enable thread-safe operations
"""
...
def open(self):
"""Open database connection. Returns True if successful."""
...
def close(self):
"""Close database connection. Returns True if successful."""
...
def flush(self):
"""Synchronize database changes to disk. Only for file-based databases."""
...Usage Example:
import unqlite
# In-memory database (default)
db = unqlite.UnQLite()
# File-based database with automatic creation
db = unqlite.UnQLite('mydata.db')
# Read-only database
db = unqlite.UnQLite('readonly.db', flags=unqlite.UNQLITE_OPEN_READONLY)
# Manual connection management
db = unqlite.UnQLite('manual.db', open_database=False)
db.open()
# ... use database
db.close()Automatic resource management using Python context managers.
def __enter__(self):
"""Enter context manager. Opens database if not already open."""
...
def __exit__(self, exc_type, exc_val, exc_tb):
"""Exit context manager. Closes database connection."""
...Usage Example:
# Automatic cleanup with context manager
with unqlite.UnQLite('data.db') as db:
db['key'] = 'value'
result = db['key']
# Database automatically closed when exiting context
# Context manager with error handling
try:
with unqlite.UnQLite('data.db') as db:
db['important_data'] = 'critical_value'
# If exception occurs, database is still properly closed
raise Exception("Something went wrong")
except Exception as e:
print(f"Error occurred: {e}")
# Database was properly closed despite the exceptionAccess database metadata and state information.
@property
def is_memory(self):
"""Returns True if database is in-memory."""
...
@property
def is_open(self):
"""Returns True if database connection is open."""
...
@property
def filename(self):
"""Returns database filename."""
...
@property
def flags(self):
"""Returns open mode flags."""
...
def __len__(self):
"""Return total number of records in database. O(n) operation."""
...Usage Example:
db = unqlite.UnQLite('example.db')
print(f"Database file: {db.filename}")
print(f"Is in-memory: {db.is_memory}")
print(f"Is open: {db.is_open}")
print(f"Open flags: {db.flags}")
# Add some data
db['key1'] = 'value1'
db['key2'] = 'value2'
# Count records (expensive for large databases)
record_count = len(db)
print(f"Total records: {record_count}")Remove all records from the database.
def flush(self):
"""Remove all records from database. Returns number of deleted records.
Note: This is an O(n) operation requiring iteration through entire key-space.
"""
...Usage Example:
db = unqlite.UnQLite(':mem:')
# Add test data
for i in range(10):
db[f'key{i}'] = f'value{i}'
print(f"Records before flush: {len(db)}") # 10
# Clear all data
deleted_count = db.flush()
print(f"Deleted {deleted_count} records")
print(f"Records after flush: {len(db)}") # 0Control database behavior with open mode flags:
# Read-only access
unqlite.UNQLITE_OPEN_READONLY
# Read-write access
unqlite.UNQLITE_OPEN_READWRITE
# Create database if it doesn't exist (default)
unqlite.UNQLITE_OPEN_CREATE
# Exclusive access
unqlite.UNQLITE_OPEN_EXCLUSIVE
# Temporary database
unqlite.UNQLITE_OPEN_TEMP_DB
# Disable mutex locking
unqlite.UNQLITE_OPEN_NOMUTEX
# Disable journaling
unqlite.UNQLITE_OPEN_OMIT_JOURNALING
# Force in-memory mode
unqlite.UNQLITE_OPEN_IN_MEMORY
# Use memory mapping
unqlite.UNQLITE_OPEN_MMAPUsage Example:
# Combine multiple flags using bitwise OR
flags = unqlite.UNQLITE_OPEN_READWRITE | unqlite.UNQLITE_OPEN_NOMUTEX
db = unqlite.UnQLite('fast.db', flags=flags)
# Read-only database
readonly_db = unqlite.UnQLite('data.db', flags=unqlite.UNQLITE_OPEN_READONLY)
# High-performance in-memory database
memory_db = unqlite.UnQLite(':mem:', flags=unqlite.UNQLITE_OPEN_IN_MEMORY | unqlite.UNQLITE_OPEN_NOMUTEX)UnQLite can be configured for thread-safe operations:
# Thread-safe database (default)
db = unqlite.UnQLite('shared.db', thread_safe=True)
# Single-threaded optimization
db = unqlite.UnQLite('private.db', thread_safe=False)Thread safety affects global library configuration and should be set consistently across all database instances in an application.
Database management operations can raise various exceptions:
try:
db = unqlite.UnQLite('/invalid/path/database.db')
except unqlite.UnQLiteError as e:
print(f"Failed to open database: {e}")
try:
db.open()
except unqlite.UnQLiteError as e:
print(f"Failed to open connection: {e}")Install with Tessl CLI
npx tessl i tessl/pypi-unqlite