Fast Python bindings for the UnQLite embedded NoSQL database.
Embedded Jx9 scripting engine for complex database operations and JSON manipulation with variable management. Jx9 is a JavaScript-like scripting language designed for database operations and JSON document processing.
Create and manage Jx9 virtual machines for script execution.
def vm(self, code):
"""Create an UnQLite Jx9 virtual machine.
Returns VM object."""
...
class VM:
def __init__(self, unqlite, code):
"""Initialize VM with database connection and script code."""
...
def __enter__(self):
"""Enter context manager. Compiles script."""
...
def __exit__(self, exc_type, exc_val, exc_tb):
"""Exit context manager. Closes VM."""
...Usage Example:
db = unqlite.UnQLite(':mem:')
# Simple Jx9 script
script = """
$key = 'hello';
$value = 'world';
db_store($key, $value);
$result = db_fetch($key);
"""
# Create and use VM
vm = db.vm(script)
# Use as context manager for automatic cleanup
with db.vm(script) as vm:
vm.execute()
result = vm.get_value('result')
print(f"Script result: {result}") # "world"Compile and execute Jx9 scripts with error handling.
def compile(self):
"""Compile the Jx9 script."""
...
def execute(self):
"""Execute the compiled Jx9 script."""
...
def reset(self):
"""Reset VM state for re-execution."""
...
def close(self):
"""Close and release the virtual machine."""
...Usage Example:
db = unqlite.UnQLite(':mem:')
script = """
// Jx9 script to process data
$users = [
{'name': 'Alice', 'age': 30},
{'name': 'Bob', 'age': 25},
{'name': 'Charlie', 'age': 35}
];
$adult_count = 0;
foreach($users as $user) {
if ($user.age >= 18) {
$adult_count++;
db_store('user:' + $user.name, $user);
}
}
$result = $adult_count;
"""
vm = db.vm(script)
try:
# Manual VM management
vm.compile()
vm.execute()
adults = vm.get_value('result')
print(f"Adults processed: {adults}")
# Re-execute with reset
vm.reset()
vm.execute()
finally:
vm.close()Pass data between Python and Jx9 scripts using variables.
def set_value(self, name, value):
"""Set the value of a variable in the Jx9 script."""
...
def get_value(self, name):
"""Retrieve the value of a variable after script execution."""
...
def set_values(self, dict data):
"""Set multiple variables from dictionary."""
...
def __setitem__(self, name, value):
"""Set variable using vm[name] = value syntax."""
...
def __getitem__(self, name):
"""Get variable using vm[name] syntax."""
...Usage Example:
db = unqlite.UnQLite(':mem:')
script = """
// Process input data from Python
$total = 0;
foreach($numbers as $num) {
$total += $num;
}
$average = $total / count($numbers);
$summary = {
'total': $total,
'count': count($numbers),
'average': $average
};
"""
with db.vm(script) as vm:
# Pass data to script
vm.set_value('numbers', [10, 20, 30, 40, 50])
# Alternative syntax
vm['multiplier'] = 2
# Set multiple values
vm.set_values({
'threshold': 25,
'category': 'test_data'
})
vm.execute()
# Retrieve results
summary = vm.get_value('summary')
print(f"Summary: {summary}")
# Alternative syntax
total = vm['total']
print(f"Total: {total}")Jx9 supports JavaScript-like data types with automatic conversion:
db = unqlite.UnQLite(':mem:')
script = """
// Strings
$text = 'Hello, World!';
// Numbers
$integer = 42;
$float = 3.14159;
// Booleans
$flag = true;
$disabled = false;
// Arrays
$list = [1, 2, 3, 'mixed', true];
// Objects (associative arrays)
$person = {
'name': 'Alice',
'age': 30,
'active': true
};
// Null
$empty = null;
"""
with db.vm(script) as vm:
vm.execute()
# Python automatically converts types
person = vm['person']
print(f"Person: {person}") # Python dict
list_data = vm['list']
print(f"List: {list_data}") # Python listJx9 provides built-in functions for database manipulation:
db = unqlite.UnQLite(':mem:')
script = """
// Key-value operations
db_store('user:1', {'name': 'Alice', 'role': 'admin'});
db_store('user:2', {'name': 'Bob', 'role': 'user'});
// Fetch data
$alice = db_fetch('user:1');
$exists = db_exists('user:1');
// Delete data
db_delete('user:2');
// Check existence after delete
$bob_exists = db_exists('user:2');
$results = {
'alice': $alice,
'alice_exists': $exists,
'bob_exists': $bob_exists
};
"""
with db.vm(script) as vm:
vm.execute()
results = vm['results']
print(f"Results: {results}")Jx9 excels at JSON document manipulation:
db = unqlite.UnQLite(':mem:')
script = """
// Create collection
if (!db_exists('products')) {
db_create('products');
}
// Store documents
$products = [
{'name': 'Laptop', 'price': 999.99, 'category': 'electronics'},
{'name': 'Book', 'price': 19.99, 'category': 'education'},
{'name': 'Coffee', 'price': 4.99, 'category': 'food'}
];
foreach($products as $product) {
db_store('products', $product);
}
// Query documents
$all_products = db_fetch_all('products');
$product_count = db_total_records('products');
$summary = {
'total_products': $product_count,
'products': $all_products
};
"""
with db.vm(script) as vm:
vm.execute()
summary = vm['summary']
print(f"Product summary: {summary}")Jx9 supports standard control flow constructs:
db = unqlite.UnQLite(':mem:')
script = """
$data = [10, 25, 5, 30, 15];
$processed = [];
$stats = {'min': null, 'max': null, 'sum': 0};
// Foreach loop
foreach($data as $value) {
$stats.sum += $value;
// Conditional processing
if ($stats.min == null || $value < $stats.min) {
$stats.min = $value;
}
if ($stats.max == null || $value > $stats.max) {
$stats.max = $value;
}
// Transform data
if ($value > 20) {
$processed[] = $value * 2;
} else {
$processed[] = $value;
}
}
$stats.average = $stats.sum / count($data);
$results = {'stats': $stats, 'processed': $processed};
"""
with db.vm(script) as vm:
vm.execute()
results = vm['results']
print(f"Processing results: {results}")Handle errors in Jx9 scripts with proper exception management:
db = unqlite.UnQLite(':mem:')
# Script with potential errors
script = """
try {
$data = db_fetch('nonexistent_key');
$success = true;
} catch($error) {
$success = false;
$error_msg = 'Key not found';
}
$result = {'success': $success, 'error': $error_msg};
"""
try:
with db.vm(script) as vm:
vm.execute()
result = vm['result']
print(f"Script result: {result}")
except unqlite.UnQLiteError as e:
print(f"VM execution failed: {e}")Use Jx9 for complex data transformations and business logic:
db = unqlite.UnQLite('analytics.db')
# Complex analytics script
script = """
// Load user activity data
$users = db_fetch_all('users');
$activities = db_fetch_all('activities');
$analytics = {};
foreach($users as $user) {
$user_id = $user.__id;
$user_activities = [];
// Filter activities for this user
foreach($activities as $activity) {
if ($activity.user_id == $user_id) {
$user_activities[] = $activity;
}
}
// Calculate metrics
$total_time = 0;
$activity_types = {};
foreach($user_activities as $activity) {
$total_time += $activity.duration;
if (!isset($activity_types[$activity.type])) {
$activity_types[$activity.type] = 0;
}
$activity_types[$activity.type]++;
}
$analytics[$user.name] = {
'total_activities': count($user_activities),
'total_time': $total_time,
'activity_breakdown': $activity_types,
'average_duration': $total_time / count($user_activities)
};
}
// Store analytics results
db_store('analytics_summary', $analytics);
"""
with db.vm(script) as vm:
vm.execute()
print("Analytics processing completed")While not directly exposed in the Python API, Jx9 scripts can define custom functions:
db = unqlite.UnQLite(':mem:')
script = """
// Define custom function
function calculate_tax($amount, $rate) {
return $amount * ($rate / 100);
}
function format_currency($amount) {
return '$' + round($amount, 2);
}
// Use custom functions
$orders = [
{'item': 'Laptop', 'price': 999.99},
{'item': 'Mouse', 'price': 29.99},
{'item': 'Keyboard', 'price': 79.99}
];
$tax_rate = 8.5;
$processed_orders = [];
foreach($orders as $order) {
$tax = calculate_tax($order.price, $tax_rate);
$total = $order.price + $tax;
$processed_orders[] = {
'item': $order.item,
'price': format_currency($order.price),
'tax': format_currency($tax),
'total': format_currency($total)
};
}
$results = $processed_orders;
"""
with db.vm(script) as vm:
vm.execute()
results = vm['results']
for order in results:
print(f"Order: {order}")# Efficient: Reuse compiled VM
db = unqlite.UnQLite(':mem:')
script = "$result = $input * 2;"
vm = db.vm(script)
vm.compile()
for i in range(100):
vm.set_value('input', i)
vm.execute()
result = vm.get_value('result')
vm.reset() # Reset for next execution
vm.close()Install with Tessl CLI
npx tessl i tessl/pypi-unqlite