activemodel 0.7.0__py3-none-any.whl → 0.9.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- activemodel/base_model.py +113 -8
- activemodel/celery.py +6 -1
- activemodel/get_column_from_field_patch.py +2 -0
- activemodel/mixins/pydantic_json.py +24 -6
- activemodel/pytest/transaction.py +34 -22
- activemodel/session_manager.py +18 -1
- activemodel/types/typeid.py +1 -2
- {activemodel-0.7.0.dist-info → activemodel-0.9.0.dist-info}/METADATA +51 -4
- {activemodel-0.7.0.dist-info → activemodel-0.9.0.dist-info}/RECORD +12 -12
- {activemodel-0.7.0.dist-info → activemodel-0.9.0.dist-info}/WHEEL +0 -0
- {activemodel-0.7.0.dist-info → activemodel-0.9.0.dist-info}/entry_points.txt +0 -0
- {activemodel-0.7.0.dist-info → activemodel-0.9.0.dist-info}/licenses/LICENSE +0 -0
activemodel/base_model.py
CHANGED
|
@@ -4,12 +4,16 @@ from uuid import UUID
|
|
|
4
4
|
|
|
5
5
|
import pydash
|
|
6
6
|
import sqlalchemy as sa
|
|
7
|
+
from sqlalchemy.orm.attributes import flag_modified as sa_flag_modified
|
|
8
|
+
from sqlalchemy.orm.base import instance_state
|
|
7
9
|
import sqlmodel as sm
|
|
8
10
|
from sqlalchemy import Connection, event
|
|
9
11
|
from sqlalchemy.orm import Mapper, declared_attr
|
|
10
|
-
from sqlmodel import
|
|
12
|
+
from sqlmodel import Column, Field, Session, SQLModel, inspect, select
|
|
11
13
|
from typeid import TypeID
|
|
12
14
|
|
|
15
|
+
from activemodel.mixins.pydantic_json import PydanticJSONMixin
|
|
16
|
+
|
|
13
17
|
# NOTE: this patches a core method in sqlmodel to support db comments
|
|
14
18
|
from . import get_column_from_field_patch # noqa: F401
|
|
15
19
|
from .logger import logger
|
|
@@ -157,7 +161,10 @@ class BaseModel(SQLModel):
|
|
|
157
161
|
@classmethod
|
|
158
162
|
def foreign_key(cls, **kwargs):
|
|
159
163
|
"""
|
|
160
|
-
Returns a Field object referencing the foreign key of the model.
|
|
164
|
+
Returns a `Field` object referencing the foreign key of the model.
|
|
165
|
+
|
|
166
|
+
>>> other_model_id: int
|
|
167
|
+
>>> other_model = OtherModel.foreign_key()
|
|
161
168
|
"""
|
|
162
169
|
|
|
163
170
|
field_options = {"nullable": False} | kwargs
|
|
@@ -174,6 +181,11 @@ class BaseModel(SQLModel):
|
|
|
174
181
|
"create a query wrapper to easily run sqlmodel queries on this model"
|
|
175
182
|
return QueryWrapper[cls](cls, *args)
|
|
176
183
|
|
|
184
|
+
@classmethod
|
|
185
|
+
def where(cls, *args):
|
|
186
|
+
"convenience method to avoid having to write .select().where() in order to add conditions"
|
|
187
|
+
return cls.select().where(*args)
|
|
188
|
+
|
|
177
189
|
def delete(self):
|
|
178
190
|
with get_session() as session:
|
|
179
191
|
if old_session := Session.object_session(self):
|
|
@@ -197,13 +209,32 @@ class BaseModel(SQLModel):
|
|
|
197
209
|
session.commit()
|
|
198
210
|
session.refresh(self)
|
|
199
211
|
|
|
212
|
+
# Only call the transform method if the class is a subclass of PydanticJSONMixin
|
|
213
|
+
if issubclass(self.__class__, PydanticJSONMixin):
|
|
214
|
+
self.__class__.__transform_dict_to_pydantic__(self)
|
|
215
|
+
|
|
200
216
|
return self
|
|
201
217
|
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
218
|
+
def refresh(self):
|
|
219
|
+
"Refreshes an object from the database"
|
|
220
|
+
|
|
221
|
+
with get_session() as session:
|
|
222
|
+
if (
|
|
223
|
+
old_session := Session.object_session(self)
|
|
224
|
+
) and old_session is not session:
|
|
225
|
+
old_session.expunge(self)
|
|
226
|
+
|
|
227
|
+
session.add(self)
|
|
228
|
+
session.refresh(self)
|
|
229
|
+
|
|
230
|
+
# Only call the transform method if the class is a subclass of PydanticJSONMixin
|
|
231
|
+
if issubclass(self.__class__, PydanticJSONMixin):
|
|
232
|
+
self.__class__.__transform_dict_to_pydantic__(self)
|
|
233
|
+
|
|
234
|
+
return self
|
|
205
235
|
|
|
206
236
|
# TODO shouldn't this be handled by pydantic?
|
|
237
|
+
# TODO where is this actually used? shoudl prob remove this
|
|
207
238
|
def json(self, **kwargs):
|
|
208
239
|
return json.dumps(self.dict(), default=str, **kwargs)
|
|
209
240
|
|
|
@@ -225,6 +256,29 @@ class BaseModel(SQLModel):
|
|
|
225
256
|
def is_new(self) -> bool:
|
|
226
257
|
return not self._sa_instance_state.has_identity
|
|
227
258
|
|
|
259
|
+
def flag_modified(self, *args: str):
|
|
260
|
+
"""
|
|
261
|
+
Flag one or more fields as modified. Useful for marking a field containing sub-objects as modified.
|
|
262
|
+
|
|
263
|
+
Will throw an error if an invalid field is passed.
|
|
264
|
+
"""
|
|
265
|
+
|
|
266
|
+
assert len(args) > 0, "Must pass at least one field name"
|
|
267
|
+
|
|
268
|
+
for field_name in args:
|
|
269
|
+
if field_name not in self.__fields__:
|
|
270
|
+
raise ValueError(f"Field '{field_name}' does not exist in the model.")
|
|
271
|
+
|
|
272
|
+
# check if the field exists
|
|
273
|
+
sa_flag_modified(self, field_name)
|
|
274
|
+
|
|
275
|
+
def modified_fields(self) -> set[str]:
|
|
276
|
+
"set of fields that are modified"
|
|
277
|
+
|
|
278
|
+
insp = inspect(self)
|
|
279
|
+
|
|
280
|
+
return {attr.key for attr in insp.attrs if attr.history.has_changes()}
|
|
281
|
+
|
|
228
282
|
@classmethod
|
|
229
283
|
def find_or_create_by(cls, **kwargs):
|
|
230
284
|
"""
|
|
@@ -256,6 +310,29 @@ class BaseModel(SQLModel):
|
|
|
256
310
|
new_model = cls(**kwargs)
|
|
257
311
|
return new_model
|
|
258
312
|
|
|
313
|
+
@classmethod
|
|
314
|
+
def primary_key_column(cls) -> Column:
|
|
315
|
+
"""
|
|
316
|
+
Returns the primary key column of the model by inspecting SQLAlchemy field information.
|
|
317
|
+
|
|
318
|
+
>>> ExampleModel.primary_key_field().name
|
|
319
|
+
"""
|
|
320
|
+
|
|
321
|
+
# TODO note_schema.__class__.__table__.primary_key
|
|
322
|
+
# TODO no reason why this couldn't be cached
|
|
323
|
+
|
|
324
|
+
pk_columns = list(cls.__table__.primary_key.columns)
|
|
325
|
+
|
|
326
|
+
if not pk_columns:
|
|
327
|
+
raise ValueError("No primary key defined for the model.")
|
|
328
|
+
|
|
329
|
+
if len(pk_columns) > 1:
|
|
330
|
+
raise ValueError(
|
|
331
|
+
"Multiple primary keys defined. This method supports only single primary key models."
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
return pk_columns[0]
|
|
335
|
+
|
|
259
336
|
# TODO what's super dangerous here is you pass a kwarg which does not map to a specific
|
|
260
337
|
# field it will result in `True`, which will return all records, and not give you any typing
|
|
261
338
|
# errors. Dangerous when iterating on structure quickly
|
|
@@ -265,9 +342,8 @@ class BaseModel(SQLModel):
|
|
|
265
342
|
@classmethod
|
|
266
343
|
def get(cls, *args: t.Any, **kwargs: t.Any):
|
|
267
344
|
"""
|
|
268
|
-
Gets a single record from the database. Pass an PK ID or
|
|
345
|
+
Gets a single record (or None) from the database. Pass an PK ID or kwargs to filter by.
|
|
269
346
|
"""
|
|
270
|
-
|
|
271
347
|
# TODO id is hardcoded, not good! Need to dynamically pick the best uid field
|
|
272
348
|
id_field_name = "id"
|
|
273
349
|
|
|
@@ -281,8 +357,37 @@ class BaseModel(SQLModel):
|
|
|
281
357
|
with get_session() as session:
|
|
282
358
|
return session.exec(statement).first()
|
|
283
359
|
|
|
360
|
+
@classmethod
|
|
361
|
+
def one(cls, *args: t.Any, **kwargs: t.Any):
|
|
362
|
+
"""
|
|
363
|
+
Gets a single record from the database. Pass an PK ID or a kwarg to filter by.
|
|
364
|
+
"""
|
|
365
|
+
|
|
366
|
+
args, kwargs = cls.__process_filter_args__(*args, **kwargs)
|
|
367
|
+
statement = select(cls).filter(*args).filter_by(**kwargs)
|
|
368
|
+
|
|
369
|
+
with get_session() as session:
|
|
370
|
+
return session.exec(statement).one()
|
|
371
|
+
|
|
372
|
+
@classmethod
|
|
373
|
+
def __process_filter_args__(cls, *args: t.Any, **kwargs: t.Any):
|
|
374
|
+
"""
|
|
375
|
+
Helper method to process filter arguments and implement some nice DX for our devs.
|
|
376
|
+
"""
|
|
377
|
+
|
|
378
|
+
id_field_name = cls.primary_key_column().name
|
|
379
|
+
|
|
380
|
+
# special case for getting by ID without having to specify the field name
|
|
381
|
+
# TODO should dynamically add new pk types based on column definition
|
|
382
|
+
if len(args) == 1 and isinstance(args[0], (int, TypeID, str, UUID)):
|
|
383
|
+
kwargs[id_field_name] = args[0]
|
|
384
|
+
args = ()
|
|
385
|
+
|
|
386
|
+
return args, kwargs
|
|
387
|
+
|
|
284
388
|
@classmethod
|
|
285
389
|
def all(cls):
|
|
390
|
+
"get a generator for all records in the database"
|
|
286
391
|
with get_session() as session:
|
|
287
392
|
results = session.exec(sm.select(cls))
|
|
288
393
|
|
|
@@ -293,7 +398,7 @@ class BaseModel(SQLModel):
|
|
|
293
398
|
@classmethod
|
|
294
399
|
def sample(cls):
|
|
295
400
|
"""
|
|
296
|
-
Pick a random record from the database.
|
|
401
|
+
Pick a random record from the database. Raises if none exist.
|
|
297
402
|
|
|
298
403
|
Helpful for testing and console debugging.
|
|
299
404
|
"""
|
activemodel/celery.py
CHANGED
|
@@ -4,12 +4,17 @@ Do not import unless you have Celery/Kombu installed.
|
|
|
4
4
|
In order for TypeID objects to be properly handled by celery, a custom encoder must be registered.
|
|
5
5
|
"""
|
|
6
6
|
|
|
7
|
+
# this is not an explicit dependency, only import this file if you have Celery installed
|
|
7
8
|
from kombu.utils.json import register_type
|
|
8
9
|
from typeid import TypeID
|
|
9
10
|
|
|
10
11
|
|
|
11
12
|
def register_celery_typeid_encoder():
|
|
12
|
-
"
|
|
13
|
+
"""
|
|
14
|
+
Ensures TypeID objects passed as arguments to a delayed function are properly serialized.
|
|
15
|
+
|
|
16
|
+
Run at the top of your celery initialization script.
|
|
17
|
+
"""
|
|
13
18
|
|
|
14
19
|
def class_full_name(clz) -> str:
|
|
15
20
|
return ".".join([clz.__module__, clz.__qualname__])
|
|
@@ -6,6 +6,8 @@ Making sure these docstrings make their way to the DB schema is helpful for a bu
|
|
|
6
6
|
This patch mutates a core sqlmodel function which translates pydantic FieldInfo objects into sqlalchemy Column objects. It adds the field description as a comment to the column.
|
|
7
7
|
|
|
8
8
|
Note that FieldInfo *from pydantic* is used when a "bare" field is defined. This can be confusing, because when inspecting model fields, the class name looks exactly the same.
|
|
9
|
+
|
|
10
|
+
Some ideas for this originally sourced from: https://github.com/fastapi/sqlmodel/issues/492#issuecomment-2489858633
|
|
9
11
|
"""
|
|
10
12
|
|
|
11
13
|
from typing import (
|
|
@@ -1,19 +1,38 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Need to store nested Pydantic models in PostgreSQL using FastAPI and SQLModel.
|
|
3
|
+
|
|
4
|
+
SQLModel lacks a direct JSONField equivalent (like Tortoise ORM's JSONField), making it tricky to handle nested model data as JSON in the DB.
|
|
5
|
+
|
|
6
|
+
Extensive discussion on the problem: https://github.com/fastapi/sqlmodel/issues/63
|
|
7
|
+
"""
|
|
8
|
+
|
|
1
9
|
from types import UnionType
|
|
2
10
|
from typing import get_args, get_origin
|
|
3
11
|
|
|
4
12
|
from pydantic import BaseModel as PydanticBaseModel
|
|
5
|
-
from sqlalchemy.orm import reconstructor
|
|
13
|
+
from sqlalchemy.orm import reconstructor, attributes
|
|
6
14
|
|
|
7
15
|
|
|
8
16
|
class PydanticJSONMixin:
|
|
9
17
|
"""
|
|
10
18
|
By default, SQLModel does not convert JSONB columns into pydantic models when they are loaded from the database.
|
|
11
19
|
|
|
12
|
-
This mixin, combined with a custom serializer, fixes that issue.
|
|
20
|
+
This mixin, combined with a custom serializer (`_serialize_pydantic_model`), fixes that issue.
|
|
21
|
+
|
|
22
|
+
>>> class ExampleWithJSON(BaseModel, PydanticJSONMixin, table=True):
|
|
23
|
+
>>> list_field: list[SubObject] = Field(sa_type=JSONB()
|
|
13
24
|
"""
|
|
14
25
|
|
|
15
26
|
@reconstructor
|
|
16
|
-
def
|
|
27
|
+
def __transform_dict_to_pydantic__(self):
|
|
28
|
+
"""
|
|
29
|
+
Transforms dictionary fields into Pydantic models upon loading.
|
|
30
|
+
|
|
31
|
+
- Reconstructor only runs once, when the object is loaded.
|
|
32
|
+
- We manually call this method on save(), etc to ensure the pydantic types are maintained
|
|
33
|
+
- `set_committed_value` sets Pydantic models as committed, avoiding `setattr` marking fields as modified
|
|
34
|
+
after loading from the database.
|
|
35
|
+
"""
|
|
17
36
|
# TODO do we need to inspect sa_type
|
|
18
37
|
for field_name, field_info in self.model_fields.items():
|
|
19
38
|
raw_value = getattr(self, field_name, None)
|
|
@@ -60,10 +79,9 @@ class PydanticJSONMixin:
|
|
|
60
79
|
model_cls, PydanticBaseModel
|
|
61
80
|
):
|
|
62
81
|
parsed_value = [model_cls(**item) for item in raw_value]
|
|
63
|
-
|
|
64
|
-
|
|
82
|
+
attributes.set_committed_value(self, field_name, parsed_value)
|
|
65
83
|
continue
|
|
66
84
|
|
|
67
85
|
# single class
|
|
68
86
|
if issubclass(model_cls, PydanticBaseModel):
|
|
69
|
-
|
|
87
|
+
attributes.set_committed_value(self, field_name, model_cls(**raw_value))
|
|
@@ -1,12 +1,19 @@
|
|
|
1
1
|
from activemodel import SessionManager
|
|
2
2
|
|
|
3
|
+
from ..logger import logger
|
|
4
|
+
|
|
3
5
|
|
|
4
6
|
def database_reset_transaction():
|
|
5
7
|
"""
|
|
6
8
|
Wrap all database interactions for a given test in a nested transaction and roll it back after the test.
|
|
7
9
|
|
|
8
10
|
>>> from activemodel.pytest import database_reset_transaction
|
|
9
|
-
>>> pytest.fixture(scope="function", autouse=True)(database_reset_transaction)
|
|
11
|
+
>>> database_reset_transaction = pytest.fixture(scope="function", autouse=True)(database_reset_transaction)
|
|
12
|
+
|
|
13
|
+
Transaction-based DB cleaning does *not* work if the DB mutations are happening in a separate process, which should
|
|
14
|
+
use spawn, because the same session is not shared across processes. Note that using `fork` is dangerous.
|
|
15
|
+
|
|
16
|
+
In this case, you should use the truncate.
|
|
10
17
|
|
|
11
18
|
References:
|
|
12
19
|
|
|
@@ -14,38 +21,43 @@ def database_reset_transaction():
|
|
|
14
21
|
- https://aalvarez.me/posts/setting-up-a-sqlalchemy-and-pytest-based-test-suite/
|
|
15
22
|
- https://github.com/nickjj/docker-flask-example/blob/93af9f4fbf185098ffb1d120ee0693abcd77a38b/test/conftest.py#L77
|
|
16
23
|
- https://github.com/caiola/vinhos.com/blob/c47d0a5d7a4bf290c1b726561d1e8f5d2ac29bc8/backend/test/conftest.py#L46
|
|
24
|
+
- https://stackoverflow.com/questions/64095876/multiprocessing-fork-vs-spawn
|
|
25
|
+
|
|
26
|
+
Using a named SAVEPOINT does not give us anything extra, so we are not using it.
|
|
17
27
|
"""
|
|
18
28
|
|
|
19
29
|
engine = SessionManager.get_instance().get_engine()
|
|
20
30
|
|
|
31
|
+
logger.info("starting global database transaction")
|
|
32
|
+
|
|
21
33
|
with engine.begin() as connection:
|
|
22
34
|
transaction = connection.begin_nested()
|
|
23
35
|
|
|
36
|
+
if SessionManager.get_instance().session_connection is not None:
|
|
37
|
+
logger.warning("session override already exists")
|
|
38
|
+
# TODO should we throw an exception here?
|
|
39
|
+
|
|
24
40
|
SessionManager.get_instance().session_connection = connection
|
|
25
41
|
|
|
26
42
|
try:
|
|
27
|
-
|
|
43
|
+
with SessionManager.get_instance().get_session() as factory_session:
|
|
44
|
+
try:
|
|
45
|
+
from factory.alchemy import SQLAlchemyModelFactory
|
|
46
|
+
|
|
47
|
+
# Ensure that all factories use the same session
|
|
48
|
+
for factory in SQLAlchemyModelFactory.__subclasses__():
|
|
49
|
+
factory._meta.sqlalchemy_session = factory_session
|
|
50
|
+
factory._meta.sqlalchemy_session_persistence = "commit"
|
|
51
|
+
except ImportError:
|
|
52
|
+
pass
|
|
53
|
+
|
|
54
|
+
yield
|
|
28
55
|
finally:
|
|
29
|
-
|
|
30
|
-
# TODO is this necessary?
|
|
31
|
-
connection.close()
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
# TODO unsure if this adds any value beyond the above approach
|
|
35
|
-
# def database_reset_named_truncation():
|
|
36
|
-
# start_truncation_query = """
|
|
37
|
-
# BEGIN;
|
|
38
|
-
# SAVEPOINT test_truncation_savepoint;
|
|
39
|
-
# """
|
|
56
|
+
logger.debug("rolling back transaction")
|
|
40
57
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
# yield
|
|
58
|
+
transaction.rollback()
|
|
44
59
|
|
|
45
|
-
#
|
|
46
|
-
|
|
47
|
-
# RELEASE SAVEPOINT test_truncation_savepoint;
|
|
48
|
-
# ROLLBACK;
|
|
49
|
-
# """
|
|
60
|
+
# TODO is this necessary? unclear
|
|
61
|
+
connection.close()
|
|
50
62
|
|
|
51
|
-
|
|
63
|
+
SessionManager.get_instance().session_connection = None
|
activemodel/session_manager.py
CHANGED
|
@@ -44,6 +44,7 @@ def _serialize_pydantic_model(model: BaseModel | list[BaseModel] | None) -> str
|
|
|
44
44
|
|
|
45
45
|
class SessionManager:
|
|
46
46
|
_instance: t.ClassVar[t.Optional["SessionManager"]] = None
|
|
47
|
+
"singleton instance of SessionManager"
|
|
47
48
|
|
|
48
49
|
session_connection: Connection | None
|
|
49
50
|
"optionally specify a specific session connection to use for all get_session() calls, useful for testing"
|
|
@@ -69,6 +70,7 @@ class SessionManager:
|
|
|
69
70
|
if not self._engine:
|
|
70
71
|
self._engine = create_engine(
|
|
71
72
|
self._database_url,
|
|
73
|
+
# NOTE very important! This enables pydantic models to be serialized for JSONB columns
|
|
72
74
|
json_serializer=_serialize_pydantic_model,
|
|
73
75
|
echo=config("ACTIVEMODEL_LOG_SQL", cast=bool, default=False),
|
|
74
76
|
# https://docs.sqlalchemy.org/en/20/core/pooling.html#disconnect-handling-pessimistic
|
|
@@ -87,6 +89,7 @@ class SessionManager:
|
|
|
87
89
|
|
|
88
90
|
return _reuse_session()
|
|
89
91
|
|
|
92
|
+
# a connection can generate nested transactions
|
|
90
93
|
if self.session_connection:
|
|
91
94
|
return Session(bind=self.session_connection)
|
|
92
95
|
|
|
@@ -94,6 +97,7 @@ class SessionManager:
|
|
|
94
97
|
|
|
95
98
|
|
|
96
99
|
def init(database_url: str):
|
|
100
|
+
"configure activemodel to connect to a specific database"
|
|
97
101
|
return SessionManager.get_instance(database_url)
|
|
98
102
|
|
|
99
103
|
|
|
@@ -106,6 +110,8 @@ def get_session():
|
|
|
106
110
|
|
|
107
111
|
|
|
108
112
|
# contextvars must be at the top-level of a module! You will not get a warning if you don't do this.
|
|
113
|
+
# ContextVar is implemented in C, so it's very special and is both thread-safe and asyncio safe. This variable gives us
|
|
114
|
+
# a place to persist a session to use globally across the application.
|
|
109
115
|
_session_context = contextvars.ContextVar[Session | None](
|
|
110
116
|
"session_context", default=None
|
|
111
117
|
)
|
|
@@ -117,12 +123,23 @@ def global_session():
|
|
|
117
123
|
token = _session_context.set(s)
|
|
118
124
|
|
|
119
125
|
try:
|
|
120
|
-
yield
|
|
126
|
+
yield s
|
|
121
127
|
finally:
|
|
122
128
|
_session_context.reset(token)
|
|
123
129
|
|
|
124
130
|
|
|
125
131
|
async def aglobal_session():
|
|
132
|
+
"""
|
|
133
|
+
Use this as a fastapi dependency to get a session that is shared across the request:
|
|
134
|
+
|
|
135
|
+
>>> APIRouter(
|
|
136
|
+
>>> prefix="/internal/v1",
|
|
137
|
+
>>> dependencies=[
|
|
138
|
+
>>> Depends(aglobal_session),
|
|
139
|
+
>>> ]
|
|
140
|
+
>>> )
|
|
141
|
+
"""
|
|
142
|
+
|
|
126
143
|
with SessionManager.get_instance().get_session() as s:
|
|
127
144
|
token = _session_context.set(s)
|
|
128
145
|
|
activemodel/types/typeid.py
CHANGED
|
@@ -137,6 +137,7 @@ class TypeIDType(types.TypeDecorator):
|
|
|
137
137
|
|
|
138
138
|
return core_schema.json_or_python_schema(
|
|
139
139
|
json_schema=from_uuid_schema,
|
|
140
|
+
# TODO in the the future we could add more exact types
|
|
140
141
|
# metadata=core_schema.str_schema(
|
|
141
142
|
# pattern="^[0-9a-f]{24}$",
|
|
142
143
|
# min_length=24,
|
|
@@ -187,5 +188,3 @@ class TypeIDType(types.TypeDecorator):
|
|
|
187
188
|
# "minLength": 24,
|
|
188
189
|
# "maxLength": 24,
|
|
189
190
|
}
|
|
190
|
-
|
|
191
|
-
return core_schema.uuid_schema()
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: activemodel
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.9.0
|
|
4
4
|
Summary: Make SQLModel more like an a real ORM
|
|
5
5
|
Project-URL: Repository, https://github.com/iloveitaly/activemodel
|
|
6
6
|
Author-email: Michael Bianco <iloveitaly@gmail.com>
|
|
@@ -29,10 +29,11 @@ This package provides a thin wrapper around SQLModel that provides a more Active
|
|
|
29
29
|
First, setup your DB:
|
|
30
30
|
|
|
31
31
|
```python
|
|
32
|
-
|
|
32
|
+
import activemodel
|
|
33
|
+
activemodel.init("sqlite:///database.db")
|
|
33
34
|
```
|
|
34
35
|
|
|
35
|
-
|
|
36
|
+
Create models:
|
|
36
37
|
|
|
37
38
|
```python
|
|
38
39
|
from activemodel import BaseModel
|
|
@@ -51,6 +52,38 @@ class User(
|
|
|
51
52
|
a_field: str
|
|
52
53
|
```
|
|
53
54
|
|
|
55
|
+
You'll need to create the models in the DB. Alembic is the best way to do it, but you can cheat as well:
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from sqlmodel import SQLModel
|
|
59
|
+
|
|
60
|
+
SQLModel.metadata.create_all(get_engine())
|
|
61
|
+
|
|
62
|
+
# now you can create a user!
|
|
63
|
+
User(a_field="a").save()
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Maybe you like JSON:
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
from activemodel import BaseModel
|
|
70
|
+
from pydantic import BaseModel as PydanticBaseModel
|
|
71
|
+
from activemodel.mixins import PydanticJSONMixin, TypeIDMixin, TimestampsMixin
|
|
72
|
+
|
|
73
|
+
class SubObject(PydanticBaseModel):
|
|
74
|
+
name: str
|
|
75
|
+
value: int
|
|
76
|
+
|
|
77
|
+
class User(
|
|
78
|
+
BaseModel,
|
|
79
|
+
TimestampsMixin,
|
|
80
|
+
PydanticJSONMixin,
|
|
81
|
+
TypeIDMixin("user"),
|
|
82
|
+
table=True
|
|
83
|
+
):
|
|
84
|
+
list_field: list[SubObject] = Field(sa_type=JSONB())
|
|
85
|
+
```
|
|
86
|
+
|
|
54
87
|
## Usage
|
|
55
88
|
|
|
56
89
|
### Integrating Alembic
|
|
@@ -60,6 +93,7 @@ class User(
|
|
|
60
93
|
* To import all of your models you want in your DB. [Here's my recommended way to do this.](https://github.com/iloveitaly/python-starter-template/blob/master/app/models/__init__.py)
|
|
61
94
|
* Use your DB URL from the ENV
|
|
62
95
|
* Target sqlalchemy metadata to the sqlmodel-generated metadata
|
|
96
|
+
* Most likely you'll want to add [alembic-postgresql-enum](https://pypi.org/project/alembic-postgresql-enum/) so migrations work properly
|
|
63
97
|
|
|
64
98
|
[Take a look at these scripts for an example of how to fully integrate Alembic into your development workflow.](https://github.com/iloveitaly/python-starter-template/blob/0af2c7e95217e34bde7357cc95be048900000e48/Justfile#L618-L712)
|
|
65
99
|
|
|
@@ -161,6 +195,15 @@ https://github.com/tomwojcik/starlette-context
|
|
|
161
195
|
* Conditional: `Scrape.select().where(Scrape.id < last_scraped.id).all()`
|
|
162
196
|
* Equality: `MenuItem.select().where(MenuItem.menu_id == menu.id).all()`
|
|
163
197
|
* `IN` example: `CanonicalMenuItem.select().where(col(CanonicalMenuItem.id).in_(canonized_ids)).all()`
|
|
198
|
+
* Compound where query: `User.where((User.last_active_at != None) & (User.last_active_at > last_24_hours)).count()`
|
|
199
|
+
|
|
200
|
+
### SQLModel Internals
|
|
201
|
+
|
|
202
|
+
SQLModel & SQLAlchemy are tricky. Here are some useful internal tricks:
|
|
203
|
+
|
|
204
|
+
* `__sqlmodel_relationships__` is where any `RelationshipInfo` objects are stored. This is used to generate relationship fields on the object.
|
|
205
|
+
* `ModelClass.relationship_name.property.local_columns`
|
|
206
|
+
* Get cached fields from a model `object_state(instance).dict.get(field_name)`
|
|
164
207
|
|
|
165
208
|
### TypeID
|
|
166
209
|
|
|
@@ -186,7 +229,7 @@ class Appointment(
|
|
|
186
229
|
TypeIDMixin("appointment"),
|
|
187
230
|
table=True
|
|
188
231
|
):
|
|
189
|
-
# `foreign_key` is a activemodel
|
|
232
|
+
# `foreign_key` is a activemodel method to generate the right `Field` for the relationship
|
|
190
233
|
# TypeIDType is really important here for fastapi serialization
|
|
191
234
|
doctor_id: TypeIDType = Doctor.foreign_key()
|
|
192
235
|
doctor: Doctor = Relationship()
|
|
@@ -233,3 +276,7 @@ https://github.com/DarylStark/my_data/blob/a17b8b3a8463b9953821b89fee895e272f94d
|
|
|
233
276
|
* https://github.com/fastapi/full-stack-fastapi-template
|
|
234
277
|
* https://github.com/DarylStark/my_data/
|
|
235
278
|
* https://github.com/petrgazarov/FastAPI-app/tree/main/fastapi_app
|
|
279
|
+
|
|
280
|
+
## Upstream Changes
|
|
281
|
+
|
|
282
|
+
- [ ] https://github.com/fastapi/sqlmodel/pull/1293
|
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
activemodel/__init__.py,sha256=q_lHQyIM70ApvjduTo9GtenQjJXsfYZsAAquD_51kF4,137
|
|
2
|
-
activemodel/base_model.py,sha256=
|
|
3
|
-
activemodel/celery.py,sha256=
|
|
2
|
+
activemodel/base_model.py,sha256=Xn5RCN-tAmGGkhaH8gnT2PFIkbefeSv85bPP41cJp14,14715
|
|
3
|
+
activemodel/celery.py,sha256=L1vKcO_HoPA5ZCfsXjxgPpDUMYDuoQMakGA9rppN7Lo,897
|
|
4
4
|
activemodel/errors.py,sha256=wycWYmk9ws4TZpxvTdtXVy2SFESb8NqKgzdivBoF0vw,115
|
|
5
|
-
activemodel/get_column_from_field_patch.py,sha256=
|
|
5
|
+
activemodel/get_column_from_field_patch.py,sha256=wAEDm_ZvSqyJwfgkXVpxsevw11hd-7VLy7zuJG8Ak7Y,4986
|
|
6
6
|
activemodel/logger.py,sha256=vU7QiGSy_AJuJFmClUocqIJ-Ltku_8C24ZU8L6fLJR0,53
|
|
7
7
|
activemodel/query_wrapper.py,sha256=rNdvueppMse2MIi-RafTEC34GPGRal_wqH2CzhmlWS8,2520
|
|
8
|
-
activemodel/session_manager.py,sha256=
|
|
8
|
+
activemodel/session_manager.py,sha256=Vtg8Lf8vUNPegdRW-fyE-Ng5wtN3hTMfUezdFUiJ1fs,4585
|
|
9
9
|
activemodel/utils.py,sha256=g17UqkphzTmb6YdpmYwT1TM00eDiXXuWn39-xNiu0AA,2112
|
|
10
10
|
activemodel/mixins/__init__.py,sha256=05EQl2u_Wgf_wkly-GTaTsR7zWpmpKcb96Js7r_rZTw,160
|
|
11
|
-
activemodel/mixins/pydantic_json.py,sha256=
|
|
11
|
+
activemodel/mixins/pydantic_json.py,sha256=0pprGZA95BGZL4WOh--NJcvxLWey4YW85lLk4GGTjFM,3530
|
|
12
12
|
activemodel/mixins/soft_delete.py,sha256=Ax4mGsQI7AVTE8c4GiWxpyB_W179-dDct79GtjP0owU,461
|
|
13
13
|
activemodel/mixins/timestamps.py,sha256=Q-IFljeVVJQqw3XHdOi7dkqzefiVg1zhJvq_bldpmjg,992
|
|
14
14
|
activemodel/mixins/typeid.py,sha256=DGjlIg8PRBYoaBbWkkxc6jkScyl-p53KuSR98lLgAvE,1284
|
|
15
15
|
activemodel/pytest/__init__.py,sha256=W9KKQHbPkyq0jrMXaiL8hG2Nsbjy_LN9HhvgGm8W_7g,98
|
|
16
|
-
activemodel/pytest/transaction.py,sha256=
|
|
16
|
+
activemodel/pytest/transaction.py,sha256=ln-3N5tXHT0fqy6a8m_NIYg5AXAeA2hDuftQtFxNqi4,2600
|
|
17
17
|
activemodel/pytest/truncate.py,sha256=IGiPLkUm2yyOKww6c6CKcVbwi2xAAFBopx9q2ABfu8w,1582
|
|
18
18
|
activemodel/types/__init__.py,sha256=y5fiGVtPJxGEhuf-TvyrkhM2yaKRcIWo6XAx-CFFjM8,31
|
|
19
|
-
activemodel/types/typeid.py,sha256=
|
|
20
|
-
activemodel-0.
|
|
21
|
-
activemodel-0.
|
|
22
|
-
activemodel-0.
|
|
23
|
-
activemodel-0.
|
|
24
|
-
activemodel-0.
|
|
19
|
+
activemodel/types/typeid.py,sha256=1xB79DGIC5-P-PcLpeZW9Ed_WjFOmmVW1yl2Q3pPJis,7250
|
|
20
|
+
activemodel-0.9.0.dist-info/METADATA,sha256=AWt9ERLLgE1X1aQvJSuPwDTBmqoH9EW2_zglUlJVfPY,9651
|
|
21
|
+
activemodel-0.9.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
22
|
+
activemodel-0.9.0.dist-info/entry_points.txt,sha256=YLX62TP_hR-n3HMBkdBex4W7XRiyOtIPkwy22puIjjQ,61
|
|
23
|
+
activemodel-0.9.0.dist-info/licenses/LICENSE,sha256=L8mmpX47rB-xtJ_HsK0zpfO6viEjxbLYGn70BMp8os4,1071
|
|
24
|
+
activemodel-0.9.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|