surreal-orm-lite 0.28.1__tar.gz → 0.29.0__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 (43) hide show
  1. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/CHANGELOG.md +149 -0
  2. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/PKG-INFO +279 -7
  3. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/README.md +278 -6
  4. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/pyproject.toml +1 -1
  5. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/__init__.py +3 -1
  6. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/cache.py +15 -3
  7. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/changefeed.py +61 -11
  8. surreal_orm_lite-0.29.0/src/surreal_orm_lite/connection_config.py +27 -0
  9. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/connection_manager.py +860 -47
  10. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/edge.py +15 -5
  11. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/embedded.py +30 -0
  12. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/live.py +168 -52
  13. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/model_auth.py +41 -26
  14. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/model_base.py +117 -28
  15. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/query_set.py +82 -28
  16. surreal_orm_lite-0.29.0/src/surreal_orm_lite/routing.py +254 -0
  17. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/subquery.py +17 -1
  18. surreal_orm_lite-0.29.0/src/surreal_orm_lite/testing/database.py +89 -0
  19. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/transaction.py +9 -0
  20. surreal_orm_lite-0.28.1/src/surreal_orm_lite/testing/database.py +0 -59
  21. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/.gitignore +0 -0
  22. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/LICENSE +0 -0
  23. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/Makefile +0 -0
  24. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/_sdk.py +0 -0
  25. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/aggregations.py +0 -0
  26. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/auth.py +0 -0
  27. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/concurrency.py +0 -0
  28. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/constants.py +0 -0
  29. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/decoding.py +0 -0
  30. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/encoding.py +0 -0
  31. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/enum.py +0 -0
  32. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/exceptions.py +0 -0
  33. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/functions.py +0 -0
  34. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/geo.py +0 -0
  35. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/py.typed +0 -0
  36. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/q.py +0 -0
  37. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/signals.py +0 -0
  38. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/surql_literal.py +0 -0
  39. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/testing/__init__.py +0 -0
  40. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/testing/fixtures.py +0 -0
  41. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/time_travel.py +0 -0
  42. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/types.py +0 -0
  43. {surreal_orm_lite-0.28.1 → surreal_orm_lite-0.29.0}/src/surreal_orm_lite/utils.py +0 -0
@@ -5,6 +5,155 @@ 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.29.0] - 2026-10-18
9
+
10
+ Multiple databases: one process works with several databases at once. Named connections stand
11
+ beside the default one, each model reads and writes through its own, and `using()` redirects a
12
+ block of code. The seventh and last minor of Tier 2.
13
+
14
+ ### Added
15
+
16
+ - **Named connections**:
17
+ `SurrealDBConnectionManager.add_connection(name, *, url, user=None, password=None, namespace, database)`
18
+ registers another database beside the default connection (`set_connection()`): another database
19
+ on the same server, another server, or the embedded engine. It opens nothing: each connection opens its own clients on first use, as the default
20
+ one does. `remove_connection(name)`, `get_config(name)` (a frozen `ConnectionConfig`, exported
21
+ from `surreal_orm_lite`) and `list_connections()` complete the registry, with the full
22
+ SurrealDB-ORM's names.
23
+
24
+ ```python
25
+ from surreal_orm_lite import BaseSurrealModel, SurrealConfigDict, SurrealDBConnectionManager
26
+
27
+ SurrealDBConnectionManager.set_connection(url="mem://", namespace="shop", database="main") # "default"
28
+ SurrealDBConnectionManager.add_connection("analytics", url="mem://", namespace="shop", database="analytics")
29
+
30
+ class Customer(BaseSurrealModel): # no connection key: "default"
31
+ id: str | None = None
32
+ name: str
33
+
34
+ class PageView(BaseSurrealModel):
35
+ model_config = SurrealConfigDict(connection="analytics")
36
+ id: str | None = None
37
+ path: str
38
+
39
+ await Customer(id="ada", name="Ada").save() # shop/main
40
+ await PageView(id="v1", path="/pricing").save() # shop/analytics
41
+
42
+ async with SurrealDBConnectionManager.using("analytics"):
43
+ elsewhere = await Customer.objects().count() # 0: Customer runs on "analytics" here
44
+ ```
45
+
46
+ - **`add_connection()` checks its arguments** before registering anything: a non-empty name, URL,
47
+ namespace and database, and a user and password for a server URL (optional on the embedded
48
+ engine); a URL the installed SDK refuses raises `SurrealDbConnectionError`. Registering a name
49
+ again with the same settings changes nothing, and `add_connection("default", …)` configures the
50
+ default connection with these checks. `ConnectionConfig` keeps the password out of its `repr`.
51
+ `remove_connection()` of a name that is not registered is a no-op, and
52
+ `remove_connection("default")` is `unset_connection()`.
53
+ - **Model routing**: `SurrealConfigDict(connection="analytics")` sends every database call of the
54
+ model to that connection: writes, reads and every QuerySet, relations, `raw_query()`,
55
+ `call_function()`, model auth, live queries, change feeds and `as_of()`. A model without the key
56
+ uses the default connection. `Model.get_connection_name()` returns the connection its calls use
57
+ right now. The key is checked when the class is defined (`TypeError` for a value that is not a
58
+ string, `ValueError` for an empty one), and whether its name is registered at the model's first
59
+ database call (`ValueError`), so models can be declared before `add_connection()` runs. Edge
60
+ models and `AuthenticatedUserMixin` models take it too; subclasses inherit it.
61
+ - **`using(name)`**: inside `async with SurrealDBConnectionManager.using("analytics"):` every model,
62
+ whatever its key, and every manager method that talks to a database use that connection. It is
63
+ async-safe (a `ContextVar`: a task created inside the block keeps its connection), blocks nest,
64
+ and the outer connection is back after the block, on an exception too; a name that is not
65
+ registered raises `ValueError` before the block runs. `get_active_connection_name()` returns the
66
+ block's name, `None` outside any block.
67
+ - **`name=` on `get_client()`, `close_connection()` and `transaction()`**: they act on a named
68
+ connection, and without it on the current one. `inspect.signature()` does not show the
69
+ parameter, so `Depends(SurrealDBConnectionManager.get_client)` in FastAPI adds no `?name=` query
70
+ parameter and behaves as in v0.28: a request never chooses the connection.
71
+ - **Each connection keeps its own state**: its clients (one per event loop; one for the whole
72
+ process on the embedded engine), its session (`signin()` inside `using(name)` signs in that
73
+ connection only, and a stored token is replayed on its own connection only), its live streams
74
+ and change feeds (bound to the connection when they start), its transactions, its
75
+ stored-function signatures and its cached reads.
76
+ - **`embedded_database(connection=name)`** isolates a named connection in tests; inside
77
+ `using(name)` it isolates the block's connection, and naming another connection there raises
78
+ `ValueError`.
79
+ - **Errors for operations across connections**, raised before any request: `SurrealDbError` for a
80
+ model given another connection's transaction (its writes, `objects(tx=)`, `refresh(tx=)`,
81
+ `call_function(tx=)`), for a subquery whose model runs on another connection than the statement
82
+ around it, for `relate()`, `remove_relation()`, `remove_all_relations()` and `get_related()`
83
+ across connections, and for following a link (`fetch()`, a dotted path) through a field typed
84
+ with a model of another connection; `SurrealDbConnectionError` (not retryable) when a second
85
+ connection opens an on-disk embedded store (`surrealkv://`, `file://`) that another connection
86
+ of the process holds open. Inside a `using()` block every model runs on one connection, so none
87
+ of them apply there.
88
+ - README section 30, "Multiple databases (`add_connection()`, `using()`)" (routing a model,
89
+ `using()`, transactions and other operations across connections, what each connection keeps for
90
+ itself, which connection a manager method uses, a note for users of the full SurrealDB-ORM), a
91
+ features row, rows in the 2.x/3.x and embedded-engine behaviour tables, the comparison and
92
+ roadmap rows, and the example notebook `examples/v0.29.0_multi_database.ipynb`.
93
+
94
+ ### Changed
95
+
96
+ - `close_connection()` ends the live streams of its own connection only (before: every live
97
+ stream of the event loop), and `unset_connection()` closes the default connection's clients only
98
+ (`close_all_connections()` still closes every client, of every connection). With the default
99
+ connection alone, both behave as before.
100
+ - A `transaction()` records the connection it was opened on: a model of another connection is
101
+ refused (above), and a transaction whose connection is registered again with other settings, or
102
+ removed, while it is open is cancelled when its block ends, with nothing committed
103
+ (`SurrealDbConnectionError`: open it again).
104
+ - The manager's state now lives in one class per connection, the default one included: code that
105
+ read or patched the private attributes of `SurrealDBConnectionManager` must follow it. A manager
106
+ method replaced by hand, public or private, is inherited by every connection: put it back from
107
+ `vars(SurrealDBConnectionManager)[name]`, as pytest's `monkeypatch.setattr()` and
108
+ `unittest.mock.patch.object()` already do. Putting back `SurrealDBConnectionManager.<name>`, saved
109
+ before the patch, worked with one connection; it is a method bound to `SurrealDBConnectionManager`
110
+ that every connection then inherits and that acts on the current connection, so once a named
111
+ connection exists, a model with a `connection` key reads and writes the current connection's
112
+ database, with no error (README section 30, "Which connection a manager method uses").
113
+ - CI adds a "Mixed server lines" job, required by `CI Success`: the mixed-lines tests put a
114
+ SurrealDB 3.x and a 2.x connection side by side in one process; they find the servers through
115
+ `SURREALDB_PORT_3X` and `SURREALDB_PORT_2X` and skip without them.
116
+
117
+ ### Notes
118
+
119
+ - **Each connection decides on its own server line**: a SurrealDB 2.x and a 3.x server work side
120
+ by side in one process, with interactive transactions on a 3.x WebSocket connection beside
121
+ buffered ones on a 2.x connection; time travel, change feeds and live queries follow each
122
+ connection's server.
123
+ - **Registering a name again with other settings, or removing it**, retires its clients and ends
124
+ what the ORM holds on the old settings: a client still opening is closed unused (a retryable
125
+ `SurrealDbConnectionError`: retry the call), live streams end, a change feed ends at its next
126
+ read (`SurrealDbConnectionError`: start a new one), and an open `transaction()` is cancelled
127
+ (above). A client the application obtained with `get_client()` before the change is its own: on
128
+ WebSocket its next request fails; an HTTP client keeps the namespace and database it was opened
129
+ on; an embedded client follows a new namespace or database, but after a new URL or a removal it
130
+ is the previous engine, so stop using it. `set_connection()` and the `set_*()` setters keep
131
+ their earlier behaviour: clients opened on the previous settings keep serving.
132
+ - **Query cache**: an ORM write removes the cached reads of its table on every connection, more
133
+ than needed but never a stale result. Entries cached with `QueryCache.make_key()` and `set()`
134
+ are not scoped to a connection: when the same statement runs on two connections, put the
135
+ connection's name among the variables.
136
+ - **What the ORM cannot see across connections**, so keep it on one connection yourself: a link
137
+ followed through a field whose annotation names no model (`RecordID`, `str`, `dict`), graph
138
+ arrows (`select("->likes->Post")`, `traverse()`), an edge saved with endpoint ids of another
139
+ database, and raw SurrealQL (`raw_query()`, `QuerySet.query()`, `call_function()`,
140
+ `Transaction.add()`).
141
+ - **SurrealDB runs a statement, and a transaction, in one database**: two `transaction()` blocks on
142
+ two connections are two independent transactions, and a `USE` inside `raw_query()` applies to
143
+ that request only (the next request reads the connection's own database).
144
+ - **Differences from the full SurrealDB-ORM**: `close_connection()` without a name closes the
145
+ current connection only (full ORM: every connection); `list_connections()` lists `'default'`
146
+ first; registering a name again with other settings closes its clients; the getters, the
147
+ setters and `reconnect()` follow `using()`; `add_connection()` and the `connection` key are
148
+ checked; `ConnectionConfig` has no `protocol` (the official SDK speaks CBOR only) and accepts
149
+ `None` for `user` and `password`; `name` is hidden from introspection; `transaction(name)`,
150
+ `embedded_database(connection=)` and the errors for operations across connections are lite
151
+ additions.
152
+ - Not available yet: a per-queryset override (`QuerySet.using()`), a client-side connection pool,
153
+ one transaction across connections.
154
+ - **Server pins unchanged**: tested against SurrealDB 3.3.4 and 2.7.0, each alone and both in one
155
+ process, and on the embedded engine, plus 3.1.5 for backward compatibility (identical).
156
+
8
157
  ## [0.28.1] - 2026-10-17
9
158
 
10
159
  Query building checks what it is given: `select()` accepts field names and paths, `limit()` and
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: surreal-orm-lite
3
- Version: 0.28.1
3
+ Version: 0.29.0
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
@@ -263,6 +263,7 @@ embedded engine refuse one above `4294967295` (`2**32 - 1`), SurrealDB 3.x reads
263
263
  | Time travel (`as_of()`, versioned storage) | ✅ |
264
264
  | Subqueries (`Subquery`, a QuerySet as a filter value) | ✅ |
265
265
  | Query cache (`cache()`, TTL, invalidated by ORM writes) | ✅ |
266
+ | Multiple databases (named connections, `using()`) | ✅ |
266
267
 
267
268
  ### Supported Filter Lookups
268
269
 
@@ -3739,6 +3740,267 @@ cached_total = await total_price() # 96 (the cache answers)
3739
3740
  - **LRU eviction** instead of FIFO.
3740
3741
  - **`invalidate()` takes a table name too**, and **`stats()` adds `hits` and `misses`**.
3741
3742
 
3743
+ ### 30. Multiple databases (`add_connection()`, `using()`)
3744
+
3745
+ Since v0.29.0 one process can work with several databases at once. Beside the default connection
3746
+ (`set_connection()`), `add_connection()` registers **named connections** — another database on the
3747
+ same server, another server, or the embedded engine — and each model reads and writes through its
3748
+ own. Each connection keeps its own clients, session, live streams, transactions and cached reads,
3749
+ and decides on its own server line: a SurrealDB 2.x server and a 3.x server work side by side. The
3750
+ examples of this section run on the embedded engine (`mem://`), with nothing to start.
3751
+
3752
+ ```python
3753
+ from surreal_orm_lite import BaseSurrealModel, SurrealConfigDict, SurrealDBConnectionManager
3754
+
3755
+ # Any URL works: ws://…/rpc or http://… (with user= and password=), mem://, surrealkv://<path>
3756
+ SurrealDBConnectionManager.set_connection(url="mem://", namespace="shop", database="main") # "default"
3757
+ SurrealDBConnectionManager.add_connection("analytics", url="mem://", namespace="shop", database="analytics")
3758
+
3759
+ class Customer(BaseSurrealModel): # no connection key: "default"
3760
+ id: str | None = None
3761
+ name: str
3762
+
3763
+ class PageView(BaseSurrealModel):
3764
+ model_config = SurrealConfigDict(connection="analytics")
3765
+ id: str | None = None
3766
+ path: str
3767
+
3768
+ await Customer(id="ada", name="Ada").save() # shop/main
3769
+ await PageView(id="v1", path="/pricing").save() # shop/analytics
3770
+ names = SurrealDBConnectionManager.list_connections() # ['default', 'analytics']
3771
+ ```
3772
+
3773
+ - `add_connection(name, *, url, user=None, password=None, namespace, database)` opens nothing:
3774
+ each connection opens its own clients on first use, as the default one does. Its arguments are
3775
+ checked before anything is registered — a non-empty name, URL, namespace and database, and a
3776
+ user and password for a server URL (optional on the embedded engine) — and a URL the installed
3777
+ SDK refuses raises `SurrealDbConnectionError`. `add_connection("default", …)` configures the
3778
+ default connection, as `set_connection()` does, with these checks.
3779
+ - Registering a name again with the same settings changes nothing; with other settings, see
3780
+ [What each connection keeps for itself](#what-each-connection-keeps-for-itself).
3781
+ - `get_config(name)` returns the settings as a frozen `ConnectionConfig` (`url`, `user`,
3782
+ `password`, `namespace`, `database`; the password is kept out of its `repr`), and `None` for a
3783
+ name that is not registered or for the default connection while it is not configured.
3784
+ `list_connections()` returns the registered names, `'default'` first while it is configured.
3785
+ - `remove_connection(name)` unregisters a name and closes what it holds; a name that is not
3786
+ registered is a no-op, and `remove_connection("default")` is `unset_connection()`.
3787
+ - `get_client(name)`, `close_connection(name)` and `transaction(name)` act on a named connection,
3788
+ and without a name on the current one
3789
+ ([Which connection a manager method uses](#which-connection-a-manager-method-uses)). For a name
3790
+ that is not registered, `get_client(name)` and `transaction(name)` raise `ValueError`, while
3791
+ `close_connection(name)` closes nothing.
3792
+
3793
+ #### Routing a model
3794
+
3795
+ A model's `connection` key — `model_config = SurrealConfigDict(connection="analytics")`, the full
3796
+ SurrealDB-ORM's key — sends every database call of the model to that connection: writes, reads
3797
+ and every QuerySet, relations, `raw_query()`, `call_function()`, model auth, live queries, change
3798
+ feeds and `as_of()`. A model without the key, or with `None`, uses the default connection.
3799
+
3800
+ ```python
3801
+ where = PageView.get_connection_name() # analytics
3802
+ ```
3803
+
3804
+ - `get_connection_name()` is the connection the model's calls use right now: the name of the
3805
+ `using()` block around the call, else the `connection` key, else `"default"`. It is resolved at
3806
+ every database call, so a QuerySet built outside a `using()` block and run inside it uses the
3807
+ block's connection; a live stream or a change feed resolves it once, when it starts.
3808
+ - The key is checked when the class is defined (`TypeError` for a value that is not a string,
3809
+ `ValueError` for an empty one). Whether the name is registered is checked at the model's first
3810
+ database call (`ValueError`), so models can be declared before `add_connection()` runs.
3811
+ - Subclasses inherit the key and may set their own; edge models (`BaseSurrealEdge`) and
3812
+ `AuthenticatedUserMixin` models take it too. `table_name` and `connection` are independent: two
3813
+ connections can each hold a table of the same name.
3814
+
3815
+ #### Redirecting a block: `using()`
3816
+
3817
+ `using(name)`, the full SurrealDB-ORM's, runs a block of code against a named connection: inside
3818
+ it every model, whatever its `connection` key, and every manager method that talks to a database
3819
+ use that connection, with the exceptions of
3820
+ [Which connection a manager method uses](#which-connection-a-manager-method-uses).
3821
+
3822
+ ```python
3823
+ async with SurrealDBConnectionManager.using("analytics"):
3824
+ elsewhere = await Customer.objects().count() # 0
3825
+ here = await Customer.objects().count() # 1
3826
+ ```
3827
+
3828
+ - The name is checked when the block is entered: one that is not registered raises `ValueError`
3829
+ before the block runs. `get_active_connection_name()` returns the block's name, `None` outside
3830
+ any block.
3831
+ - Blocks nest, and the outer connection is back after the inner block, on an exception too.
3832
+ - It is async-safe: the name lives in a `contextvars.ContextVar`, so concurrent tasks each see
3833
+ their own block. A task created inside the block keeps its connection for its whole life, even
3834
+ after the block exits; `asyncio.to_thread()` carries it, a new `threading.Thread` does not.
3835
+ - Live streams and change feeds started inside the block keep its connection after it.
3836
+ - `signin()` inside `using(name)` signs in that connection only.
3837
+ - With the test helpers, `embedded_database()` inside `using(name)` isolates that connection, and
3838
+ `embedded_database(connection=name)` does so outside any block; inside a `using()` block, naming
3839
+ another connection raises `ValueError` (the block's models would reach their real database).
3840
+
3841
+ #### Transactions and other operations across connections
3842
+
3843
+ SurrealDB runs a statement, and a transaction, in one database. So the ORM refuses, before sending
3844
+ the statement, every operation that would mix two connections in one statement or one
3845
+ transaction:
3846
+
3847
+ ```python
3848
+ from surreal_orm_lite import SurrealDbError
3849
+
3850
+ async with SurrealDBConnectionManager.transaction("analytics") as tx:
3851
+ await PageView(id="v2", path="/").save(tx=tx)
3852
+
3853
+ try:
3854
+ async with SurrealDBConnectionManager.transaction() as tx: # the default connection
3855
+ await PageView(id="v3", path="/x").save(tx=tx)
3856
+ except SurrealDbError as exc:
3857
+ refused = type(exc).__name__ # SurrealDbError
3858
+ ```
3859
+
3860
+ - **A transaction is one connection's.** `transaction(name)`, or `transaction()` inside
3861
+ `using(name)`, opens it on that connection, with that connection's strategy (interactive on a
3862
+ 3.x server over WebSocket, buffered otherwise). A model of another connection given that `tx=`
3863
+ raises `SurrealDbError`, before any request and any signal: its writes, `objects(tx=)`,
3864
+ `refresh(tx=)`, `call_function(tx=)`, and the manager's `call_function(tx=)`. Transactions of
3865
+ two connections are independent: nothing commits across connections.
3866
+ - **Subqueries**: a `Subquery`, or a QuerySet used as a filter value, whose model runs on another
3867
+ connection than the statement around it raises `SurrealDbError`: SurrealDB would read it in the
3868
+ outer statement's database. Read it through its own connection first and filter on its values.
3869
+ - **Relations**: `relate()`, `remove_relation()`, `remove_all_relations()` and `get_related()`
3870
+ raise `SurrealDbError` when the source, a target model instance, the edge model and
3871
+ `model_class` are not all on one connection. A `RecordID` or `"table:id"` target is not checked.
3872
+ - **Links**: following a record link — `fetch()`, or a dotted path in `filter()`, `Q`, `select()`,
3873
+ `order_by()`, `values()` or an aggregation — through a field typed with a model of another
3874
+ connection raises `SurrealDbError`: SurrealDB resolves a link in the statement's database.
3875
+ - **An on-disk embedded store** (`surrealkv://`, `file://`) is open under one name at a time in a
3876
+ process: a second name raises `SurrealDbConnectionError` until the first one closes it
3877
+ (`close_connection()`, `remove_connection()`). Two `mem://` names are two separate databases.
3878
+ - Inside a `using()` block every model runs on the block's connection, so none of these refusals
3879
+ apply there.
3880
+
3881
+ What the ORM cannot see, and you keep on one connection yourself:
3882
+
3883
+ - a link followed through a field whose annotation names no model (`RecordID`, `str`, `dict`);
3884
+ - graph arrows: `select("->likes->Post")`, `traverse()`;
3885
+ - an edge saved with endpoint ids of another database;
3886
+ - raw SurrealQL: `raw_query()`, `QuerySet.query()`, `call_function()`, `Transaction.add()`.
3887
+
3888
+ #### What each connection keeps for itself
3889
+
3890
+ - **Its clients**: one per event loop, as the default connection's
3891
+ ([Connections and event loops](#connections-and-event-loops)); on the embedded engine, one for
3892
+ the whole process. `close_connection(name)` closes one connection's client on the running loop,
3893
+ `close_all_connections()` every connection's.
3894
+ - **Its session**: `signin()`, `signup()`, `authenticate()`, `invalidate()`, `info()` and
3895
+ `clear_session()` act on the current connection, so sign in inside `using(name)`. A stored token
3896
+ is replayed on its own connection only, and an identity lost on one connection does not block
3897
+ another. An `AuthenticatedUserMixin` model signs in on its own connection.
3898
+ - **Its live streams and change feeds**, bound to the connection when they start:
3899
+ `close_connection(name)` ends that connection's live streams only.
3900
+ - **Its transactions**, with the strategy of its server: one process holds interactive
3901
+ transactions on a 3.x connection beside buffered ones on a 2.x connection.
3902
+ - **Its stored-function signatures** (`call_function()`).
3903
+ - **The ORM's cached reads** (`cache()`): a cached result is never served to another connection.
3904
+ An ORM write removes the cached reads of its table on every connection: more than needed, never
3905
+ a stale result.
3906
+ - Registering a name again with other settings, or removing it with `remove_connection()`, ends what the ORM holds
3907
+ on the old settings: a client still opening is closed unused (the embedded engine is closed only when its URL
3908
+ changed or the name was removed; otherwise it is kept and its session is selected again at the next call) and its
3909
+ caller gets a retryable `SurrealDbConnectionError` (retry the call), live streams end, a change feed ends at its
3910
+ next read (`SurrealDbConnectionError`: its cursor belongs to the old database, start a new one), and an open
3911
+ `transaction()` is cancelled when its block ends, with nothing committed (`SurrealDbConnectionError`: open it
3912
+ again). After `remove_connection()`, a call already under way on the name opens no new client on the old settings:
3913
+ one still waiting for the embedded engine while another thread held it raises `ValueError`
3914
+ (`Connection not been set ('<name>').`). A client you obtained yourself with `get_client()` before the change is
3915
+ yours: on WebSocket its socket is closed and its next request fails; an HTTP client keeps the namespace and database
3916
+ it was opened on, so call `get_client()` again; an embedded client is the connection's one in-process session: it
3917
+ follows a new namespace or database at the ORM's next call, but after a new URL or `remove_connection()` it is the
3918
+ previous engine (with SDK 2.x still running), so stop using it, as after `close_connection()`.
3919
+ `set_connection()` and the `set_*()` setters do none of this: clients opened on the previous
3920
+ settings keep serving, as in earlier versions.
3921
+
3922
+ Entries you cache yourself with `QueryCache.make_key()` and `set()` are not scoped to a connection: the key is
3923
+ built from the table, the statement and the variables only. When the same statement runs on two connections, put
3924
+ the connection's name among the variables (keep the table name as it is, so the ORM's writes still invalidate the
3925
+ entry).
3926
+
3927
+ ```python
3928
+ from surreal_orm_lite import QueryCache
3929
+
3930
+ statement = "SELECT count() AS n FROM page_view GROUP ALL;"
3931
+ key_main = QueryCache.make_key(statement, {"connection": "default"}, "page_view")
3932
+ key_analytics = QueryCache.make_key(statement, {"connection": "analytics"}, "page_view")
3933
+ distinct = key_main != key_analytics # True
3934
+ ```
3935
+
3936
+ #### Which connection a manager method uses
3937
+
3938
+ A manager method acts on the **current connection** — the `name` it is given, else the innermost
3939
+ `using()` block's, else the default one — except where this table says otherwise:
3940
+
3941
+ | Method | Acts on |
3942
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
3943
+ | `add_connection()`, `remove_connection()`, `get_config()`, `list_connections()`, `using()`, `get_active_connection_name()` | the registry, by the name given |
3944
+ | `set_connection()`, `unset_connection()` | always the default connection |
3945
+ | `close_all_connections()` | every connection, on every event loop |
3946
+ | `get_client(name)`, `close_connection(name)`, `transaction(name)` | _name_, else the current connection |
3947
+ | `subscribe_live(uuid)`, `kill(uuid)` | the connection whose live stream started _uuid_ on this event loop, else the current connection |
3948
+ | every other method: the session methods (`signin()`, `info()` …), the getters and setters (`get_url()`, `set_database()` …), `reconnect()`, `validate_connection()`, `ephemeral_client()`, `call_function()`, `is_connected()`, `is_embedded()`, `async with SurrealDBConnectionManager():` | the current connection |
3949
+
3950
+ A coroutine method (`get_client()`, `signin()`, `close_connection()` …) resolves the connection
3951
+ when it is awaited, and a context manager (`transaction()`, `ephemeral_client()`) when it is opened
3952
+ by `async with` (strictly, when it is called), so both act on the connection of the `using()`
3953
+ block they are written in.
3954
+
3955
+ A manager method you replace by hand, in a test for instance, is inherited by every connection, so
3956
+ it intercepts the calls of every connection. Save what the class body holds,
3957
+ `vars(SurrealDBConnectionManager)[name]`, and put that back: pytest's `monkeypatch.setattr()` and
3958
+ `unittest.mock.patch.object()` already do. Saving `SurrealDBConnectionManager.<name>` instead, which
3959
+ worked while there was one connection, saves a method bound to `SurrealDBConnectionManager`: put
3960
+ back, it is what every connection inherits, and it acts on the current connection, so a model with
3961
+ a `connection` key reads and writes the current connection's database, with no error.
3962
+
3963
+ ```python
3964
+ async def offline():
3965
+ raise ConnectionError("no database in this test")
3966
+
3967
+ saved = vars(SurrealDBConnectionManager)["get_client"]
3968
+ SurrealDBConnectionManager.get_client = offline # every connection calls offline()
3969
+ try:
3970
+ await PageView.objects().count() # raises ConnectionError
3971
+ except ConnectionError:
3972
+ pass
3973
+ finally:
3974
+ SurrealDBConnectionManager.get_client = saved # the classmethod again
3975
+ views = await PageView.objects().count() # 2
3976
+ ```
3977
+
3978
+ #### Coming from the full SurrealDB-ORM
3979
+
3980
+ - Same names: `add_connection()`, `remove_connection()`, `get_config()`, `list_connections()`,
3981
+ `get_active_connection_name()`, `using()`, `ConnectionConfig`, `SurrealConfigDict(connection=)`,
3982
+ `get_connection_name()`, `get_client(name)`, `close_connection(name)`.
3983
+ - `ConnectionConfig` has the same fields in the same order, built by position or by keyword, without `protocol`
3984
+ (the official SDK speaks CBOR only); `user` and `password` may be `None` (the embedded engine needs neither).
3985
+ - `close_connection()` without a name: closing an embedded `mem://` client discards its database, so
3986
+ `close_connection()` without a name stays on the current connection; `close_all_connections()` closes every one
3987
+ (full ORM: `close_connection()` closes every connection).
3988
+ - `list_connections()` lists `'default'` first while it is configured (full ORM: registration order).
3989
+ - Registering a name again with other settings closes its open clients and ends what the ORM holds on the old
3990
+ settings (full ORM: drops the clients without closing them). `set_connection()` keeps its open clients, as in
3991
+ earlier lite versions.
3992
+ - The getters, the setters and `reconnect()` follow `using()` (full ORM: the default connection).
3993
+ - `transaction(name)`, `embedded_database(connection=)` and the errors for operations across connections are lite
3994
+ additions.
3995
+ - `add_connection()` checks its arguments before registering anything (a non-empty name, URL, namespace and
3996
+ database; a user and password for a server URL, optional on the embedded engine), and a model's `connection` key
3997
+ must be a non-empty string, checked when the class is defined (full ORM: no checks). `ConnectionConfig` keeps the
3998
+ password out of its `repr`.
3999
+ - `get_client(name)`, `close_connection(name)` and `transaction(name)` accept `name` in code, but
4000
+ `inspect.signature()` does not show it, so FastAPI's `Depends(SurrealDBConnectionManager.get_client)` adds no
4001
+ `?name=` query parameter: a request never chooses the connection (full ORM: `name` is visible and becomes a query
4002
+ parameter).
4003
+
3742
4004
  ---
3743
4005
 
3744
4006
  ## Configuration Options
@@ -3795,6 +4057,9 @@ async with SurrealDBConnectionManager():
3795
4057
  # Connection automatically closed
3796
4058
  ```
3797
4059
 
4060
+ `async with SurrealDBConnectionManager():` uses the current connection (the default, or the `using()` block's)
4061
+ and closes that connection's client on exit.
4062
+
3798
4063
  ### Connections and event loops
3799
4064
 
3800
4065
  The manager caches **one client per event loop**. A SurrealDB WebSocket client is bound to
@@ -3815,11 +4080,16 @@ An entry whose loop has been closed is dropped the next time a client is request
3815
4080
  client is not closed — that would have to be awaited on a loop that is already gone — and its
3816
4081
  socket is released when the loop is finalised.
3817
4082
 
3818
- - `close_connection()` closes **the running loop's** client only.
3819
- - `close_all_connections()` tears down every cached client (used by `unset_connection()`).
4083
+ - `close_connection()` closes **the running loop's** client of the current connection only (the default, or the
4084
+ one a `using()` block names).
4085
+ - `close_all_connections()` tears down every cached client of every connection; `unset_connection()` does that for
4086
+ the default connection only, `remove_connection(name)` for a named one.
3820
4087
  - `is_connected()` answers for the loop asking; called outside a loop, it reports whether any
3821
4088
  loop still holds a client.
3822
4089
 
4090
+ Each named connection keeps its own per-loop clients in the same way
4091
+ ([section 30](#30-multiple-databases-add_connection-using)).
4092
+
3823
4093
  Long-lived single-loop applications are unaffected: one loop, one connection, as before.
3824
4094
 
3825
4095
  An embedded URL is the exception: the engine runs in this process and is not bound to a loop, so
@@ -3853,7 +4123,7 @@ features introduced in SurrealDB 3.x. On 2.x the ORM degrades gracefully. Capabi
3853
4123
  listed behave the same on both lines. The 2.x column was measured on 2.6.5 and holds unchanged
3854
4124
  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
3855
4125
  otherwise. The full suite and every divergence below were re-verified on both new versions.
3856
- 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.
4126
+ 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.
3857
4127
  The SDK's in-process engine has a table of its own: [ORM behaviour: the embedded engine](#orm-behaviour-the-embedded-engine).
3858
4128
 
3859
4129
  | ORM capability | SurrealDB 2.6.x / 2.7.x | SurrealDB 3.2.x / 3.3.x | Since |
@@ -3962,6 +4232,7 @@ The SDK's in-process engine has a table of its own: [ORM behaviour: the embedded
3962
4232
  | `select("meta.*")` on a nested object that is not a record link | its values, as a list; through a link (`select("author.*")`), the linked record | the object; through a link, the linked record | pre-existing (documented in v0.28.1) |
3963
4233
  | `filter(f="$x")`: a string filter value starting with `$` | same on both lines: compared with the string `"$x"`, bound like any value, in a live query too; `Var("x")` reads the variable `$x`, `Var("auth")` SurrealDB's `$auth` | the same; on an edge's `in`/`out` (record ids) such a string raises `ValueError`, on both lines; `$access`, `$session`, `$token` read like `$auth` | v0.28.1 |
3964
4234
  | `limit(n)` or `offset(n)` above `4294967295` (`2**32 - 1`) | the server refuses the read: `Found <n> but the LIMIT clause must evaluate to a positive integer` (`START` likewise) | read; above `2**63 - 1` the ORM raises `ValueError` when `limit()` or `offset()` is called, on both lines | pre-existing (documented in v0.28.1) |
4235
+ | Several connections in one process (`add_connection()`, `using()`) | each connection follows its own server: a 2.x connection's transactions are buffered, whatever the others are | each 3.x WebSocket connection gets interactive transactions, beside 2.x connections in the same process | v0.29.0 |
3965
4236
  | 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 |
3966
4237
 
3967
4238
  > **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.
@@ -3977,7 +4248,7 @@ Capabilities not listed behave as on a 2.x server.
3977
4248
  | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | ------- |
3978
4249
  | Connection and credentials (`set_connection()`) | URL, namespace and database; `user` and `password` optional, kept and never sent | every setting required; the configured user signs in on each new connection | v0.25.0 |
3979
4250
  | URLs the SDK refuses (`rocksdb://`, a typo) | `SurrealDbConnectionError` quoting the SDK (naming #233 for `rocksdb://`), before anything is opened | n/a | v0.25.0 |
3980
- | Clients | one for the whole process, shared by every event loop and thread | one per event loop | v0.25.0 |
4251
+ | Clients | one per connection for the whole process, shared by every event loop and thread | one per connection and event loop | v0.25.0 |
3981
4252
  | Namespace/database change | the next call resets the session to the owner and selects the new pair on the same engine (no data lost); the stored session ends | taken by the next connection | v0.25.0 |
3982
4253
  | Closing (`close_connection()`, `unset_connection()`, `reconnect()`) | `mem://` discarded, `surrealkv://` reopened with its data; with SDK 2.x a client kept after the close is still a running engine; `close_connection()` and `reconnect()` leave the server clients open (`is_connected()` stays true on a loop with one) | the connection closes | v0.25.0 |
3983
4254
  | SurrealQL line | 2.x (SurrealDB 2.3.10 core); `client.version()` reports the SDK (`surrealdb-2.0.0`) | the server's | v0.25.0 |
@@ -3992,6 +4263,7 @@ Capabilities not listed behave as on a 2.x server.
3992
4263
  | Reading a table that does not exist | `[]`, raw queries included (as on 2.x) | the ORM reads `[]`; a raw query on 3.x raises `NotFoundError` | v0.25.0 |
3993
4264
  | Parse errors | bare `RuntimeError` (the DDL helpers raise `SurrealDbError`) | the SDK's error classes | v0.25.0 |
3994
4265
  | Time travel (`as_of()`) | `surrealkv+versioned://` only (`?versioned=true` is ignored by SDK 2.0.0); any other URL → `SurrealDbError` before any request; `fetch()` refused (2.x core) | versioned storage required (see the 2.x/3.x table) | v0.26.0 |
4266
+ | Several connections (`add_connection()`) | `mem://`: each name is a database of its own; an on-disk store (`surrealkv://`, `file://`) is open under one name at a time — a second name raises `SurrealDbConnectionError` | each name opens its own clients; two databases on one server are isolated | v0.29.0 |
3995
4267
  | 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 |
3996
4268
 
3997
4269
  ---
@@ -4035,7 +4307,7 @@ Contributions are welcome! Please:
4035
4307
  | v0.26.0 | Time travel (versioned storage) | ✅ Released |
4036
4308
  | v0.27.0 | Subqueries | ✅ Released |
4037
4309
  | v0.28.0 | Query cache | ✅ Released |
4038
- | v0.29.0 | Tier 2 — Multi-database | 📋 Planned |
4310
+ | v0.29.0 | Tier 2 — Multi-database | ✅ Released |
4039
4311
  | v0.30.0 – v0.39.0 | Tier 3 — Advanced (search, DDL, migrations, CLI) | 📋 Planned |
4040
4312
  | v0.40.0 | Beta Phase (API freeze, hardening) | 📋 Planned |
4041
4313
  | v2.0.0 | Production / GA (aligned with SDK 2.0) | 📋 Planned |
@@ -4088,7 +4360,7 @@ SDK) and **server support**. Everything below is on the lite roadmap via the off
4088
4360
  | Time travel (`VERSION`) | ✅ v0.26.0 (`as_of()`) | ❌ |
4089
4361
  | Subqueries | ✅ v0.27.0 (`Subquery`, a QuerySet in `filter()`) | ✅ |
4090
4362
  | Query Cache | ✅ v0.28.0 (`cache()`, `QueryCache`) | ✅ |
4091
- | Multi-database | v0.29.0 | ✅ |
4363
+ | Multi-database | ✅ v0.29.0 (`add_connection()`, `using()`) | ✅ |
4092
4364
  | Schema Introspection | v0.30.0 | ✅ |
4093
4365
  | DEFINE EVENT | v0.31.0 | ✅ |
4094
4366
  | Materialized views | v0.32.0 | ✅ |