1mod credential;
31mod distribution;
32mod planner;
33mod relationship;
34mod schema;
35mod semantic;
36
37pub fn is_credential_name(name: &str) -> bool {
42 credential::is_high_confidence_credential(name)
43}
44
45use std::collections::{BTreeMap, BTreeSet};
46use std::fmt;
47
48use serde::Serialize;
49
50use crate::diagnostic::{codes, Diagnostic};
51use crate::generate::registry::ExtensionRegistry;
52use crate::profile::evidence::{ColumnEvidence, DumpProfile, TableEvidence};
53use crate::synthetic::model::{
54 ColumnRule, GeneratorConfig, ModelDefaults, ModelKind, ModifierConfig, OutputModel,
55 PlannerConfig, ProfileInference, ProfileMetadata, RelationshipModel, RelationshipReference,
56 RowsModel, SourceModel, SyntheticModel, TableModel, TableSeed,
57};
58use crate::synthetic::schema::{
59 declared_character_length, PortableColumn, PortableRelationship, PortableSchema, PortableTable,
60 SqlTypeFamily,
61};
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
68pub enum Precedence {
69 TypeFallback,
71 ObservedDistribution,
73 StrongSemantic,
75 Relationship,
77 CredentialGuard,
79 SchemaConstraint,
81 ExplicitYaml,
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
89pub enum Confidence {
90 Low,
91 Medium,
92 High,
93 Certain,
94}
95
96impl Confidence {
97 fn label(self) -> &'static str {
99 match self {
100 Confidence::Low => "low",
101 Confidence::Medium => "medium",
102 Confidence::High => "high",
103 Confidence::Certain => "certain",
104 }
105 }
106}
107
108#[derive(Debug, Clone)]
113pub struct Candidate {
114 precedence: Precedence,
115 confidence: Confidence,
116 reason: &'static str,
118 generator: GeneratorConfig,
119 semantic: Option<String>,
120 source_literals: Vec<String>,
123}
124
125impl Candidate {
126 fn new(
128 precedence: Precedence,
129 confidence: Confidence,
130 reason: &'static str,
131 generator: GeneratorConfig,
132 ) -> Self {
133 Self {
134 precedence,
135 confidence,
136 reason,
137 generator,
138 semantic: None,
139 source_literals: Vec::new(),
140 }
141 }
142
143 fn with_semantic(mut self, semantic: impl Into<String>) -> Self {
145 self.semantic = Some(semantic.into());
146 self
147 }
148
149 fn with_source_literals(mut self, literals: Vec<String>) -> Self {
151 self.source_literals = literals;
152 self
153 }
154
155 fn rank_key(&self) -> (Precedence, Confidence, std::cmp::Reverse<&str>) {
159 (
160 self.precedence,
161 self.confidence,
162 std::cmp::Reverse(self.generator.kind.as_str()),
163 )
164 }
165}
166
167pub(crate) struct ColumnContext<'a> {
173 table: &'a PortableTable,
174 column: &'a PortableColumn,
175 evidence: Option<&'a ColumnEvidence>,
176 row_count: Option<u64>,
177}
178
179impl<'a> ColumnContext<'a> {
180 fn table(&self) -> &'a PortableTable {
181 self.table
182 }
183 fn column(&self) -> &'a PortableColumn {
184 self.column
185 }
186 fn evidence(&self) -> Option<&'a ColumnEvidence> {
187 self.evidence
188 }
189 fn row_count(&self) -> Option<u64> {
190 self.row_count
191 }
192}
193
194#[derive(Debug, Clone)]
199pub struct RejectedCandidate {
200 pub generator_kind: String,
201 pub reason: String,
202 pub precedence: Precedence,
203 pub confidence: Confidence,
204}
205
206#[derive(Debug, Clone)]
209pub struct Decision {
210 pub column: String,
212 pub reason: String,
214 pub confidence: Confidence,
215 pub generator_kind: String,
216 pub source_derived: bool,
218 pub rejected: Vec<RejectedCandidate>,
219}
220
221#[derive(Debug, Clone)]
224pub struct InferenceResult {
225 pub model: SyntheticModel,
226 pub decisions: Vec<Decision>,
227 pub warnings: Vec<Diagnostic>,
228 source_literals: BTreeMap<String, Vec<String>>,
230}
231
232impl InferenceResult {
233 pub fn decision(&self, key: &str) -> Option<&Decision> {
235 self.decisions.iter().find(|d| d.column == key)
236 }
237
238 pub fn column_rule(&self, table: &str, column: &str) -> Option<&ColumnRule> {
240 self.model.tables.get(table)?.columns.get(column)
241 }
242
243 pub fn source_literals(&self, key: &str) -> &[String] {
246 self.source_literals
247 .get(key)
248 .map(Vec::as_slice)
249 .unwrap_or(&[])
250 }
251}
252
253#[derive(Debug, Clone, PartialEq, Eq)]
255pub enum InferenceError {
256 NoTables,
258}
259
260impl fmt::Display for InferenceError {
261 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262 match self {
263 InferenceError::NoTables => {
264 write!(f, "no profiled table matched the provided schema")
265 }
266 }
267 }
268}
269
270impl std::error::Error for InferenceError {}
271
272#[derive(Debug, Clone)]
276pub struct InferenceOptions {
277 include_profiles: bool,
281}
282
283impl Default for InferenceOptions {
284 fn default() -> Self {
285 Self {
286 include_profiles: true,
287 }
288 }
289}
290
291impl InferenceOptions {
292 pub fn include_profiles(mut self, include: bool) -> Self {
295 self.include_profiles = include;
296 self
297 }
298}
299
300pub struct ModelInference {
306 registry: ExtensionRegistry,
307 options: InferenceOptions,
308}
309
310impl ModelInference {
311 pub fn standard() -> Self {
314 Self {
315 registry: ExtensionRegistry::standard(),
316 options: InferenceOptions::default(),
317 }
318 }
319
320 pub fn new(registry: ExtensionRegistry, options: InferenceOptions) -> Self {
322 Self { registry, options }
323 }
324
325 pub fn infer(
331 &self,
332 schema: &PortableSchema,
333 profile: &DumpProfile,
334 ) -> Result<InferenceResult, InferenceError> {
335 let mut tables = BTreeMap::new();
336 let mut decisions = Vec::new();
337 let mut warnings = Vec::new();
338 let mut profiles = BTreeMap::new();
339 let mut source_literals = BTreeMap::new();
340
341 let referenced: BTreeSet<(String, String)> = schema
345 .tables
346 .values()
347 .flat_map(|table| {
348 table.relationships.iter().flat_map(|fk| {
349 let referenced_table = canonical_table_name(schema, &fk.referenced_table)
350 .unwrap_or(&fk.referenced_table)
351 .to_string();
352 fk.referenced_columns
353 .iter()
354 .map(move |column| (referenced_table.clone(), column.clone()))
355 })
356 })
357 .collect();
358
359 for table_evidence in &profile.tables {
360 let Some(portable) = schema.tables.get(&table_evidence.table) else {
361 warnings.push(Diagnostic::warning(
362 &codes::INFER_TABLE_UNKNOWN,
363 format!("tables.{}", table_evidence.table),
364 format!(
365 "profiled table `{}` is not in the schema; skipped",
366 table_evidence.table
367 ),
368 ));
369 continue;
370 };
371 let portable = detach_missing_schema_relationships(schema, portable, &mut warnings);
372 let table_model = self.infer_table(
373 &portable,
374 Some(table_evidence),
375 &referenced,
376 &mut decisions,
377 &mut warnings,
378 &mut profiles,
379 &mut source_literals,
380 );
381 tables.insert(portable.name.clone(), table_model);
382 }
383
384 for (name, portable) in &schema.tables {
387 if tables.contains_key(name) {
388 continue;
389 }
390 let portable = detach_missing_schema_relationships(schema, portable, &mut warnings);
391 let table_model = self.infer_table(
392 &portable,
393 None,
394 &referenced,
395 &mut decisions,
396 &mut warnings,
397 &mut profiles,
398 &mut source_literals,
399 );
400 tables.insert(name.clone(), table_model);
401 }
402
403 if tables.is_empty() {
404 return Err(InferenceError::NoTables);
405 }
406
407 let model = SyntheticModel {
408 schema_ref: None,
409 version: 1,
410 kind: ModelKind::Model,
411 imports: Vec::new(),
412 source: Some(SourceModel {
413 dialect: schema.dialect.clone(),
414 fingerprint: None,
415 fingerprint_policy: None,
416 }),
417 defaults: ModelDefaults::default(), seed: None,
419 output: OutputModel::default(),
420 tables,
421 profiles: if self.options.include_profiles {
422 profiles
423 } else {
424 BTreeMap::new()
425 },
426 };
427
428 Ok(InferenceResult {
429 model,
430 decisions,
431 warnings,
432 source_literals,
433 })
434 }
435
436 #[allow(clippy::too_many_arguments)]
437 fn infer_table(
438 &self,
439 portable: &PortableTable,
440 evidence: Option<&TableEvidence>,
441 referenced: &BTreeSet<(String, String)>,
442 decisions: &mut Vec<Decision>,
443 warnings: &mut Vec<Diagnostic>,
444 profiles: &mut BTreeMap<String, ProfileMetadata>,
445 source_literals: &mut BTreeMap<String, Vec<String>>,
446 ) -> TableModel {
447 let row_count = evidence.and_then(|e| e.row_count);
448 let mut columns = BTreeMap::new();
449
450 for column in &portable.columns {
451 let key = format!("{}.{}", portable.name, column.name);
452
453 if relationship::is_foreign_key_column(portable, &column.name) {
457 decisions.push(Decision {
458 column: key,
459 reason: "relationship_declared_fk".to_string(),
460 confidence: Confidence::High,
461 generator_kind: "relation.foreign_key".to_string(),
462 source_derived: false,
463 rejected: Vec::new(),
464 });
465 continue;
466 }
467
468 if column.primary_key
473 && matches!(column.family, SqlTypeFamily::Text | SqlTypeFamily::Other)
474 && referenced.contains(&(portable.name.clone(), column.name.clone()))
475 && text_column_fits_uuid(&column.source_type)
480 {
481 decisions.push(Decision {
482 column: key,
483 reason: "referenced_text_key".to_string(),
484 confidence: Confidence::High,
485 generator_kind: "uuid".to_string(),
486 source_derived: false,
487 rejected: Vec::new(),
488 });
489 columns.insert(
490 column.name.clone(),
491 ColumnRule {
492 semantic: None,
493 generator: Some(GeneratorConfig {
494 kind: "uuid".to_string(),
495 args: BTreeMap::new(),
496 }),
497 modifiers: Vec::new(),
498 },
499 );
500 continue;
501 }
502
503 let column_evidence = evidence.and_then(|e| find_column_evidence(e, &column.name));
504 let ctx = ColumnContext {
505 table: portable,
506 column,
507 evidence: column_evidence,
508 row_count,
509 };
510
511 let mut candidates = Vec::new();
512 candidates.extend(schema::candidates(&ctx));
513 candidates.extend(credential::candidates(&ctx));
514 candidates.extend(semantic::candidates(&ctx));
515 candidates.extend(distribution::candidates(&ctx));
516
517 candidates
520 .retain(|candidate| self.registry.generator(&candidate.generator.kind).is_some());
521
522 let (rule, decision, literals) = resolve_column(&ctx, &key, candidates);
523
524 let (rule, decision, literals) = if is_single_column_unique(portable, column)
531 && rule
532 .generator
533 .as_ref()
534 .is_some_and(|g| is_bounded_generator(&g.kind))
535 {
536 match high_cardinality_generator(column) {
537 Some(generator) => (
538 ColumnRule {
539 semantic: None,
540 generator: Some(GeneratorConfig {
541 kind: generator.0.clone(),
542 args: generator.1,
543 }),
544 modifiers: Vec::new(),
545 },
546 Decision {
547 column: key.clone(),
548 reason: "unique_high_cardinality".to_string(),
549 confidence: Confidence::High,
550 generator_kind: generator.0,
551 source_derived: false,
552 rejected: Vec::new(),
553 },
554 Vec::new(),
555 ),
556 None => (rule, decision, literals),
557 }
558 } else {
559 (rule, decision, literals)
560 };
561
562 if !literals.is_empty() {
563 warnings.push(Diagnostic::warning(
564 &codes::INFER_SOURCE_DERIVED,
565 key.clone(),
566 format!(
567 "persists {} source-derived literal value(s) required by its `{}` rule",
568 literals.len(),
569 decision.generator_kind
570 ),
571 ));
572 source_literals.insert(key.clone(), literals);
573 }
574
575 if self.options.include_profiles {
576 if let Some(meta) = profile_metadata(&ctx, &decision) {
577 profiles.insert(key.clone(), meta);
578 }
579 }
580
581 decisions.push(decision);
582 columns.insert(column.name.clone(), rule);
583 }
584
585 warnings.extend(planner::nominations(portable, evidence));
590
591 let planners = inferred_planners(portable);
595 if planners.is_empty() {
596 if let Some(column) = distinctness_sequence_column(portable) {
597 columns.insert(
598 column,
599 ColumnRule {
600 semantic: None,
601 generator: Some(GeneratorConfig {
602 kind: "sequence".to_string(),
603 args: [("start".to_string(), yaml(1))].into_iter().collect(),
604 }),
605 modifiers: Vec::new(),
606 },
607 );
608 }
609 }
610
611 TableModel {
612 seed: TableSeed::Inherit,
613 rows: match row_count {
614 Some(count) => RowsModel::Observed { count },
615 None => RowsModel::Fixed { count: 0 },
616 },
617 schema: portable.clone(),
618 columns,
619 relationships: declared_relationships(portable),
620 planners,
621 }
622 }
623}
624
625fn detach_missing_schema_relationships(
630 schema: &PortableSchema,
631 table: &PortableTable,
632 warnings: &mut Vec<Diagnostic>,
633) -> PortableTable {
634 let mut portable = table.clone();
635 let mut detached = false;
636 portable.relationships = table
637 .relationships
638 .iter()
639 .filter_map(|relationship| {
640 if let Some(canonical) =
644 canonical_table_name(schema, &relationship.referenced_table)
645 {
646 let mut relationship = relationship.clone();
647 relationship.referenced_table = canonical.to_string();
648 return Some(relationship);
649 }
650 detached = true;
651 warnings.push(Diagnostic::warning(
652 &codes::DETACHED_DEPENDENCY,
653 format!("tables.{}.relationships", table.name),
654 format!(
655 "source relationship `{}` on table `{}` references table `{}`, which is absent from the dump; its foreign key is detached and omitted from the rendered DDL",
656 relationship.name.as_deref().unwrap_or("(unnamed)"),
657 table.name,
658 relationship.referenced_table
659 ),
660 ));
661 None
662 })
663 .collect();
664 if detached {
665 portable.create_statement = None;
666 }
667 portable
668}
669
670fn canonical_table_name<'a>(schema: &'a PortableSchema, name: &str) -> Option<&'a str> {
671 schema
672 .tables
673 .get_key_value(name)
674 .map(|(canonical, _)| canonical.as_str())
675 .or_else(|| {
676 schema
677 .tables
678 .keys()
679 .find(|candidate| candidate.eq_ignore_ascii_case(name))
680 .map(String::as_str)
681 })
682}
683
684fn resolve_column(
687 ctx: &ColumnContext<'_>,
688 key: &str,
689 mut candidates: Vec<Candidate>,
690) -> (ColumnRule, Decision, Vec<String>) {
691 if candidates.is_empty() {
693 candidates.push(schema::type_fallback(ctx));
694 }
695
696 let winner_index = candidates
698 .iter()
699 .enumerate()
700 .max_by(|(_, a), (_, b)| a.rank_key().cmp(&b.rank_key()))
701 .map(|(index, _)| index)
702 .expect("candidates is non-empty");
703
704 let winner = candidates.swap_remove(winner_index);
705
706 let rejected = candidates
707 .iter()
708 .map(|candidate| RejectedCandidate {
709 generator_kind: candidate.generator.kind.clone(),
710 reason: candidate.reason.to_string(),
711 precedence: candidate.precedence,
712 confidence: candidate.confidence,
713 })
714 .collect();
715
716 let mut modifiers = Vec::new();
717 if let Some(modifier) = character_limit_modifier(ctx, &winner) {
718 modifiers.push(modifier);
719 }
720 if let Some(modifier) = sparse_modifier(ctx, &winner) {
721 modifiers.push(modifier);
722 }
723
724 let decision = Decision {
725 column: key.to_string(),
726 reason: winner.reason.to_string(),
727 confidence: winner.confidence,
728 generator_kind: winner.generator.kind.clone(),
729 source_derived: !winner.source_literals.is_empty(),
730 rejected,
731 };
732
733 let rule = ColumnRule {
734 semantic: winner.semantic.clone(),
735 generator: Some(winner.generator.clone()),
736 modifiers,
737 };
738
739 (rule, decision, winner.source_literals)
740}
741
742fn character_limit_modifier(ctx: &ColumnContext<'_>, winner: &Candidate) -> Option<ModifierConfig> {
750 if ctx.column().family != SqlTypeFamily::Text {
751 return None;
752 }
753 if matches!(
754 winner.generator.kind.as_str(),
755 "string" | "constant" | "weighted_choice" | "observed_sample" | "database_default" | "null"
756 ) {
757 return None;
758 }
759 let max_length = declared_character_length(&ctx.column().source_type)?;
760 Some(ModifierConfig {
761 kind: "truncate".to_string(),
762 args: [("max_length".to_string(), yaml(max_length))]
763 .into_iter()
764 .collect(),
765 })
766}
767
768pub fn schema_inferred_generator(
775 table: &PortableTable,
776 column: &PortableColumn,
777) -> GeneratorConfig {
778 let ctx = ColumnContext {
779 table,
780 column,
781 evidence: None,
782 row_count: None,
783 };
784 let mut candidates = Vec::new();
785 candidates.extend(schema::candidates(&ctx));
786 candidates.extend(credential::candidates(&ctx));
787 candidates.extend(semantic::candidates(&ctx));
788 let (rule, _decision, _literals) = resolve_column(&ctx, &column.name, candidates);
789 rule.generator
790 .expect("resolve_column always assigns a generator")
791}
792
793fn sparse_modifier(ctx: &ColumnContext<'_>, winner: &Candidate) -> Option<ModifierConfig> {
796 if !ctx.column().nullable {
797 return None;
798 }
799 if matches!(winner.generator.kind.as_str(), "null" | "database_default") {
800 return None;
801 }
802 let rate = ctx.evidence()?.null_rate;
803 if !(0.005..=0.995).contains(&rate) {
804 return None;
805 }
806 let mut args = BTreeMap::new();
807 args.insert("rate".to_string(), yaml(round4(rate)));
808 Some(ModifierConfig {
809 kind: "null_rate".to_string(),
810 args,
811 })
812}
813
814fn profile_metadata(ctx: &ColumnContext<'_>, decision: &Decision) -> Option<ProfileMetadata> {
816 let evidence = ctx.evidence()?;
817 Some(ProfileMetadata {
818 rows: ctx.row_count().unwrap_or(evidence.total_count),
819 null_fraction: round4(evidence.null_rate),
820 distinct_estimate: evidence.distinct_estimate.round() as u64,
821 inference: Some(ProfileInference {
822 selected: decision.generator_kind.clone(),
823 confidence: decision.confidence.label().to_string(),
824 reasons: vec![decision.reason.clone()],
825 }),
826 })
827}
828
829fn is_bounded_generator(kind: &str) -> bool {
834 matches!(
835 kind,
836 "observed_sample"
837 | "choice"
838 | "weighted_choice"
839 | "histogram"
840 | "normal"
841 | "integer"
842 | "decimal"
843 | "boolean"
844 | "constant"
845 | "null"
846 | "database_default"
847 )
848}
849
850fn text_column_fits_uuid(source_type: &str) -> bool {
853 const UUID_LEN: usize = 36;
854 declared_character_length(source_type).is_none_or(|n| n >= UUID_LEN)
855}
856
857fn high_cardinality_generator(
861 column: &PortableColumn,
862) -> Option<(String, BTreeMap<String, serde_yaml_ng::Value>)> {
863 match column.family {
864 SqlTypeFamily::Integer | SqlTypeFamily::BigInteger => Some((
865 "sequence".to_string(),
866 [("start".to_string(), yaml(1))].into_iter().collect(),
867 )),
868 SqlTypeFamily::Text | SqlTypeFamily::Other | SqlTypeFamily::Uuid => {
869 if text_column_fits_uuid(&column.source_type) {
873 Some(("uuid".to_string(), BTreeMap::new()))
874 } else {
875 None
876 }
877 }
878 _ => None,
879 }
880}
881
882fn is_single_column_unique(table: &PortableTable, column: &PortableColumn) -> bool {
887 if column.unique {
888 return true;
889 }
890 let single = |columns: &[String]| columns.len() == 1 && columns[0] == column.name;
891 table
892 .unique_constraints
893 .iter()
894 .any(|constraint| single(&constraint.columns))
895 || table
896 .indexes
897 .iter()
898 .any(|index| index.unique && single(&index.columns))
899}
900
901fn single_column_fk<'a>(
904 table: &'a PortableTable,
905 column: &str,
906) -> Option<&'a PortableRelationship> {
907 table
908 .relationships
909 .iter()
910 .find(|fk| fk.columns.len() == 1 && fk.columns[0] == column)
911}
912
913fn inferred_planners(table: &PortableTable) -> Vec<PlannerConfig> {
924 let pk = &table.primary_key;
925 if pk.len() < 2 {
926 return Vec::new();
927 }
928 let fk_columns: Vec<(&String, &PortableRelationship)> = pk
930 .iter()
931 .filter_map(|column| single_column_fk(table, column).map(|fk| (column, fk)))
932 .collect();
933 if fk_columns.len() < 2 {
934 return Vec::new();
935 }
936 let (left_col, left) = fk_columns[0];
937 let (right_col, right) = fk_columns[1];
938 let (Some(left_name), Some(right_name)) = (left.name.clone(), right.name.clone()) else {
939 return Vec::new();
940 };
941
942 let mut columns = serde_yaml_ng::Mapping::new();
943 columns.insert(yaml("left"), yaml(left_col));
944 columns.insert(yaml("right"), yaml(right_col));
945 let mut args = BTreeMap::new();
946 args.insert(
947 "columns".to_string(),
948 serde_yaml_ng::Value::Mapping(columns),
949 );
950 args.insert("left_relationship".to_string(), yaml(left_name));
951 args.insert("right_relationship".to_string(), yaml(right_name));
952
953 vec![PlannerConfig {
954 kind: "relation.junction_pair".to_string(),
955 args,
956 }]
957}
958
959fn distinctness_sequence_column(table: &PortableTable) -> Option<String> {
967 if table.primary_key.len() < 2 {
968 return None;
969 }
970 table.primary_key.iter().find_map(|column| {
971 let is_integer = table.columns.iter().any(|c| {
972 &c.name == column
973 && matches!(c.family, SqlTypeFamily::Integer | SqlTypeFamily::BigInteger)
974 });
975 (is_integer && single_column_fk(table, column).is_none()).then(|| column.clone())
976 })
977}
978
979fn declared_relationships(table: &PortableTable) -> Vec<RelationshipModel> {
980 table
981 .relationships
982 .iter()
983 .map(|fk| RelationshipModel {
984 name: fk.name.clone(),
985 columns: fk.columns.clone(),
986 references: RelationshipReference {
987 table: fk.referenced_table.clone(),
988 columns: fk.referenced_columns.clone(),
989 },
990 distribution: None,
991 })
992 .collect()
993}
994
995fn find_column_evidence<'a>(table: &'a TableEvidence, name: &str) -> Option<&'a ColumnEvidence> {
996 table.columns.iter().find(|c| c.name == name)
997}
998
999pub(crate) fn yaml<T: Serialize>(value: T) -> serde_yaml_ng::Value {
1003 serde_yaml_ng::to_value(value).unwrap_or(serde_yaml_ng::Value::Null)
1004}
1005
1006pub(crate) fn generator(kind: &str) -> GeneratorConfig {
1008 GeneratorConfig {
1009 kind: kind.to_string(),
1010 args: BTreeMap::new(),
1011 }
1012}
1013
1014pub(crate) fn generator_with(
1016 kind: &str,
1017 args: impl IntoIterator<Item = (&'static str, serde_yaml_ng::Value)>,
1018) -> GeneratorConfig {
1019 GeneratorConfig {
1020 kind: kind.to_string(),
1021 args: args.into_iter().map(|(k, v)| (k.to_string(), v)).collect(),
1022 }
1023}
1024
1025pub(crate) fn weighted_entries(entries: &[(String, u64)]) -> serde_yaml_ng::Value {
1027 let seq = entries
1028 .iter()
1029 .map(|(value, weight)| {
1030 let mut map = serde_yaml_ng::Mapping::new();
1031 map.insert(yaml("value"), yaml(value));
1032 map.insert(yaml("weight"), yaml(*weight));
1033 serde_yaml_ng::Value::Mapping(map)
1034 })
1035 .collect();
1036 serde_yaml_ng::Value::Sequence(seq)
1037}
1038
1039fn round4(value: f64) -> f64 {
1041 (value * 10_000.0).round() / 10_000.0
1042}
1043
1044#[cfg(test)]
1045mod uuid_length_tests {
1046 use super::*;
1047
1048 fn text_col(source_type: &str) -> PortableColumn {
1049 PortableColumn {
1050 name: "code".to_string(),
1051 source_type: source_type.to_string(),
1052 family: SqlTypeFamily::Text,
1053 nullable: false,
1054 primary_key: false,
1055 unique: true,
1056 default_sql: None,
1057 generated: false,
1058 identity: false,
1059 collation: None,
1060 }
1061 }
1062
1063 #[test]
1064 fn short_text_unique_not_forced_to_uuid() {
1065 assert!(
1068 high_cardinality_generator(&text_col("varchar(8)")).is_none(),
1069 "uuid forced into a column too short to hold it"
1070 );
1071 }
1072
1073 #[test]
1074 fn long_and_unbounded_text_unique_get_uuid() {
1075 assert_eq!(
1076 high_cardinality_generator(&text_col("varchar(64)")).map(|(k, _)| k),
1077 Some("uuid".to_string())
1078 );
1079 assert_eq!(
1081 high_cardinality_generator(&text_col("text")).map(|(k, _)| k),
1082 Some("uuid".to_string())
1083 );
1084 }
1085}