activemodel 0.8.0__py3-none-any.whl → 0.10.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
@@ -7,9 +7,10 @@ import sqlalchemy as sa
7
7
  import sqlmodel as sm
8
8
  from sqlalchemy import Connection, event
9
9
  from sqlalchemy.orm import Mapper, declared_attr
10
- from sqlmodel import Field, MetaData, Session, SQLModel, select
10
+ from sqlalchemy.orm.attributes import flag_modified as sa_flag_modified
11
+ from sqlalchemy.orm.base import instance_state
12
+ from sqlmodel import Column, Field, Session, SQLModel, inspect, select
11
13
  from typeid import TypeID
12
- from inspect import isclass
13
14
 
14
15
  from activemodel.mixins.pydantic_json import PydanticJSONMixin
15
16
 
@@ -18,6 +19,7 @@ from . import get_column_from_field_patch # noqa: F401
18
19
  from .logger import logger
19
20
  from .query_wrapper import QueryWrapper
20
21
  from .session_manager import get_session
22
+ from sqlalchemy.dialects.postgresql import insert as postgres_insert
21
23
 
22
24
  POSTGRES_INDEXES_NAMING_CONVENTION = {
23
25
  "ix": "%(column_0_label)s_idx",
@@ -136,8 +138,15 @@ class BaseModel(SQLModel):
136
138
  cls.__table_args__ = {"comment": doc}
137
139
  elif isinstance(table_args, dict):
138
140
  table_args.setdefault("comment", doc)
141
+ elif isinstance(table_args, tuple):
142
+ # If it's a tuple, we need to convert it to a list and add the comment
143
+ table_args = list(table_args)
144
+ table_args.append({"comment": doc})
145
+ cls.__table_args__ = tuple(table_args)
139
146
  else:
140
- raise ValueError("Unexpected __table_args__ type")
147
+ raise ValueError(
148
+ f"Unexpected __table_args__ type {type(table_args)}, expected dictionary."
149
+ )
141
150
 
142
151
  # TODO no type check decorator here
143
152
  @declared_attr
@@ -162,8 +171,10 @@ class BaseModel(SQLModel):
162
171
  """
163
172
  Returns a `Field` object referencing the foreign key of the model.
164
173
 
165
- >>> other_model_id: int
166
- >>> other_model = OtherModel.foreign_key()
174
+ Helps quickly build a many-to-one or one-to-one relationship.
175
+
176
+ >>> other_model_id: int = OtherModel.foreign_key()
177
+ >>> other_model = Relationship()
167
178
  """
168
179
 
169
180
  field_options = {"nullable": False} | kwargs
@@ -185,6 +196,42 @@ class BaseModel(SQLModel):
185
196
  "convenience method to avoid having to write .select().where() in order to add conditions"
186
197
  return cls.select().where(*args)
187
198
 
199
+ @classmethod
200
+ def upsert(
201
+ cls,
202
+ data: dict[str, t.Any],
203
+ unique_by: str | list[str],
204
+ ) -> None:
205
+ """
206
+ This method will insert a new record if it doesn't exist, or update the existing record if it does.
207
+
208
+ It uses SQLAlchemy's `on_conflict_do_update` and does not yet support MySQL. Some implementation details below.
209
+
210
+ ---
211
+
212
+ - `index_elements=["name"]`: Specifies the column(s) to check for conflicts (e.g., unique constraint or index). If a row with the same "name" exists, it triggers the update instead of an insert.
213
+ - `values`: Defines the data to insert (e.g., `name="example", value=123`). If no conflict occurs, this data is inserted as a new row.
214
+
215
+ The `set_` parameter (e.g., `set_=dict(value=123)`) then dictates what gets updated on conflict, overriding matching fields in `values` if specified.
216
+ """
217
+ index_elements = [unique_by] if isinstance(unique_by, str) else unique_by
218
+
219
+ stmt = (
220
+ postgres_insert(cls)
221
+ .values(**data)
222
+ .on_conflict_do_update(index_elements=index_elements, set_=data)
223
+ .returning(cls)
224
+ )
225
+
226
+ with get_session() as session:
227
+ result = session.exec(stmt)
228
+ session.commit()
229
+
230
+ # TODO this is so ugly:
231
+ result = result.one()[0]
232
+
233
+ return result
234
+
188
235
  def delete(self):
189
236
  with get_session() as session:
190
237
  if old_session := Session.object_session(self):
@@ -214,7 +261,26 @@ class BaseModel(SQLModel):
214
261
 
215
262
  return self
216
263
 
264
+ def refresh(self):
265
+ "Refreshes an object from the database"
266
+
267
+ with get_session() as session:
268
+ if (
269
+ old_session := Session.object_session(self)
270
+ ) and old_session is not session:
271
+ old_session.expunge(self)
272
+
273
+ session.add(self)
274
+ session.refresh(self)
275
+
276
+ # Only call the transform method if the class is a subclass of PydanticJSONMixin
277
+ if issubclass(self.__class__, PydanticJSONMixin):
278
+ self.__class__.__transform_dict_to_pydantic__(self)
279
+
280
+ return self
281
+
217
282
  # TODO shouldn't this be handled by pydantic?
283
+ # TODO where is this actually used? shoudl prob remove this
218
284
  def json(self, **kwargs):
219
285
  return json.dumps(self.dict(), default=str, **kwargs)
220
286
 
@@ -236,6 +302,29 @@ class BaseModel(SQLModel):
236
302
  def is_new(self) -> bool:
237
303
  return not self._sa_instance_state.has_identity
238
304
 
305
+ def flag_modified(self, *args: str) -> None:
306
+ """
307
+ Flag one or more fields as modified/mutated/dirty. Useful for marking a field containing sub-objects as modified.
308
+
309
+ Will throw an error if an invalid field is passed.
310
+ """
311
+
312
+ assert len(args) > 0, "Must pass at least one field name"
313
+
314
+ for field_name in args:
315
+ if field_name not in self.__fields__:
316
+ raise ValueError(f"Field '{field_name}' does not exist in the model.")
317
+
318
+ # check if the field exists
319
+ sa_flag_modified(self, field_name)
320
+
321
+ def modified_fields(self) -> set[str]:
322
+ "set of fields that are modified"
323
+
324
+ insp = inspect(self)
325
+
326
+ return {attr.key for attr in insp.attrs if attr.history.has_changes()}
327
+
239
328
  @classmethod
240
329
  def find_or_create_by(cls, **kwargs):
241
330
  """
@@ -268,13 +357,15 @@ class BaseModel(SQLModel):
268
357
  return new_model
269
358
 
270
359
  @classmethod
271
- def primary_key_field(cls):
360
+ def primary_key_column(cls) -> Column:
272
361
  """
273
362
  Returns the primary key column of the model by inspecting SQLAlchemy field information.
274
363
 
275
364
  >>> ExampleModel.primary_key_field().name
276
365
  """
366
+
277
367
  # TODO note_schema.__class__.__table__.primary_key
368
+ # TODO no reason why this couldn't be cached
278
369
 
279
370
  pk_columns = list(cls.__table__.primary_key.columns)
280
371
 
@@ -297,9 +388,8 @@ class BaseModel(SQLModel):
297
388
  @classmethod
298
389
  def get(cls, *args: t.Any, **kwargs: t.Any):
299
390
  """
300
- Gets a single record from the database. Pass an PK ID or a kwarg to filter by.
391
+ Gets a single record (or None) from the database. Pass an PK ID or kwargs to filter by.
301
392
  """
302
-
303
393
  # TODO id is hardcoded, not good! Need to dynamically pick the best uid field
304
394
  id_field_name = "id"
305
395
 
@@ -313,8 +403,37 @@ class BaseModel(SQLModel):
313
403
  with get_session() as session:
314
404
  return session.exec(statement).first()
315
405
 
406
+ @classmethod
407
+ def one(cls, *args: t.Any, **kwargs: t.Any):
408
+ """
409
+ Gets a single record from the database. Pass an PK ID or a kwarg to filter by.
410
+ """
411
+
412
+ args, kwargs = cls.__process_filter_args__(*args, **kwargs)
413
+ statement = select(cls).filter(*args).filter_by(**kwargs)
414
+
415
+ with get_session() as session:
416
+ return session.exec(statement).one()
417
+
418
+ @classmethod
419
+ def __process_filter_args__(cls, *args: t.Any, **kwargs: t.Any):
420
+ """
421
+ Helper method to process filter arguments and implement some nice DX for our devs.
422
+ """
423
+
424
+ id_field_name = cls.primary_key_column().name
425
+
426
+ # special case for getting by ID without having to specify the field name
427
+ # TODO should dynamically add new pk types based on column definition
428
+ if len(args) == 1 and isinstance(args[0], (int, TypeID, str, UUID)):
429
+ kwargs[id_field_name] = args[0]
430
+ args = ()
431
+
432
+ return args, kwargs
433
+
316
434
  @classmethod
317
435
  def all(cls):
436
+ "get a generator for all records in the database"
318
437
  with get_session() as session:
319
438
  results = session.exec(sm.select(cls))
320
439
 
@@ -325,7 +444,7 @@ class BaseModel(SQLModel):
325
444
  @classmethod
326
445
  def sample(cls):
327
446
  """
328
- Pick a random record from the database.
447
+ Pick a random record from the database. Raises if none exist.
329
448
 
330
449
  Helpful for testing and console debugging.
331
450
  """
@@ -1,12 +1,16 @@
1
1
  """
2
- https://github.com/fastapi/sqlmodel/issues/63
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
3
7
  """
4
8
 
5
9
  from types import UnionType
6
10
  from typing import get_args, get_origin
7
11
 
8
12
  from pydantic import BaseModel as PydanticBaseModel
9
- from sqlalchemy.orm import reconstructor
13
+ from sqlalchemy.orm import reconstructor, attributes
10
14
 
11
15
 
12
16
  class PydanticJSONMixin:
@@ -26,6 +30,8 @@ class PydanticJSONMixin:
26
30
 
27
31
  - Reconstructor only runs once, when the object is loaded.
28
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.
29
35
  """
30
36
  # TODO do we need to inspect sa_type
31
37
  for field_name, field_info in self.model_fields.items():
@@ -73,10 +79,9 @@ class PydanticJSONMixin:
73
79
  model_cls, PydanticBaseModel
74
80
  ):
75
81
  parsed_value = [model_cls(**item) for item in raw_value]
76
- setattr(self, field_name, parsed_value)
77
-
82
+ attributes.set_committed_value(self, field_name, parsed_value)
78
83
  continue
79
84
 
80
85
  # single class
81
86
  if issubclass(model_cls, PydanticBaseModel):
82
- setattr(self, field_name, model_cls(**raw_value))
87
+ attributes.set_committed_value(self, field_name, model_cls(**raw_value))
@@ -4,43 +4,30 @@ from typeid import TypeID
4
4
  from activemodel.types.typeid import TypeIDType
5
5
 
6
6
  # global list of prefixes to ensure uniqueness
7
- _prefixes = []
7
+ _prefixes: list[str] = []
8
8
 
9
9
 
10
10
  def TypeIDMixin(prefix: str):
11
+ # make sure duplicate prefixes are not used!
12
+ # NOTE this will cause issues on code reloads
11
13
  assert prefix
12
14
  assert prefix not in _prefixes, (
13
15
  f"prefix {prefix} already exists, pick a different one"
14
16
  )
15
17
 
16
18
  class _TypeIDMixin:
19
+ __abstract__ = True
20
+
17
21
  id: TypeIDType = Field(
18
- sa_column=Column(TypeIDType(prefix), primary_key=True, nullable=False),
19
- default_factory=lambda: TypeID(prefix),
22
+ sa_column=Column(
23
+ TypeIDType(prefix),
24
+ primary_key=True,
25
+ nullable=False,
26
+ default=lambda: TypeID(prefix),
27
+ ),
28
+ # default_factory=lambda: TypeID(prefix),
20
29
  )
21
30
 
22
31
  _prefixes.append(prefix)
23
32
 
24
33
  return _TypeIDMixin
25
-
26
-
27
- # TODO not sure if I love the idea of a dynamic class for each mixin as used above
28
- # may give this approach another shot in the future
29
- # class TypeIDMixin2:
30
- # """
31
- # Mixin class that adds a TypeID primary key to models.
32
-
33
-
34
- # >>> class MyModel(BaseModel, TypeIDMixin, prefix="xyz", table=True):
35
- # >>> name: str
36
-
37
- # Will automatically have an `id` field with prefix "xyz"
38
- # """
39
-
40
- # def __init_subclass__(cls, *, prefix: str, **kwargs):
41
- # super().__init_subclass__(**kwargs)
42
-
43
- # cls.id: uuid.UUID = Field(
44
- # sa_column=Column(TypeIDType(prefix), primary_key=True),
45
- # default_factory=lambda: TypeID(prefix),
46
- # )
@@ -28,7 +28,7 @@ def database_reset_transaction():
28
28
 
29
29
  engine = SessionManager.get_instance().get_engine()
30
30
 
31
- logger.info("starting database transaction")
31
+ logger.info("starting global database transaction")
32
32
 
33
33
  with engine.begin() as connection:
34
34
  transaction = connection.begin_nested()
@@ -72,6 +72,7 @@ class SessionManager:
72
72
  self._database_url,
73
73
  # NOTE very important! This enables pydantic models to be serialized for JSONB columns
74
74
  json_serializer=_serialize_pydantic_model,
75
+ # TODO move to a constants area
75
76
  echo=config("ACTIVEMODEL_LOG_SQL", cast=bool, default=False),
76
77
  # https://docs.sqlalchemy.org/en/20/core/pooling.html#disconnect-handling-pessimistic
77
78
  pool_pre_ping=True,
@@ -119,6 +120,9 @@ _session_context = contextvars.ContextVar[Session | None](
119
120
 
120
121
  @contextlib.contextmanager
121
122
  def global_session():
123
+ if _session_context.get() is not None:
124
+ raise RuntimeError("global session already set")
125
+
122
126
  with SessionManager.get_instance().get_session() as s:
123
127
  token = _session_context.set(s)
124
128
 
@@ -140,6 +144,9 @@ async def aglobal_session():
140
144
  >>> )
141
145
  """
142
146
 
147
+ if _session_context.get() is not None:
148
+ raise RuntimeError("global session already set")
149
+
143
150
  with SessionManager.get_instance().get_session() as s:
144
151
  token = _session_context.set(s)
145
152
 
@@ -188,5 +188,3 @@ class TypeIDType(types.TypeDecorator):
188
188
  # "minLength": 24,
189
189
  # "maxLength": 24,
190
190
  }
191
-
192
- return core_schema.uuid_schema()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: activemodel
3
- Version: 0.8.0
3
+ Version: 0.10.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>
@@ -1,24 +1,24 @@
1
1
  activemodel/__init__.py,sha256=q_lHQyIM70ApvjduTo9GtenQjJXsfYZsAAquD_51kF4,137
2
- activemodel/base_model.py,sha256=MM-TRlf_0DnCZHeNWxQ1S-VMq8JSBYybPfhtLZHZeRE,12066
2
+ activemodel/base_model.py,sha256=VSItKKMxP-g-en_v16VnR9W6ueSLlWqmxn7I2-TgpGk,16646
3
3
  activemodel/celery.py,sha256=L1vKcO_HoPA5ZCfsXjxgPpDUMYDuoQMakGA9rppN7Lo,897
4
4
  activemodel/errors.py,sha256=wycWYmk9ws4TZpxvTdtXVy2SFESb8NqKgzdivBoF0vw,115
5
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=Vtg8Lf8vUNPegdRW-fyE-Ng5wtN3hTMfUezdFUiJ1fs,4585
8
+ activemodel/session_manager.py,sha256=ltmUyBsYCNNddoilLWrh3HX9QY9eQSZiRsyFf0awevs,4835
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=8A5X6QVzMSvDkBIb1impZ9PYskkUviG1UW7kkoxI8Wg,3057
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
- activemodel/mixins/typeid.py,sha256=DGjlIg8PRBYoaBbWkkxc6jkScyl-p53KuSR98lLgAvE,1284
14
+ activemodel/mixins/typeid.py,sha256=WBZwnryF2QkI1ki0fW-jEbE8cIqMIldwkaeJdGT01S4,841
15
15
  activemodel/pytest/__init__.py,sha256=W9KKQHbPkyq0jrMXaiL8hG2Nsbjy_LN9HhvgGm8W_7g,98
16
- activemodel/pytest/transaction.py,sha256=GfUpGUiTHATooVfxU3FMF28FHljBVdfVcb51g2KMzhY,2593
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=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,,
19
+ activemodel/types/typeid.py,sha256=1xB79DGIC5-P-PcLpeZW9Ed_WjFOmmVW1yl2Q3pPJis,7250
20
+ activemodel-0.10.0.dist-info/METADATA,sha256=rin3Edbj6CFW8-cj6fcL6S6GU8a1Qn0Sl9tGOLM-_rw,9652
21
+ activemodel-0.10.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
22
+ activemodel-0.10.0.dist-info/entry_points.txt,sha256=YLX62TP_hR-n3HMBkdBex4W7XRiyOtIPkwy22puIjjQ,61
23
+ activemodel-0.10.0.dist-info/licenses/LICENSE,sha256=L8mmpX47rB-xtJ_HsK0zpfO6viEjxbLYGn70BMp8os4,1071
24
+ activemodel-0.10.0.dist-info/RECORD,,