1use crate::{
4 __private::RowInfo,
5 Error, IndexValue,
6 codec::Decoder,
7 key,
8 primary::RowKey,
9 types::{TypeGraph, TypeLink},
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 crate::member::resolve_field(self, path).is_ok_and(|(parent, member)| {
233 !self.fields[parent].optional && member.is_none_or(|m| !m.field().optional)
234 })
235 }
236
237 pub(crate) fn record_member(&self, path: &str) -> Option<(usize, crate::member::RecordMember)> {
238 let (parent, child) = path.split_once('.')?;
239 let position = self.field_position(parent)?;
240 let member =
241 crate::member::RecordMember::resolve(self.fields[position].value, child).ok()?;
242 Some((position, member))
243 }
244
245 pub(crate) fn index_field(&self, name: &str) -> Option<&FieldSchema> {
246 self.field_by_name(name)
247 .or_else(|| self.record_member(name).map(|(_, member)| member.field()))
248 }
249
250 pub(crate) fn index_by_name(&self, name: &str) -> Option<&IndexSchema> {
251 self.indexes.iter().find(|index| index.name == name)
252 }
253
254 pub(crate) fn has_managed(&self) -> bool {
255 self.fields.iter().any(|field| field.managed.is_some())
256 }
257
258 pub(crate) fn key_type(&self) -> Result<FieldType, Error> {
259 self.field_by_name(self.primary_key)
260 .filter(|field| !field.optional)
261 .map(|f| f.value)
262 .ok_or(Error::Corrupt)
263 }
264 pub(crate) fn inspect_row(&self, bytes: &[u8]) -> Result<RowInfo, Error> {
267 let mut values = [IndexValue::Absent; MAX_FIELDS];
268 let mut spans = [(0, 0); MAX_FIELDS];
269 self.inspect_fields(bytes, self.key_fields(), &mut values, Some(&mut spans))?;
270
271 self.row_info(&values, bytes, &spans)
272 }
273
274 pub(crate) fn key_fields(&self) -> u32 {
275 self.fields
276 .iter()
277 .enumerate()
278 .fold(0, |mask, (position, field)| {
279 if field.name == self.primary_key
280 || self.indexes.iter().any(|i| i.fields.contains(&field.name))
281 {
282 mask | (1 << position)
283 } else {
284 mask
285 }
286 })
287 }
288 pub(crate) fn inspect_fields<'a>(
294 &self,
295 bytes: &'a [u8],
296 selected: u32,
297 keys: &mut [IndexValue<'a>; MAX_FIELDS],
298 mut spans: Option<&mut [(u16, u16); MAX_FIELDS]>,
299 ) -> Result<(), Error> {
300 let mut reader = Decoder::for_entity(bytes, self)?;
301 let mut times = [None; 2];
302 for (position, field) in self.fields.iter().enumerate() {
303 let start = reader.position();
304 let present = !field.optional || reader.boolean()?;
305 if !present {
306 } else if let Some(managed) = field.managed {
308 let value = reader.timestamp()?;
309 times[managed.slot()] = Some(value);
310 keys[position] = IndexValue::from(value);
311 } else if selected & (1 << position) != 0 {
312 *keys.get_mut(position).ok_or(Error::Corrupt)? =
313 IndexValue::read(&mut reader, field.value)?;
314 } else {
315 reader.skip(field.value)?;
316 }
317 if let Some(spans) = &mut spans {
318 spans[position] = (start as u16, reader.position() as u16);
319 }
320 }
321 reader.finish()?;
322 crate::managed::validate_order(times)?;
323
324 Ok(())
325 }
326
327 pub(crate) fn row_info<'a>(
328 &self,
329 keys: &[IndexValue<'a>; MAX_FIELDS],
330 bytes: &'a [u8],
331 spans: &[(u16, u16); MAX_FIELDS],
332 ) -> Result<RowInfo, Error> {
333 let position = |name: &str| self.field_position(name).ok_or(Error::Corrupt);
334 let indexes = self
335 .indexes
336 .iter()
337 .map(|index| {
338 let mut components = [(IndexValue::Absent, false); 4];
339 for (slot, name) in components.iter_mut().zip(index.fields) {
340 *slot = if let Some(position) = self.field_position(name) {
341 (keys[position], self.fields[position].optional)
342 } else {
343 let (parent, member) = self.record_member(name).ok_or(Error::Corrupt)?;
344 let (start, end) = spans[parent];
345 (
346 member.read(&bytes[usize::from(start)..usize::from(end)], false)?,
347 false,
348 )
349 };
350 if slot.0 == IndexValue::Absent && !slot.1 {
351 return Err(Error::Corrupt);
352 }
353 }
354
355 Ok(key::encode_index(
356 &components[..index.fields.len()],
357 index.present_only,
358 ))
359 })
360 .collect::<Result<_, Error>>()?;
361 let key = RowKey::from_index(keys[position(self.primary_key)?])?;
362
363 let mut list_links = Vec::new();
364 for (field, &(start, end)) in self.fields.iter().zip(spans) {
365 if let (Some(reference), FieldType::List { item, max_items }) =
366 (field.reference, field.value)
367 {
368 let mut reader = Decoder::new(&bytes[usize::from(start)..usize::from(end)])?;
369 if !field.optional || reader.boolean()? {
370 let count = reader.nat32()?;
371 if count > max_items {
372 return Err(Error::Corrupt);
373 }
374 for _ in 0..count {
375 list_links.push((
376 reference.index,
377 RowKey::from_index(IndexValue::read(&mut reader, *item)?)?,
378 ));
379 }
380 }
381 reader.finish()?;
382 }
383 }
384 Ok(RowInfo {
385 key,
386 indexes,
387 list_links,
388 })
389 }
390}
391
392#[derive(Clone)]
397pub struct Schema {
398 entities: Vec<&'static EntitySchema>,
399 pub(crate) fingerprint: [u8; 32],
400 types: TypeGraph,
401}
402
403impl Schema {
404 pub fn new(entities: &[&'static EntitySchema]) -> Result<Self, Error> {
408 Self::admit_schema(entities, |_, _, _, _| {})
409 }
410
411 pub(crate) fn admit_schema(
413 entities: &[&'static EntitySchema],
414 report_reference: impl FnOnce(&str, &FieldSchema, &str, Option<(&str, FieldType)>),
415 ) -> Result<Self, Error> {
416 if entities.is_empty() || entities.len() > usize::from(MAX_ENTITIES) {
417 return Err(Error::InvalidSchema);
418 }
419 let mut entities = entities.to_vec();
420 entities.sort_by_key(|entity| entity.name);
421 let mut bytes = b"ICDBSC01".to_vec();
422 for version in [2, crate::codec::ROW_CODEC_VERSION, 1, 2, 1] {
428 bytes.extend(version.to_le_bytes());
429 }
430 bytes.extend((entities.len() as u32).to_le_bytes());
431 let mut ids = BTreeSet::new();
432 let mut types = TypeGraph::default();
433 for entity in &entities {
434 if entity.id != handle(entity.name)
435 || !ids.insert(entity.id)
436 || entity.fields.is_empty()
437 || !(1..=crate::codec::MAX_ROW_BYTES).contains(&entity.max_row_bytes)
438 || entity.fields.len() > MAX_FIELDS
439 || entity.indexes.len() > 8
440 || !entity.key_type().is_ok_and(RowKey::supports)
441 || entity
442 .fields
443 .windows(2)
444 .any(|pair| pair[0].name >= pair[1].name)
445 {
446 return Err(Error::InvalidSchema);
447 }
448 name(&mut bytes, entity.name)?;
449 if entity.max_row_bytes != crate::codec::DEFAULT_ROW_BYTES {
450 bytes.extend(0_u32.to_le_bytes());
452 bytes.extend((entity.max_row_bytes as u32).to_le_bytes());
453 }
454 bytes.extend((entity.fields.len() as u32).to_le_bytes());
455 let mut list_fanout = 0;
456 let mut list_indexes = BTreeSet::new();
457 for field in entity.fields {
458 name(&mut bytes, field.name)?;
459 encode_type(
460 &mut bytes,
461 field.value,
462 field.optional,
463 field.reference.is_some(),
464 )?;
465 types.include(field.value)?;
466 if let Some(reference) = field.reference {
467 let Some(target) = entities.iter().find(|target| {
468 target.id == reference.entity && target.name == reference.entity_name
469 }) else {
470 report_reference(entity.name, field, reference.entity_name, None);
471
472 return Err(Error::InvalidSchema);
473 };
474 let key_type = target.key_type().map_err(|_| Error::InvalidSchema)?;
475 let referenced_type = match field.value {
476 FieldType::List { item, .. } => *item,
477 scalar => scalar,
478 };
479 if referenced_type != key_type {
480 report_reference(
481 entity.name,
482 field,
483 target.name,
484 Some((target.primary_key, key_type)),
485 );
486
487 return Err(Error::InvalidSchema);
488 }
489 if let FieldType::List { max_items, .. } = field.value {
490 list_fanout += max_items;
491 if list_fanout > 32
492 || reference.index != handle(field.name)
493 || !list_indexes.insert(reference.index)
494 {
495 return Err(Error::InvalidSchema);
496 }
497 name(&mut bytes, target.name)?;
498 name(&mut bytes, field.name)?;
499 continue;
500 }
501 if !RowKey::supports(field.value) {
502 return Err(Error::InvalidSchema);
503 }
504 let index = entity
505 .indexes
506 .iter()
507 .find(|index| {
508 index.id == reference.index
509 && !index.present_only
510 && index.fields.first() == Some(&field.name)
511 })
512 .ok_or(Error::InvalidSchema)?;
513 name(&mut bytes, target.name)?;
514 name(&mut bytes, index.name)?;
515 }
516 }
517 name(&mut bytes, entity.primary_key)?;
518 bytes.extend((entity.indexes.len() as u32).to_le_bytes());
519 let mut index_ids = BTreeSet::new();
520 for index in entity.indexes {
521 if index.id != handle(index.name)
522 || !index_ids.insert(index.id)
523 || index.fields.is_empty()
524 || index.fields.len() > 4
525 {
526 return Err(Error::InvalidSchema);
527 }
528 let mut fields = BTreeSet::new();
529 let has_optional = index.fields.iter().any(|name| {
530 entity
531 .fields
532 .iter()
533 .any(|field| field.name == *name && field.optional)
534 });
535 if (index.unique && has_optional && !index.present_only)
536 || (index.present_only && (!index.unique || !has_optional))
537 {
538 return Err(Error::InvalidSchema);
539 }
540 name(&mut bytes, index.name)?;
541 bytes.push(u8::from(index.unique) | (u8::from(index.present_only) << 1));
542 bytes.extend((index.fields.len() as u32).to_le_bytes());
543 for field in index.fields {
544 if !fields.insert(field) {
545 return Err(Error::InvalidSchema);
546 }
547 if let Some(declared) = entity.field_by_name(field) {
548 if !key::supports(declared.value) {
549 return Err(Error::InvalidSchema);
550 }
551 name(&mut bytes, field)?;
552 } else {
553 let (parent, member) =
554 entity.record_member(field).ok_or(Error::InvalidSchema)?;
555 let parent = &entity.fields[parent];
556 let leaf = member.field();
557 if index.unique
558 || index.fields.len() != 1
559 || parent.optional
560 || leaf.optional
561 {
562 return Err(Error::InvalidSchema);
563 }
564 bytes.extend(u32::MAX.to_le_bytes());
567 name(&mut bytes, parent.name)?;
568 name(&mut bytes, leaf.name)?;
569 }
570 }
571 }
572 if entity
573 .indexes
574 .windows(2)
575 .any(|pair| pair[0].name >= pair[1].name)
576 {
577 return Err(Error::InvalidSchema);
578 }
579 }
580 types.encode(&mut bytes)?;
581 let defaults: Vec<_> = entities
584 .iter()
585 .flat_map(|entity| {
586 entity
587 .fields
588 .iter()
589 .filter_map(move |field| field.default.map(|value| (entity, field, value)))
590 })
591 .collect();
592 if !defaults.is_empty() {
593 bytes.extend(b"ic-db:insert-defaults:v1\0");
594 bytes.extend((defaults.len() as u32).to_le_bytes());
595 for (entity, field, value) in defaults {
596 if field.name == entity.primary_key {
597 return Err(Error::InvalidSchema);
598 }
599 name(&mut bytes, entity.name)?;
600 name(&mut bytes, field.name)?;
601 let encoded = value.encode(field.value)?;
602 bytes.extend((encoded.len() as u32).to_le_bytes());
603 bytes.extend(encoded);
604 }
605 }
606 let mut policies = Vec::new();
607 for entity in &entities {
608 let mut seen = [false; 2];
609 for field in entity.fields {
610 if let Some(managed) = field.managed {
611 if crate::key::operand_type(field.value) != FieldType::Timestamp
612 || field.optional
613 || field.default.is_some()
614 || field.reference.is_some()
615 || field.name == entity.primary_key
616 || seen[managed.slot()]
617 {
618 return Err(Error::InvalidSchema);
619 }
620 seen[managed.slot()] = true;
621 policies.push((entity.name, field.name, managed));
622 }
623 }
624 }
625 if !policies.is_empty() {
626 bytes.extend(b"ic-db:managed-times:v1\0");
627 bytes.extend((policies.len() as u32).to_le_bytes());
628 for (entity, field, managed) in policies {
629 name(&mut bytes, entity)?;
630 name(&mut bytes, field)?;
631 bytes.push(managed.slot() as u8 + 1);
632 }
633 }
634 let mut hash = Sha256::new();
635 hash.update(b"ic-db:schema:v1\0");
636 hash.update(bytes);
637
638 Ok(Self {
639 entities,
640 types,
641 fingerprint: hash.finalize().into(),
642 })
643 }
644
645 #[must_use]
647 pub const fn fingerprint(&self) -> [u8; 32] {
648 self.fingerprint
649 }
650
651 #[must_use]
653 pub fn entities(&self) -> &[&'static EntitySchema] {
654 &self.entities
655 }
656
657 pub(crate) fn entity_by_id(&self, id: u32) -> Option<&'static EntitySchema> {
658 self.entities.iter().copied().find(|entity| entity.id == id)
659 }
660
661 pub(crate) fn entity_by_name(&self, name: &str) -> Option<&'static EntitySchema> {
662 self.entities
663 .binary_search_by_key(&name, |entity| entity.name)
664 .ok()
665 .map(|position| self.entities[position])
666 }
667
668 pub fn types(&self) -> impl Iterator<Item = &'static crate::TypeSchema> + '_ {
670 self.types.definitions()
671 }
672
673 pub(crate) fn admits(&self, proposed: &EntitySchema) -> Result<&'static EntitySchema, Error> {
677 let current = self.entity_by_id(proposed.id).ok_or(Error::UnknownEntity)?;
678 if current.max_row_bytes != proposed.max_row_bytes
679 || current.name != proposed.name
680 || current.fields != proposed.fields
681 || current.primary_key != proposed.primary_key
682 || current.indexes != proposed.indexes
683 {
684 return Err(Error::UnknownEntity);
685 }
686 let mut proposed_types = TypeGraph::default();
687 for field in proposed.fields {
688 proposed_types
689 .include(field.value)
690 .map_err(|_| Error::UnknownEntity)?;
691 }
692 if !self.types.contains(&proposed_types) {
693 return Err(Error::UnknownEntity);
694 }
695
696 Ok(current)
697 }
698}
699
700pub(crate) fn name(bytes: &mut Vec<u8>, value: &str) -> Result<(), Error> {
701 if value.is_empty() || value.len() > 64 {
702 return Err(Error::InvalidSchema);
703 }
704 bytes.extend((value.len() as u32).to_le_bytes());
705 bytes.extend(value.as_bytes());
706
707 Ok(())
708}
709
710pub(crate) fn encode_type(
711 bytes: &mut Vec<u8>,
712 value: FieldType,
713 optional: bool,
714 reference: bool,
715) -> Result<(), Error> {
716 let tag = match value {
717 FieldType::Nat64 => 1,
718 FieldType::Bool => 2,
719 FieldType::Text { .. } => 3,
720 FieldType::Int64 => 4,
721 FieldType::Nat128 => 5,
722 FieldType::Int128 => 6,
723 FieldType::Blob { .. } => 7,
724 FieldType::Nat8 => 8,
725 FieldType::Nat16 => 9,
726 FieldType::Nat32 => 10,
727 FieldType::Int8 => 11,
728 FieldType::Int16 => 12,
729 FieldType::Int32 => 13,
730 FieldType::Principal => 14,
731 FieldType::Named(_) => 15,
732 FieldType::List { .. } => 16,
733 FieldType::U256 => 17,
734 FieldType::Float32 => 18,
735 FieldType::Float64 => 19,
736 FieldType::Subaccount => 20,
737 FieldType::Account => 21,
738 FieldType::Ulid => 22,
739 FieldType::Date => 23,
740 FieldType::Timestamp => 24,
741 FieldType::Duration => 25,
742 FieldType::Decimal { .. } => 26,
743 };
744 bytes.push(tag | if optional { 0x80 } else { 0 } | if reference { 0x40 } else { 0 });
745 match value {
746 FieldType::Decimal { scale } => {
747 if scale > crate::Decimal::MAX_SCALE {
748 return Err(Error::InvalidSchema);
749 }
750 bytes.extend(scale.to_le_bytes());
751 }
752 FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } => {
753 if max_bytes > crate::codec::MAX_ROW_BYTES as u32 {
754 return Err(Error::InvalidSchema);
755 }
756 bytes.extend(max_bytes.to_le_bytes());
757 }
758 FieldType::Named(link) => name(bytes, link.name)?,
759 FieldType::List { item, max_items } => {
760 if max_items > crate::types::MAX_COLLECTION_ITEMS as u32
761 || matches!(item, FieldType::List { .. })
762 {
763 return Err(Error::InvalidSchema);
764 }
765 for bound in [
766 max_items,
767 crate::types::MAX_DEPTH as u32,
768 crate::types::MAX_NODES as u32,
769 crate::types::MAX_COLLECTION_ITEMS as u32,
770 ] {
771 bytes.extend(bound.to_le_bytes());
772 }
773 encode_type(bytes, *item, false, false)?;
774 }
775 _ => {}
776 }
777
778 Ok(())
779}