icydb-model 0.213.35

IcyDB application-model authoring, validation, and code generation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use crate::prelude::*;
use icydb_schema::{SchemaContractError, SourceCheckExpr};
use std::{
    fmt::{self, Display},
    ops::Not,
};

use crate::node::{Schema, SourceExpressionResolver};

///
/// IndexExpression
///
/// Canonical deterministic expression key metadata for expression indexes.
/// This enum is semantic authority across schema/runtime/planner boundaries.
///
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
pub enum IndexExpression {
    Lower(&'static str),
    Upper(&'static str),
    Trim(&'static str),
    LowerTrim(&'static str),
    Date(&'static str),
    Year(&'static str),
    Month(&'static str),
    Day(&'static str),
}

impl IndexExpression {
    /// Borrow the referenced field for this expression key item.
    #[must_use]
    pub const fn field(&self) -> &'static str {
        match self {
            Self::Lower(field)
            | Self::Upper(field)
            | Self::Trim(field)
            | Self::LowerTrim(field)
            | Self::Date(field)
            | Self::Year(field)
            | Self::Month(field)
            | Self::Day(field) => field,
        }
    }
}

impl Display for IndexExpression {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Lower(field) => write!(f, "LOWER({field})"),
            Self::Upper(field) => write!(f, "UPPER({field})"),
            Self::Trim(field) => write!(f, "TRIM({field})"),
            Self::LowerTrim(field) => write!(f, "LOWER(TRIM({field}))"),
            Self::Date(field) => write!(f, "DATE({field})"),
            Self::Year(field) => write!(f, "YEAR({field})"),
            Self::Month(field) => write!(f, "MONTH({field})"),
            Self::Day(field) => write!(f, "DAY({field})"),
        }
    }
}

///
/// IndexKeyItem
///
/// Canonical index key-item metadata.
/// `Field` preserves field-key behavior.
/// `Expression` reserves deterministic expression-key identity metadata.
///
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
pub enum IndexKeyItem {
    Field(&'static str),
    Expression(IndexExpression),
}

impl IndexKeyItem {
    /// Borrow this key-item's referenced field.
    #[must_use]
    pub const fn field(&self) -> &'static str {
        match self {
            Self::Field(field) => field,
            Self::Expression(expression) => expression.field(),
        }
    }

    /// Render one deterministic canonical text form for diagnostics/display.
    #[must_use]
    pub fn canonical_text(&self) -> String {
        match self {
            Self::Field(field) => (*field).to_string(),
            Self::Expression(expression) => expression.to_string(),
        }
    }
}

///
/// IndexKeyItemsRef
///
/// Borrowed view over index key-item metadata.
/// Field-only indexes use `Fields`; mixed/explicit key metadata uses `Items`.
///
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum IndexKeyItemsRef {
    Fields(&'static [&'static str]),
    Items(&'static [IndexKeyItem]),
}

///
/// Index
///

#[derive(Clone, Debug, Serialize)]
pub struct Index {
    source_key: &'static str,
    name: &'static str,
    fields: &'static [&'static str],

    #[serde(skip_serializing_if = "Option::is_none")]
    key_items: Option<&'static [IndexKeyItem]>,

    #[serde(skip_serializing_if = "Not::not")]
    unique: bool,

    // Raw predicate SQL remains input metadata until lowered into canonical
    // predicate semantics at runtime schema boundary.
    #[serde(skip_serializing_if = "Option::is_none")]
    predicate: Option<&'static str>,

    #[serde(skip)]
    predicate_expression: Option<SourceExpressionResolver>,
}

impl Index {
    /// Build one index declaration from field-list and uniqueness metadata.
    #[must_use]
    pub const fn new(
        source_key: &'static str,
        name: &'static str,
        fields: &'static [&'static str],
        unique: bool,
    ) -> Self {
        Self::new_with_key_items_and_predicate(source_key, name, fields, None, unique, None, None)
    }

    /// Build one index declaration with optional conditional predicate metadata.
    #[must_use]
    pub const fn new_with_predicate(
        source_key: &'static str,
        name: &'static str,
        fields: &'static [&'static str],
        unique: bool,
        predicate: Option<&'static str>,
        predicate_expression: Option<SourceExpressionResolver>,
    ) -> Self {
        Self::new_with_key_items_and_predicate(
            source_key,
            name,
            fields,
            None,
            unique,
            predicate,
            predicate_expression,
        )
    }

    /// Build one index declaration with explicit canonical key-item metadata.
    #[must_use]
    pub const fn new_with_key_items(
        source_key: &'static str,
        name: &'static str,
        fields: &'static [&'static str],
        key_items: &'static [IndexKeyItem],
        unique: bool,
    ) -> Self {
        Self::new_with_key_items_and_predicate(
            source_key,
            name,
            fields,
            Some(key_items),
            unique,
            None,
            None,
        )
    }

    /// Build one index declaration with explicit key items + predicate metadata.
    #[must_use]
    pub const fn new_with_key_items_and_predicate(
        source_key: &'static str,
        name: &'static str,
        fields: &'static [&'static str],
        key_items: Option<&'static [IndexKeyItem]>,
        unique: bool,
        predicate: Option<&'static str>,
        predicate_expression: Option<SourceExpressionResolver>,
    ) -> Self {
        Self {
            source_key,
            name,
            fields,
            key_items,
            unique,
            predicate,
            predicate_expression,
        }
    }

    /// Borrow the immutable index source key.
    #[must_use]
    pub const fn source_key(&self) -> &'static str {
        self.source_key
    }

    /// Borrow the editable index name.
    #[must_use]
    pub const fn name(&self) -> &'static str {
        self.name
    }

    /// Borrow index field sequence.
    #[must_use]
    pub const fn fields(&self) -> &'static [&'static str] {
        self.fields
    }

    /// Borrow canonical key-item metadata for this index.
    #[must_use]
    pub const fn key_items(&self) -> IndexKeyItemsRef {
        if let Some(items) = self.key_items {
            IndexKeyItemsRef::Items(items)
        } else {
            IndexKeyItemsRef::Fields(self.fields)
        }
    }

    /// Return whether this index includes expression key items.
    #[must_use]
    pub const fn has_expression_key_items(&self) -> bool {
        let Some(items) = self.key_items else {
            return false;
        };

        let mut index = 0usize;
        while index < items.len() {
            if matches!(items[index], IndexKeyItem::Expression(_)) {
                return true;
            }
            index = index.saturating_add(1);
        }

        false
    }

    /// Return whether the index enforces uniqueness.
    #[must_use]
    pub const fn is_unique(&self) -> bool {
        self.unique
    }

    /// Return optional conditional-index predicate SQL metadata.
    ///
    /// This text is input-only; runtime/planner semantics must consume the
    /// canonical lowered predicate form.
    #[must_use]
    pub const fn predicate(&self) -> Option<&'static str> {
        self.predicate
    }

    /// Lower the optional compiler-validated predicate into the public source
    /// AST.
    ///
    /// # Errors
    ///
    /// Returns a typed proposal error when an enum literal no longer resolves
    /// through the sealed graph or the expression violates public bounds.
    pub fn source_predicate(
        &self,
        schema: &Schema,
    ) -> Result<Option<SourceCheckExpr>, SchemaContractError> {
        match (self.predicate, self.predicate_expression) {
            (None, None) => Ok(None),
            (Some(_), Some(resolve)) => resolve(schema).map(Some),
            (None, Some(_)) | (Some(_), None) => Err(SchemaContractError::InvalidExpression),
        }
    }

    #[must_use]
    pub fn is_prefix_of(&self, other: &Self) -> bool {
        self.fields().len() < other.fields().len() && other.fields().starts_with(self.fields())
    }

    fn joined_key_items(&self) -> String {
        match self.key_items() {
            IndexKeyItemsRef::Fields(fields) => fields.join(", "),
            IndexKeyItemsRef::Items(items) => {
                let mut joined = String::new();

                for item in items {
                    if !joined.is_empty() {
                        joined.push_str(", ");
                    }
                    joined.push_str(item.canonical_text().as_str());
                }

                joined
            }
        }
    }
}

impl Display for Index {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let fields = self.joined_key_items();

        if self.is_unique() {
            if let Some(predicate) = self.predicate() {
                write!(f, "UNIQUE ({fields}) WHERE {predicate}")
            } else {
                write!(f, "UNIQUE ({fields})")
            }
        } else if let Some(predicate) = self.predicate() {
            write!(f, "({fields}) WHERE {predicate}")
        } else {
            write!(f, "({fields})")
        }
    }
}

impl MacroNode for Index {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl ValidateNode for Index {
    fn validate(&self) -> Result<(), ErrorTree> {
        let mut errs = ErrorTree::new();
        validate_source_key(
            &mut errs,
            "index",
            self.source_key(),
            icydb_schema::IndexSourceKey::try_new,
        );
        errs.result()
    }
}

impl VisitableNode for Index {
    fn route_key(&self) -> String {
        self.joined_key_items()
    }
}

///
/// TESTS
///

#[cfg(test)]
mod tests {
    use crate::node::index::{Index, IndexExpression, IndexKeyItem, IndexKeyItemsRef};

    #[test]
    fn index_with_predicate_reports_conditional_shape() {
        let index = Index::new_with_predicate(
            "email_active",
            "idx_user__email",
            &["email"],
            false,
            Some("active = true"),
            None,
        );

        assert_eq!(index.predicate(), Some("active = true"));
        assert_eq!(index.to_string(), "(email) WHERE active = true");
    }

    #[test]
    fn index_without_predicate_preserves_unconditional_shape() {
        let index = Index::new("email", "uidx_user__email", &["email"], true);

        assert_eq!(index.predicate(), None);
        assert_eq!(index.to_string(), "UNIQUE (email)");
    }

    #[test]
    fn index_with_explicit_key_items_exposes_expression_items() {
        static KEY_ITEMS: [IndexKeyItem; 2] = [
            IndexKeyItem::Field("tenant_id"),
            IndexKeyItem::Expression(IndexExpression::Lower("email")),
        ];
        let index = Index::new_with_key_items(
            "tenant_lower_email",
            "idx_user__tenant_id__lower_email",
            &["tenant_id"],
            &KEY_ITEMS,
            false,
        );

        assert!(index.has_expression_key_items());
        assert_eq!(index.to_string(), "(tenant_id, LOWER(email))");
        std::assert_matches!(
            index.key_items(),
            IndexKeyItemsRef::Items(items)
                if items == KEY_ITEMS.as_slice()
        );
    }
}