surreal-orm-lite 0.36.0__tar.gz → 0.36.1__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.0 → surreal_orm_lite-0.36.1}/CHANGELOG.md +44 -0
  2. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/PKG-INFO +1 -1
  3. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/pyproject.toml +1 -1
  4. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/__init__.py +1 -1
  5. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/cache.py +11 -1
  6. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/edge.py +5 -4
  7. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/model_auth.py +10 -6
  8. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/model_base.py +71 -59
  9. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/transaction.py +4 -2
  10. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/.gitignore +0 -0
  11. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/LICENSE +0 -0
  12. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/Makefile +0 -0
  13. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/README.md +0 -0
  14. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/_sdk.py +0 -0
  15. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/aggregations.py +0 -0
  16. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/auth.py +0 -0
  17. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/changefeed.py +0 -0
  18. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/concurrency.py +0 -0
  19. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/connection_config.py +0 -0
  20. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/connection_manager.py +0 -0
  21. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/constants.py +0 -0
  22. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/decoding.py +0 -0
  23. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/define_parser.py +0 -0
  24. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/embedded.py +0 -0
  25. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/encoding.py +0 -0
  26. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/enum.py +0 -0
  27. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/exceptions.py +0 -0
  28. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/functions.py +0 -0
  29. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/geo.py +0 -0
  30. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/introspection.py +0 -0
  31. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/live.py +0 -0
  32. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/model_ddl.py +0 -0
  33. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/model_generator.py +0 -0
  34. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/py.typed +0 -0
  35. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/q.py +0 -0
  36. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/query_set.py +0 -0
  37. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/routing.py +0 -0
  38. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/schema.py +0 -0
  39. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/schema_state.py +0 -0
  40. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/search.py +0 -0
  41. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/signals.py +0 -0
  42. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/subquery.py +0 -0
  43. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/surql_literal.py +0 -0
  44. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/testing/__init__.py +0 -0
  45. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/testing/database.py +0 -0
  46. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/testing/fixtures.py +0 -0
  47. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/time_travel.py +0 -0
  48. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/types.py +0 -0
  49. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/utils.py +0 -0
  50. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.1}/src/surreal_orm_lite/vector.py +0 -0
@@ -5,6 +5,50 @@ 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.1] - 2026-10-23
9
+
10
+ Follow-ups to the review of v0.35.4 (#315): an instance write that the model refuses (a
11
+ materialized view, a snapshot read with `as_of()`, an auth model with an excluded signup field)
12
+ now leaves its transaction exactly as it was, and the docstring of `access_ddl()` lists every call
13
+ that refuses an excluded signup field. No new public API.
14
+
15
+ ### Fixed
16
+
17
+ - **A refused instance write no longer marks its table as written on the transaction** (#315).
18
+ With `tx=`, the model's own refusals ran after the ORM had noted the model's table on the
19
+ transaction. A refused `update(tx=tx)` or `upsert(tx=tx)` (materialized view, snapshot, excluded
20
+ signup field), a `save()`, `merge()`, `patch()`, `atomic_*()` or `delete()` refused on a view
21
+ or a snapshot, or a `relate()`, `remove_relation()` or `remove_all_relations()` refused on a
22
+ snapshot queued no statement but left the table noted. A caller that caught the error and kept using the
23
+ transaction then had a later `define_indexes(tx=tx)` on that table refused by the v0.35.3 check
24
+ (#304), and the commit dropped the table's cached reads although nothing was written. These
25
+ refusals now run right after the connection check and before anything is noted: the transaction
26
+ keeps no statement and no table, `define_indexes(tx=tx)` is accepted, and the refused call
27
+ invalidates no cached read, with a transaction or without. The v0.35.4 entry's "nothing is added
28
+ to the transaction" now holds for the transaction's bookkeeping too. Refusal order (view,
29
+ snapshot, then excluded signup field) and messages are unchanged; the behaviour is the same on
30
+ SurrealDB 2.x and 3.x and on both transaction strategies.
31
+
32
+ ### Changed
33
+
34
+ - **The atomic helpers and an edge's `save()` refuse a view or a snapshot before checking their
35
+ arguments** (#315). `atomic_append()`, `atomic_remove()`, `atomic_set_add()`,
36
+ `atomic_increment()` and the `atomic_*_many()` helpers checked the field name (`atomic_increment()`
37
+ a duration amount, the `atomic_*_many()` helpers a `values` that is not a list) before the view
38
+ and snapshot refusals: on a view or a snapshot, an invalid argument now raises the view's
39
+ `TypeError` or the snapshot's `SurrealDbError` instead of the argument's error. An edge read with
40
+ `as_of()` raises the snapshot error before the `save(server_values=…)` and `save(extra_vars=…)`
41
+ refusal. Valid calls are unchanged.
42
+
43
+ ### Notes
44
+
45
+ - **Docs**: the `Raises` section of `access_ddl()` lists every call that refuses an auth model
46
+ with an excluded signup field, as `signup()` and the error message do: `table_ddl()`,
47
+ `define_table()`, `define_access()`, `signup()`, `signin()`, `authenticate()`, `refresh()`,
48
+ `update()` and `upsert()`.
49
+ - Server pins unchanged: tested against SurrealDB 3.3.4 and 2.7.0, plus 3.1.5 for backward
50
+ compatibility.
51
+
8
52
  ## [0.36.0] - 2026-10-23
9
53
 
10
54
  Vector search: a queryset finds the records whose vector is nearest to a query vector with the
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: surreal-orm-lite
3
- Version: 0.36.0
3
+ Version: 0.36.1
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
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "surreal-orm-lite"
3
- version = "0.36.0"
3
+ version = "0.36.1"
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.0"
1
+ __version__ = "0.36.1"
2
2
 
3
3
  from ._sdk import BoundExcluded, BoundIncluded
4
4
  from .aggregations import Aggregation, Avg, Count, Max, Min, Sum
@@ -790,7 +790,9 @@ def _note_records(tables: frozenset[str] | None, tx: Any) -> None:
790
790
  tx._note_record_write(tables)
791
791
 
792
792
 
793
- def invalidates(of: _Of, *, deletes: bool = False, records: bool = True) -> Callable[[F], F]:
793
+ def invalidates(
794
+ of: _Of, *, deletes: bool = False, records: bool = True, refuse: Callable[[Any], None] | None = None
795
+ ) -> Callable[[F], F]:
794
796
  """Decorate an ORM write method so that it invalidates the cached reads it can change.
795
797
 
796
798
  ``of`` says which tables the call writes, from its first argument: ``"self"`` (the instance's model table),
@@ -810,6 +812,12 @@ def invalidates(of: _Of, *, deletes: bool = False, records: bool = True) -> Call
810
812
  the model's raises ``SurrealDbError`` (``routing.check_transaction()``) before the write is put in flight or noted
811
813
  on the transaction, so a refused write invalidates nothing. The transaction is read statically, never asked. A
812
814
  queryset's transaction is checked by ``objects(tx=)``.
815
+
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).
813
821
  """
814
822
  if of not in _RESOLVERS:
815
823
  raise ValueError(f"invalidates() takes one of {sorted(_RESOLVERS)}, not {of!r}")
@@ -830,6 +838,8 @@ def invalidates(of: _Of, *, deletes: bool = False, records: bool = True) -> Call
830
838
  arg0 = bound.arguments[first]
831
839
  model = arg0 if isinstance(arg0, type) else type(arg0)
832
840
  _routing.check_transaction(model, tx, f"{model.__name__}.{func.__name__}()")
841
+ if refuse is not None and first in bound.arguments:
842
+ refuse(bound.arguments[first])
833
843
  if records and tx is not None:
834
844
  _note_records(tables, tx)
835
845
  async with writing(tables, tx):
@@ -27,7 +27,7 @@ from .connection_manager import SurrealDBConnectionManager
27
27
  from .define_parser import parse_define_table
28
28
  from .exceptions import SurrealDbError
29
29
  from .functions import SurrealFunc
30
- from .model_base import BaseSurrealModel, _own_annotation_names
30
+ from .model_base import BaseSurrealModel, _own_annotation_names, _write_refusals
31
31
  from .schema import (
32
32
  TableClauses,
33
33
  read_table_definitions,
@@ -454,7 +454,7 @@ class BaseSurrealEdge(BaseSurrealModel):
454
454
  """``in_``/``out``: SurrealDB ignores a change to an existing edge's endpoints."""
455
455
  return _ENDPOINT_FIELDS
456
456
 
457
- @_cache.invalidates("self")
457
+ @_cache.invalidates("self", refuse=_write_refusals("save()"))
458
458
  async def save(
459
459
  self,
460
460
  tx: Transaction | None = None,
@@ -489,8 +489,9 @@ class BaseSurrealEdge(BaseSurrealModel):
489
489
  buffered one the edge is written at commit and ``id`` stays ``None``.
490
490
 
491
491
  Raises:
492
- SurrealDbError: ``server_values``/``extra_vars`` given (before any call), a duplicate
493
- id, a refused or rejected write.
492
+ 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
494
+ duplicate id, a refused or rejected write.
494
495
  SurrealDbNotFoundError: an ``ENFORCED`` endpoint that does not exist.
495
496
  ValueError: an id that is a ``RecordID`` of another table, or a ``bool``.
496
497
  """
@@ -287,9 +287,10 @@ class AuthenticatedUserMixin:
287
287
  ``BaseSurrealModel._table_ddl()`` (behind ``table_ddl()`` and ``define_table()``), :meth:`access_ddl` (behind
288
288
  :meth:`define_access`, with or without the table), :meth:`_auth_variables` (behind :meth:`signup` and
289
289
  :meth:`signin`), :meth:`authenticate`, :meth:`refresh`, and ``update()`` and ``upsert()`` (through
290
- ``BaseSurrealModel._reject_signup_excluded()``, with or without ``tx``, before any signal) call it before any
291
- request: whichever call loads the record — ``authenticate()``, a ``get()``, a signup by another client —,
292
- ``update()`` and ``upsert()`` would drop the stored hash.
290
+ ``BaseSurrealModel._reject_signup_excluded()``, with or without ``tx``, before any signal and before the table
291
+ is noted on the transaction, #315) call it before any request: whichever call loads the record —
292
+ ``authenticate()``, a ``get()``, a signup by another client —, ``update()`` and ``upsert()`` would drop the
293
+ stored hash.
293
294
 
294
295
  Raises:
295
296
  TypeError: naming the model and those fields, in declaration order (``schema.signup_excluded_refused()``).
@@ -410,9 +411,12 @@ class AuthenticatedUserMixin:
410
411
  be refused by a required column, and a ``SCHEMAFULL`` table would not define
411
412
  the field (SurrealDB 3.x would refuse every signup, 2.x drop the value). The
412
413
  message names the model and the fields, in declaration order; ``table_ddl()``,
413
- ``define_table()``, :meth:`signup` and :meth:`signin` refuse that model too.
414
- Remove ``exclude=True`` and pass ``exclude=`` to ``model_dump()`` where you
415
- serialise the model.
414
+ ``define_table()``, :meth:`define_access`, :meth:`signup`, :meth:`signin`,
415
+ :meth:`authenticate`, :meth:`refresh`, ``update()`` and ``upsert()`` refuse that
416
+ model too (``schema.signup_excluded_refused()``), the last two before any signal,
417
+ with or without ``tx`` — leaving nothing on the transaction (#315). Remove
418
+ ``exclude=True`` and pass ``exclude=`` to ``model_dump()`` where you serialise
419
+ the model.
416
420
  ValueError: an auth key naming no field of the model, an unknown hashing family or
417
421
  duration, a primary key SIGNUP cannot bind; with ``with_table=True`` and a
418
422
  ``SCHEMAFULL`` schema mode, a ``FLEXIBLE`` request on a kind without an object
@@ -583,6 +583,29 @@ def _snapshot_moment(instance: BaseModel) -> datetime | None:
583
583
  return (instance.__pydantic_private__ or {}).get("_surreal_as_of")
584
584
 
585
585
 
586
+ def _write_refusals(call: str, *, view: bool = True, signup: bool = False) -> Callable[[Any], None]:
587
+ """The model's own refusals of the instance write *call* (``"update()"``, named as the user wrote it), for
588
+ ``invalidates(refuse=…)`` (issue #315).
589
+
590
+ In this order: the materialized view (W1, :meth:`BaseSurrealModel._reject_view_write`; ``view=False`` for the
591
+ relation helpers, which write the edge table), the snapshot (:meth:`BaseSurrealModel._reject_snapshot_write`),
592
+ then, with ``signup=True`` (the full replaces :meth:`~BaseSurrealModel.update` and
593
+ :meth:`~BaseSurrealModel.upsert`), SG1 (:meth:`BaseSurrealModel._reject_signup_excluded`). The wrapper calls it
594
+ with the instance after ``routing.check_transaction()`` and before the write's tables are noted on the transaction
595
+ or put in flight, so a refused write leaves the transaction as it was: no statement, no table noted for
596
+ ``define_indexes(tx=…)`` (#304) or the query cache. A write decorated with it does not repeat these checks.
597
+ """
598
+
599
+ def refuse(instance: Any) -> None:
600
+ if view:
601
+ instance._reject_view_write(call)
602
+ instance._reject_snapshot_write(call)
603
+ if signup:
604
+ instance._reject_signup_excluded()
605
+
606
+ return refuse
607
+
608
+
586
609
  class SurrealConfigDict(ConfigDict, total=False):
587
610
  """
588
611
  SurrealConfigDict is a configuration dictionary for SurrealDB models.
@@ -795,9 +818,10 @@ class BaseSurrealModel(BaseModel):
795
818
  """Refuse *method* (named with its ``()``) on a snapshot, an instance read with ``as_of()`` (v0.26.0).
796
819
 
797
820
  Called at the start of every instance write — right after the materialized-view check of the writes that
798
- have one (:meth:`_reject_view_write`, v0.32.0) —, so no signal, transaction or request runs before it. The
799
- marker is read through :func:`_snapshot_moment`, the only reader (an instance pickled by v0.25.x may have no
800
- private state).
821
+ have one (:meth:`_reject_view_write`, v0.32.0) —, so no signal, transaction or request runs before it: by the
822
+ write's ``invalidates(refuse=…)`` (:func:`_write_refusals`), before its tables are noted on the transaction, so
823
+ a refused write leaves the transaction as it was (#315). The marker is read through :func:`_snapshot_moment`,
824
+ the only reader (an instance pickled by v0.25.x may have no private state).
801
825
 
802
826
  Raises:
803
827
  SurrealDbError: the instance holds the record as it was at a moment, not the current record.
@@ -1473,8 +1497,10 @@ class BaseSurrealModel(BaseModel):
1473
1497
 
1474
1498
  SurrealDB computes a view's records from its ``view_query``, so the ORM never writes them: the first statement
1475
1499
  of every ORM write of the model — the instance writes and the queryset's — before the snapshot check, any
1476
- signal, transaction use or request. The relation helpers write the edge table, not the view, and stay
1477
- allowed; raw SurrealQL is never guarded.
1500
+ signal, transaction use or request. An instance write runs it through its ``invalidates(refuse=…)``
1501
+ (:func:`_write_refusals`), before its table is noted on the transaction, which a refused write leaves as it
1502
+ was (#315). The relation helpers write the edge table, not the view, and stay allowed; raw SurrealQL is never
1503
+ guarded.
1478
1504
 
1479
1505
  Raises:
1480
1506
  TypeError: the model is a materialized view (W1, naming the class and *call*).
@@ -1491,7 +1517,9 @@ class BaseSurrealModel(BaseModel):
1491
1517
  Called by :meth:`_table_ddl`, after its other refusals, and by the full replaces :meth:`update` and
1492
1518
  :meth:`upsert`, right after the view and snapshot checks — before any signal, transaction use or request: they
1493
1519
  write what ``model_dump()`` writes, so they would drop the stored value of such a field (a password hash, and
1494
- every later signin fails).
1520
+ every later signin fails). There it runs in their ``invalidates(refuse=…)`` (:func:`_write_refusals`), before
1521
+ the model's table is noted on the transaction: a refused ``update(tx=…)`` or ``upsert(tx=…)`` leaves nothing on
1522
+ the transaction — no statement, and no table noted for ``define_indexes(tx=…)`` or the query cache (#315).
1495
1523
 
1496
1524
  Raises:
1497
1525
  TypeError: the auth model and those fields, in declaration order (``schema.signup_excluded_refused()``).
@@ -3076,20 +3104,22 @@ class BaseSurrealModel(BaseModel):
3076
3104
  self._apply_record(rows)
3077
3105
  return self, True
3078
3106
 
3079
- @_cache.invalidates("self")
3107
+ @_cache.invalidates("self", refuse=_write_refusals("save()"))
3080
3108
  async def _save_naming(self, fields: Iterable[str], tx: Transaction | None = None) -> Self:
3081
3109
  """``save()`` that also writes the ``server_fields`` among ``fields``.
3082
3110
 
3083
3111
  Backs the create branch of ``get_or_create``/``update_or_create``, where a server field
3084
3112
  can legitimately be named — as a lookup criterion or in ``defaults`` — and must then be
3085
- stored, or the next identical lookup would miss the row and create another one.
3113
+ stored, or the next identical lookup would miss the row and create another one. It refuses a
3114
+ materialized view and a snapshot as ``save()`` does, naming ``save()``, before its table is noted
3115
+ on the transaction (#315) — also when it writes a server field, which does not go through ``save()``.
3086
3116
  """
3087
3117
  keep = frozenset(fields) & self.get_server_fields()
3088
3118
  if not keep:
3089
3119
  return await self.save(tx=tx)
3090
3120
  return await self._save_with_signals(functools.partial(self._do_save, keep=keep), tx)
3091
3121
 
3092
- @_cache.invalidates("self")
3122
+ @_cache.invalidates("self", refuse=_write_refusals("save()"))
3093
3123
  async def save(
3094
3124
  self,
3095
3125
  tx: Transaction | None = None,
@@ -3137,8 +3167,6 @@ class BaseSurrealModel(BaseModel):
3137
3167
  values are unknown until commit, so the instance keeps its pre-save values for
3138
3168
  those fields — ``refresh()`` after commit if you need them.
3139
3169
  """
3140
- self._reject_view_write("save()")
3141
- self._reject_snapshot_write("save()")
3142
3170
  self._validate_server_values(server_values, extra_vars)
3143
3171
  if server_values:
3144
3172
  self._reject_computed_writes(server_values, "save(server_values=)")
@@ -3398,7 +3426,7 @@ class BaseSurrealModel(BaseModel):
3398
3426
  return rows[0].get("before"), rows[0].get("after")
3399
3427
  return None, None
3400
3428
 
3401
- @_cache.invalidates("self")
3429
+ @_cache.invalidates("self", refuse=_write_refusals("upsert()", signup=True))
3402
3430
  async def upsert(self, tx: Transaction | None = None) -> Self:
3403
3431
  """
3404
3432
  Insert the model instance, or fully replace it if a record with the same id exists.
@@ -3416,6 +3444,11 @@ class BaseSurrealModel(BaseModel):
3416
3444
  in a transaction ``around_save`` is skipped and ``post_save`` is deferred to a
3417
3445
  successful commit (consistent with ``save(tx=)``).
3418
3446
 
3447
+ The view, snapshot and SG1 refusals below come before the model's table is noted on
3448
+ ``tx``: a call they refuse leaves nothing on the transaction — no statement, and no table
3449
+ noted as written, so a later ``define_indexes(tx=…)`` of the model is not refused for it
3450
+ and the commit drops no cached read for it (#315).
3451
+
3419
3452
  Raises:
3420
3453
  TypeError: the model is a materialized view (W1); or an auth model
3421
3454
  (``AuthenticatedUserMixin``) with a field SIGNUP writes that ``Field(exclude=True)``
@@ -3424,12 +3457,9 @@ class BaseSurrealModel(BaseModel):
3424
3457
  without ``tx``.
3425
3458
  SurrealDbError: the instance is a snapshot read with ``as_of()``.
3426
3459
  """
3427
- self._reject_view_write("upsert()")
3428
- self._reject_snapshot_write("upsert()")
3429
- self._reject_signup_excluded()
3430
3460
  return await self._save_with_signals(self._do_upsert, tx)
3431
3461
 
3432
- @_cache.invalidates("self")
3462
+ @_cache.invalidates("self", refuse=_write_refusals("update()", signup=True))
3433
3463
  async def update(self, tx: Transaction | None = None) -> Any:
3434
3464
  """
3435
3465
  Update the model instance to the database.
@@ -3474,6 +3504,11 @@ class BaseSurrealModel(BaseModel):
3474
3504
  The updated row as the SDK reads it (``[]`` for a record that does not exist), or
3475
3505
  ``None`` in a transaction.
3476
3506
 
3507
+ The view, snapshot and SG1 refusals below come before the model's table is noted on
3508
+ ``tx``: a call they refuse leaves nothing on the transaction — no statement, and no table
3509
+ noted as written, so a later ``define_indexes(tx=…)`` of the model is not refused for it
3510
+ and the commit drops no cached read for it (#315).
3511
+
3477
3512
  Raises:
3478
3513
  TypeError: the model is a materialized view (W1); or an auth model
3479
3514
  (``AuthenticatedUserMixin``) with a field SIGNUP writes that ``Field(exclude=True)``
@@ -3482,9 +3517,6 @@ class BaseSurrealModel(BaseModel):
3482
3517
  without ``tx``.
3483
3518
  SurrealDbError: the instance is a snapshot read with ``as_of()``, or it has no id.
3484
3519
  """
3485
- self._reject_view_write("update()")
3486
- self._reject_snapshot_write("update()")
3487
- self._reject_signup_excluded()
3488
3520
  sender = self.__class__
3489
3521
  data = self._write_payload(replace=True)
3490
3522
  record_id = self._record_id()
@@ -3593,7 +3625,7 @@ class BaseSurrealModel(BaseModel):
3593
3625
  await post_update.send(sender, instance=self, update_fields=update_fields)
3594
3626
  return None
3595
3627
 
3596
- @_cache.invalidates("self")
3628
+ @_cache.invalidates("self", refuse=_write_refusals("merge()"))
3597
3629
  async def merge(
3598
3630
  self,
3599
3631
  tx: Transaction | None = None,
@@ -3647,8 +3679,6 @@ class BaseSurrealModel(BaseModel):
3647
3679
  >>> await user.merge(plan="pro", server_values={"updated_at": SurrealFunc("time::now()")})
3648
3680
  >>> await user.merge(last_seen=now, refresh=False) # fire-and-forget
3649
3681
  """
3650
- self._reject_view_write("merge()")
3651
- self._reject_snapshot_write("merge()")
3652
3682
  self._reject_computed_writes(data, "merge()")
3653
3683
  self._validate_server_values(server_values, extra_vars)
3654
3684
  if server_values:
@@ -3692,7 +3722,7 @@ class BaseSurrealModel(BaseModel):
3692
3722
 
3693
3723
  # ==================== Patch & atomic operations ====================
3694
3724
 
3695
- @_cache.invalidates("self")
3725
+ @_cache.invalidates("self", refuse=_write_refusals("patch()"))
3696
3726
  async def patch(self, operations: list[dict[str, Any]], tx: Transaction | None = None) -> Self:
3697
3727
  """Apply a JSON Patch (RFC 6902) to this record.
3698
3728
 
@@ -3710,8 +3740,6 @@ class BaseSurrealModel(BaseModel):
3710
3740
  name a field either way — ``/password`` or its column ``/password_hash`` — and are
3711
3741
  rewritten to the column before they are sent.
3712
3742
  """
3713
- self._reject_view_write("patch()")
3714
- self._reject_snapshot_write("patch()")
3715
3743
  validate_patch_operations(operations)
3716
3744
  self._reject_computed_patch(operations, "patch()")
3717
3745
  operations = self._columns_for_patch(operations)
@@ -3727,18 +3755,16 @@ class BaseSurrealModel(BaseModel):
3727
3755
  self._apply_record(record)
3728
3756
  return self
3729
3757
 
3730
- async def _atomic_update(self, set_expr: str, variables: dict[str, Any], tx: Transaction | None, *, label: str) -> Self:
3758
+ async def _atomic_update(self, set_expr: str, variables: dict[str, Any], tx: Transaction | None) -> Self:
3731
3759
  """Run ``UPDATE $rid SET <set_expr>`` atomically and sync ``self`` with the result.
3732
3760
 
3733
3761
  Shared by the atomic helpers. ``$rid`` and every value in ``variables`` are bound
3734
3762
  (robust for any id type; anti-injection); only the validated ``set_expr`` is inlined.
3735
3763
  Non-tx and interactive-tx apply the returned row to ``self``; a buffered tx leaves
3736
3764
  ``self`` stale (the new value is computed server-side, unknown until commit).
3737
- ``label`` is the calling method's name with its ``()``, for the view refusal (v0.32.0) and the snapshot
3738
- refusal (v0.26.0).
3765
+ Each helper refuses a materialized view (v0.32.0) and a snapshot (v0.26.0) under its own
3766
+ name through its ``invalidates(refuse=…)`` (#315), before its field is checked.
3739
3767
  """
3740
- self._reject_view_write(label)
3741
- self._reject_snapshot_write(label)
3742
3768
  record_id = self._record_id()
3743
3769
  if record_id is None:
3744
3770
  raise SurrealDbError("atomic operations require an explicit id.")
@@ -3753,7 +3779,7 @@ class BaseSurrealModel(BaseModel):
3753
3779
  self._apply_record(rows)
3754
3780
  return self
3755
3781
 
3756
- @_cache.invalidates("self")
3782
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_append()"))
3757
3783
  async def atomic_append(self, field: str, value: Any, tx: Transaction | None = None) -> Self:
3758
3784
  """Atomically append ``value`` to an array ``field`` (duplicates allowed).
3759
3785
 
@@ -3761,11 +3787,9 @@ class BaseSurrealModel(BaseModel):
3761
3787
  semantics (skip if already present) use :meth:`atomic_set_add`. Emits no signals.
3762
3788
  """
3763
3789
  column = self._validate_atomic_field(field)
3764
- return await self._atomic_update(
3765
- f"{column} = array::append({column}, $value)", {"value": value}, tx, label="atomic_append()"
3766
- )
3790
+ return await self._atomic_update(f"{column} = array::append({column}, $value)", {"value": value}, tx)
3767
3791
 
3768
- @_cache.invalidates("self")
3792
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_remove()"))
3769
3793
  async def atomic_remove(self, field: str, value: Any, tx: Transaction | None = None) -> Self:
3770
3794
  """Atomically remove ALL occurrences of ``value`` from an array ``field``.
3771
3795
 
@@ -3774,11 +3798,9 @@ class BaseSurrealModel(BaseModel):
3774
3798
  but only the first on 2.6.x.) Emits no signals.
3775
3799
  """
3776
3800
  column = self._validate_atomic_field(field)
3777
- return await self._atomic_update(
3778
- f"{column} = array::complement({column}, [$value])", {"value": value}, tx, label="atomic_remove()"
3779
- )
3801
+ return await self._atomic_update(f"{column} = array::complement({column}, [$value])", {"value": value}, tx)
3780
3802
 
3781
- @_cache.invalidates("self")
3803
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_set_add()"))
3782
3804
  async def atomic_set_add(self, field: str, value: Any, tx: Transaction | None = None) -> Self:
3783
3805
  """Atomically add ``value`` to an array ``field`` only if not already present.
3784
3806
 
@@ -3786,11 +3808,9 @@ class BaseSurrealModel(BaseModel):
3786
3808
  ``+=`` operator, which appends duplicates on both server lines.) Emits no signals.
3787
3809
  """
3788
3810
  column = self._validate_atomic_field(field)
3789
- return await self._atomic_update(
3790
- f"{column} = array::add({column}, $value)", {"value": value}, tx, label="atomic_set_add()"
3791
- )
3811
+ return await self._atomic_update(f"{column} = array::add({column}, $value)", {"value": value}, tx)
3792
3812
 
3793
- @_cache.invalidates("self")
3813
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_increment()"))
3794
3814
  async def atomic_increment(self, field: str, amount: Decimal | int | float = 1, tx: Transaction | None = None) -> Self:
3795
3815
  """Atomically add ``amount`` (default 1) to a numeric ``field``.
3796
3816
 
@@ -3811,7 +3831,7 @@ class BaseSurrealModel(BaseModel):
3811
3831
  f"Set the new value with merge({field}=…) instead."
3812
3832
  )
3813
3833
  column = self._validate_atomic_field(field)
3814
- return await self._atomic_update(f"{column} += $amount", {"amount": amount}, tx, label="atomic_increment()")
3834
+ return await self._atomic_update(f"{column} += $amount", {"amount": amount}, tx)
3815
3835
 
3816
3836
  @staticmethod
3817
3837
  def _as_value_list(values: Any) -> list[Any]:
@@ -3822,7 +3842,7 @@ class BaseSurrealModel(BaseModel):
3822
3842
  return list(values)
3823
3843
  raise ValueError(f"values must be a list of items, got {type(values).__name__}")
3824
3844
 
3825
- @_cache.invalidates("self")
3845
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_append_many()"))
3826
3846
  async def atomic_append_many(self, field: str, values: list[Any], tx: Transaction | None = None) -> Self:
3827
3847
  """Atomically append every element of ``values`` to an array ``field`` (duplicates allowed).
3828
3848
 
@@ -3836,10 +3856,9 @@ class BaseSurrealModel(BaseModel):
3836
3856
  f"{column} = array::concat({column}, $values)",
3837
3857
  {"values": self._as_value_list(values)},
3838
3858
  tx,
3839
- label="atomic_append_many()",
3840
3859
  )
3841
3860
 
3842
- @_cache.invalidates("self")
3861
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_set_add_many()"))
3843
3862
  async def atomic_set_add_many(self, field: str, values: list[Any], tx: Transaction | None = None) -> Self:
3844
3863
  """Atomically add every element of ``values`` to an array ``field``, skipping any already present.
3845
3864
 
@@ -3852,10 +3871,9 @@ class BaseSurrealModel(BaseModel):
3852
3871
  f"{column} = array::add({column}, $values)",
3853
3872
  {"values": self._as_value_list(values)},
3854
3873
  tx,
3855
- label="atomic_set_add_many()",
3856
3874
  )
3857
3875
 
3858
- @_cache.invalidates("self")
3876
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_remove_many()"))
3859
3877
  async def atomic_remove_many(self, field: str, values: list[Any], tx: Transaction | None = None) -> Self:
3860
3878
  """Atomically remove ALL occurrences of every element of ``values`` from an array ``field``.
3861
3879
 
@@ -3867,10 +3885,9 @@ class BaseSurrealModel(BaseModel):
3867
3885
  f"{column} = array::complement({column}, $values)",
3868
3886
  {"values": self._as_value_list(values)},
3869
3887
  tx,
3870
- label="atomic_remove_many()",
3871
3888
  )
3872
3889
 
3873
- @_cache.invalidates("self", deletes=True)
3890
+ @_cache.invalidates("self", deletes=True, refuse=_write_refusals("delete()"))
3874
3891
  async def delete(self, tx: Transaction | None = None) -> None:
3875
3892
  """
3876
3893
  Delete the model instance from the database.
@@ -3884,8 +3901,6 @@ class BaseSurrealModel(BaseModel):
3884
3901
  ``around_delete`` is skipped (the write is deferred to commit) and
3885
3902
  ``post_delete`` only fires after a successful commit.
3886
3903
  """
3887
- self._reject_view_write("delete()")
3888
- self._reject_snapshot_write("delete()")
3889
3904
  sender = self.__class__
3890
3905
  record_id = self._record_id()
3891
3906
  if record_id is None:
@@ -4119,7 +4134,7 @@ class BaseSurrealModel(BaseModel):
4119
4134
  **edge_data: Any,
4120
4135
  ) -> list[dict[str, Any]]: ...
4121
4136
 
4122
- @_cache.invalidates("edge")
4137
+ @_cache.invalidates("edge", refuse=_write_refusals("relate()", view=False))
4123
4138
  async def relate(
4124
4139
  self,
4125
4140
  edge: "str | type[BaseSurrealEdge]",
@@ -4202,7 +4217,6 @@ class BaseSurrealModel(BaseModel):
4202
4217
  async with SurrealDBConnectionManager.transaction() as tx:
4203
4218
  await user.relate(Follows, other_user, tx=tx)
4204
4219
  """
4205
- self._reject_snapshot_write("relate()")
4206
4220
  self._check_relation("relate", self._model_of(target), self._edge_model(edge))
4207
4221
  if isinstance(edge, type) and issubclass(edge, BaseSurrealModel) and edge.__surreal_edge__:
4208
4222
  fields = self._merge_edge_fields(data, edge_data, edge.to_py_field)
@@ -4329,7 +4343,7 @@ class BaseSurrealModel(BaseModel):
4329
4343
  with contextlib.suppress(NotFoundError):
4330
4344
  await client.query(statement, _encoding.encode(variables))
4331
4345
 
4332
- @_cache.invalidates("edge")
4346
+ @_cache.invalidates("edge", refuse=_write_refusals("remove_relation()", view=False))
4333
4347
  async def remove_relation(
4334
4348
  self,
4335
4349
  edge: "str | type[BaseSurrealEdge]",
@@ -4390,7 +4404,6 @@ class BaseSurrealModel(BaseModel):
4390
4404
  async with SurrealDBConnectionManager.transaction() as tx:
4391
4405
  await user.remove_relation(Follows, other_user, tx=tx)
4392
4406
  """
4393
- self._reject_snapshot_write("remove_relation()")
4394
4407
  self._check_relation("remove_relation", self._model_of(target), self._edge_model(edge))
4395
4408
  edge_name = self._edge_name(edge)
4396
4409
  source = self._graph_source()
@@ -4408,7 +4421,7 @@ class BaseSurrealModel(BaseModel):
4408
4421
  variables = {"src": source, "dst": self._graph_target(target)}
4409
4422
  await self._run_graph_delete(statement, variables, tx)
4410
4423
 
4411
- @_cache.invalidates("edge")
4424
+ @_cache.invalidates("edge", refuse=_write_refusals("remove_all_relations()", view=False))
4412
4425
  async def remove_all_relations(
4413
4426
  self,
4414
4427
  edge: "str | type[BaseSurrealEdge] | Sequence[str | type[BaseSurrealEdge]]",
@@ -4453,7 +4466,6 @@ class BaseSurrealModel(BaseModel):
4453
4466
  async with SurrealDBConnectionManager.transaction() as tx:
4454
4467
  await user.remove_all_relations(["likes", "blocks"], direction="both", tx=tx)
4455
4468
  """
4456
- self._reject_snapshot_write("remove_all_relations()")
4457
4469
  self._check_direction(direction)
4458
4470
  edges = edge if isinstance(edge, (list, tuple)) else (edge,)
4459
4471
  self._check_relation("remove_all_relations", *(self._edge_model(item) for item in edges))
@@ -277,8 +277,10 @@ class Transaction(ABC):
277
277
  """Note the tables an ORM write of records in this transaction changes (``None``: every table) — issue #304.
278
278
 
279
279
  ``cache.invalidates()`` calls it for each write method of records that joins the transaction, before the write
280
- is sent or queued — never for a definition (``define_table()``, ``remove_index()``…), whose table is noted for
281
- the query cache only. Unlike the query cache's tables, the commit and the cancel keep them.
280
+ is sent or queued and after the method's own refusals (``invalidates(refuse=…)``: an instance write the model
281
+ refuses as a materialized view, a snapshot or SG1 notes nothing, #315) — never for a definition
282
+ (``define_table()``, ``remove_index()``…), whose table is noted for the query cache only. Unlike the query
283
+ cache's tables, the commit and the cancel keep them.
282
284
  """
283
285
  if tables is None:
284
286
  self._record_all = True