mssql-pythonでのロジックと接続レジリエンスの再試行

一時的な障害は、mssql-pythonドライバを通じてSQL ServerやAzure SQLに接続した際に発生する一時的なエラーです。 これらのエラーはしばしば自然に解決します。

  • ネットワーク接続の一時的な途切れ。
  • サーバーリソースの制約。
  • Azure SQL のスロットリング
  • フェイルオーバーイベント。

リトライロジックの実装は、特にクラウドホスト型データベースにおいてアプリケーションの信頼性を向上させます。

設定やコーディングのミスを隠すためにリトライは使わないでください。 データベースの欠損、認証情報の不具合、または接続プールの使い切れた場合は修正が必要で、再度試す必要はありません。

プーリングとデフォルトの msodbcsql18 プロバイダーでは、ドライバは再利用された接続の検証中に一時的にネイティブな接続操作タイムアウトを適用します。これは 0 より大きいログイン タイムアウト値、またはログインタイムアウトがゼロまたは未指定の場合は 15 秒です。 これは全体の検証やチェックアウトの締め切りではありません。 複数のネイティブ操作、クリーンアップ、交換接続の開設は時間がかかることがあります。 検証が失敗した場合、ドライバーは残っている各アイドル接続ごとに待機する代わりに、置き換えを試みます。 この回復はあなたのステートメントを再生したり、プール枯渇を再試行したりするものではありません。 詳細については、 コネクションプーリングをご覧ください。

一時的な誤りを特定する

mssql-pythonは例外時にSQL Serverエンジンのエラー番号を属性として公開しません。 代わりに、ドライバーはSQLSTATEコードをPEP 249例外サブクラス(OperationalError、 ProgrammingErrorなど)の固定セットと、 driver_error 属性の標準化された英語テキストにマッピングします。 その組み合わせを過渡性分類の基礎として使います。

信頼性の高い過渡信号

以下のSQLSTATE値は OperationalError として表示され、再試す価値のある条件を示します。 右側の列は運転手が設定した正確な driver_error テキストを示しています:

SQLSTATE driver_error テキスト 状態
HYT00 Timeout expired 声明レベルのタイムアウトです。
HYT01 Connection timeout expired 接続時のタイムアウト。
08001 Client unable to establish connection 接続が開けなかった。
08S01 Communication link failure ネットワーク切断、サーバーリセット、TCP障害。
08007 Connection failure during transaction 取引中に接続が途絶えました。
40001 Serialization failure デッドロックの犠牲。
40003 Statement completion unknown 取引状態は不確定です。
import mssql_python


TRANSIENT_DRIVER_ERRORS = frozenset({
    "Timeout expired",
    "Connection timeout expired",
    "Client unable to establish connection",
    "Communication link failure",
    "Connection failure during transaction",
    "Serialization failure",
    "Statement completion unknown",
})


def is_transient_error(error: BaseException) -> bool:
    """Return True if the exception represents a retryable transient failure.

    Classification is based on the driver's PEP 249 exception subclass and
    on the standardized `driver_error` text that mssql-python sets from
    the SQLSTATE returned by the server.
    """
    if isinstance(error, mssql_python.OperationalError):
        return getattr(error, "driver_error", "") in TRANSIENT_DRIVER_ERRORS
    return False

Azure SQL 調整 (ベスト エフォート)

Azure SQL のスロットリング エラー(40197、40501、40613、49918、49919、49920、および関連コード)は、通常 SQLSTATE 42000 として返され、mssql-python ではこれが ProgrammingError にマップされます。 エンジンエラー番号は属性として表示されず、信号は ddbc_error 属性内のサーバーメッセージテキストだけです。

既知の番号が存在する場合は、それらと標準的な英語のエラー 40501 メッセージについて ddbc_error を確認してください。 番号が欠けている場合もあり、メッセージのテキストは安定した仕様ではありません。 ローカライズされた診断やフォーマットが異なる診断は一致しない場合があります:

import re

# Azure SQL throttling and reconfiguration error numbers.
AZURE_THROTTLING_ERRORS = frozenset({
    40197, 40501, 40540, 40613, 40680, 49918, 49919, 49920, 10928, 10929,
})

_ERROR_NUMBER_RE = re.compile(r"\b(?:Error|Msg)\s+(\d+)\b")
_AZURE_40501_MESSAGE = "The service is currently busy. Retry the request after 10 seconds."


def is_azure_throttling(error: BaseException) -> bool:
    """Best-effort detection of Azure SQL throttling in ProgrammingError text."""
    if not isinstance(error, mssql_python.ProgrammingError):
        return False
    ddbc_text = getattr(error, "ddbc_error", "") or ""
    return (
        _AZURE_40501_MESSAGE in ddbc_text
        or any(int(m) in AZURE_THROTTLING_ERRORS for m in _ERROR_NUMBER_RE.findall(ddbc_text))
    )


def is_retryable(error: BaseException) -> bool:
    return is_transient_error(error) or is_azure_throttling(error)

再試行しないもの

再試行ではなくすぐに失敗させるべきエラーの例としては、無効な認証情報(Invalid authorization specification ドライバーテキスト OperationalError付き)、データベースの欠如や権限の不足、構文の誤り(ProgrammingError)、オブジェクトの欠如、接続プールの枯渇などがあります。 上記の is_transient_error 関数はこれらすべてを構成上除外しています。

ベーシック リトライ デコレーター

固定遅延の簡単な再挑戦

一定遅延でラップされた関数を一定回数リトライするデコレーター:

import time
import functools
import mssql_python

def retry_on_failure(max_retries: int = 3, delay: float = 1.0):
    """Decorator to retry database operations on transient failures."""
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            last_exception = None
            for attempt in range(max_retries + 1):
                try:
                    return func(*args, **kwargs)
                except mssql_python.Error as e:
                    last_exception = e
                    if not is_transient_error(e) or attempt == max_retries:
                        raise
                    print(f"Attempt {attempt + 1} failed: {e}. Retrying in {delay}s...")
                    time.sleep(delay)
            raise last_exception
        return wrapper
    return decorator

# Usage
@retry_on_failure(max_retries=3, delay=2.0)
def get_user(cursor, user_id: int):
    cursor.execute("SELECT * FROM Person.Person WHERE BusinessEntityID = %(id)s", {"id": user_id})
    return cursor.fetchone()

指数バックオフ

再試行間の遅延を指数関数的に増加させ、オプションのジッターで同時再試行を分散させる:

import time
import random

def retry_with_backoff(max_retries: int = 5, 
                       base_delay: float = 1.0,
                       max_delay: float = 30.0,
                       jitter: bool = True):
    """Retry with exponential backoff and optional jitter."""
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            last_exception = None
            for attempt in range(max_retries + 1):
                try:
                    return func(*args, **kwargs)
                except mssql_python.Error as e:
                    last_exception = e
                    if not is_transient_error(e) or attempt == max_retries:
                        raise
                    
                    # Calculate delay with exponential backoff
                    delay = min(base_delay * (2 ** attempt), max_delay)
                    if jitter:
                        delay = delay * (0.5 + random.random())
                    
                    print(f"Attempt {attempt + 1} failed. Retrying in {delay:.2f}s...")
                    time.sleep(delay)
            raise last_exception
        return wrapper
    return decorator

@retry_with_backoff(max_retries=5, base_delay=1.0, max_delay=30.0)
def execute_query(cursor, query: str, params: dict):
    cursor.execute(query, params)
    return cursor.fetchall()

接続再試行クラス

レジリエント接続マネージャー

再試行と自動再接続の両方を処理する接続ラッパー:

import mssql_python
import time
import logging

# This example uses is_transient_error from the "Identify transient errors"
# section earlier in this article. Include that helper in your module.

# Configure logging so the retry and reconnect messages are visible
logging.basicConfig(level=logging.INFO)

class ResilientConnection:
    """Connection wrapper with automatic retry and reconnection."""
    
    def __init__(self, connection_string: str, max_retries: int = 5,
                 base_delay: float = 1.0, max_delay: float = 60.0):
        self.connection_string = connection_string
        self.max_retries = max_retries
        self.base_delay = base_delay
        self.max_delay = max_delay
        self._conn = None
        self._logger = logging.getLogger(__name__)
    
    def _connect(self) -> mssql_python.Connection:
        """Establish connection with retry logic."""
        last_exception = None
        
        for attempt in range(self.max_retries + 1):
            try:
                self._logger.debug(f"Connection attempt {attempt + 1}")
                return mssql_python.connect(self.connection_string)
            except mssql_python.Error as e:
                last_exception = e
                if not is_transient_error(e) or attempt == self.max_retries:
                    self._logger.error(f"Connection failed: {e}")
                    raise
                
                delay = min(self.base_delay * (2 ** attempt), self.max_delay)
                self._logger.warning(f"Connection attempt {attempt + 1} failed. "
                                   f"Retrying in {delay:.1f}s...")
                time.sleep(delay)
        
        raise last_exception
    
    @property
    def connection(self) -> mssql_python.Connection:
        """Get or create connection."""
        if self._conn is None:
            self._conn = self._connect()
        return self._conn
    
    def execute(self, query: str, params: dict = None):
        """Execute query with automatic retry and reconnection."""
        return self._execute_with_retry(
            lambda c: self._do_execute(c, query, params)
        )
    
    def _do_execute(self, cursor, query: str, params: dict):
        cursor.execute(query, params or {})
        return cursor.fetchall()
    
    def _execute_with_retry(self, operation):
        """Execute an operation with retry logic."""
        last_exception = None
        
        for attempt in range(self.max_retries + 1):
            try:
                cursor = self.connection.cursor()
                return operation(cursor)
            except mssql_python.Error as e:
                last_exception = e
                
                if not is_transient_error(e):
                    raise
                
                if attempt == self.max_retries:
                    raise
                
                # Try to reconnect
                self._logger.warning(f"Operation failed. Reconnecting...")
                self._close()
                
                delay = min(self.base_delay * (2 ** attempt), self.max_delay)
                time.sleep(delay)
        
        raise last_exception
    
    def _close(self):
        """Close connection."""
        if self._conn:
            try:
                self._conn.close()
            except:
                pass
            self._conn = None
    
    def close(self):
        """Public close method."""
        self._close()
    
    def __enter__(self):
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()
        return False

# Usage
with ResilientConnection(connection_string) as db:
    users = db.execute("SELECT * FROM Person.Person WHERE EmailPromotion = %(promo)s", 
                       {"promo": 1})
    print(f"Retrieved {len(users)} rows")

Azure SQL 固有の処理

Identify Transient errorのmssql-python例外マッピングを使って、以下のカタログからエラーを分類してください。

以下のエラーは、接続確立時やサーバーへのリクエスト送信時に一時的に発生することがあります。 短い境界付きバックオフで再試行します。 数回のリトライを経てもエラーが続くのは、サーバーの誤り、権限の欠落、暗号化設定の互換性がなさない、またはクォータが尽きてリトライでは直らない設定の問題を示していることが多いです。

エラー エラーの種類 Message Troubleshooting
64 ログイン時の転送 A connection was successfully established with the server, but then an error occurred during the login process. (provider: TCP Provider, error: 0 - The specified network name is no longer available.) TCP 接続がハンドシェイクの途中で切断されます。 認証情報エラーではありません。 それでも解決しない場合は、クライアント側のネットワークが不安定であるか、または半分確立された接続を切断する中間デバイスを確認します。
233 ログイン前のトランスポートまたはTLS The client was unable to establish a connection because of an error during connection initialization process before login. サーバーはリソースの枯渇、接続制限、またはサポートされていないクライアントのために接続を受け入れられない場合にこのエラーを返すことが多いです。 認証情報エラーではありません。 サーバーの正常性を確認し、クライアント ログインのタイムアウト、TLS 設定、およびクライアント/サーバーの TLS バージョンの互換性を確認します。
4060 データベースの利用可能性やアクセス Cannot open database "%.*ls" requested by the login. The login failed. ログインは認証されますが、要求されたデータベースを開くことはありません。 一時的な原因には、データベースの移行中 (フェールオーバー、復元、スケーリング) や自動一時停止が含まれます。 永続的な原因 (データベースが存在せず、ログインにアクセスできない) は再試行によって修正されません。データベース名、ログイン マッピング、およびデータベースの状態を確認します。
4221 読みやすいセカンダリ遷移 Login to read-secondary failed due to long wait on 'HADR_DATABASE_WAIT_FOR_TRANSITION_TO_VERSIONING'. レプリカがリサイクルされたときに実行中だったトランザクションに対して行バージョンが見つからないため、レプリカはログインに使用できません。 プライマリでアクティブなトランザクションをロールバックまたはコミットして、問題を解決します。 プライマリで長い書き込みトランザクションを回避することで軽減します。
10053 現地輸送中止 A transport-level error has occurred when sending the request to the server. (provider: TCP Provider, error: 0 - An established connection was aborted by the software in your host machine.) ローカル側が接続を中止します。 クライアント側のネットワーク正常性と、ローカル ファイアウォールまたは VPN クライアントを確認します。
10054 リモートトランスポートリセット A transport-level error has occurred when sending the request to the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.) リモート側は TCP リセットを送信します。 一般的な原因: ピア プロセスがクラッシュした、ファイアウォールがリセットを挿入した、またはAzure SQLゲートウェイがアイドル状態の接続を閉じた。 アイドル リセット パターンの場合は、クライアントで TCP キープアライブを有効にするか、接続プールのアイドル タイムアウトを短縮します。
10060 接続タイムアウト A connection attempt failed because the connected party did not properly respond after a period of time. サーバーや中間のネットワークデバイスがTCP接続のタイムアウト前に応答しませんでした。 サーバーの健康状態、ルーティング、ファイアウォールルール、設定されたホストとポートが到達可能かどうかを確認しましょう。
10928 データベースリソースの制限 Resource ID: %d. The %s limit for the database is %d and has been reached. データベースがAzure SQLリソース ガバナンスの制限を超えています。 リソース ID 1 はワーカーの制限を示します。リソース ID 2 は、セッションの制限を示します。 メッセージから制限の種類を特定し、コンカレンシーを減らすか、データベースをスケールアップするか、リソースを保持する実行時間の長い操作を短縮します。
10929 データベースのスロットリング Resource ID: %d. The %s minimum guarantee is %d, maximum limit is %d, and the current usage for the database is %d. However, the server is currently too busy to support requests greater than %d for this database. データベースは最小保証を超過しており、基盤となるサーバーでスロットル制御が行われています。 再試行は通常、近隣の負荷が低下したときに成功します。 継続的な発生は、より高いサービス レベルまたはノイズの少ない環境が必要であることを示します。
40020、40143、40166、40540 Azure SQL フェールオーバー サブコード フェールオーバー中にエラー 40197 の Error code %d スロットで報告されました。 40197フェイルオーバーメッセージに埋め込まれたサブコードで、一部の経路は最上位エラー番号として表面化します。 40197 と同じように扱います。
40197 Azure SQL フェールオーバー The service has encountered an error processing your request. Please try again. Error code %d. Azure SQLでのソフトウェアのアップグレード、ハードウェア障害、またはその他のフェールオーバー イベント。 再接続すると、正常なレプリカにルーティングされます。 埋め込みエラー コードは、フェールオーバーの種類を識別します。 エラーが解決しない場合は、セッション トレース ID をキャプチャし、サポートにお問い合わせください。
40501 Azure SQL のスロットリング The service is currently busy. Retry the request after 10 seconds. Incident ID: %ls. Code: %d. Azure SQL Engine のスロットリング。 推奨されるバックオフの下限は 10 秒です。 持続的なスロットリングは、作業負荷がデータベースのリソース割り当てを超えていることを示します。サービス層を拡大するか、並行性を減らすか。
40613 データベースは使用できません Database '%.*ls' on server '%.*ls' is not currently available. Please retry the connection later. If the problem persists, contact customer support, and provide them with the session tracing ID of '%.*ls'. データベースは使用できません。通常はフェールオーバー中、またはスケール操作中に短時間です。 バックオフ時に再試行します。数分後に保持される場合は、セッション トレース ID をキャプチャし、サポート ケースを開きます。
42108 SQLプールの一時停止 Can not connect to the SQL pool since it is paused. Please resume the SQL pool and try again. 専用 SQL プール (Synapse) は一時停止状態です。 再試行は、プールが再開された後にのみ成功します。 プールを明示的に再開するか、プールの再開後にワークロードを実行するようにスケジュールします。
42109 SQLプールの再開 The SQL pool is warming up. Please try again. 専用 SQL プールが再開中です。 プールがオンラインになるまでバックオフを再試行します。ウォームアップには通常数分かかります。
49918 サービス資源不足 Cannot process request. Not enough resources to process request. The service is currently busy. Please retry the request later. サーバーは現在、要求を満たすのに十分なリソースを割り当てられません。 バックオフ時に再試行してください。 エラーが解決しない場合は、データベースまたはエラスティック プールをスケールアップします。
49919 管理操作スロットリング Cannot process create or update request. Too many create or update operations in progress for subscription "%ld". 管理操作に対するサブスクリプション レベルのコンカレンシー制限。 並列作成/更新呼び出しを減らすか、それらをずらします。
49920 サブスクリプション操作スロットリング Cannot process request. Too many operations in progress for subscription "%ld". 実行中の操作に対するサブスクリプション レベルでの同時実行制限。 並列処理を減らすか、進行中の操作が完了するまで待機してください。

ステートメント レベルのエラーは、接続が確立された後に発生し、エラーによってセッションが使用可能な状態になるため、この一覧には含まれません。 再試行可能な最も一般的なステートメント エラーは、1205 (デッドロックの対象) と 1222 (ロック要求タイムアウト) です。 単一の失敗したステートメントではなく、トランザクション全体を再試行してください。

エラー メッセージ テキストはAzure SQL の一時的な接続エラーから取得されます。 これらのエラーは、SQL Server、Azure SQL Database、Azure SQL Managed Instance、Microsoft FabricのSQL Database、およびAzure Synapse Analyticsの専用SQLプールで再試行が可能です。

Azure スロットリングに対処する

Azure SQLのスロットリングエラーは、標準的な一時的なエラーよりも長い遅延と再試行が必要です。 一時的なエラーを特定する の is_azure_throttling を再利用します:

def execute_with_throttle_handling(cursor, query: str, params: dict,
                                   max_retries: int = 10,
                                   base_delay: float = 10.0):
    """Execute with extended retry for Azure SQL throttling."""
    for attempt in range(max_retries + 1):
        try:
            cursor.execute(query, params)
            return cursor.fetchall()
        except mssql_python.Error as e:
            if is_azure_throttling(e):
                if attempt < max_retries:
                    # Longer delays for throttling
                    delay = base_delay * (2 ** min(attempt, 4))  # Cap at 16 times the base delay
                    print(f"Throttled. Waiting {delay}s before retry...")
                    time.sleep(delay)
                    continue
            raise

フェールオーバーの処理

Azure SQLまたは可用性グループのフェイルオーバーが接続を中断した場合、再接続して再試行してください:

def execute_with_failover_retry(connect, query: str, params: dict,
                                max_retries: int = 3,
                                recovery_delay: float = 10.0):
    """Reconnect and retry during Azure SQL failover scenarios."""
    failover_numbers = frozenset({40613, 40197, 40540})
    last_exception = None

    for attempt in range(max_retries + 1):
        conn = None
        try:
            conn = connect()
            cursor = conn.cursor()
            cursor.execute(query, params)
            return cursor.fetchall()
        except mssql_python.Error as e:
            last_exception = e

            # Failover surfaces either as a transient OperationalError or as
            # a ProgrammingError whose ddbc_error text contains the engine
            # error number. Treat both as recoverable.
            ddbc_text = getattr(e, "ddbc_error", "") or ""
            is_failover = is_transient_error(e) or any(
                int(m) in failover_numbers for m in _ERROR_NUMBER_RE.findall(ddbc_text)
            )

            if is_failover and attempt < max_retries:
                print(f"Failover detected. Reconnecting in {recovery_delay}s...")
                if conn is not None:
                    try:
                        conn.close()
                    except mssql_python.Error:
                        pass
                time.sleep(recovery_delay)
                continue
            raise

    raise last_exception


# Usage
connection_string = (
    "Server=tcp:<server>.database.windows.net,1433;"
    "Database=AdventureWorks2025;"
    "Authentication=ActiveDirectoryDefault;"
    "Encrypt=yes;TrustServerCertificate=no"
)

rows = execute_with_failover_retry(
    lambda: mssql_python.connect(connection_string),
    "SELECT TOP 10 ProductID, Name FROM Production.Product WHERE Color = %(color)s",
    {"color": "Silver"}
)

デッドロック処理

デッドロック時に再試行

デッドロック(エラー1205)は一時的なものです。 デッドロックサイクルを破るために、短いランダム遅延で再挑戦してください。 再試行は即時の失敗を解決しますが、繰り返されるデッドロックは設計上の問題を示しており、サーバー側で調査すべきです。 根本原因の分析と解決に関する指針については、 Deadlock errorsを参照してください。

def execute_with_deadlock_retry(cursor, query: str, params: dict,
                                max_retries: int = 3):
    """Automatically retry deadlocked transactions.

    Deadlocks (SQL Server error 1205) surface as OperationalError with
    driver_error == "Serialization failure" (SQLSTATE 40001).
    """
    for attempt in range(max_retries + 1):
        try:
            cursor.execute(query, params)
            return cursor.fetchall()
        except mssql_python.OperationalError as e:
            if getattr(e, "driver_error", "") == "Serialization failure":
                if attempt < max_retries:
                    delay = random.uniform(0.1, 0.5) * (attempt + 1)
                    print(f"Deadlock detected. Retry {attempt + 1} in {delay:.2f}s")
                    time.sleep(delay)
                    continue
            raise

# Usage in transaction
conn.autocommit = False
try:
    cursor = conn.cursor()
    rows = execute_with_deadlock_retry(
        cursor,
        "SELECT TOP 5 Name, ListPrice FROM Production.Product WHERE ListPrice > %(price)s",
        {"price": 100}
    )
    conn.commit()
except Exception:
    conn.rollback()
    raise

設定可能な構造化リトライ

再試行ポリシー クラス

異なる操作間で再利用可能なデータクラスに再試行構成をカプセル化します:

from dataclasses import dataclass, field
from typing import FrozenSet
import time
import random

# This example uses TRANSIENT_DRIVER_ERRORS from the "Identify transient errors"
# section earlier in this article. Include that allowlist in your module.

@dataclass
class RetryPolicy:
    """Configuration for retry behavior."""
    max_retries: int = 3
    base_delay: float = 1.0
    max_delay: float = 30.0
    exponential_base: float = 2.0
    jitter: bool = True
    transient_driver_errors: FrozenSet[str] = field(default_factory=lambda: TRANSIENT_DRIVER_ERRORS)

    def get_delay(self, attempt: int) -> float:
        """Calculate delay for given attempt number."""
        delay = min(
            self.base_delay * (self.exponential_base ** attempt),
            self.max_delay,
        )
        if self.jitter:
            delay *= (0.5 + random.random())
        return delay

    def should_retry(self, error: BaseException, attempt: int) -> bool:
        """Determine if operation should be retried."""
        if attempt >= self.max_retries:
            return False
        if isinstance(error, mssql_python.OperationalError):
            return getattr(error, "driver_error", "") in self.transient_driver_errors
        return False

def execute_with_policy(cursor, query: str, params: dict,
                        policy: RetryPolicy = None):
    """Execute query with configurable retry policy."""
    policy = policy or RetryPolicy()
    last_exception = None

    for attempt in range(policy.max_retries + 1):
        try:
            cursor.execute(query, params)
            return cursor.fetchall()
        except mssql_python.Error as e:
            last_exception = e
            if not policy.should_retry(e, attempt):
                raise

            delay = policy.get_delay(attempt)
            time.sleep(delay)

    raise last_exception

# Usage with custom policy
aggressive_retry = RetryPolicy(max_retries=10, base_delay=0.5, max_delay=60.0)
conservative_retry = RetryPolicy(max_retries=2, base_delay=5.0, max_delay=10.0)

results = execute_with_policy(cursor, query, params, aggressive_retry)

サーキット ブレーカー パターン

連続したエラーを追跡し、閾値に達した際に一時的に通話をブロックすることで連鎖的な故障を防ぎます:

import time
from enum import Enum
from threading import Lock

class CircuitState(Enum):
    CLOSED = "closed"      # Normal operation
    OPEN = "open"          # Failing, reject all calls
    HALF_OPEN = "half_open"  # Testing if service recovered

class CircuitBreaker:
    """Circuit breaker to prevent cascading failures."""
    
    def __init__(self, failure_threshold: int = 5,
                 recovery_timeout: float = 30.0):
        self.failure_threshold = failure_threshold
        self.recovery_timeout = recovery_timeout
        self.state = CircuitState.CLOSED
        self.failure_count = 0
        self.last_failure_time = None
        self._lock = Lock()
    
    def can_execute(self) -> bool:
        """Check if circuit allows execution."""
        with self._lock:
            if self.state == CircuitState.CLOSED:
                return True
            
            if self.state == CircuitState.OPEN:
                # Check if recovery timeout has passed
                if time.time() - self.last_failure_time > self.recovery_timeout:
                    self.state = CircuitState.HALF_OPEN
                    return True
                return False
            
            # HALF_OPEN: allow one test request
            return True
    
    def record_success(self):
        """Record successful operation."""
        with self._lock:
            self.failure_count = 0
            self.state = CircuitState.CLOSED
    
    def record_failure(self):
        """Record failed operation."""
        with self._lock:
            self.failure_count += 1
            self.last_failure_time = time.time()
            
            if self.failure_count >= self.failure_threshold:
                self.state = CircuitState.OPEN

# Usage
circuit = CircuitBreaker(failure_threshold=5, recovery_timeout=30.0)

def execute_with_circuit_breaker(cursor, query: str, params: dict):
    if not circuit.can_execute():
        raise Exception("Circuit breaker is open")
    
    try:
        cursor.execute(query, params)
        result = cursor.fetchall()
        circuit.record_success()
        return result
    except mssql_python.Error as e:
        if is_transient_error(e):
            circuit.record_failure()
        raise

設定エラーをやり直さないでください

すべてのエラーが一時的なものではありません。 設定やコーディングの誤りをやり直すのは時間の無駄で、本当の問題を隠してしまうことがあります。 自動で解決しそうなエラーだけを再試行してください。 mssql-pythonはエンジンのエラー番号を属性として公開しないため、例外サブクラスと driver_error テキストで分類します。

これらの場合は絶対に再試 しないでください(代わりにコードや設定を修正してください):

状態 例外の種類 driver_error テキスト Fix
無効なオブジェクト名(エンジン208) ProgrammingError Base table or view not found テーブルは存在しません。 クエリを修正するか、テーブルを作成してください。
無効な列名 (エンジン 207) ProgrammingError Column not found その列は存在しません。 スキーマを確認してください。
誤った構文(エンジン102) ProgrammingError Syntax error or access violation クエリを修正してください。
ログイン失敗(エンジン18456) OperationalError Invalid authorization specification 間違った資格です。 接続文字列を直してください。
データベースが見つからない、またはアクセスが拒否されました (エンジン 4060) OperationalError Server rejected the connection データベースは存在しないか、ログイン時にアクセスできません。 ターゲットや権限を固定します。
接続プールの枯渇 OperationalError (異なる) プール容量を増やしたり、接続を迅速に解除したり、並行性を減らすこと。
ConnectionStringParseError スタンドアロン なし 「接続文字列」キーワードにタイプミスがあります。 紐を直せ。
サポートされていない機能 NotSupportedError Optional feature not implemented 別の方法を使いましょう。

必ずこれらのものをやり直してください (自動で解決します):

状態 例外の種類 driver_error テキスト
ステートメントのタイムアウト OperationalError Timeout expired
接続タイムアウト OperationalError Connection timeout expired
接続が開けませんでした OperationalError Client unable to establish connection
ネットワークの断絶 OperationalError Communication link failure
取引途中で接続が切断されました OperationalError Connection failure during transaction
デッドロック被害者 (エンジン 1205) OperationalError Serialization failure
不確定取引状態 OperationalError Statement completion unknown
Azure SQL throttling (40197, 40501, 40613, 49918–49920) ProgrammingError Syntax error or access violation (ddbc_error テキストに合わせるには is_azure_throttling を使用)