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