activemodel 0.12.0__py3-none-any.whl → 0.13.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
@@ -1,23 +1,21 @@
1
1
  import json
2
2
  import typing as t
3
+ import textcase
3
4
  from uuid import UUID
5
+ from contextlib import nullcontext
4
6
 
5
7
  import sqlalchemy as sa
6
8
  import sqlmodel as sm
7
- import textcase
8
- from sqlalchemy import Connection, event
9
9
  from sqlalchemy.dialects.postgresql import insert as postgres_insert
10
- from sqlalchemy.orm import Mapper, declared_attr
11
10
  from sqlalchemy.orm.attributes import flag_modified as sa_flag_modified
12
- from sqlalchemy.orm.base import instance_state
13
11
  from sqlmodel import Column, Field, Session, SQLModel, inspect, select
14
12
  from typeid import TypeID
13
+ from sqlalchemy.orm import declared_attr
15
14
 
16
15
  from activemodel.mixins.pydantic_json import PydanticJSONMixin
17
16
 
18
17
  # NOTE: this patches a core method in sqlmodel to support db comments
19
18
  from . import get_column_from_field_patch # noqa: F401
20
- from .logger import logger
21
19
  from .query_wrapper import QueryWrapper
22
20
  from .session_manager import get_session
23
21
 
@@ -42,85 +40,46 @@ SQLModel.metadata.naming_convention = POSTGRES_INDEXES_NAMING_CONVENTION
42
40
 
43
41
  class BaseModel(SQLModel):
44
42
  """
45
- Base model class to inherit from so we can hate python less
43
+ Base model class to inherit from so we can hate python less.
46
44
 
47
- https://github.com/woofz/sqlmodel-basecrud/blob/main/sqlmodel_basecrud/basecrud.py
45
+ Some notes:
48
46
 
49
- - {before,after} lifecycle hooks are modeled after Rails.
50
- - class docstrings are converd to table-level comments
51
- - save(), delete(), select(), where(), and other easy methods you would expect
47
+ - Inspired by https://github.com/woofz/sqlmodel-basecrud/blob/main/sqlmodel_basecrud/basecrud.py
48
+ - lifecycle hooks are modeled after Rails.
49
+ - class docstrings are converted to table-level comments
50
+ - save(), delete(), select(), where(), and other easy methods you would expect in a real ORM
52
51
  - Fixes foreign key naming conventions
52
+ - Sane table names
53
+
54
+ Here's how hooks work:
55
+
56
+ Create/Update: before_create, after_create, before_update, after_update, before_save, after_save, around_save
57
+ Delete: before_delete, after_delete, around_delete
58
+
59
+ around_* hooks must be context managers (method returning a CM or a CM attribute).
60
+ Ordering (create): before_create -> before_save -> (enter around_save) -> persist -> after_create -> after_save -> (exit around_save)
61
+ Ordering (update): before_update -> before_save -> (enter around_save) -> persist -> after_update -> after_save -> (exit around_save)
62
+ Delete: before_delete -> (enter around_delete) -> delete -> after_delete -> (exit around_delete)
63
+
64
+ # TODO document this in activemodel, this is an interesting edge case
65
+ # https://claude.ai/share/f09e4f70-2ff7-4cd0-abff-44645134693a
66
+
53
67
  """
54
68
 
55
- # this is used for table-level comments
56
69
  __table_args__ = None
57
70
 
58
71
  @classmethod
59
72
  def __init_subclass__(cls, **kwargs):
60
- "Setup automatic sqlalchemy lifecycle events for the class"
61
-
62
73
  super().__init_subclass__(**kwargs)
63
74
 
64
75
  from sqlmodel._compat import set_config_value
65
76
 
66
- # enables field-level docstrings on the pydanatic `description` field, which we then copy into
67
- # sa_args, which is persisted to sql table comments
77
+ # Enables field-level docstrings on the pydantic `description` field, which we
78
+ # copy into table/column comments by patching SQLModel internals elsewhere.
68
79
  set_config_value(model=cls, parameter="use_attribute_docstrings", value=True)
69
80
 
70
81
  cls._apply_class_doc()
71
82
 
72
- def event_wrapper(method_name: str):
73
- """
74
- This does smart heavy lifting for us to make sqlalchemy lifecycle events nicer to work with:
75
-
76
- * Passes the target first to the lifecycle method, so it feels like an instance method
77
- * Allows as little as a single positional argument, so methods can be simple
78
- * Removes the need for decorators or anything fancy on the subclass
79
- """
80
-
81
- def wrapper(mapper: Mapper, connection: Connection, target: BaseModel):
82
- if hasattr(cls, method_name):
83
- method = getattr(cls, method_name)
84
-
85
- if callable(method):
86
- arg_count = method.__code__.co_argcount
87
-
88
- if arg_count == 1: # Just self/cls
89
- method(target)
90
- elif arg_count == 2: # Self, mapper
91
- method(target, mapper)
92
- elif arg_count == 3: # Full signature
93
- method(target, mapper, connection)
94
- else:
95
- raise TypeError(
96
- f"Method {method_name} must accept either 1 to 3 arguments, got {arg_count}"
97
- )
98
- else:
99
- logger.warning(
100
- "SQLModel lifecycle hook found, but not callable hook_name=%s",
101
- method_name,
102
- )
103
-
104
- return wrapper
105
-
106
- event.listen(cls, "before_insert", event_wrapper("before_insert"))
107
- event.listen(cls, "before_update", event_wrapper("before_update"))
108
-
109
- # before_save maps to two type of events
110
- event.listen(cls, "before_insert", event_wrapper("before_save"))
111
- event.listen(cls, "before_update", event_wrapper("before_save"))
112
-
113
- # now, let's handle after_* variants
114
- event.listen(cls, "after_insert", event_wrapper("after_insert"))
115
- event.listen(cls, "after_update", event_wrapper("after_update"))
116
-
117
- # after_save maps to two type of events
118
- event.listen(cls, "after_insert", event_wrapper("after_save"))
119
- event.listen(cls, "after_update", event_wrapper("after_save"))
120
-
121
- # def foreign_key()
122
- # table.id
123
-
124
83
  @classmethod
125
84
  def _apply_class_doc(cls):
126
85
  """
@@ -234,36 +193,81 @@ class BaseModel(SQLModel):
234
193
  return result
235
194
 
236
195
  def delete(self):
237
- "Delete record completely from the database"
196
+ """Delete instance running delete hooks and optional around_delete context manager."""
197
+
198
+ cm = self._get_around_context_manager("around_delete") or nullcontext()
238
199
 
239
200
  with get_session() as session:
240
- if old_session := Session.object_session(self):
201
+ if (
202
+ old_session := Session.object_session(self)
203
+ ) and old_session is not session:
241
204
  old_session.expunge(self)
242
-
243
205
  session.delete(self)
244
- session.commit()
245
- return True
206
+
207
+ self._call_hook("before_delete")
208
+ with cm:
209
+ session.commit()
210
+ self._call_hook("after_delete")
211
+
212
+ return True
246
213
 
247
214
  def save(self):
215
+ """Persist instance running create/update hooks and optional around_save context manager."""
216
+
217
+ is_new = self.is_new()
218
+ cm = self._get_around_context_manager("around_save") or nullcontext()
219
+
248
220
  with get_session() as session:
249
- if old_session := Session.object_session(self):
250
- # I was running into an issue where the object was already
251
- # associated with a session, but the session had been closed,
252
- # to get around this, you need to remove it from the old one,
253
- # then add it to the new one (below)
221
+ if (
222
+ old_session := Session.object_session(self)
223
+ ) and old_session is not session:
254
224
  old_session.expunge(self)
255
225
 
256
226
  session.add(self)
257
- # NOTE very important method! This triggers sqlalchemy lifecycle hooks automatically
258
- session.commit()
259
- session.refresh(self)
227
+
228
+ # the order and placement of these hooks is really important
229
+ # we need the current object to be in a session otherwise it will not be able to
230
+ # load any relationships.
231
+ self._call_hook("before_create" if is_new else "before_update")
232
+ self._call_hook("before_save")
233
+
234
+ with cm:
235
+ session.commit()
236
+ session.refresh(self)
237
+
238
+ self._call_hook("after_create" if is_new else "after_update")
239
+ self._call_hook("after_save")
260
240
 
261
241
  # Only call the transform method if the class is a subclass of PydanticJSONMixin
262
242
  if issubclass(self.__class__, PydanticJSONMixin):
263
243
  self.__class__.__transform_dict_to_pydantic__(self)
264
-
265
244
  return self
266
245
 
246
+ def _call_hook(self, hook_name: str) -> None:
247
+ method = getattr(self, hook_name, None)
248
+ if callable(method):
249
+ if method.__code__.co_argcount != 1:
250
+ raise TypeError(
251
+ f"Hook '{hook_name}' must accept exactly 1 positional argument (self)"
252
+ )
253
+ method()
254
+
255
+ def _get_around_context_manager(self, name: str) -> t.ContextManager | None:
256
+ obj = getattr(self, name, None)
257
+ if obj is None:
258
+ return None
259
+
260
+ # If it's a callable (method/function), call it to obtain the CM
261
+ if callable(obj):
262
+ obj = obj()
263
+
264
+ cm = obj
265
+ if not (hasattr(cm, "__enter__") and hasattr(cm, "__exit__")):
266
+ raise TypeError(
267
+ f"{name} must return or be a context manager implementing __enter__/__exit__"
268
+ )
269
+ return t.cast(t.ContextManager, cm)
270
+
267
271
  def refresh(self):
268
272
  "Refreshes an object from the database"
269
273
 
@@ -284,6 +288,7 @@ class BaseModel(SQLModel):
284
288
 
285
289
  # TODO shouldn't this be handled by pydantic?
286
290
  # TODO where is this actually used? shoudl prob remove this
291
+ # TODO should we even do this? Can we specify a better json rendering class?
287
292
  def json(self, **kwargs):
288
293
  return json.dumps(self.dict(), default=str, **kwargs)
289
294
 
@@ -299,7 +304,12 @@ class BaseModel(SQLModel):
299
304
  # TODO got to be a better way to fwd these along...
300
305
  @classmethod
301
306
  def first(cls):
302
- return cls.select().first()
307
+ # TODO should use dynamic pk
308
+ return cls.select().order_by(sa.desc(cls.id)).first()
309
+
310
+ # @classmethod
311
+ # def last(cls):
312
+ # return cls.select().first()
303
313
 
304
314
  # TODO throw an error if this field is set on the model
305
315
  def is_new(self) -> bool:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: activemodel
3
- Version: 0.12.0
3
+ Version: 0.13.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,5 +1,5 @@
1
1
  activemodel/__init__.py,sha256=q_lHQyIM70ApvjduTo9GtenQjJXsfYZsAAquD_51kF4,137
2
- activemodel/base_model.py,sha256=zku7nKOcN4_YpIpHjP3_sWeJWGTf141gUYtPPilY0MU,17359
2
+ activemodel/base_model.py,sha256=0QRs2C_QtJFx6voSWr0jFXsbEgtn_PmYA2rrwejVzCU,17496
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
@@ -23,8 +23,8 @@ activemodel/types/sqlalchemy_protocol.py,sha256=2MSuGIp6pcIyiy8uK7qX3FLWABBMQOJG
23
23
  activemodel/types/sqlalchemy_protocol.pyi,sha256=SP4Z50SGcw6qSexGgNd_4g6E_sQwpIE44vgNT4ncmeI,5667
24
24
  activemodel/types/typeid.py,sha256=qycqklKv5nKuCqjJRnxA-6MjtcWJ4vFUsAVBc1ySwfg,7865
25
25
  activemodel/types/typeid_patch.py,sha256=y6kiCJQ_NzeKfuI4UtRAs7QW_nEog5RIA_-k4HUBMkU,575
26
- activemodel-0.12.0.dist-info/METADATA,sha256=j9sLMrYMP-2pnGE5yFFYELUqgbO-H8uKNCFrpHgw-8Q,10724
27
- activemodel-0.12.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
28
- activemodel-0.12.0.dist-info/entry_points.txt,sha256=rytVrsNgUT4oDiW9RvRH6JBTHQn0hPZLK-jzQt3dY9s,51
29
- activemodel-0.12.0.dist-info/licenses/LICENSE,sha256=L8mmpX47rB-xtJ_HsK0zpfO6viEjxbLYGn70BMp8os4,1071
30
- activemodel-0.12.0.dist-info/RECORD,,
26
+ activemodel-0.13.0.dist-info/METADATA,sha256=744GzqxDiyQQYxv5jlVcC8PBDLj8Xj0gL7P49oM3buI,10724
27
+ activemodel-0.13.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
28
+ activemodel-0.13.0.dist-info/entry_points.txt,sha256=rytVrsNgUT4oDiW9RvRH6JBTHQn0hPZLK-jzQt3dY9s,51
29
+ activemodel-0.13.0.dist-info/licenses/LICENSE,sha256=L8mmpX47rB-xtJ_HsK0zpfO6viEjxbLYGn70BMp8os4,1071
30
+ activemodel-0.13.0.dist-info/RECORD,,