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