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