Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ jobs:
run: uv run ruff check .

- name: Mypy
run: uv run mypy packages/cockroachdb/src packages/cockroachdb-core/src packages/cockroachdb-continuum/src packages/cockroachdb-testing/src
run: uv run mypy packages/cockroachdb/src packages/cockroachdb-core/src packages/cockroachdb-continuum/src packages/cockroachdb-testing/src packages/cockroachdb-cdc/src packages/cockroachdb-ai/src packages/cockroachdb-sqlalchemy/src packages/cockroachdb-django/src

- name: Start CockroachDB
# Many tests (DDL compiler, dialect, alembic, integration) connect to a
Expand Down
2 changes: 1 addition & 1 deletion packages/cockroachdb-ai/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "cockroachdb-ai"
version = "0.1.2"
version = "0.2.0"
description = "CockroachDB AI — vector search, RAG pipelines, and embedding providers for pgvector"
readme = "README.md"
requires-python = ">=3.11"
Expand Down
4 changes: 2 additions & 2 deletions packages/cockroachdb-ai/src/cockroachdb/ai/embeddings.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ async def embed_batch(self, texts: list[str]) -> list[list[float]]:
if not texts:
return []
vectors: Any = self._model.encode(texts)
return [v.tolist() for v in vectors] # type: ignore[union-attr]
return [v.tolist() for v in vectors]


class OpenAIEmbeddingProvider:
Expand Down Expand Up @@ -203,7 +203,7 @@ async def embed(self, text: str) -> list[float]:
input=text,
dimensions=self._dimensions,
)
return response.data[0].embedding
return list(response.data[0].embedding)

async def embed_batch(self, texts: list[str]) -> list[list[float]]:
"""Embed multiple texts in a single API call.
Expand Down
Empty file.
2 changes: 1 addition & 1 deletion packages/cockroachdb-cdc/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "cockroachdb-cdc"
version = "0.1.1"
version = "0.2.0"
description = "CockroachDB Change Data Capture — webhook handlers, changefeed management, and framework integration"
readme = "README.md"
requires-python = ">=3.11"
Expand Down
Empty file.
4 changes: 2 additions & 2 deletions packages/cockroachdb-cdc/src/cockroachdb/cdc/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import json
import logging
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, cast

if TYPE_CHECKING:
from cockroachdb.cdc.handler import ChangefeedHandlerRegistry
Expand Down Expand Up @@ -44,7 +44,7 @@ def create_fastapi_router(
"Install it with: pip install cockroachdb-cdc[fastapi]"
) from exc

router = APIRouter(prefix=prefix, tags=tags or ["cdc"])
router = APIRouter(prefix=prefix, tags=cast("list[Any]", tags or ["cdc"]))

for endpoint, info in registry.get_handlers().items():

Expand Down
2 changes: 1 addition & 1 deletion packages/cockroachdb-core/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "cockroachdb-core"
version = "0.2.0"
version = "0.3.0"
description = "CockroachDB Python Library — engine layer with retry, circuit breaker, and template"
readme = "README.md"
requires-python = ">=3.11"
Expand Down
5 changes: 5 additions & 0 deletions packages/cockroachdb-core/src/cockroachdb/core/region.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ def current(cls) -> str | None:
def set(cls, region: str) -> contextvars.Token[str | None]:
return _region_var.set(region)

@classmethod
def reset(cls, token: contextvars.Token[str | None]) -> None:
"""Restore the region to its value before the matching :meth:`set`."""
_region_var.reset(token)

@classmethod
@contextmanager
def scoped(cls, region: str) -> Iterator[str]:
Expand Down
2 changes: 1 addition & 1 deletion packages/cockroachdb-django/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "cockroachdb-django"
version = "0.2.0"
version = "0.3.0"
description = "CockroachDB Python Library — Django adapter with retry, region, and follower-read support"
readme = "README.md"
requires-python = ">=3.11"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,12 @@

from __future__ import annotations

from typing import Any

__version__ = "0.1.0"


def __getattr__(name: str):
def __getattr__(name: str) -> Any:
"""Lazy module-level imports to avoid triggering Django's app registry."""
_lazy = {
"CockroachDBMiddleware": "cockroachdb.django.middleware",
Expand Down
2 changes: 1 addition & 1 deletion packages/cockroachdb-django/src/cockroachdb/django/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from django.apps import AppConfig


class CockroachDBConfig(AppConfig):
class CockroachDBConfig(AppConfig): # type: ignore[misc]
name = "cockroachdb.django"
label = "cockroachdb"
verbose_name = "CockroachDB"
Expand Down
6 changes: 3 additions & 3 deletions packages/cockroachdb-django/src/cockroachdb/django/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
SETTING = "COCKROACHDB_MULTIREGION_MODE"


def _tables_from_models(models: Iterable[type]) -> list[MultiregionTable]:
def _tables_from_models(models: Iterable[Any]) -> list[MultiregionTable]:
"""Every concrete model as a :class:`MultiregionTable`.

Keys off the ORM mixins' ``crdb_locality`` attribute. Unannotated models are
Expand Down Expand Up @@ -95,9 +95,9 @@ def check_multiregion_schema(app_configs: Any = None, **kwargs: Any) -> list[Che
try:
with conn.cursor() as cursor:

def query(sql: str, params: object = ()) -> list:
def query(sql: str, params: object = ()) -> list[Any]:
cursor.execute(sql, params or None)
return cursor.fetchall()
return list(cursor.fetchall())

outcome, report = evaluate_schema(query, tables, mode)
except Exception as exc: # pragma: no cover - exercised via integration
Expand Down
6 changes: 3 additions & 3 deletions packages/cockroachdb-django/src/cockroachdb/django/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class Meta(GlobalTableMixin.Meta):
from django.utils import timezone


class RegionalByRowMixin(models.Model):
class RegionalByRowMixin(models.Model): # type: ignore[misc]
"""Mixin for CockroachDB REGIONAL BY ROW tables.

Adds a ``crdb_region`` column and sets ``Meta`` to include the
Expand All @@ -52,7 +52,7 @@ class Meta:
abstract = True


class GlobalTableMixin(models.Model):
class GlobalTableMixin(models.Model): # type: ignore[misc]
"""Mixin for CockroachDB GLOBAL tables.

Marks the table as globally replicated. Global tables are readable
Expand All @@ -66,7 +66,7 @@ class Meta:
abstract = True


class TimestampMixin(models.Model):
class TimestampMixin(models.Model): # type: ignore[misc]
"""Mixin that adds ``created_at`` and ``updated_at`` timestamp fields.

Common pattern in CockroachDB applications for tracking record
Expand Down
Empty file.
4 changes: 2 additions & 2 deletions packages/cockroachdb-django/src/cockroachdb/django/retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ def __exit__(
exc_tb: Any,
) -> bool:
# Delegate to the inner atomic context manager
return self._atomic.__exit__(exc_type, exc_val, exc_tb) # type: ignore[union-attr]
return bool(self._atomic.__exit__(exc_type, exc_val, exc_tb))

def __call__(self, fn: Callable[..., T]) -> Callable[..., T]:
"""Use as a decorator to wrap a function with retry + atomic."""
Expand Down Expand Up @@ -221,4 +221,4 @@ def wrapper(*args: Any, **kwargs: Any) -> T:
last_err,
) from last_err

return wrapper # type: ignore[return-value]
return wrapper
2 changes: 1 addition & 1 deletion packages/cockroachdb-sqlalchemy/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "cockroachdb-sqlalchemy"
version = "0.2.0"
version = "0.3.0"
description = "CockroachDB Python Library — SQLAlchemy 2.0 adapter with retry, region, and follower-read support"
readme = "README.md"
requires-python = ">=3.11"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

from __future__ import annotations

from typing import Any

try:
import alembic.ddl.postgresql
from sqlalchemy.ext.compiler import compiles
Expand All @@ -29,9 +31,9 @@ class CockroachDBImpl(alembic.ddl.postgresql.PostgresqlImpl):
transactional_ddl = False

@compiles(alembic.ddl.postgresql.PostgresqlColumnType, "cockroachdb")
def visit_column_type(*args, **kwargs):
def visit_column_type(*args: Any, **kwargs: Any) -> Any:
return alembic.ddl.postgresql.visit_column_type(*args, **kwargs)

@compiles(alembic.ddl.postgresql.ColumnComment, "cockroachdb")
def visit_column_comment(*args, **kwargs):
@compiles(alembic.ddl.postgresql.ColumnComment, "cockroachdb") # type: ignore[attr-defined]
def visit_column_comment(*args: Any, **kwargs: Any) -> Any:
return alembic.ddl.postgresql.visit_column_comment(*args, **kwargs)
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,16 @@

from __future__ import annotations

from typing import Any

from sqlalchemy import exc
from sqlalchemy.dialects.postgresql.base import PGDDLCompiler


class CockroachDDLCompiler(PGDDLCompiler):
"""DDL compiler that inlines indexes and handles computed columns."""

def visit_computed_column(self, generated, **kw):
def visit_computed_column(self, generated: Any, **kw: Any) -> str:
"""CockroachDB computed columns must be STORED (no virtual)."""
if generated.persisted is False:
raise exc.CompileError(
Expand All @@ -26,15 +28,15 @@ def visit_computed_column(self, generated, **kw):
)
return f"AS ({sqltext}) STORED"

def visit_create_table(self, create, **kw):
def visit_create_table(self, create: Any, **kw: Any) -> str:
"""Override CREATE TABLE to inject inline indexes before closing paren.

CockroachDB processes inline indexes in a single schema-change job,
whereas separate ``CREATE INDEX`` statements each trigger their own
job — resulting in ~25x slower table creation.
"""
table = create.element
ddl = super().visit_create_table(create, **kw)
ddl: str = super().visit_create_table(create, **kw) # type: ignore[no-untyped-call]

inline_parts: list[str] = []
for index in table.indexes:
Expand Down Expand Up @@ -62,9 +64,9 @@ def visit_create_table(self, create, **kw):

return ddl

def visit_create_index(self, create, **kw):
def visit_create_index(self, create: Any, **kw: Any) -> str: # type: ignore[override]
"""Skip non-unique indexes — they were already inlined."""
index = create.element
if not index.unique and hasattr(index, "table") and index.table is not None:
return ""
return super().visit_create_index(create, **kw)
return super().visit_create_index(create, **kw) # type: ignore[no-untyped-call,no-any-return]
36 changes: 18 additions & 18 deletions packages/cockroachdb-sqlalchemy/src/cockroachdb/sqla/dialect.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class _SavepointState(threading.local):
server-side retry protocol.
"""

def __init__(self):
def __init__(self) -> None:
self.cockroach_restart = False


Expand All @@ -59,38 +59,38 @@ class CockroachDBDialect(PGDialect_psycopg):
supports_sequences = False
supports_statement_cache = True

statement_compiler = CockroachCompiler
preparer = CockroachIdentifierPreparer
statement_compiler = CockroachCompiler # type: ignore[assignment]
preparer = CockroachIdentifierPreparer # type: ignore[assignment]
ddl_compiler = CockroachDDLCompiler

construct_arguments: ClassVar = [
construct_arguments: ClassVar = [ # type: ignore[misc]
(
sa_schema.Index,
{"storing": []},
),
]

def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
super().__init__(**kwargs) # type: ignore[no-untyped-call]

# --- Version detection ------------------------------------------------

def _get_server_version_info(self, connection):
def _get_server_version_info(self, connection: Connection) -> tuple[int, int, int]:
"""Parse CockroachDB version string.

CockroachDB returns ``CockroachDB CCL v24.3.33 (...)`` instead
of PostgreSQL's ``PostgreSQL 15.4 ...``. We extract the CRDB
version and present it as a tuple so SQLAlchemy doesn't crash.
"""
v = connection.exec_driver_sql("select version()").scalar()
m = re.match(r".*?v(\d+)\.(\d+)\.(\d+)", v)
m = re.match(r".*?v(\d+)\.(\d+)\.(\d+)", str(v))
if m:
return (int(m.group(1)), int(m.group(2)), int(m.group(3)))
return (24, 3, 0)

# --- Column reflection ------------------------------------------------

def get_columns(
def get_columns( # type: ignore[override]
self,
connection: Connection,
table_name: str,
Expand Down Expand Up @@ -162,7 +162,7 @@ def get_columns(

return result

def get_multi_columns(self, connection: Connection, **kw: Any) -> Any:
def get_multi_columns(self, connection: Connection, **kw: Any) -> Any: # type: ignore[override]
"""Route batch column reflection through the CRDB-safe ``get_columns``.

SQLAlchemy 2.1's ``MetaData.reflect()`` uses the batch
Expand All @@ -171,43 +171,43 @@ def get_multi_columns(self, connection: Connection, **kw: Any) -> Any:
not implement. Delegating to the generic per-table reflection makes
it call our ``information_schema``-based :meth:`get_columns` instead.
"""
return self._default_multi_reflect(self.get_columns, connection, **kw)
return self._default_multi_reflect(self.get_columns, connection, **kw) # type: ignore[no-untyped-call]

# --- Index reflection -------------------------------------------------

def get_indexes(
def get_indexes( # type: ignore[override]
self,
connection: Connection,
table_name: str,
schema: str | None = None,
**kw: Any,
) -> list[dict[str, Any]]:
"""Reflect indexes, removing ``duplicates_constraint`` from unique indexes."""
indexes = super().get_indexes(connection, table_name, schema, **kw)
indexes: list[dict[str, Any]] = super().get_indexes(connection, table_name, schema, **kw) # type: ignore[no-untyped-call]
for index in indexes:
if index.get("unique") and "duplicates_constraint" in index:
del index["duplicates_constraint"]
return indexes

# --- Savepoint protocol -----------------------------------------------

def do_savepoint(self, connection, name):
def do_savepoint(self, connection: Any, name: Any) -> None:
if savepoint_state.cockroach_restart:
connection.execute(text("SAVEPOINT cockroach_restart"))
else:
super().do_savepoint(connection, name)
super().do_savepoint(connection, name) # type: ignore[no-untyped-call]

def do_rollback_to_savepoint(self, connection, name):
def do_rollback_to_savepoint(self, connection: Any, name: Any) -> None:
if savepoint_state.cockroach_restart:
connection.execute(text("ROLLBACK TO SAVEPOINT cockroach_restart"))
else:
super().do_rollback_to_savepoint(connection, name)
super().do_rollback_to_savepoint(connection, name) # type: ignore[no-untyped-call]

def do_release_savepoint(self, connection, name):
def do_release_savepoint(self, connection: Any, name: Any) -> None:
if savepoint_state.cockroach_restart:
connection.execute(text("RELEASE SAVEPOINT cockroach_restart"))
else:
super().do_release_savepoint(connection, name)
super().do_release_savepoint(connection, name) # type: ignore[no-untyped-call]


# --- Alembic integration (side-effect import) ---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
if TYPE_CHECKING:
from sqlalchemy.engine import Engine

__all__ = ["FollowerReadContext", "RegionContext", "setup_cockroachdb_events"]

logger = logging.getLogger(__name__)


Expand Down
Loading
Loading