surreal-orm-lite 0.36.0__tar.gz → 0.36.2__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.2}/CHANGELOG.md +88 -0
  2. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/PKG-INFO +16 -5
  3. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/README.md +15 -4
  4. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/pyproject.toml +1 -1
  5. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/__init__.py +1 -1
  6. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/cache.py +11 -1
  7. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/edge.py +5 -4
  8. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/model_auth.py +10 -6
  9. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/model_base.py +119 -77
  10. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/transaction.py +33 -2
  11. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/.gitignore +0 -0
  12. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/LICENSE +0 -0
  13. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/Makefile +0 -0
  14. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/_sdk.py +0 -0
  15. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/aggregations.py +0 -0
  16. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/auth.py +0 -0
  17. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/changefeed.py +0 -0
  18. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/concurrency.py +0 -0
  19. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/connection_config.py +0 -0
  20. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/connection_manager.py +0 -0
  21. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/constants.py +0 -0
  22. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/decoding.py +0 -0
  23. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/define_parser.py +0 -0
  24. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/embedded.py +0 -0
  25. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/encoding.py +0 -0
  26. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/enum.py +0 -0
  27. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/exceptions.py +0 -0
  28. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/functions.py +0 -0
  29. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/geo.py +0 -0
  30. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/introspection.py +0 -0
  31. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/live.py +0 -0
  32. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/model_ddl.py +0 -0
  33. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/model_generator.py +0 -0
  34. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/py.typed +0 -0
  35. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/q.py +0 -0
  36. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/query_set.py +0 -0
  37. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/routing.py +0 -0
  38. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/schema.py +0 -0
  39. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/schema_state.py +0 -0
  40. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/search.py +0 -0
  41. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/signals.py +0 -0
  42. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/subquery.py +0 -0
  43. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/surql_literal.py +0 -0
  44. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/testing/__init__.py +0 -0
  45. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/testing/database.py +0 -0
  46. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/testing/fixtures.py +0 -0
  47. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/time_travel.py +0 -0
  48. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/types.py +0 -0
  49. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/utils.py +0 -0
  50. {surreal_orm_lite-0.36.0 → surreal_orm_lite-0.36.2}/src/surreal_orm_lite/vector.py +0 -0
@@ -5,6 +5,94 @@ 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.2] - 2026-10-23
9
+
10
+ Follow-ups to the review of v0.35.3 (#312): an index that `remove_index(tx=…)` removed earlier in
11
+ a transaction is defined again by `define_indexes(tx=…)` in the same block instead of being lost
12
+ at the commit, and the docs say why the refusal after a write covers every kind of index. No new
13
+ public API.
14
+
15
+ ### Fixed
16
+
17
+ - **`remove_index(tx=…)` then `define_indexes(tx=…)` in one block no longer loses an existing
18
+ index** (#312). `define_indexes(tx=…)` reads `INFO FOR TABLE` outside the transaction, where an
19
+ index removed earlier in the block still stands: it planned nothing, returned `[]`, and the
20
+ commit applied the removal, leaving the table without the index and without an error (since
21
+ v0.35.0, over WebSocket and HTTP and on the embedded engine, on SurrealDB 2.x and 3.x).
22
+ `remove_index(tx=…)` now notes the removal on the transaction, and `define_indexes(tx=…)`
23
+ counts the noted index as missing: it defines it again after the removal
24
+ (`DEFINE INDEX OVERWRITE`, or `IF NOT EXISTS` with `overwrite=False`), so the commit keeps
25
+ it, and a later call in the block compares it with committed state again. Only an index the
26
+ model declares comes back: another model's index on the same table comes back with that
27
+ model's `define_indexes(tx=…)`, and one no model declares stays removed. When the block has
28
+ already written records to the table, the call is refused before any DDL, as since v0.35.3. A
29
+ raw `tx.add("REMOVE INDEX …")` is not tracked.
30
+ - **The same fix also applies to vector (HNSW) indexes since v0.36.0**: on v0.36.0 and v0.36.1,
31
+ `remove_index(tx=…)` then `define_indexes(tx=…)` lost an HNSW index at the commit on every
32
+ engine; it is now defined again, as a full-text or `UNIQUE` index is.
33
+
34
+ ### Notes
35
+
36
+ - **Removing an index and defining it again in one block on SurrealDB 2.x**: on a table that
37
+ held records, the commit fails with a retryable `SurrealDbConflictError` that a retry meets
38
+ again, a 2.x limitation; nothing of the block is committed and the index stands as before. On an
39
+ empty table it commits, as on SurrealDB 3.x and the embedded engine. A row in each behaviour
40
+ table of the README ("ORM behaviour: SurrealDB 2.x vs 3.x" and the embedded engine's) describes
41
+ each engine's outcome, which tests pin.
42
+ - **A write after `define_indexes(tx=…)` on SurrealDB 2.x**: the v0.35.3 qualifier "to a table
43
+ that held records" is now pinned: on an empty table, a write after the index in the same block
44
+ commits and is indexed.
45
+ - **Docs**: README section 36 (Transactions) and the `define_indexes()` docstring say why the
46
+ refusal after a write covers every kind of index, not only full-text ones: a search would miss
47
+ those records, and a `UNIQUE` index missing them would not enforce uniqueness for them
48
+ ([surrealdb/surrealdb#7618](https://github.com/surrealdb/surrealdb/issues/7618)).
49
+ - Server pins unchanged: tested against SurrealDB 3.3.4 and 2.7.0 and on the embedded engine,
50
+ plus 3.1.5 for backward compatibility.
51
+
52
+ ## [0.36.1] - 2026-10-23
53
+
54
+ Follow-ups to the review of v0.35.4 (#315): an instance write that the model refuses (a
55
+ materialized view, a snapshot read with `as_of()`, an auth model with an excluded signup field)
56
+ now leaves its transaction exactly as it was, and the docstring of `access_ddl()` lists every call
57
+ that refuses an excluded signup field. No new public API.
58
+
59
+ ### Fixed
60
+
61
+ - **A refused instance write no longer marks its table as written on the transaction** (#315).
62
+ With `tx=`, the model's own refusals ran after the ORM had noted the model's table on the
63
+ transaction. A refused `update(tx=tx)` or `upsert(tx=tx)` (materialized view, snapshot, excluded
64
+ signup field), a `save()`, `merge()`, `patch()`, `atomic_*()` or `delete()` refused on a view
65
+ or a snapshot, or a `relate()`, `remove_relation()` or `remove_all_relations()` refused on a
66
+ snapshot queued no statement but left the table noted. A caller that caught the error and kept using the
67
+ transaction then had a later `define_indexes(tx=tx)` on that table refused by the v0.35.3 check
68
+ (#304), and the commit dropped the table's cached reads although nothing was written. These
69
+ refusals now run right after the connection check and before anything is noted: the transaction
70
+ keeps no statement and no table, `define_indexes(tx=tx)` is accepted, and the refused call
71
+ invalidates no cached read, with a transaction or without. The v0.35.4 entry's "nothing is added
72
+ to the transaction" now holds for the transaction's bookkeeping too. Refusal order (view,
73
+ snapshot, then excluded signup field) and messages are unchanged; the behaviour is the same on
74
+ SurrealDB 2.x and 3.x and on both transaction strategies.
75
+
76
+ ### Changed
77
+
78
+ - **The atomic helpers and an edge's `save()` refuse a view or a snapshot before checking their
79
+ arguments** (#315). `atomic_append()`, `atomic_remove()`, `atomic_set_add()`,
80
+ `atomic_increment()` and the `atomic_*_many()` helpers checked the field name (`atomic_increment()`
81
+ a duration amount, the `atomic_*_many()` helpers a `values` that is not a list) before the view
82
+ and snapshot refusals: on a view or a snapshot, an invalid argument now raises the view's
83
+ `TypeError` or the snapshot's `SurrealDbError` instead of the argument's error. An edge read with
84
+ `as_of()` raises the snapshot error before the `save(server_values=…)` and `save(extra_vars=…)`
85
+ refusal. Valid calls are unchanged.
86
+
87
+ ### Notes
88
+
89
+ - **Docs**: the `Raises` section of `access_ddl()` lists every call that refuses an auth model
90
+ with an excluded signup field, as `signup()` and the error message do: `table_ddl()`,
91
+ `define_table()`, `define_access()`, `signup()`, `signin()`, `authenticate()`, `refresh()`,
92
+ `update()` and `upsert()`.
93
+ - Server pins unchanged: tested against SurrealDB 3.3.4 and 2.7.0, plus 3.1.5 for backward
94
+ compatibility.
95
+
8
96
  ## [0.36.0] - 2026-10-23
9
97
 
10
98
  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.2
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
@@ -6087,6 +6087,11 @@ print(await NoteV2.objects().search(text="physics").count())
6087
6087
  SurrealDB 3.x), at the commit in a buffered one (HTTP, SurrealDB 2.x, the embedded engine), where a refusal comes
6088
6088
  back as the transaction's own `SurrealDbError`. A block that raises applies nothing. `remove_index(tx=…)` joins it
6089
6089
  the same way.
6090
+ - An index `remove_index(tx=…)` removed earlier in the block counts as missing, although committed state still holds
6091
+ it: `define_indexes(tx=…)` defines it again after its removal (`OVERWRITE`, or `IF NOT EXISTS` with
6092
+ `overwrite=False`), so the commit keeps it. Only an index the model declares comes back: another model's on the same
6093
+ table comes back with that model's `define_indexes(tx=…)`, and one no model declares stays removed. A raw
6094
+ `tx.add("REMOVE INDEX …")` is not tracked.
6090
6095
  - The analyzers must be in place: SurrealDB builds an index with the analyzers committed before the transaction began.
6091
6096
  So `define_indexes(tx=…)` raises `SurrealDbError` before any DDL when an analyzer must be defined or redefined, and
6092
6097
  `define_analyzer(tx=…)` when a redefinition has indexes to rebuild (a new analyzer, or a redefinition no index uses,
@@ -6095,11 +6100,15 @@ print(await NoteV2.objects().search(text="physics").count())
6095
6100
  wrote before the index was defined, which stay out of it after the commit. It is a server defect
6096
6101
  ([surrealdb/surrealdb#7618](https://github.com/surrealdb/surrealdb/issues/7618) on 3.x, the same on 2.x); only the
6097
6102
  embedded engine indexes them. So `define_indexes(tx=…)` raises `SurrealDbError` before any DDL, naming the model and
6098
- the table, when an index must be defined or redefined and the block has already written records to the model's table
6099
- with the ORM (`save()`, `objects(tx=…).bulk_create()`, …). The refusal does not fail the block. `define_table(tx=…)`,
6103
+ the table, when an index must be defined or redefined — one removed earlier in the block included — and the block
6104
+ has already written records to the model's table with the ORM (`save()`, `objects(tx=…).bulk_create()`, …). The
6105
+ refusal covers every kind of index, not only full-text ones: a search would miss those records, and a `UNIQUE` index
6106
+ missing them would not enforce uniqueness for them. The refusal does not fail the block. `define_table(tx=…)`,
6100
6107
  `define_relation(tx=…)` and a write to another table do not count; a raw `tx.add()` is not tracked.
6101
6108
  - Prefer `define_indexes()` outside the block: on SurrealDB 2.x, a write to a table that held records, after its index
6102
- in the same block, fails the commit with a retryable `SurrealDbConflictError` that a retry meets again.
6109
+ in the same block, fails the commit with a retryable `SurrealDbConflictError` that a retry meets again; so does a
6110
+ block that removes an index of a table that held records and defines it again, where the index stands as before.
6111
+ Nothing of such a block is committed. On an empty table both commit, as on 3.x.
6103
6112
  - `remove_analyzer(tx=…)` reads committed state to find the indexes that use the analyzer: an index queued earlier in
6104
6113
  a buffered block is not seen.
6105
6114
  - A search in an interactive transaction sees the transaction's writes; in a buffered one, a read raises, as every
@@ -6597,7 +6606,7 @@ features introduced in SurrealDB 3.x. On 2.x the ORM degrades gracefully. Capabi
6597
6606
  listed behave the same on both lines. The 2.x column was measured on 2.6.5 and holds unchanged
6598
6607
  on 2.7.0. The 3.x column was measured on 3.2.4 and holds on 3.3.0, except where a row says
6599
6608
  otherwise. The full suite and every divergence below were re-verified on both new versions.
6600
- Rows added in v0.20.0 were measured directly on 2.7.0 and 3.3.0; rows added in v0.21.0 on 2.7.0 and 3.3.2, re-verified on 3.3.3, with 3.1.5 where it differs; rows added in v0.22.0 on 2.7.0 and 3.3.3, with 3.1.5 where it differs; rows added in v0.23.0 on 2.7.0 and 3.3.4, with 3.1.5 where it differs; rows added in v0.24.0 on 2.7.0 and 3.3.4, identical on 3.1.5; rows added in v0.26.0 on 2.7.0 and 3.3.4, in memory and on versioned storage, identical on 3.1.5; rows added in v0.27.0 on 2.7.0 and 3.3.4, with 3.1.5 where it differs; rows added in v0.28.0 on 2.7.0 and 3.3.4, identical on 3.1.5; the rows added in v0.28.1 on 2.7.0 and 3.3.4, identical on 3.1.5; rows added in v0.29.0 on 2.7.0 and 3.3.4 in one process, identical on 3.1.5. The row added in v0.29.2 was measured on 2.7.0, 3.3.4 and the embedded engine, identical on 3.1.5. Rows added in v0.30.0 were measured on 2.7.0, 3.3.4 and the embedded engine, with 3.1.5 where it differs. The row added in v0.30.3 was measured on 2.7.0 and 3.3.4, over WebSocket and HTTP, and on the embedded engine, identical on 3.1.5. The row added in v0.30.7 was measured on 2.7.0, 3.3.4 and the embedded engine, identical on 3.1.5: its parser refuses a statement that nests six objects, and `update()` nests at most four. Rows added in v0.31.0 were measured on 2.7.0, 3.3.4 and the embedded engine, identical on 3.1.5. The row added in v0.31.1 was measured on 2.7.0, 3.3.4 and the embedded engine, identical on 3.1.5. Rows added in v0.32.0 were measured on 2.7.0, 3.3.4 and the embedded engine; 3.1.5 behaves as 3.3.4 but accepts raw writes to a view. Rows added in v0.33.0 were measured on 2.7.0, 3.3.4 and the embedded engine; 3.1.5 behaves as 3.3.4. Rows added in v0.34.0 were measured on 2.7.0, 3.3.4 and the embedded engine; 3.1.5 behaves as 3.3.4 except that it refuses a Python `set` written to a `set` field, and an object item of an optional untyped `list`. Rows added in v0.35.0 were measured on 2.7.0, 3.3.4 and the embedded engine, with 3.1.5 where it differs. The row added in v0.35.2 was measured on 2.7.0 and 3.3.4, identical on 3.1.5. The row added in v0.35.3 was measured on 2.7.0 and 3.3.4, over WebSocket and HTTP, and on the embedded engine, identical on 3.1.5. Rows added in v0.36.0 were measured on 2.7.0, 3.3.4 and the embedded engine, with 3.1.5 where it differs.
6609
+ Rows added in v0.20.0 were measured directly on 2.7.0 and 3.3.0; rows added in v0.21.0 on 2.7.0 and 3.3.2, re-verified on 3.3.3, with 3.1.5 where it differs; rows added in v0.22.0 on 2.7.0 and 3.3.3, with 3.1.5 where it differs; rows added in v0.23.0 on 2.7.0 and 3.3.4, with 3.1.5 where it differs; rows added in v0.24.0 on 2.7.0 and 3.3.4, identical on 3.1.5; rows added in v0.26.0 on 2.7.0 and 3.3.4, in memory and on versioned storage, identical on 3.1.5; rows added in v0.27.0 on 2.7.0 and 3.3.4, with 3.1.5 where it differs; rows added in v0.28.0 on 2.7.0 and 3.3.4, identical on 3.1.5; the rows added in v0.28.1 on 2.7.0 and 3.3.4, identical on 3.1.5; rows added in v0.29.0 on 2.7.0 and 3.3.4 in one process, identical on 3.1.5. The row added in v0.29.2 was measured on 2.7.0, 3.3.4 and the embedded engine, identical on 3.1.5. Rows added in v0.30.0 were measured on 2.7.0, 3.3.4 and the embedded engine, with 3.1.5 where it differs. The row added in v0.30.3 was measured on 2.7.0 and 3.3.4, over WebSocket and HTTP, and on the embedded engine, identical on 3.1.5. The row added in v0.30.7 was measured on 2.7.0, 3.3.4 and the embedded engine, identical on 3.1.5: its parser refuses a statement that nests six objects, and `update()` nests at most four. Rows added in v0.31.0 were measured on 2.7.0, 3.3.4 and the embedded engine, identical on 3.1.5. The row added in v0.31.1 was measured on 2.7.0, 3.3.4 and the embedded engine, identical on 3.1.5. Rows added in v0.32.0 were measured on 2.7.0, 3.3.4 and the embedded engine; 3.1.5 behaves as 3.3.4 but accepts raw writes to a view. Rows added in v0.33.0 were measured on 2.7.0, 3.3.4 and the embedded engine; 3.1.5 behaves as 3.3.4. Rows added in v0.34.0 were measured on 2.7.0, 3.3.4 and the embedded engine; 3.1.5 behaves as 3.3.4 except that it refuses a Python `set` written to a `set` field, and an object item of an optional untyped `list`. Rows added in v0.35.0 were measured on 2.7.0, 3.3.4 and the embedded engine, with 3.1.5 where it differs. The row added in v0.35.2 was measured on 2.7.0 and 3.3.4, identical on 3.1.5. The row added in v0.35.3 was measured on 2.7.0 and 3.3.4, over WebSocket and HTTP, and on the embedded engine, identical on 3.1.5. Rows added in v0.36.0 were measured on 2.7.0, 3.3.4 and the embedded engine, with 3.1.5 where it differs. The row added in v0.36.2 was measured on 2.7.0 and 3.3.4, over WebSocket and HTTP, and on the embedded engine, identical on 3.1.5.
6601
6610
  The SDK's in-process engine has a table of its own: [ORM behaviour: the embedded engine](#orm-behaviour-the-embedded-engine).
6602
6611
 
6603
6612
  | ORM capability | SurrealDB 2.6.x / 2.7.x | SurrealDB 3.2.x / 3.3.x | Since |
@@ -6757,6 +6766,7 @@ The SDK's in-process engine has a table of its own: [ORM behaviour: the embedded
6757
6766
  | `similar_to()` with a condition that keeps few records | HNSW is approximate: fewer than `limit` records, depending on how the index was built, even with a tenth of the table kept; `dist=` is exact | rarer; also seen with a `Subquery` id list keeping a few percent of the table | v0.36.0 |
6758
6767
  | `similar_to(dist=…)` with a condition on a linked record's field | the ORM selects the matching records first (a `LET`): 2.x's exact scan would return every matching record, ignoring `limit` | the condition stays next to the KNN operator | v0.36.0 |
6759
6768
  | `similar_to()` on a field without a vector index | no record | no record; 3.1 answers every record, with no distance | v0.36.0 |
6769
+ | `remove_index(tx=)` then `define_indexes(tx=)` in one block, the index stored before the block | on a table holding records, the commit fails with a retryable `SurrealDbConflictError`, again on retry: nothing committed, the index kept; on an empty table, defined again | the index is defined again after its removal and committed, serving the records committed before the block | v0.36.2 |
6760
6770
  | Full suite and every divergence in this table, re-run on SurrealDB 2.7.0 and 3.3.0 | 2.7.0 identical to 2.6.5 (same passes, same 3.x-only skips) | 3.3.0 identical to 3.2.4, except the system-user signin row | v0.19.1 |
6761
6771
 
6762
6772
  > **Note on record IDs**: A record loaded from the database has its `id` field set to a native `surrealdb.RecordID` object, not a plain string. Use `model.get_raw_id()` to obtain the bare identifier string (e.g. `"alice"`), or compare directly with `model.id == RecordID("User", "alice")`. In-memory instances you construct yourself retain whatever value you assign.
@@ -6796,6 +6806,7 @@ Capabilities not listed behave as on a 2.x server.
6796
6806
  | Full-text search (v0.35.0) | as on a 2.x server: `SEARCH ANALYZER`, a term in more than half the documents scores below zero, BM25 statistics grow with each rebuild and keep deleted records, `remove_analyzer()` refuses an analyzer an index uses; an index defined in the transaction that defines its analyzer sees it, which `define_indexes(tx=…)` refuses all the same | 3.x writes `FULLTEXT ANALYZER`, scores such a term `0.0`, keeps BM25 statistics exact and refuses that removal | v0.35.0 |
6797
6807
  | `define_indexes(tx=)` in a block that writes to the model's table | an ORM write before it: refused all the same, although this engine indexes its records; a write after it is committed and indexed | refused (left out of the index); on 2.x a write after it, to a table holding records, fails the commit | v0.35.3 |
6798
6808
  | Vector search (v0.36.0) | as on a 2.x server: `MTREE` accepted, at most `ef` records returned (the ORM raises `ef` to `limit`), other conditions selected first in a `LET` (search annotations refused), writes made by the ids of the nearest, fewer records with a selective condition; an index without `TYPE` is `F64` (servers: `F32`), so the ORM always writes `TYPE` | 3.x refuses `MTREE`, applies the conditions during the index search and keeps search annotations | v0.36.0 |
6809
+ | `remove_index(tx=)` then `define_indexes(tx=)` in one block | the index is defined again after its removal and committed, on a table holding records too | the same on 3.x; on 2.x, on a table holding records, the commit fails with a retryable conflict | v0.36.2 |
6799
6810
  | Everything else | CRUD, QuerySet, aggregations, relations, typed edges, rich and geo fields, upsert/patch, server values, computed fields, stored functions, signals: the same as on a 2.x server | unchanged | v0.25.0 |
6800
6811
 
6801
6812
  ---
@@ -6036,6 +6036,11 @@ print(await NoteV2.objects().search(text="physics").count())
6036
6036
  SurrealDB 3.x), at the commit in a buffered one (HTTP, SurrealDB 2.x, the embedded engine), where a refusal comes
6037
6037
  back as the transaction's own `SurrealDbError`. A block that raises applies nothing. `remove_index(tx=…)` joins it
6038
6038
  the same way.
6039
+ - An index `remove_index(tx=…)` removed earlier in the block counts as missing, although committed state still holds
6040
+ it: `define_indexes(tx=…)` defines it again after its removal (`OVERWRITE`, or `IF NOT EXISTS` with
6041
+ `overwrite=False`), so the commit keeps it. Only an index the model declares comes back: another model's on the same
6042
+ table comes back with that model's `define_indexes(tx=…)`, and one no model declares stays removed. A raw
6043
+ `tx.add("REMOVE INDEX …")` is not tracked.
6039
6044
  - The analyzers must be in place: SurrealDB builds an index with the analyzers committed before the transaction began.
6040
6045
  So `define_indexes(tx=…)` raises `SurrealDbError` before any DDL when an analyzer must be defined or redefined, and
6041
6046
  `define_analyzer(tx=…)` when a redefinition has indexes to rebuild (a new analyzer, or a redefinition no index uses,
@@ -6044,11 +6049,15 @@ print(await NoteV2.objects().search(text="physics").count())
6044
6049
  wrote before the index was defined, which stay out of it after the commit. It is a server defect
6045
6050
  ([surrealdb/surrealdb#7618](https://github.com/surrealdb/surrealdb/issues/7618) on 3.x, the same on 2.x); only the
6046
6051
  embedded engine indexes them. So `define_indexes(tx=…)` raises `SurrealDbError` before any DDL, naming the model and
6047
- the table, when an index must be defined or redefined and the block has already written records to the model's table
6048
- with the ORM (`save()`, `objects(tx=…).bulk_create()`, …). The refusal does not fail the block. `define_table(tx=…)`,
6052
+ the table, when an index must be defined or redefined — one removed earlier in the block included — and the block
6053
+ has already written records to the model's table with the ORM (`save()`, `objects(tx=…).bulk_create()`, …). The
6054
+ refusal covers every kind of index, not only full-text ones: a search would miss those records, and a `UNIQUE` index
6055
+ missing them would not enforce uniqueness for them. The refusal does not fail the block. `define_table(tx=…)`,
6049
6056
  `define_relation(tx=…)` and a write to another table do not count; a raw `tx.add()` is not tracked.
6050
6057
  - Prefer `define_indexes()` outside the block: on SurrealDB 2.x, a write to a table that held records, after its index
6051
- in the same block, fails the commit with a retryable `SurrealDbConflictError` that a retry meets again.
6058
+ in the same block, fails the commit with a retryable `SurrealDbConflictError` that a retry meets again; so does a
6059
+ block that removes an index of a table that held records and defines it again, where the index stands as before.
6060
+ Nothing of such a block is committed. On an empty table both commit, as on 3.x.
6052
6061
  - `remove_analyzer(tx=…)` reads committed state to find the indexes that use the analyzer: an index queued earlier in
6053
6062
  a buffered block is not seen.
6054
6063
  - A search in an interactive transaction sees the transaction's writes; in a buffered one, a read raises, as every
@@ -6546,7 +6555,7 @@ features introduced in SurrealDB 3.x. On 2.x the ORM degrades gracefully. Capabi
6546
6555
  listed behave the same on both lines. The 2.x column was measured on 2.6.5 and holds unchanged
6547
6556
  on 2.7.0. The 3.x column was measured on 3.2.4 and holds on 3.3.0, except where a row says
6548
6557
  otherwise. The full suite and every divergence below were re-verified on both new versions.
6549
- Rows added in v0.20.0 were measured directly on 2.7.0 and 3.3.0; rows added in v0.21.0 on 2.7.0 and 3.3.2, re-verified on 3.3.3, with 3.1.5 where it differs; rows added in v0.22.0 on 2.7.0 and 3.3.3, with 3.1.5 where it differs; rows added in v0.23.0 on 2.7.0 and 3.3.4, with 3.1.5 where it differs; rows added in v0.24.0 on 2.7.0 and 3.3.4, identical on 3.1.5; rows added in v0.26.0 on 2.7.0 and 3.3.4, in memory and on versioned storage, identical on 3.1.5; rows added in v0.27.0 on 2.7.0 and 3.3.4, with 3.1.5 where it differs; rows added in v0.28.0 on 2.7.0 and 3.3.4, identical on 3.1.5; the rows added in v0.28.1 on 2.7.0 and 3.3.4, identical on 3.1.5; rows added in v0.29.0 on 2.7.0 and 3.3.4 in one process, identical on 3.1.5. The row added in v0.29.2 was measured on 2.7.0, 3.3.4 and the embedded engine, identical on 3.1.5. Rows added in v0.30.0 were measured on 2.7.0, 3.3.4 and the embedded engine, with 3.1.5 where it differs. The row added in v0.30.3 was measured on 2.7.0 and 3.3.4, over WebSocket and HTTP, and on the embedded engine, identical on 3.1.5. The row added in v0.30.7 was measured on 2.7.0, 3.3.4 and the embedded engine, identical on 3.1.5: its parser refuses a statement that nests six objects, and `update()` nests at most four. Rows added in v0.31.0 were measured on 2.7.0, 3.3.4 and the embedded engine, identical on 3.1.5. The row added in v0.31.1 was measured on 2.7.0, 3.3.4 and the embedded engine, identical on 3.1.5. Rows added in v0.32.0 were measured on 2.7.0, 3.3.4 and the embedded engine; 3.1.5 behaves as 3.3.4 but accepts raw writes to a view. Rows added in v0.33.0 were measured on 2.7.0, 3.3.4 and the embedded engine; 3.1.5 behaves as 3.3.4. Rows added in v0.34.0 were measured on 2.7.0, 3.3.4 and the embedded engine; 3.1.5 behaves as 3.3.4 except that it refuses a Python `set` written to a `set` field, and an object item of an optional untyped `list`. Rows added in v0.35.0 were measured on 2.7.0, 3.3.4 and the embedded engine, with 3.1.5 where it differs. The row added in v0.35.2 was measured on 2.7.0 and 3.3.4, identical on 3.1.5. The row added in v0.35.3 was measured on 2.7.0 and 3.3.4, over WebSocket and HTTP, and on the embedded engine, identical on 3.1.5. Rows added in v0.36.0 were measured on 2.7.0, 3.3.4 and the embedded engine, with 3.1.5 where it differs.
6558
+ Rows added in v0.20.0 were measured directly on 2.7.0 and 3.3.0; rows added in v0.21.0 on 2.7.0 and 3.3.2, re-verified on 3.3.3, with 3.1.5 where it differs; rows added in v0.22.0 on 2.7.0 and 3.3.3, with 3.1.5 where it differs; rows added in v0.23.0 on 2.7.0 and 3.3.4, with 3.1.5 where it differs; rows added in v0.24.0 on 2.7.0 and 3.3.4, identical on 3.1.5; rows added in v0.26.0 on 2.7.0 and 3.3.4, in memory and on versioned storage, identical on 3.1.5; rows added in v0.27.0 on 2.7.0 and 3.3.4, with 3.1.5 where it differs; rows added in v0.28.0 on 2.7.0 and 3.3.4, identical on 3.1.5; the rows added in v0.28.1 on 2.7.0 and 3.3.4, identical on 3.1.5; rows added in v0.29.0 on 2.7.0 and 3.3.4 in one process, identical on 3.1.5. The row added in v0.29.2 was measured on 2.7.0, 3.3.4 and the embedded engine, identical on 3.1.5. Rows added in v0.30.0 were measured on 2.7.0, 3.3.4 and the embedded engine, with 3.1.5 where it differs. The row added in v0.30.3 was measured on 2.7.0 and 3.3.4, over WebSocket and HTTP, and on the embedded engine, identical on 3.1.5. The row added in v0.30.7 was measured on 2.7.0, 3.3.4 and the embedded engine, identical on 3.1.5: its parser refuses a statement that nests six objects, and `update()` nests at most four. Rows added in v0.31.0 were measured on 2.7.0, 3.3.4 and the embedded engine, identical on 3.1.5. The row added in v0.31.1 was measured on 2.7.0, 3.3.4 and the embedded engine, identical on 3.1.5. Rows added in v0.32.0 were measured on 2.7.0, 3.3.4 and the embedded engine; 3.1.5 behaves as 3.3.4 but accepts raw writes to a view. Rows added in v0.33.0 were measured on 2.7.0, 3.3.4 and the embedded engine; 3.1.5 behaves as 3.3.4. Rows added in v0.34.0 were measured on 2.7.0, 3.3.4 and the embedded engine; 3.1.5 behaves as 3.3.4 except that it refuses a Python `set` written to a `set` field, and an object item of an optional untyped `list`. Rows added in v0.35.0 were measured on 2.7.0, 3.3.4 and the embedded engine, with 3.1.5 where it differs. The row added in v0.35.2 was measured on 2.7.0 and 3.3.4, identical on 3.1.5. The row added in v0.35.3 was measured on 2.7.0 and 3.3.4, over WebSocket and HTTP, and on the embedded engine, identical on 3.1.5. Rows added in v0.36.0 were measured on 2.7.0, 3.3.4 and the embedded engine, with 3.1.5 where it differs. The row added in v0.36.2 was measured on 2.7.0 and 3.3.4, over WebSocket and HTTP, and on the embedded engine, identical on 3.1.5.
6550
6559
  The SDK's in-process engine has a table of its own: [ORM behaviour: the embedded engine](#orm-behaviour-the-embedded-engine).
6551
6560
 
6552
6561
  | ORM capability | SurrealDB 2.6.x / 2.7.x | SurrealDB 3.2.x / 3.3.x | Since |
@@ -6706,6 +6715,7 @@ The SDK's in-process engine has a table of its own: [ORM behaviour: the embedded
6706
6715
  | `similar_to()` with a condition that keeps few records | HNSW is approximate: fewer than `limit` records, depending on how the index was built, even with a tenth of the table kept; `dist=` is exact | rarer; also seen with a `Subquery` id list keeping a few percent of the table | v0.36.0 |
6707
6716
  | `similar_to(dist=…)` with a condition on a linked record's field | the ORM selects the matching records first (a `LET`): 2.x's exact scan would return every matching record, ignoring `limit` | the condition stays next to the KNN operator | v0.36.0 |
6708
6717
  | `similar_to()` on a field without a vector index | no record | no record; 3.1 answers every record, with no distance | v0.36.0 |
6718
+ | `remove_index(tx=)` then `define_indexes(tx=)` in one block, the index stored before the block | on a table holding records, the commit fails with a retryable `SurrealDbConflictError`, again on retry: nothing committed, the index kept; on an empty table, defined again | the index is defined again after its removal and committed, serving the records committed before the block | v0.36.2 |
6709
6719
  | Full suite and every divergence in this table, re-run on SurrealDB 2.7.0 and 3.3.0 | 2.7.0 identical to 2.6.5 (same passes, same 3.x-only skips) | 3.3.0 identical to 3.2.4, except the system-user signin row | v0.19.1 |
6710
6720
 
6711
6721
  > **Note on record IDs**: A record loaded from the database has its `id` field set to a native `surrealdb.RecordID` object, not a plain string. Use `model.get_raw_id()` to obtain the bare identifier string (e.g. `"alice"`), or compare directly with `model.id == RecordID("User", "alice")`. In-memory instances you construct yourself retain whatever value you assign.
@@ -6745,6 +6755,7 @@ Capabilities not listed behave as on a 2.x server.
6745
6755
  | Full-text search (v0.35.0) | as on a 2.x server: `SEARCH ANALYZER`, a term in more than half the documents scores below zero, BM25 statistics grow with each rebuild and keep deleted records, `remove_analyzer()` refuses an analyzer an index uses; an index defined in the transaction that defines its analyzer sees it, which `define_indexes(tx=…)` refuses all the same | 3.x writes `FULLTEXT ANALYZER`, scores such a term `0.0`, keeps BM25 statistics exact and refuses that removal | v0.35.0 |
6746
6756
  | `define_indexes(tx=)` in a block that writes to the model's table | an ORM write before it: refused all the same, although this engine indexes its records; a write after it is committed and indexed | refused (left out of the index); on 2.x a write after it, to a table holding records, fails the commit | v0.35.3 |
6747
6757
  | Vector search (v0.36.0) | as on a 2.x server: `MTREE` accepted, at most `ef` records returned (the ORM raises `ef` to `limit`), other conditions selected first in a `LET` (search annotations refused), writes made by the ids of the nearest, fewer records with a selective condition; an index without `TYPE` is `F64` (servers: `F32`), so the ORM always writes `TYPE` | 3.x refuses `MTREE`, applies the conditions during the index search and keeps search annotations | v0.36.0 |
6758
+ | `remove_index(tx=)` then `define_indexes(tx=)` in one block | the index is defined again after its removal and committed, on a table holding records too | the same on 3.x; on 2.x, on a table holding records, the commit fails with a retryable conflict | v0.36.2 |
6748
6759
  | Everything else | CRUD, QuerySet, aggregations, relations, typed edges, rich and geo fields, upsert/patch, server values, computed fields, stored functions, signals: the same as on a 2.x server | unchanged | v0.25.0 |
6749
6760
 
6750
6761
  ---
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "surreal-orm-lite"
3
- version = "0.36.0"
3
+ version = "0.36.2"
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.2"
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.
@@ -1280,19 +1304,31 @@ class BaseSurrealModel(BaseModel):
1280
1304
  Before any DDL (nothing sent but the reads): an index that names by ``str`` an analyzer neither the database
1281
1305
  nor the model's ``Analyzer`` objects define is refused; with *tx*, an analyzer to define or redefine is refused
1282
1306
  — SurrealDB builds an index with the analyzers committed before the transaction began: define it first,
1283
- outside the block. With *tx*, an index to define or redefine is also refused when the transaction has already
1284
- written records to the model's table — an ORM write (``save()``, ``objects(tx=…).bulk_create()``, …) or one
1285
- noted on every table; a definition such as ``define_table(tx=…)`` does not count, nor does a raw ``tx.add()``,
1286
- which the ORM does not track: SurrealDB servers do not index the records a transaction wrote before the index
1287
- was defined, which stay out of it after the commit — a server defect (surrealdb/surrealdb#7618 on 3.x, the
1288
- same on 2.x; the embedded engine indexes them). The refusal does not fail the transaction; call
1289
- ``define_indexes()`` without *tx* first. With *tx* and the analyzers in place, the index statements join the
1290
- transaction — applied at once in an interactive one (WebSocket, SurrealDB 3.x),
1291
- at the commit in a buffered one (HTTP, SurrealDB 2.x, the embedded engine), where a refusal comes back as the
1292
- transaction's own error; a block that raises applies nothing. On SurrealDB 2.x, a write to a table that held
1293
- records, after its index in the same block, fails the commit with a retryable ``SurrealDbConflictError`` that a
1294
- retry meets again. In a buffered transaction an index queued earlier in the block is not seen by the reads, and
1295
- is queued again (the same statement). Every cached read is dropped.
1307
+ outside the block. With *tx*, an index to define or redefine (one removed in the block included) is also refused
1308
+ when the transaction has already written records to the model's table — an ORM write (``save()``,
1309
+ ``objects(tx=…).bulk_create()``, …) or one noted on every table; a definition such as ``define_table(tx=…)``
1310
+ does not count, nor does a raw ``tx.add()``, which the ORM does not track: SurrealDB servers do not index the
1311
+ records a transaction wrote before the index was defined, which stay out of it after the commit — a server
1312
+ defect (surrealdb/surrealdb#7618 on 3.x, the same on 2.x; the embedded engine indexes them). Every kind of
1313
+ index is refused, not only a full-text one: a search would miss those records, and a ``UNIQUE`` index would
1314
+ not enforce uniqueness for them. The refusal does not fail the transaction; call ``define_indexes()`` without
1315
+ *tx* first. With *tx* and the analyzers in place, the index statements join the transaction — applied at once
1316
+ in an interactive one (WebSocket, SurrealDB 3.x), at the commit in a buffered one (HTTP, SurrealDB 2.x, the
1317
+ embedded engine), where a refusal comes back as the transaction's own error; a block that raises applies
1318
+ nothing. On SurrealDB 2.x, a write to a table that held records, after its index in the same block, fails the
1319
+ commit with a retryable ``SurrealDbConflictError`` that a retry meets again; on an empty table it commits, as on
1320
+ 3.x. In a buffered transaction an index queued earlier in the block is not seen by the reads, and is queued
1321
+ again (the same statement). Every cached read is dropped.
1322
+
1323
+ **An index removed in the transaction.** With *tx*, an index :meth:`remove_index` removed with the same *tx*
1324
+ counts as missing, although the committed state the reads see still holds it: it is defined again after its
1325
+ removal (``DEFINE INDEX OVERWRITE``, or ``IF NOT EXISTS`` without *overwrite*), so the commit keeps it; a later
1326
+ call in the block compares it with committed state again. Only an index this model declares is defined again:
1327
+ another model's on the same table comes back with that model's ``define_indexes(tx=…)``, and one no model
1328
+ declares stays removed. A raw ``tx.add("REMOVE INDEX …")`` is not tracked. On SurrealDB 2.x, on a table that
1329
+ held records, a block that removes an index and defines it again fails the commit with a retryable
1330
+ ``SurrealDbConflictError`` that a retry meets again: nothing of the block is committed and the index stands as
1331
+ before; on an empty table it commits, as on 3.x.
1296
1332
 
1297
1333
  Names are written in backticks, filters re-rendered from a closed grammar, numbers from Python numbers,
1298
1334
  comments as string literals. A refusal names the analyzer or the index and its table, never the statement:
@@ -1304,15 +1340,16 @@ class BaseSurrealModel(BaseModel):
1304
1340
  overwrite: ``True`` (default) redefines a changed analyzer or index — the model wins. ``False`` defines
1305
1341
  what is missing (``IF NOT EXISTS``) and leaves what exists as it is.
1306
1342
  tx: optional transaction the index statements are applied with; the reads happen before anything is
1307
- queued.
1343
+ queued. An index :meth:`remove_index` removed with it counts as missing.
1308
1344
 
1309
1345
  Raises:
1310
1346
  TypeError: *overwrite* is not a ``bool`` — before any request.
1311
1347
  SurrealDbError: *tx* belongs to another connection — before any request; an analyzer named by ``str`` does
1312
1348
  not exist, or *tx* is given and an analyzer must be defined or redefined, or an index must be defined
1313
- or redefined after the transaction wrote records to the model's table (the message names the model and
1314
- the table) — before any DDL; the server refused a statement (``Can't apply analyzer definition: …``,
1315
- ``Can't apply index definition: …``, ``Can't apply index rebuild: …``).
1349
+ or redefined (one removed in the block included) after the transaction wrote records to the model's
1350
+ table (the message names the model and the table) — before any DDL; the server refused a statement
1351
+ (``Can't apply analyzer definition: …``, ``Can't apply index definition: …``, ``Can't apply index
1352
+ rebuild: …``).
1316
1353
  SurrealDbAuthenticationError: the session may not read the definitions or define the analyzers and
1317
1354
  indexes.
1318
1355
 
@@ -1353,6 +1390,11 @@ class BaseSurrealModel(BaseModel):
1353
1390
  if any(index.search_analyzer is not None for index in indexes):
1354
1391
  keyword = fulltext_keyword(_time_travel.line_major(await client.version()))
1355
1392
  stored_indexes = await read_table_indexes(client, table, what="index", kind="definition")
1393
+ # Issue #312: an index remove_index(tx=…) removed in this transaction still stands in committed state; it is
1394
+ # missing once the transaction commits, so it is planned as missing (DEFINE INDEX after the removal).
1395
+ removed = tx._indexes_removed(table) if isinstance(tx, Transaction) else frozenset()
1396
+ if removed:
1397
+ stored_indexes = {name: state for name, state in stored_indexes.items() if name not in removed}
1356
1398
  redefined = {analyzer.name for analyzer in redefine}
1357
1399
  definitions, rebuilds = plan_indexes(
1358
1400
  indexes,
@@ -1390,6 +1432,8 @@ class BaseSurrealModel(BaseModel):
1390
1432
  classify=True,
1391
1433
  subjects=[index_subject(name, table) for name, _ in definitions],
1392
1434
  )
1435
+ if removed and isinstance(tx, Transaction):
1436
+ tx._forget_index_removals(table, (name for name, _ in definitions))
1393
1437
  applied += await apply_rebuilds(client, tx, own_rebuilds)
1394
1438
  warn_redefined(redefine, [*other_rebuilds, *redefined_indexes, *own_rebuilds])
1395
1439
  return applied
@@ -1405,11 +1449,18 @@ class BaseSurrealModel(BaseModel):
1405
1449
  not starting with a digit), checked before any request. The model's cached reads are dropped. A ``search()`` of
1406
1450
  the field afterwards raises ``SurrealDbError`` until an index covers it again.
1407
1451
 
1452
+ With *tx*, the transaction notes the removal: :meth:`define_indexes` called later with the same *tx* counts the
1453
+ index as missing, although committed state still holds it, and defines it again after the removal when its
1454
+ model declares it — so removing an index and defining it again in one block keeps it. On SurrealDB 2.x, on a
1455
+ table that held records, such a block fails the commit with a retryable ``SurrealDbConflictError`` that a retry
1456
+ meets again, and nothing of it is committed. A raw ``tx.add("REMOVE INDEX …")`` is not noted.
1457
+
1408
1458
  Args:
1409
1459
  name: the index's name.
1410
1460
  missing_ok: ``True`` (default) emits ``REMOVE INDEX IF EXISTS …``, so a missing index is not an error;
1411
1461
  ``False`` raises ``SurrealDbNotFoundError`` for it.
1412
- tx: optional transaction the statement is applied with.
1462
+ tx: optional transaction the statement is applied with; it notes the removal for
1463
+ :meth:`define_indexes`.
1413
1464
 
1414
1465
  Raises:
1415
1466
  TypeError, ValueError: *name* is not an identifier, or *missing_ok* not a ``bool`` — before any request.
@@ -1438,6 +1489,9 @@ class BaseSurrealModel(BaseModel):
1438
1489
  classify=True,
1439
1490
  subjects=[index_subject(name, table)],
1440
1491
  )
1492
+ if isinstance(tx, Transaction):
1493
+ # Issue #312: define_indexes(tx=…) reads committed state, where the index still stands.
1494
+ tx._note_index_removal(table, name)
1441
1495
  return statement
1442
1496
 
1443
1497
  # ==================== Materialized views (v0.32.0) ====================
@@ -1473,8 +1527,10 @@ class BaseSurrealModel(BaseModel):
1473
1527
 
1474
1528
  SurrealDB computes a view's records from its ``view_query``, so the ORM never writes them: the first statement
1475
1529
  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.
1530
+ signal, transaction use or request. An instance write runs it through its ``invalidates(refuse=…)``
1531
+ (:func:`_write_refusals`), before its table is noted on the transaction, which a refused write leaves as it
1532
+ was (#315). The relation helpers write the edge table, not the view, and stay allowed; raw SurrealQL is never
1533
+ guarded.
1478
1534
 
1479
1535
  Raises:
1480
1536
  TypeError: the model is a materialized view (W1, naming the class and *call*).
@@ -1491,7 +1547,9 @@ class BaseSurrealModel(BaseModel):
1491
1547
  Called by :meth:`_table_ddl`, after its other refusals, and by the full replaces :meth:`update` and
1492
1548
  :meth:`upsert`, right after the view and snapshot checks — before any signal, transaction use or request: they
1493
1549
  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).
1550
+ every later signin fails). There it runs in their ``invalidates(refuse=…)`` (:func:`_write_refusals`), before
1551
+ the model's table is noted on the transaction: a refused ``update(tx=…)`` or ``upsert(tx=…)`` leaves nothing on
1552
+ the transaction — no statement, and no table noted for ``define_indexes(tx=…)`` or the query cache (#315).
1495
1553
 
1496
1554
  Raises:
1497
1555
  TypeError: the auth model and those fields, in declaration order (``schema.signup_excluded_refused()``).
@@ -3076,20 +3134,22 @@ class BaseSurrealModel(BaseModel):
3076
3134
  self._apply_record(rows)
3077
3135
  return self, True
3078
3136
 
3079
- @_cache.invalidates("self")
3137
+ @_cache.invalidates("self", refuse=_write_refusals("save()"))
3080
3138
  async def _save_naming(self, fields: Iterable[str], tx: Transaction | None = None) -> Self:
3081
3139
  """``save()`` that also writes the ``server_fields`` among ``fields``.
3082
3140
 
3083
3141
  Backs the create branch of ``get_or_create``/``update_or_create``, where a server field
3084
3142
  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.
3143
+ stored, or the next identical lookup would miss the row and create another one. It refuses a
3144
+ materialized view and a snapshot as ``save()`` does, naming ``save()``, before its table is noted
3145
+ on the transaction (#315) — also when it writes a server field, which does not go through ``save()``.
3086
3146
  """
3087
3147
  keep = frozenset(fields) & self.get_server_fields()
3088
3148
  if not keep:
3089
3149
  return await self.save(tx=tx)
3090
3150
  return await self._save_with_signals(functools.partial(self._do_save, keep=keep), tx)
3091
3151
 
3092
- @_cache.invalidates("self")
3152
+ @_cache.invalidates("self", refuse=_write_refusals("save()"))
3093
3153
  async def save(
3094
3154
  self,
3095
3155
  tx: Transaction | None = None,
@@ -3137,8 +3197,6 @@ class BaseSurrealModel(BaseModel):
3137
3197
  values are unknown until commit, so the instance keeps its pre-save values for
3138
3198
  those fields — ``refresh()`` after commit if you need them.
3139
3199
  """
3140
- self._reject_view_write("save()")
3141
- self._reject_snapshot_write("save()")
3142
3200
  self._validate_server_values(server_values, extra_vars)
3143
3201
  if server_values:
3144
3202
  self._reject_computed_writes(server_values, "save(server_values=)")
@@ -3398,7 +3456,7 @@ class BaseSurrealModel(BaseModel):
3398
3456
  return rows[0].get("before"), rows[0].get("after")
3399
3457
  return None, None
3400
3458
 
3401
- @_cache.invalidates("self")
3459
+ @_cache.invalidates("self", refuse=_write_refusals("upsert()", signup=True))
3402
3460
  async def upsert(self, tx: Transaction | None = None) -> Self:
3403
3461
  """
3404
3462
  Insert the model instance, or fully replace it if a record with the same id exists.
@@ -3416,6 +3474,11 @@ class BaseSurrealModel(BaseModel):
3416
3474
  in a transaction ``around_save`` is skipped and ``post_save`` is deferred to a
3417
3475
  successful commit (consistent with ``save(tx=)``).
3418
3476
 
3477
+ The view, snapshot and SG1 refusals below come before the model's table is noted on
3478
+ ``tx``: a call they refuse leaves nothing on the transaction — no statement, and no table
3479
+ noted as written, so a later ``define_indexes(tx=…)`` of the model is not refused for it
3480
+ and the commit drops no cached read for it (#315).
3481
+
3419
3482
  Raises:
3420
3483
  TypeError: the model is a materialized view (W1); or an auth model
3421
3484
  (``AuthenticatedUserMixin``) with a field SIGNUP writes that ``Field(exclude=True)``
@@ -3424,12 +3487,9 @@ class BaseSurrealModel(BaseModel):
3424
3487
  without ``tx``.
3425
3488
  SurrealDbError: the instance is a snapshot read with ``as_of()``.
3426
3489
  """
3427
- self._reject_view_write("upsert()")
3428
- self._reject_snapshot_write("upsert()")
3429
- self._reject_signup_excluded()
3430
3490
  return await self._save_with_signals(self._do_upsert, tx)
3431
3491
 
3432
- @_cache.invalidates("self")
3492
+ @_cache.invalidates("self", refuse=_write_refusals("update()", signup=True))
3433
3493
  async def update(self, tx: Transaction | None = None) -> Any:
3434
3494
  """
3435
3495
  Update the model instance to the database.
@@ -3474,6 +3534,11 @@ class BaseSurrealModel(BaseModel):
3474
3534
  The updated row as the SDK reads it (``[]`` for a record that does not exist), or
3475
3535
  ``None`` in a transaction.
3476
3536
 
3537
+ The view, snapshot and SG1 refusals below come before the model's table is noted on
3538
+ ``tx``: a call they refuse leaves nothing on the transaction — no statement, and no table
3539
+ noted as written, so a later ``define_indexes(tx=…)`` of the model is not refused for it
3540
+ and the commit drops no cached read for it (#315).
3541
+
3477
3542
  Raises:
3478
3543
  TypeError: the model is a materialized view (W1); or an auth model
3479
3544
  (``AuthenticatedUserMixin``) with a field SIGNUP writes that ``Field(exclude=True)``
@@ -3482,9 +3547,6 @@ class BaseSurrealModel(BaseModel):
3482
3547
  without ``tx``.
3483
3548
  SurrealDbError: the instance is a snapshot read with ``as_of()``, or it has no id.
3484
3549
  """
3485
- self._reject_view_write("update()")
3486
- self._reject_snapshot_write("update()")
3487
- self._reject_signup_excluded()
3488
3550
  sender = self.__class__
3489
3551
  data = self._write_payload(replace=True)
3490
3552
  record_id = self._record_id()
@@ -3593,7 +3655,7 @@ class BaseSurrealModel(BaseModel):
3593
3655
  await post_update.send(sender, instance=self, update_fields=update_fields)
3594
3656
  return None
3595
3657
 
3596
- @_cache.invalidates("self")
3658
+ @_cache.invalidates("self", refuse=_write_refusals("merge()"))
3597
3659
  async def merge(
3598
3660
  self,
3599
3661
  tx: Transaction | None = None,
@@ -3647,8 +3709,6 @@ class BaseSurrealModel(BaseModel):
3647
3709
  >>> await user.merge(plan="pro", server_values={"updated_at": SurrealFunc("time::now()")})
3648
3710
  >>> await user.merge(last_seen=now, refresh=False) # fire-and-forget
3649
3711
  """
3650
- self._reject_view_write("merge()")
3651
- self._reject_snapshot_write("merge()")
3652
3712
  self._reject_computed_writes(data, "merge()")
3653
3713
  self._validate_server_values(server_values, extra_vars)
3654
3714
  if server_values:
@@ -3692,7 +3752,7 @@ class BaseSurrealModel(BaseModel):
3692
3752
 
3693
3753
  # ==================== Patch & atomic operations ====================
3694
3754
 
3695
- @_cache.invalidates("self")
3755
+ @_cache.invalidates("self", refuse=_write_refusals("patch()"))
3696
3756
  async def patch(self, operations: list[dict[str, Any]], tx: Transaction | None = None) -> Self:
3697
3757
  """Apply a JSON Patch (RFC 6902) to this record.
3698
3758
 
@@ -3710,8 +3770,6 @@ class BaseSurrealModel(BaseModel):
3710
3770
  name a field either way — ``/password`` or its column ``/password_hash`` — and are
3711
3771
  rewritten to the column before they are sent.
3712
3772
  """
3713
- self._reject_view_write("patch()")
3714
- self._reject_snapshot_write("patch()")
3715
3773
  validate_patch_operations(operations)
3716
3774
  self._reject_computed_patch(operations, "patch()")
3717
3775
  operations = self._columns_for_patch(operations)
@@ -3727,18 +3785,16 @@ class BaseSurrealModel(BaseModel):
3727
3785
  self._apply_record(record)
3728
3786
  return self
3729
3787
 
3730
- async def _atomic_update(self, set_expr: str, variables: dict[str, Any], tx: Transaction | None, *, label: str) -> Self:
3788
+ async def _atomic_update(self, set_expr: str, variables: dict[str, Any], tx: Transaction | None) -> Self:
3731
3789
  """Run ``UPDATE $rid SET <set_expr>`` atomically and sync ``self`` with the result.
3732
3790
 
3733
3791
  Shared by the atomic helpers. ``$rid`` and every value in ``variables`` are bound
3734
3792
  (robust for any id type; anti-injection); only the validated ``set_expr`` is inlined.
3735
3793
  Non-tx and interactive-tx apply the returned row to ``self``; a buffered tx leaves
3736
3794
  ``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).
3795
+ Each helper refuses a materialized view (v0.32.0) and a snapshot (v0.26.0) under its own
3796
+ name through its ``invalidates(refuse=…)`` (#315), before its field is checked.
3739
3797
  """
3740
- self._reject_view_write(label)
3741
- self._reject_snapshot_write(label)
3742
3798
  record_id = self._record_id()
3743
3799
  if record_id is None:
3744
3800
  raise SurrealDbError("atomic operations require an explicit id.")
@@ -3753,7 +3809,7 @@ class BaseSurrealModel(BaseModel):
3753
3809
  self._apply_record(rows)
3754
3810
  return self
3755
3811
 
3756
- @_cache.invalidates("self")
3812
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_append()"))
3757
3813
  async def atomic_append(self, field: str, value: Any, tx: Transaction | None = None) -> Self:
3758
3814
  """Atomically append ``value`` to an array ``field`` (duplicates allowed).
3759
3815
 
@@ -3761,11 +3817,9 @@ class BaseSurrealModel(BaseModel):
3761
3817
  semantics (skip if already present) use :meth:`atomic_set_add`. Emits no signals.
3762
3818
  """
3763
3819
  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
- )
3820
+ return await self._atomic_update(f"{column} = array::append({column}, $value)", {"value": value}, tx)
3767
3821
 
3768
- @_cache.invalidates("self")
3822
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_remove()"))
3769
3823
  async def atomic_remove(self, field: str, value: Any, tx: Transaction | None = None) -> Self:
3770
3824
  """Atomically remove ALL occurrences of ``value`` from an array ``field``.
3771
3825
 
@@ -3774,11 +3828,9 @@ class BaseSurrealModel(BaseModel):
3774
3828
  but only the first on 2.6.x.) Emits no signals.
3775
3829
  """
3776
3830
  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
- )
3831
+ return await self._atomic_update(f"{column} = array::complement({column}, [$value])", {"value": value}, tx)
3780
3832
 
3781
- @_cache.invalidates("self")
3833
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_set_add()"))
3782
3834
  async def atomic_set_add(self, field: str, value: Any, tx: Transaction | None = None) -> Self:
3783
3835
  """Atomically add ``value`` to an array ``field`` only if not already present.
3784
3836
 
@@ -3786,11 +3838,9 @@ class BaseSurrealModel(BaseModel):
3786
3838
  ``+=`` operator, which appends duplicates on both server lines.) Emits no signals.
3787
3839
  """
3788
3840
  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
- )
3841
+ return await self._atomic_update(f"{column} = array::add({column}, $value)", {"value": value}, tx)
3792
3842
 
3793
- @_cache.invalidates("self")
3843
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_increment()"))
3794
3844
  async def atomic_increment(self, field: str, amount: Decimal | int | float = 1, tx: Transaction | None = None) -> Self:
3795
3845
  """Atomically add ``amount`` (default 1) to a numeric ``field``.
3796
3846
 
@@ -3811,7 +3861,7 @@ class BaseSurrealModel(BaseModel):
3811
3861
  f"Set the new value with merge({field}=…) instead."
3812
3862
  )
3813
3863
  column = self._validate_atomic_field(field)
3814
- return await self._atomic_update(f"{column} += $amount", {"amount": amount}, tx, label="atomic_increment()")
3864
+ return await self._atomic_update(f"{column} += $amount", {"amount": amount}, tx)
3815
3865
 
3816
3866
  @staticmethod
3817
3867
  def _as_value_list(values: Any) -> list[Any]:
@@ -3822,7 +3872,7 @@ class BaseSurrealModel(BaseModel):
3822
3872
  return list(values)
3823
3873
  raise ValueError(f"values must be a list of items, got {type(values).__name__}")
3824
3874
 
3825
- @_cache.invalidates("self")
3875
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_append_many()"))
3826
3876
  async def atomic_append_many(self, field: str, values: list[Any], tx: Transaction | None = None) -> Self:
3827
3877
  """Atomically append every element of ``values`` to an array ``field`` (duplicates allowed).
3828
3878
 
@@ -3836,10 +3886,9 @@ class BaseSurrealModel(BaseModel):
3836
3886
  f"{column} = array::concat({column}, $values)",
3837
3887
  {"values": self._as_value_list(values)},
3838
3888
  tx,
3839
- label="atomic_append_many()",
3840
3889
  )
3841
3890
 
3842
- @_cache.invalidates("self")
3891
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_set_add_many()"))
3843
3892
  async def atomic_set_add_many(self, field: str, values: list[Any], tx: Transaction | None = None) -> Self:
3844
3893
  """Atomically add every element of ``values`` to an array ``field``, skipping any already present.
3845
3894
 
@@ -3852,10 +3901,9 @@ class BaseSurrealModel(BaseModel):
3852
3901
  f"{column} = array::add({column}, $values)",
3853
3902
  {"values": self._as_value_list(values)},
3854
3903
  tx,
3855
- label="atomic_set_add_many()",
3856
3904
  )
3857
3905
 
3858
- @_cache.invalidates("self")
3906
+ @_cache.invalidates("self", refuse=_write_refusals("atomic_remove_many()"))
3859
3907
  async def atomic_remove_many(self, field: str, values: list[Any], tx: Transaction | None = None) -> Self:
3860
3908
  """Atomically remove ALL occurrences of every element of ``values`` from an array ``field``.
3861
3909
 
@@ -3867,10 +3915,9 @@ class BaseSurrealModel(BaseModel):
3867
3915
  f"{column} = array::complement({column}, $values)",
3868
3916
  {"values": self._as_value_list(values)},
3869
3917
  tx,
3870
- label="atomic_remove_many()",
3871
3918
  )
3872
3919
 
3873
- @_cache.invalidates("self", deletes=True)
3920
+ @_cache.invalidates("self", deletes=True, refuse=_write_refusals("delete()"))
3874
3921
  async def delete(self, tx: Transaction | None = None) -> None:
3875
3922
  """
3876
3923
  Delete the model instance from the database.
@@ -3884,8 +3931,6 @@ class BaseSurrealModel(BaseModel):
3884
3931
  ``around_delete`` is skipped (the write is deferred to commit) and
3885
3932
  ``post_delete`` only fires after a successful commit.
3886
3933
  """
3887
- self._reject_view_write("delete()")
3888
- self._reject_snapshot_write("delete()")
3889
3934
  sender = self.__class__
3890
3935
  record_id = self._record_id()
3891
3936
  if record_id is None:
@@ -4119,7 +4164,7 @@ class BaseSurrealModel(BaseModel):
4119
4164
  **edge_data: Any,
4120
4165
  ) -> list[dict[str, Any]]: ...
4121
4166
 
4122
- @_cache.invalidates("edge")
4167
+ @_cache.invalidates("edge", refuse=_write_refusals("relate()", view=False))
4123
4168
  async def relate(
4124
4169
  self,
4125
4170
  edge: "str | type[BaseSurrealEdge]",
@@ -4202,7 +4247,6 @@ class BaseSurrealModel(BaseModel):
4202
4247
  async with SurrealDBConnectionManager.transaction() as tx:
4203
4248
  await user.relate(Follows, other_user, tx=tx)
4204
4249
  """
4205
- self._reject_snapshot_write("relate()")
4206
4250
  self._check_relation("relate", self._model_of(target), self._edge_model(edge))
4207
4251
  if isinstance(edge, type) and issubclass(edge, BaseSurrealModel) and edge.__surreal_edge__:
4208
4252
  fields = self._merge_edge_fields(data, edge_data, edge.to_py_field)
@@ -4329,7 +4373,7 @@ class BaseSurrealModel(BaseModel):
4329
4373
  with contextlib.suppress(NotFoundError):
4330
4374
  await client.query(statement, _encoding.encode(variables))
4331
4375
 
4332
- @_cache.invalidates("edge")
4376
+ @_cache.invalidates("edge", refuse=_write_refusals("remove_relation()", view=False))
4333
4377
  async def remove_relation(
4334
4378
  self,
4335
4379
  edge: "str | type[BaseSurrealEdge]",
@@ -4390,7 +4434,6 @@ class BaseSurrealModel(BaseModel):
4390
4434
  async with SurrealDBConnectionManager.transaction() as tx:
4391
4435
  await user.remove_relation(Follows, other_user, tx=tx)
4392
4436
  """
4393
- self._reject_snapshot_write("remove_relation()")
4394
4437
  self._check_relation("remove_relation", self._model_of(target), self._edge_model(edge))
4395
4438
  edge_name = self._edge_name(edge)
4396
4439
  source = self._graph_source()
@@ -4408,7 +4451,7 @@ class BaseSurrealModel(BaseModel):
4408
4451
  variables = {"src": source, "dst": self._graph_target(target)}
4409
4452
  await self._run_graph_delete(statement, variables, tx)
4410
4453
 
4411
- @_cache.invalidates("edge")
4454
+ @_cache.invalidates("edge", refuse=_write_refusals("remove_all_relations()", view=False))
4412
4455
  async def remove_all_relations(
4413
4456
  self,
4414
4457
  edge: "str | type[BaseSurrealEdge] | Sequence[str | type[BaseSurrealEdge]]",
@@ -4453,7 +4496,6 @@ class BaseSurrealModel(BaseModel):
4453
4496
  async with SurrealDBConnectionManager.transaction() as tx:
4454
4497
  await user.remove_all_relations(["likes", "blocks"], direction="both", tx=tx)
4455
4498
  """
4456
- self._reject_snapshot_write("remove_all_relations()")
4457
4499
  self._check_direction(direction)
4458
4500
  edges = edge if isinstance(edge, (list, tuple)) else (edge,)
4459
4501
  self._check_relation("remove_all_relations", *(self._edge_model(item) for item in edges))
@@ -30,6 +30,11 @@ Records written (issue #304): an ORM write of records that joins a transaction a
30
30
  for the cache only. ``define_indexes(tx=…)`` reads them (``_records_written``): SurrealDB servers do not index the
31
31
  records a transaction wrote before the index was defined. A raw ``tx.add()`` is not noted.
32
32
 
33
+ Indexes removed (issue #312): ``remove_index(tx=…)`` notes the index it removes, by table (``_note_index_removal``).
34
+ ``define_indexes(tx=…)`` reads committed state, where that index still stands: it counts the indexes noted for its table
35
+ (``_indexes_removed``) as missing, plans them again, and forgets those it defines (``_forget_index_removals``). The
36
+ commit and the cancel keep the note, like the tables written. A raw ``tx.add("REMOVE INDEX …")`` is not noted.
37
+
33
38
  Errors (issue #278): the errors a failed transaction raises give the server's reason and the failed statement's
34
39
  position, without the server's excerpt of the statement; the server's own text stays reachable as their suppressed
35
40
  ``__context__``. A query the server or the embedded engine refuses at a buffered commit raises ``SurrealDbError`` on
@@ -232,6 +237,9 @@ class Transaction(ABC):
232
237
  # until the transaction ends.
233
238
  self._record_tables: set[str] = set()
234
239
  self._record_all = False
240
+ # Issue #312: the indexes remove_index(tx=…) removed in this transaction, by table, until define_indexes(tx=…)
241
+ # defines them again; kept until the transaction ends.
242
+ self._removed_indexes: dict[str, set[str]] = {}
235
243
  # Issue #268: the errors of the statements that failed in this transaction (interactive strategy).
236
244
  self._failures: list[BaseException] = []
237
245
 
@@ -277,8 +285,10 @@ class Transaction(ABC):
277
285
  """Note the tables an ORM write of records in this transaction changes (``None``: every table) — issue #304.
278
286
 
279
287
  ``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.
288
+ is sent or queued and after the method's own refusals (``invalidates(refuse=…)``: an instance write the model
289
+ refuses as a materialized view, a snapshot or SG1 notes nothing, #315) — never for a definition
290
+ (``define_table()``, ``remove_index()``…), whose table is noted for the query cache only. Unlike the query
291
+ cache's tables, the commit and the cancel keep them.
282
292
  """
283
293
  if tables is None:
284
294
  self._record_all = True
@@ -290,6 +300,27 @@ class Transaction(ABC):
290
300
  every table. ``define_indexes(tx=…)`` reads it; a raw ``tx.add()`` is not counted."""
291
301
  return None if self._record_all else frozenset(self._record_tables)
292
302
 
303
+ def _note_index_removal(self, table: str, name: str) -> None:
304
+ """Note that the index *name* of *table* was removed in this transaction — issue #312.
305
+
306
+ ``remove_index(tx=…)`` calls it once its ``REMOVE INDEX`` was applied (interactive) or queued (buffered).
307
+ ``define_indexes(tx=…)``, which reads committed state where the index still stands, counts it as missing. Like
308
+ the tables written, the commit and the cancel keep it. A raw ``tx.add()`` is not noted.
309
+ """
310
+ self._removed_indexes.setdefault(table, set()).add(name)
311
+
312
+ def _indexes_removed(self, table: str) -> frozenset[str]:
313
+ """The indexes of *table* removed in this transaction and not defined again since (issue #312)."""
314
+ return frozenset(self._removed_indexes.get(table, ()))
315
+
316
+ def _forget_index_removals(self, table: str, names: Iterable[str]) -> None:
317
+ """Forget the removal of the indexes *names* of *table*, which ``define_indexes(tx=…)`` defined again in this
318
+ transaction (issue #312): a later call compares them with committed state again, as any index the transaction
319
+ did not remove, instead of defining them once more. A name not noted is ignored."""
320
+ removed = self._removed_indexes.get(table)
321
+ if removed is not None:
322
+ removed.difference_update(names)
323
+
293
324
  @property
294
325
  @abstractmethod
295
326
  def is_interactive(self) -> bool: