feat: support stale reads by IlyaFaer · Pull Request #146 · googleapis/python-spanner-sqlalchemy · GitHub
Skip to content
This repository was archived by the owner on May 14, 2026. It is now read-only.
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
39 changes: 39 additions & 0 deletions README.md
13 changes: 13 additions & 0 deletions google/cloud/sqlalchemy_spanner/sqlalchemy_spanner.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@
from sqlalchemy import ForeignKeyConstraint, types, util
from sqlalchemy.engine.base import Engine
from sqlalchemy.engine.default import DefaultDialect, DefaultExecutionContext
from sqlalchemy.event import listens_for
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.pool import Pool
from sqlalchemy.sql.compiler import (
selectable,
DDLCompiler,
Expand All @@ -38,6 +40,13 @@
from google.cloud import spanner_dbapi
from google.cloud.sqlalchemy_spanner._opentelemetry_tracing import trace_call


@listens_for(Pool, "reset")
def reset_connection(dbapi_conn, connection_record):
"""An event of returning a connection back to a pool."""
dbapi_conn.connection.staleness = None

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to the docs, connection the hook to the Pool class will connect it to all the pools used by the dialect. In the test below a QueuedPool is used (by default), and it's working fine.



# Spanner-to-SQLAlchemy types map
_type_map = {
"BOOL": types.Boolean,
Expand Down Expand Up @@ -128,6 +137,10 @@ def pre_exec(self):
if read_only is not None:
self._dbapi_connection.connection.read_only = read_only

staleness = self.execution_options.get("staleness", None)
if staleness is not None:
self._dbapi_connection.connection.staleness = staleness


class SpannerIdentifierPreparer(IdentifierPreparer):
"""Identifiers compiler.
Expand Down
20 changes: 17 additions & 3 deletions test/test_suite.py