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
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

from collections import namedtuple
from dataclasses import replace
from typing import Optional

import sqlparse
from google.api_core.exceptions import (
Expand Down Expand Up @@ -321,6 +322,7 @@ def _reset(self):
self._result_set = None
self._row_count = None
self._batch_dml_rows_count = None
self._parsed_statement = None

@check_not_closed
def execute(self, sql, args=None):
Expand Down Expand Up @@ -402,20 +404,36 @@ def _execute(self, sql, args=None, call_from_execute_many=False):
raise

finally:
if (
not self._in_retry_mode
and not call_from_execute_many
and not (
self._parsed_statement is not None
and self._parsed_statement.statement_type == StatementType.DDL
)
if not call_from_execute_many and self._should_record_execute_for_retry(
exception
):
self.transaction_helper.add_execute_statement_for_retry(
self, sql, args, exception, False
)
if self.connection._client_transaction_started is False:
self.connection._spanner_transaction_started = False

def _should_record_execute_for_retry(self, exception: Optional[Exception]) -> bool:
"""Return whether the current execute() call should be recorded for retry."""
if self._in_retry_mode:
return False
if self._parsed_statement is None:
return True
if self._parsed_statement.statement_type == StatementType.DDL:
return False
if (
self._parsed_statement.statement_type == StatementType.CLIENT_SIDE
and self._parsed_statement.client_side_statement_type is not None
):
# Transaction boundary statements (such as BEGIN, COMMIT, ROLLBACK)
# alter client-side transaction lifecycle state rather than a single
# Spanner attempt; COMMIT/ROLLBACK also reset retry state on failure.
statement_type = self._parsed_statement.client_side_statement_type
if exception is None:
return statement_type.should_record_success_for_retry
return statement_type.should_record_failure_for_retry
return True

def _execute_in_rw_transaction(self):
# For every other operation, we've got to ensure that
# any prior DDL statements were run.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,25 @@ class ClientSideStatementType(Enum):
SET_AUTO_PARTITION_MODE = 15
SHOW_AUTO_PARTITION_MODE = 16

@property
def should_record_success_for_retry(self) -> bool:
"""Whether a successful statement should be recorded for transaction retry."""
return self not in (
ClientSideStatementType.BEGIN,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Should we include SHOW_COMMIT_TIMESTAMP and SHOW_READ_TIMESTAMP because they are executed based on the results of prev commit?

For example

// Executes Transaction 1 and commit
cursor.execute("INSERT INTO singers (id, name) VALUES (1, 'A')")
conn.commit()

// Post commit - Print the commit timestamp
cursor.execute("SHOW VARIABLE COMMIT_TIMESTAMP")
rows = cursor.fetchall()

// Execute Transaction 28
cursor.execute("INSERT INTO singers (id, name) VALUES (2, 'B')")
conn.commit() -> Fails with aborted error

When seconds transaction fails with ABORTED error, reply will fail because second transaction detail is overridden because Transaction 2 is already started.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

No, we should not touch those (and also not the other SHOW / SET / START BATCH commands). This pull request intentionally limits the scope to the transaction control statements. Fixing this type of issues for connection state in general with a few small changes is not possible. Instead, the long-term fix is to replace the current ad-hoc fields that are used for connection state with a real ConnectionState implementation like we have in Java Connection API and Go database/sql. This will also make it possible to make ConnectionState transactional. I will be working on that in later pull requests.

ClientSideStatementType.COMMIT,
ClientSideStatementType.ROLLBACK,
)

@property
def should_record_failure_for_retry(self) -> bool:
"""Whether a failed statement should be recorded for transaction retry."""
# COMMIT and ROLLBACK reset transaction state in finally blocks, so
# recording a failure would leak into the next transaction.
return self not in (
ClientSideStatementType.COMMIT,
ClientSideStatementType.ROLLBACK,
)


class AutocommitDmlMode(Enum):
TRANSACTIONAL = 1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,11 @@ def __init__(self, connection: "Connection"):
# new cursor object used in the retry
self._cursor_map: Dict[Cursor, Cursor] = {}

def _set_connection_for_retry(self):
def _set_connection_for_retry(self) -> None:
# Only reset Spanner-side transaction and batch state here. Client-side
# transaction state (such as whether begin() was called) must remain
# active across retry attempts.
self._connection._spanner_transaction_started = False
self._connection._transaction_begin_marked = False
self._connection._batch_mode = BatchMode.NONE

def reset(self):
Expand Down
Loading
Loading