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