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/examples-it-multiregion.yml
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ jobs:
env:
CRDB_MULTIREGION: "true"
CRDB_URL: "postgres://root@localhost:26257/defaultdb?sslmode=disable"
run: python -m pytest test_regional_it.py -v
run: python -m pytest test_regional_it.py test_multiregion_check_it.py -v

- name: Cluster diagnostics on failure
if: failure()
Expand Down
61 changes: 61 additions & 0 deletions examples/ideas-board/multiregion_check_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""Multi-region schema check (cockroachdb-sqlalchemy 0.2.0) for the ideas board.

The rest of this example talks to CockroachDB through plain psycopg. The 0.2.0
multi-region *check* is a SQLAlchemy-layer feature: you declare each table's
locality with an ORM mixin (``RegionalByRowMixin`` / ``GlobalTableMixin``), and
the library compares your models against the live database so a model that says
"REGIONAL BY ROW" can't silently drift from a table that isn't.

This module mirrors the ``regional_idea`` table (created by
``regional_service.REGIONAL_BY_ROW_DDL``) as a SQLAlchemy model and runs the
check at engine creation. It never calls ``create_all`` — the check is
read-only; the model is just metadata the check reads.
"""

from __future__ import annotations

# tag::mr-check-entity[]
from sqlalchemy import Column, String
from sqlalchemy.orm import DeclarativeBase

from cockroachdb.sqla import RegionalByRowMixin


class Base(DeclarativeBase):
pass


class RegionalIdeaModel(RegionalByRowMixin, Base):
"""ORM view of the ``regional_idea`` table, declared REGIONAL BY ROW.

``RegionalByRowMixin`` adds the ``crdb_region`` column and stamps the
locality the check reads — it is the SQLAlchemy counterpart of the Java
``@RegionalByRow`` and .NET ``[RegionalByRow]`` the other demos use.
"""

__tablename__ = "regional_idea"

id = Column(String, primary_key=True)
text = Column(String, nullable=False)


# end::mr-check-entity[]


# tag::mr-check-usage[]
from cockroachdb.sqla import create_cockroachdb_engine


def start_engine(url: str):
"""Create the engine and verify the multi-region schema at startup.

``multiregion_mode="warn"`` logs a mismatch (e.g. the model says REGIONAL BY
ROW but the table isn't) instead of failing boot; a direct contradiction
still raises even in ``warn``. Use ``"validate"`` to fail on any problem, or
``"none"`` to skip. ``url`` is a SQLAlchemy URL, e.g.
``cockroachdb+psycopg://root@localhost:26257/defaultdb?sslmode=disable``.
"""
return create_cockroachdb_engine(url, multiregion_base=Base, multiregion_mode="warn")


# end::mr-check-usage[]
1 change: 1 addition & 0 deletions examples/ideas-board/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

cockroachdb==0.1.2
cockroachdb-core==0.2.0 # metrics (RetryEngine) + follower-read/region context
cockroachdb-sqlalchemy==0.2.0 # multi-region schema check (verify_multiregion_schema + ORM mixins); pulls sqlalchemy>=2.0
cockroachdb-cdc==0.1.1 # changefeed handlers + webhook payload parsing
cockroachdb-ai==0.1.2 # pgvector vector store (semantic search); CREATE VECTOR INDEX needs cockroach >= v26.2
psycopg[binary]>=3.1
Expand Down
49 changes: 49 additions & 0 deletions examples/ideas-board/test_multiregion_check_it.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""Integration test for the 0.2.0 multi-region schema check — gated like the
REGIONAL BY ROW writes in ``test_regional_it.py``.

``verify_multiregion_schema`` reads the *live* multi-region configuration, so it
only means anything against a real multi-region cluster. This test therefore
SKIPS unless ``CRDB_MULTIREGION=true``; when enabled it reads an external
cluster from ``CRDB_URL`` (expected to already have the regions added). It never
fails by default — it is skipped.
"""

from __future__ import annotations

import os

import multiregion_check_service as mc
import psycopg
import pytest
import regional_service as rs

from cockroachdb.sqla import verify_multiregion_schema

pytestmark = pytest.mark.skipif(
os.environ.get("CRDB_MULTIREGION") != "true",
reason="multi-region check needs a multi-region cluster; set CRDB_MULTIREGION=true and CRDB_URL",
)


def _sqlalchemy_url(pg_url: str) -> str:
"""Rewrite a ``postgres://`` DSN to the CockroachDB SQLAlchemy dialect URL."""
return "cockroachdb+psycopg://" + pg_url.split("://", 1)[1]


# tag::mr-check-report[]
def test_matching_schema_passes() -> None:
url = os.environ["CRDB_URL"]
# Make the live table match the model: regional_idea as REGIONAL BY ROW.
with psycopg.connect(url, autocommit=True) as conn, conn.cursor() as cur:
cur.execute("DROP TABLE IF EXISTS regional_idea")
for ddl in rs.REGIONAL_BY_ROW_DDL.split(";"):
if ddl.strip():
cur.execute(ddl)

engine = mc.start_engine(_sqlalchemy_url(url)) # warn opt-in runs here; match => no raise

# A matching schema passes even the strict mode (any problem would raise).
verify_multiregion_schema(engine, mc.Base, mode="validate")


# end::mr-check-report[]
Loading