Skip to content
Open
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
10 changes: 10 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ Unreleased
implementations. `get_table_names()` returns base tables only; views were
also listed and are reported by `get_view_names()`. `has_table()` still
returns True for views, as in SQLAlchemy 2.0 (#310).
- asyncpg: invalidate cached prepared statements when a schema change makes
them stale ("cached plan must not change result type", or "type with ID ...
does not exist" after a user-defined type is recreated). asyncpg recognizes
stale statements only by PostgreSQL's routine names, so such a statement
failed on every pooled connection that had cached it, for the life of the
connection. Now the first execution fails and a retry re-prepares, as on
PostgreSQL.
- asyncpg: also invalidate cached prepared statements on "placeholder $N
already has type ...", raised when a column a textual statement binds a
parameter to changes type.

# Version 2.0.4
April 23, 2026
Expand Down
29 changes: 29 additions & 0 deletions sqlalchemy_cockroachdb/asyncpg.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,44 @@
import re

from sqlalchemy.dialects.postgresql.asyncpg import PGDialect_asyncpg
from sqlalchemy.dialects.postgresql.asyncpg import PGExecutionContext_asyncpg
from .base import CockroachDBDialect
from .ddl_compiler import CockroachDDLCompiler
from .stmt_compiler import CockroachCompiler
from .stmt_compiler import CockroachIdentifierPreparer

# Errors CockroachDB raises when a schema change has made a prepared statement
# stale. asyncpg recognizes stale statements by PostgreSQL's routine names,
# which CockroachDB doesn't report, so these are matched by SQLSTATE and
# message instead.
_STALE_STATEMENT_ERRORS = (
# The statement's result columns changed type.
("0A000", re.compile(r"cached plan must not change result type")),
# A user-defined type the statement was prepared against was dropped.
("42704", re.compile(r"type with ID \d+ does not exist")),
# A placeholder's type no longer fits its column (binds without casts,
# e.g. textual SQL). Some fresh statements also raise this; harmless.
("42804", re.compile(r"placeholder \$\d+ already has type")),
)


class CockroachDBExecutionContext_asyncpg(PGExecutionContext_asyncpg):
def handle_dbapi_exception(self, e):
super().handle_dbapi_exception(e)
sqlstate = getattr(e, "sqlstate", None)
if any(
sqlstate == code and message.search(str(e))
for code, message in _STALE_STATEMENT_ERRORS
):
self.dialect._invalidate_schema_cache()


class CockroachDBDialect_asyncpg(PGDialect_asyncpg, CockroachDBDialect):
driver = "asyncpg" # driver name
preparer = CockroachIdentifierPreparer
ddl_compiler = CockroachDDLCompiler
statement_compiler = CockroachCompiler
execution_ctx_cls = CockroachDBExecutionContext_asyncpg

supports_statement_cache = True

Expand Down
94 changes: 94 additions & 0 deletions test/test_asyncpg_cached_plan.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
from sqlalchemy import exc, text
from sqlalchemy.testing import engines, eq_, expect_raises_message, fixtures

UUID_VALUE = "6f1c3a2e-0000-4000-8000-000000000001"


class CachedPlanInvalidationTest(fixtures.TestBase):
"""A prepared statement made stale by DDL from another process fails once,
and then the dialect re-prepares it."""

__only_on__ = "cockroachdb+asyncpg"
__backend__ = True

def _drop_all(self, conn):
conn.execute(text("DROP TABLE IF EXISTS cached_plan_t"))
conn.execute(text("DROP TABLE IF EXISTS cached_plan_t_new"))
conn.execute(text("DROP TYPE IF EXISTS cached_plan_e"))

def _ddl(self, *statements):
with engines.testing_engine().begin() as conn:
for statement in statements:
conn.execute(text(statement))

def setup_test(self):
with engines.testing_engine().begin() as conn:
self._drop_all(conn)

def teardown_test(self):
with engines.testing_engine().begin() as conn:
self._drop_all(conn)

def _assert_recovers(self, query, params, ddl, message):
# DDL emitted through the same dialect invalidates its caches up front,
# so the schema change has to come from a separate engine.
with engines.testing_engine().connect() as conn:
conn.execute(query, params)
conn.commit()

self._ddl(*ddl)

with expect_raises_message(exc.DBAPIError, message):
conn.execute(query, params)
conn.rollback()

result = conn.execute(query, params)
return result.all() if result.returns_rows else None

def test_result_type_change(self):
self._ddl(
"CREATE TABLE cached_plan_t (id INT PRIMARY KEY, a STRING)",
"INSERT INTO cached_plan_t VALUES (1, 'x')",
)
rows = self._assert_recovers(
text("SELECT * FROM cached_plan_t"),
{},
["ALTER TABLE cached_plan_t ADD COLUMN b STRING"],
# asyncpg versions that classify this error replace its message.
"cached plan must not change result type|cached statement plan is invalid",
)
eq_(rows, [(1, "x", None)])

def test_type_recreated(self):
create = [
"CREATE TYPE cached_plan_e AS ENUM ('a', 'b')",
"CREATE TABLE cached_plan_t (id INT PRIMARY KEY, v cached_plan_e)",
]
self._ddl(*create)
self._assert_recovers(
text("UPSERT INTO cached_plan_t (id, v) VALUES (:id, CAST(:v AS cached_plan_e))"),
{"id": 1, "v": "a"},
["DROP TABLE cached_plan_t", "DROP TYPE cached_plan_e", *create],
"type with ID",
)

def _assert_placeholder_type_change_recovers(self, params):
self._ddl("CREATE TABLE cached_plan_t (id INT PRIMARY KEY, a UUID)")
self._assert_recovers(
text("UPSERT INTO cached_plan_t (id, a) VALUES (:id, :a)"),
params,
[
"CREATE TABLE cached_plan_t_new (id INT PRIMARY KEY, a STRING)",
"DROP TABLE cached_plan_t",
"ALTER TABLE cached_plan_t_new RENAME TO cached_plan_t",
],
"already has type",
)

def test_placeholder_type_change(self):
self._assert_placeholder_type_change_recovers({"id": 1, "a": UUID_VALUE})

def test_placeholder_type_change_executemany(self):
self._assert_placeholder_type_change_recovers(
[{"id": 1, "a": UUID_VALUE}, {"id": 2, "a": UUID_VALUE}]
)
Loading