1use std::path::Path;
16use std::time::{Duration, Instant};
17
18use rudb_common::{LogicalType, Result, Value};
19use rudb_graph::{Degrees, Form, KeyMap, Keys, NO_PARENT, link, wire};
20use rudb_vector::Chunk;
21
22use crate::section::{self, Attachment};
23use crate::{Catalog, Reader, invalid, type_tag};
24
25#[derive(Debug)]
35pub struct KeyColumn<'a> {
36 reader: &'a Reader,
37 columns: Vec<usize>,
38}
39
40impl<'a> KeyColumn<'a> {
41 pub fn new(reader: &'a Reader, key: usize) -> Result<Self> {
50 let fields = reader.table().fields();
51 let columns = columns_of(key);
52 for &column in &columns {
53 let Some(field) = fields.get(column) else {
54 return Err(invalid(&format!(
55 "column {column} is past the {} of table {}",
56 fields.len(),
57 reader.table().name()
58 )));
59 };
60 if !mappable(&field.ty) {
61 return Err(invalid(&format!(
62 "a key map over {} needs an integer key form, and {} has none",
63 field.name, field.ty
64 )));
65 }
66 }
67 Ok(Self { reader, columns })
68 }
69}
70
71impl Keys for KeyColumn<'_> {
72 fn scan(&self, each: &mut dyn FnMut(Option<i128>) -> Result<()>) -> Result<()> {
73 for part in 0..self.reader.parts() {
74 let chunk = self.reader.read(part, &self.columns)?;
75 let first = chunk.column(0)?;
76 let second = if self.columns.len() == 2 { Some(chunk.column(1)?) } else { None };
77 for row in 0..chunk.len() {
78 let key = key_at(&chunk, first, 0, row)?;
79 let key = match second {
80 None => key,
81 Some(second) => match (key, key_at(&chunk, second, 1, row)?) {
82 (Some(high), Some(low)) => Some(fold(high, low)?),
83 _ => None,
85 },
86 };
87 each(key)?;
88 }
89 }
90 Ok(())
91 }
92}
93
94const PAIR: usize = 1 << 31;
103
104const PAIR_BITS: u32 = 15;
106
107#[must_use]
112pub fn key_of(columns: &[usize]) -> Option<usize> {
113 let fits = |column: usize| column < 1 << PAIR_BITS;
114 match *columns {
115 [column] if column < PAIR => Some(column),
116 [first, second] if fits(first) && fits(second) => Some(PAIR | first << PAIR_BITS | second),
117 _ => None,
118 }
119}
120
121#[must_use]
123pub fn pair(first: usize, second: usize) -> Option<usize> {
124 key_of(&[first, second])
125}
126
127#[must_use]
129pub fn columns_of(key: usize) -> Vec<usize> {
130 if key & PAIR == 0 {
131 return vec![key];
132 }
133 let mask = (1 << PAIR_BITS) - 1;
134 vec![(key >> PAIR_BITS) & mask, key & mask]
135}
136
137fn fold(high: i128, low: i128) -> Result<i128> {
147 const SHIFT: i128 = 1 << 32;
148 let fits = |value: i128| i128::from(i32::MIN) <= value && value <= i128::from(i32::MAX);
149 if !fits(high) || !fits(low) {
150 return Err(invalid("a two column key holds a value too wide to fold into one key"));
151 }
152 Ok(high * SHIFT + (low - i128::from(i32::MIN)))
153}
154
155fn key_tag(fields: &[rudb_common::Field], key: usize) -> Option<u8> {
160 match *columns_of(key) {
161 [column] => type_tag(&fields.get(column)?.ty).ok(),
162 [first, second] => {
163 fields.get(first)?;
164 fields.get(second)?;
165 type_tag(&LogicalType::BigInt).ok()
166 }
167 _ => None,
168 }
169}
170
171fn mappable(ty: &LogicalType) -> bool {
173 matches!(
174 ty,
175 LogicalType::TinyInt
176 | LogicalType::SmallInt
177 | LogicalType::Integer
178 | LogicalType::BigInt
179 | LogicalType::HugeInt
180 | LogicalType::UTinyInt
181 | LogicalType::USmallInt
182 | LogicalType::UInteger
183 | LogicalType::UBigInt
184 | LogicalType::Date
185 | LogicalType::Decimal { .. }
186 )
187}
188
189fn key_at(
197 chunk: &Chunk,
198 values: &rudb_vector::Vector,
199 column: usize,
200 row: usize,
201) -> Result<Option<i128>> {
202 if let Some(key) = values.signed_at(row) {
203 return Ok(Some(key));
204 }
205 match chunk.value_at(row, column) {
206 Value::Null => Ok(None),
207 Value::TinyInt(key) => Ok(Some(i128::from(key))),
208 Value::SmallInt(key) => Ok(Some(i128::from(key))),
209 Value::Integer(key) | Value::Date(key) => Ok(Some(i128::from(key))),
210 Value::BigInt(key) | Value::Time(key) | Value::Timestamp(key) => Ok(Some(i128::from(key))),
211 Value::HugeInt(key) | Value::Decimal { unscaled: key, .. } => Ok(Some(key)),
212 Value::UTinyInt(key) => Ok(Some(i128::from(key))),
213 Value::USmallInt(key) => Ok(Some(i128::from(key))),
214 Value::UInteger(key) => Ok(Some(i128::from(key))),
215 Value::UBigInt(key) => Ok(Some(i128::from(key))),
216 other => Err(invalid(&format!("a key column holds {other}, which is not a key"))),
217 }
218}
219
220#[derive(Debug, Clone, Copy)]
227pub struct Built {
228 pub column: usize,
230 pub form: Form,
232 pub rows: u64,
234 pub distinct: bool,
237 pub bytes: usize,
239 pub column_bytes: u64,
241 pub built: bool,
245 pub build: Duration,
247}
248
249pub fn build_key_map(reader: &Reader, column: usize) -> Result<KeyMap> {
255 KeyMap::build_from(&KeyColumn::new(reader, column)?)
256}
257
258pub const BUDGET_SHARE: u64 = 10;
266
267pub const BUDGET_FLOOR: u64 = 64 * 1024;
280
281pub fn build_key_maps(path: &Path, table: &str, columns: &[usize]) -> Result<Vec<Built>> {
291 build_key_maps_within(path, table, columns, BUDGET_SHARE)
292}
293
294pub fn build_key_maps_within(
312 path: &Path,
313 table: &str,
314 columns: &[usize],
315 share: u64,
316) -> Result<Vec<Built>> {
317 let reader = Catalog::open(path)?.table(table)?;
318 let column_bytes = reader.layout().columns_total();
319 let allowance = (column_bytes.saturating_mul(share) / 100).max(BUDGET_FLOOR);
320 let mut spent = held_bytes(&reader, columns)?;
321 let mut report = Vec::with_capacity(columns.len());
322 let mut payloads = Vec::with_capacity(columns.len());
323 for &column in columns {
324 let start = Instant::now();
325 let map = build_key_map(&reader, column)?;
326 let tag = key_tag(reader.table().fields(), column)
327 .ok_or_else(|| invalid("a key map over a column the table does not have"))?;
328 let payload = wire::encode(&map, tag)?;
329 report.push(Built {
330 column,
331 form: map.form(),
332 rows: map.observed().rows,
333 distinct: map.observed().distinct,
334 bytes: payload.bytes.len(),
335 column_bytes,
336 built: false,
337 build: start.elapsed(),
338 });
339 payloads.push((column, payload));
340 }
341 let mut order = (0..payloads.len()).collect::<Vec<_>>();
344 order.sort_by_key(|&at| payloads[at].1.bytes.len());
345 let mut keep = vec![false; payloads.len()];
346 for at in order {
347 if !report[at].distinct {
352 continue;
353 }
354 let cost = payloads[at].1.bytes.len() as u64;
355 if spent.saturating_add(cost) <= allowance {
356 spent += cost;
357 keep[at] = true;
358 report[at].built = true;
359 }
360 }
361 drop(reader);
365 let attachments = payloads
370 .iter()
371 .zip(&keep)
372 .map(|((column, payload), &keep)| {
373 Ok(Attachment {
374 kind: *section::KEY_MAP,
375 id: u64::try_from(*column).map_err(|_| invalid("column index overflow"))?,
376 flags: payload.flags,
377 header_bytes: if keep { payload.header_bytes } else { cost(payload.bytes.len()) },
378 bytes: if keep { &payload.bytes } else { &[] },
379 })
380 })
381 .collect::<Result<Vec<_>>>()?;
382 crate::attach(path, table, &attachments)?;
383 Ok(report)
384}
385
386fn held_bytes(reader: &Reader, replacing: &[usize]) -> Result<u64> {
396 held_bytes_except(reader, *section::KEY_MAP, replacing)
397}
398
399#[must_use]
408pub fn key_map(reader: &Reader, column: usize) -> Option<KeyMap> {
409 let table = reader.table();
410 let id = u64::try_from(column).ok()?;
411 let held = table
412 .sections()
413 .iter()
414 .find(|section| section.kind == *section::KEY_MAP && section.id == id)?;
415 if !held.usable(table.generation()) {
416 return None;
417 }
418 let (map, tag) = wire::decode(&reader.payload(held).ok()?).ok()?;
419 if tag != key_tag(table.fields(), column)? {
424 return None;
425 }
426 Some(map)
427}
428
429#[derive(Debug, Clone)]
435pub struct Edge {
436 pub child: String,
438 pub child_column: usize,
440 pub parent: String,
442 pub parent_column: usize,
444}
445
446#[derive(Debug, Clone)]
448pub struct BuiltLink {
449 pub edge: Edge,
451 pub form: Option<link::Form>,
453 pub children: u64,
455 pub parents: u64,
457 pub linked: u64,
460 pub bytes: usize,
462 pub table_bytes: u64,
465 pub degrees: Option<Degrees>,
471 pub built: bool,
473 pub note: Option<String>,
475 pub build: Duration,
477}
478
479pub fn build_links(path: &Path, edges: &[Edge]) -> Result<Vec<BuiltLink>> {
490 build_links_within(path, edges, BUDGET_SHARE)
491}
492
493pub fn build_links_within(path: &Path, edges: &[Edge], share: u64) -> Result<Vec<BuiltLink>> {
508 let mut tables: Vec<&str> = Vec::new();
509 for edge in edges {
510 if !tables.iter().any(|held| *held == edge.child) {
511 tables.push(&edge.child);
512 }
513 }
514 let mut report = Vec::with_capacity(edges.len());
515 for table in tables {
516 let mine = edges.iter().filter(|edge| edge.child == table).cloned().collect::<Vec<Edge>>();
517 report.extend(links_of_one_table(path, table, &mine, share)?);
518 }
519 Ok(report)
520}
521
522fn links_of_one_table(
524 path: &Path,
525 table: &str,
526 edges: &[Edge],
527 share: u64,
528) -> Result<Vec<BuiltLink>> {
529 let catalog = Catalog::open(path)?;
530 let child = catalog.table(table)?;
531 let column_bytes = child.layout().columns_total();
532 let allowance = (column_bytes.saturating_mul(share) / 100).max(BUDGET_FLOOR);
533 let replacing = edges.iter().map(|edge| edge.child_column).collect::<Vec<usize>>();
534 let mut spent = held_bytes_except(&child, *section::FORWARD_LINK, &replacing)?;
535 let mut report = Vec::with_capacity(edges.len());
536 let mut payloads: Vec<Option<Vec<u8>>> = Vec::with_capacity(edges.len());
537 for edge in edges {
538 let start = Instant::now();
539 match one_link(&catalog, &child, edge) {
540 Ok((built, bytes)) => {
541 report.push(BuiltLink {
542 build: start.elapsed(),
543 table_bytes: column_bytes,
544 ..built
545 });
546 payloads.push(Some(bytes));
547 }
548 Err(note) => {
549 report.push(BuiltLink {
550 edge: edge.clone(),
551 form: None,
552 children: child.table().rows() as u64,
553 parents: 0,
554 linked: 0,
555 bytes: 0,
556 table_bytes: column_bytes,
557 degrees: None,
558 built: false,
559 note: Some(note),
560 build: start.elapsed(),
561 });
562 payloads.push(None);
563 }
564 }
565 }
566 let mut order = (0..report.len()).filter(|at| payloads[*at].is_some()).collect::<Vec<_>>();
567 order.sort_by(|left, right| {
575 let value = |at: &usize| -> f64 {
576 let bytes = report[*at].bytes.max(1);
577 report[*at].children.min(report[*at].parents) as f64 / bytes as f64
578 };
579 value(right).partial_cmp(&value(left)).unwrap_or(std::cmp::Ordering::Equal)
580 });
581 for at in order {
582 let cost = report[at].bytes as u64;
583 if spent.saturating_add(cost) <= allowance {
584 spent += cost;
585 report[at].built = true;
586 } else {
587 report[at].note = Some(format!("over the budget of {allowance} bytes"));
588 }
589 }
590 drop(child);
591 let measured = report
594 .iter()
595 .filter(|built| built.built)
596 .filter_map(|built| {
597 let mut bytes = Vec::with_capacity(rudb_graph::degree::BYTES);
598 built.degrees.as_ref()?.write(&mut bytes);
599 Some((built.edge.child_column, bytes))
600 })
601 .collect::<Vec<_>>();
602 let mut attachments = report
608 .iter()
609 .zip(&payloads)
610 .filter(|(_, payload)| payload.is_some())
611 .map(|(built, payload)| {
612 let bytes = payload.as_ref().expect("filtered to the measured");
613 Ok(Attachment {
614 kind: *section::FORWARD_LINK,
615 id: u64::try_from(built.edge.child_column)
616 .map_err(|_| invalid("column index overflow"))?,
617 flags: built.form.map_or(0, |form| u32::from(form.tag())),
618 header_bytes: if built.built {
619 u32::try_from(binding_bytes(&built.edge.parent))
620 .map_err(|_| invalid("a parent name longer than a section header"))?
621 } else {
622 cost(bytes.len())
623 },
624 bytes: if built.built { bytes } else { &[] },
625 })
626 })
627 .collect::<Result<Vec<_>>>()?;
628 for (column, bytes) in &measured {
633 attachments.push(Attachment {
634 kind: *section::DEGREES,
635 id: u64::try_from(*column).map_err(|_| invalid("column index overflow"))?,
636 flags: 0,
637 header_bytes: 0,
638 bytes,
639 });
640 }
641 crate::attach(path, table, &attachments)?;
642 Ok(report)
643}
644
645fn one_link(
652 catalog: &Catalog,
653 child: &Reader,
654 edge: &Edge,
655) -> std::result::Result<(BuiltLink, Vec<u8>), String> {
656 let parent =
657 catalog.table(&edge.parent).map_err(|_| format!("no table named {}", edge.parent))?;
658 let map = parent_map(&parent, edge)?;
659 if !map.observed().usable_as_parent() {
660 return Err(format!("the key of {} is not unique", edge.parent));
661 }
662 let keys = KeyColumn::new(child, edge.child_column).map_err(|error| error.to_string())?;
663 let mut parents_of = Vec::with_capacity(child.table().rows());
664 let mut failed = None;
665 keys.scan(&mut |key| {
666 let parent = match key {
667 None => NO_PARENT,
668 Some(key) => match map.lookup(key) {
669 Ok(found) => found.unwrap_or(NO_PARENT),
670 Err(error) => {
671 failed = Some(error.to_string());
672 NO_PARENT
673 }
674 },
675 };
676 parents_of.push(parent);
677 Ok(())
678 })
679 .map_err(|error| error.to_string())?;
680 if let Some(failed) = failed {
681 return Err(failed);
682 }
683 let link = link::Link::build(&parents_of, map.len()).map_err(|error| error.to_string())?;
684 let degrees = Degrees::of(&parents_of, map.len(), true);
693 let bytes = encode_link(&link, &parent, edge).map_err(|error| error.to_string())?;
694 Ok((
695 BuiltLink {
696 edge: edge.clone(),
697 form: Some(link.form()),
698 children: link.children(),
699 parents: map.len(),
700 linked: link.linked(),
701 bytes: bytes.len(),
702 table_bytes: 0,
703 degrees: Some(degrees),
704 built: false,
705 note: None,
706 build: Duration::ZERO,
707 },
708 bytes,
709 ))
710}
711
712fn parent_map(parent: &Reader, edge: &Edge) -> std::result::Result<KeyMap, String> {
721 if columns_of(edge.parent_column).len() == 1 {
722 return key_map(parent, edge.parent_column)
723 .ok_or_else(|| format!("no key map is stored for {}", edge.parent));
724 }
725 KeyColumn::new(parent, edge.parent_column)
726 .and_then(|keys| KeyMap::build_from(&keys))
727 .map_err(|error| error.to_string())
728}
729
730fn cost(bytes: usize) -> u32 {
736 u32::try_from(bytes).unwrap_or(u32::MAX)
737}
738
739fn binding_bytes(parent: &str) -> usize {
744 16 + parent.len().div_ceil(8) * 8
745}
746
747fn encode_link(link: &link::Link, parent: &Reader, edge: &Edge) -> Result<Vec<u8>> {
756 let name = edge.parent.as_bytes();
757 let mut bytes = Vec::with_capacity(binding_bytes(&edge.parent) + link.bytes());
758 bytes.extend_from_slice(&parent.table().generation().to_le_bytes());
759 bytes.extend_from_slice(
760 &u32::try_from(edge.parent_column)
761 .map_err(|_| invalid("column index overflow"))?
762 .to_le_bytes(),
763 );
764 bytes.extend_from_slice(
765 &u32::try_from(name.len())
766 .map_err(|_| invalid("a parent name longer than a u32"))?
767 .to_le_bytes(),
768 );
769 bytes.extend_from_slice(name);
770 bytes.resize(binding_bytes(&edge.parent), 0);
771 link.write(&mut bytes)?;
772 Ok(bytes)
773}
774
775#[must_use]
783pub fn stored_link(child: &Reader, parent: &Reader, edge: &Edge) -> Option<link::Link> {
784 let table = child.table();
785 let id = u64::try_from(edge.child_column).ok()?;
786 let held = table
787 .sections()
788 .iter()
789 .find(|section| section.kind == *section::FORWARD_LINK && section.id == id)?;
790 if !held.usable(table.generation()) {
791 return None;
792 }
793 let bytes = child.payload(held).ok()?;
794 let binding = binding_bytes(&edge.parent);
795 if bytes.len() < binding {
796 return None;
797 }
798 let generation = u64::from_le_bytes(bytes[0..8].try_into().ok()?);
799 let column = u32::from_le_bytes(bytes[8..12].try_into().ok()?);
800 let length = u32::from_le_bytes(bytes[12..16].try_into().ok()?) as usize;
801 if generation != parent.table().generation()
802 || column as usize != edge.parent_column
803 || length != edge.parent.len()
804 || &bytes[16..16 + length] != edge.parent.as_bytes()
805 {
806 return None;
807 }
808 link::Link::read(&bytes[binding..]).ok()
809}
810
811#[must_use]
818pub fn stored_degrees(child: &Reader, child_column: usize) -> Option<Degrees> {
819 let table = child.table();
820 let id = u64::try_from(child_column).ok()?;
821 let held = table
822 .sections()
823 .iter()
824 .find(|section| section.kind == *section::DEGREES && section.id == id)?;
825 if !held.usable(table.generation()) {
826 return None;
827 }
828 Degrees::read(&child.payload(held).ok()?).ok()
829}
830
831#[must_use]
838pub fn refused_key_map(reader: &Reader, column: usize) -> Option<(Form, u64)> {
839 let (form, bytes) = refused(reader, *section::KEY_MAP, column)?;
840 Some((Form::from_tag(form).ok()?, bytes))
841}
842
843#[must_use]
847pub fn refused_link(child: &Reader, child_column: usize) -> Option<(link::Form, u64)> {
848 let (form, bytes) = refused(child, *section::FORWARD_LINK, child_column)?;
849 Some((link::Form::from_tag(form).ok()?, bytes))
850}
851
852fn refused(reader: &Reader, kind: [u8; 8], id: usize) -> Option<(u8, u64)> {
854 let table = reader.table();
855 let id = u64::try_from(id).ok()?;
856 let held = table.sections().iter().find(|section| section.kind == kind && section.id == id)?;
857 if !held.usable(table.generation()) {
858 return None;
859 }
860 Some((u8::try_from(held.flags).ok()?, held.refused()?))
861}
862
863fn held_bytes_except(reader: &Reader, kind: [u8; 8], replacing: &[usize]) -> Result<u64> {
865 let mut total = 0;
866 for held in reader.table().sections() {
867 if !held.among(section::GRAPH_KINDS) {
868 continue;
869 }
870 let replaced =
871 held.kind == kind && replacing.iter().any(|&id| u64::try_from(id) == Ok(held.id));
872 if replaced || !held.usable(reader.table().generation()) {
873 continue;
874 }
875 let Ok(extents) = reader.extents(held) else { continue };
876 total += extents.iter().map(|extent| u64::from(extent.length)).sum::<u64>();
877 }
878 Ok(total)
879}
880
881#[cfg(test)]
882mod tests {
883 use std::fs;
884 use std::path::PathBuf;
885 use std::time::{SystemTime, UNIX_EPOCH};
886
887 use rudb_common::Field;
888 use rudb_graph::Rid;
889 use rudb_vector::Vector;
890
891 use super::*;
892 use crate::Writer;
893
894 fn path(label: &str) -> PathBuf {
895 let stamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("time advances").as_nanos();
896 std::env::temp_dir().join(format!("rudb-graph-{label}-{}-{stamp}.rdb", std::process::id()))
897 }
898
899 fn graph_sections(reader: &Reader) -> Vec<§ion::Section> {
905 reader.table().sections().iter().filter(|held| held.among(section::GRAPH_KINDS)).collect()
906 }
907
908 fn table_of(label: &str, keys: &[Option<i64>]) -> PathBuf {
910 let path = path(label);
911 let mut writer =
912 Writer::create(&path, "parent", vec![Field::new("key", LogicalType::BigInt)])
913 .expect("new file");
914 for part in keys.chunks(1000) {
915 let values =
916 part.iter().map(|key| key.map_or(Value::Null, Value::BigInt)).collect::<Vec<_>>();
917 let chunk =
918 Chunk::new(vec![Vector::from_values(LogicalType::BigInt, &values).expect("keys")])
919 .expect("one column");
920 writer.append(&chunk).expect("a part");
921 }
922 writer.finish().expect("commit");
923 path
924 }
925
926 fn resolves(keys: &[Option<i64>], map: &KeyMap) {
928 for (rid, key) in keys.iter().enumerate() {
929 let Some(key) = *key else { continue };
930 let found =
931 map.lookup(i128::from(key)).expect("lookup").expect("a key in the column resolves");
932 assert_eq!(found, rid as Rid, "key {key} resolved to {found} rather than {rid}");
933 }
934 }
935
936 #[test]
937 fn a_key_map_built_over_a_file_resolves_every_key_to_its_own_row() {
938 let keys = (1..=3000_i64).map(Some).collect::<Vec<_>>();
943 let path = table_of("identity", &keys);
944 let built = build_key_maps(&path, "parent", &[0]).expect("build");
945 assert_eq!(built.len(), 1);
946 assert_eq!(built[0].form, Form::Identity);
947 assert_eq!(built[0].rows, 3000);
948 assert!(built[0].distinct);
949 assert_eq!(built[0].bytes, wire::HEADER_BYTES, "identity is a header and nothing else");
950
951 let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
952 let map = key_map(&reader, 0).expect("the map is in the file");
953 assert_eq!(map.form(), Form::Identity);
954 resolves(&keys, &map);
955 assert_eq!(map.lookup(0).expect("a key below the column"), None);
956 assert_eq!(map.lookup(3001).expect("a key past the column"), None);
957
958 fs::remove_file(&path).expect("clean up");
959 }
960
961 #[test]
962 fn a_column_with_gaps_takes_the_bitmap_form_and_still_resolves() {
963 let keys = (0..2000_i64).map(|value| Some(value * 4 + 7)).collect::<Vec<_>>();
964 let path = table_of("dense", &keys);
965 let built = build_key_maps(&path, "parent", &[0]).expect("build");
966 assert_eq!(built[0].form, Form::Dense);
967
968 let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
969 let map = key_map(&reader, 0).expect("the map is in the file");
970 resolves(&keys, &map);
971 assert_eq!(map.lookup(8).expect("a value in the range but not the column"), None);
972
973 fs::remove_file(&path).expect("clean up");
974 }
975
976 #[test]
977 fn a_column_out_of_order_takes_the_sorted_form_and_still_resolves() {
978 let keys = (0..1500_i64).map(|value| Some((value * 7919) % 100_003)).collect::<Vec<_>>();
979 let path = table_of("sorted", &keys);
980 let built = build_key_maps(&path, "parent", &[0]).expect("build");
981 assert_eq!(built[0].form, Form::Sorted);
982 assert!(built[0].distinct, "the sort settles distinctness for an unordered column");
983
984 let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
985 let map = key_map(&reader, 0).expect("the map is in the file");
986 resolves(&keys, &map);
987
988 fs::remove_file(&path).expect("clean up");
989 }
990
991 #[test]
992 fn a_null_in_the_key_column_does_not_shift_the_rows_after_it() {
993 let mut keys = (1..=1200_i64).map(Some).collect::<Vec<_>>();
998 keys[3] = None;
999 keys[900] = None;
1000 let path = table_of("nulls", &keys);
1001 let built = build_key_maps(&path, "parent", &[0]).expect("build");
1002 assert_eq!(built[0].rows, 1198, "a null is not a key");
1003
1004 let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
1005 let map = key_map(&reader, 0).expect("the map is in the file");
1006 resolves(&keys, &map);
1007
1008 fs::remove_file(&path).expect("clean up");
1009 }
1010
1011 #[test]
1012 fn a_column_with_a_repeat_in_it_is_mapped_and_reported_as_no_parent() {
1013 let mut keys = (1..=500_i64).map(Some).collect::<Vec<_>>();
1018 keys[200] = Some(7);
1019 let path = table_of("repeat", &keys);
1020 let built = build_key_maps(&path, "parent", &[0]).expect("build");
1021 assert!(!built[0].distinct, "a repeat is observed rather than declared away");
1022 assert!(!built[0].built, "and a map no rid can be resolved through is not kept");
1023 assert!(built[0].bytes > 0, "what it would have cost is still reported");
1024
1025 let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
1026 assert!(key_map(&reader, 0).is_none(), "no map was written to read back");
1027 let (form, bytes) = refused_key_map(&reader, 0).expect("the record of what it would cost");
1031 assert_eq!(form, built[0].form);
1032 assert_eq!(bytes, built[0].bytes as u64);
1033 assert_eq!(graph_sections(&reader).len(), 1, "one entry, and no payload");
1034 assert_eq!(graph_sections(&reader)[0].extents, 0);
1035
1036 fs::remove_file(&path).expect("clean up");
1037 }
1038
1039 #[test]
1040 fn a_table_with_no_key_map_answers_with_none_rather_than_an_error() {
1041 let path = table_of("absent", &[Some(1), Some(2)]);
1044 let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
1045 assert!(key_map(&reader, 0).is_none());
1046 assert!(key_map(&reader, 99).is_none(), "a column that does not exist is not a panic");
1047 fs::remove_file(&path).expect("clean up");
1048 }
1049
1050 #[test]
1051 fn a_stale_key_map_is_ignored_and_the_table_still_reads() {
1052 let path = table_of("stale", &(1..=100_i64).map(Some).collect::<Vec<_>>());
1053 build_key_maps(&path, "parent", &[0]).expect("build");
1054
1055 let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
1058 assert!(key_map(&reader, 0).is_some());
1059 let generation = reader.table().generation();
1060 drop(reader);
1061
1062 let held = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
1064 let mut entry = *graph_sections(&held).first().copied().expect("the key map");
1065 assert!(entry.usable(generation));
1066 entry.generation = generation + 1;
1067 assert!(!entry.usable(generation), "a rewrite invalidates rather than corrupts");
1068
1069 fs::remove_file(&path).expect("clean up");
1070 }
1071
1072 #[test]
1073 fn a_torn_key_map_costs_the_shortcut_and_not_the_query() {
1074 let keys = (1..=200_i64).map(Some).collect::<Vec<_>>();
1075 let path = table_of("torn", &keys);
1076 build_key_maps(&path, "parent", &[0]).expect("build");
1077
1078 let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
1079 let extent = reader
1080 .extents(graph_sections(&reader).first().copied().expect("the key map"))
1081 .expect("extent table")
1082 .first()
1083 .copied()
1084 .expect("one extent");
1085 drop(reader);
1086 let file = fs::OpenOptions::new().write(true).open(&path).expect("reopen to corrupt");
1087 crate::write_at(&file, extent.offset, &[0xff; 8]).expect("flip the header");
1088 drop(file);
1089
1090 let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
1091 assert!(key_map(&reader, 0).is_none(), "a payload that does not checksum is not a map");
1092 assert_eq!(reader.table().rows(), 200, "and the table is untouched");
1093
1094 fs::remove_file(&path).expect("clean up");
1095 }
1096
1097 #[test]
1098 fn a_column_with_no_integer_key_form_is_refused_by_name() {
1099 let path = path("varchar");
1100 let mut writer =
1101 Writer::create(&path, "parent", vec![Field::new("name", LogicalType::Varchar)])
1102 .expect("new file");
1103 let chunk = Chunk::new(vec![
1104 Vector::from_values(LogicalType::Varchar, &[Value::Varchar("a".into())])
1105 .expect("one name"),
1106 ])
1107 .expect("one column");
1108 writer.append(&chunk).expect("a part");
1109 writer.finish().expect("commit");
1110
1111 let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
1112 let error = KeyColumn::new(&reader, 0).expect_err("a string key needs its codes");
1113 assert!(error.to_string().contains("integer key form"), "{error}");
1114
1115 fs::remove_file(&path).expect("clean up");
1116 }
1117
1118 #[test]
1119 fn several_columns_are_mapped_in_one_commit() {
1120 let path = path("two_columns");
1121 let mut writer = Writer::create(
1122 &path,
1123 "parent",
1124 vec![
1125 Field::required("id", LogicalType::BigInt),
1126 Field::required("code", LogicalType::Integer),
1127 ],
1128 )
1129 .expect("new file");
1130 let ids = (1..=400_i64).map(Value::BigInt).collect::<Vec<_>>();
1131 let codes = (1..=400_i32).map(|code| Value::Integer(code * 3)).collect::<Vec<_>>();
1132 let chunk = Chunk::new(vec![
1133 Vector::from_values(LogicalType::BigInt, &ids).expect("ids"),
1134 Vector::from_values(LogicalType::Integer, &codes).expect("codes"),
1135 ])
1136 .expect("two columns");
1137 writer.append(&chunk).expect("a part");
1138 writer.finish().expect("commit");
1139
1140 let built = build_key_maps(&path, "parent", &[0, 1]).expect("build both");
1141 assert_eq!(built.len(), 2);
1142 assert_eq!(built[0].form, Form::Identity);
1143 assert_eq!(built[1].form, Form::Dense);
1144
1145 let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
1146 assert_eq!(graph_sections(&reader).len(), 2, "one commit and two entries");
1147 assert_eq!(key_map(&reader, 0).expect("the id map").form(), Form::Identity);
1148 assert_eq!(key_map(&reader, 1).expect("the code map").form(), Form::Dense);
1149 assert_eq!(
1150 key_map(&reader, 1).expect("the code map").lookup(9).expect("lookup"),
1151 Some(2),
1152 "the third code is the third row"
1153 );
1154
1155 fs::remove_file(&path).expect("clean up");
1156 }
1157
1158 #[test]
1159 fn the_statistics_sections_do_not_count_against_the_graph_budget() {
1160 let keys = (1..=3000_i64).map(Some).collect::<Vec<_>>();
1166 let path = table_of("apart", &keys);
1167 crate::stats::build_stats(&path, "parent", &[0]).expect("summaries first");
1168
1169 let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
1170 let statistics = reader
1171 .table()
1172 .sections()
1173 .iter()
1174 .filter(|held| held.among(section::STATISTICS_KINDS))
1175 .count();
1176 assert_eq!(statistics, 2, "a summary and a sketch are in the file");
1177 assert_eq!(held_bytes(&reader, &[0]).expect("held"), 0, "and neither is the graph's");
1178
1179 drop(reader);
1180 fs::remove_file(&path).expect("clean up");
1181 }
1182
1183 #[test]
1184 fn a_map_that_does_not_fit_the_budget_is_measured_and_not_written() {
1185 let keys = (0..100_000_i64).map(|value| Some(value * 8)).collect::<Vec<_>>();
1192 let path = table_of("budget", &keys);
1193 let built = build_key_maps(&path, "parent", &[0]).expect("build");
1194 assert_eq!(built[0].form, Form::Dense);
1195 assert!(!built[0].built, "a map ten times its column does not fit a tenth of it");
1196 assert!(built[0].bytes as u64 > built[0].column_bytes, "{built:?}");
1197
1198 let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
1199 assert!(key_map(&reader, 0).is_none(), "and no map was written");
1200 assert_eq!(refused_key_map(&reader, 0), Some((Form::Dense, built[0].bytes as u64)));
1203 assert_eq!(held_bytes(&reader, &[]).expect("held"), 0, "a record costs the budget nothing");
1204 drop(reader);
1205
1206 let built = build_key_maps_within(&path, "parent", &[0], 100_000).expect("build");
1209 assert!(built[0].built);
1210 let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
1211 let map = key_map(&reader, 0).expect("the map is in the file");
1212 resolves(&keys, &map);
1213
1214 fs::remove_file(&path).expect("clean up");
1215 }
1216
1217 #[test]
1218 fn the_budget_admits_the_cheapest_maps_it_can_fit() {
1219 let path = path("budget_order");
1225 let mut writer = Writer::create(
1226 &path,
1227 "parent",
1228 vec![
1229 Field::required("id", LogicalType::BigInt),
1230 Field::required("code", LogicalType::BigInt),
1231 ],
1232 )
1233 .expect("new file");
1234 let ids = (1..=100_000_i64).map(Value::BigInt).collect::<Vec<_>>();
1235 let codes = (1..=100_000_i64)
1236 .map(|code| Value::BigInt((code * 2_147_483_647) % 999_999_937))
1237 .collect::<Vec<_>>();
1238 for part in 0..100 {
1239 let at = part * 1000;
1240 let chunk = Chunk::new(vec![
1241 Vector::from_values(LogicalType::BigInt, &ids[at..at + 1000]).expect("ids"),
1242 Vector::from_values(LogicalType::BigInt, &codes[at..at + 1000]).expect("codes"),
1243 ])
1244 .expect("two columns");
1245 writer.append(&chunk).expect("a part");
1246 }
1247 writer.finish().expect("commit");
1248
1249 let built = build_key_maps(&path, "parent", &[1, 0]).expect("build");
1250 assert_eq!(built[0].column, 1, "the report is in the order it was asked in");
1251 assert_eq!(built[0].form, Form::Sorted);
1252 assert!(!built[0].built, "the sorted map did not fit: {built:?}");
1253 assert!(built[1].built, "the identity map did, and was reached second: {built:?}");
1254
1255 let reader = Catalog::open(&path).expect("reopen").table("parent").expect("the table");
1256 assert!(key_map(&reader, 0).is_some());
1257 assert!(key_map(&reader, 1).is_none());
1258
1259 fs::remove_file(&path).expect("clean up");
1260 }
1261
1262 fn related(label: &str, parents: i64, foreign: &[Option<i64>]) -> PathBuf {
1266 let path = table_of(label, &(1..=parents).map(Some).collect::<Vec<_>>());
1267 let mut writer = Writer::open(&path, "child", vec![Field::new("fk", LogicalType::BigInt)])
1268 .expect("a second table");
1269 for part in foreign.chunks(1000) {
1270 let values =
1271 part.iter().map(|key| key.map_or(Value::Null, Value::BigInt)).collect::<Vec<_>>();
1272 let chunk =
1273 Chunk::new(vec![Vector::from_values(LogicalType::BigInt, &values).expect("keys")])
1274 .expect("one column");
1275 writer.append(&chunk).expect("a part");
1276 }
1277 writer.finish().expect("commit");
1278 build_key_maps(&path, "parent", &[0]).expect("the parent's key map");
1279 path
1280 }
1281
1282 fn edge() -> Edge {
1283 Edge { child: "child".into(), child_column: 0, parent: "parent".into(), parent_column: 0 }
1284 }
1285
1286 fn links(path: &PathBuf, foreign: &[Option<i64>]) -> link::Link {
1289 let catalog = Catalog::open(path).expect("reopen");
1290 let child = catalog.table("child").expect("the child");
1291 let parent = catalog.table("parent").expect("the parent");
1292 let link = stored_link(&child, &parent, &edge()).expect("the link is in the file");
1293 let map = key_map(&parent, 0).expect("the parent's key map");
1294 for (rid, key) in foreign.iter().enumerate() {
1295 let want = key.and_then(|key| map.lookup(i128::from(key)).expect("lookup"));
1296 assert_eq!(link.forward(rid as Rid), want, "child {rid}");
1297 }
1298 link
1299 }
1300
1301 type Pair = (Option<i64>, Option<i64>);
1303
1304 fn pairs_into(mut writer: Writer, rows: &[Pair]) {
1306 let values = |pick: fn(&Pair) -> Option<i64>, part: &[Pair]| {
1307 let values = part
1308 .iter()
1309 .map(|row| pick(row).map_or(Value::Null, Value::BigInt))
1310 .collect::<Vec<_>>();
1311 Vector::from_values(LogicalType::BigInt, &values).expect("keys")
1312 };
1313 for part in rows.chunks(1000) {
1314 let chunk = Chunk::new(vec![values(|row| row.0, part), values(|row| row.1, part)])
1315 .expect("two columns");
1316 writer.append(&chunk).expect("a part");
1317 }
1318 writer.finish().expect("commit");
1319 }
1320
1321 #[test]
1322 fn a_key_over_one_column_is_named_the_way_it_always_was() {
1323 assert_eq!(key_of(&[0]), Some(0));
1326 assert_eq!(key_of(&[17]), Some(17));
1327 assert_eq!(columns_of(17), vec![17]);
1328 let pair = key_of(&[1, 2]).expect("a pair");
1329 assert_ne!(pair, key_of(&[2, 1]).expect("a pair"), "the order is part of the key");
1330 assert_eq!(columns_of(pair), vec![1, 2]);
1331 assert!(pair > u32::MAX as usize / 2, "a pair never reads as a column index");
1332 assert_eq!(key_of(&[]), None);
1333 assert_eq!(key_of(&[0, 1, 2]), None, "nothing is built over three columns");
1334 assert_eq!(key_of(&[1 << 15, 0]), None, "an index too wide to pack is refused");
1335 }
1336
1337 #[test]
1338 fn two_values_fold_into_one_key_without_two_pairs_ever_meeting() {
1339 let values = [i128::from(i32::MIN), -1, 0, 1, i128::from(i32::MAX)];
1340 let mut seen = std::collections::HashSet::new();
1341 for &high in &values {
1342 for &low in &values {
1343 assert!(seen.insert(fold(high, low).expect("fits")), "({high}, {low}) met another");
1344 }
1345 }
1346 let wide = i128::from(i32::MAX) + 1;
1347 assert!(fold(0, wide).is_err(), "a second value past 32 bits");
1348 assert!(fold(wide, 0).is_err(), "a first value past 32 bits");
1349 let span = fold(i128::from(i32::MAX), i128::from(i32::MAX)).expect("fits")
1350 - fold(i128::from(i32::MIN), i128::from(i32::MIN)).expect("fits");
1351 assert!(span <= i128::from(u64::MAX), "a key map's keys span no more than a u64");
1352 }
1353
1354 #[test]
1355 fn a_link_over_a_two_column_key_finds_the_row_holding_both_values() {
1356 let path = path("pair");
1360 let fields =
1361 vec![Field::new("part", LogicalType::BigInt), Field::new("supp", LogicalType::BigInt)];
1362 let parents = (1..=500_i64)
1363 .flat_map(|part| (0..4).map(move |at| (Some(part), Some((part + at * 125) % 1000 + 1))))
1364 .collect::<Vec<_>>();
1365 pairs_into(Writer::create(&path, "parent", fields.clone()).expect("new file"), &parents);
1366 let mut children = (0..3000_i64)
1367 .map(|at| parents[usize::try_from((at * 7) % 2000).expect("small")])
1368 .collect::<Vec<_>>();
1369 children[5] = (Some(3), Some(999)); children[6] = (None, Some(4));
1371 children[7] = (Some(4), None);
1372 pairs_into(Writer::open(&path, "child", fields).expect("a second table"), &children);
1373
1374 let key = pair(0, 1).expect("a pair");
1375 let edge = Edge {
1376 child: "child".into(),
1377 child_column: key,
1378 parent: "parent".into(),
1379 parent_column: key,
1380 };
1381 let report = build_links(&path, std::slice::from_ref(&edge)).expect("build");
1382 assert!(report[0].built, "{:?}", report[0].note);
1383 assert_eq!(report[0].linked, 2997, "three children name no parent");
1384
1385 let catalog = Catalog::open(&path).expect("reopen");
1386 let parent = catalog.table("parent").expect("the parent");
1387 let child = catalog.table("child").expect("the child");
1388 assert!(key_map(&parent, key).is_none(), "a pair's map is built for the link and not kept");
1389 let link = stored_link(&child, &parent, &edge).expect("the link is in the file");
1390 for (rid, row) in children.iter().enumerate() {
1391 let want = parents.iter().position(|held| held == row).map(|at| at as Rid);
1392 assert_eq!(link.forward(rid as Rid), want, "child {rid} is {row:?}");
1393 }
1394 let one = Edge { child_column: 0, parent_column: 0, ..edge };
1395 assert!(stored_link(&child, &parent, &one).is_none(), "half of the key is not the key");
1396
1397 fs::remove_file(&path).expect("clean up");
1398 }
1399
1400 #[test]
1401 fn a_clustered_foreign_key_takes_the_monotone_form_and_answers_both_directions() {
1402 let foreign = (0..4000_i64).map(|child| Some(child / 4 + 1)).collect::<Vec<_>>();
1405 let path = related("monotone", 1000, &foreign);
1406 let report = build_links(&path, &[edge()]).expect("build");
1407 assert_eq!(report.len(), 1);
1408 assert!(report[0].built, "{:?}", report[0].note);
1409 assert_eq!(report[0].form, Some(link::Form::Monotone));
1410 assert_eq!(report[0].children, 4000);
1411 assert_eq!(report[0].linked, 4000);
1412
1413 let link = links(&path, &foreign);
1414 assert_eq!(link.form(), link::Form::Monotone);
1415 assert_eq!(link.backward(0), Some(0..4), "the first parent's four children");
1416 assert_eq!(link.backward(999), Some(3996..4000));
1417 assert_eq!(link.backward(1000), None, "past the last parent");
1418
1419 fs::remove_file(&path).expect("clean up");
1420 }
1421
1422 #[test]
1423 fn an_unclustered_foreign_key_takes_the_packed_form_and_still_resolves() {
1424 let foreign = (0..3000_i64).map(|child| Some((child * 7) % 1000 + 1)).collect::<Vec<_>>();
1425 let path = related("packed", 1000, &foreign);
1426 let report = build_links(&path, &[edge()]).expect("build");
1427 assert!(report[0].built, "{:?}", report[0].note);
1428 assert_eq!(report[0].form, Some(link::Form::Packed));
1429
1430 let link = links(&path, &foreign);
1431 assert_eq!(link.backward(0), None, "the packed form answers one direction");
1432 assert!(link.bytes() < 3000 * 2 + 3 * 16, "{} bytes is not bit-packed", link.bytes());
1436
1437 fs::remove_file(&path).expect("clean up");
1438 }
1439
1440 #[test]
1441 fn a_built_link_leaves_the_shape_of_the_relationship_beside_it() {
1442 let foreign = (0..4000_i64).map(|child| Some(child / 4 + 1)).collect::<Vec<_>>();
1445 let path = related("degrees", 1000, &foreign);
1446 let report = build_links(&path, &[edge()]).expect("build");
1447 assert!(report[0].built, "{:?}", report[0].note);
1448 let measured = report[0].degrees.as_ref().expect("the build measured it");
1449 assert!((measured.mean() - 4.0).abs() < 1e-9);
1450
1451 let catalog = Catalog::open(&path).expect("reopen");
1452 let child = catalog.table("child").expect("the child");
1453 let held = stored_degrees(&child, 0).expect("it is in the file");
1454 assert_eq!(&held, measured, "what the build measured is what the file holds");
1455 assert_eq!(held.parents(), 1000);
1456 assert_eq!(held.highest(), 4);
1457 assert!(held.total(), "every child found a parent");
1458 assert!(held.unique(), "and the parent key is why there is a link at all");
1459 let near = held.locality().expect("something to gather");
1463 assert!((near - 999.0 / 3999.0).abs() < 1e-9, "{near}");
1464 assert!(stored_degrees(&child, 1).is_none(), "and no other column has one");
1465
1466 fs::remove_file(&path).expect("clean up");
1467 }
1468
1469 #[test]
1470 fn a_foreign_key_that_matches_nothing_is_a_child_with_no_parent() {
1471 let foreign = vec![Some(1), Some(2), None, Some(9999), Some(3)];
1474 let path = related("orphans", 10, &foreign);
1475 let report = build_links(&path, &[edge()]).expect("build");
1476 assert!(report[0].built, "{:?}", report[0].note);
1477 assert_eq!(report[0].form, Some(link::Form::Packed));
1478 assert_eq!(report[0].children, 5);
1479 assert_eq!(report[0].linked, 3, "the null and the key that matches nothing are not links");
1480
1481 let link = links(&path, &foreign);
1482 assert_eq!(link.forward(2), None, "a null is not a link");
1483 assert_eq!(link.forward(3), None, "a key that matches nothing is not a link");
1484
1485 fs::remove_file(&path).expect("clean up");
1486 }
1487
1488 #[test]
1489 fn a_parent_with_no_key_map_is_a_relationship_with_no_link_rather_than_an_error() {
1490 let path = table_of("unmapped", &(1..=100_i64).map(Some).collect::<Vec<_>>());
1493 let mut writer = Writer::open(&path, "child", vec![Field::new("fk", LogicalType::BigInt)])
1494 .expect("a second table");
1495 let values = (1..=100_i64).map(Value::BigInt).collect::<Vec<_>>();
1496 writer
1497 .append(
1498 &Chunk::new(vec![Vector::from_values(LogicalType::BigInt, &values).expect("keys")])
1499 .expect("one column"),
1500 )
1501 .expect("a part");
1502 writer.finish().expect("commit");
1503
1504 let report = build_links(&path, &[edge()]).expect("build");
1505 assert!(!report[0].built);
1506 assert_eq!(report[0].note.as_deref(), Some("no key map is stored for parent"));
1507
1508 let catalog = Catalog::open(&path).expect("reopen");
1509 let child = catalog.table("child").expect("the child");
1510 let parent = catalog.table("parent").expect("the parent");
1511 assert!(stored_link(&child, &parent, &edge()).is_none());
1512
1513 fs::remove_file(&path).expect("clean up");
1514 }
1515
1516 #[test]
1517 fn a_link_asked_for_against_the_wrong_parent_is_not_handed_over() {
1518 let foreign = (0..500_i64).map(|child| Some(child / 5 + 1)).collect::<Vec<_>>();
1522 let path = related("binding", 100, &foreign);
1523 build_links(&path, &[edge()]).expect("build");
1524
1525 let catalog = Catalog::open(&path).expect("reopen");
1526 let child = catalog.table("child").expect("the child");
1527 let parent = catalog.table("parent").expect("the parent");
1528 assert!(stored_link(&child, &parent, &edge()).is_some());
1529 let wrong = Edge { parent: "child".into(), ..edge() };
1530 assert!(stored_link(&child, &parent, &wrong).is_none(), "a different parent name");
1531 let wrong = Edge { parent_column: 1, ..edge() };
1532 assert!(stored_link(&child, &parent, &wrong).is_none(), "a different parent column");
1533 let wrong = Edge { child_column: 1, ..edge() };
1534 assert!(stored_link(&child, &parent, &wrong).is_none(), "a different child column");
1535
1536 fs::remove_file(&path).expect("clean up");
1537 }
1538
1539 #[test]
1540 fn a_link_that_does_not_fit_the_budget_is_reported_rather_than_stored() {
1541 let foreign = (0..60_000_i64).map(|child| Some((child * 7) % 1000 + 1)).collect::<Vec<_>>();
1544 let path = related("budget", 1000, &foreign);
1545 let report = build_links_within(&path, &[edge()], 0).expect("build");
1546 assert!(!report[0].built);
1547 assert!(report[0].bytes > 0, "the report says what a larger budget would buy");
1548 assert!(report[0].note.as_deref().unwrap_or_default().contains("budget"), "{report:?}");
1549
1550 let catalog = Catalog::open(&path).expect("reopen");
1551 let child = catalog.table("child").expect("the child");
1552 let parent = catalog.table("parent").expect("the parent");
1553 assert!(stored_link(&child, &parent, &edge()).is_none());
1554 assert!(report[0].degrees.is_some(), "it was measured");
1557 assert!(stored_degrees(&child, 0).is_none(), "and not written");
1558 assert_eq!(refused_link(&child, 0), Some((link::Form::Packed, report[0].bytes as u64)));
1561
1562 fs::remove_file(&path).expect("clean up");
1563 }
1564
1565 #[test]
1566 fn the_budget_keeps_the_link_that_saves_the_larger_hash_table() {
1567 let path = table_of("rank", &(1..=1000).map(Some).collect::<Vec<_>>());
1572 let small = [Field::new("key", LogicalType::BigInt)];
1573 let mut writer = Writer::open(&path, "small", small.to_vec()).expect("a second table");
1574 let keys = (1..=4).map(Value::BigInt).collect::<Vec<_>>();
1575 let chunk =
1576 Chunk::new(vec![Vector::from_values(LogicalType::BigInt, &keys).expect("keys")])
1577 .expect("one column");
1578 writer.append(&chunk).expect("a part");
1579 writer.finish().expect("commit");
1580 let rows = (0..45_000_i64)
1581 .map(|child| (Some((child * 7) % 1000 + 1), Some(child % 4 + 1)))
1582 .collect::<Vec<_>>();
1583 let fields = vec![
1584 Field::new("large", LogicalType::BigInt),
1585 Field::new("small", LogicalType::BigInt),
1586 ];
1587 pairs_into(Writer::open(&path, "child", fields).expect("a third table"), &rows);
1588 build_key_maps(&path, "parent", &[0]).expect("the large key map");
1589 build_key_maps(&path, "small", &[0]).expect("the small key map");
1590
1591 let edges = [
1592 edge(),
1593 Edge {
1594 child: "child".into(),
1595 child_column: 1,
1596 parent: "small".into(),
1597 parent_column: 0,
1598 },
1599 ];
1600 let report = build_links_within(&path, &edges, 0).expect("build");
1601 assert!(report[1].bytes < report[0].bytes, "the small link is the cheaper one");
1602 assert!(
1603 (report[0].bytes + report[1].bytes) as u64 > BUDGET_FLOOR,
1604 "the two have to not fit together for this to test anything"
1605 );
1606 assert_eq!((report[0].parents, report[1].parents), (1000, 4));
1607 assert!(report[0].built, "the link that saves a thousand rows was turned away: {report:?}");
1608 assert!(!report[1].built, "the link that saves four rows was kept instead");
1609
1610 fs::remove_file(&path).expect("clean up");
1611 }
1612
1613 #[test]
1614 fn a_parent_whose_key_repeats_gets_no_link_at_all() {
1615 let path = table_of("repeats", &[Some(1), Some(1), Some(2)]);
1619 let mut writer = Writer::open(&path, "child", vec![Field::new("fk", LogicalType::BigInt)])
1620 .expect("a second table");
1621 let values = [Value::BigInt(1), Value::BigInt(2)];
1622 writer
1623 .append(
1624 &Chunk::new(vec![Vector::from_values(LogicalType::BigInt, &values).expect("keys")])
1625 .expect("one column"),
1626 )
1627 .expect("a part");
1628 writer.finish().expect("commit");
1629 build_key_maps(&path, "parent", &[0]).expect("the parent's key map");
1630
1631 let report = build_links(&path, &[edge()]).expect("build");
1632 assert!(!report[0].built);
1633 assert_eq!(report[0].note.as_deref(), Some("no key map is stored for parent"));
1634
1635 fs::remove_file(&path).expect("clean up");
1636 }
1637}