WorkerSQL Python SDK
WorkerSQL Python SDK
Section titled “WorkerSQL Python SDK”A Python SDK for WorkerSQL - bringing MySQL-compatible database operations to the edge with Cloudflare Workers.
Features
Section titled “Features”- 🚀 Edge-Native: Run SQL queries at the edge for ultra-low latency
- 🔒 Secure: Built-in SQL injection prevention and schema validation
- 📊 MySQL Compatible: Familiar SQL syntax with MySQL compatibility
- 🔄 Async Support: Modern async/await support with httpx
- 📝 Type Safe: Full type hints and Pydantic validation
- 🧪 Well Tested: Comprehensive test coverage with pytest
- 📚 Well Documented: Complete API documentation and examples
Installation
Section titled “Installation”From PyPI (Recommended)
Section titled “From PyPI (Recommended)”pip install workersql-python-sdk
From Source
Section titled “From Source”git clone https://github.com/healthfees-org/workersql.gitcd workersql/sdk/pythonpip install -e .
Development Installation
Section titled “Development Installation”git clone https://github.com/healthfees-org/workersql.gitcd workersql/sdk/pythonpip install -e ".[dev]"
Quick Start
Section titled “Quick Start”Using DSN String
Section titled “Using DSN String”from workersql_client import WorkerSQLClient
# Connect using DSN
# Execute a queryresult = client.query("SELECT * FROM users WHERE id = ?", [1])print(f"User: {result.data}")
# Close the connectionclient.close()
Using Configuration Dict
Section titled “Using Configuration Dict”from workersql_client import WorkerSQLClient
# Initialize clientconfig = { "host": "api.workersql.com", "port": 443, "database": "mydb", "username": "myuser", "password": "mypass", "api_key": "your-api-key", "ssl": True, "pooling": { "enabled": True, "min_connections": 2, "max_connections": 10 }}
with WorkerSQLClient(config=config) as client: # Execute queries users = client.query("SELECT * FROM users") print(f"Users: {users.data}")
# Execute batch queries queries = [ {"sql": "INSERT INTO users (name, email) VALUES (?, ?)", "params": ["John Doe", "[email protected]"]}, ] batch_result = client.batch_query(queries) print(f"Batch result: {batch_result}")
Configuration
Section titled “Configuration”Environment Variables
Section titled “Environment Variables”Create a .env
file in your project root:
WORKERSQL_API_ENDPOINT=https://your-endpoint.com/apiWORKERSQL_API_KEY=your-api-keyWORKERSQL_HOST=your-database-hostWORKERSQL_USERNAME=your-usernameWORKERSQL_PASSWORD=your-passwordWORKERSQL_DATABASE=your-databaseWORKERSQL_SSL=trueWORKERSQL_TIMEOUT=30000
Programmatic Configuration
Section titled “Programmatic Configuration”from workersql_client import WorkerSQLClient
config = { "api_endpoint": "https://your-endpoint.com/api", "api_key": "your-api-key", # Optional "host": "localhost", "username": "user", "password": "password", "database": "mydb", "port": 3306, "ssl": True, "timeout": 30000, "retry_attempts": 3, "retry_delay": 1.0,}
API Reference
Section titled “API Reference”WorkerSQLClient
Section titled “WorkerSQLClient”Methods
Section titled “Methods”query(sql, params=None, timeout=None, cache=None)
- Execute a single SQL querybatch_query(queries, transaction=False, stop_on_error=True)
- Execute multiple querieshealth_check()
- Check service healthclose()
- Close the client connection
Query Parameters
Section titled “Query Parameters”sql
: SQL query stringparams
: Query parameters (list)timeout
: Query timeout in milliseconds (default: 30000)cache
: Cache options (optional)
Cache Options
Section titled “Cache Options”cache_options = { "enabled": True, "ttl": 300, # seconds "key": "custom-cache-key" # optional}
Error Handling
Section titled “Error Handling”from workersql_client import WorkerSQLClient, ValidationError
try: with WorkerSQLClient(config) as client: result = client.query("SELECT * FROM invalid_table")except ValidationError as e: print(f"Validation error: {e.code} - {e.message}")except Exception as e: print(f"Unexpected error: {e}")
Async Support
Section titled “Async Support”import asyncioimport httpxfrom workersql_client import WorkerSQLClient
async def async_query(): # Using httpx for async HTTP requests async with httpx.AsyncClient() as http_client: # Configure client to use async HTTP client config["http_client"] = http_client client = WorkerSQLClient(config)
result = await client.query_async("SELECT * FROM users") print(f"Async result: {result}")
asyncio.run(async_query())
Schema Validation
Section titled “Schema Validation”The SDK includes built-in schema validation using JSON Schema:
from workersql_client import SchemaValidator
# Validate query requestrequest = { "sql": "SELECT * FROM users", "params": [], "timeout": 30000}
try: validated = SchemaValidator.validate_query_request(request) print("Request is valid!")except ValidationError as e: print(f"Invalid request: {e}")
Development
Section titled “Development”Running Tests
Section titled “Running Tests”# Run all testspytest
# Run with coveragepytest --cov=workersql_client
# Run specific test filepytest tests/test_client.py
Code Quality
Section titled “Code Quality”# Format codeblack .
# Sort importsisort .
# Type checkingmypy .
# Lintingruff check .
# Security scanningbandit -r .
Building Documentation
Section titled “Building Documentation”pip install -e ".[docs]"sphinx-build docs _build/html
Contributing
Section titled “Contributing”- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
License
Section titled “License”This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
Support
Section titled “Support”Changelog
Section titled “Changelog”See CHANGELOG.md for release notes.