"""pymssql database configuration with thread-local connections."""
import contextlib
import logging
import threading
import time
from contextlib import contextmanager
from typing import TYPE_CHECKING, Any, cast
from sqlspec.adapters.pymssql._typing import PYMSSQL_MODULE, PymssqlConnection
from sqlspec.utils.logging import POOL_LOGGER_NAME, get_logger, log_with_context
from sqlspec.utils.uuids import uuid4
if TYPE_CHECKING:
from collections.abc import Callable, Generator
__all__ = ("PymssqlConnectionPool",)
logger = get_logger(POOL_LOGGER_NAME)
_ADAPTER_NAME = "pymssql"
pymssql = PYMSSQL_MODULE
class PymssqlConnectionPool:
"""Thread-local connection manager for pymssql."""
__slots__ = (
"_connection_parameters",
"_health_check_interval",
"_on_connection_create",
"_pool_id",
"_recycle_seconds",
"_thread_local",
)
def __init__(
self,
connection_parameters: "dict[str, Any]",
recycle_seconds: int = 86400,
health_check_interval: float = 30.0,
on_connection_create: "Callable[[PymssqlConnection], None] | None" = None,
) -> None:
"""Initialize the thread-local connection manager.
Args:
connection_parameters: pymssql connection parameters
recycle_seconds: Connection recycle time in seconds (default 24h)
health_check_interval: Seconds of idle time before running health check
on_connection_create: Callback executed when connection is created
"""
self._connection_parameters = connection_parameters
self._thread_local = threading.local()
self._recycle_seconds = recycle_seconds
self._health_check_interval = health_check_interval
self._on_connection_create = on_connection_create
self._pool_id = str(uuid4())[:8]