Skip to content

Commit

Permalink
make compatible to SQLAlchemy and add example
Browse files Browse the repository at this point in the history
  • Loading branch information
beheh committed Sep 25, 2023
1 parent 9ab5e17 commit ee0de5b
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
29 changes: 29 additions & 0 deletions examples/sqlalchemy.py
Original file line number Diff line number Diff line change
@@ -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)


8 changes: 8 additions & 0 deletions typeid/typeid.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)))

0 comments on commit ee0de5b

Please sign in to comment.