Skip to main content

๐Ÿ Python Client

Welcome to the official ZTeraDB Python Client documentation. This package implements a high-performance, ZQL-first database driver utilizing a raw TCP socket transport layer.

๐Ÿ“˜ What Is ZTeraDB?โ€‹

ZTeraDB allows you to connect to your existing databases (PostgreSQL, MySQL, MSSQL, etc.) through a single, unified platform using One Unified Query Language (ZQL).

Technical Overviewโ€‹

This package implements a performance-optimized, ZQL-first Python client utilizing an asynchronous, raw TCP socket transport layer.

To ensure low-overhead binary framing, the client communicates with the ZTeraDB server using 4-byte big-endian length-prefixed payloads containing structured JSON data. This underlying transport architecture eliminates HTTP overhead, offering high-throughput query execution directly from your Python runtime via asyncio.

๐Ÿง  Architecture Overviewโ€‹

You never connect to your backend databases directly. ZTeraDB handles all connections, cryptographic signing, proxy routing, and query execution securely behind the scenes.


โญ Key Featuresโ€‹

  • ๐Ÿš€ Unified Query Language (ZQL): Write once, run on any database.
  • ๐Ÿ”Œ Easy Integration: Seamlessly plugs into any Python application.
  • โš™๏ธ Auto-Managed Connections: Handles connection pooling and automatic retries.
  • ๐Ÿ” Secure Authentication: Protected via client, access, and secret keys.
  • ๐ŸŽฏ Clean Query Builder: Fluent interface for standard CRUD operations (insert, select, update, delete).
  • ๐Ÿ” Advanced Filtering: Built-in support for complex logical and mathematical filters.
  • ๐Ÿงต Streamed Results: Efficiently memory-manages large datasets using Python generators.
  • ๐Ÿ“ฆ Modern Ecosystem: Composer-ready and fully compatible with frameworks like Laravel, Symfony, and CodeIgniter.

๐Ÿ›  Prerequisites & Requirementsโ€‹

RequirementSpecification
Python VersionPython 3.8 or higher (Download from python.org)
DependenciesBuilt-in asyncio support and standard socket modules
Package RegistryAvailable via PyPI

Installationโ€‹

Run the following command in your terminal to install the ZTeraDB client:

# Using pip
pip install zteradb

Option 2: From GitHub Repositoryโ€‹

Alternatively, you can pull the package directly from GitHub using pip's VCS support:

pip install git+https://github.com/zteradb/zteradb-python.git

๐Ÿš€ 60-Second Quick Startโ€‹

import asyncio
import logging
import os
import sys
from typing import Any

from zteradb import ZTeraDBConnectionAsync, ZTeraDBQuery
from zteradb.config.connection_pool import ConnectionPool
from zteradb.config.envs import ENVS
from zteradb.config.options import Options
from zteradb.config.response_data_types import ResponseDataTypes
from zteradb.config.zteradb_config import ZTeraDBConfig

# Configure logging for production visibility
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)

def get_required_env(key: str) -> str:
"""Ensures crucial configuration variables exist before proceeding."""
value = os.getenv(key)
if not value:
logger.critical(f"Missing required environment variable: {key}")
sys.exit(1)
return value

async def main() -> None:
# 1. Setup Configuration
config = ZTeraDBConfig(
client_key=get_required_env("ZTERADB_CLIENT_KEY"),
access_key=get_required_env("ZTERADB_ACCESS_KEY"),
secret_key=get_required_env("ZTERADB_SECRET_KEY"),
database_id=get_required_env("ZTERADB_DATABASE_ID"),
env=ENVS(os.getenv("ZTERADB_ENV", "dev")),
response_data_type=ResponseDataTypes(os.getenv("ZTERADB_RESPONSE_TYPE", "json")),
options=Options(
connection_pool=ConnectionPool(
min=int(os.getenv("ZTERADB_POOL_MIN", 1)),
max=int(os.getenv("ZTERADB_POOL_MAX", 5))
)
),
)

# 2. Initialize Connection
host = get_required_env("ZTERADB_HOST")
try:
port = int(os.getenv("ZTERADB_PORT", "7777"))
except ValueError:
logger.error("Invalid ZTERADB_PORT format. Defaulting to 7777.")
port = 7777

db = ZTeraDBConnectionAsync(host, port, config)

# 3. Robust Execution Framework
try:
# Build ZQL Query
query = ZTeraDBQuery("user").select()

# Execute and Process Results
logger.info("Executing ZQL query...")
result: Any = await db.run(query)
print(result)

except Exception as e:
logger.error(f"Database operation failed: {e}", exc_info=True)

finally:
# 4. Guaranteed Cleanup
# Ensures network sockets are closed even if the query errors out
logger.info("Closing database connection...")
await db.close()

if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
logger.info("Application interrupted by user.")

๐Ÿ—‚ Documentation Sectionsโ€‹

Explore the rest of our guides to unlock the full potential of ZTeraDB:

  • ๐Ÿ” Configuration โ€” Learn all available configuration options.
  • ๐Ÿ”Œ Connection โ€” Deep dive into socket connections and lifecycle management.
  • ๐Ÿ” Query Builder โ€” Master building fluent ZQL queries.
  • ๐ŸŽ›๏ธ Filter Conditions โ€” Apply advanced math and logical filters to your data.
  • ๐ŸณExamples โ€” Copy-pasteable snippets for common use cases.
  • ๐Ÿ›  Troubleshooting Guide โ€” How to resolve common connection or runtime errors.
  • ๐Ÿš€ Quickstart Guide โ€” A streamlined, 5-minute setup guide.
  • ๐Ÿฅ‡ Licence โ€” Open-source licence terms.