Source code for sqlspec.utils.uuids

"""UUID and ID generation utilities with optional acceleration.

Provides wrapper functions for UUID construction, uuid3, uuid4, uuid5, uuid6,
uuid7, and nanoid generation. Uses uuid-utils and fastnanoid packages for
performance when available, falling back to the standard library.

When uuid-utils is installed:
    - uuid3, uuid4, uuid5, uuid6, uuid7 use the faster Rust implementation
    - uuid6 and uuid7 provide proper time-ordered UUIDs per RFC 9562

When uuid-utils is NOT installed:
    - uuid3, uuid4, uuid5 fall back silently to stdlib (equivalent output)
    - uuid6, uuid7 fall back to uuid4 with a warning (different UUID version)

When fastnanoid is installed:
    - nanoid() uses the Rust implementation for 21-char URL-safe IDs

When fastnanoid is NOT installed:
    - nanoid() falls back to uuid4().hex with a warning (different format)
"""

import uuid as _uuid_mod
import warnings
from typing import Any, cast
from uuid import NAMESPACE_DNS, NAMESPACE_OID, NAMESPACE_URL, NAMESPACE_X500, UUID
from uuid import uuid3 as _stdlib_uuid3
from uuid import uuid4 as _stdlib_uuid4
from uuid import uuid5 as _stdlib_uuid5

from sqlspec.typing import NANOID_INSTALLED, UUID_UTILS_INSTALLED
from sqlspec.utils.module_loader import import_optional

__all__ = (
    "NAMESPACE_DNS",
    "NAMESPACE_OID",
    "NAMESPACE_URL",
    "NAMESPACE_X500",
    "NANOID_INSTALLED",
    "UUID_UTILS_INSTALLED",
    "nanoid",
    "uuid3",
    "uuid4",
    "uuid5",
    "uuid6",
    "uuid7",
    "uuid_from_bytes",
    "uuid_from_int",
    "uuid_from_string",
)


_uuid_utils_mod: Any | None = import_optional("uuid_utils.compat")
_uuid_utils_native_mod: Any | None = import_optional("uuid_utils")
_fastnanoid_mod: Any | None = import_optional("fastnanoid")


def uuid_from_string(value: str) -> "UUID":
    """Construct a stdlib UUID from text, using Rust parsing when available.

    Args:
        value: Canonical, hexadecimal, URN, or braced UUID text accepted by
            ``uuid.UUID`` and ``uuid_utils.UUID``.

    Returns:
        A standard-library UUID suitable for native database drivers.
    """
    module = _uuid_utils_native_mod
    if module is None:
        return UUID(value)
    return UUID(int=module.UUID(value).int)
def uuid_from_bytes(value: bytes) -> "UUID": """Construct a stdlib UUID from its 16-byte representation. The stdlib constructor is retained for this shape because converting a Rust UUID back to the driver-compatible stdlib type is slower. Args: value: UUID bytes in big-endian order. Returns: A standard-library UUID. """ return UUID(bytes=value)