Visitar URL original
feat(dbapi): wire timeout parameter through Connection to execute_sql… · googleapis/google-cloud-python@98fc304 · GitHub
Skip to content

Commit 98fc304

Browse files
feat(dbapi): wire timeout parameter through Connection to execute_sql (#18484)
- Wire timeout parameter to Connection.__init__, connect(), run_statement(), and validate(). - Pass timeout from connection to execute_sql and batch_update calls when specified. - Add unit tests for DBAPI timeout propagation.
1 parent 0cabf7c commit 98fc304

5 files changed

Lines changed: 636 additions & 14 deletions

File tree

‎packages/google-cloud-spanner/google/cloud/spanner_dbapi/batch_dml_executor.py‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,9 @@ def run_batch_dml(cursor: "Cursor", statements: List[Statement]):
9292
statements_tuple.append(statement.get_tuple())
9393
if not connection._client_transaction_started:
9494
res = connection.database.run_in_transaction(
95-
_do_batch_update_autocommit, statements_tuple
95+
_do_batch_update_autocommit,
96+
statements_tuple,
97+
timeout=cursor.timeout,
9698
)
9799
many_result_set.add_iter(res)
98100
cursor._row_count = sum([max(val, 0) for val in res])
@@ -101,7 +103,10 @@ def run_batch_dml(cursor: "Cursor", statements: List[Statement]):
101103
while True:
102104
try:
103105
transaction = connection.transaction_checkout()
104-
status, res = transaction.batch_update(statements_tuple)
106+
kwargs = {}
107+
if cursor.timeout is not None:
108+
kwargs["timeout"] = cursor.timeout
109+
status, res = transaction.batch_update(statements_tuple, **kwargs)
105110
if status.code == ABORTED:
106111
connection._transaction = None
107112
raise Aborted(status.message)
@@ -133,10 +138,14 @@ def run_batch_dml(cursor: "Cursor", statements: List[Statement]):
133138
raise ex
134139

135140

136-
def _do_batch_update_autocommit(transaction, statements):
141+
def _do_batch_update_autocommit(transaction, statements, timeout=None):
137142
from google.cloud.spanner_dbapi import OperationalError
138143

139-
status, res = transaction.batch_update(statements, last_statement=True)
144+
kwargs = {"last_statement": True}
145+
if timeout is not None:
146+
kwargs["timeout"] = timeout
147+
148+
status, res = transaction.batch_update(statements, **kwargs)
140149
if status.code == ABORTED:
141150
raise Aborted(status.message)
142151
elif status.code != OK:

‎packages/google-cloud-spanner/google/cloud/spanner_dbapi/connection.py‎

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"""DB-API Connection for the Google Cloud Spanner."""
1616

1717
import warnings
18+
from typing import Optional
1819

1920
from google.api_core.client_options import ClientOptions
2021
from google.api_core.exceptions import Aborted
@@ -102,6 +103,10 @@ class Connection:
102103
or autocommit connections are automatically partitioned and executed in parallel.
103104
Defaults to False.
104105
106+
:type timeout: Optional[float]
107+
:param timeout: (Optional) The amount of time, in seconds, to wait
108+
for requests to complete.
109+
105110
**kwargs: Initial value for connection variables.
106111
"""
107112

@@ -112,6 +117,7 @@ def __init__(
112117
read_only=False,
113118
data_boost_enabled=False,
114119
auto_partition_mode=False,
120+
timeout=None,
115121
**kwargs,
116122
):
117123
self._instance = instance
@@ -133,6 +139,7 @@ def __init__(
133139
self._auto_partition_mode = bool(auto_partition_mode)
134140
self._staleness = None
135141
self.request_priority = None
142+
self.timeout = timeout
136143
self._transaction_begin_marked = False
137144
self._transaction_isolation_level = None
138145
# whether transaction started at Spanner. This means that we had
@@ -598,7 +605,10 @@ def run_prior_DDL_statements(self):
598605
return self.database.update_ddl(ddl_statements).result()
599606

600607
def run_statement(
601-
self, statement: Statement, request_options: RequestOptions = None
608+
self,
609+
statement: Statement,
610+
request_options: RequestOptions = None,
611+
timeout: Optional[float] = None,
602612
):
603613
"""Run single SQL statement in begun transaction.
604614
@@ -616,17 +626,31 @@ def run_statement(
616626
:type request_options: :class:`RequestOptions`
617627
:param request_options: Request options to use for this statement.
618628
629+
:type timeout: Optional[float]
630+
:param timeout: (Optional) The amount of time, in seconds, to wait
631+
for the request to complete. Defaults to the
632+
connection's timeout if None; when the connection's
633+
timeout is set, passing None will use the connection's
634+
timeout rather than the underlying RPC default timeout.
635+
619636
:rtype: :class:`google.cloud.spanner_v1.streamed.StreamedResultSet`,
620637
:class:`google.cloud.spanner_dbapi.checksum.ResultsChecksum`
621638
:returns: Streamed result set of the statement and a
622639
checksum of this statement results.
623640
"""
624641
transaction = self.transaction_checkout()
642+
kwargs = {
643+
"param_types": statement.param_types,
644+
"request_options": request_options or self.request_options,
645+
}
646+
effective_timeout = timeout if timeout is not None else self.timeout
647+
if effective_timeout is not None:
648+
kwargs["timeout"] = effective_timeout
649+
625650
return transaction.execute_sql(
626651
statement.sql,
627652
statement.params,
628-
param_types=statement.param_types,
629-
request_options=request_options or self.request_options,
653+
**kwargs,
630654
)
631655

632656
@check_not_closed
@@ -646,8 +670,11 @@ def validate(self):
646670
"""
647671
if self.database is None:
648672
raise ValueError("Database needs to be passed for this operation")
673+
kwargs = {}
674+
if self.timeout is not None:
675+
kwargs["timeout"] = self.timeout
649676
with self.database.snapshot() as snapshot:
650-
result = list(snapshot.execute_sql("SELECT 1"))
677+
result = list(snapshot.execute_sql("SELECT 1", **kwargs))
651678
if result != [[1]]:
652679
raise OperationalError(
653680
"The checking query (SELECT 1) returned an unexpected result: %s. "
@@ -822,10 +849,15 @@ def connect(
822849
auto_partition_mode=False,
823850
username=None,
824851
password=None,
852+
timeout=None,
825853
**kwargs,
826854
):
827855
"""Creates a connection to a Google Cloud Spanner database.
828856
857+
:type timeout: float
858+
:param timeout: (Optional) The amount of time, in seconds, to wait
859+
for requests to complete.
860+
829861
:type instance_id: str
830862
:param instance_id: The ID of the instance to connect to.
831863
@@ -1024,6 +1056,7 @@ def connect(
10241056
database,
10251057
data_boost_enabled=data_boost_enabled,
10261058
auto_partition_mode=auto_partition_mode,
1059+
timeout=timeout,
10271060
**kwargs,
10281061
)
10291062
if pool is not None:

‎packages/google-cloud-spanner/google/cloud/spanner_dbapi/cursor.py‎

Lines changed: 43 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,31 @@ def __init__(self, connection):
103103
self._in_retry_mode = False
104104
self._batch_dml_rows_count = None
105105
self._request_tag = None
106+
self._timeout = None
107+
108+
@property
109+
def timeout(self):
110+
"""The timeout (in seconds) that will be applied to statements on this
111+
cursor. Defaults to the connection's timeout if not set on the cursor.
112+
113+
Returns:
114+
Optional[float]: The timeout (in seconds) for statements on this
115+
cursor.
116+
"""
117+
return (
118+
self._timeout
119+
if self._timeout is not None
120+
else getattr(self.connection, "timeout", None)
121+
)
122+
123+
@timeout.setter
124+
def timeout(self, value):
125+
"""Sets the timeout (in seconds) for statements on this cursor.
126+
127+
Args:
128+
value (Optional[float]): The timeout (in seconds) for statements.
129+
"""
130+
self._timeout = value
106131

107132
@property
108133
def request_tag(self):
@@ -232,11 +257,16 @@ def _do_execute_update_in_autocommit(self, transaction, sql, params):
232257
"""This function should only be used in autocommit mode."""
233258
self.connection._transaction = transaction
234259
self.connection._snapshot = None
260+
kwargs = {
261+
"params": params,
262+
"param_types": get_param_types(params),
263+
"last_statement": True,
264+
}
265+
if self.timeout is not None:
266+
kwargs["timeout"] = self.timeout
235267
self._result_set = transaction.execute_sql(
236268
sql,
237-
params=params,
238-
param_types=get_param_types(params),
239-
last_statement=True,
269+
**kwargs,
240270
)
241271
self._itr = BufferedIterator(self._result_set)
242272
self._row_count = None
@@ -376,7 +406,7 @@ def _execute_in_rw_transaction(self):
376406
while True:
377407
try:
378408
self._result_set = self.connection.run_statement(
379-
statement, self.request_options
409+
statement, self.request_options, self.timeout
380410
)
381411
self._itr = PeekIterator(self._result_set)
382412
return
@@ -558,11 +588,14 @@ def _fetch(self, cursor_statement_type, size=None):
558588
return rows
559589

560590
def _handle_DQL_with_snapshot(self, snapshot, sql, params):
591+
kwargs = {"request_options": self.request_options}
592+
if self.timeout is not None:
593+
kwargs["timeout"] = self.timeout
561594
self._result_set = snapshot.execute_sql(
562595
sql,
563596
params,
564597
get_param_types(params),
565-
request_options=self.request_options,
598+
**kwargs,
566599
)
567600
# Read the first element so that the StreamedResultSet can
568601
# return the metadata after a DQL statement.
@@ -651,8 +684,12 @@ def run_sql_in_snapshot(self, sql, params=None, param_types=None):
651684
raise ValueError("Database needs to be passed for this operation")
652685
self.connection.run_prior_DDL_statements()
653686

687+
kwargs = {}
688+
if self.timeout is not None:
689+
kwargs["timeout"] = self.timeout
690+
654691
with self.connection.database.snapshot() as snapshot:
655-
return list(snapshot.execute_sql(sql, params, param_types))
692+
return list(snapshot.execute_sql(sql, params, param_types, **kwargs))
656693

657694
def get_table_column_schema(self, table_name, schema_name=""):
658695
rows = self.run_sql_in_snapshot(

‎packages/google-cloud-spanner/google/cloud/spanner_dbapi/transaction_helper.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,9 @@ def retry_transaction(self, default_retry_delay=None):
187187
else:
188188
cursor = self._connection.cursor()
189189
cursor._in_retry_mode = True
190+
cursor._timeout = getattr(
191+
statement_result_details.cursor, "_timeout", None
192+
)
190193
self._cursor_map[statement_result_details.cursor] = cursor
191194
try:
192195
_handle_statement(statement_result_details, cursor)

0 commit comments

Comments
 (0)