django-bulk-hooks 0.1.247__tar.gz → 0.1.248__tar.gz

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.

Potentially problematic release.


This version of django-bulk-hooks might be problematic. Click here for more details.

Files changed (17) hide show
  1. {django_bulk_hooks-0.1.247 → django_bulk_hooks-0.1.248}/PKG-INFO +1 -1
  2. {django_bulk_hooks-0.1.247 → django_bulk_hooks-0.1.248}/django_bulk_hooks/queryset.py +46 -354
  3. {django_bulk_hooks-0.1.247 → django_bulk_hooks-0.1.248}/pyproject.toml +1 -1
  4. {django_bulk_hooks-0.1.247 → django_bulk_hooks-0.1.248}/LICENSE +0 -0
  5. {django_bulk_hooks-0.1.247 → django_bulk_hooks-0.1.248}/README.md +0 -0
  6. {django_bulk_hooks-0.1.247 → django_bulk_hooks-0.1.248}/django_bulk_hooks/__init__.py +0 -0
  7. {django_bulk_hooks-0.1.247 → django_bulk_hooks-0.1.248}/django_bulk_hooks/conditions.py +0 -0
  8. {django_bulk_hooks-0.1.247 → django_bulk_hooks-0.1.248}/django_bulk_hooks/constants.py +0 -0
  9. {django_bulk_hooks-0.1.247 → django_bulk_hooks-0.1.248}/django_bulk_hooks/context.py +0 -0
  10. {django_bulk_hooks-0.1.247 → django_bulk_hooks-0.1.248}/django_bulk_hooks/decorators.py +0 -0
  11. {django_bulk_hooks-0.1.247 → django_bulk_hooks-0.1.248}/django_bulk_hooks/engine.py +0 -0
  12. {django_bulk_hooks-0.1.247 → django_bulk_hooks-0.1.248}/django_bulk_hooks/enums.py +0 -0
  13. {django_bulk_hooks-0.1.247 → django_bulk_hooks-0.1.248}/django_bulk_hooks/handler.py +0 -0
  14. {django_bulk_hooks-0.1.247 → django_bulk_hooks-0.1.248}/django_bulk_hooks/manager.py +0 -0
  15. {django_bulk_hooks-0.1.247 → django_bulk_hooks-0.1.248}/django_bulk_hooks/models.py +0 -0
  16. {django_bulk_hooks-0.1.247 → django_bulk_hooks-0.1.248}/django_bulk_hooks/priority.py +0 -0
  17. {django_bulk_hooks-0.1.247 → django_bulk_hooks-0.1.248}/django_bulk_hooks/registry.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: django-bulk-hooks
3
- Version: 0.1.247
3
+ Version: 0.1.248
4
4
  Summary: Hook-style hooks for Django bulk operations like bulk_create and bulk_update.
5
5
  Home-page: https://github.com/AugendLimited/django-bulk-hooks
6
6
  License: MIT
@@ -1,11 +1,10 @@
1
1
  import logging
2
2
 
3
3
  from django.db import models, transaction
4
- from django.db.models import AutoField, Case, Field, Value, When
4
+ from django.db.models import AutoField, Case, Field, Subquery, Value, When
5
5
 
6
6
  from django_bulk_hooks import engine
7
7
 
8
- logger = logging.getLogger(__name__)
9
8
  from django_bulk_hooks.constants import (
10
9
  AFTER_CREATE,
11
10
  AFTER_DELETE,
@@ -20,9 +19,12 @@ from django_bulk_hooks.constants import (
20
19
  from django_bulk_hooks.context import (
21
20
  HookContext,
22
21
  get_bulk_update_value_map,
22
+ get_bypass_hooks,
23
23
  set_bulk_update_value_map,
24
24
  )
25
25
 
26
+ logger = logging.getLogger(__name__)
27
+
26
28
 
27
29
  class HookQuerySetMixin:
28
30
  """
@@ -55,7 +57,7 @@ class HookQuerySetMixin:
55
57
 
56
58
  @transaction.atomic
57
59
  def update(self, **kwargs):
58
- logger.debug(f"Entering update method with {len(kwargs)} kwargs")
60
+ """Simplified update method that handles hooks cleanly."""
59
61
  instances = list(self)
60
62
  if not instances:
61
63
  return 0
@@ -63,382 +65,72 @@ class HookQuerySetMixin:
63
65
  model_cls = self.model
64
66
  pks = [obj.pk for obj in instances]
65
67
 
66
- # Load originals for hook comparison and ensure they match the order of instances
67
- # Use the base manager to avoid recursion
68
+ # Load originals for hook comparison
68
69
  original_map = {
69
70
  obj.pk: obj for obj in model_cls._base_manager.filter(pk__in=pks)
70
71
  }
71
72
  originals = [original_map.get(obj.pk) for obj in instances]
72
73
 
73
- # Check if any of the update values are Subquery objects
74
- try:
75
- from django.db.models import Subquery
76
-
77
- logger.debug(f"Successfully imported Subquery from django.db.models")
78
- except ImportError as e:
79
- logger.error(f"Failed to import Subquery: {e}")
80
- raise
81
-
82
- logger.debug(f"Checking for Subquery objects in {len(kwargs)} kwargs")
83
-
84
- subquery_detected = []
85
- for key, value in kwargs.items():
86
- is_subquery = isinstance(value, Subquery)
87
- logger.debug(
88
- f"Key '{key}': type={type(value).__name__}, is_subquery={is_subquery}"
89
- )
90
- if is_subquery:
91
- subquery_detected.append(key)
92
-
93
- has_subquery = len(subquery_detected) > 0
94
- logger.debug(
95
- f"Subquery detection result: {has_subquery}, detected keys: {subquery_detected}"
96
- )
97
-
98
- # Debug logging for Subquery detection
99
- logger.debug(f"Update kwargs: {list(kwargs.keys())}")
100
- logger.debug(
101
- f"Update kwargs types: {[(k, type(v).__name__) for k, v in kwargs.items()]}"
102
- )
74
+ # Check for Subquery updates
75
+ has_subquery = any(isinstance(v, Subquery) for v in kwargs.values())
103
76
 
104
- if has_subquery:
105
- logger.debug(
106
- f"Detected Subquery in update: {[k for k, v in kwargs.items() if isinstance(v, Subquery)]}"
107
- )
108
- else:
109
- # Check if we missed any Subquery objects
110
- for k, v in kwargs.items():
111
- if hasattr(v, "query") and hasattr(v, "resolve_expression"):
112
- logger.warning(
113
- f"Potential Subquery-like object detected but not recognized: {k}={type(v).__name__}"
114
- )
115
- logger.warning(
116
- f"Object attributes: query={hasattr(v, 'query')}, resolve_expression={hasattr(v, 'resolve_expression')}"
117
- )
118
- logger.warning(
119
- f"Object dir: {[attr for attr in dir(v) if not attr.startswith('_')][:10]}"
120
- )
77
+ # Skip hooks if bypassed
78
+ if get_bypass_hooks():
79
+ return super().update(**kwargs)
121
80
 
122
- # Apply field updates to instances
123
- # If a per-object value map exists (from bulk_update), prefer it over kwargs
124
- # IMPORTANT: Do not assign Django expression objects (e.g., Subquery/Case/F)
125
- # to in-memory instances before running BEFORE_UPDATE hooks. Hooks must not
126
- # receive unresolved expression objects.
127
- per_object_values = get_bulk_update_value_map()
81
+ ctx = HookContext(model_cls, bypass_hooks=False)
128
82
 
129
- # For Subquery updates, skip all in-memory field assignments to prevent
130
- # expression objects from reaching hooks
131
83
  if has_subquery:
132
- logger.debug(
133
- "Skipping in-memory field assignments due to Subquery detection"
134
- )
135
- else:
136
- for obj in instances:
137
- if per_object_values and obj.pk in per_object_values:
138
- for field, value in per_object_values[obj.pk].items():
139
- setattr(obj, field, value)
140
- else:
141
- for field, value in kwargs.items():
142
- # Skip assigning expression-like objects (they will be handled at DB level)
143
- is_expression_like = hasattr(value, "resolve_expression")
144
- if is_expression_like:
145
- # Special-case Value() which can be unwrapped safely
146
- if isinstance(value, Value):
147
- try:
148
- setattr(obj, field, value.value)
149
- except Exception:
150
- # If Value cannot be unwrapped for any reason, skip assignment
151
- continue
152
- else:
153
- # Do not assign unresolved expressions to in-memory objects
154
- logger.debug(
155
- f"Skipping assignment of expression {type(value).__name__} to field {field}"
156
- )
157
- continue
158
- else:
159
- setattr(obj, field, value)
160
-
161
- # Salesforce-style trigger behavior: Always run hooks, rely on Django's stack overflow protection
162
- from django_bulk_hooks.context import get_bypass_hooks
163
-
164
- current_bypass_hooks = get_bypass_hooks()
165
-
166
- # Only skip hooks if explicitly bypassed (not for recursion prevention)
167
- if current_bypass_hooks:
168
- logger.debug("update: hooks explicitly bypassed")
169
- ctx = HookContext(model_cls, bypass_hooks=True)
170
- else:
171
- # Always run hooks - Django will handle stack overflow protection
172
- logger.debug("update: running hooks with Salesforce-style behavior")
173
- ctx = HookContext(model_cls, bypass_hooks=False)
174
-
175
- # Run validation hooks first
176
- engine.run(model_cls, VALIDATE_UPDATE, instances, originals, ctx=ctx)
177
-
178
- # For Subquery updates, skip BEFORE_UPDATE hooks here - they'll run after refresh
179
- if not has_subquery:
180
- # Then run BEFORE_UPDATE hooks for non-Subquery updates
181
- engine.run(model_cls, BEFORE_UPDATE, instances, originals, ctx=ctx)
182
-
183
- # Persist any additional field mutations made by BEFORE_UPDATE hooks.
184
- # Build CASE statements per modified field not already present in kwargs.
185
- # Note: For Subquery updates, this will be empty since hooks haven't run yet
186
- modified_fields = self._detect_modified_fields(instances, originals)
187
- extra_fields = [f for f in modified_fields if f not in kwargs]
188
- if extra_fields:
189
- case_statements = {}
190
- for field_name in extra_fields:
191
- try:
192
- field_obj = model_cls._meta.get_field(field_name)
193
- except Exception:
194
- # Skip unknown fields
195
- continue
196
-
197
- when_statements = []
198
- for obj in instances:
199
- obj_pk = getattr(obj, "pk", None)
200
- if obj_pk is None:
201
- continue
202
-
203
- # Determine value and output field
204
- if getattr(field_obj, "is_relation", False):
205
- # For FK fields, store the raw id and target field output type
206
- value = getattr(obj, field_obj.attname, None)
207
- output_field = field_obj.target_field
208
- target_name = (
209
- field_obj.attname
210
- ) # use column name (e.g., fk_id)
211
- else:
212
- value = getattr(obj, field_name)
213
- output_field = field_obj
214
- target_name = field_name
215
-
216
- # Special handling for Subquery and other expression values in CASE statements
217
- if isinstance(value, Subquery):
218
- logger.debug(
219
- f"Creating When statement with Subquery for {field_name}"
220
- )
221
- # Ensure the Subquery has proper output_field
222
- if (
223
- not hasattr(value, "output_field")
224
- or value.output_field is None
225
- ):
226
- value.output_field = output_field
227
- logger.debug(
228
- f"Set output_field for Subquery in When statement to {output_field}"
229
- )
230
- when_statements.append(When(pk=obj_pk, then=value))
231
- elif hasattr(value, "resolve_expression"):
232
- # Handle other expression objects (Case, F, etc.)
233
- logger.debug(
234
- f"Creating When statement with expression for {field_name}: {type(value).__name__}"
235
- )
236
- when_statements.append(When(pk=obj_pk, then=value))
237
- else:
238
- when_statements.append(
239
- When(
240
- pk=obj_pk,
241
- then=Value(value, output_field=output_field),
242
- )
243
- )
84
+ # For Subquery updates: database first, then hooks
85
+ update_count = super().update(**kwargs)
244
86
 
245
- if when_statements:
246
- case_statements[target_name] = Case(
247
- *when_statements, output_field=output_field
248
- )
249
-
250
- # Merge extra CASE updates into kwargs for DB update
251
- if case_statements:
252
- logger.debug(
253
- f"Adding case statements to kwargs: {list(case_statements.keys())}"
254
- )
255
- for field_name, case_stmt in case_statements.items():
256
- logger.debug(
257
- f"Case statement for {field_name}: {type(case_stmt).__name__}"
258
- )
259
- # Check if the case statement contains Subquery objects
260
- if hasattr(case_stmt, "get_source_expressions"):
261
- source_exprs = case_stmt.get_source_expressions()
262
- for expr in source_exprs:
263
- if isinstance(expr, Subquery):
264
- logger.debug(
265
- f"Case statement for {field_name} contains Subquery"
266
- )
267
- elif hasattr(expr, "get_source_expressions"):
268
- # Check nested expressions (like Value objects)
269
- nested_exprs = expr.get_source_expressions()
270
- for nested_expr in nested_exprs:
271
- if isinstance(nested_expr, Subquery):
272
- logger.debug(
273
- f"Case statement for {field_name} contains nested Subquery"
274
- )
275
-
276
- kwargs = {**kwargs, **case_statements}
277
-
278
- # Use Django's built-in update logic directly
279
- # Call the base QuerySet implementation to avoid recursion
280
-
281
- # Additional safety check: ensure Subquery objects are properly handled
282
- # This prevents the "cannot adapt type 'Subquery'" error
283
- safe_kwargs = {}
284
- logger.debug(f"Processing {len(kwargs)} kwargs for safety check")
285
-
286
- for key, value in kwargs.items():
287
- logger.debug(
288
- f"Processing key '{key}' with value type {type(value).__name__}"
289
- )
290
-
291
- if isinstance(value, Subquery):
292
- logger.debug(f"Found Subquery for field {key}")
293
- # Ensure Subquery has proper output_field
294
- if not hasattr(value, "output_field") or value.output_field is None:
295
- logger.warning(
296
- f"Subquery for field {key} missing output_field, attempting to infer"
297
- )
298
- # Try to infer from the model field
299
- try:
300
- field = model_cls._meta.get_field(key)
301
- logger.debug(f"Inferred field type: {type(field).__name__}")
302
- value = value.resolve_expression(None, None)
303
- value.output_field = field
304
- logger.debug(f"Set output_field to {field}")
305
- except Exception as e:
306
- logger.error(
307
- f"Failed to infer output_field for Subquery on {key}: {e}"
308
- )
309
- raise
310
- else:
311
- logger.debug(
312
- f"Subquery for field {key} already has output_field: {value.output_field}"
313
- )
314
- safe_kwargs[key] = value
315
- elif hasattr(value, "get_source_expressions") and hasattr(
316
- value, "resolve_expression"
317
- ):
318
- # Handle Case statements and other complex expressions
319
- logger.debug(
320
- f"Found complex expression for field {key}: {type(value).__name__}"
321
- )
322
-
323
- # Check if this expression contains any Subquery objects
324
- source_expressions = value.get_source_expressions()
325
- has_nested_subquery = False
326
-
327
- for expr in source_expressions:
328
- if isinstance(expr, Subquery):
329
- has_nested_subquery = True
330
- logger.debug(f"Found nested Subquery in {type(value).__name__}")
331
- # Ensure the nested Subquery has proper output_field
332
- if (
333
- not hasattr(expr, "output_field")
334
- or expr.output_field is None
335
- ):
336
- try:
337
- field = model_cls._meta.get_field(key)
338
- expr.output_field = field
339
- logger.debug(
340
- f"Set output_field for nested Subquery to {field}"
341
- )
342
- except Exception as e:
343
- logger.error(
344
- f"Failed to set output_field for nested Subquery: {e}"
345
- )
346
- raise
347
-
348
- if has_nested_subquery:
349
- logger.debug(
350
- f"Expression contains Subquery, ensuring proper output_field"
351
- )
352
- # Try to resolve the expression to ensure it's properly formatted
353
- try:
354
- resolved_value = value.resolve_expression(None, None)
355
- safe_kwargs[key] = resolved_value
356
- logger.debug(f"Successfully resolved expression for {key}")
357
- except Exception as e:
358
- logger.error(f"Failed to resolve expression for {key}: {e}")
359
- raise
360
- else:
361
- safe_kwargs[key] = value
362
- else:
363
- logger.debug(
364
- f"Non-Subquery value for field {key}: {type(value).__name__}"
365
- )
366
- safe_kwargs[key] = value
367
-
368
- logger.debug(f"Safe kwargs keys: {list(safe_kwargs.keys())}")
369
- logger.debug(
370
- f"Safe kwargs types: {[(k, type(v).__name__) for k, v in safe_kwargs.items()]}"
371
- )
372
-
373
- logger.debug(f"Calling super().update() with {len(safe_kwargs)} kwargs")
374
- try:
375
- update_count = super().update(**safe_kwargs)
376
- logger.debug(f"Super update successful, count: {update_count}")
377
- except Exception as e:
378
- logger.error(f"Super update failed: {e}")
379
- logger.error(f"Exception type: {type(e).__name__}")
380
- logger.error(f"Safe kwargs that caused failure: {safe_kwargs}")
381
- raise
382
-
383
- # If we used Subquery objects, refresh the instances to get computed values
384
- # and run BEFORE_UPDATE hooks so HasChanged conditions work correctly
385
- if has_subquery and instances and not current_bypass_hooks:
386
- logger.debug(
387
- "Refreshing instances with Subquery computed values before running hooks"
388
- )
389
- # Simple refresh of model fields without fetching related objects
390
- # Subquery updates only affect the model's own fields, not relationships
391
- refreshed_instances = {
87
+ # Refresh instances with computed values
88
+ refreshed_map = {
392
89
  obj.pk: obj for obj in model_cls._base_manager.filter(pk__in=pks)
393
90
  }
394
-
395
- # Bulk update all instances in memory and save pre-hook state
396
- pre_hook_state = {}
397
91
  for instance in instances:
398
- if instance.pk in refreshed_instances:
399
- refreshed_instance = refreshed_instances[instance.pk]
400
- # Save current state before modifying for hook comparison
401
- pre_hook_values = {}
92
+ if instance.pk in refreshed_map:
93
+ refreshed = refreshed_map[instance.pk]
402
94
  for field in model_cls._meta.fields:
403
95
  if field.name != "id":
404
- pre_hook_values[field.name] = getattr(refreshed_instance, field.name)
405
96
  setattr(
406
- instance,
407
- field.name,
408
- getattr(refreshed_instance, field.name),
97
+ instance, field.name, getattr(refreshed, field.name)
409
98
  )
410
- pre_hook_state[instance.pk] = pre_hook_values
411
99
 
412
- # Now run BEFORE_UPDATE hooks with refreshed instances so conditions work
413
- logger.debug("Running BEFORE_UPDATE hooks after Subquery refresh")
100
+ # Run hooks with refreshed data
101
+ engine.run(model_cls, VALIDATE_UPDATE, instances, originals, ctx=ctx)
414
102
  engine.run(model_cls, BEFORE_UPDATE, instances, originals, ctx=ctx)
415
103
 
416
- # Check if hooks modified any fields and persist them with bulk_update
417
- hook_modified_fields = set()
418
- for instance in instances:
419
- if instance.pk in pre_hook_state:
420
- pre_hook_values = pre_hook_state[instance.pk]
421
- for field_name, pre_hook_value in pre_hook_values.items():
422
- current_value = getattr(instance, field_name)
423
- if current_value != pre_hook_value:
424
- hook_modified_fields.add(field_name)
425
-
426
- hook_modified_fields = list(hook_modified_fields)
104
+ # Persist hook modifications
105
+ hook_modified_fields = self._detect_modified_fields(instances, originals)
427
106
  if hook_modified_fields:
428
- logger.debug(
429
- f"Running bulk_update for hook-modified fields: {hook_modified_fields}"
430
- )
431
- # Use bulk_update to persist hook modifications, bypassing hooks to avoid recursion
432
107
  model_cls.objects.bulk_update(
433
108
  instances, hook_modified_fields, bypass_hooks=True
434
109
  )
435
-
436
- # Salesforce-style: Always run AFTER_UPDATE hooks unless explicitly bypassed
437
- if not current_bypass_hooks:
438
- logger.debug("update: running AFTER_UPDATE")
439
- engine.run(model_cls, AFTER_UPDATE, instances, originals, ctx=ctx)
440
110
  else:
441
- logger.debug("update: AFTER_UPDATE explicitly bypassed")
111
+ # For regular updates: hooks first, then database
112
+ # Apply field updates to instances
113
+ for instance in instances:
114
+ for field, value in kwargs.items():
115
+ setattr(instance, field, value)
116
+
117
+ # Run hooks
118
+ engine.run(model_cls, VALIDATE_UPDATE, instances, originals, ctx=ctx)
119
+ engine.run(model_cls, BEFORE_UPDATE, instances, originals, ctx=ctx)
120
+
121
+ # Execute database update with hook modifications
122
+ update_count = super().update(**kwargs)
123
+
124
+ # Detect and persist additional hook modifications
125
+ hook_modified_fields = self._detect_modified_fields(instances, originals)
126
+ extra_fields = [f for f in hook_modified_fields if f not in kwargs]
127
+ if extra_fields:
128
+ model_cls.objects.bulk_update(
129
+ instances, extra_fields, bypass_hooks=True
130
+ )
131
+
132
+ # Always run AFTER_UPDATE hooks
133
+ engine.run(model_cls, AFTER_UPDATE, instances, originals, ctx=ctx)
442
134
 
443
135
  return update_count
444
136
 
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "django-bulk-hooks"
3
- version = "0.1.247"
3
+ version = "0.1.248"
4
4
  description = "Hook-style hooks for Django bulk operations like bulk_create and bulk_update."
5
5
  authors = ["Konrad Beck <konrad.beck@merchantcapital.co.za>"]
6
6
  readme = "README.md"