Skip to main content

schema_core/config/
projection.rs

1//! Projecting a self-describing schema into a fully-typed mapping — without a
2//! database.
3//!
4//! Every gap a thin config once left to the source is now stated in the schema:
5//! a column field carries its [`FlussoType`](super::FlussoType) and nullability,
6//! an aggregate its result type. So the mapping follows from the schema alone.
7//! The structural rules are unchanged from when the source derived them — a
8//! group is an `object`, a to-many join is a `nested` array, a `count` is a
9//! non-null `long`, a primary key is never null — they just no longer need a
10//! round-trip to ask.
11
12use crate::common::{ColumnName, GenericValue, IndexName};
13
14use super::{
15    Aggregate, AggregateOp, Column, ContentHash, Field, FieldSource, IndexMapping, IndexSchema,
16    Mapping, MappingType, Relation, ResolvedField,
17};
18
19impl IndexSchema {
20    /// Project this schema into its fully-typed [`IndexMapping`].
21    pub fn resolve(&self, index: IndexName) -> IndexMapping {
22        resolve_index(index, self)
23    }
24}
25
26fn resolve_index(index: IndexName, schema: &IndexSchema) -> IndexMapping {
27    IndexMapping {
28        index,
29        // Hash the parsed schema, not the file: structural changes (including a
30        // declared type) flip the hash; cosmetic file changes do not.
31        hash: ContentHash::of(schema),
32        fields: resolve_fields(&schema.fields, schema.primary_key.as_ref()),
33    }
34}
35
36/// Resolve a list of fields. `primary_key` is the root table's key while we are
37/// still on the root row (it passes through groups, which stay on the same row);
38/// it is `None` once we cross into a related table via a join.
39fn resolve_fields(fields: &[Field], primary_key: Option<&ColumnName>) -> Vec<ResolvedField> {
40    fields
41        .iter()
42        .map(|field| resolve_field(field, primary_key))
43        .collect()
44}
45
46fn resolve_field(field: &Field, primary_key: Option<&ColumnName>) -> ResolvedField {
47    let (child_fields, child_pk): (&[Field], Option<&ColumnName>) = match &field.source {
48        FieldSource::Relation(Relation::Join(join)) => (&join.fields, Some(&join.primary_key)),
49        FieldSource::Group(fields) => (fields, primary_key),
50        _ => (&[], primary_key),
51    };
52    let children = resolve_fields(child_fields, child_pk);
53
54    let (mapping_type, nullable) = type_and_nullability(field, primary_key);
55    let mapping = Mapping {
56        mapping_type,
57        extra: field.options.clone(),
58    };
59
60    ResolvedField {
61        name: field.field.clone(),
62        mapping,
63        nullable,
64        children,
65    }
66}
67
68fn type_and_nullability(field: &Field, primary_key: Option<&ColumnName>) -> (MappingType, bool) {
69    match &field.source {
70        FieldSource::Column(Column {
71            column,
72            ty,
73            nullable,
74            default,
75            ..
76        }) => {
77            let forced_non_null = primary_key == Some(column) || default.is_some();
78            (ty.opensearch(), *nullable && !forced_non_null)
79        }
80        FieldSource::Group(_) => (MappingType::Object, false),
81        FieldSource::Geo(geo) => (MappingType::Other("geo_point".to_owned()), geo.nullable),
82        FieldSource::Constant(value) => (
83            constant_mapping_type(value),
84            matches!(value, GenericValue::Null),
85        ),
86        FieldSource::Relation(Relation::Join(join)) => {
87            if join.kind.is_to_many() {
88                (MappingType::Nested, false)
89            } else {
90                (MappingType::Object, true)
91            }
92        }
93        FieldSource::Relation(Relation::Aggregate(aggregate)) => aggregate_type(aggregate),
94    }
95}
96
97fn aggregate_type(aggregate: &Aggregate) -> (MappingType, bool) {
98    match &aggregate.op {
99        AggregateOp::Count => (MappingType::Long, false),
100        AggregateOp::Avg(_) => (MappingType::Double, true),
101        AggregateOp::Sum(_) | AggregateOp::Min(_) | AggregateOp::Max(_) => {
102            let mapping_type = aggregate
103                .value_type
104                .as_ref()
105                .map(|ty| ty.opensearch())
106                // Conversion requires a `value_type` for these ops; `double` is
107                // a defensive fallback that should never be reached.
108                .unwrap_or(MappingType::Double);
109            (mapping_type, true)
110        }
111    }
112}
113
114/// The mapping type a constant value's shape implies.
115fn constant_mapping_type(value: &GenericValue) -> MappingType {
116    match value {
117        GenericValue::Bool(_) => MappingType::Boolean,
118        GenericValue::Int(_) => MappingType::Long,
119        GenericValue::Decimal(_) => MappingType::Double,
120        GenericValue::Array(items) => items
121            .first()
122            .map(constant_mapping_type)
123            .unwrap_or(MappingType::Keyword),
124        GenericValue::Map(_) => MappingType::Object,
125        GenericValue::String(_) | GenericValue::Null => MappingType::Keyword,
126    }
127}