Skip to content

Commit f563d3f

Browse files
committed
readd retry for serialization failures in DatabaseOperations.execute_sql_flush()
I removed this with CockroachDB 21.2.x support as I couldn't reproduce failures with CockroachDB 22.1.x and later, but I've now seen the failure with CockroachDB 23.1.x alpha 8. The code is now psycopg3 compatible.
1 parent 85eb1e9 commit f563d3f

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

django_cockroachdb/operations.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
1+
import time
2+
13
from django.db.backends.base.base import timezone_constructor
24
from django.db.backends.postgresql.operations import (
35
DatabaseOperations as PostgresDatabaseOperations,
46
)
5-
from django.db.backends.postgresql.psycopg_any import is_psycopg3
7+
from django.db.backends.postgresql.psycopg_any import errors, is_psycopg3
8+
from django.db.utils import OperationalError
69

710

811
class DatabaseOperations(PostgresDatabaseOperations):
@@ -72,6 +75,22 @@ def explain_query_prefix(self, format=None, **options):
7275
prefix += ' (%s)' % ', '.join(extra)
7376
return prefix
7477

78+
def execute_sql_flush(self, sql_list):
79+
# Retry TRUNCATE if it fails with a serialization error.
80+
num_retries = 10
81+
initial_retry_delay = 0.5 # The initial retry delay, in seconds.
82+
backoff_ = 1.5 # For each retry, the last delay is multiplied by this.
83+
next_retry_delay = initial_retry_delay
84+
for retry in range(1, num_retries + 1):
85+
try:
86+
return super().execute_sql_flush(sql_list)
87+
except OperationalError as exc:
88+
if (not isinstance(exc.__cause__, errors.SerializationFailure) or
89+
retry >= num_retries):
90+
raise
91+
time.sleep(next_retry_delay)
92+
next_retry_delay *= backoff_
93+
7594
def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False):
7695
# CockroachDB doesn't support resetting sequences.
7796
return super().sql_flush(style, tables, reset_sequences=False, allow_cascade=allow_cascade)

0 commit comments

Comments
 (0)