SQLAlchemy CockroachDB Dialect

2.0.3 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

Demonstrates connecting to CockroachDB, executing a simple query, creating a table with a UUID primary key, inserting data, and selecting data. It uses an environment variable for the connection URL, falling back to a common local insecure setup.

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.")

view raw JSON →