fix lint · googleapis/python-spanner@69f28c8 · GitHub | Latest TMZ Celebrity News & Gossip | Watch TMZ Live
Skip to content

Commit 69f28c8

Browse files
committed
fix lint
1 parent b45500d commit 69f28c8

File tree

8 files changed

+157
-50
lines changed

8 files changed

+157
-50
lines changed

.github/workflows/integration-tests-against-emulator-with-multiplexed-session.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ on:
33
branches:
44
- main
55
pull_request:
6-
name: Run Spanner integration tests against emulator
6+
name: Run Spanner integration tests against emulator with multiplexed sessions
77
jobs:
88
system-tests:
99
runs-on: ubuntu-latest

google/cloud/spanner_v1/database.py

Lines changed: 46 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,6 @@ def __init__(
199199
pool.bind(self)
200200
self._session_manager = DatabaseSessionsManager(database=self, pool=pool)
201201

202-
203202
@classmethod
204203
def from_pb(cls, database_pb, instance, pool=None):
205204
"""Creates an instance of this class from a protobuf.
@@ -785,8 +784,8 @@ def execute_pdml():
785784
# re-raising the error.
786785
except NotImplementedError as exc:
787786
if (
788-
"Transaction type partitioned_dml not supported with multiplexed sessions"
789-
in str(exc)
787+
"Transaction type partitioned_dml not supported with multiplexed sessions"
788+
in str(exc)
790789
):
791790
self.session_options.disable_multiplexed(
792791
self.logger, TransactionType.PARTITIONED
@@ -1248,8 +1247,20 @@ def observability_options(self):
12481247

12491248
class SessionCheckout(object):
12501249
"""Context manager for using a session from a database.
1250+
1251+
This is the recommended way to obtain sessions for database operations.
1252+
It automatically integrates with the database session manager to support
1253+
multiplexed sessions when enabled via environment variables.
1254+
1255+
For read-only operations, consider using ``database.snapshot()`` instead.
1256+
12511257
:type database: :class:`~google.cloud.spanner_v1.database.Database`
12521258
:param database: database to use the session from
1259+
1260+
:type transaction_type: :class:`~google.cloud.spanner_v1.session_options.TransactionType`
1261+
:param transaction_type: type of transaction this session will be used for.
1262+
Defaults to READ_WRITE. For read-only operations, use READ_ONLY to
1263+
enable multiplexed session support.
12531264
"""
12541265

12551266
_session = None # Not checked out until '__enter__'.
@@ -1261,6 +1272,7 @@ def __init__(
12611272
):
12621273
# Move import here to avoid circular import
12631274
from google.cloud.spanner_v1.database import Database
1275+
12641276
if not isinstance(database, Database):
12651277
raise TypeError(
12661278
"{class_name} must receive an instance of {expected_class_name}. Received: {actual_class_name}".format(
@@ -1290,6 +1302,7 @@ def __enter__(self):
12901302
def __exit__(self, *ignored):
12911303
self._database._session_manager.put_session(self._session)
12921304

1305+
12931306
class BatchCheckout(object):
12941307
"""Context manager for using a batch from a database.
12951308
@@ -1339,8 +1352,12 @@ def __init__(
13391352

13401353
def __enter__(self):
13411354
"""Begin ``with`` block."""
1355+
from google.cloud.spanner_v1.database import TransactionType
1356+
13421357
current_span = get_current_span()
1343-
session = self._session = self._database._pool.get()
1358+
session = self._session = self._database._session_manager.get_session(
1359+
TransactionType.READ_WRITE
1360+
)
13441361
add_span_event(current_span, "Using session", {"id": session.session_id})
13451362
batch = self._batch = Batch(session)
13461363
if self._request_options.transaction_tag:
@@ -1365,7 +1382,7 @@ def __exit__(self, exc_type, exc_val, exc_tb):
13651382
"CommitStats: {}".format(self._batch.commit_stats),
13661383
extra={"commit_stats": self._batch.commit_stats},
13671384
)
1368-
self._database._pool.put(self._session)
1385+
self._database._session_manager.put_session(self._session)
13691386
current_span = get_current_span()
13701387
add_span_event(
13711388
current_span,
@@ -1393,7 +1410,11 @@ def __init__(self, database):
13931410

13941411
def __enter__(self):
13951412
"""Begin ``with`` block."""
1396-
session = self._session = self._database._pool.get()
1413+
from google.cloud.spanner_v1.database import TransactionType
1414+
1415+
session = self._session = self._database._session_manager.get_session(
1416+
TransactionType.READ_WRITE
1417+
)
13971418
return MutationGroups(session)
13981419

13991420
def __exit__(self, exc_type, exc_val, exc_tb):
@@ -1402,9 +1423,9 @@ def __exit__(self, exc_type, exc_val, exc_tb):
14021423
# If NotFound exception occurs inside the with block
14031424
# then we validate if the session still exists.
14041425
if not self._session.exists():
1405-
self._session = self._database._pool._new_session()
1426+
self._session = self._database._session_manager._pool._new_session()
14061427
self._session.create()
1407-
self._database._pool.put(self._session)
1428+
self._database._session_manager.put_session(self._session)
14081429

14091430

14101431
class SnapshotCheckout(object):
@@ -1432,7 +1453,11 @@ def __init__(self, database, **kw):
14321453

14331454
def __enter__(self):
14341455
"""Begin ``with`` block."""
1435-
session = self._session = self._database._pool.get()
1456+
from google.cloud.spanner_v1.database import TransactionType
1457+
1458+
session = self._session = self._database._session_manager.get_session(
1459+
TransactionType.READ_ONLY
1460+
)
14361461
return Snapshot(session, **self._kw)
14371462

14381463
def __exit__(self, exc_type, exc_val, exc_tb):
@@ -1441,9 +1466,9 @@ def __exit__(self, exc_type, exc_val, exc_tb):
14411466
# If NotFound exception occurs inside the with block
14421467
# then we validate if the session still exists.
14431468
if not self._session.exists():
1444-
self._session = self._database._pool._new_session()
1469+
self._session = self._database._session_manager._pool._new_session()
14451470
self._session.create()
1446-
self._database._pool.put(self._session)
1471+
self._database._session_manager.put_session(self._session)
14471472

14481473

14491474
class BatchSnapshot(object):
@@ -1488,8 +1513,12 @@ def from_dict(cls, database, mapping):
14881513
14891514
:rtype: :class:`BatchSnapshot`
14901515
"""
1516+
from google.cloud.spanner_v1.database import TransactionType
1517+
14911518
instance = cls(database)
1492-
session = instance._session = database.session()
1519+
session = instance._session = database._session_manager.get_session(
1520+
TransactionType.READ_ONLY
1521+
)
14931522
session._session_id = mapping["session_id"]
14941523
snapshot = instance._snapshot = session.snapshot()
14951524
snapshot._transaction_id = mapping["transaction_id"]
@@ -1522,8 +1551,12 @@ def _get_session(self):
15221551
Caller is responsible for cleaning up the session after
15231552
all partitions have been processed.
15241553
"""
1554+
from google.cloud.spanner_v1.database import TransactionType
1555+
15251556
if self._session is None:
1526-
session = self._session = self._database.session()
1557+
session = self._session = self._database._session_manager.get_session(
1558+
TransactionType.READ_ONLY
1559+
)
15271560
if self._session_id is None:
15281561
session.create()
15291562
else:
@@ -1978,4 +2011,3 @@ def _retry_on_aborted(func, retry_config):
19782011
"""
19792012
retry = retry_config.with_predicate(if_exception_type(Aborted))
19802013
return retry(func)
1981-

google/cloud/spanner_v1/database_sessions_manager.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -256,4 +256,4 @@ def _maintain_multiplexed_session(session_manager_ref) -> None:
256256
session_manager._disable_multiplexed_sessions()
257257
return
258258

259-
session_created_time = time.time()
259+
session_created_time = time.time()

google/cloud/spanner_v1/pool.py

Lines changed: 57 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -137,15 +137,33 @@ def _new_session(self):
137137
)
138138

139139
def session(self, **kwargs):
140-
"""Check out a session from the pool.
140+
"""Return a context manager for a session from the pool.
141141
142-
:param kwargs: (optional) keyword arguments, passed through to
143-
the returned checkout.
142+
.. warning::
143+
This method bypasses the database session manager and will NOT use
144+
multiplexed sessions even if they are enabled. For normal application
145+
usage, prefer using database-level session APIs like
146+
``database.snapshot()`` or ``SessionCheckout(database)`` which
147+
support multiplexed sessions.
144148
145-
:rtype: :class:`~google.cloud.spanner_v1.session.SessionCheckout`
146-
:returns: a checkout instance, to be used as a context manager for
147-
accessing the session and returning it to the pool.
149+
This method is primarily intended for pool testing and advanced use cases
150+
where direct pool control is needed.
151+
152+
:type kwargs: dict
153+
:param kwargs: additional keyword arguments to pass to the session
154+
155+
:rtype: :class:`SessionCheckout`
156+
:returns: a context manager that yields a session from the pool
148157
"""
158+
import warnings
159+
160+
warnings.warn(
161+
"pool.session() bypasses multiplexed session support. "
162+
"Consider using database-level APIs like database.snapshot() "
163+
"or SessionCheckout(database) instead.",
164+
UserWarning,
165+
stacklevel=2,
166+
)
149167
return SessionCheckout(self, **kwargs)
150168

151169

@@ -537,7 +555,7 @@ def bind(self, database):
537555
request = BatchCreateSessionsRequest(
538556
database=database.name,
539557
session_count=self.size,
540-
session_template=Session(creator_role=self.database_role),
558+
session_template=SessionPB(creator_role=self.database_role),
541559
)
542560

543561
span_event_attributes = {"kind": type(self).__name__}
@@ -789,5 +807,37 @@ def begin_pending_transactions(self):
789807
super(TransactionPingingPool, self).put(session)
790808

791809

810+
class SessionCheckout(object):
811+
"""Context manager for checking out a session from a pool.
812+
813+
.. warning::
814+
This is a low-level API primarily intended for pool testing and
815+
internal use. It bypasses the database session manager and will
816+
NOT use multiplexed sessions even if enabled.
792817
818+
For normal application usage, prefer database-level APIs:
819+
- ``database.snapshot()`` for read-only operations
820+
- ``SessionCheckout(database)`` for general session management
821+
- ``database.batch()`` for batch operations
822+
823+
:type pool: :class:`AbstractSessionPool`
824+
:param pool: the pool to check out a session from
825+
:type kwargs: dict
826+
:param kwargs: additional keyword arguments for the session
827+
"""
793828

829+
def __init__(self, pool, **kwargs):
830+
self._pool = pool
831+
self._session = None
832+
self._kwargs = kwargs
833+
834+
def __enter__(self):
835+
"""Check out a session from the pool."""
836+
self._session = self._pool.get(**self._kwargs)
837+
return self._session
838+
839+
def __exit__(self, exc_type, exc_val, exc_tb):
840+
"""Return the session to the pool."""
841+
if self._session is not None:
842+
self._pool.put(self._session)
843+
self._session = None

google/cloud/spanner_v1/session_options.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,8 @@ def use_multiplexed(self, transaction_type: TransactionType) -> bool:
6666
"""
6767

6868
if transaction_type is TransactionType.READ_ONLY:
69-
return (
70-
self._is_multiplexed_enabled[transaction_type]
71-
and self._getenv(self.ENV_VAR_ENABLE_MULTIPLEXED)
69+
return self._is_multiplexed_enabled[transaction_type] and self._getenv(
70+
self.ENV_VAR_ENABLE_MULTIPLEXED
7271
)
7372

7473
elif transaction_type is TransactionType.PARTITIONED:
@@ -80,7 +79,7 @@ def use_multiplexed(self, transaction_type: TransactionType) -> bool:
8079

8180
elif transaction_type is TransactionType.READ_WRITE:
8281
return False
83-
82+
8483
raise ValueError(f"Transaction type {transaction_type} is not supported.")
8584

8685
def disable_multiplexed(
@@ -104,11 +103,15 @@ def disable_multiplexed(
104103
if transaction_type is None:
105104
if logger:
106105
logger.warning(
107-
disable_multiplexed_log_msg_fstring.format(transaction_type_value="all")
106+
disable_multiplexed_log_msg_fstring.format(
107+
transaction_type_value="all"
108+
)
108109
)
109110
else:
110111
print(
111-
disable_multiplexed_log_msg_fstring.format(transaction_type_value="all")
112+
disable_multiplexed_log_msg_fstring.format(
113+
transaction_type_value="all"
114+
)
112115
)
113116
for transaction_type in TransactionType:
114117
self._is_multiplexed_enabled[transaction_type] = False
@@ -123,7 +126,9 @@ def disable_multiplexed(
123126
)
124127
else:
125128
print(
126-
disable_multiplexed_log_msg_fstring.format(transaction_type_value=transaction_type.value)
129+
disable_multiplexed_log_msg_fstring.format(
130+
transaction_type_value=transaction_type.value
131+
)
127132
)
128133
self._is_multiplexed_enabled[transaction_type] = False
129134
return
@@ -137,4 +142,4 @@ def _getenv(name: str) -> bool:
137142
considered false.
138143
"""
139144
env_var = os.getenv(name, "").lower().strip()
140-
return env_var in ["1", "true"]
145+
return env_var in ["1", "true"]

google/cloud/spanner_v1/snapshot.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,7 @@ def _restart_on_unavailable(
196196

197197
del item_buffer[:]
198198

199+
199200
def _handle_not_implemented_error(exception, database) -> None:
200201
"""Handles NotImplementedError for the database. If the error is due to unsupported
201202
partitioned operations with multiplexed sessions, disables multiplexed sessions for
@@ -212,10 +213,13 @@ def _handle_not_implemented_error(exception, database) -> None:
212213
exception
213214
):
214215
session_options = database.session_options
215-
session_options.disable_multiplexed(database.logger, TransactionType.PARTITIONED)
216+
session_options.disable_multiplexed(
217+
database.logger, TransactionType.PARTITIONED
218+
)
216219

217220
raise exception
218221

222+
219223
class _SnapshotBase(_SessionWrapper):
220224
"""Base class for Snapshot.
221225
@@ -614,7 +618,6 @@ def wrapped_restart(*args, **kwargs):
614618
return self._get_streamed_result_set(**get_streamed_result_set_args)
615619
return self._get_streamed_result_set(**get_streamed_result_set_args)
616620

617-
618621
def partition_read(
619622
self,
620623
table,
@@ -856,14 +859,14 @@ def attempt_tracking_method():
856859
return [partition.partition_token for partition in response.partitions]
857860

858861
def _get_streamed_result_set(
859-
self,
860-
method,
861-
request,
862-
metadata,
863-
trace_attributes,
864-
column_info,
865-
observability_options,
866-
lazy_decode,
862+
self,
863+
method,
864+
request,
865+
metadata,
866+
trace_attributes,
867+
column_info,
868+
observability_options,
869+
lazy_decode,
867870
):
868871
"""Returns the streamed result set for a read or execute SQL request with the given arguments."""
869872

@@ -901,6 +904,7 @@ def _get_streamed_result_set(
901904

902905
return StreamedResultSet(**streamed_result_set_args)
903906

907+
904908
class Snapshot(_SnapshotBase):
905909
"""Allow a set of reads / SQL statements with shared staleness.
906910

0 commit comments

Comments
 (0)

TMZ Celebrity News – Breaking Stories, Videos & Gossip

Looking for the latest TMZ celebrity news? You've come to the right place. From shocking Hollywood scandals to exclusive videos, TMZ delivers it all in real time.

Whether it’s a red carpet slip-up, a viral paparazzi moment, or a legal drama involving your favorite stars, TMZ news is always first to break the story. Stay in the loop with daily updates, insider tips, and jaw-dropping photos.

🎥 Watch TMZ Live

TMZ Live brings you daily celebrity news and interviews straight from the TMZ newsroom. Don’t miss a beat—watch now and see what’s trending in Hollywood.