Skip to content

Commit 609abf3

Browse files
committed
refactor: adds jsonb annotation for postgres
1 parent 3312a12 commit 609abf3

File tree

1 file changed

+42
-15
lines changed

1 file changed

+42
-15
lines changed

src/labs/models/utils.py

Lines changed: 42 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,24 @@
1010

1111
from uuid import UUID
1212

13-
from sqlalchemy import DateTime, ForeignKey, func,\
14-
select,\
15-
update as sqlalchemy_update,\
13+
from sqlalchemy import (
14+
DateTime,
15+
ForeignKey,
16+
func,
17+
select,
18+
update as sqlalchemy_update,
1619
delete as sqlalchemy_delete
17-
from sqlalchemy.orm import Mapped, mapped_column
18-
from sqlalchemy.dialects.postgresql import UUID as PGUUID
20+
)
21+
22+
from sqlalchemy.orm import (
23+
Mapped,
24+
mapped_column
25+
)
26+
27+
from sqlalchemy.dialects.postgresql import (
28+
UUID as PGUUID,
29+
JSONB
30+
)
1931

2032
pk_uuid = Annotated[
2133
UUID,
@@ -73,6 +85,24 @@
7385
),
7486
]
7587

88+
timestamp_auto = Annotated[
89+
datetime,
90+
mapped_column(
91+
DateTime(timezone=True),
92+
nullable=False,
93+
server_default=func.now(),
94+
onupdate=func.now()
95+
),
96+
]
97+
98+
jsonb = Annotated[
99+
dict|list,
100+
mapped_column(
101+
JSONB,
102+
nullable=True,
103+
),
104+
]
105+
76106

77107
class IdentifierMixin(object):
78108
"""An ID for a given object
@@ -95,7 +125,7 @@ class DateTimeMixin(object):
95125
values manually.
96126
"""
97127
created_at: Mapped[timestamp_req]
98-
updated_at: Mapped[timestamp_req]
128+
updated_at: Mapped[timestamp_auto]
99129
deleted_at: Mapped[timestamp]
100130

101131

@@ -141,14 +171,11 @@ async def create(
141171
await async_db_session.refresh(new_instance) # Ensure we get the id
142172

143173
# This will trigger using the _base_get_query to load any
144-
# relationships we need. The if statement is to ensure that tables
145-
# like join tables do not always have an id field.
146-
updated_instance = new_instance
147-
if hasattr(cls, "id"):
148-
updated_instance = await cls.get(
149-
async_db_session,
150-
new_instance.id
151-
)
174+
# relationships we need.
175+
updated_instance = await cls.get(
176+
async_db_session,
177+
new_instance.id
178+
)
152179

153180
return updated_instance
154181

@@ -231,7 +258,7 @@ def _base_get_query(cls):
231258
async def get(
232259
cls,
233260
async_db_session,
234-
id
261+
id: [UUID, str]
235262
):
236263
""" Get a single record from the database by ID
237264

0 commit comments

Comments
 (0)