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