4040MAX_INTERNAL_RETRIES = 50
4141
4242
43+ def check_not_closed (function ):
44+ """`Connection` class methods decorator.
45+
46+ Raise an exception if the connection is closed.
47+
48+ :raises: :class:`InterfaceError` if the connection is closed.
49+ """
50+
51+ def wrapper (connection , * args , ** kwargs ):
52+ if connection .is_closed :
53+ raise InterfaceError ("Connection is already closed" )
54+
55+ return function (connection , * args , ** kwargs )
56+
57+ return wrapper
58+
59+
4360class Connection :
4461 """Representation of a DB-API connection to a Cloud Spanner database.
4562
@@ -328,15 +345,6 @@ def snapshot_checkout(self):
328345
329346 return self ._snapshot
330347
331- def _raise_if_closed (self ):
332- """Helper to check the connection state before running a query.
333- Raises an exception if this connection is closed.
334-
335- :raises: :class:`InterfaceError`: if this connection is closed.
336- """
337- if self .is_closed :
338- raise InterfaceError ("connection is already closed" )
339-
340348 def close (self ):
341349 """Closes this connection.
342350
@@ -391,15 +399,13 @@ def rollback(self):
391399 self ._release_session ()
392400 self ._statements = []
393401
402+ @check_not_closed
394403 def cursor (self ):
395- """Factory to create a DB-API Cursor."""
396- self ._raise_if_closed ()
397-
404+ """Factory to create a DB API Cursor."""
398405 return Cursor (self )
399406
407+ @check_not_closed
400408 def run_prior_DDL_statements (self ):
401- self ._raise_if_closed ()
402-
403409 if self ._ddl_statements :
404410 ddl_statements = self ._ddl_statements
405411 self ._ddl_statements = []
@@ -454,6 +460,7 @@ def run_statement(self, statement, retried=False):
454460 ResultsChecksum () if retried else statement .checksum ,
455461 )
456462
463+ @check_not_closed
457464 def validate (self ):
458465 """
459466 Execute a minimal request to check if the connection
@@ -468,8 +475,6 @@ def validate(self):
468475 :raises: :class:`google.cloud.exceptions.NotFound`: if the linked instance
469476 or database doesn't exist.
470477 """
471- self ._raise_if_closed ()
472-
473478 with self .database .snapshot () as snapshot :
474479 result = list (snapshot .execute_sql ("SELECT 1" ))
475480 if result != [[1 ]]:
0 commit comments