Skip to content

Commit 6eb4d3b

Browse files
committed
refactor: add custom ULID type for sqlalchemy
1 parent 340974f commit 6eb4d3b

File tree

4 files changed

+28
-2
lines changed

4 files changed

+28
-2
lines changed

components/renku_data_services/project/db.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ async def insert_project(
171171
creation_date=datetime.now(UTC).replace(microsecond=0),
172172
keywords=project.keywords,
173173
)
174-
project_slug = schemas.ProjectSlug(slug, project_id=project_orm.id, namespace_id=ns.id)
174+
project_slug = schemas.ProjectSlug(slug, project_id=str(project_orm.id), namespace_id=ns.id)
175175

176176
session.add(project_slug)
177177
session.add(project_orm)

components/renku_data_services/project/orm.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from renku_data_services.namespace.orm import NamespaceORM
1414
from renku_data_services.project import models
1515
from renku_data_services.project.apispec import Visibility
16+
from renku_data_services.utils.sqlalchemy import ULIDType
1617

1718
metadata_obj = MetaData(schema="projects") # Has to match alembic ini section name
1819

@@ -27,7 +28,7 @@ class ProjectORM(BaseORM):
2728
"""A Renku native project."""
2829

2930
__tablename__ = "projects"
30-
id: Mapped[str] = mapped_column("id", String(26), primary_key=True, default_factory=lambda: str(ULID()), init=False)
31+
id: Mapped[ULID] = mapped_column("id", ULIDType, primary_key=True, default_factory=lambda: str(ULID()), init=False)
3132
name: Mapped[str] = mapped_column("name", String(99))
3233
visibility: Mapped[Visibility]
3334
created_by_id: Mapped[str] = mapped_column("created_by_id", String())

components/renku_data_services/utils/py.typed

Whitespace-only changes.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""Utilities for SQLAlchemy."""
2+
3+
from typing import cast
4+
5+
from sqlalchemy import Dialect, types
6+
from ulid import ULID
7+
8+
9+
class ULIDType(types.TypeDecorator):
10+
"""Wrapper type for ULID <--> str conversion."""
11+
12+
impl = types.String
13+
cache_ok = True
14+
15+
def process_bind_param(self, value: ULID | None, dialect: Dialect) -> str | None:
16+
"""Transform value for storing in the database."""
17+
if value is None:
18+
return None
19+
return str(value)
20+
21+
def process_result_value(self, value: str | None, dialect: Dialect) -> ULID | None:
22+
"""Transform string from database into ULID."""
23+
if value is None:
24+
return None
25+
return cast(ULID, ULID.from_str(value))

0 commit comments

Comments
 (0)