Verified Commit 06b53773 authored by Jakob Moser's avatar Jakob Moser
Browse files

Add Uuid type and InvalidUuidError type

parent 243222a9
Loading
Loading
Loading
Loading
+6 −0
Original line number Diff line number Diff line
class InvalidUuidError(ValueError):
    """
    A given string should have been a valid UUID, but was not.
    """

    pass

poolpay/model/Uuid.py

0 → 100644
+37 −0
Original line number Diff line number Diff line
from uuid import UUID

import sqlalchemy.types as types
from sqlalchemy.engine import Dialect

UUID_LENGTH = 36


class Uuid(types.TypeDecorator):
    """
    A UUID, stored as a 36-character string containing dashes.

    There is a built-in SQLAlchemy type representing a UUID (which uses built-in database types for UUIDs, if they
    exist), but it falls back to 32-character strings (dashes are removed) if there is no such type (like with
    MySQL, MariaDB or SQLite).

    This makes working directly in the database (which often is a requirement) complicated, so we've decided to
    implement our own type for that.
    """

    impl = types.TypeEngine
    cache_ok = True

    def load_dialect_impl(self, dialect: Dialect) -> types.TypeEngine[str]:
        return types.String(UUID_LENGTH)

    def process_bind_param(
        self, value: str | UUID | None, dialect: Dialect
    ) -> str | None:
        if isinstance(value, str):
            # Manually create UUID from string, to raise an error if the string is malformed
            UUID(value)

        return str(value) if value else None

    def process_result_value(self, value: str | None, dialect: Dialect) -> UUID | None:
        return UUID(value) if value else None