surreal-orm-lite 0.37.0__tar.gz → 0.37.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 (51) hide show
  1. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/CHANGELOG.md +74 -1
  2. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/PKG-INFO +17 -6
  3. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/README.md +16 -5
  4. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/pyproject.toml +1 -1
  5. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/__init__.py +1 -1
  6. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/model_base.py +106 -11
  7. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/query_set.py +3 -0
  8. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/search.py +2 -1
  9. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/utils.py +22 -0
  10. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/vector.py +28 -19
  11. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/.gitignore +0 -0
  12. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/LICENSE +0 -0
  13. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/Makefile +0 -0
  14. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/_sdk.py +0 -0
  15. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/aggregations.py +0 -0
  16. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/auth.py +0 -0
  17. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/cache.py +0 -0
  18. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/changefeed.py +0 -0
  19. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/concurrency.py +0 -0
  20. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/connection_config.py +0 -0
  21. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/connection_manager.py +0 -0
  22. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/constants.py +0 -0
  23. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/decoding.py +0 -0
  24. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/define_parser.py +0 -0
  25. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/edge.py +0 -0
  26. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/embedded.py +0 -0
  27. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/encoding.py +0 -0
  28. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/enum.py +0 -0
  29. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/exceptions.py +0 -0
  30. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/functions.py +0 -0
  31. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/geo.py +0 -0
  32. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/hybrid.py +0 -0
  33. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/introspection.py +0 -0
  34. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/live.py +0 -0
  35. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/model_auth.py +0 -0
  36. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/model_ddl.py +0 -0
  37. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/model_generator.py +0 -0
  38. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/py.typed +0 -0
  39. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/q.py +0 -0
  40. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/routing.py +0 -0
  41. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/schema.py +0 -0
  42. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/schema_state.py +0 -0
  43. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/signals.py +0 -0
  44. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/subquery.py +0 -0
  45. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/surql_literal.py +0 -0
  46. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/testing/__init__.py +0 -0
  47. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/testing/database.py +0 -0
  48. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/testing/fixtures.py +0 -0
  49. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/time_travel.py +0 -0
  50. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/transaction.py +0 -0
  51. {surreal_orm_lite-0.37.0 → surreal_orm_lite-0.37.1}/src/surreal_orm_lite/types.py +0 -0
@@ -5,6 +5,78 @@ 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.37.1] - 2026-10-24
9
+
10
+ Follow-ups to the review of v0.36.3 (#327): a `Literal[None]` member of a vector field's union
11
+ reads as `None`, and a vector field declared through a forward reference gets the vector checks
12
+ of the `class` statement once its name resolves. Any model a forward reference left incomplete is
13
+ completed before the ORM writes its DDL or builds a queryset. No new public API.
14
+
15
+ ### Fixed
16
+
17
+ - **`VectorField[d] | Literal[None]` is read as a vector field** (#327). Since v0.36.3 a
18
+ `Literal[None]` union member counted as a type other than `None`: `get_vector_info()` and
19
+ `is_vector_field()` raised `ValueError` for that annotation and the `class` statement refused
20
+ the field, although `Literal[None]` admits only `None` and `define_table()` already read it as
21
+ `None`. Such a member now counts as `None`: the annotation gives `(d, 'F32')` wherever
22
+ `VectorField[d] | None` does (`get_vector_info()`, `is_vector_field()`, the `class`-statement
23
+ checks of a vector index, `similar_to()`, and `define_table()` with
24
+ `option<array<float, d>>`). A `Literal` holding another value (`Literal[None, "x"]`) next to a
25
+ marker is still refused.
26
+ - **A vector field declared through a forward reference is checked once its name resolves**
27
+ (#327). A field annotated with a name defined after the class (`e: "Later" = None`, then
28
+ `Later = VectorField[3]`) has no `Vector` marker at the `class` statement, so since v0.36.0 the
29
+ vector checks skipped it: a vector index of another dimension or storage type, or an ambiguous
30
+ annotation such as `Later = VectorField[3] | str`, was accepted once `model_rebuild()` or the
31
+ model's first use resolved the name. Until then, `table_ddl()` and `define_table()` wrote the
32
+ column as `any`, `define_indexes()` defined the index unchecked and `similar_to()` accepted a
33
+ query vector of any length, without an error. The checks now run again when Pydantic completes
34
+ the model (at `model_rebuild()`, or at its first instantiation, validation or JSON schema), and
35
+ the ORM completes such a model before `table_ddl()`, `define_table()`, `index_ddl()`,
36
+ `define_indexes()`, `get_indexes()` or a queryset (`similar_to()` included) reads it, resolving
37
+ the name as Pydantic's first instantiation does: with the local names of the caller, then the
38
+ names of the model's module (a caller's local name wins, and the field keeps what it resolved
39
+ to). The refusals are those of the field written directly, naming the model, the index and
40
+ the field, raised before anything is sent; a refused model stays incomplete, so each of these
41
+ calls raises the same error again. A matching index is accepted, and `similar_to()` checks the
42
+ query vector against the field's dimension. A name still undefined leaves the model incomplete
43
+ and read as before. A model complete at its `class` statement is checked there only, in the same
44
+ order and with the same messages.
45
+ - **Every model a forward reference left incomplete is completed before the ORM reads it**
46
+ (#327). The completion of the previous bullet applies to any model Pydantic could not complete
47
+ at its `class` statement, with or without a vector field: `table_ddl()`, `define_table()`,
48
+ `index_ddl()`, `define_indexes()`, `get_indexes()` and every queryset complete it first. Until
49
+ now such a model was read with its unresolved fields as `any` until `model_rebuild()` or its
50
+ first instance: in `Author` with `best: "Book | None" = None` and `score: "Score" = 0`, `Book`
51
+ and `Score = int` defined after it, `table_ddl()` and `define_table()` wrote `best TYPE any`
52
+ and `score TYPE any DEFAULT 0`, and the cross-connection check of a queryset that follows a
53
+ link (`fetch()`) saw no linked model in such a field. Its columns now get the resolved kinds,
54
+ whether or not the model was instantiated first — what these calls already wrote after an
55
+ instance: `best TYPE option<object> FLEXIBLE` and `score TYPE int DEFAULT 0` on a `SCHEMAFULL`
56
+ table —, and its links are resolved for the cross-connection check, without `model_rebuild()`.
57
+ **Upgrading**: `define_table()` on such a model now redefines a column it wrote `any` with its
58
+ kind, and SurrealDB checks the values written to that column against it from then on. A name
59
+ still undefined leaves the model read as before.
60
+
61
+ ### Notes
62
+
63
+ - **CHANGELOG correction**: the `### Changed` bullet of `## [0.36.3]` said that every spelling
64
+ v0.36.2 read as a vector field gives the same result. A field with two different `Vector`
65
+ markers, which v0.36.2 read by its first marker, is refused since v0.36.3: the sentence now
66
+ reads "Every spelling with a single `Vector` marker that v0.36.2 read as a vector field gives
67
+ the same result."
68
+ - **Docs**: README section 37 (Vector search) says that `get_vector_info()` and
69
+ `is_vector_field()` raise `ValueError` for a field or annotation with no single dimension (code
70
+ that scans the fields of a plain Pydantic model has no `class`-statement check, so it gets the
71
+ exception where v0.36.2 returned `False`), that a `Literal[None]` member counts as `None`, and
72
+ which calls check a field declared through a forward reference. Section 35 (Model table DDL)
73
+ says that such a field gets the kind of the type its name resolves to, before or after an
74
+ instance.
75
+ - The fixes are in the ORM's model checks, built on Pydantic's `__pydantic_on_complete__` hook
76
+ (available in the supported `pydantic>=2.13.4`): the behaviour is the same on SurrealDB 2.x and
77
+ 3.x and on the embedded engine. Server pins unchanged: tested against SurrealDB 3.3.4 and 2.7.0,
78
+ plus 3.1.5 for backward compatibility.
79
+
8
80
  ## [0.37.0] - 2026-10-24
9
81
 
10
82
  Hybrid search: a queryset fuses the records nearest to a query vector, as `similar_to()` finds
@@ -212,7 +284,8 @@ Follow-up to the review of v0.36.0 (#316): a vector field declared with `| None`
212
284
  whether or not it declares indexes. Until v0.36.2 such a model was accepted (the first of two
213
285
  markers decided the checks, a union with another type was not a vector field).
214
286
  `get_vector_info()` and `is_vector_field()` raise the same `ValueError` for such a field or
215
- annotation. Every spelling that v0.36.2 read as a vector field gives the same result.
287
+ annotation. Every spelling with a single `Vector` marker that v0.36.2 read as a vector field
288
+ gives the same result.
216
289
 
217
290
  ### Notes
218
291
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: surreal-orm-lite
3
- Version: 0.37.0
3
+ Version: 0.37.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
@@ -5508,6 +5508,12 @@ Each column's `TYPE` comes from its annotation (`Annotated` unwrapped):
5508
5508
 
5509
5509
  Anything else is `any`.
5510
5510
 
5511
+ A field annotated with a name defined after the class (a forward reference: `score: "Score" = 0`, then `Score = int`)
5512
+ gets the kind of the type its name resolves to. Since v0.37.1, `table_ddl()` and `define_table()` complete such a model
5513
+ first, as its first instantiation does, so they write the same statements before and after an instance (`score` is
5514
+ `TYPE int DEFAULT 0`, which earlier versions wrote `TYPE any DEFAULT 0` until the model was instantiated or rebuilt). A
5515
+ name still undefined gives `any`.
5516
+
5511
5517
  - **Columns**: every field but `id` (and an edge's `in_` and `out`), under its column — its alias, if any
5512
5518
  ([section 20](#20-field-aliases-server_fields-and-mergerefreshfalse)) —, then the Pydantic `@computed_field`s; a
5513
5519
  `Field(exclude=True)` field is left out. A sub-model's fields follow its column (`address.city`, `subs.*.city`), its
@@ -6225,7 +6231,11 @@ the default —, `I64`, `I32` or `I16`). An `Index` with `hnsw=True` is a vector
6225
6231
  `SurrealConfigDict(indexes=[...])` next to the full-text indexes of
6226
6232
  [section 36](#36-full-text-search-search-searchscore-searchhighlight-analyzer-index). Its attributes hold what was
6227
6233
  declared (`None` for an option not given). When the class is defined, two vector indexes on one column are refused,
6228
- and so is a vector index whose dimension or storage type differs from its field's `VectorField`.
6234
+ and so is a vector index whose dimension or storage type differs from its field's `VectorField`. A field annotated
6235
+ with a name defined after the class (a forward reference) is checked once the name resolves, with the same error: at
6236
+ `model_rebuild()`, at the model's first instantiation, validation or JSON schema, and before `table_ddl()`,
6237
+ `define_table()`, `index_ddl()`, `define_indexes()`, `get_indexes()` or a queryset (`similar_to()` included) reads the
6238
+ model. Once refused, each of these raises it again.
6229
6239
 
6230
6240
  ```python
6231
6241
  from surreal_orm_lite import (
@@ -6337,10 +6347,11 @@ print(get_vector_info(Document.model_fields["embedding"]), is_vector_field(Passa
6337
6347
  `VectorField[d]` is already optional, so it needs no `| None`. Written `VectorField[d] | None` or
6338
6348
  `Optional[VectorField[d]]`, its `None` default sits inside a union member, where Pydantic ignores it with an
6339
6349
  `UnsupportedFieldAttributeWarning`: write `= None`, or the field is required. The ORM reads these spellings, and
6340
- `Annotated[list[float], Vector(d)] | None`, like the plain ones: the same column, the same checks of the vector index
6341
- when the class is defined, the same dimension for `similar_to()`, the same answer from `get_vector_info()`. A union
6342
- that holds a vector next to a type other than `None`, or two different `Vector` markers, has no single dimension: the
6343
- class statement refuses it, naming the field.
6350
+ `Annotated[list[float], Vector(d)] | None`, like the plain ones (a `Literal[None]` member counts as `None`): the same
6351
+ column, the same checks of the vector index when the class is defined, the same dimension for `similar_to()`, the same
6352
+ answer from `get_vector_info()`. A union that holds a vector next to a type other than `None`, or two different
6353
+ `Vector` markers, has no single dimension: the class statement refuses it, naming the field, and `get_vector_info()`
6354
+ and `is_vector_field()` raise `ValueError` for such a field or annotation.
6344
6355
 
6345
6356
  #### Find the nearest
6346
6357
 
@@ -5457,6 +5457,12 @@ Each column's `TYPE` comes from its annotation (`Annotated` unwrapped):
5457
5457
 
5458
5458
  Anything else is `any`.
5459
5459
 
5460
+ A field annotated with a name defined after the class (a forward reference: `score: "Score" = 0`, then `Score = int`)
5461
+ gets the kind of the type its name resolves to. Since v0.37.1, `table_ddl()` and `define_table()` complete such a model
5462
+ first, as its first instantiation does, so they write the same statements before and after an instance (`score` is
5463
+ `TYPE int DEFAULT 0`, which earlier versions wrote `TYPE any DEFAULT 0` until the model was instantiated or rebuilt). A
5464
+ name still undefined gives `any`.
5465
+
5460
5466
  - **Columns**: every field but `id` (and an edge's `in_` and `out`), under its column — its alias, if any
5461
5467
  ([section 20](#20-field-aliases-server_fields-and-mergerefreshfalse)) —, then the Pydantic `@computed_field`s; a
5462
5468
  `Field(exclude=True)` field is left out. A sub-model's fields follow its column (`address.city`, `subs.*.city`), its
@@ -6174,7 +6180,11 @@ the default —, `I64`, `I32` or `I16`). An `Index` with `hnsw=True` is a vector
6174
6180
  `SurrealConfigDict(indexes=[...])` next to the full-text indexes of
6175
6181
  [section 36](#36-full-text-search-search-searchscore-searchhighlight-analyzer-index). Its attributes hold what was
6176
6182
  declared (`None` for an option not given). When the class is defined, two vector indexes on one column are refused,
6177
- and so is a vector index whose dimension or storage type differs from its field's `VectorField`.
6183
+ and so is a vector index whose dimension or storage type differs from its field's `VectorField`. A field annotated
6184
+ with a name defined after the class (a forward reference) is checked once the name resolves, with the same error: at
6185
+ `model_rebuild()`, at the model's first instantiation, validation or JSON schema, and before `table_ddl()`,
6186
+ `define_table()`, `index_ddl()`, `define_indexes()`, `get_indexes()` or a queryset (`similar_to()` included) reads the
6187
+ model. Once refused, each of these raises it again.
6178
6188
 
6179
6189
  ```python
6180
6190
  from surreal_orm_lite import (
@@ -6286,10 +6296,11 @@ print(get_vector_info(Document.model_fields["embedding"]), is_vector_field(Passa
6286
6296
  `VectorField[d]` is already optional, so it needs no `| None`. Written `VectorField[d] | None` or
6287
6297
  `Optional[VectorField[d]]`, its `None` default sits inside a union member, where Pydantic ignores it with an
6288
6298
  `UnsupportedFieldAttributeWarning`: write `= None`, or the field is required. The ORM reads these spellings, and
6289
- `Annotated[list[float], Vector(d)] | None`, like the plain ones: the same column, the same checks of the vector index
6290
- when the class is defined, the same dimension for `similar_to()`, the same answer from `get_vector_info()`. A union
6291
- that holds a vector next to a type other than `None`, or two different `Vector` markers, has no single dimension: the
6292
- class statement refuses it, naming the field.
6299
+ `Annotated[list[float], Vector(d)] | None`, like the plain ones (a `Literal[None]` member counts as `None`): the same
6300
+ column, the same checks of the vector index when the class is defined, the same dimension for `similar_to()`, the same
6301
+ answer from `get_vector_info()`. A union that holds a vector next to a type other than `None`, or two different
6302
+ `Vector` markers, has no single dimension: the class statement refuses it, naming the field, and `get_vector_info()`
6303
+ and `is_vector_field()` raise `ValueError` for such a field or annotation.
6293
6304
 
6294
6305
  #### Find the nearest
6295
6306
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "surreal-orm-lite"
3
- version = "0.37.0"
3
+ version = "0.37.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.37.0"
1
+ __version__ = "0.37.1"
2
2
 
3
3
  from ._sdk import BoundExcluded, BoundIncluded
4
4
  from .aggregations import Aggregation, Avg, Count, Max, Min, Sum
@@ -107,6 +107,7 @@ from .utils import (
107
107
  format_record_id,
108
108
  merge_extra_vars,
109
109
  replace_content,
110
+ user_namespace,
110
111
  user_stacklevel,
111
112
  validate_alias_name,
112
113
  validate_edge_name,
@@ -878,6 +879,16 @@ class BaseSurrealModel(BaseModel):
878
879
  model from a node, so they need not import ``edge.py`` (which imports this module).
879
880
  """
880
881
 
882
+ __surreal_checks_pending__: typing.ClassVar[bool] = False
883
+ """``True`` on a model Pydantic could not complete at its ``class`` statement, until it does and the vector checks
884
+ accept it (issue #327).
885
+
886
+ Set by ``__pydantic_init_subclass__`` when a field is still a forward reference: its vector checks then wait for
887
+ ``__pydantic_on_complete__``, and the ORM completes the model before it reads its fields or its indexes
888
+ (``_complete_pending_checks()``). Read from the class's own ``__dict__`` only, never inherited: a subclass is
889
+ completed, and checked, on its own.
890
+ """
891
+
881
892
  _surreal_as_of: datetime | None = PrivateAttr(default=None)
882
893
  """The moment a time-travel read (``QuerySet.as_of()``) returned this instance at; ``None`` for a current record (v0.26.0).
883
894
 
@@ -980,8 +991,10 @@ class BaseSurrealModel(BaseModel):
980
991
  per column and one ``Analyzer`` definition per analyzer name, one vector index per column
981
992
  and, on a vector field of any spelling — a union with ``None`` included —, of its dimension
982
993
  and storage type (v0.36.0) — inherited values included, the messages naming the subclass.
983
- So are the ``table_type``, ``relation_in``,
984
- ``relation_out`` and ``enforced`` keys (v0.33.0), when any of them is not ``None``: a
994
+ These two (``_check_vectors_and_indexes()``) read the fields Pydantic could resolve: when a
995
+ field is still a forward reference, the model is incomplete and they run again once Pydantic
996
+ completes it (``__pydantic_on_complete__()``, issue #327). So are the ``table_type``,
997
+ ``relation_in``, ``relation_out`` and ``enforced`` keys (v0.33.0), when any of them is not ``None``: a
985
998
  ``TableType`` (``RELATION`` on an edge only), and the relation keys on an edge model only
986
999
  (``schema.check_relation_config()``). So are, on every model and after the relation keys,
987
1000
  the ``schema_mode``, ``changefeed``, ``permissions``, ``comment`` and
@@ -1013,12 +1026,10 @@ class BaseSurrealModel(BaseModel):
1013
1026
  user=issubclass(cls, AuthenticatedUserMixin),
1014
1027
  computed=tuple(cls.__surreal_computed__),
1015
1028
  )
1016
- # Every model, with or without indexes: a field whose Vector markers are ambiguous is refused here.
1017
- declared = declared_vectors(cls.__name__, cls.model_fields)
1018
- indexes = cls.model_config.get("indexes")
1019
- if indexes is not None:
1020
- vectors = {cls.to_db_field(name): info for name, info in declared.items()}
1021
- check_indexes_config(cls, indexes, view=cls._is_view(), column=cls.to_db_field, vectors=vectors)
1029
+ cls._check_vectors_and_indexes()
1030
+ if not cls.__pydantic_complete__:
1031
+ # A field still a forward reference has no Vector marker yet: checked again once the model is complete.
1032
+ cls.__surreal_checks_pending__ = True
1022
1033
  relation = {key: cls.model_config.get(key) for key in ("table_type", "relation_in", "relation_out", "enforced")}
1023
1034
  if any(value is not None for value in relation.values()):
1024
1035
  check_relation_config(cls, edge=cls.__surreal_edge__, **relation)
@@ -1045,6 +1056,79 @@ class BaseSurrealModel(BaseModel):
1045
1056
  message += " table_name wins."
1046
1057
  warnings.warn(message, DeprecationWarning, stacklevel=user_stacklevel(also_skip=(_PYDANTIC_DIR,)))
1047
1058
 
1059
+ @classmethod
1060
+ def _check_vectors_and_indexes(cls) -> None:
1061
+ """The vector checks of the ``class`` statement (v0.36.0; issues #318, #327), on the fields as Pydantic has
1062
+ resolved them.
1063
+
1064
+ On every model, with or without indexes, the ``Vector`` markers of the fields (``vector.declared_vectors()``):
1065
+ a field whose markers are ambiguous is refused, naming the model and the field. Then the ``indexes`` key
1066
+ (``search.check_indexes_config()``), each vector index checked against its vector field's dimension and
1067
+ storage type. Run by ``__pydantic_init_subclass__``, and again by ``__pydantic_on_complete__`` on a model that
1068
+ a forward reference left incomplete there.
1069
+ """
1070
+ declared = declared_vectors(cls.__name__, cls.model_fields)
1071
+ indexes = cls.model_config.get("indexes")
1072
+ if indexes is not None:
1073
+ vectors = {cls.to_db_field(name): info for name, info in declared.items()}
1074
+ check_indexes_config(cls, indexes, view=cls._is_view(), column=cls.to_db_field, vectors=vectors)
1075
+
1076
+ @classmethod
1077
+ def __pydantic_on_complete__(cls) -> None:
1078
+ """Run the vector checks of the ``class`` statement once Pydantic completes a model it could not complete
1079
+ there (issue #327).
1080
+
1081
+ A field annotated with a forward reference (``e: "Later" = None``) has no ``Vector`` marker until Pydantic
1082
+ resolves the name and completes the model: at ``model_rebuild()``, at the model's first instantiation,
1083
+ validation or JSON schema, or when the ORM first reads its fields or its indexes
1084
+ (``_complete_pending_checks()``); Pydantic calls this hook then. ``_check_vectors_and_indexes()`` runs again on
1085
+ every field, with the refusals of the field written directly, raised from the call that completed the model.
1086
+ A model complete at its ``class`` statement is checked there only: Pydantic calls this hook first, before
1087
+ ``__pydantic_init_subclass__``, which has not asked for it (``__surreal_checks_pending__``).
1088
+
1089
+ Pydantic marks the model complete before it calls this hook, so a refusal puts the model back as it was,
1090
+ incomplete: each of these calls completes it again and raises the same error. The refusal is never lost.
1091
+ """
1092
+ super().__pydantic_on_complete__()
1093
+ if not cls.__dict__.get("__surreal_checks_pending__", False):
1094
+ return
1095
+ try:
1096
+ cls._check_vectors_and_indexes()
1097
+ except BaseException:
1098
+ # Pydantic's own mocks for a model it could not complete: the next use rebuilds it, and so checks it again.
1099
+ from pydantic._internal._mock_val_ser import set_model_mocks
1100
+
1101
+ cls.__pydantic_complete__ = False
1102
+ set_model_mocks(cls)
1103
+ raise
1104
+ cls.__surreal_checks_pending__ = False
1105
+
1106
+ @classmethod
1107
+ def _complete_pending_checks(cls) -> None:
1108
+ """Complete a model whose vector checks still wait for Pydantic (issue #327), before the ORM reads its fields
1109
+ or its indexes: ``_table_ddl()`` and ``_table_columns()`` (behind ``table_ddl()``, ``define_table()``),
1110
+ ``get_indexes()`` (behind ``index_ddl()``, ``define_indexes()``, ``similar_to()``) and ``QuerySet()`` (every
1111
+ queryset) call it first.
1112
+
1113
+ Pydantic completes a model that a forward reference left incomplete at its ``class`` statement at
1114
+ ``model_rebuild()`` or at its first instantiation, validation or JSON schema, never when the ORM writes its DDL
1115
+ or builds a query: ``define_table()`` would write the field's column ``any`` and ``define_indexes()`` a vector
1116
+ index its field contradicts, unchecked. So the model is rebuilt here as Pydantic's first instantiation rebuilds
1117
+ it — with the local names of the first caller outside the ORM (``utils.user_namespace()``), then the names of
1118
+ the model's module: a caller's local name wins, and the field keeps what it resolved to — and
1119
+ ``__pydantic_on_complete__()`` runs the checks: a refusal raises from here, at every call, the model staying
1120
+ incomplete. A name still undefined leaves the model incomplete, read as before, without an error; the next call
1121
+ tries again. A complete model costs one attribute read.
1122
+
1123
+ Every model a forward reference left incomplete is completed, with or without a vector field: its columns get
1124
+ the resolved kinds (``define_table()`` writes ``int`` for ``score: "Score" = 0`` once ``Score = int`` is
1125
+ defined, not ``any``), and its links are resolved for the cross-connection check (``routing.linked_models()``),
1126
+ whether or not the model was instantiated first.
1127
+ """
1128
+ if cls.__pydantic_complete__ or not cls.__dict__.get("__surreal_checks_pending__", False):
1129
+ return
1130
+ cls.model_rebuild(raise_errors=False, _types_namespace=user_namespace())
1131
+
1048
1132
  @classmethod
1049
1133
  def get_computed_fields(cls) -> dict[str, str]:
1050
1134
  """Return ``{field_name: SurrealQL expression}`` for this model's computed fields.
@@ -1324,7 +1408,12 @@ class BaseSurrealModel(BaseModel):
1324
1408
  A tuple; ``()`` when the model declares none. A subclass inherits its parent's indexes unless it sets
1325
1409
  ``indexes`` itself (``indexes=[]`` drops them); a subclass with another table defines the same indexes on its
1326
1410
  own table.
1411
+
1412
+ A model a forward reference left incomplete at its ``class`` statement is completed first, and checked as the
1413
+ ``class`` statement checks a vector field (issue #327): its refusal raises here, as from :meth:`index_ddl`,
1414
+ :meth:`define_indexes` and ``similar_to()``.
1327
1415
  """
1416
+ cls._complete_pending_checks()
1328
1417
  indexes = cls.model_config.get("indexes")
1329
1418
  # Checked at the class statement: a list or tuple of Index, or None.
1330
1419
  return tuple(indexes) if isinstance(indexes, (list, tuple)) else ()
@@ -1970,8 +2059,11 @@ class BaseSurrealModel(BaseModel):
1970
2059
 
1971
2060
  Raises:
1972
2061
  ValueError: a ``FLEXIBLE`` request on a kind without an object; a computed field's expression that is not
1973
- SurrealQL the ORM can embed; ``server_fields`` names a field the model does not declare.
2062
+ SurrealQL the ORM can embed; ``server_fields`` names a field the model does not declare. Before them, a
2063
+ model a forward reference left incomplete at its ``class`` statement is completed, and its vector
2064
+ checks may refuse it (issue #327, ``_complete_pending_checks()``).
1974
2065
  """
2066
+ cls._complete_pending_checks()
1975
2067
  computed = cls.get_computed_fields()
1976
2068
  endpoints = {cls.to_py_field(column) for column in cls._endpoint_columns()}
1977
2069
  flexible = cls.model_config.get("flexible_fields")
@@ -1997,6 +2089,7 @@ class BaseSurrealModel(BaseModel):
1997
2089
  that ``Field(exclude=True)`` keeps out of ``model_dump()`` (SG1, #296, #299).
1998
2090
  ValueError: see :meth:`_table_columns`.
1999
2091
  """
2092
+ cls._complete_pending_checks()
2000
2093
  if cls._is_view():
2001
2094
  return [cls.view_ddl(overwrite=overwrite)]
2002
2095
  table = cls.get_table_name()
@@ -2061,7 +2154,8 @@ class BaseSurrealModel(BaseModel):
2061
2154
  and ``signin()`` refuse the model too; remove ``exclude=True`` and pass ``exclude=`` to
2062
2155
  ``model_dump()`` where you serialise the model.
2063
2156
  ValueError: a ``FLEXIBLE`` request on a kind without an object; a computed field's expression that is not
2064
- SurrealQL the ORM can embed.
2157
+ SurrealQL the ORM can embed; the refusals of a vector field declared through a forward reference, the
2158
+ ``class`` statement's, checked once the name resolves (issue #327, :meth:`get_indexes`).
2065
2159
 
2066
2160
  Example:
2067
2161
  >>> print("\\n".join(Person.table_ddl()))
@@ -2239,7 +2333,8 @@ class BaseSurrealModel(BaseModel):
2239
2333
  with a field SIGNUP writes that ``Field(exclude=True)`` keeps out of ``model_dump()``, whatever its
2240
2334
  schema mode (see :meth:`table_ddl`) — before any request.
2241
2335
  ValueError: a ``FLEXIBLE`` request on a kind without an object; a computed field's expression that is not
2242
- SurrealQL the ORM can embed — before any request.
2336
+ SurrealQL the ORM can embed; the refusals of a vector field declared through a forward reference
2337
+ (:meth:`table_ddl`) — before any request.
2243
2338
  SurrealDbError: *tx* belongs to another connection — before any request; the table is a materialized view
2244
2339
  or a relation table, or a table or field definition cannot be read back or carried — before any DDL;
2245
2340
  the server refused a statement (``Can't apply table definition: …``, ``Can't apply field definition:
@@ -148,6 +148,9 @@ class QuerySet:
148
148
  """
149
149
 
150
150
  def __init__(self, model: type[BaseSurrealModel]) -> None:
151
+ # Issue #327: a model a forward reference left incomplete at its class statement is completed, and its vector
152
+ # checks run, before a query reads its fields — their refusal raises here.
153
+ model._complete_pending_checks()
151
154
  self.model = model
152
155
  self._filters: list[tuple[str, str, Any]] = []
153
156
  self._q_filters: list[Q] = []
@@ -830,7 +830,8 @@ def check_indexes_config(
830
830
  vectors: Mapping[str, tuple[int, str]],
831
831
  ) -> None:
832
832
  """The ``indexes`` key of a model's ``SurrealConfigDict``, checked when the class is defined (v0.35.0; the vector
833
- indexes v0.36.0).
833
+ indexes v0.36.0), and again when Pydantic completes a model that a forward reference left incomplete at its
834
+ ``class`` statement, *vectors* then holding the fields it resolved (issue #327).
834
835
 
835
836
  ``None`` (no indexes) is not passed here. The first fault raises, in this order: *value* is not a ``list`` or a
836
837
  ``tuple``; an item is not an ``Index``; two indexes share a name (the second definition would replace the first);
@@ -91,6 +91,28 @@ def user_stacklevel(*, also_skip: tuple[str, ...] = ()) -> int:
91
91
  return 2
92
92
 
93
93
 
94
+ def user_namespace() -> dict[str, Any]:
95
+ """The local names of the first frame outside the ORM (its subpackages included); ``{}`` when there is none.
96
+
97
+ Pydantic completes a model that a forward reference left incomplete at its ``class`` statement, on its first
98
+ instantiation, with the local names of the caller's frame, then the names of the module the model is defined in (a
99
+ caller's local name wins). ``BaseSurrealModel._complete_pending_checks()`` completes such a model the same way
100
+ before the ORM reads its fields or its indexes (issue #327): the caller is the first frame outside the ORM, whatever
101
+ the depth of the call.
102
+ """
103
+ frame = inspect.currentframe()
104
+ try:
105
+ while frame is not None:
106
+ directory = os.path.dirname(os.path.abspath(frame.f_code.co_filename))
107
+ if directory != _PACKAGE_DIR and not directory.startswith(_PACKAGE_DIR + os.sep):
108
+ return dict(frame.f_locals)
109
+ frame = frame.f_back
110
+ return {}
111
+ finally:
112
+ # A frame refers to its locals: dropping it here keeps no reference cycle alive.
113
+ del frame
114
+
115
+
94
116
  def split_statements(query: str) -> list[str]:
95
117
  """Split SurrealQL on the statement separator, ignoring ``;`` inside strings and comments.
96
118
 
@@ -9,10 +9,12 @@ Pydantic reads the ``Vector`` marker exactly as ``VectorField[1536]``'s. Both sp
9
9
  validation, the same column type (``option<array<float, 1536>>``), the same schema. ``get_vector_info()`` and
10
10
  ``is_vector_field()`` — the full ORM's helpers, under their names — read the marker of either spelling from a model
11
11
  field or an annotation, and of their unions with ``None`` (``VectorField[1536] | None``,
12
- ``Annotated[list[float], Vector(1536)] | None``), as ``define_table()`` reads them; never from inside a container
13
- (``list[VectorField[3]]``). A field or an annotation holding two different markers, or a marker next to a type other
14
- than ``None``, has no single dimension: the helpers refuse it, and a model's ``class`` statement refuses such a field
15
- (``declared_vectors()``).
12
+ ``Annotated[list[float], Vector(1536)] | None``, ``VectorField[1536] | Literal[None]``), as ``define_table()`` reads
13
+ them; never from inside a container (``list[VectorField[3]]``). A field or an annotation holding two different markers,
14
+ or a marker next to a type other than ``None``, has no single dimension: the helpers refuse it, and a model's ``class``
15
+ statement refuses such a field (``declared_vectors()``) — or, for a field declared through a forward reference, the
16
+ completion of the model once the name resolves: ``model_rebuild()``, its first instantiation, validation or JSON schema,
17
+ or the ORM's first DDL or queryset of the model (``BaseSurrealModel._complete_pending_checks()``).
16
18
 
17
19
  A value is ``None`` or a ``list``/``tuple`` of exactly ``d`` real numbers — ``int``, ``float``, any ``numbers.Real``,
18
20
  a ``decimal.Decimal`` (SurrealDB's decimals read back as ``Decimal``) —, never a ``bool`` nor a ``str``, each finite
@@ -55,7 +57,7 @@ from dataclasses import dataclass
55
57
  from decimal import Decimal
56
58
  from numbers import Real
57
59
  from types import NoneType, UnionType
58
- from typing import Annotated, Any, NoReturn, Self, TypedDict, Union, get_args, get_origin
60
+ from typing import Annotated, Any, Literal, NoReturn, Self, TypedDict, Union, get_args, get_origin
59
61
 
60
62
  from pydantic import Field, GetCoreSchemaHandler, GetJsonSchemaHandler
61
63
  from pydantic.fields import FieldInfo
@@ -303,9 +305,11 @@ def _held(annotation: Any, metadata: Sequence[Any] = ()) -> tuple[tuple[Vector,
303
305
 
304
306
  The ``Annotated`` layers are unwrapped and their metadata added to *metadata*: when it holds a ``Vector``, those
305
307
  markers decide, whatever the type under them (a ``Vector`` validates the value itself). Otherwise ``None`` gives
306
- neither; a union gives the markers and other types of its members, each read the same way; any other type is
307
- another type — a container holding vectors (``list[VectorField[3]]``) included, whose arguments are never read.
308
- This is the reading ``model_ddl`` gives the column its kind by, so the column and the checks agree.
308
+ neither, and so does a ``Literal`` whose values are all ``None`` (``Literal[None]`` admits ``None`` only, issue
309
+ #327); a union gives the markers and other types of its members, each read the same way; any other type is
310
+ another type — a ``Literal`` holding another value (``Literal[None, "x"]``) and a container holding vectors
311
+ (``list[VectorField[3]]``) included, whose arguments are never read. This is the reading ``model_ddl`` gives the
312
+ column its kind by, so the column and the checks agree.
309
313
  """
310
314
  while get_origin(annotation) is Annotated:
311
315
  metadata = (*metadata, *annotation.__metadata__)
@@ -313,9 +317,9 @@ def _held(annotation: Any, metadata: Sequence[Any] = ()) -> tuple[tuple[Vector,
313
317
  markers = tuple(dict.fromkeys(item for item in metadata if isinstance(item, Vector)))
314
318
  if markers:
315
319
  return markers, False
316
- if annotation is None or annotation is NoneType:
317
- return (), False
318
320
  origin = get_origin(annotation)
321
+ if annotation is None or annotation is NoneType or (origin is Literal and all(arg is None for arg in get_args(annotation))):
322
+ return (), False
319
323
  if origin is not Union and origin is not UnionType:
320
324
  return (), True
321
325
  members = [_held(member) for member in get_args(annotation)]
@@ -360,30 +364,35 @@ def get_vector_info(annotation_or_field: Any) -> tuple[int, str] | None:
360
364
  Takes a model field (``Model.model_fields["embedding"]``, a Pydantic ``FieldInfo``) or an annotation
361
365
  (``VectorField[3]``, ``Annotated[list[float] | None, Vector(3)]``): both spellings give ``(3, "F32")``, and so do
362
366
  their unions with ``None`` (``VectorField[3] | None``, ``Optional[VectorField[3]]``,
363
- ``Annotated[list[float], Vector(3)] | None``), read as ``define_table()`` reads them. Anything without a ``Vector``
364
- marker — ``list[float]``, another field, vectors held in a container such as ``list[VectorField[3]]`` — gives
365
- ``None``.
367
+ ``Annotated[list[float], Vector(3)] | None``, ``VectorField[3] | Literal[None]``), read as ``define_table()`` reads
368
+ them. Anything without a ``Vector`` marker — ``list[float]``, another field, vectors held in a container such as
369
+ ``list[VectorField[3]]`` — gives ``None``.
366
370
 
367
371
  :raises ValueError: the field or annotation holds two different ``Vector`` markers, or a marker next to a type
368
- other than ``None`` in a union (``VectorField[3] | str``): its dimension and storage type are not one. A
369
- model's ``class`` statement refuses such a field already, naming it.
372
+ other than ``None`` in a union (``VectorField[3] | str``, ``VectorField[3] | Literal[None, "x"]``): its
373
+ dimension and storage type are not one. A model's ``class`` statement refuses such a field already, naming it
374
+ (for a field declared through a forward reference, once Pydantic completes the model).
370
375
  """
371
376
  marker = _marker(annotation_or_field)
372
377
  return None if marker is None else (marker.dimension, marker.vector_type)
373
378
 
374
379
 
375
380
  def is_vector_field(annotation_or_field: Any) -> bool:
376
- """Whether a model field or an annotation is a vector field, any spelling — a union with ``None`` included — (the
377
- full ORM's helper). Refuses what ``get_vector_info()`` refuses, with its ``ValueError``."""
381
+ """Whether a model field or an annotation is a vector field, any spelling — a union with ``None`` or
382
+ ``Literal[None]`` included — (the full ORM's helper). Refuses what ``get_vector_info()`` refuses, with its
383
+ ``ValueError``: a field or an annotation holding two different ``Vector`` markers, or a marker next to a type other
384
+ than ``None``."""
378
385
  return _marker(annotation_or_field) is not None
379
386
 
380
387
 
381
388
  def declared_vectors(owner: str, fields: Mapping[str, FieldInfo]) -> dict[str, tuple[int, str]]:
382
389
  """The ``(dimension, storage type)`` of each vector field among a model's *fields*, by field name, as
383
- ``get_vector_info()`` reads them: what the model's ``class`` statement checks (issue #318).
390
+ ``get_vector_info()`` reads them: what the model's ``class`` statement checks (issue #318), and checks again once
391
+ Pydantic completes a model a forward reference left incomplete there (issue #327).
384
392
 
385
393
  A field whose ``Vector`` markers are ambiguous raises ``ValueError`` naming the model *owner* and the field, so the
386
- ``class`` statement refuses it whether or not the model declares indexes.
394
+ ``class`` statement refuses it whether or not the model declares indexes. A field still a forward reference has no
395
+ marker yet: it is not a vector field here.
387
396
  """
388
397
  declared: dict[str, tuple[int, str]] = {}
389
398
  for name, field in fields.items():