icydb_core/model/field.rs
1//! Module: model::field
2//! Responsibility: runtime field metadata and storage-decode contracts.
3//! Does not own: planner-wide query semantics or row-container orchestration.
4//! Boundary: field-level runtime schema surface used by storage and planning layers.
5
6use crate::{traits::FieldValueKind, types::EntityTag};
7
8///
9/// FieldStorageDecode
10///
11/// FieldStorageDecode captures how one persisted field payload must be
12/// interpreted at structural decode boundaries.
13/// Semantic `FieldKind` alone is not always authoritative for persisted decode:
14/// some fields intentionally store raw `Value` payloads even when their planner
15/// shape is narrower.
16///
17
18#[derive(Clone, Copy, Debug, Eq, PartialEq)]
19pub enum FieldStorageDecode {
20 /// Decode the persisted field payload according to semantic `FieldKind`.
21 ByKind,
22 /// Decode the persisted field payload directly into `Value`.
23 Value,
24}
25
26///
27/// ScalarCodec
28///
29/// ScalarCodec identifies the canonical binary leaf encoding used for one
30/// scalar persisted field payload.
31/// These codecs are fixed-width or span-bounded by the surrounding row slot
32/// container; they do not perform map/array/value dispatch.
33///
34
35#[derive(Clone, Copy, Debug, Eq, PartialEq)]
36pub enum ScalarCodec {
37 Blob,
38 Bool,
39 Date,
40 Duration,
41 Float32,
42 Float64,
43 Int64,
44 Principal,
45 Subaccount,
46 Text,
47 Timestamp,
48 Uint64,
49 Ulid,
50 Unit,
51}
52
53///
54/// LeafCodec
55///
56/// LeafCodec declares whether one persisted field payload uses a dedicated
57/// scalar codec or falls back to CBOR leaf decoding.
58/// The row container consults this metadata before deciding whether a slot can
59/// stay on the scalar fast path.
60///
61
62#[derive(Clone, Copy, Debug, Eq, PartialEq)]
63pub enum LeafCodec {
64 Scalar(ScalarCodec),
65 CborFallback,
66}
67
68///
69/// EnumVariantModel
70///
71/// EnumVariantModel carries structural decode metadata for one generated enum
72/// variant payload.
73/// Runtime structural decode uses this to stay on the field-kind contract for
74/// enum payloads instead of falling back to generic untyped CBOR decoding.
75///
76
77#[derive(Clone, Copy, Debug)]
78pub struct EnumVariantModel {
79 /// Stable schema variant tag.
80 pub(crate) ident: &'static str,
81 /// Declared payload kind when this variant carries data.
82 pub(crate) payload_kind: Option<&'static FieldKind>,
83 /// Persisted payload decode contract for the carried data.
84 pub(crate) payload_storage_decode: FieldStorageDecode,
85}
86
87impl EnumVariantModel {
88 /// Build one enum variant structural decode descriptor.
89 #[must_use]
90 pub const fn new(
91 ident: &'static str,
92 payload_kind: Option<&'static FieldKind>,
93 payload_storage_decode: FieldStorageDecode,
94 ) -> Self {
95 Self {
96 ident,
97 payload_kind,
98 payload_storage_decode,
99 }
100 }
101
102 /// Return the stable schema variant tag.
103 #[must_use]
104 pub const fn ident(&self) -> &'static str {
105 self.ident
106 }
107
108 /// Return the declared payload kind when this variant carries data.
109 #[must_use]
110 pub const fn payload_kind(&self) -> Option<&'static FieldKind> {
111 self.payload_kind
112 }
113
114 /// Return the persisted payload decode contract for this variant.
115 #[must_use]
116 pub const fn payload_storage_decode(&self) -> FieldStorageDecode {
117 self.payload_storage_decode
118 }
119}
120
121///
122/// FieldModel
123///
124/// Runtime field metadata surfaced by macro-generated `EntityModel` values.
125///
126/// This is the smallest unit consumed by predicate validation, planning,
127/// and executor-side plan checks.
128///
129
130#[derive(Debug)]
131pub struct FieldModel {
132 /// Field name as used in predicates and indexing.
133 pub(crate) name: &'static str,
134 /// Runtime type shape (no schema-layer graph nodes).
135 pub(crate) kind: FieldKind,
136 /// Whether the field may persist an explicit `NULL` payload.
137 pub(crate) nullable: bool,
138 /// Persisted field decode contract used by structural runtime decoders.
139 pub(crate) storage_decode: FieldStorageDecode,
140 /// Leaf payload codec used by slot readers and writers.
141 pub(crate) leaf_codec: LeafCodec,
142 /// Insert-time generation contract admitted on reduced SQL write lanes.
143 pub(crate) insert_generation: Option<FieldInsertGeneration>,
144 /// Auto-managed write contract emitted for derive-owned system fields.
145 pub(crate) write_management: Option<FieldWriteManagement>,
146}
147
148///
149/// FieldInsertGeneration
150///
151/// FieldInsertGeneration declares whether one runtime field may be synthesized
152/// by the reduced SQL insert boundary when the user omits that field.
153/// This stays separate from typed-Rust `Default` behavior so write-time
154/// generation remains an explicit schema contract.
155///
156
157#[derive(Clone, Copy, Debug, Eq, PartialEq)]
158pub enum FieldInsertGeneration {
159 /// Generate one fresh `Ulid` value at insert time.
160 Ulid,
161}
162
163///
164/// FieldWriteManagement
165///
166/// FieldWriteManagement declares whether one runtime field is owned by the
167/// write boundary during insert or update synthesis.
168/// This keeps auto-managed system fields explicit in schema/runtime metadata
169/// instead of relying on literal field names in write paths.
170///
171
172#[derive(Clone, Copy, Debug, Eq, PartialEq)]
173pub enum FieldWriteManagement {
174 /// Fill only on insert when the row is first created.
175 CreatedAt,
176 /// Refresh on insert and every update.
177 UpdatedAt,
178}
179
180impl FieldModel {
181 /// Build one generated runtime field descriptor.
182 ///
183 /// This constructor exists for derive/codegen output and trusted test
184 /// fixtures. Runtime planning and execution treat `FieldModel` values as
185 /// build-time-validated metadata.
186 #[must_use]
187 #[doc(hidden)]
188 pub const fn generated(name: &'static str, kind: FieldKind) -> Self {
189 Self::generated_with_storage_decode_and_nullability(
190 name,
191 kind,
192 FieldStorageDecode::ByKind,
193 false,
194 )
195 }
196
197 /// Build one runtime field descriptor with an explicit persisted decode contract.
198 #[must_use]
199 #[doc(hidden)]
200 pub const fn generated_with_storage_decode(
201 name: &'static str,
202 kind: FieldKind,
203 storage_decode: FieldStorageDecode,
204 ) -> Self {
205 Self::generated_with_storage_decode_and_nullability(name, kind, storage_decode, false)
206 }
207
208 /// Build one runtime field descriptor with an explicit decode contract and nullability.
209 #[must_use]
210 #[doc(hidden)]
211 pub const fn generated_with_storage_decode_and_nullability(
212 name: &'static str,
213 kind: FieldKind,
214 storage_decode: FieldStorageDecode,
215 nullable: bool,
216 ) -> Self {
217 Self::generated_with_storage_decode_nullability_and_write_policies(
218 name,
219 kind,
220 storage_decode,
221 nullable,
222 None,
223 None,
224 )
225 }
226
227 /// Build one runtime field descriptor with an explicit decode contract, nullability,
228 /// and insert-time generation contract.
229 #[must_use]
230 #[doc(hidden)]
231 pub const fn generated_with_storage_decode_nullability_and_insert_generation(
232 name: &'static str,
233 kind: FieldKind,
234 storage_decode: FieldStorageDecode,
235 nullable: bool,
236 insert_generation: Option<FieldInsertGeneration>,
237 ) -> Self {
238 Self::generated_with_storage_decode_nullability_and_write_policies(
239 name,
240 kind,
241 storage_decode,
242 nullable,
243 insert_generation,
244 None,
245 )
246 }
247
248 /// Build one runtime field descriptor with explicit insert-generation and
249 /// write-management policies.
250 #[must_use]
251 #[doc(hidden)]
252 pub const fn generated_with_storage_decode_nullability_and_write_policies(
253 name: &'static str,
254 kind: FieldKind,
255 storage_decode: FieldStorageDecode,
256 nullable: bool,
257 insert_generation: Option<FieldInsertGeneration>,
258 write_management: Option<FieldWriteManagement>,
259 ) -> Self {
260 Self {
261 name,
262 kind,
263 nullable,
264 storage_decode,
265 leaf_codec: leaf_codec_for(kind, storage_decode),
266 insert_generation,
267 write_management,
268 }
269 }
270
271 /// Return the stable field name.
272 #[must_use]
273 pub const fn name(&self) -> &'static str {
274 self.name
275 }
276
277 /// Return the runtime type-kind descriptor.
278 #[must_use]
279 pub const fn kind(&self) -> FieldKind {
280 self.kind
281 }
282
283 /// Return whether the persisted field contract permits explicit `NULL`.
284 #[must_use]
285 pub const fn nullable(&self) -> bool {
286 self.nullable
287 }
288
289 /// Return the persisted field decode contract.
290 #[must_use]
291 pub const fn storage_decode(&self) -> FieldStorageDecode {
292 self.storage_decode
293 }
294
295 /// Return the persisted leaf payload codec.
296 #[must_use]
297 pub const fn leaf_codec(&self) -> LeafCodec {
298 self.leaf_codec
299 }
300
301 /// Return the reduced-SQL insert-time generation contract for this field.
302 #[must_use]
303 pub const fn insert_generation(&self) -> Option<FieldInsertGeneration> {
304 self.insert_generation
305 }
306
307 /// Return the write-boundary management contract for this field.
308 #[must_use]
309 pub const fn write_management(&self) -> Option<FieldWriteManagement> {
310 self.write_management
311 }
312}
313
314// Resolve the canonical leaf codec from semantic field kind plus storage
315// contract. Fields that intentionally persist as `Value` or that still require
316// recursive payload decoding remain on the shared CBOR fallback.
317const fn leaf_codec_for(kind: FieldKind, storage_decode: FieldStorageDecode) -> LeafCodec {
318 if matches!(storage_decode, FieldStorageDecode::Value) {
319 return LeafCodec::CborFallback;
320 }
321
322 match kind {
323 FieldKind::Blob => LeafCodec::Scalar(ScalarCodec::Blob),
324 FieldKind::Bool => LeafCodec::Scalar(ScalarCodec::Bool),
325 FieldKind::Date => LeafCodec::Scalar(ScalarCodec::Date),
326 FieldKind::Duration => LeafCodec::Scalar(ScalarCodec::Duration),
327 FieldKind::Float32 => LeafCodec::Scalar(ScalarCodec::Float32),
328 FieldKind::Float64 => LeafCodec::Scalar(ScalarCodec::Float64),
329 FieldKind::Int => LeafCodec::Scalar(ScalarCodec::Int64),
330 FieldKind::Principal => LeafCodec::Scalar(ScalarCodec::Principal),
331 FieldKind::Subaccount => LeafCodec::Scalar(ScalarCodec::Subaccount),
332 FieldKind::Text => LeafCodec::Scalar(ScalarCodec::Text),
333 FieldKind::Timestamp => LeafCodec::Scalar(ScalarCodec::Timestamp),
334 FieldKind::Uint => LeafCodec::Scalar(ScalarCodec::Uint64),
335 FieldKind::Ulid => LeafCodec::Scalar(ScalarCodec::Ulid),
336 FieldKind::Unit => LeafCodec::Scalar(ScalarCodec::Unit),
337 FieldKind::Relation { key_kind, .. } => leaf_codec_for(*key_kind, storage_decode),
338 FieldKind::Account
339 | FieldKind::Decimal { .. }
340 | FieldKind::Enum { .. }
341 | FieldKind::Int128
342 | FieldKind::IntBig
343 | FieldKind::List(_)
344 | FieldKind::Map { .. }
345 | FieldKind::Set(_)
346 | FieldKind::Structured { .. }
347 | FieldKind::Uint128
348 | FieldKind::UintBig => LeafCodec::CborFallback,
349 }
350}
351
352///
353/// RelationStrength
354///
355/// Explicit relation intent for save-time referential integrity.
356///
357
358#[derive(Clone, Copy, Debug, Eq, PartialEq)]
359pub enum RelationStrength {
360 Strong,
361 Weak,
362}
363
364///
365/// FieldKind
366///
367/// Minimal runtime type surface needed by planning, validation, and execution.
368///
369/// This is aligned with `Value` variants and intentionally lossy: it encodes
370/// only the shape required for predicate compatibility and index planning.
371///
372
373#[derive(Clone, Copy, Debug)]
374pub enum FieldKind {
375 // Scalar primitives
376 Account,
377 Blob,
378 Bool,
379 Date,
380 Decimal {
381 /// Required schema-declared fractional scale for decimal fields.
382 scale: u32,
383 },
384 Duration,
385 Enum {
386 /// Fully-qualified enum type path used for strict filter normalization.
387 path: &'static str,
388 /// Declared per-variant payload decode metadata.
389 variants: &'static [EnumVariantModel],
390 },
391 Float32,
392 Float64,
393 Int,
394 Int128,
395 IntBig,
396 Principal,
397 Subaccount,
398 Text,
399 Timestamp,
400 Uint,
401 Uint128,
402 UintBig,
403 Ulid,
404 Unit,
405
406 /// Typed relation; `key_kind` reflects the referenced key type.
407 /// `strength` encodes strong vs. weak relation intent.
408 Relation {
409 /// Fully-qualified Rust type path for diagnostics.
410 target_path: &'static str,
411 /// Stable external name used in storage keys.
412 target_entity_name: &'static str,
413 /// Stable runtime identity used on hot execution paths.
414 target_entity_tag: EntityTag,
415 /// Data store path where the target entity is persisted.
416 target_store_path: &'static str,
417 key_kind: &'static Self,
418 strength: RelationStrength,
419 },
420
421 // Collections
422 List(&'static Self),
423 Set(&'static Self),
424 /// Deterministic, unordered key/value collection.
425 ///
426 /// Map fields are persistable and patchable, but not queryable or indexable.
427 Map {
428 key: &'static Self,
429 value: &'static Self,
430 },
431
432 /// Structured (non-atomic) value.
433 /// Queryability here controls whether predicates may target this field,
434 /// not whether it may be stored or updated.
435 Structured {
436 queryable: bool,
437 },
438}
439
440impl FieldKind {
441 #[must_use]
442 pub const fn value_kind(&self) -> FieldValueKind {
443 match self {
444 Self::Account
445 | Self::Blob
446 | Self::Bool
447 | Self::Date
448 | Self::Duration
449 | Self::Enum { .. }
450 | Self::Float32
451 | Self::Float64
452 | Self::Int
453 | Self::Int128
454 | Self::IntBig
455 | Self::Principal
456 | Self::Subaccount
457 | Self::Text
458 | Self::Timestamp
459 | Self::Uint
460 | Self::Uint128
461 | Self::UintBig
462 | Self::Ulid
463 | Self::Unit
464 | Self::Decimal { .. }
465 | Self::Relation { .. } => FieldValueKind::Atomic,
466 Self::List(_) | Self::Set(_) => FieldValueKind::Structured { queryable: true },
467 Self::Map { .. } => FieldValueKind::Structured { queryable: false },
468 Self::Structured { queryable } => FieldValueKind::Structured {
469 queryable: *queryable,
470 },
471 }
472 }
473
474 /// Returns `true` if this field shape is permitted in
475 /// persisted or query-visible schemas under the current
476 /// determinism policy.
477 ///
478 /// This shape-level check is structural only; query-time policy
479 /// enforcement (for example, map predicate fencing) is applied at
480 /// query construction and validation boundaries.
481 #[must_use]
482 pub const fn is_deterministic_collection_shape(&self) -> bool {
483 match self {
484 Self::Relation { key_kind, .. } => key_kind.is_deterministic_collection_shape(),
485
486 Self::List(inner) | Self::Set(inner) => inner.is_deterministic_collection_shape(),
487
488 Self::Map { key, value } => {
489 key.is_deterministic_collection_shape() && value.is_deterministic_collection_shape()
490 }
491
492 _ => true,
493 }
494 }
495}