surreal-orm-lite 0.36.4__tar.gz → 0.36.5__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.
Files changed (50) hide show
  1. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/CHANGELOG.md +45 -0
  2. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/PKG-INFO +15 -7
  3. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/README.md +14 -6
  4. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/pyproject.toml +1 -1
  5. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/__init__.py +1 -1
  6. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/cache.py +21 -8
  7. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/edge.py +14 -7
  8. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/model_base.py +145 -50
  9. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/query_set.py +84 -31
  10. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/transaction.py +5 -4
  11. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/.gitignore +0 -0
  12. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/LICENSE +0 -0
  13. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/Makefile +0 -0
  14. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/_sdk.py +0 -0
  15. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/aggregations.py +0 -0
  16. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/auth.py +0 -0
  17. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/changefeed.py +0 -0
  18. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/concurrency.py +0 -0
  19. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/connection_config.py +0 -0
  20. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/connection_manager.py +0 -0
  21. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/constants.py +0 -0
  22. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/decoding.py +0 -0
  23. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/define_parser.py +0 -0
  24. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/embedded.py +0 -0
  25. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/encoding.py +0 -0
  26. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/enum.py +0 -0
  27. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/exceptions.py +0 -0
  28. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/functions.py +0 -0
  29. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/geo.py +0 -0
  30. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/introspection.py +0 -0
  31. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/live.py +0 -0
  32. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/model_auth.py +0 -0
  33. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/model_ddl.py +0 -0
  34. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/model_generator.py +0 -0
  35. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/py.typed +0 -0
  36. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/q.py +0 -0
  37. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/routing.py +0 -0
  38. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/schema.py +0 -0
  39. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/schema_state.py +0 -0
  40. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/search.py +0 -0
  41. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/signals.py +0 -0
  42. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/subquery.py +0 -0
  43. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/surql_literal.py +0 -0
  44. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/testing/__init__.py +0 -0
  45. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/testing/database.py +0 -0
  46. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/testing/fixtures.py +0 -0
  47. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/time_travel.py +0 -0
  48. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/types.py +0 -0
  49. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/utils.py +0 -0
  50. {surreal_orm_lite-0.36.4 → surreal_orm_lite-0.36.5}/src/surreal_orm_lite/vector.py +0 -0
@@ -5,6 +5,51 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.36.5] - 2026-10-24
9
+
10
+ Follow-up to v0.36.1 (#315): a queryset write that the ORM refuses, and an instance write
11
+ refused for one of its arguments, now leave the transaction and the query cache as they were.
12
+ No new public API.
13
+
14
+ ### Fixed
15
+
16
+ - **A refused queryset write no longer marks its table as written** (#320).
17
+ `objects(tx=tx).bulk_create()`, `bulk_update()`, `bulk_delete()` and `patch()` ran their
18
+ materialized-view and `as_of()` refusals, `bulk_create()`'s check of a snapshot in its list,
19
+ `bulk_update()`'s check of a subquery value or a computed field and `patch()`'s check of its
20
+ operations after the ORM had noted the table on the transaction. The refused call queued no
21
+ statement but left the table noted: a caller that caught the error and kept the transaction had
22
+ a later `define_indexes(tx=tx)` on that table refused by the v0.35.3 check (#304), and the
23
+ commit dropped the table's cached reads although nothing was written. Outside a transaction,
24
+ the refused call (a queryset read `as_of()` included, and `delete_table()` on a view or under
25
+ `as_of()`) put the table in flight and dropped its cached reads. These refusals now run before
26
+ anything is noted: the transaction keeps no statement and no table, `define_indexes(tx=tx)` is
27
+ accepted, and no cached read is dropped, with a transaction or without.
28
+ - **An instance write refused for one of its arguments no longer marks its table as written**
29
+ (#320). `update()` and `delete()` without an id, `patch()` refused for its operations, a
30
+ computed field or a missing id, `merge()` refused for its fields, `server_values`/`extra_vars`
31
+ or a missing id, `save()` refused for `server_values`/`extra_vars`, the `atomic_*()` helpers
32
+ refused for their amount, field, values or a missing id, and an edge's `save(server_values=…)`
33
+ or `save(extra_vars=…)` had the same effect as above, with `tx=` or without. These checks now
34
+ run right after the model's own refusals (materialized view, snapshot, excluded signup field)
35
+ and before anything is noted. Error types, messages and the refusal order are unchanged: the
36
+ connection, the model's refusals, then the arguments (`update()` and `patch()` still build their
37
+ payload before reading the id). The bookkeeping is client-side: the behaviour is the same on
38
+ SurrealDB 2.x and 3.x and on both transaction strategies.
39
+
40
+ ### Notes
41
+
42
+ - A few refusals still run after the table is noted (`upsert()` without an id, a buffered
43
+ `save(tx=…)` without an id, the argument checks of `relate()`, `remove_relation()` and
44
+ `remove_all_relations()`, among others); they are tracked in #325.
45
+ - **Docs**: the README sections "Snapshots" and "What a time-travel queryset refuses" (27),
46
+ "Writes are refused" (33) and the `define_indexes(tx=…)` note of "Transactions" (36), and the
47
+ docstrings of the affected writes, say that a refused write leaves the transaction and the query
48
+ cache as they were. No behaviour-table row: the change is client-side and identical on both
49
+ lines.
50
+ - Server pins unchanged: tested against SurrealDB 3.3.4 and 2.7.0, plus 3.1.5 for backward
51
+ compatibility.
52
+
8
53
  ## [0.36.4] - 2026-10-24
9
54
 
10
55
  Follow-ups to the review of v0.36.2 (#322): an index that `remove_index(tx=…)` removed earlier
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: surreal-orm-lite
3
- Version: 0.36.4
3
+ Version: 0.36.5
4
4
  Summary: Lightweight Django-style ORM for SurrealDB using the official Python SDK. Async support with Pydantic validation.
5
5
  Project-URL: Homepage, https://github.com/EulogySnowfall/SurrealDB-ORM-lite
6
6
  Project-URL: Documentation, https://github.com/EulogySnowfall/SurrealDB-ORM-lite
@@ -3395,8 +3395,9 @@ check. The moment is always a bound parameter.
3395
3395
  The instances a time-travel read returns are **snapshots**, read-only: `save()`, `update()`,
3396
3396
  `merge()`, `patch()`, `upsert()`, `delete()`, the `atomic_*()` methods, `relate()`,
3397
3397
  `remove_relation()` and `remove_all_relations()` raise `SurrealDbError` before any signal or
3398
- request, and `bulk_create()` refuses a snapshot in its list. To restore a past state, build a new
3399
- instance from the snapshot:
3398
+ request, and `bulk_create()` refuses a snapshot in its list. A refused write leaves a transaction
3399
+ as it was (no statement, its table not counted as written) and drops no cached read. To restore a
3400
+ past state, build a new instance from the snapshot:
3400
3401
 
3401
3402
  ```python
3402
3403
  from surreal_orm_lite import SurrealDbError
@@ -3450,9 +3451,9 @@ assert old_desk != current_desk and old_desk.model_dump() == current_desk.model_
3450
3451
  A time-travel read is read-only and cannot be streamed: `bulk_create()`, `bulk_update()`,
3451
3452
  `bulk_delete()`, `patch()`, `update_or_create()`, `get_or_create()`, `delete_table()`, `query()`,
3452
3453
  `live()`, `watch()` and `changes()` raise `SurrealDbError` on a queryset with `as_of()`, before
3453
- any request. History cannot join a transaction: `Model.objects(tx=...).as_of(...)` raises at the
3454
- call. On the embedded engine, a URL that keeps no history raises before any request, naming
3455
- `surrealkv+versioned://`.
3454
+ any request and without dropping any cached read. History cannot join a transaction:
3455
+ `Model.objects(tx=...).as_of(...)` raises at the call. On the embedded engine, a URL that keeps
3456
+ no history raises before any request, naming `surrealkv+versioned://`.
3456
3457
 
3457
3458
  #### SurrealDB 2.x without versioned storage
3458
3459
 
@@ -4955,6 +4956,10 @@ print([(str(order.id), order.amount) for order in await PaidOrder.objects().orde
4955
4956
  `bulk_delete()`, `patch()`, `update_or_create()`, `get_or_create()` (even when the record exists) and
4956
4957
  `delete_table()`. The message starts with the full ORM's `Cannot modify materialized view '<table>'` and names the
4957
4958
  call: write to the tables the view selects from instead.
4959
+ - The refusal comes before the call's own argument checks (a missing id, an invalid patch operation, a snapshot in
4960
+ `bulk_create()`'s list…). A refused call, under `tx=` or `objects(tx=…)`, leaves the transaction as it was: no
4961
+ statement, and its table is not counted as written, so a later `define_indexes(tx=…)` of the model in the block is
4962
+ not refused for it and the commit drops no cached read. Outside a transaction it drops no cached read either.
4958
4963
  - `refresh()`, `relate()`, `remove_relation()`, `remove_all_relations()`, `define_events()` and `remove_event()` stay
4959
4964
  allowed: they do not write the view's table.
4960
4965
  - Raw SurrealQL (`raw_query()`, `QuerySet.query()`, the client's `query()`) is not checked: SurrealDB 3.2 and later
@@ -6104,7 +6109,10 @@ print(await NoteV2.objects().search(text="physics").count())
6104
6109
  has already written records to the model's table with the ORM (`save()`, `objects(tx=…).bulk_create()`, …). The
6105
6110
  refusal covers every kind of index, not only full-text ones: a search would miss those records, and a `UNIQUE` index
6106
6111
  missing them would not enforce uniqueness for them. The refusal does not fail the block. `define_table(tx=…)`,
6107
- `define_relation(tx=…)` and a write to another table do not count; a raw `tx.add()` is not tracked.
6112
+ `define_relation(tx=…)` and a write to another table do not count, nor does a write the ORM refused for a
6113
+ materialized view or a snapshot read with `as_of()` (a snapshot in `bulk_create()`'s list included), an `update()`,
6114
+ `merge()`, `patch()`, `delete()` or `atomic_*()` call refused for a missing id, or a `patch()` refused for its
6115
+ operations; a raw `tx.add()` is not tracked.
6108
6116
  - Prefer `define_indexes()` outside the block: on SurrealDB 2.x, a write to a table that held records, after its index
6109
6117
  in the same block, fails the commit with a retryable `SurrealDbConflictError` that a retry meets again; so does a
6110
6118
  block that removes an index of a table that held records and defines it again, where the index stands as before.
@@ -3344,8 +3344,9 @@ check. The moment is always a bound parameter.
3344
3344
  The instances a time-travel read returns are **snapshots**, read-only: `save()`, `update()`,
3345
3345
  `merge()`, `patch()`, `upsert()`, `delete()`, the `atomic_*()` methods, `relate()`,
3346
3346
  `remove_relation()` and `remove_all_relations()` raise `SurrealDbError` before any signal or
3347
- request, and `bulk_create()` refuses a snapshot in its list. To restore a past state, build a new
3348
- instance from the snapshot:
3347
+ request, and `bulk_create()` refuses a snapshot in its list. A refused write leaves a transaction
3348
+ as it was (no statement, its table not counted as written) and drops no cached read. To restore a
3349
+ past state, build a new instance from the snapshot:
3349
3350
 
3350
3351
  ```python
3351
3352
  from surreal_orm_lite import SurrealDbError
@@ -3399,9 +3400,9 @@ assert old_desk != current_desk and old_desk.model_dump() == current_desk.model_
3399
3400
  A time-travel read is read-only and cannot be streamed: `bulk_create()`, `bulk_update()`,
3400
3401
  `bulk_delete()`, `patch()`, `update_or_create()`, `get_or_create()`, `delete_table()`, `query()`,
3401
3402
  `live()`, `watch()` and `changes()` raise `SurrealDbError` on a queryset with `as_of()`, before
3402
- any request. History cannot join a transaction: `Model.objects(tx=...).as_of(...)` raises at the
3403
- call. On the embedded engine, a URL that keeps no history raises before any request, naming
3404
- `surrealkv+versioned://`.
3403
+ any request and without dropping any cached read. History cannot join a transaction:
3404
+ `Model.objects(tx=...).as_of(...)` raises at the call. On the embedded engine, a URL that keeps
3405
+ no history raises before any request, naming `surrealkv+versioned://`.
3405
3406
 
3406
3407
  #### SurrealDB 2.x without versioned storage
3407
3408
 
@@ -4904,6 +4905,10 @@ print([(str(order.id), order.amount) for order in await PaidOrder.objects().orde
4904
4905
  `bulk_delete()`, `patch()`, `update_or_create()`, `get_or_create()` (even when the record exists) and
4905
4906
  `delete_table()`. The message starts with the full ORM's `Cannot modify materialized view '<table>'` and names the
4906
4907
  call: write to the tables the view selects from instead.
4908
+ - The refusal comes before the call's own argument checks (a missing id, an invalid patch operation, a snapshot in
4909
+ `bulk_create()`'s list…). A refused call, under `tx=` or `objects(tx=…)`, leaves the transaction as it was: no
4910
+ statement, and its table is not counted as written, so a later `define_indexes(tx=…)` of the model in the block is
4911
+ not refused for it and the commit drops no cached read. Outside a transaction it drops no cached read either.
4907
4912
  - `refresh()`, `relate()`, `remove_relation()`, `remove_all_relations()`, `define_events()` and `remove_event()` stay
4908
4913
  allowed: they do not write the view's table.
4909
4914
  - Raw SurrealQL (`raw_query()`, `QuerySet.query()`, the client's `query()`) is not checked: SurrealDB 3.2 and later
@@ -6053,7 +6058,10 @@ print(await NoteV2.objects().search(text="physics").count())
6053
6058
  has already written records to the model's table with the ORM (`save()`, `objects(tx=…).bulk_create()`, …). The
6054
6059
  refusal covers every kind of index, not only full-text ones: a search would miss those records, and a `UNIQUE` index
6055
6060
  missing them would not enforce uniqueness for them. The refusal does not fail the block. `define_table(tx=…)`,
6056
- `define_relation(tx=…)` and a write to another table do not count; a raw `tx.add()` is not tracked.
6061
+ `define_relation(tx=…)` and a write to another table do not count, nor does a write the ORM refused for a
6062
+ materialized view or a snapshot read with `as_of()` (a snapshot in `bulk_create()`'s list included), an `update()`,
6063
+ `merge()`, `patch()`, `delete()` or `atomic_*()` call refused for a missing id, or a `patch()` refused for its
6064
+ operations; a raw `tx.add()` is not tracked.
6057
6065
  - Prefer `define_indexes()` outside the block: on SurrealDB 2.x, a write to a table that held records, after its index
6058
6066
  in the same block, fails the commit with a retryable `SurrealDbConflictError` that a retry meets again; so does a
6059
6067
  block that removes an index of a table that held records and defines it again, where the index stands as before.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "surreal-orm-lite"
3
- version = "0.36.4"
3
+ version = "0.36.5"
4
4
  description = "Lightweight Django-style ORM for SurrealDB using the official Python SDK. Async support with Pydantic validation."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -1,4 +1,4 @@
1
- __version__ = "0.36.4"
1
+ __version__ = "0.36.5"
2
2
 
3
3
  from ._sdk import BoundExcluded, BoundIncluded
4
4
  from .aggregations import Aggregation, Avg, Count, Max, Min, Sum
@@ -755,10 +755,10 @@ _MODEL_RESOLVERS: Final = frozenset({"self", "cls", "edge"})
755
755
  def _resolve(
756
756
  of: _Of, first: str, bound: inspect.BoundArguments, has_tx: bool, deletes: bool
757
757
  ) -> tuple[frozenset[str] | None, Any]:
758
- """The tables a call writes and the transaction it joins; every table when resolving raises."""
758
+ """The tables a call writes and the transaction it joins; every table when resolving raises. *bound* has its
759
+ defaults applied."""
759
760
  tx: Any = None
760
761
  try:
761
- bound.apply_defaults()
762
762
  if has_tx:
763
763
  tx = bound.arguments.get("tx")
764
764
  if of == "all":
@@ -791,7 +791,12 @@ def _note_records(tables: frozenset[str] | None, tx: Any) -> None:
791
791
 
792
792
 
793
793
  def invalidates(
794
- of: _Of, *, deletes: bool = False, records: bool = True, refuse: Callable[[Any], None] | None = None
794
+ of: _Of,
795
+ *,
796
+ deletes: bool = False,
797
+ records: bool = True,
798
+ refuse: Callable[[Any], None] | None = None,
799
+ refuse_args: Callable[[Mapping[str, Any]], None] | None = None,
795
800
  ) -> Callable[[F], F]:
796
801
  """Decorate an ORM write method so that it invalidates the cached reads it can change.
797
802
 
@@ -813,11 +818,16 @@ def invalidates(
813
818
  on the transaction, so a refused write invalidates nothing. The transaction is read statically, never asked. A
814
819
  queryset's transaction is checked by ``objects(tx=)``.
815
820
 
816
- ``refuse`` (issue #315) runs the method's own refusals — the model's materialized-view, snapshot and excluded
817
- signup field checks — with the call's first argument, right after that connection check and before the tables
818
- are noted on the transaction or put in flight, with a transaction or without. Whatever it raises propagates: a
819
- write it refuses leaves the transaction as it was (no statement, no table noted) and invalidates nothing. It is
820
- not called when the arguments do not bind (Python raises the function's own error).
821
+ ``refuse`` (issue #315) runs the method's own refusals with the call's first argument: the model's
822
+ materialized-view, snapshot and excluded signup field checks, or a queryset's materialized-view and ``as_of()``
823
+ checks (issue #320). Then ``refuse_args`` (issue #320) runs the checks of the call's other arguments that need no
824
+ request — a missing id, invalid patch operations, ``extra_vars`` without ``server_values``, a snapshot in
825
+ ``bulk_create()``'s list… — with the bound arguments by name, defaults applied. Both run right after that
826
+ connection check and before the tables are noted on the transaction or put in flight, with a transaction or
827
+ without, so the refusal order is the connection, the method's own refusals, then the arguments. They send nothing
828
+ and never ask the transaction. Whatever they raise propagates: a write they refuse leaves the transaction as it was
829
+ (no statement, no table noted) and invalidates nothing — no table in flight, no cached read dropped. Neither is
830
+ called when the arguments do not bind (Python raises the function's own error).
821
831
  """
822
832
  if of not in _RESOLVERS:
823
833
  raise ValueError(f"invalidates() takes one of {sorted(_RESOLVERS)}, not {of!r}")
@@ -833,6 +843,7 @@ def invalidates(
833
843
  bound = signature.bind(*args, **kwargs)
834
844
  except TypeError:
835
845
  return await func(*args, **kwargs) # Python raises the function's own error
846
+ bound.apply_defaults()
836
847
  tables, tx = _resolve(of, first, bound, has_tx, deletes)
837
848
  if tx is not None and of in _MODEL_RESOLVERS and first in bound.arguments:
838
849
  arg0 = bound.arguments[first]
@@ -840,6 +851,8 @@ def invalidates(
840
851
  _routing.check_transaction(model, tx, f"{model.__name__}.{func.__name__}()")
841
852
  if refuse is not None and first in bound.arguments:
842
853
  refuse(bound.arguments[first])
854
+ if refuse_args is not None:
855
+ refuse_args(bound.arguments)
843
856
  if records and tx is not None:
844
857
  _note_records(tables, tx)
845
858
  async with writing(tables, tx):
@@ -63,6 +63,17 @@ _GUARDED_INSERT = (
63
63
  )
64
64
 
65
65
 
66
+ def _save_arguments(arguments: Mapping[str, Any]) -> None:
67
+ """An edge's ``save()`` argument check, for ``invalidates(refuse_args=…)`` (#320): ``server_values`` and
68
+ ``extra_vars`` are refused, after the snapshot refusal and before the edge table is noted on the transaction or
69
+ put in flight — ``INSERT RELATION`` cannot evaluate ``SET`` expressions."""
70
+ if arguments["server_values"] or arguments["extra_vars"]:
71
+ raise SurrealDbError(
72
+ "save(server_values=) is not available on an edge: INSERT RELATION cannot evaluate SET "
73
+ "expressions. Use DEFINE FIELD … DEFAULT/VALUE on the edge table."
74
+ )
75
+
76
+
66
77
  def _check_edge_id(model: BaseSurrealModel) -> None:
67
78
  """Refuse, before any call, an edge id the server would misread.
68
79
 
@@ -454,7 +465,7 @@ class BaseSurrealEdge(BaseSurrealModel):
454
465
  """``in_``/``out``: SurrealDB ignores a change to an existing edge's endpoints."""
455
466
  return _ENDPOINT_FIELDS
456
467
 
457
- @_cache.invalidates("self", refuse=_write_refusals("save()"))
468
+ @_cache.invalidates("self", refuse=_write_refusals("save()"), refuse_args=_save_arguments)
458
469
  async def save(
459
470
  self,
460
471
  tx: Transaction | None = None,
@@ -490,16 +501,12 @@ class BaseSurrealEdge(BaseSurrealModel):
490
501
 
491
502
  Raises:
492
503
  SurrealDbError: the edge was read with ``as_of()`` (a snapshot) — before its table is noted
493
- on the transaction (#315); ``server_values``/``extra_vars`` given (before any call); a
504
+ on the transaction (#315); ``server_values``/``extra_vars`` given — after the snapshot
505
+ check, before any call and before its table is noted on the transaction (#320); a
494
506
  duplicate id, a refused or rejected write.
495
507
  SurrealDbNotFoundError: an ``ENFORCED`` endpoint that does not exist.
496
508
  ValueError: an id that is a ``RecordID`` of another table, or a ``bool``.
497
509
  """
498
- if server_values or extra_vars:
499
- raise SurrealDbError(
500
- "save(server_values=) is not available on an edge: INSERT RELATION cannot evaluate SET "
501
- "expressions. Use DEFINE FIELD … DEFAULT/VALUE on the edge table."
502
- )
503
510
  return await super().save(tx=tx)
504
511
 
505
512
  async def upsert(self, tx: Transaction | None = None) -> Self:
@@ -595,7 +595,9 @@ def _write_refusals(call: str, *, view: bool = True, signup: bool = False) -> Ca
595
595
  :meth:`~BaseSurrealModel.upsert`), SG1 (:meth:`BaseSurrealModel._reject_signup_excluded`). The wrapper calls it
596
596
  with the instance after ``routing.check_transaction()`` and before the write's tables are noted on the transaction
597
597
  or put in flight, so a refused write leaves the transaction as it was: no statement, no table noted for
598
- ``define_indexes(tx=…)`` (#304) or the query cache. A write decorated with it does not repeat these checks.
598
+ ``define_indexes(tx=…)`` (#304) or the query cache. A write decorated with it does not repeat these checks. The
599
+ call's argument checks (a missing id, invalid patch operations…) run right after it, in the write's
600
+ ``invalidates(refuse_args=…)`` (#320), so these refusals come first when both apply.
599
601
  """
600
602
 
601
603
  def refuse(instance: Any) -> None:
@@ -608,6 +610,95 @@ def _write_refusals(call: str, *, view: bool = True, signup: bool = False) -> Ca
608
610
  return refuse
609
611
 
610
612
 
613
+ # The argument checks of the instance writes, for ``invalidates(refuse_args=…)`` (issue #320). The wrapper calls each
614
+ # with the call's bound arguments, after the model's own refusals (``_write_refusals()``) and before the write's tables
615
+ # are noted on the transaction or put in flight: a call they refuse leaves the transaction as it was — no statement,
616
+ # no table noted for ``define_indexes(tx=…)`` (#304) or the query cache — and drops no cached read. Each keeps the
617
+ # order and the messages the method's body had; none sends anything or asks the transaction.
618
+
619
+ _UPDATE_WITHOUT_ID = "Can't update data, no id found."
620
+ _DELETE_WITHOUT_ID = "Can't delete data, no id found."
621
+ _PATCH_WITHOUT_ID = "patch() requires an explicit id (there is nothing to patch without one)."
622
+ _ATOMIC_WITHOUT_ID = "atomic operations require an explicit id."
623
+
624
+
625
+ def _save_arguments(arguments: Mapping[str, Any]) -> None:
626
+ """``save()``: the ``server_values``/``extra_vars`` pair (:meth:`BaseSurrealModel._validate_server_values`), then a
627
+ computed field or an edge endpoint among the server values."""
628
+ instance, server_values = arguments["self"], arguments["server_values"]
629
+ instance._validate_server_values(server_values, arguments["extra_vars"])
630
+ if server_values:
631
+ instance._reject_computed_writes(server_values, "save(server_values=)")
632
+
633
+
634
+ def _update_arguments(arguments: Mapping[str, Any]) -> None:
635
+ """``update()``: an instance without an id. ``update()`` builds what it writes before it reads the id, so without
636
+ an id the payload is built here first: one that cannot be built raises its own error, as before."""
637
+ instance = arguments["self"]
638
+ if instance.get_id() is None:
639
+ instance._write_payload(replace=True)
640
+ raise SurrealDbError(_UPDATE_WITHOUT_ID)
641
+
642
+
643
+ def _merge_arguments(arguments: Mapping[str, Any]) -> None:
644
+ """``merge()``: a computed field or an edge endpoint among the fields, the ``server_values``/``extra_vars`` pair,
645
+ a computed field or an endpoint among the server values, then an instance without an id."""
646
+ instance, data, server_values = arguments["self"], arguments["data"], arguments["server_values"]
647
+ instance._reject_computed_writes(data, "merge()")
648
+ instance._validate_server_values(server_values, arguments["extra_vars"])
649
+ if server_values:
650
+ instance._reject_computed_writes(server_values, "merge(server_values=)")
651
+ if instance.get_id() is None:
652
+ raise SurrealDbError(f"No Id for the data to merge: {data}")
653
+
654
+
655
+ def _patch_arguments(arguments: Mapping[str, Any]) -> None:
656
+ """``patch()``: the JSON Patch document (:func:`~surreal_orm_lite.utils.validate_patch_operations`), the computed
657
+ fields and edge endpoints it writes, then an instance without an id. ``patch()`` rewrites the pointers to columns
658
+ before it reads the id, so without an id they are rewritten here first, as before."""
659
+ instance, operations = arguments["self"], arguments["operations"]
660
+ validate_patch_operations(operations)
661
+ instance._reject_computed_patch(operations, "patch()")
662
+ if instance.get_id() is None:
663
+ instance._columns_for_patch(operations)
664
+ raise SurrealDbError(_PATCH_WITHOUT_ID)
665
+
666
+
667
+ def _reject_duration_amount(field: str, amount: object) -> None:
668
+ """Refuse a duration as ``atomic_increment()``'s amount (v0.23.0): SurrealDB 2.x ignores ``+=`` with a duration."""
669
+ if isinstance(amount, (timedelta, SdkDuration, Duration)):
670
+ raise TypeError(
671
+ f"atomic_increment() adds a number, not a duration ({amount!r}): SurrealDB 2.x ignores += with a "
672
+ "duration, so the result would differ between server lines. "
673
+ f"Set the new value with merge({field}=…) instead."
674
+ )
675
+
676
+
677
+ def _atomic_arguments(*, amount: bool = False, values: bool = False) -> Callable[[Mapping[str, Any]], None]:
678
+ """An atomic helper's checks, in this order: a duration ``amount`` (``amount=True``: ``atomic_increment()``), the
679
+ field (:meth:`BaseSurrealModel._validate_atomic_field`), a ``values`` that is not a list (``values=True``: the
680
+ ``atomic_*_many()`` helpers), then an instance without an id. The helper's body reads the field's column and the
681
+ list of values again for what it writes."""
682
+
683
+ def refuse(arguments: Mapping[str, Any]) -> None:
684
+ instance = arguments["self"]
685
+ if amount:
686
+ _reject_duration_amount(arguments["field"], arguments["amount"])
687
+ instance._validate_atomic_field(arguments["field"])
688
+ if values:
689
+ instance._as_value_list(arguments["values"])
690
+ if instance.get_id() is None:
691
+ raise SurrealDbError(_ATOMIC_WITHOUT_ID)
692
+
693
+ return refuse
694
+
695
+
696
+ def _delete_arguments(arguments: Mapping[str, Any]) -> None:
697
+ """``delete()``: an instance without an id."""
698
+ if arguments["self"].get_id() is None:
699
+ raise SurrealDbError(_DELETE_WITHOUT_ID)
700
+
701
+
611
702
  class SurrealConfigDict(ConfigDict, total=False):
612
703
  """
613
704
  SurrealConfigDict is a configuration dictionary for SurrealDB models.
@@ -822,7 +913,8 @@ class BaseSurrealModel(BaseModel):
822
913
  Called at the start of every instance write — right after the materialized-view check of the writes that
823
914
  have one (:meth:`_reject_view_write`, v0.32.0) —, so no signal, transaction or request runs before it: by the
824
915
  write's ``invalidates(refuse=…)`` (:func:`_write_refusals`), before its tables are noted on the transaction, so
825
- a refused write leaves the transaction as it was (#315). The marker is read through :func:`_snapshot_moment`,
916
+ a refused write leaves the transaction as it was (#315), and before the call's argument checks (a missing id,
917
+ invalid patch operations…, #320). The marker is read through :func:`_snapshot_moment`,
826
918
  the only reader (an instance pickled by v0.25.x may have no private state).
827
919
 
828
920
  Raises:
@@ -1550,10 +1642,13 @@ class BaseSurrealModel(BaseModel):
1550
1642
 
1551
1643
  SurrealDB computes a view's records from its ``view_query``, so the ORM never writes them: the first statement
1552
1644
  of every ORM write of the model — the instance writes and the queryset's — before the snapshot check, any
1553
- signal, transaction use or request. An instance write runs it through its ``invalidates(refuse=…)``
1554
- (:func:`_write_refusals`), before its table is noted on the transaction, which a refused write leaves as it
1555
- was (#315). The relation helpers write the edge table, not the view, and stay allowed; raw SurrealQL is never
1556
- guarded.
1645
+ signal, transaction use or request. Every one runs it through its ``invalidates(refuse=…)`` — an instance write
1646
+ through :func:`_write_refusals` (#315), ``bulk_create()``, ``bulk_update()``, ``bulk_delete()``, ``patch()``
1647
+ and ``delete_table()`` through ``query_set._queryset_refusals()`` (#320) —, before its table is noted on the
1648
+ transaction or put in flight: a refused write leaves the transaction as it was and drops no cached read.
1649
+ ``update_or_create()`` and ``get_or_create()`` run it at their start, before any lookup. It comes before the
1650
+ call's argument checks too. The relation helpers write the edge table, not the view, and stay allowed; raw
1651
+ SurrealQL is never guarded.
1557
1652
 
1558
1653
  Raises:
1559
1654
  TypeError: the model is a materialized view (W1, naming the class and *call*).
@@ -3172,7 +3267,7 @@ class BaseSurrealModel(BaseModel):
3172
3267
  return await self.save(tx=tx)
3173
3268
  return await self._save_with_signals(functools.partial(self._do_save, keep=keep), tx)
3174
3269
 
3175
- @_cache.invalidates("self", refuse=_write_refusals("save()"))
3270
+ @_cache.invalidates("self", refuse=_write_refusals("save()"), refuse_args=_save_arguments)
3176
3271
  async def save(
3177
3272
  self,
3178
3273
  tx: Transaction | None = None,
@@ -3219,10 +3314,12 @@ class BaseSurrealModel(BaseModel):
3219
3314
  In a **buffered** transaction (HTTP or SurrealDB 2.6.x) the server-computed
3220
3315
  values are unknown until commit, so the instance keeps its pre-save values for
3221
3316
  those fields — ``refresh()`` after commit if you need them.
3317
+
3318
+ An invalid ``server_values``/``extra_vars`` pair, or a computed field or an edge endpoint in
3319
+ ``server_values``, is refused before any signal or request and before the model's table is
3320
+ noted on ``tx``, which a refused call leaves as it was (#320).
3222
3321
  """
3223
- self._validate_server_values(server_values, extra_vars)
3224
3322
  if server_values:
3225
- self._reject_computed_writes(server_values, "save(server_values=)")
3226
3323
  do_op = functools.partial(self._do_save_server, server_values=server_values, extra_vars=extra_vars)
3227
3324
  return await self._save_with_signals(do_op, tx)
3228
3325
  return await self._save_with_signals(self._do_save, tx)
@@ -3512,7 +3609,7 @@ class BaseSurrealModel(BaseModel):
3512
3609
  """
3513
3610
  return await self._save_with_signals(self._do_upsert, tx)
3514
3611
 
3515
- @_cache.invalidates("self", refuse=_write_refusals("update()", signup=True))
3612
+ @_cache.invalidates("self", refuse=_write_refusals("update()", signup=True), refuse_args=_update_arguments)
3516
3613
  async def update(self, tx: Transaction | None = None) -> Any:
3517
3614
  """
3518
3615
  Update the model instance to the database.
@@ -3557,10 +3654,11 @@ class BaseSurrealModel(BaseModel):
3557
3654
  The updated row as the SDK reads it (``[]`` for a record that does not exist), or
3558
3655
  ``None`` in a transaction.
3559
3656
 
3560
- The view, snapshot and SG1 refusals below come before the model's table is noted on
3561
- ``tx``: a call they refuse leaves nothing on the transaction — no statement, and no table
3562
- noted as written, so a later ``define_indexes(tx=…)`` of the model is not refused for it
3563
- and the commit drops no cached read for it (#315).
3657
+ The view, snapshot and SG1 refusals below, then the missing id, come before the model's
3658
+ table is noted on ``tx``: a call they refuse leaves nothing on the transaction — no
3659
+ statement, and no table noted as written, so a later ``define_indexes(tx=…)`` of the model
3660
+ is not refused for it and the commit drops no cached read for it (#315, #320). Outside a
3661
+ transaction, it drops no cached read either.
3564
3662
 
3565
3663
  Raises:
3566
3664
  TypeError: the model is a materialized view (W1); or an auth model
@@ -3573,8 +3671,7 @@ class BaseSurrealModel(BaseModel):
3573
3671
  sender = self.__class__
3574
3672
  data = self._write_payload(replace=True)
3575
3673
  record_id = self._record_id()
3576
- if record_id is None:
3577
- raise SurrealDbError("Can't update data, no id found.")
3674
+ assert record_id is not None # refused by _update_arguments() (#320)
3578
3675
  content, bound = replace_content(data)
3579
3676
 
3580
3677
  has_signals = pre_update.has_handlers(sender) or post_update.has_handlers(sender) or around_update.has_handlers(sender)
@@ -3644,8 +3741,7 @@ class BaseSurrealModel(BaseModel):
3644
3741
  """
3645
3742
  sender = self.__class__
3646
3743
  record_id = self._record_id()
3647
- if record_id is None:
3648
- raise SurrealDbError(f"No Id for the data to merge: {data}")
3744
+ assert record_id is not None # refused by merge()'s _merge_arguments() (#320)
3649
3745
 
3650
3746
  # Columns on the wire, Python names in the signal payload and the local apply below.
3651
3747
  merged: dict[str, Any] = {**self._columns_for(data), **self._columns_for(server_values)}
@@ -3678,7 +3774,7 @@ class BaseSurrealModel(BaseModel):
3678
3774
  await post_update.send(sender, instance=self, update_fields=update_fields)
3679
3775
  return None
3680
3776
 
3681
- @_cache.invalidates("self", refuse=_write_refusals("merge()"))
3777
+ @_cache.invalidates("self", refuse=_write_refusals("merge()"), refuse_args=_merge_arguments)
3682
3778
  async def merge(
3683
3779
  self,
3684
3780
  tx: Transaction | None = None,
@@ -3731,11 +3827,14 @@ class BaseSurrealModel(BaseModel):
3731
3827
  Example:
3732
3828
  >>> await user.merge(plan="pro", server_values={"updated_at": SurrealFunc("time::now()")})
3733
3829
  >>> await user.merge(last_seen=now, refresh=False) # fire-and-forget
3830
+
3831
+ A computed field or an edge endpoint in ``data`` (``ValueError``), an invalid
3832
+ ``server_values``/``extra_vars`` pair (``ValueError``/``TypeError``), a computed field or an
3833
+ endpoint in ``server_values`` (``ValueError``) and a missing id (``SurrealDbError``) are
3834
+ refused in this order, before any signal or request and before the model's table is noted
3835
+ on ``tx``, which a refused call leaves as it was (#320).
3734
3836
  """
3735
- self._reject_computed_writes(data, "merge()")
3736
- self._validate_server_values(server_values, extra_vars)
3737
3837
  if server_values:
3738
- self._reject_computed_writes(server_values, "merge(server_values=)")
3739
3838
  return await self._merge_server(tx, server_values, extra_vars, data, refresh)
3740
3839
 
3741
3840
  sender = self.__class__
@@ -3744,9 +3843,7 @@ class BaseSurrealModel(BaseModel):
3744
3843
  # that stays on this side of the wire — signals, the local apply — keeps `data_set`.
3745
3844
  wire_data = self._columns_for(data_set)
3746
3845
  record_id = self._record_id()
3747
-
3748
- if record_id is None:
3749
- raise SurrealDbError(f"No Id for the data to merge: {data}")
3846
+ assert record_id is not None # refused by _merge_arguments() (#320)
3750
3847
 
3751
3848
  has_signals = pre_update.has_handlers(sender) or post_update.has_handlers(sender) or around_update.has_handlers(sender)
3752
3849
 
@@ -3775,7 +3872,7 @@ class BaseSurrealModel(BaseModel):
3775
3872
 
3776
3873
  # ==================== Patch & atomic operations ====================
3777
3874
 
3778
- @_cache.invalidates("self", refuse=_write_refusals("patch()"))
3875
+ @_cache.invalidates("self", refuse=_write_refusals("patch()"), refuse_args=_patch_arguments)
3779
3876
  async def patch(self, operations: list[dict[str, Any]], tx: Transaction | None = None) -> Self:
3780
3877
  """Apply a JSON Patch (RFC 6902) to this record.
3781
3878
 
@@ -3791,14 +3888,14 @@ class BaseSurrealModel(BaseModel):
3791
3888
  Unlike ``merge``/``save`` this emits NO signals: it is a low-level atomic primitive.
3792
3889
  ``operations`` is validated then bound as data, never string-interpolated. Pointers may
3793
3890
  name a field either way — ``/password`` or its column ``/password_hash`` — and are
3794
- rewritten to the column before they are sent.
3891
+ rewritten to the column before they are sent. Invalid operations (``ValueError``), a
3892
+ computed field or an edge endpoint they write (``ValueError``) and a missing id
3893
+ (``SurrealDbError``) are refused in this order, before any request and before the model's
3894
+ table is noted on ``tx``, which a refused call leaves as it was (#320).
3795
3895
  """
3796
- validate_patch_operations(operations)
3797
- self._reject_computed_patch(operations, "patch()")
3798
3896
  operations = self._columns_for_patch(operations)
3799
3897
  record_id = self._record_id()
3800
- if record_id is None:
3801
- raise SurrealDbError("patch() requires an explicit id (there is nothing to patch without one).")
3898
+ assert record_id is not None # refused by _patch_arguments() (#320)
3802
3899
  if tx is not None:
3803
3900
  rows = await tx.add("UPDATE $rid PATCH $data;", {"rid": record_id, "data": operations})
3804
3901
  self._apply_record(rows) # interactive: applies; buffered: add() returns None → no-op (stale)
@@ -3816,11 +3913,13 @@ class BaseSurrealModel(BaseModel):
3816
3913
  Non-tx and interactive-tx apply the returned row to ``self``; a buffered tx leaves
3817
3914
  ``self`` stale (the new value is computed server-side, unknown until commit).
3818
3915
  Each helper refuses a materialized view (v0.32.0) and a snapshot (v0.26.0) under its own
3819
- name through its ``invalidates(refuse=…)`` (#315), before its field is checked.
3916
+ name through its ``invalidates(refuse=…)`` (#315), then its arguments — the amount, the
3917
+ field, the values — and a missing id through its ``invalidates(refuse_args=…)``
3918
+ (:func:`_atomic_arguments`, #320), all before its table is noted on the transaction or put
3919
+ in flight.
3820
3920
  """
3821
3921
  record_id = self._record_id()
3822
- if record_id is None:
3823
- raise SurrealDbError("atomic operations require an explicit id.")
3922
+ assert record_id is not None # refused by the helper's _atomic_arguments() (#320)
3824
3923
  vars_: dict[str, Any] = {"rid": record_id, **variables}
3825
3924
  statement = f"UPDATE $rid SET {set_expr};"
3826
3925
  if tx is not None:
@@ -3832,7 +3931,7 @@ class BaseSurrealModel(BaseModel):
3832
3931
  self._apply_record(rows)
3833
3932
  return self
3834
3933
 
3835
- @_cache.invalidates("self", refuse=_write_refusals("atomic_append()"))
3934
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_append()"), refuse_args=_atomic_arguments())
3836
3935
  async def atomic_append(self, field: str, value: Any, tx: Transaction | None = None) -> Self:
3837
3936
  """Atomically append ``value`` to an array ``field`` (duplicates allowed).
3838
3937
 
@@ -3842,7 +3941,7 @@ class BaseSurrealModel(BaseModel):
3842
3941
  column = self._validate_atomic_field(field)
3843
3942
  return await self._atomic_update(f"{column} = array::append({column}, $value)", {"value": value}, tx)
3844
3943
 
3845
- @_cache.invalidates("self", refuse=_write_refusals("atomic_remove()"))
3944
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_remove()"), refuse_args=_atomic_arguments())
3846
3945
  async def atomic_remove(self, field: str, value: Any, tx: Transaction | None = None) -> Self:
3847
3946
  """Atomically remove ALL occurrences of ``value`` from an array ``field``.
3848
3947
 
@@ -3853,7 +3952,7 @@ class BaseSurrealModel(BaseModel):
3853
3952
  column = self._validate_atomic_field(field)
3854
3953
  return await self._atomic_update(f"{column} = array::complement({column}, [$value])", {"value": value}, tx)
3855
3954
 
3856
- @_cache.invalidates("self", refuse=_write_refusals("atomic_set_add()"))
3955
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_set_add()"), refuse_args=_atomic_arguments())
3857
3956
  async def atomic_set_add(self, field: str, value: Any, tx: Transaction | None = None) -> Self:
3858
3957
  """Atomically add ``value`` to an array ``field`` only if not already present.
3859
3958
 
@@ -3863,7 +3962,7 @@ class BaseSurrealModel(BaseModel):
3863
3962
  column = self._validate_atomic_field(field)
3864
3963
  return await self._atomic_update(f"{column} = array::add({column}, $value)", {"value": value}, tx)
3865
3964
 
3866
- @_cache.invalidates("self", refuse=_write_refusals("atomic_increment()"))
3965
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_increment()"), refuse_args=_atomic_arguments(amount=True))
3867
3966
  async def atomic_increment(self, field: str, amount: Decimal | int | float = 1, tx: Transaction | None = None) -> Self:
3868
3967
  """Atomically add ``amount`` (default 1) to a numeric ``field``.
3869
3968
 
@@ -3877,12 +3976,6 @@ class BaseSurrealModel(BaseModel):
3877
3976
  A duration amount raises ``TypeError`` (v0.23.0): SurrealDB 2.x ignores ``+=`` with a
3878
3977
  duration.
3879
3978
  """
3880
- if isinstance(amount, (timedelta, SdkDuration, Duration)):
3881
- raise TypeError(
3882
- f"atomic_increment() adds a number, not a duration ({amount!r}): SurrealDB 2.x ignores += with a "
3883
- "duration, so the result would differ between server lines. "
3884
- f"Set the new value with merge({field}=…) instead."
3885
- )
3886
3979
  column = self._validate_atomic_field(field)
3887
3980
  return await self._atomic_update(f"{column} += $amount", {"amount": amount}, tx)
3888
3981
 
@@ -3895,7 +3988,7 @@ class BaseSurrealModel(BaseModel):
3895
3988
  return list(values)
3896
3989
  raise ValueError(f"values must be a list of items, got {type(values).__name__}")
3897
3990
 
3898
- @_cache.invalidates("self", refuse=_write_refusals("atomic_append_many()"))
3991
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_append_many()"), refuse_args=_atomic_arguments(values=True))
3899
3992
  async def atomic_append_many(self, field: str, values: list[Any], tx: Transaction | None = None) -> Self:
3900
3993
  """Atomically append every element of ``values`` to an array ``field`` (duplicates allowed).
3901
3994
 
@@ -3911,7 +4004,7 @@ class BaseSurrealModel(BaseModel):
3911
4004
  tx,
3912
4005
  )
3913
4006
 
3914
- @_cache.invalidates("self", refuse=_write_refusals("atomic_set_add_many()"))
4007
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_set_add_many()"), refuse_args=_atomic_arguments(values=True))
3915
4008
  async def atomic_set_add_many(self, field: str, values: list[Any], tx: Transaction | None = None) -> Self:
3916
4009
  """Atomically add every element of ``values`` to an array ``field``, skipping any already present.
3917
4010
 
@@ -3926,7 +4019,7 @@ class BaseSurrealModel(BaseModel):
3926
4019
  tx,
3927
4020
  )
3928
4021
 
3929
- @_cache.invalidates("self", refuse=_write_refusals("atomic_remove_many()"))
4022
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_remove_many()"), refuse_args=_atomic_arguments(values=True))
3930
4023
  async def atomic_remove_many(self, field: str, values: list[Any], tx: Transaction | None = None) -> Self:
3931
4024
  """Atomically remove ALL occurrences of every element of ``values`` from an array ``field``.
3932
4025
 
@@ -3940,7 +4033,7 @@ class BaseSurrealModel(BaseModel):
3940
4033
  tx,
3941
4034
  )
3942
4035
 
3943
- @_cache.invalidates("self", deletes=True, refuse=_write_refusals("delete()"))
4036
+ @_cache.invalidates("self", deletes=True, refuse=_write_refusals("delete()"), refuse_args=_delete_arguments)
3944
4037
  async def delete(self, tx: Transaction | None = None) -> None:
3945
4038
  """
3946
4039
  Delete the model instance from the database.
@@ -3953,11 +4046,13 @@ class BaseSurrealModel(BaseModel):
3953
4046
  Emits pre_delete, post_delete, and around_delete signals. In tx mode,
3954
4047
  ``around_delete`` is skipped (the write is deferred to commit) and
3955
4048
  ``post_delete`` only fires after a successful commit.
4049
+
4050
+ An instance without an id raises ``SurrealDbError`` before any signal or request, and
4051
+ before the model's table is noted on ``tx``, which it leaves as it was (#320).
3956
4052
  """
3957
4053
  sender = self.__class__
3958
4054
  record_id = self._record_id()
3959
- if record_id is None:
3960
- raise SurrealDbError("Can't delete data, no id found.")
4055
+ assert record_id is not None # refused by _delete_arguments() (#320)
3961
4056
 
3962
4057
  has_signals = pre_delete.has_handlers(sender) or post_delete.has_handlers(sender) or around_delete.has_handlers(sender)
3963
4058
 
@@ -85,6 +85,52 @@ def _unwritable_variable(field: str, name: str) -> str:
85
85
  return f"Cannot create a record from Var('{name}') given for '{field}': {why}. {advice}"
86
86
 
87
87
 
88
+ def _queryset_refusals(method: str) -> Callable[["QuerySet"], None]:
89
+ """The queryset's own refusals of the write *method* (``"bulk_update()"``), for ``invalidates(refuse=…)`` (#320).
90
+
91
+ In this order: the materialized view (W1, :meth:`BaseSurrealModel._reject_view_write`, naming
92
+ ``objects().<method>``), then a queryset read ``as_of()`` (T5, :meth:`QuerySet._reject_time_travel`). The wrapper
93
+ calls it with the queryset before the write's tables are noted on its ``objects(tx=…)`` transaction or put in
94
+ flight, so a refused write leaves the transaction as it was and drops no cached read. A write decorated with it
95
+ does not repeat these checks.
96
+ """
97
+
98
+ def refuse(queryset: "QuerySet") -> None:
99
+ queryset.model._reject_view_write(f"objects().{method}")
100
+ queryset._reject_time_travel(method)
101
+
102
+ return refuse
103
+
104
+
105
+ def _bulk_create_arguments(arguments: Mapping[str, Any]) -> None:
106
+ """:meth:`QuerySet.bulk_create`'s argument check, for ``invalidates(refuse_args=…)`` (#320): a snapshot (an
107
+ instance read with ``as_of()``, v0.26.0) in ``models`` is refused, naming its class, after the queryset's own
108
+ refusals and before anything is noted on the transaction or put in flight."""
109
+ for model in arguments["models"]:
110
+ moment = _snapshot_moment(model) if isinstance(model, BaseSurrealModel) else None
111
+ if moment is not None:
112
+ raise SurrealDbError(_time_travel.snapshot_write_refused(type(model).__name__, "bulk_create()", moment))
113
+
114
+
115
+ def _bulk_update_arguments(arguments: Mapping[str, Any]) -> None:
116
+ """:meth:`QuerySet.bulk_update`'s argument checks, for ``invalidates(refuse_args=…)`` (#320), in this order: a
117
+ value that is a subquery (v0.27.0), then a computed field or an edge endpoint among the fields to write."""
118
+ values: Mapping[str, Any] = arguments["kwargs"]
119
+ for field, value in values.items():
120
+ if _subquery.subquery_of(value) is not None:
121
+ raise ValueError(_subquery.value_written(field))
122
+ arguments["self"].model._reject_computed_writes(values, "bulk_update()")
123
+
124
+
125
+ def _patch_arguments(arguments: Mapping[str, Any]) -> None:
126
+ """:meth:`QuerySet.patch`'s argument checks, for ``invalidates(refuse_args=…)`` (#320): the JSON Patch document
127
+ (:func:`~surreal_orm_lite.utils.validate_patch_operations`), then the computed fields and edge endpoints it
128
+ writes."""
129
+ operations = arguments["operations"]
130
+ validate_patch_operations(operations)
131
+ arguments["self"].model._reject_computed_patch(operations, "patch()")
132
+
133
+
88
134
  class QuerySet:
89
135
  """
90
136
  A class used to build, execute, and manage queries on a SurrealDB table associated with a specific model.
@@ -868,8 +914,12 @@ class QuerySet:
868
914
  def _reject_time_travel(self, method: str) -> None:
869
915
  """Refuse *method* (a write or a stream, named with its ``()``) on a queryset read ``as_of()`` (v0.26.0).
870
916
 
871
- A time-travel read is read-only and cannot be streamed: called at the start of each such method — right
872
- after a write's materialized-view check (v0.32.0) —, so nothing is sent and no client is acquired.
917
+ A time-travel read is read-only and cannot be streamed, so nothing is sent and no client is acquired: each
918
+ such write runs it right after its materialized-view check (v0.32.0), and each stream (and ``query()``) at
919
+ its start. ``bulk_create()``, ``bulk_update()``, ``bulk_delete()``, ``patch()`` and ``delete_table()`` run
920
+ both in their ``invalidates(refuse=…)`` (:func:`_queryset_refusals`, #320), before their tables are noted on
921
+ the transaction or put in flight: a refused write leaves the transaction as it was and drops no cached read.
922
+ ``update_or_create()`` and ``get_or_create()`` run both at their start, before any lookup or write.
873
923
  """
874
924
  if self._as_of is not None:
875
925
  raise SurrealDbError(_time_travel.queryset_refused(method))
@@ -2040,7 +2090,7 @@ class QuerySet:
2040
2090
 
2041
2091
  return await self._cached_read("select", "", {"target": target}, tables, self.model._is_view(), run)
2042
2092
 
2043
- @_cache.invalidates("table", deletes=True)
2093
+ @_cache.invalidates("table", deletes=True, refuse=_queryset_refusals("delete_table()"))
2044
2094
  async def delete_table(self) -> bool:
2045
2095
  """
2046
2096
  Delete the associated table from the SurrealDB database.
@@ -2051,10 +2101,10 @@ class QuerySet:
2051
2101
 
2052
2102
  It runs at once, outside the queryset's ``objects(tx=)`` transaction (a rollback does
2053
2103
  not bring the rows back), so the cached reads of the table — and of every edge table,
2054
- whose edges die with the records — are invalidated when it ends, never at a commit.
2104
+ whose edges die with the records — are invalidated when it ends, never at a commit. A
2105
+ materialized view (``TypeError``) and a queryset read ``as_of()`` (``SurrealDbError``) are
2106
+ refused before any request, and drop no cached read (#320).
2055
2107
  """
2056
- self.model._reject_view_write("objects().delete_table()")
2057
- self._reject_time_travel("delete_table()")
2058
2108
  client = await self._manager().get_client()
2059
2109
  with contextlib.suppress(NotFoundError):
2060
2110
  await client.delete(self._model_table)
@@ -2377,7 +2427,7 @@ class QuerySet:
2377
2427
 
2378
2428
  # ==================== Bulk Operations ====================
2379
2429
 
2380
- @_cache.invalidates("queryset")
2430
+ @_cache.invalidates("queryset", refuse=_queryset_refusals("bulk_create()"), refuse_args=_bulk_create_arguments)
2381
2431
  async def bulk_create(self, models: list[BaseSurrealModel]) -> list[BaseSurrealModel]:
2382
2432
  """
2383
2433
  Create multiple records in a single operation.
@@ -2407,10 +2457,16 @@ class QuerySet:
2407
2457
  edge without an explicit id keeps ``id=None``). ``[]`` for an empty list, without any
2408
2458
  call.
2409
2459
 
2460
+ The materialized view, a queryset read ``as_of()``, then a snapshot in ``models`` are
2461
+ refused in this order, before any call and before the table is noted on the
2462
+ ``objects(tx=…)`` transaction or put in flight: a refused call leaves the transaction as it
2463
+ was and drops no cached read (#320).
2464
+
2410
2465
  Raises:
2411
2466
  SurrealDbError: an edge id that already exists, edges the ``PERMISSIONS`` refused, or
2412
- any other refusal of an edge batch by the server; a model read with ``as_of()``
2413
- (a read-only snapshot) in ``models``, before any call (v0.26.0).
2467
+ any other refusal of an edge batch by the server; the queryset reads ``as_of()``; a
2468
+ model read with ``as_of()`` (a read-only snapshot) in ``models``, before any call
2469
+ (v0.26.0).
2414
2470
  SurrealDbNotFoundError: an endpoint of an ``ENFORCED`` relation that does not exist.
2415
2471
  TypeError: the model is a materialized view (v0.32.0), before any call.
2416
2472
  ValueError: an edge id that is a ``RecordID`` of another table, or a ``bool``.
@@ -2425,12 +2481,6 @@ class QuerySet:
2425
2481
  Purchased(in_=bob, out=widget, quantity=1),
2426
2482
  ]) # one insert_relation() round-trip
2427
2483
  """
2428
- self.model._reject_view_write("objects().bulk_create()")
2429
- self._reject_time_travel("bulk_create()")
2430
- for model in models:
2431
- moment = _snapshot_moment(model) if isinstance(model, BaseSurrealModel) else None
2432
- if moment is not None:
2433
- raise SurrealDbError(_time_travel.snapshot_write_refused(type(model).__name__, "bulk_create()", moment))
2434
2484
  if not models:
2435
2485
  return []
2436
2486
 
@@ -2480,7 +2530,7 @@ class QuerySet:
2480
2530
  return models # buffered: not executed until commit; return inputs
2481
2531
  return cast(list[BaseSurrealModel], self.model.from_db(created))
2482
2532
 
2483
- @_cache.invalidates("queryset")
2533
+ @_cache.invalidates("queryset", refuse=_queryset_refusals("bulk_update()"), refuse_args=_bulk_update_arguments)
2484
2534
  async def bulk_update(self, **kwargs: Any) -> int:
2485
2535
  """
2486
2536
  Update all records matching the current filters.
@@ -2497,24 +2547,24 @@ class QuerySet:
2497
2547
  Returns:
2498
2548
  The number of updated records (``0`` inside a buffered transaction, whose statements run at commit).
2499
2549
 
2550
+ The materialized view, a queryset read ``as_of()``, then a subquery value and a computed field or an edge
2551
+ endpoint among the fields are refused in this order, before any request and before the table is noted on the
2552
+ ``objects(tx=…)`` transaction or put in flight: a refused call leaves the transaction as it was and drops no
2553
+ cached read (#320).
2554
+
2500
2555
  Raises:
2501
2556
  TypeError: the model is a materialized view (v0.32.0), before any request.
2557
+ SurrealDbError: the queryset reads ``as_of()``, before any request.
2502
2558
  ValueError: a value is a ``Subquery`` or a QuerySet (v0.27.0), before any request: filter with it, and
2503
- pass the value to write.
2559
+ pass the value to write; a field is a computed field or an edge endpoint.
2504
2560
 
2505
2561
  Example::
2506
2562
 
2507
2563
  count = await User.objects().filter(status="pending").bulk_update(status="active")
2508
2564
  count = await Post.objects().filter(author__in=Subquery(banned)).bulk_update(hidden=True)
2509
2565
  """
2510
- self.model._reject_view_write("objects().bulk_update()")
2511
- self._reject_time_travel("bulk_update()")
2512
2566
  if not kwargs:
2513
2567
  return 0
2514
- for field, value in kwargs.items():
2515
- if _subquery.subquery_of(value) is not None:
2516
- raise ValueError(_subquery.value_written(field))
2517
- self.model._reject_computed_writes(kwargs, "bulk_update()")
2518
2568
 
2519
2569
  def compile_statement(compiler: SubqueryCompiler) -> tuple[str, dict[str, Any]]:
2520
2570
  where_clause, where_vars = self._write_where(compiler)
@@ -2531,7 +2581,7 @@ class QuerySet:
2531
2581
  results = await self._run_compiled(compile_statement, write=True)
2532
2582
  return len(results) if isinstance(results, list) else 0
2533
2583
 
2534
- @_cache.invalidates("queryset", deletes=True)
2584
+ @_cache.invalidates("queryset", deletes=True, refuse=_queryset_refusals("bulk_delete()"))
2535
2585
  async def bulk_delete(self) -> int:
2536
2586
  """
2537
2587
  Delete all records matching the current filters.
@@ -2543,13 +2593,15 @@ class QuerySet:
2543
2593
  Returns:
2544
2594
  The number of deleted records (``0`` inside a buffered transaction, whose statements run at commit).
2545
2595
 
2596
+ The materialized view (``TypeError``), then a queryset read ``as_of()`` (``SurrealDbError``), are refused
2597
+ before any request and before the table and the edges are noted on the ``objects(tx=…)`` transaction or put in
2598
+ flight: a refused call leaves the transaction as it was and drops no cached read (#320).
2599
+
2546
2600
  Example::
2547
2601
 
2548
2602
  count = await User.objects().filter(status="inactive").bulk_delete()
2549
2603
  count = await Post.objects().filter(author__in=Subquery(banned)).bulk_delete()
2550
2604
  """
2551
- self.model._reject_view_write("objects().bulk_delete()")
2552
- self._reject_time_travel("bulk_delete()")
2553
2605
 
2554
2606
  def compile_statement(compiler: SubqueryCompiler) -> tuple[str, dict[str, Any]]:
2555
2607
  where_clause, where_vars = self._write_where(compiler)
@@ -2559,7 +2611,7 @@ class QuerySet:
2559
2611
  results = await self._run_compiled(compile_statement, write=True)
2560
2612
  return len(results) if isinstance(results, list) else 0
2561
2613
 
2562
- @_cache.invalidates("queryset")
2614
+ @_cache.invalidates("queryset", refuse=_queryset_refusals("patch()"), refuse_args=_patch_arguments)
2563
2615
  async def patch(self, operations: list[dict[str, Any]]) -> int:
2564
2616
  """
2565
2617
  Apply a JSON Patch (RFC 6902) to every row matching the current filters.
@@ -2571,16 +2623,17 @@ class QuerySet:
2571
2623
  (v0.36.0) it patches the ``limit`` nearest records among those the filters select, by their ids
2572
2624
  (:meth:`_write_where`).
2573
2625
 
2626
+ The materialized view (``TypeError``), a queryset read ``as_of()`` (``SurrealDbError``), invalid operations,
2627
+ then a computed field or an edge endpoint they write (``ValueError``) are refused in this order, before any
2628
+ request and before the table is noted on the ``objects(tx=…)`` transaction or put in flight: a refused call
2629
+ leaves the transaction as it was and drops no cached read (#320).
2630
+
2574
2631
  Example::
2575
2632
 
2576
2633
  n = await User.objects().filter(status="trial").patch(
2577
2634
  [{"op": "replace", "path": "/plan", "value": "free"}]
2578
2635
  )
2579
2636
  """
2580
- self.model._reject_view_write("objects().patch()")
2581
- self._reject_time_travel("patch()")
2582
- validate_patch_operations(operations)
2583
- self.model._reject_computed_patch(operations, "patch()")
2584
2637
 
2585
2638
  def compile_statement(compiler: SubqueryCompiler) -> tuple[str, dict[str, Any]]:
2586
2639
  where_clause, where_vars = self._write_where(compiler)
@@ -297,10 +297,11 @@ class Transaction(ABC):
297
297
  """Note the tables an ORM write of records in this transaction changes (``None``: every table) — issue #304.
298
298
 
299
299
  ``cache.invalidates()`` calls it for each write method of records that joins the transaction, before the write
300
- is sent or queued and after the method's own refusals (``invalidates(refuse=…)``: an instance write the model
301
- refuses as a materialized view, a snapshot or SG1 notes nothing, #315) — never for a definition
302
- (``define_table()``, ``remove_index()``…), whose table is noted for the query cache only. Unlike the query
303
- cache's tables, the commit and the cancel keep them.
300
+ is sent or queued and after the method's own refusals and argument checks (``invalidates(refuse=…,
301
+ refuse_args=…)``: a write refused for a materialized view, a snapshot or SG1, #315, or for a snapshot in
302
+ ``bulk_create()``'s list, a missing id or another argument it checks, #320, notes nothing) — never for a
303
+ definition (``define_table()``, ``remove_index()``…), whose table is noted for the query cache only. Unlike
304
+ the query cache's tables, the commit and the cancel keep them.
304
305
  """
305
306
  if tables is None:
306
307
  self._record_all = True