Skip to main content

vantage_vista/
source.rs

1use std::pin::Pin;
2#[cfg(feature = "rhai")]
3use vantage_rhai::rhai;
4
5use async_trait::async_trait;
6use ciborium::Value as CborValue;
7use futures_core::Stream;
8use indexmap::IndexMap;
9use vantage_core::{Result, VantageError, error};
10use vantage_types::Record;
11
12use crate::{
13    aggregate::AggregateSpec,
14    capabilities::VistaCapabilities,
15    column::Column,
16    reference::{ContainedSpec, Reference},
17    sort::SortDirection,
18    vista::Vista,
19};
20
21/// A single change observed on the underlying set by a live subscription.
22///
23/// This is the *push* counterpart to `list_vista_values`: a driver whose
24/// backend can stream changes (SurrealDB LIVE, Postgres `LISTEN/NOTIFY`,
25/// a Mongo change stream) emits one of these per affected row. The `value`
26/// carried on `Inserted`/`Updated` is the record in the **same projected,
27/// id-keyed shape** the driver returns from `list_vista_values`, so consumers
28/// can drop it straight into a cache without re-reading.
29#[derive(Debug, Clone)]
30pub enum VistaChange {
31    /// A row entered the set.
32    Inserted {
33        id: String,
34        value: Record<CborValue>,
35    },
36    /// An existing row's contents changed.
37    Updated {
38        id: String,
39        value: Record<CborValue>,
40    },
41    /// A row left the set.
42    Deleted { id: String },
43    /// "Something changed, but I can't say what" — a coarse invalidation. The
44    /// consumer should reconcile by re-reading the whole set. This is what a
45    /// payload-less push (Postgres `LISTEN/NOTIFY`) can offer; drivers that
46    /// carry the row (SurrealDB LIVE) emit the fine-grained variants instead.
47    Invalidated,
48}
49
50impl VistaChange {
51    /// The id of the affected row, or `None` for a coarse [`Invalidated`](Self::Invalidated).
52    pub fn id(&self) -> Option<&str> {
53        match self {
54            VistaChange::Inserted { id, .. }
55            | VistaChange::Updated { id, .. }
56            | VistaChange::Deleted { id } => Some(id),
57            VistaChange::Invalidated => None,
58        }
59    }
60}
61
62/// A stream of [`VistaChange`]s from a live subscription. `'static` and `Send`
63/// so it can be handed to a background task.
64pub type VistaChangeStream = Pin<Box<dyn Stream<Item = Result<VistaChange>> + Send>>;
65
66/// Per-driver executor for a `Vista`.
67///
68/// Implementations live in driver crates (vantage-sqlite, vantage-mongodb,
69/// vantage-aws, etc.). Each method receives `&Vista` so the driver can read
70/// the current condition state, columns, and other metadata.
71///
72/// `Id = String` and `Value = ciborium::Value` at this boundary, so every
73/// driver's native id (Mongo `ObjectId`, Surreal `Thing`, …) stringifies
74/// here. Methods are named with the `_vista_` infix to mirror
75/// `TableSource`'s `_table_` convention; `Vista`'s `ValueSet` impls
76/// delegate by stripping the infix.
77///
78/// `id: &String` (rather than `&str`) is intentional: the upstream
79/// `vantage_dataset::ValueSet` trait family fixes `Id = String` and uses
80/// `&Self::Id` in its signatures, so impls receive `&String` and forward
81/// it through unchanged.
82#[async_trait]
83#[allow(clippy::ptr_arg)]
84pub trait TableShell: Send + Sync + 'static {
85    // ---- Schema --------------------------------------------------------------
86    //
87    // The shell owns the schema. `Vista` is a thin wrapper that forwards its
88    // metadata accessors here. No defaults — every impl must answer (an empty
89    // schema is a deliberate choice the impl declares explicitly).
90
91    fn columns(&self) -> &IndexMap<String, Column>;
92
93    fn references(&self) -> &IndexMap<String, Reference>;
94
95    fn id_column(&self) -> Option<&str>;
96
97    // ---- ReadableValueSet delegates ----------------------------------------
98
99    async fn list_vista_values(&self, vista: &Vista)
100    -> Result<IndexMap<String, Record<CborValue>>>;
101
102    async fn get_vista_value(
103        &self,
104        vista: &Vista,
105        id: &String,
106    ) -> Result<Option<Record<CborValue>>>;
107
108    /// Fetch one record by id, with the caller's existing (cheap) record
109    /// available to drivers that can use it (e.g. a cmd detail script reading
110    /// list-pass columns). The default ignores `row` and delegates to
111    /// [`get_vista_value`](Self::get_vista_value); only drivers that benefit
112    /// override it.
113    async fn get_vista_value_with_row(
114        &self,
115        vista: &Vista,
116        id: &String,
117        _row: &Record<CborValue>,
118    ) -> Result<Option<Record<CborValue>>> {
119        self.get_vista_value(vista, id).await
120    }
121
122    async fn get_vista_some_value(
123        &self,
124        vista: &Vista,
125    ) -> Result<Option<(String, Record<CborValue>)>>;
126
127    /// Default implementation wraps `list_vista_values`. Drivers with native
128    /// streaming (cursor-based queries, paginated REST APIs) override.
129    #[allow(clippy::type_complexity)]
130    fn stream_vista_values<'a>(
131        &'a self,
132        vista: &'a Vista,
133    ) -> Pin<Box<dyn Stream<Item = Result<(String, Record<CborValue>)>> + Send + 'a>>
134    where
135        Self: Sync,
136    {
137        Box::pin(async_stream::stream! {
138            match self.list_vista_values(vista).await {
139                Ok(map) => {
140                    for item in map {
141                        yield Ok(item);
142                    }
143                }
144                Err(e) => yield Err(e),
145            }
146        })
147    }
148
149    // ---- WritableValueSet delegates ----------------------------------------
150    //
151    // Default impls return a typed VantageError via `default_error` — drivers
152    // override only what they actually support. The matching `VistaCapabilities`
153    // flag must be set to `true` for any method the driver implements; if the
154    // flag is `true` but the trait method falls through to the default,
155    // `default_error` produces an `Unimplemented`-kind error (placeholder
156    // detected). If the flag is `false`, it produces `Unsupported`. Both are
157    // emitted as tracing events at construction.
158
159    async fn insert_vista_value(
160        &self,
161        _vista: &Vista,
162        _id: &String,
163        _record: &Record<CborValue>,
164    ) -> Result<Record<CborValue>> {
165        Err(self.default_error("insert_vista_value", "can_insert"))
166    }
167
168    async fn replace_vista_value(
169        &self,
170        _vista: &Vista,
171        _id: &String,
172        _record: &Record<CborValue>,
173    ) -> Result<Record<CborValue>> {
174        Err(self.default_error("replace_vista_value", "can_update"))
175    }
176
177    async fn patch_vista_value(
178        &self,
179        _vista: &Vista,
180        _id: &String,
181        _partial: &Record<CborValue>,
182    ) -> Result<Record<CborValue>> {
183        Err(self.default_error("patch_vista_value", "can_update"))
184    }
185
186    async fn delete_vista_value(&self, _vista: &Vista, _id: &String) -> Result<()> {
187        Err(self.default_error("delete_vista_value", "can_delete"))
188    }
189
190    async fn delete_vista_all_values(&self, _vista: &Vista) -> Result<()> {
191        Err(self.default_error("delete_vista_all_values", "can_delete"))
192    }
193
194    // ---- InsertableValueSet delegate ---------------------------------------
195
196    async fn insert_vista_return_id_value(
197        &self,
198        _vista: &Vista,
199        _record: &Record<CborValue>,
200    ) -> Result<String> {
201        Err(self.default_error("insert_vista_return_id_value", "can_insert"))
202    }
203
204    // ---- Bulk import -------------------------------------------------------
205
206    /// Store `records` (id → record) in one driver-native operation —
207    /// SQL COPY, Surreal batch insert — and return how many were
208    /// **newly inserted**. An id the table already held counts zero,
209    /// whether the driver's batch skips it or upserts it: the number
210    /// travels to a user as "n records created", and the per-record
211    /// fallback in `Dio::import_values` counts the same way. A driver
212    /// that cannot tell new from existing must not advertise
213    /// [`can_import`](VistaCapabilities::can_import).
214    ///
215    /// All-or-nothing is the other half of the contract: a driver that
216    /// cannot make the batch atomic must not advertise it either; the
217    /// caller then falls back to per-record inserts where partial
218    /// progress is honest and reportable.
219    async fn import_vista_values(
220        &self,
221        _vista: &Vista,
222        _records: &IndexMap<String, Record<CborValue>>,
223    ) -> Result<usize> {
224        Err(self.default_error("import_vista_values", "can_import"))
225    }
226
227    // ---- Aggregates --------------------------------------------------------
228
229    /// Default impl falls back to `list_vista_values` — drivers with native
230    /// count (`SELECT COUNT(*)`, etc.) override.
231    async fn get_vista_count(&self, vista: &Vista) -> Result<i64> {
232        Ok(self.list_vista_values(vista).await?.len() as i64)
233    }
234
235    /// Derive a **new vista** that reduces this one — the driver's equivalent
236    /// of selecting from a subquery.
237    ///
238    /// An aggregation is not a value, it is a different set: `count(*)` yields
239    /// one row, `GROUP BY` yields one per group, and either can then be
240    /// conditioned, ordered or counted like any other set. Returning a
241    /// [`Vista`] is what lets every consumer keep the single shape it already
242    /// handles instead of growing a scalar special case.
243    ///
244    /// `Ok(None)` means *this driver cannot answer this request* — not that
245    /// the result is empty. The caller then reduces locally, which is a
246    /// different question (the rows it holds, not every row that matches) with
247    /// a different answer, so "can't" must never collapse into a number.
248    ///
249    /// **Narrow before aggregating.** Conditions belong to the source, applied
250    /// with `add_eq_condition` before this call — the order SQL uses, where the
251    /// filter is the inner query and the aggregate selects from its result.
252    /// Narrowing reports its own failure, so a driver is never handed a filter
253    /// it would silently ignore.
254    ///
255    /// **The returned vista's capabilities describe the DERIVED set, not the
256    /// source.** In particular it must not advertise condition support unless
257    /// the driver really implements it: adding a condition to an aggregate is
258    /// `HAVING`, a different operation over different values, and inheriting
259    /// the source's flag would promise a filter that silently does nothing.
260    /// An aggregator holding its entire output in memory is the exception —
261    /// it can filter what it produced, and may say so.
262    ///
263    /// This is construction, not a query — nothing is fetched until someone
264    /// lists the returned vista.
265    fn aggregate_vista(&self, _vista: &Vista, _spec: &AggregateSpec) -> Result<Option<Vista>> {
266        Ok(None)
267    }
268
269    // ---- Conditions --------------------------------------------------------
270
271    /// Translate `field == value` into the driver's native condition type and
272    /// apply it to the wrapped table. The default impl returns `Unimplemented`
273    /// — every driver is expected to override.
274    ///
275    /// `value` is the universal CBOR carrier; the driver picks the appropriate
276    /// translation (e.g. `cbor_to_bson` for Mongo, `cbor → AnyCsvType` for CSV).
277    fn add_eq_condition(&mut self, _field: &str, _value: &CborValue) -> Result<()> {
278        Err(error!(
279            format!(
280                "add_eq_condition not implemented for '{}'",
281                std::any::type_name::<Self>()
282            ),
283            method = "add_eq_condition",
284            source_type = std::any::type_name::<Self>()
285        )
286        .mark_unimplemented()
287        .traced())
288    }
289
290    /// Translate `field <op> value` into the driver's native condition and
291    /// apply it. The default routes `Eq` to [`add_eq_condition`](Self::add_eq_condition)
292    /// (so every driver gets equality for free) and returns `Unimplemented`
293    /// for every richer operator. Drivers whose query language expresses the
294    /// operators (SQL, SurrealDB) override this and advertise
295    /// [`can_filter_operators`](crate::VistaCapabilities::can_filter_operators);
296    /// consumers that see `false` skip the call and filter locally instead.
297    fn add_op_condition(
298        &mut self,
299        field: &str,
300        op: crate::FilterOp,
301        value: &CborValue,
302    ) -> Result<()> {
303        match op {
304            crate::FilterOp::Eq => self.add_eq_condition(field, value),
305            _ => Err(error!(
306                format!(
307                    "add_op_condition operator {:?} not implemented for '{}'",
308                    op,
309                    std::any::type_name::<Self>()
310                ),
311                method = "add_op_condition",
312                operator = format!("{:?}", op),
313                source_type = std::any::type_name::<Self>()
314            )
315            .mark_unimplemented()
316            .traced()),
317        }
318    }
319
320    /// Push a driver-native condition into the wrapped table. The
321    /// caller boxes the condition as `dyn Any` and the driver
322    /// downcasts to its own `T::Condition`. Used by YAML-driven
323    /// relation traversal, where the factory constructs a
324    /// `DeferredFn`-bearing condition outside the value-set surface
325    /// (which only accepts scalar eq) and pushes it through this
326    /// channel. Default is `Unimplemented`.
327    fn add_raw_condition(
328        &mut self,
329        _condition: Box<dyn std::any::Any + Send + Sync>,
330    ) -> Result<()> {
331        Err(error!(
332            format!(
333                "add_raw_condition not implemented for '{}'",
334                std::any::type_name::<Self>()
335            ),
336            method = "add_raw_condition",
337            source_type = std::any::type_name::<Self>()
338        )
339        .mark_unimplemented()
340        .traced())
341    }
342
343    // ---- Pagination --------------------------------------------------------
344
345    /// Declare how many records constitute one page. Used by both
346    /// [`fetch_page`](Self::fetch_page) and [`fetch_next`](Self::fetch_next).
347    /// Default returns `default_error("set_page_size", "can_set_page_size")`.
348    fn set_page_size(&mut self, _size: usize) -> Result<()> {
349        Err(self.default_error("set_page_size", "can_set_page_size"))
350    }
351
352    /// Fetch a specific page (1-based) using offset-style pagination. The
353    /// per-page count comes from the most recent
354    /// [`set_page_size`](Self::set_page_size).
355    ///
356    /// Drivers without random-access pagination (DynamoDB, most token-paginated
357    /// REST APIs) leave the default in place, which produces `Unsupported`.
358    /// Callers should branch on `vista.capabilities().can_fetch_page` first.
359    async fn fetch_page(
360        &self,
361        _vista: &Vista,
362        _page: usize,
363    ) -> Result<Vec<(String, Record<CborValue>)>> {
364        Err(self.default_error("fetch_page", "can_fetch_page"))
365    }
366
367    /// Cursor-style chain fetch. Pass `None` on the first call; pass the
368    /// previous call's returned token on subsequent calls. Returned token is
369    /// `None` when the result set is exhausted.
370    ///
371    /// The token is **driver-private** — its shape is whatever the backend
372    /// finds convenient (DynamoDB `LastEvaluatedKey` as a CBOR map, REST
373    /// `nextToken` as `CborValue::Text`, offset-based as `CborValue::Integer`).
374    /// Consumers treat it as opaque and round-trip it back unchanged.
375    ///
376    /// Default returns `default_error("fetch_next", "can_fetch_next")`.
377    async fn fetch_next(
378        &self,
379        _vista: &Vista,
380        _token: Option<CborValue>,
381    ) -> Result<(Vec<(String, Record<CborValue>)>, Option<CborValue>)> {
382        Err(self.default_error("fetch_next", "can_fetch_next"))
383    }
384
385    /// Fetch the half-open row window `[offset, offset + limit)` in the
386    /// source's natural order. Offset-style like [`fetch_page`](Self::fetch_page)
387    /// but addressed by absolute row index rather than page number, so it
388    /// maps directly onto a diorama `on_load_chunk` `Range<usize>` — which
389    /// is *not* guaranteed page-aligned. This is the primitive a paged,
390    /// lazily-loaded grid drives on scroll.
391    ///
392    /// Drivers leave the default in place (producing `Unsupported`) until
393    /// they implement it; callers branch on
394    /// `vista.capabilities().can_fetch_window` first. Default returns
395    /// `default_error("fetch_window", "can_fetch_window")`.
396    async fn fetch_window(
397        &self,
398        _vista: &Vista,
399        _offset: usize,
400        _limit: usize,
401    ) -> Result<Vec<(String, Record<CborValue>)>> {
402        Err(self.default_error("fetch_window", "can_fetch_window"))
403    }
404
405    /// [`fetch_window`](Self::fetch_window), plus the grand total of matching
406    /// rows when this fetch already learned it.
407    ///
408    /// Paged sources typically report the total in every response envelope,
409    /// alongside the window's rows. A caller needing both — a lazily-loaded
410    /// grid sizing its scrollbar — would otherwise pay a second round trip for
411    /// a number the first reply already carried.
412    ///
413    /// Drivers that can answer override this. The default delegates and
414    /// reports `None`, so no existing driver changes and no caller is told a
415    /// total exists when it doesn't. `None` means "this fetch didn't say",
416    /// never "zero".
417    async fn fetch_window_counted(
418        &self,
419        vista: &Vista,
420        offset: usize,
421        limit: usize,
422    ) -> Result<(Vec<(String, Record<CborValue>)>, Option<i64>)> {
423        Ok((self.fetch_window(vista, offset, limit).await?, None))
424    }
425
426    // ---- Quicksearch -------------------------------------------------------
427
428    /// Apply a quicksearch filter — a single string the driver fans out across
429    /// the columns it considers searchable (typically those flagged
430    /// [`SEARCHABLE`](crate::flags::SEARCHABLE), but each driver decides).
431    ///
432    /// **Replace semantics**: calling `add_search` again wipes the previous
433    /// search filter before applying the new one. Default produces
434    /// `Unimplemented` (when `can_search: true`) or `Unsupported` (when
435    /// `can_search: false`).
436    fn add_search(&mut self, _text: &str) -> Result<()> {
437        Err(self.default_error("add_search", "can_search"))
438    }
439
440    /// Drop the search filter previously applied via
441    /// [`add_search`](Self::add_search). Default mirrors `add_search`.
442    fn clear_search(&mut self) -> Result<()> {
443        Err(self.default_error("clear_search", "can_search"))
444    }
445
446    // ---- Ordering ----------------------------------------------------------
447
448    /// Push a single ORDER BY clause onto the wrapped table.
449    ///
450    /// Vista's `add_order` is replace-semantics: the driver shell should clear
451    /// any previously-set order before pushing the new one. Default produces
452    /// `Unimplemented` (when `can_order: true`) or `Unsupported` (when
453    /// `can_order: false`).
454    fn add_order(&mut self, _field: &str, _dir: SortDirection) -> Result<()> {
455        Err(self.default_error("add_order", "can_order"))
456    }
457
458    /// Wipe every order clause. Default mirrors [`add_order`](Self::add_order).
459    fn clear_orders(&mut self) -> Result<()> {
460        Err(self.default_error("clear_orders", "can_order"))
461    }
462
463    // ---- Cloning -----------------------------------------------------------
464
465    /// Produce an independent copy of this shell, or `None` if the driver can't
466    /// be cloned cheaply. The copy must share the backing store / connection
467    /// (typically `Arc`) but own its own query state (conditions / order /
468    /// search) so a caller can narrow it — set an ORDER BY, add a WHERE — without
469    /// disturbing the original. This is how a consumer builds a per-view ordered
470    /// Vista to fetch from: `clone_shell()` → `add_order(...)` → `fetch_window`.
471    ///
472    /// Default `None`: drivers opt in only where a clone is genuinely cheap
473    /// (query state is small; the store is `Arc`-shared). Callers that get `None`
474    /// fall back to reading the shared shell and ordering client-side.
475    fn clone_shell(&self) -> Option<Box<dyn TableShell>> {
476        None
477    }
478
479    // ---- References --------------------------------------------------------
480
481    /// Resolve a same-persistence relation using a known source row, returning
482    /// the related table as a new `Vista`.
483    ///
484    /// Drivers override by forwarding into the wrapped typed `Table`'s
485    /// `get_ref_from_row::<EmptyEntity>(relation, &native_row)` and then
486    /// wrapping the result back as a `Vista` through the driver's factory.
487    /// The default returns `Unimplemented`. Cross-persistence refs are
488    /// handled one layer up by `vantage-vista-factory`'s `VistaCatalog`,
489    /// never here.
490    fn get_ref(&self, relation: &str, _row: &Record<CborValue>) -> Result<Vista> {
491        Err(error!(
492            format!(
493                "get_ref not implemented for '{}'",
494                std::any::type_name::<Self>()
495            ),
496            method = "get_ref",
497            relation = relation,
498            source_type = std::any::type_name::<Self>()
499        )
500        .mark_unimplemented()
501        .traced())
502    }
503
504    /// Build the **bare** target of a same-persistence relation as a `Vista` —
505    /// the table a new related row would be inserted into, with no join
506    /// condition applied. Used by Vista's nested insert to reach a has-one /
507    /// has-many child's destination.
508    ///
509    /// Drivers override by forwarding into the wrapped typed `Table`'s
510    /// `get_ref_target_erased(relation)` and wrapping the result back
511    /// through the driver's factory — the same path as [`get_ref`](Self::get_ref)
512    /// minus the row-derived condition. The default returns `Unimplemented`;
513    /// cross-persistence relations are rejected at the `Vista` layer before
514    /// this is reached.
515    fn get_ref_target(&self, relation: &str) -> Result<Vista> {
516        Err(error!(
517            format!(
518                "get_ref_target not implemented for '{}'",
519                std::any::type_name::<Self>()
520            ),
521            method = "get_ref_target",
522            relation = relation,
523            source_type = std::any::type_name::<Self>()
524        )
525        .mark_unimplemented()
526        .traced())
527    }
528
529    /// Contained (embedded-in-row) relations this shell exposes, keyed by name.
530    /// Default empty — only shells that model embedded objects/arrays override.
531    fn contained(&self) -> &IndexMap<String, ContainedSpec> {
532        static EMPTY: std::sync::OnceLock<IndexMap<String, ContainedSpec>> =
533            std::sync::OnceLock::new();
534        EMPTY.get_or_init(IndexMap::new)
535    }
536
537    /// Resolve a contained relation against a known parent `row`, returning the
538    /// embedded records as a sub-`Vista`. Writes to that sub-Vista patch the
539    /// host column of `row`'s record back through the shell. Default returns
540    /// `Unimplemented`; shells override to seed [`crate::build_contained_vista`]
541    /// with a writeback that patches the parent.
542    fn get_contained_ref(&self, relation: &str, _row: &Record<CborValue>) -> Result<Vista> {
543        Err(error!(
544            format!(
545                "get_contained_ref not implemented for '{}'",
546                std::any::type_name::<Self>()
547            ),
548            method = "get_contained_ref",
549            relation = relation,
550            source_type = std::any::type_name::<Self>()
551        )
552        .mark_unimplemented()
553        .traced())
554    }
555
556    /// Names + cardinalities of the shell's same-persistence references.
557    /// Derived from [`references`](Self::references) by default; impls
558    /// should rarely need to override.
559    fn get_ref_kinds(&self) -> Vec<(String, crate::reference::ReferenceKind)> {
560        self.references()
561            .iter()
562            .map(|(name, r)| (name.clone(), r.kind))
563            .collect()
564    }
565
566    // ---- Identity ----------------------------------------------------------
567
568    /// Short human label for the underlying driver (e.g. `"csv"`, `"sqlite"`,
569    /// `"postgres"`, `"mongodb"`). Used for diagnostics and CLI output.
570    /// Drivers should override; the default is a placeholder.
571    fn driver_name(&self) -> &'static str {
572        "unknown"
573    }
574
575    // ---- Preview -----------------------------------------------------------
576
577    /// Render the query this shell would send, **without sending it**.
578    ///
579    /// Free-form and driver-shaped: SQL answers with `sql`, GraphQL with a
580    /// `query` document, a cmd datasource with the argv it would spawn. The
581    /// only convention is a `driver` key naming the driver, so a reader can
582    /// tell what the rest of the object means.
583    ///
584    /// There is no default and no `Result`. No default, so a new driver is
585    /// forced to answer rather than inheriting silence; no `Result`, because
586    /// "there is no query" is an answer, not a failure — a driver that
587    /// generates its rows in-process says so in a `note` and is done.
588    ///
589    /// # Contract
590    ///
591    /// **Synchronous, and performs no I/O.** That is what makes preview safe
592    /// to expose where fetching is not. A value known only at fetch time (an
593    /// unresolved foreign-key narrowing) renders as a placeholder; it is never
594    /// awaited.
595    ///
596    /// **Lossy is acceptable, wrong is not.** A preview that omits a detail
597    /// should say so in a `note`. A preview showing a filter the driver would
598    /// not actually send is a bug.
599    fn preview_query(&self, vista: &Vista) -> serde_json::Value;
600
601    // ---- Scripting ---------------------------------------------------------
602
603    /// Contribute backend-specific vocabulary to a Rhai engine that
604    /// vantage-vista has already seeded with the conventional `Vista` verbs
605    /// (see the `rhai_conventional` module). Backends with an expression engine
606    /// (SurrealDB, SQL) override this to register `ident`/`==`/`fx`/graph
607    /// constructors plus a `with_condition(<backend expr>)` builder that routes
608    /// a boxed native condition through [`add_raw_condition`](Self::add_raw_condition).
609    ///
610    /// Default is a no-op: engine-less datasources (CSV/Mongo/REST) still get
611    /// the conventional verbs and only lose the vendor expression syntax —
612    /// graceful degradation, not all-or-nothing.
613    #[cfg(feature = "rhai")]
614    fn register_rhai_extensions(&self, _engine: &mut rhai::Engine) {}
615
616    /// Vendor constants a script sees beside `row`/`self` — the per-evaluation
617    /// half of [`register_rhai_extensions`](Self::register_rhai_extensions).
618    /// SurrealDB pushes `me`, the current-record anchor. A value here is a
619    /// scope variable, never an engine hook, so it composes with the host's
620    /// own resolver.
621    ///
622    /// Default: `env` unchanged.
623    #[cfg(feature = "rhai")]
624    fn rhai_env(&self, env: vantage_rhai::Env) -> vantage_rhai::Env {
625        env
626    }
627
628    // ---- Live subscription -------------------------------------------------
629
630    /// Subscribe to changes on the set and stream them as [`VistaChange`]s.
631    ///
632    /// Drivers whose backend can push changes (SurrealDB LIVE, Postgres
633    /// `LISTEN/NOTIFY`) override this and advertise
634    /// [`can_subscribe`](VistaCapabilities::can_subscribe). The row-bearing
635    /// variants carry the record in the same projected shape as
636    /// [`list_vista_values`](Self::list_vista_values), so a consumer can apply
637    /// them to a cache directly; [`VistaChange::Invalidated`] carries nothing at
638    /// all and means "re-read the set". The default produces `Unimplemented` (when
639    /// `can_subscribe: true`) or `Unsupported` (when `false`); callers branch on
640    /// `vista.capabilities().can_subscribe` first.
641    ///
642    /// # The subscription contract
643    ///
644    /// Callers always pass the full `vista`, and drivers deliver on a best-effort
645    /// basis. A consumer must not need to know whether a given backend filters
646    /// row-, select- or table-wide — that is what keeps consumer code identical
647    /// across drivers, and lets a driver tighten its scope later without
648    /// breaking anyone. Four promises hold for every implementation:
649    ///
650    /// 1. **The stream may be coarser than the vista.** Subscribing table-wide
651    ///    and letting the consumer discard what it doesn't want is a valid
652    ///    implementation; `vista` is a hint about what's interesting, not a
653    ///    filter the driver is obliged to apply.
654    /// 2. **Payload rows may fall outside the vista's conditions**, precisely
655    ///    because of (1). Either the driver reconciles (SurrealDB re-reads each
656    ///    notified id *through* the vista's conditions, so a row that no longer
657    ///    matches surfaces as [`VistaChange::Deleted`]) or the consumer must.
658    ///    Never assume an `Inserted`/`Updated` row belongs in the set.
659    /// 3. **[`VistaChange::Invalidated`] means "re-read everything".** It carries
660    ///    no id and implies nothing about how much changed — a driver with no row
661    ///    payload to offer may emit it for every single write.
662    /// 4. **Stream end is normal, not an error.** Connections drop and sessions
663    ///    expire; consumers resubscribe (with backoff) and reconcile the gap. A
664    ///    driver need not reconnect internally.
665    ///
666    /// Delivery is not guaranteed even while subscribed — see
667    /// [`can_subscribe`](VistaCapabilities::can_subscribe).
668    async fn watch_vista(&self, _vista: &Vista) -> Result<VistaChangeStream> {
669        Err(self.default_error("watch_vista", "can_subscribe"))
670    }
671
672    // ---- Capability advertisement -----------------------------------------
673
674    fn capabilities(&self) -> &VistaCapabilities;
675
676    /// Look up a capability flag by name. Used by `default_error` to decide
677    /// between `Unsupported` and `Unimplemented`. Drivers don't normally
678    /// need to override this.
679    fn capability_flag(&self, name: &str) -> bool {
680        let caps = self.capabilities();
681        match name {
682            "can_count" => caps.can_count,
683            "can_insert" => caps.can_insert,
684            "can_update" => caps.can_update,
685            "can_delete" => caps.can_delete,
686            "can_import" => caps.can_import,
687            "can_subscribe" => caps.can_subscribe,
688            "can_invalidate" => caps.can_invalidate,
689            "can_order" => caps.can_order,
690            "can_search" => caps.can_search,
691            "can_set_page_size" => caps.can_set_page_size,
692            "can_fetch_page" => caps.can_fetch_page,
693            "can_fetch_next" => caps.can_fetch_next,
694            "can_fetch_window" => caps.can_fetch_window,
695            "can_traverse_to_record" => caps.can_traverse_to_record,
696            "can_traverse_to_set" => caps.can_traverse_to_set,
697            "can_build_ref_via_script" => caps.can_build_ref_via_script,
698            "can_traverse_in_columns" => caps.can_traverse_in_columns,
699            _ => false,
700        }
701    }
702
703    /// Build the standard error returned by default trait method impls.
704    ///
705    /// Picks the kind based on the capability flag: a `true` flag means the
706    /// driver advertised support but didn't override the method (placeholder
707    /// → `Unimplemented`); a `false` flag means the driver honestly doesn't
708    /// claim the op (caller should have checked → `Unsupported`).
709    ///
710    /// Only the `Unimplemented` kind traces at error level — it's a driver
711    /// bug. An `Unsupported` refusal is a legitimate answer to a caller
712    /// probing a capability (e.g. an exploratory data script calling
713    /// `set_page_size` on a cache-mode vista): the error value carries the
714    /// full message to the caller, so it logs at debug only.
715    fn default_error(&self, method: &str, capability: &str) -> VantageError {
716        let source_type = std::any::type_name::<Self>();
717        if self.capability_flag(capability) {
718            error!(
719                format!(
720                    "'{}' is advertised as VistaCapability for '{}' but implementation for '{}' is missing",
721                    capability, source_type, method
722                ),
723                method = method,
724                capability = capability,
725                source_type = source_type
726            )
727            .mark_unimplemented().traced()
728        } else {
729            error!(
730                format!(
731                    "'{}' is not supported by '{}'; '{}' refused",
732                    capability, source_type, method
733                ),
734                method = method,
735                capability = capability,
736                source_type = source_type
737            )
738            .mark_unsupported()
739            .traced_debug()
740        }
741    }
742}