SingleStoreDB Python SDK Architecture
This document describes the architecture of the SingleStoreDB Python SDK, explaining how the components fit together, their responsibilities, and their interactions.
Table of Contents
Overview
Purpose
The SingleStoreDB Python SDK provides:
DB-API 2.0 compliant interface to SingleStore databases
Cloud management API for workspace and cluster lifecycle management
Fusion SQL for client-side SQL command extension
External Functions (UDFs) for deploying Python functions to SingleStore
AI integrations for chat and embeddings
Design Principles
Protocol Abstraction: Single
connect()function handles both MySQL wire protocol and HTTP API connections transparentlyC Acceleration: Optional C extension provides 10x faster row parsing with pure Python fallback
Extensive Result Formats: Support for tuples, dicts, namedtuples, numpy, pandas, polars, and arrow formats
Environment-based Configuration: All parameters configurable via environment variables
Package Structure
Database Connectivity
The primary use case of the SDK is connecting to SingleStore databases. The connection layer provides a unified interface with protocol-specific implementations.
Connection Architecture
The entry point is singlestoredb.connect() in singlestoredb/connection.py:1312:
Protocol Selection Flow:
Connection Abstraction (singlestoredb/connection.py)
The high-level Connection and Cursor classes in connection.py define the abstract interface that both protocol implementations must satisfy.
Connection provides:
DB-API 2.0 compliance:
connect(),cursor(),commit(),rollback(),close()Context manager support:
with s2.connect(...) as conn:Variable accessor:
conn.locals.autocommit = TrueShow accessor:
conn.show.tables(),conn.show.databases()
Cursor provides:
DB-API 2.0 methods:
execute(),executemany(),fetchone(),fetchmany(),fetchall()Iteration support:
for row in cursor:Context manager:
with conn.cursor() as cur:Result metadata:
description,rowcount,rownumber
ShowAccessor
The ShowAccessor class provides convenient methods for SHOW commands:
VariableAccessor
The VariableAccessor class (conn.locals / conn.globals) provides attribute-style access to session and global variables:
MySQL Connector (singlestoredb/mysql/)
The MySQL connector is based on PyMySQL but heavily extended for SingleStore features.
SingleStore-Specific Features
The connector includes extensive SingleStore-specific functionality beyond standard MySQL:
Vector Data Types:
Extended Data Types:
VECTOR(n, F32/F64/I8/I16/I32/I64)- Dense vector types for ML embeddingsBSON- Binary JSON for document storageAutomatic conversion between Python types and SingleStore extended types
SingleStore SHOW Commands (via ShowAccessor):
Fusion SQL Integration:
Client-side interception of extended SQL commands
Workspace management via SQL syntax
Stage (file storage) operations via SQL
Multiple Result Formats:
The SDK supports 7 result formats, selectable via results_type parameter:
Each format also has streaming variants (SS*Cursor) for memory-efficient iteration over large result sets without buffering the entire result in memory.
Key Files
| File | Purpose |
|---|---|
connection.py | MySQL connection with C acceleration support |
cursors.py | 20+ cursor implementations using mixin composition |
protocol.py | MySQL wire protocol parsing |
_auth.py | Authentication methods (native, SHA256, GSSAPI) |
converters.py | MySQL data type converters |
charset.py | Character set definitions |
C Acceleration
The C extension (accel.c → _singlestoredb_accel.abi3.so) provides ~10x faster row parsing. It's automatically used unless disabled:
The acceleration targets the hot path in row parsing from the binary protocol.
Cursor Hierarchy
The SDK provides 20+ cursor types through mixin composition. The pattern allows combining buffering behavior with result formats:
Usage:
Authentication Methods
Defined in singlestoredb/mysql/_auth.py:
| Method | Function | Description |
|---|---|---|
| Native | scramble_native_password() | MySQL native password authentication |
| SHA256 | sha256_password_auth() | SHA-256 with RSA encryption |
| Caching SHA2 | caching_sha2_password_auth() | Fast cached authentication |
| Ed25519 | ed25519_password() | Ed25519 signature authentication |
| GSSAPI | gssapi_auth() | Kerberos/GSSAPI authentication |
HTTP Connector (singlestoredb/http/)
The HTTP connector provides REST-based access via SingleStore's HTTP API (port 9000).
Key Characteristics:
JSON request/response encoding
Simpler protocol, no binary parsing
Useful for environments where MySQL protocol is blocked
Same cursor interface as MySQL connector
Configuration System
The configuration system in singlestoredb/config.py provides centralized option management with validation and environment variable support.
Option Access
Key Configuration Categories
| Category | Options | Description |
|---|---|---|
| Connection | host, user, password, port, database | Database connection parameters |
| Performance | pure_python, buffered | Performance tuning |
| Results | results_type, nan_as_null, inf_as_null | Result handling |
| SSL | ssl_key, ssl_cert, ssl_ca, ssl_disabled | SSL/TLS configuration |
| Fusion | fusion.enabled | Fusion SQL enablement |
Environment Variables
All options can be set via environment variables with the SINGLESTOREDB_ prefix:
Management API
The management API (singlestoredb/management/) provides programmatic access to SingleStore's cloud management features.
Architecture
Resource Hierarchy
Usage
Key Classes
| Class | File | Purpose |
|---|---|---|
Manager | manager.py | Base REST client with auth |
WorkspaceManager | workspace.py | Main management interface |
WorkspaceGroup | workspace.py | Group of workspaces |
Workspace | workspace.py | Database instance |
Stage | workspace.py | File storage operations |
StarterWorkspace | workspace.py | Free tier workspace |
Organization | organization.py | Organization management |
Billing | workspace.py | Usage and billing |
Fusion SQL
Fusion SQL extends the SQL interface with client-side command handling. Commands are intercepted before being sent to the database and processed by registered handlers.
Architecture
Enabling Fusion SQL
Handler Architecture
Handlers extend SQLHandler (singlestoredb/fusion/handler.py) with grammar defined in the docstring:
Grammar Syntax
| Element | Syntax | Example |
|---|---|---|
| Keywords | ALL_CAPS | SHOW, CREATE, IN |
| String literals | '<name>' | '<path>', '<region-id>' |
| Numeric literals | <number>, <integer> | <integer> |
| Optional blocks | [ ... ] | [ WITH PASSWORD ] |
| Selection blocks | { A | B } | { QUIET | VERBOSE } |
| Repeated values | rule,... | '<ip-range>',... |
| Builtins | <name> | <extended>, <like>, <limit>, <order-by> |
Built-in Handlers
Located in singlestoredb/fusion/handlers/:
| Handler | Commands |
|---|---|
workspace.py | SHOW WORKSPACE GROUPS, CREATE WORKSPACE, etc. |
stage.py | UPLOAD, DOWNLOAD, CREATE STAGE FOLDER |
job.py | SHOW JOBS, CREATE JOB, DROP JOB |
files.py | File management commands |
models.py | ML model commands |
export.py | Data export commands |
External Functions (UDFs)
The functions module (singlestoredb/functions/) enables deploying Python functions as SingleStore external functions.
Architecture
Usage
Type Mapping
The signature.py module maps Python types to SQL types:
| Python Type | SQL Type |
|---|---|
int | BIGINT |
float | DOUBLE |
str | TEXT |
bytes | BLOB |
bool | TINYINT |
datetime.datetime | DATETIME |
datetime.date | DATE |
decimal.Decimal | DECIMAL |
List[T] | ARRAY |
Optional[T] | Nullable variant |
Execution Modes
| Mode | File | Use Case |
|---|---|---|
| ASGI | asgi.py | Remote execution via HTTP, scalable |
| Memory-mapped | mmap.py | Collocated execution, lowest latency |
| JSON | json.py | Simple serialization, debugging |
| ROWDAT_1 | rowdat_1.py | Binary format, efficient |
| Arrow | arrow.py | Columnar format, analytics |
AI Integration
The AI module (singlestoredb/ai/) provides factory functions for creating AI clients configured for SingleStore's AI services.
Chat Factory
Embeddings Factory
Supported Providers
OpenAI: GPT models, text embeddings
AWS Bedrock: Claude, Titan models
Vector Store
The vector store module (singlestoredb/vectorstore.py) integrates with the singlestore-vectorstore package for vector similarity search.
Supporting Modules
Types (singlestoredb/types.py)
DB-API 2.0 type objects for parameter binding:
Converters (singlestoredb/converters.py)
Data type conversion between Python and database types. Handles encoding/decoding of dates, times, decimals, JSON, vectors, and binary data.
Exceptions (singlestoredb/exceptions.py)
DB-API 2.0 exception hierarchy:
Authentication (singlestoredb/auth.py)
JWT token handling for management API authentication:
Testing Infrastructure
The testing infrastructure (singlestoredb/pytest.py) provides automatic Docker container management for tests.
Architecture
_TestContainerManager
The _TestContainerManager class (singlestoredb/pytest.py) handles:
Starting SingleStore Docker container
Dynamic port allocation (avoids conflicts)
Connection health checks
Container cleanup
Fixtures
| Fixture | Purpose |
|---|---|
singlestoredb_test_container | Manages Docker container lifecycle |
singlestoredb_connection | Provides a connection to test server |
singlestoredb_tempdb | Creates temporary database with cursor |
execution_mode | Returns MySQL or HTTP mode |
name_allocator | Generates unique test names |
Test Categories
| Category | Marker | Description |
|---|---|---|
| Protocol | (none) | MySQL protocol tests |
| HTTP | USE_DATA_API=1 | HTTP API tests |
| Management | @pytest.mark.management | Management API tests |
| Pure Python | SINGLESTOREDB_PURE_PYTHON=1 | No C acceleration |
Additional Integrations
SQLAlchemy (singlestoredb/alchemy/)
SQLAlchemy dialect for SingleStore:
Jupyter/Notebook (singlestoredb/notebook/, singlestoredb/magics/)
IPython magic commands for notebooks:
Portal and Live Accessor Objects
When running in SingleStore Helios notebooks, the singlestoredb.notebook module provides live accessor objects that automatically reflect the currently selected cloud resources in the Portal UI:
Secrets Accessor - attribute-style access to stored secrets:
Stage Accessor - proxy to the currently selected Stage:
Changing Resources - updates Portal UI via JavaScript bridge:
The accessors are "live" - they always reflect the current Portal state and changes propagate bidirectionally between Python and the Portal UI.
Server Tools (singlestoredb/server/)
Utilities for managing SingleStore server instances, including Docker helpers and free tier management.
Appendices
A. Environment Variables Reference
| Variable | Description | Default |
|---|---|---|
SINGLESTOREDB_URL | Full connection URL | None |
SINGLESTOREDB_HOST | Database host | localhost |
SINGLESTOREDB_PORT | Database port | 3306 |
SINGLESTOREDB_USER | Database user | root |
SINGLESTOREDB_PASSWORD | Database password | None |
SINGLESTOREDB_DATABASE | Default database | None |
SINGLESTOREDB_PURE_PYTHON | Disable C acceleration | 0 |
SINGLESTOREDB_RESULTS_TYPE | Default result format | tuples |
SINGLESTOREDB_FUSION_ENABLED | Enable Fusion SQL | 0 |
SINGLESTOREDB_MANAGEMENT_TOKEN | Management API token | None |
SINGLESTORE_LICENSE | License key for Docker | None |
USE_DATA_API | Use HTTP API for tests | 0 |
B. Cursor Type Matrix
| Cursor | Buffered | Format | Class |
|---|---|---|---|
| Default | Yes | tuples | Cursor |
| Dict | Yes | dict | DictCursor |
| Namedtuple | Yes | namedtuple | NamedtupleCursor |
| Arrow | Yes | PyArrow | ArrowCursor |
| Numpy | Yes | numpy arrays | NumpyCursor |
| Pandas | Yes | DataFrame | PandasCursor |
| Polars | Yes | DataFrame | PolarsCursor |
| SS* | No | (streaming) | SS*Cursor |
C. Configuration Options Reference
Connection options:
host,user,password,port,databasedriver:mysql,http,httpscharset: Character encodingssl_*: SSL/TLS optionscredential_type:PASSWORD,JWT,BROWSER_SSO
Performance options:
pure_python: Disable C accelerationbuffered: Buffer all results in memoryconnect_timeout: Connection timeout in seconds
Result options:
results_type:tuples,dicts,namedtuples,numpy,pandas,polars,arrownan_as_null: Treat NaN as NULLinf_as_null: Treat Inf as NULL
Feature options:
local_infile: Allow local file uploadsmulti_statements: Allow multiple statementsautocommit: Auto-commit modeenable_extended_data_types: Enable BSON, vector typesvector_data_format:jsonorbinary
D. File Quick Reference
| Purpose | Primary File |
|---|---|
| Entry point | singlestoredb/__init__.py |
| Connect function | singlestoredb/connection.py:1312 |
| MySQL connection | singlestoredb/mysql/connection.py |
| Cursor types | singlestoredb/mysql/cursors.py |
| HTTP connection | singlestoredb/http/connection.py |
| Configuration | singlestoredb/config.py |
| Management API | singlestoredb/management/workspace.py |
| Fusion handlers | singlestoredb/fusion/handler.py |
| UDF decorator | singlestoredb/functions/decorator.py |
| Test fixtures | singlestoredb/pytest.py |