diff --git a/examples/sqlalchemy.py b/examples/sqlalchemy.py new file mode 100644 index 0000000..675b209 --- /dev/null +++ b/examples/sqlalchemy.py @@ -0,0 +1,29 @@ +from typing import Optional + +from sqlalchemy import types +from typeid import TypeID, from_uuid + + +class TypeIDType(types.TypeDecorator): + impl = types.Uuid + + cache_ok = True + + prefix: Optional[str] + + def __init__(self, prefix: Optional[str], *args, **kwargs): + self.prefix = prefix + super().__init__(*args, **kwargs) + + def process_bind_param(self, value: TypeID, dialect): + if self.prefix is None: + assert value.prefix is None + else: + assert value.prefix == self.prefix + + return value.uuid + + def process_result_value(self, value, dialect): + return from_uuid(value, self.prefix) + + diff --git a/typeid/typeid.py b/typeid/typeid.py index 3ff3fb7..ba1ce4c 100644 --- a/typeid/typeid.py +++ b/typeid/typeid.py @@ -26,6 +26,10 @@ def suffix(self) -> str: def prefix(self) -> str: return self._prefix + @property + def uuid(self) -> UUID: + return _convert_b32_to_uuid(self.suffix) + def __str__(self) -> str: value = "" if self.prefix: @@ -69,3 +73,7 @@ def get_prefix_and_suffix(string: str) -> tuple: def _convert_uuid_to_b32(uuid_instance: UUID) -> str: return base32.encode(list(uuid_instance.bytes)) + + +def _convert_b32_to_uuid(b32: str) -> UUID: + return UUID(bytes=bytes(base32.decode(b32)))