SQLAlchemy CockroachDB Dialect
The `sqlalchemy-cockroachdb` library provides a database dialect for SQLAlchemy, enabling Python applications to connect and interact with CockroachDB. It currently supports SQLAlchemy 2.0 and later, adapting SQLAlchemy's ORM and SQL Expression Language to CockroachDB's distributed SQL features. The library maintains an active release schedule, often aligning with updates to CockroachDB and SQLAlchemy.
Warnings
- breaking SQLAlchemy 2.0 Compatibility: `sqlalchemy-cockroachdb` v2.x is specifically designed for SQLAlchemy v2.x. Attempting to use a v1.x dialect with SQLAlchemy v2.x, or vice-versa, will result in errors.
- gotcha Transaction Retries: CockroachDB frequently requires client-side transaction retry logic due to its distributed nature, which can lead to `SQLSTATE 40001` (serialization_failure) errors. SQLAlchemy does not inherently provide this.
- gotcha Primary Key Strategy (`SERIAL` vs `UUID`/`UNIQUE_ROWID()`): Using `SERIAL` or `AUTOINCREMENT` for primary keys in CockroachDB can create hotspots and performance bottlenecks. `UUID` or `UNIQUE_ROWID()` are generally preferred for distributed performance.
- gotcha Connection String `sslmode`: CockroachDB Cloud typically requires `sslmode=require` in the connection string. Local insecure instances might use `sslmode=disable`. Misconfiguring `sslmode` is a common cause of connection failures.
Install
-
pip install sqlalchemy-cockroachdb psycopg2-binary
Imports
- create_engine
from sqlalchemy import create_engine
- text
from sqlalchemy import text
Quickstart
import os
from sqlalchemy import create_engine, text
# CockroachDB connection string (replace with your actual connection string)
# For a local insecure instance: "cockroachdb://root@localhost:26257/defaultdb?sslmode=disable"
# For CockroachDB Cloud: "cockroachdb://<username>:<password>@<host>:<port>/<database>?sslmode=require"
DATABASE_URL = os.environ.get(
"COCKROACHDB_URL",
"cockroachdb://root@localhost:26257/defaultdb?sslmode=disable"
)
try:
engine = create_engine(DATABASE_URL)
with engine.connect() as connection:
# Verify connection
result = connection.execute(text("SELECT 1+1"))
print(f"Result of 1+1: {result.scalar()}")
# Example: Create a table with UUID primary key (recommended for CockroachDB)
connection.execute(text("""
CREATE TABLE IF NOT EXISTS accounts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
balance INT
)
"""))
connection.commit()
print("Table 'accounts' checked/created.")
# Example: Insert data
connection.execute(text("INSERT INTO accounts (balance) VALUES (:balance)"), {"balance": 100})
connection.commit()
print("Inserted a new account.")
# Example: Select data
accounts_result = connection.execute(text("SELECT id, balance FROM accounts LIMIT 5"))
for row in accounts_result:
print(f"Account ID: {row.id}, Balance: {row.balance}")
except Exception as e:
print(f"An error occurred: {e}")
print("Please ensure CockroachDB is running and your connection string is correct.")