Source code for sqlspec.utils.sync_tools

"""Utilities for async/sync interoperability in SQLSpec.

This module provides utilities for converting between async and sync functions,
managing concurrency limits, and handling context managers. Used primarily
for adapter implementations that need to support both sync and async patterns.
"""

import asyncio
import atexit
import concurrent.futures
import contextvars
import functools
import inspect
import os
import sys
import threading
from contextlib import AbstractAsyncContextManager, AbstractContextManager
from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast, overload

from typing_extensions import ParamSpec

from sqlspec.utils.env import get_env
from sqlspec.utils.module_loader import module_available
from sqlspec.utils.portal import get_global_portal

if TYPE_CHECKING:
    from collections.abc import Awaitable, Callable, Coroutine
    from types import TracebackType

if module_available("uvloop"):
    import uvloop  # pyright: ignore[reportMissingImports]
else:
    uvloop = None  # type: ignore[assignment,unused-ignore]


ReturnT = TypeVar("ReturnT")
ParamSpecT = ParamSpec("ParamSpecT")
T = TypeVar("T")

DEFAULT_ASYNC_THREAD_LIMIT = 8
ASYNC_THREAD_LIMIT_ENV = "SQLSPEC_ASYNC_THREAD_LIMIT"
_ASYNC_THREAD_NAME_PREFIX = "sqlspec-async"


class NoValue:
    """Sentinel class for missing values."""
NO_VALUE = NoValue() class CapacityLimiter: """Limits the number of concurrent operations using a semaphore.""" def __init__(self, total_tokens: int) -> None: """Initialize the capacity limiter. Args: total_tokens: Maximum number of concurrent operations allowed """ self._total_tokens = total_tokens self._semaphore_instance: asyncio.Semaphore | None = None self._pid: int | None = None