activemodel 0.7.0__py3-none-any.whl → 0.8.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 CHANGED
@@ -9,6 +9,9 @@ from sqlalchemy import Connection, event
9
9
  from sqlalchemy.orm import Mapper, declared_attr
10
10
  from sqlmodel import Field, MetaData, Session, SQLModel, select
11
11
  from typeid import TypeID
12
+ from inspect import isclass
13
+
14
+ from activemodel.mixins.pydantic_json import PydanticJSONMixin
12
15
 
13
16
  # NOTE: this patches a core method in sqlmodel to support db comments
14
17
  from . import get_column_from_field_patch # noqa: F401
@@ -157,7 +160,10 @@ class BaseModel(SQLModel):
157
160
  @classmethod
158
161
  def foreign_key(cls, **kwargs):
159
162
  """
160
- Returns a Field object referencing the foreign key of the model.
163
+ Returns a `Field` object referencing the foreign key of the model.
164
+
165
+ >>> other_model_id: int
166
+ >>> other_model = OtherModel.foreign_key()
161
167
  """
162
168
 
163
169
  field_options = {"nullable": False} | kwargs
@@ -174,6 +180,11 @@ class BaseModel(SQLModel):
174
180
  "create a query wrapper to easily run sqlmodel queries on this model"
175
181
  return QueryWrapper[cls](cls, *args)
176
182
 
183
+ @classmethod
184
+ def where(cls, *args):
185
+ "convenience method to avoid having to write .select().where() in order to add conditions"
186
+ return cls.select().where(*args)
187
+
177
188
  def delete(self):
178
189
  with get_session() as session:
179
190
  if old_session := Session.object_session(self):
@@ -197,11 +208,11 @@ class BaseModel(SQLModel):
197
208
  session.commit()
198
209
  session.refresh(self)
199
210
 
200
- return self
211
+ # Only call the transform method if the class is a subclass of PydanticJSONMixin
212
+ if issubclass(self.__class__, PydanticJSONMixin):
213
+ self.__class__.__transform_dict_to_pydantic__(self)
201
214
 
202
- # except IntegrityError:
203
- # log.quiet(f"{self} already exists in the database.")
204
- # session.rollback()
215
+ return self
205
216
 
206
217
  # TODO shouldn't this be handled by pydantic?
207
218
  def json(self, **kwargs):
@@ -256,6 +267,27 @@ class BaseModel(SQLModel):
256
267
  new_model = cls(**kwargs)
257
268
  return new_model
258
269
 
270
+ @classmethod
271
+ def primary_key_field(cls):
272
+ """
273
+ Returns the primary key column of the model by inspecting SQLAlchemy field information.
274
+
275
+ >>> ExampleModel.primary_key_field().name
276
+ """
277
+ # TODO note_schema.__class__.__table__.primary_key
278
+
279
+ pk_columns = list(cls.__table__.primary_key.columns)
280
+
281
+ if not pk_columns:
282
+ raise ValueError("No primary key defined for the model.")
283
+
284
+ if len(pk_columns) > 1:
285
+ raise ValueError(
286
+ "Multiple primary keys defined. This method supports only single primary key models."
287
+ )
288
+
289
+ return pk_columns[0]
290
+
259
291
  # TODO what's super dangerous here is you pass a kwarg which does not map to a specific
260
292
  # field it will result in `True`, which will return all records, and not give you any typing
261
293
  # errors. Dangerous when iterating on structure quickly
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
- "this ensures TypeID objects passed as arguments to a delayed function are properly serialized"
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,3 +1,7 @@
1
+ """
2
+ https://github.com/fastapi/sqlmodel/issues/63
3
+ """
4
+
1
5
  from types import UnionType
2
6
  from typing import get_args, get_origin
3
7
 
@@ -9,11 +13,20 @@ class PydanticJSONMixin:
9
13
  """
10
14
  By default, SQLModel does not convert JSONB columns into pydantic models when they are loaded from the database.
11
15
 
12
- This mixin, combined with a custom serializer, fixes that issue.
16
+ This mixin, combined with a custom serializer (`_serialize_pydantic_model`), fixes that issue.
17
+
18
+ >>> class ExampleWithJSON(BaseModel, PydanticJSONMixin, table=True):
19
+ >>> list_field: list[SubObject] = Field(sa_type=JSONB()
13
20
  """
14
21
 
15
22
  @reconstructor
16
- def init_on_load(self):
23
+ def __transform_dict_to_pydantic__(self):
24
+ """
25
+ Transforms dictionary fields into Pydantic models upon loading.
26
+
27
+ - Reconstructor only runs once, when the object is loaded.
28
+ - We manually call this method on save(), etc to ensure the pydantic types are maintained
29
+ """
17
30
  # TODO do we need to inspect sa_type
18
31
  for field_name, field_info in self.model_fields.items():
19
32
  raw_value = getattr(self, field_name, None)
@@ -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 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
- yield
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
- transaction.rollback()
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
- # raw_sql_exec(start_truncation_query)
42
-
43
- # yield
58
+ transaction.rollback()
44
59
 
45
- # end_truncation_query = """
46
- # ROLLBACK TO SAVEPOINT test_truncation_savepoint;
47
- # RELEASE SAVEPOINT test_truncation_savepoint;
48
- # ROLLBACK;
49
- # """
60
+ # TODO is this necessary? unclear
61
+ connection.close()
50
62
 
51
- # raw_sql_exec(end_truncation_query)
63
+ SessionManager.get_instance().session_connection = None
@@ -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
 
@@ -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,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: activemodel
3
- Version: 0.7.0
3
+ Version: 0.8.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
- Then, setup some models:
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-specific method to generate the right `Field` for the relationship
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=aa5cJYZsRvYYk-TvPP_DoblvtZrn6-KGB7YS0rbAJbw,10964
3
- activemodel/celery.py,sha256=F2X5VJoNej6yg__nbF2VXaq6MK8jmgUlfo5XXivfgtU,740
2
+ activemodel/base_model.py,sha256=MM-TRlf_0DnCZHeNWxQ1S-VMq8JSBYybPfhtLZHZeRE,12066
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=Rl1KIsELSLxDGDb4K7l97Fjr1qyXZtlTJlMa7-ddllc,4869
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=JpCN_mTsbYOOud9HsX6mP_HOf3i57O5haMgnv9WOeyU,3874
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=HfnUKy_XA7MQcmR9yMTBweaNgxJhhEo3Z07hFz31gIg,2555
11
+ activemodel/mixins/pydantic_json.py,sha256=8A5X6QVzMSvDkBIb1impZ9PYskkUviG1UW7kkoxI8Wg,3057
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=rrsoHnbu79kNdnI5fZeOZr5hzrLB-cQH10MueQp5jV4,1670
16
+ activemodel/pytest/transaction.py,sha256=GfUpGUiTHATooVfxU3FMF28FHljBVdfVcb51g2KMzhY,2593
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=uTCtTm-HdvqZ2_wkIAOkCwDMNiNZna9AbSbOBNBca7o,7225
20
- activemodel-0.7.0.dist-info/METADATA,sha256=Ht_6c2mD2_qGnrEDfMFxazdNqB9P4POPAU7dCrZ0s94,8216
21
- activemodel-0.7.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
22
- activemodel-0.7.0.dist-info/entry_points.txt,sha256=YLX62TP_hR-n3HMBkdBex4W7XRiyOtIPkwy22puIjjQ,61
23
- activemodel-0.7.0.dist-info/licenses/LICENSE,sha256=L8mmpX47rB-xtJ_HsK0zpfO6viEjxbLYGn70BMp8os4,1071
24
- activemodel-0.7.0.dist-info/RECORD,,
19
+ activemodel/types/typeid.py,sha256=XrwCMvAkoZSeM5WhKH-aGJeiK0e9HoTXCheEDUgBBgQ,7292
20
+ activemodel-0.8.0.dist-info/METADATA,sha256=niH50sWYcT1c8eprDrEhetodN2bx_otnMsuzpKQZAAk,9651
21
+ activemodel-0.8.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
22
+ activemodel-0.8.0.dist-info/entry_points.txt,sha256=YLX62TP_hR-n3HMBkdBex4W7XRiyOtIPkwy22puIjjQ,61
23
+ activemodel-0.8.0.dist-info/licenses/LICENSE,sha256=L8mmpX47rB-xtJ_HsK0zpfO6viEjxbLYGn70BMp8os4,1071
24
+ activemodel-0.8.0.dist-info/RECORD,,