Skip to main content

vantage_table/table/impls/
spec.rs

1//! Lowering a YAML [`VistaSpec`] onto a table:
2//! the steps every driver factory shares. Type mapping and driver blocks stay
3//! with the driver, passed in as `build` functions.
4
5use indexmap::IndexMap;
6use vantage_core::{Context, Result, VantageError, error};
7use vantage_expressions::{Expressive, SelectableDataSource};
8use vantage_types::{EmptyEntity, Entity};
9use vantage_vista::{ColumnFlag, ColumnSpec, JoinKey, ReferenceKind, ReferenceSugar, VistaSpec};
10
11use crate::{
12    source::SelectSource,
13    table::Table,
14    table::inject::{BuildEnv, BuildKind, BuildTrail, SpecTableBuilder},
15    traits::table_source::TableSource,
16};
17
18impl<T: TableSource, E: Entity<T::Value>> Table<T, E> {
19    /// Add one spec column. A `lazy:` column becomes a computed column;
20    /// any other is built by `build` (unless the table already has it, as a
21    /// derived table may) and registered as a title when flagged `title`.
22    /// Returns whether the column is stored.
23    pub fn add_spec_column<C>(
24        &mut self,
25        name: &str,
26        spec: &ColumnSpec<C>,
27        build: impl FnOnce(&str, &ColumnSpec<C>) -> Result<T::Column<T::AnyType>>,
28    ) -> Result<bool> {
29        if self.add_lazy_spec_column(spec, name)? {
30            return Ok(false);
31        }
32        if !self.columns.contains_key(name) {
33            self.add_column(build(name, spec)?);
34        }
35        if spec.has_flag(ColumnFlag::Title) {
36            self.add_title_field(name);
37        }
38        Ok(true)
39    }
40
41    /// [`add_spec_column`](Self::add_spec_column) for each column, in order.
42    pub fn add_spec_columns<C>(
43        &mut self,
44        columns: &IndexMap<String, ColumnSpec<C>>,
45        build: impl Fn(&str, &ColumnSpec<C>) -> Result<T::Column<T::AnyType>>,
46    ) -> Result<()> {
47        for (name, spec) in columns {
48            self.add_spec_column(name, spec, &build)?;
49        }
50        Ok(())
51    }
52
53    /// Mark the spec's id column as the id field. Errors when the spec
54    /// doesn't declare that column.
55    pub fn set_spec_id_field(&mut self, id: &str) -> Result<()> {
56        if !self.columns.contains_key(id) {
57            return Err(error!("id column not present in spec.columns", id = id));
58        }
59        self.set_id_field(id);
60        Ok(())
61    }
62
63    /// [`set_spec_id_field`](Self::set_spec_id_field), and mark the id
64    /// backend-made ([`with_auto_id`](Self::with_auto_id)) when its spec
65    /// column carries `auto`. For drivers whose backend can make ids.
66    pub fn set_spec_id<C>(
67        &mut self,
68        id: &str,
69        columns: &IndexMap<String, ColumnSpec<C>>,
70    ) -> Result<()> {
71        self.set_spec_id_field(id)?;
72        if columns
73            .get(id)
74            .is_some_and(|c| c.has_flag(ColumnFlag::Auto))
75        {
76            self.id_auto = true;
77        }
78        Ok(())
79    }
80}
81
82impl<T: TableSource + 'static, E: Entity<T::Value> + 'static> Table<T, E>
83where
84    T::Value: Into<ciborium::Value> + From<ciborium::Value>,
85    T::Id: std::fmt::Display + From<String>,
86{
87    /// Register every join `spec` declares as `with_one` / `with_many`: its
88    /// `references:` entries, then the column-level `references:` sugar
89    /// (see [`spec_references`]).
90    ///
91    /// At traversal time the reference asks `env`'s resolver for the target's
92    /// current spec and rebuilds it with `build`, in a fresh environment of
93    /// kind [`BuildKind::Reference`] carrying `env`'s injector. A miss or a
94    /// build error is a traversal error, never a wider table. Without a
95    /// resolver the target is a column-less `Table::new(target)`, still run
96    /// through the injector. A contained kind is an error: contained
97    /// relations are declared under `contained:`.
98    pub fn with_spec_references<X, C, R, S: 'static>(
99        mut self,
100        spec: &VistaSpec<X, C, R>,
101        env: &BuildEnv<S, T>,
102        build: SpecTableBuilder<S, T>,
103    ) -> Result<Self> {
104        for (relation, reference) in &spec.references {
105            let foreign_key = reference.foreign_key(relation);
106            self = self.with_spec_join(
107                &spec.name,
108                relation,
109                &reference.table,
110                reference.kind,
111                (&foreign_key, &reference.keys),
112                env,
113                build,
114            )?;
115        }
116        for (column, sugar) in column_references(spec) {
117            let (target, kind, foreign_key, keys) = match sugar {
118                ReferenceSugar::Sugar(target) => {
119                    (target, ReferenceKind::HasOne, column.clone(), &[][..])
120                }
121                ReferenceSugar::Full(r) => (&r.table, r.kind, r.foreign_key(column), &r.keys[..]),
122                _ => return Err(unknown_sugar(column)),
123            };
124            self = self.with_spec_join(
125                &spec.name,
126                column,
127                target,
128                kind,
129                (&foreign_key, keys),
130                env,
131                build,
132            )?;
133        }
134        Ok(self)
135    }
136
137    /// `join` is the foreign key and the `keys:`, which supersede it when
138    /// given.
139    #[allow(clippy::too_many_arguments)]
140    fn with_spec_join<S: 'static>(
141        self,
142        from: &str,
143        relation: &str,
144        target: &str,
145        kind: ReferenceKind,
146        join: (&str, &[JoinKey]),
147        env: &BuildEnv<S, T>,
148        build: SpecTableBuilder<S, T>,
149    ) -> Result<Self> {
150        let target_name = target.to_string();
151        let relation_name = relation.to_string();
152        let child = BuildEnv {
153            resolver: env.resolver.clone(),
154            injector: env.injector.clone(),
155            trail: BuildTrail::default().enter(target)?,
156            kind: BuildKind::Reference {
157                from: from.to_string(),
158                relation: relation.to_string(),
159            },
160        };
161        let build_target = move |source: T| -> Result<Table<T, EmptyEntity>> {
162            let Some(r) = &child.resolver else {
163                let mut table = Table::new(target_name.clone(), source);
164                child.inject(&target_name, &mut table, build)?;
165                return Ok(table);
166            };
167            let spec = r.resolve(&target_name).ok_or_else(|| {
168                error!(
169                    "reference target has no spec",
170                    relation = relation_name.as_str(),
171                    target = target_name.as_str()
172                )
173            })?;
174            build(&spec, source, &child).with_context(|| {
175                error!(
176                    "reference target failed to build",
177                    relation = relation_name.as_str(),
178                    target = target_name.as_str()
179                )
180            })
181        };
182        let (foreign_key, keys) = join;
183        match kind {
184            ReferenceKind::HasOne if keys.is_empty() => {
185                Ok(self.try_with_one(relation, foreign_key, target, build_target))
186            }
187            ReferenceKind::HasOne => self.try_with_one_keyed(relation, keys, target, build_target),
188            ReferenceKind::HasMany if keys.is_empty() => {
189                Ok(self.try_with_many(relation, foreign_key, target, build_target))
190            }
191            ReferenceKind::HasMany => {
192                self.try_with_many_keyed(relation, keys, target, build_target)
193            }
194            _ => Err(error!(
195                "references: entries must be has_one or has_many",
196                relation = relation
197            )),
198        }
199    }
200}
201
202/// Every join `spec` declares, as Vista references: each `references:`
203/// entry, then each column-level `references:` not shadowed by an entry of
204/// the same name. The sugar names its relation after the column, which is
205/// also its foreign key: `bakery: { references: bakery }` is a has-one
206/// keyed by `bakery`. `source_id` is the column a `has_many` reads from
207/// this table's rows.
208pub fn spec_references<X, C, R>(
209    spec: &VistaSpec<X, C, R>,
210    source_id: &str,
211) -> Result<Vec<vantage_vista::Reference>> {
212    let mut out = Vec::with_capacity(spec.references.len());
213    for (relation, reference) in &spec.references {
214        out.push(reference.to_reference(relation, source_id)?);
215    }
216    for (column, sugar) in column_references(spec) {
217        out.push(match sugar {
218            ReferenceSugar::Sugar(target) => {
219                vantage_vista::Reference::has_one(column, target, JoinKey::to_target_id(column))
220            }
221            ReferenceSugar::Full(r) => r.to_reference(column, source_id)?,
222            _ => return Err(unknown_sugar(column)),
223        });
224    }
225    Ok(out)
226}
227
228fn unknown_sugar(column: &str) -> VantageError {
229    error!(
230        "column references: takes a table name or a full reference",
231        column = column
232    )
233}
234
235/// The column-level `references:` of `spec` that no `references:` entry
236/// shadows, keyed by column.
237fn column_references<X, C, R>(
238    spec: &VistaSpec<X, C, R>,
239) -> impl Iterator<Item = (&String, &ReferenceSugar)> {
240    spec.columns.iter().filter_map(|(column, col)| {
241        let sugar = col.references.as_ref()?;
242        (!spec.references.contains_key(column)).then_some((column, sugar))
243    })
244}
245
246// Same bounds as `Table::derive_from`, which this builds on.
247impl<T, E, V, Cond, S> Table<T, E>
248where
249    T: SelectableDataSource<V, Cond, Select = S>
250        + TableSource<Value = V, Condition = Cond, Source = SelectSource<S>>,
251    V: Clone + Send + Sync + 'static + From<String>,
252    Cond: Clone + Send + Sync + 'static,
253    S: Expressive<V> + Clone,
254    E: Entity<V>,
255{
256    /// Lower a `base:` spec: a table over `select` (the base's select, possibly
257    /// transformed) that inherits the listed base columns and relations, adds
258    /// the spec's own columns (aggregate outputs, say) and contained
259    /// relations, and keeps the base's id unless the spec names one.
260    pub fn derive_from_spec<E2: Entity<V> + 'static, X, C, R>(
261        base: &Table<T, E2>,
262        spec: &VistaSpec<X, C, R>,
263        select: S,
264        inherit_columns: &[String],
265        inherit_relations: &[String],
266        build_column: impl Fn(&str, &ColumnSpec<C>) -> Result<T::Column<T::AnyType>>,
267    ) -> Result<Self>
268    where
269        T: 'static,
270        E: 'static,
271    {
272        let columns: Vec<&str> = inherit_columns.iter().map(String::as_str).collect();
273        let relations: Vec<&str> = inherit_relations.iter().map(String::as_str).collect();
274        let mut table = Self::derive_from(
275            base,
276            spec.name.clone(),
277            move |_| select,
278            &columns,
279            &relations,
280        );
281        table.add_spec_columns(&spec.columns, &build_column)?;
282        if let Some(id) = &spec.id_column {
283            // The base made its own id, not this one: a different id is
284            // auto only when its own column says so.
285            if table.id_field.as_deref() != Some(id.as_str()) {
286                table.set_id_field(id);
287                table.id_auto = spec
288                    .columns
289                    .get(id)
290                    .is_some_and(|c| c.has_flag(ColumnFlag::Auto));
291            }
292        }
293        table.with_contained_specs(&spec.contained, build_column)
294    }
295}