1use crate::{
4 __private::RowInfo,
5 Error, IndexValue,
6 codec::Decoder,
7 key,
8 named_schema::{TypeGraph, TypeLink},
9 primary::RowKey,
10};
11use sha2::{Digest, Sha256};
12use std::collections::BTreeSet;
13
14#[doc(hidden)]
18#[must_use]
19pub const fn check_schema_member(path: &str, root: &str, members: Option<&str>) -> bool {
20 const fn listed(path: &[u8], list: &[u8]) -> bool {
21 let mut start = 0;
22 while start < list.len() {
23 let mut end = start;
24 let mut same = true;
25 while end < list.len() && list[end] != b'|' {
26 let i = end - start;
27 same = same && i < path.len() && path[i] == list[end];
28 end += 1;
29 }
30 if same && end - start == path.len() {
31 return true;
32 }
33 start = end + 1;
34 }
35
36 false
37 }
38 let path = path.as_bytes();
39 let mut first_separator = 0;
40 while first_separator < path.len() && path[first_separator] != b':' {
41 first_separator += 1;
42 }
43 let (_, relative) = path.split_at(first_separator);
44
45 let root = root.as_bytes();
46 let mut index = 0;
47 while index < root.len() {
48 if index == relative.len() || relative[index] != root[index] {
49 return true;
50 }
51 index += 1;
52 }
53
54 match members {
55 Some(paths) => listed(relative, paths.as_bytes()),
56 None => false,
57 }
58}
59
60pub(crate) const MAX_ENTITIES: u8 = 128;
61pub(crate) const MAX_FIELDS: usize = 32;
62
63#[doc(hidden)]
66#[must_use]
67pub const fn handle(name: &str) -> u32 {
68 let bytes = name.as_bytes();
69 let mut value = 2_166_136_261_u32;
70 let mut position = 0;
71 while position < bytes.len() {
72 value = (value ^ bytes[position] as u32).wrapping_mul(16_777_619);
73 position += 1;
74 }
75
76 value
77}
78
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub enum FieldType {
82 List {
84 item: &'static FieldType,
86 max_items: u32,
88 },
89 Named(TypeLink),
92 Nat8,
94 Nat16,
96 Nat32,
98 Int8,
100 Int16,
102 Int32,
104 Nat64,
106 Int64,
108 Nat128,
110 Int128,
112 U256,
114 Ulid,
116 Date,
118 Timestamp,
120 Duration,
122 Decimal {
124 scale: u32,
126 },
127 Float32,
129 Float64,
131 Bool,
133 Principal,
135 Subaccount,
137 Account,
139 Text {
141 max_bytes: u32,
143 },
144 Blob {
146 max_bytes: u32,
148 },
149}
150
151#[derive(Clone, Copy, Debug, PartialEq, Eq)]
153pub struct FieldSchema {
154 pub managed: Option<crate::ManagedTimestamp>,
156 pub default: Option<&'static crate::LiteralDefault>,
158 pub name: &'static str,
160 pub value: FieldType,
162 pub optional: bool,
164 pub reference: Option<ReferenceSchema>,
166}
167
168#[derive(Clone, Copy, Debug, PartialEq, Eq)]
171pub struct ReferenceSchema {
172 pub entity_name: &'static str,
174 #[doc(hidden)]
176 pub entity: u32,
177 pub index: u32,
179}
180
181#[derive(Debug, PartialEq, Eq)]
183pub struct IndexSchema {
184 #[doc(hidden)]
186 pub id: u32,
187 pub name: &'static str,
189 pub fields: &'static [&'static str],
191 pub unique: bool,
193 pub present_only: bool,
195}
196
197impl IndexSchema {
198 pub(crate) fn is_unique_lookup(&self, fixed_components: usize) -> bool {
200 self.unique && fixed_components == self.fields.len()
201 }
202}
203
204pub struct EntitySchema {
206 pub max_row_bytes: usize,
208 #[doc(hidden)]
210 pub id: u32,
211 pub name: &'static str,
213 pub fields: &'static [FieldSchema],
215 pub primary_key: &'static str,
217 pub indexes: &'static [IndexSchema],
219}
220
221impl EntitySchema {
222 pub(crate) fn field_position(&self, name: &str) -> Option<usize> {
223 self.fields.iter().position(|field| field.name == name)
224 }
225
226 pub(crate) fn field_by_name(&self, name: &str) -> Option<&FieldSchema> {
227 self.field_position(name)
228 .map(|position| &self.fields[position])
229 }
230
231 pub(crate) fn field_is_required(&self, path: &str) -> bool {
232 self.index_field(path).is_some_and(|field| !field.optional)
233 }
234
235 pub(crate) fn record_member(&self, path: &str) -> Option<(usize, crate::member::RecordMember)> {
236 let (parent, child) = path.split_once('.')?;
237 let position = self.field_position(parent)?;
238 let member =
239 crate::member::RecordMember::resolve(self.fields[position].value, child).ok()?;
240 Some((position, member))
241 }
242
243 pub(crate) fn index_field(&self, name: &str) -> Option<crate::ValueSchema> {
244 let (parent, member) = crate::member::resolve_field(self, name).ok()?;
245 let field = &self.fields[parent];
246 let leaf = member.map_or(field, |m| m.field());
247
248 Some(crate::ValueSchema {
249 value: leaf.value,
250 optional: field.optional || leaf.optional,
251 })
252 }
253
254 pub(crate) fn index_by_name(&self, name: &str) -> Option<&IndexSchema> {
255 self.indexes.iter().find(|index| index.name == name)
256 }
257
258 pub(crate) fn has_managed(&self) -> bool {
259 self.fields.iter().any(|field| field.managed.is_some())
260 }
261
262 pub(crate) fn key_type(&self) -> Result<FieldType, Error> {
263 self.field_by_name(self.primary_key)
264 .filter(|field| !field.optional)
265 .map(|f| f.value)
266 .ok_or(Error::Corrupt)
267 }
268 pub(crate) fn inspect_row(&self, bytes: &[u8]) -> Result<RowInfo, Error> {
271 let mut values = [IndexValue::Absent; MAX_FIELDS];
272 let mut spans = [(0, 0); MAX_FIELDS];
273 self.inspect_fields(bytes, self.key_fields(), &mut values, Some(&mut spans))?;
274
275 self.row_info(&values, bytes, &spans)
276 }
277
278 pub(crate) fn key_fields(&self) -> u32 {
279 self.fields
280 .iter()
281 .enumerate()
282 .fold(0, |mask, (position, field)| {
283 if field.name == self.primary_key
284 || self.indexes.iter().any(|i| i.fields.contains(&field.name))
285 {
286 mask | (1 << position)
287 } else {
288 mask
289 }
290 })
291 }
292 pub(crate) fn inspect_fields<'a>(
298 &self,
299 bytes: &'a [u8],
300 selected: u32,
301 keys: &mut [IndexValue<'a>; MAX_FIELDS],
302 mut spans: Option<&mut [(u16, u16); MAX_FIELDS]>,
303 ) -> Result<(), Error> {
304 let mut reader = Decoder::for_entity(bytes, self)?;
305 let mut times = [None; 2];
306 for (position, field) in self.fields.iter().enumerate() {
307 let start = reader.position();
308 let present = !field.optional || reader.boolean()?;
309 if !present {
310 } else if let Some(managed) = field.managed {
312 let value = reader.timestamp()?;
313 times[managed.slot()] = Some(value);
314 keys[position] = IndexValue::from(value);
315 } else if selected & (1 << position) != 0 {
316 *keys.get_mut(position).ok_or(Error::Corrupt)? =
317 IndexValue::read(&mut reader, field.value)?;
318 } else {
319 reader.skip(field.value)?;
320 }
321 if let Some(spans) = &mut spans {
322 spans[position] = (start as u16, reader.position() as u16);
323 }
324 }
325 reader.finish()?;
326 crate::managed::validate_order(times)?;
327
328 Ok(())
329 }
330
331 pub(crate) fn row_info<'a>(
332 &self,
333 keys: &[IndexValue<'a>; MAX_FIELDS],
334 bytes: &'a [u8],
335 spans: &[(u16, u16); MAX_FIELDS],
336 ) -> Result<RowInfo, Error> {
337 let position = |name: &str| self.field_position(name).ok_or(Error::Corrupt);
338 let indexes = self
339 .indexes
340 .iter()
341 .map(|index| {
342 let mut components = [(IndexValue::Absent, false); 4];
343 for (slot, name) in components.iter_mut().zip(index.fields) {
344 *slot = if let Some(position) = self.field_position(name) {
345 (keys[position], self.fields[position].optional)
346 } else {
347 let (parent, member) = self.record_member(name).ok_or(Error::Corrupt)?;
348 let (start, end) = spans[parent];
349 let optional = self.fields[parent].optional;
350 (
351 member.read(&bytes[usize::from(start)..usize::from(end)], optional)?,
352 optional || member.field().optional,
353 )
354 };
355 if slot.0 == IndexValue::Absent && !slot.1 {
356 return Err(Error::Corrupt);
357 }
358 }
359
360 Ok(key::encode_index(
361 &components[..index.fields.len()],
362 index.present_only,
363 ))
364 })
365 .collect::<Result<_, Error>>()?;
366 let key = RowKey::from_index(keys[position(self.primary_key)?])?;
367
368 let mut list_links = Vec::new();
369 for (field, &(start, end)) in self.fields.iter().zip(spans) {
370 if let (Some(reference), FieldType::List { item, max_items }) =
371 (field.reference, field.value)
372 {
373 let mut reader = Decoder::new(&bytes[usize::from(start)..usize::from(end)])?;
374 if !field.optional || reader.boolean()? {
375 let count = reader.nat32()?;
376 if count > max_items {
377 return Err(Error::Corrupt);
378 }
379 for _ in 0..count {
380 list_links.push((
381 reference.index,
382 RowKey::from_index(IndexValue::read(&mut reader, *item)?)?,
383 ));
384 }
385 }
386 reader.finish()?;
387 }
388 }
389 Ok(RowInfo {
390 key,
391 indexes,
392 list_links,
393 })
394 }
395}
396
397#[derive(Clone)]
402pub struct Schema {
403 entities: Vec<&'static EntitySchema>,
404 pub(crate) fingerprint: [u8; 32],
405 types: TypeGraph,
406}
407
408impl Schema {
409 pub fn new(entities: &[&'static EntitySchema]) -> Result<Self, Error> {
413 Self::admit_schema(entities, |_, _, _, _| {})
414 }
415
416 pub(crate) fn admit_schema(
418 entities: &[&'static EntitySchema],
419 report_reference: impl FnOnce(&str, &FieldSchema, &str, Option<(&str, FieldType)>),
420 ) -> Result<Self, Error> {
421 if entities.is_empty() || entities.len() > usize::from(MAX_ENTITIES) {
422 return Err(Error::InvalidSchema);
423 }
424 let mut entities = entities.to_vec();
425 entities.sort_by_key(|entity| entity.name);
426 let mut bytes = b"ICDBSC01".to_vec();
427 for version in [2, crate::codec::ROW_CODEC_VERSION, 1, 2, 1] {
433 bytes.extend(version.to_le_bytes());
434 }
435 bytes.extend((entities.len() as u32).to_le_bytes());
436 let mut ids = BTreeSet::new();
437 let mut types = TypeGraph::default();
438 for entity in &entities {
439 if entity.id != handle(entity.name)
440 || !ids.insert(entity.id)
441 || entity.fields.is_empty()
442 || !(1..=crate::codec::MAX_ROW_BYTES).contains(&entity.max_row_bytes)
443 || entity.fields.len() > MAX_FIELDS
444 || entity.indexes.len() > 8
445 || !entity.key_type().is_ok_and(RowKey::supports)
446 || entity
447 .fields
448 .windows(2)
449 .any(|pair| pair[0].name >= pair[1].name)
450 {
451 return Err(Error::InvalidSchema);
452 }
453 name(&mut bytes, entity.name)?;
454 if entity.max_row_bytes != crate::codec::DEFAULT_ROW_BYTES {
455 bytes.extend(0_u32.to_le_bytes());
457 bytes.extend((entity.max_row_bytes as u32).to_le_bytes());
458 }
459 bytes.extend((entity.fields.len() as u32).to_le_bytes());
460 let mut list_fanout = 0;
461 let mut list_indexes = BTreeSet::new();
462 for field in entity.fields {
463 name(&mut bytes, field.name)?;
464 encode_type(
465 &mut bytes,
466 field.value,
467 field.optional,
468 field.reference.is_some(),
469 )?;
470 types.include(field.value)?;
471 if let Some(reference) = field.reference {
472 let Some(target) = entities.iter().find(|target| {
473 target.id == reference.entity && target.name == reference.entity_name
474 }) else {
475 report_reference(entity.name, field, reference.entity_name, None);
476
477 return Err(Error::InvalidSchema);
478 };
479 let key_type = target.key_type().map_err(|_| Error::InvalidSchema)?;
480 let referenced_type = match field.value {
481 FieldType::List { item, .. } => *item,
482 scalar => scalar,
483 };
484 if referenced_type != key_type {
485 report_reference(
486 entity.name,
487 field,
488 target.name,
489 Some((target.primary_key, key_type)),
490 );
491
492 return Err(Error::InvalidSchema);
493 }
494 if let FieldType::List { max_items, .. } = field.value {
495 list_fanout += max_items;
496 if list_fanout > 32
497 || reference.index != handle(field.name)
498 || !list_indexes.insert(reference.index)
499 {
500 return Err(Error::InvalidSchema);
501 }
502 name(&mut bytes, target.name)?;
503 name(&mut bytes, field.name)?;
504 continue;
505 }
506 if !RowKey::supports(field.value) {
507 return Err(Error::InvalidSchema);
508 }
509 let index = entity
510 .indexes
511 .iter()
512 .find(|index| {
513 index.id == reference.index
514 && !index.present_only
515 && index.fields.first() == Some(&field.name)
516 })
517 .ok_or(Error::InvalidSchema)?;
518 name(&mut bytes, target.name)?;
519 name(&mut bytes, index.name)?;
520 }
521 }
522 name(&mut bytes, entity.primary_key)?;
523 bytes.extend((entity.indexes.len() as u32).to_le_bytes());
524 let mut index_ids = BTreeSet::new();
525 for index in entity.indexes {
526 if index.id != handle(index.name)
527 || !index_ids.insert(index.id)
528 || index.fields.is_empty()
529 || index.fields.len() > 4
530 {
531 return Err(Error::InvalidSchema);
532 }
533 let mut fields = BTreeSet::new();
534 let has_optional = index.fields.iter().any(|name| {
535 entity
536 .fields
537 .iter()
538 .any(|field| field.name == *name && field.optional)
539 });
540 if (index.unique && has_optional && !index.present_only)
541 || (index.present_only && (!index.unique || !has_optional))
542 {
543 return Err(Error::InvalidSchema);
544 }
545 name(&mut bytes, index.name)?;
546 bytes.push(u8::from(index.unique) | (u8::from(index.present_only) << 1));
547 bytes.extend((index.fields.len() as u32).to_le_bytes());
548 for field in index.fields {
549 if !fields.insert(field) {
550 return Err(Error::InvalidSchema);
551 }
552 if let Some(declared) = entity.field_by_name(field) {
553 if !key::supports(declared.value) {
554 return Err(Error::InvalidSchema);
555 }
556 name(&mut bytes, field)?;
557 } else {
558 let (parent, member) =
559 entity.record_member(field).ok_or(Error::InvalidSchema)?;
560 let parent = &entity.fields[parent];
561 let leaf = member.field();
562 if index.unique || index.fields.len() != 1 {
563 return Err(Error::InvalidSchema);
564 }
565 bytes.extend(u32::MAX.to_le_bytes());
568 name(&mut bytes, parent.name)?;
569 name(&mut bytes, leaf.name)?;
570 }
571 }
572 }
573 if entity
574 .indexes
575 .windows(2)
576 .any(|pair| pair[0].name >= pair[1].name)
577 {
578 return Err(Error::InvalidSchema);
579 }
580 }
581 types.encode(&mut bytes)?;
582 let defaults: Vec<_> = entities
585 .iter()
586 .flat_map(|entity| {
587 entity
588 .fields
589 .iter()
590 .filter_map(move |field| field.default.map(|value| (entity, field, value)))
591 })
592 .collect();
593 if !defaults.is_empty() {
594 bytes.extend(b"ic-db:insert-defaults:v1\0");
595 bytes.extend((defaults.len() as u32).to_le_bytes());
596 for (entity, field, value) in defaults {
597 if field.name == entity.primary_key {
598 return Err(Error::InvalidSchema);
599 }
600 name(&mut bytes, entity.name)?;
601 name(&mut bytes, field.name)?;
602 let encoded = value.encode(field.value)?;
603 bytes.extend((encoded.len() as u32).to_le_bytes());
604 bytes.extend(encoded);
605 }
606 }
607 let mut policies = Vec::new();
608 for entity in &entities {
609 let mut seen = [false; 2];
610 for field in entity.fields {
611 if let Some(managed) = field.managed {
612 if crate::key::operand_type(field.value) != FieldType::Timestamp
613 || field.optional
614 || field.default.is_some()
615 || field.reference.is_some()
616 || field.name == entity.primary_key
617 || seen[managed.slot()]
618 {
619 return Err(Error::InvalidSchema);
620 }
621 seen[managed.slot()] = true;
622 policies.push((entity.name, field.name, managed));
623 }
624 }
625 }
626 if !policies.is_empty() {
627 bytes.extend(b"ic-db:managed-times:v1\0");
628 bytes.extend((policies.len() as u32).to_le_bytes());
629 for (entity, field, managed) in policies {
630 name(&mut bytes, entity)?;
631 name(&mut bytes, field)?;
632 bytes.push(managed.slot() as u8 + 1);
633 }
634 }
635 let mut hash = Sha256::new();
636 hash.update(b"ic-db:schema:v1\0");
637 hash.update(bytes);
638
639 Ok(Self {
640 entities,
641 types,
642 fingerprint: hash.finalize().into(),
643 })
644 }
645
646 #[must_use]
648 pub const fn fingerprint(&self) -> [u8; 32] {
649 self.fingerprint
650 }
651
652 #[must_use]
654 pub fn entities(&self) -> &[&'static EntitySchema] {
655 &self.entities
656 }
657
658 pub(crate) fn entity_by_id(&self, id: u32) -> Option<&'static EntitySchema> {
659 self.entities.iter().copied().find(|entity| entity.id == id)
660 }
661
662 pub(crate) fn entity_by_name(&self, name: &str) -> Option<&'static EntitySchema> {
663 self.entities
664 .binary_search_by_key(&name, |entity| entity.name)
665 .ok()
666 .map(|position| self.entities[position])
667 }
668
669 pub fn types(&self) -> impl Iterator<Item = &'static crate::TypeSchema> + '_ {
671 self.types.definitions()
672 }
673
674 pub(crate) fn admits(&self, proposed: &EntitySchema) -> Result<&'static EntitySchema, Error> {
678 let current = self.entity_by_id(proposed.id).ok_or(Error::UnknownEntity)?;
679 if current.max_row_bytes != proposed.max_row_bytes
680 || current.name != proposed.name
681 || current.fields != proposed.fields
682 || current.primary_key != proposed.primary_key
683 || current.indexes != proposed.indexes
684 {
685 return Err(Error::UnknownEntity);
686 }
687 let mut proposed_types = TypeGraph::default();
688 for field in proposed.fields {
689 proposed_types
690 .include(field.value)
691 .map_err(|_| Error::UnknownEntity)?;
692 }
693 if !self.types.contains(&proposed_types) {
694 return Err(Error::UnknownEntity);
695 }
696
697 Ok(current)
698 }
699}
700
701pub(crate) fn name(bytes: &mut Vec<u8>, value: &str) -> Result<(), Error> {
702 if value.is_empty() || value.len() > 64 {
703 return Err(Error::InvalidSchema);
704 }
705 bytes.extend((value.len() as u32).to_le_bytes());
706 bytes.extend(value.as_bytes());
707
708 Ok(())
709}
710
711pub(crate) fn encode_type(
712 bytes: &mut Vec<u8>,
713 value: FieldType,
714 optional: bool,
715 reference: bool,
716) -> Result<(), Error> {
717 let tag = match value {
718 FieldType::Nat64 => 1,
719 FieldType::Bool => 2,
720 FieldType::Text { .. } => 3,
721 FieldType::Int64 => 4,
722 FieldType::Nat128 => 5,
723 FieldType::Int128 => 6,
724 FieldType::Blob { .. } => 7,
725 FieldType::Nat8 => 8,
726 FieldType::Nat16 => 9,
727 FieldType::Nat32 => 10,
728 FieldType::Int8 => 11,
729 FieldType::Int16 => 12,
730 FieldType::Int32 => 13,
731 FieldType::Principal => 14,
732 FieldType::Named(_) => 15,
733 FieldType::List { .. } => 16,
734 FieldType::U256 => 17,
735 FieldType::Float32 => 18,
736 FieldType::Float64 => 19,
737 FieldType::Subaccount => 20,
738 FieldType::Account => 21,
739 FieldType::Ulid => 22,
740 FieldType::Date => 23,
741 FieldType::Timestamp => 24,
742 FieldType::Duration => 25,
743 FieldType::Decimal { .. } => 26,
744 };
745 bytes.push(tag | if optional { 0x80 } else { 0 } | if reference { 0x40 } else { 0 });
746 match value {
747 FieldType::Decimal { scale } => {
748 if scale > crate::Decimal::MAX_SCALE {
749 return Err(Error::InvalidSchema);
750 }
751 bytes.extend(scale.to_le_bytes());
752 }
753 FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => {
754 if max_bytes > crate::codec::MAX_ROW_BYTES as u32 {
755 return Err(Error::InvalidSchema);
756 }
757 bytes.extend(max_bytes.to_le_bytes());
758 }
759 FieldType::Named(link) => name(bytes, link.name)?,
760 FieldType::List { item, max_items } => {
761 if max_items > crate::named_schema::MAX_COLLECTION_ITEMS as u32
762 || matches!(item, FieldType::List { .. })
763 {
764 return Err(Error::InvalidSchema);
765 }
766 for bound in [
767 max_items,
768 crate::named_schema::MAX_DEPTH as u32,
769 crate::named_schema::MAX_NODES as u32,
770 crate::named_schema::MAX_COLLECTION_ITEMS as u32,
771 ] {
772 bytes.extend(bound.to_le_bytes());
773 }
774 encode_type(bytes, *item, false, false)?;
775 }
776 _ => {}
777 }
778
779 Ok(())
780}