1use std::collections::{BTreeMap, BTreeSet};
36use std::sync::{Arc, LazyLock};
37
38use anyhow::bail;
39use futures::FutureExt;
40use futures::future::BoxFuture;
41use mz_build_info::{BuildInfo, DUMMY_BUILD_INFO};
42use mz_catalog::builtin::{
43 BUILTIN_LOOKUP, Builtin, Fingerprint, MZ_CATALOG_RAW, MZ_CATALOG_RAW_DESCRIPTION,
44 MZ_CLUSTER_REPLICA_FRONTIERS_DESCRIPTION, MZ_COMPUTE_HYDRATION_TIMES_DESCRIPTION,
45 MZ_OBJECT_ARRANGEMENT_SIZE_HISTORY_DESCRIPTION, MZ_OBJECT_HYDRATION_HISTORY,
46 MZ_OBJECT_HYDRATION_HISTORY_DESCRIPTION, MZ_REPLICA_HYDRATION_HISTORY,
47 MZ_REPLICA_HYDRATION_HISTORY_DESCRIPTION, MZ_STORAGE_USAGE_BY_SHARD,
48 MZ_STORAGE_USAGE_BY_SHARD_DESCRIPTION, RUNTIME_ALTERABLE_FINGERPRINT_SENTINEL,
49};
50use mz_catalog::config::BuiltinItemMigrationConfig;
51use mz_catalog::durable::objects::SystemObjectUniqueIdentifier;
52use mz_catalog::durable::{SystemObjectDescription, SystemObjectMapping, Transaction};
53use mz_catalog::memory::error::{Error, ErrorKind};
54use mz_ore::soft_assert_or_log;
55use mz_persist_client::cfg::USE_CRITICAL_SINCE_CATALOG;
56use mz_persist_client::critical::{Opaque, SinceHandle};
57use mz_persist_client::read::ReadHandle;
58use mz_persist_client::schema::CaESchema;
59use mz_persist_client::write::WriteHandle;
60use mz_persist_client::{Diagnostics, PersistClient};
61use mz_persist_types::ShardId;
62use mz_persist_types::codec_impls::{ShardIdSchema, UnitSchema};
63use mz_persist_types::schema::backward_compatible;
64use mz_repr::namespaces::{MZ_CATALOG_SCHEMA, MZ_INTERNAL_SCHEMA};
65use mz_repr::{CatalogItemId, GlobalId, Timestamp};
66use mz_sql::catalog::{CatalogItemType, NameReference};
67use mz_storage_client::controller::StorageTxn;
68use mz_storage_types::StorageDiff;
69use mz_storage_types::sources::SourceData;
70use semver::Version;
71use timely::progress::Antichain;
72use tracing::{debug, info};
73
74use crate::catalog::migrate::get_migration_version;
75
76static MIGRATIONS: LazyLock<Vec<MigrationStep>> = LazyLock::new(|| {
92 vec![
93 MigrationStep::replacement(
94 "0.149.0",
95 CatalogItemType::Source,
96 MZ_INTERNAL_SCHEMA,
97 "mz_sink_statistics_raw",
98 ),
99 MigrationStep::replacement(
100 "0.149.0",
101 CatalogItemType::Source,
102 MZ_INTERNAL_SCHEMA,
103 "mz_source_statistics_raw",
104 ),
105 MigrationStep::evolution(
106 "0.159.0",
107 CatalogItemType::Source,
108 MZ_INTERNAL_SCHEMA,
109 "mz_cluster_replica_metrics_history",
110 ),
111 MigrationStep::replacement(
112 "26.18.0-dev.0",
113 CatalogItemType::MaterializedView,
114 MZ_CATALOG_SCHEMA,
115 "mz_databases",
116 ),
117 MigrationStep::replacement(
118 "26.19.0-dev.0",
119 CatalogItemType::MaterializedView,
120 MZ_CATALOG_SCHEMA,
121 "mz_schemas",
122 ),
123 MigrationStep::replacement(
124 "26.19.0-dev.0",
125 CatalogItemType::MaterializedView,
126 MZ_CATALOG_SCHEMA,
127 "mz_role_members",
128 ),
129 MigrationStep::replacement(
130 "26.19.0-dev.0",
131 CatalogItemType::MaterializedView,
132 MZ_INTERNAL_SCHEMA,
133 "mz_network_policies",
134 ),
135 MigrationStep::replacement(
136 "26.19.0-dev.0",
137 CatalogItemType::MaterializedView,
138 MZ_INTERNAL_SCHEMA,
139 "mz_network_policy_rules",
140 ),
141 MigrationStep::replacement(
142 "26.19.0-dev.0",
143 CatalogItemType::MaterializedView,
144 MZ_INTERNAL_SCHEMA,
145 "mz_cluster_workload_classes",
146 ),
147 MigrationStep::replacement(
148 "26.19.0-dev.0",
149 CatalogItemType::MaterializedView,
150 MZ_INTERNAL_SCHEMA,
151 "mz_internal_cluster_replicas",
152 ),
153 MigrationStep::replacement(
154 "26.19.0-dev.0",
155 CatalogItemType::MaterializedView,
156 MZ_INTERNAL_SCHEMA,
157 "mz_pending_cluster_replicas",
158 ),
159 MigrationStep::replacement(
160 "26.20.0-dev.0",
161 CatalogItemType::MaterializedView,
162 MZ_CATALOG_SCHEMA,
163 "mz_materialized_views",
164 ),
165 MigrationStep::replacement(
166 "26.22.0-dev.0",
167 CatalogItemType::MaterializedView,
168 MZ_CATALOG_SCHEMA,
169 "mz_connections",
170 ),
171 MigrationStep::replacement(
172 "26.22.0-dev.0",
173 CatalogItemType::MaterializedView,
174 MZ_CATALOG_SCHEMA,
175 "mz_secrets",
176 ),
177 MigrationStep::replacement(
178 "26.27.0-dev.0",
179 CatalogItemType::MaterializedView,
180 MZ_CATALOG_SCHEMA,
181 "mz_sources",
182 ),
183 MigrationStep::replacement(
184 "26.29.0-dev.0",
185 CatalogItemType::MaterializedView,
186 MZ_CATALOG_SCHEMA,
187 "mz_indexes",
188 ),
189 MigrationStep::replacement(
190 "26.29.0-dev.0",
191 CatalogItemType::MaterializedView,
192 MZ_CATALOG_SCHEMA,
193 "mz_roles",
194 ),
195 MigrationStep::replacement(
196 "26.29.0-dev.0",
197 CatalogItemType::MaterializedView,
198 MZ_CATALOG_SCHEMA,
199 "mz_role_parameters",
200 ),
201 MigrationStep::replacement(
206 "26.30.0-dev.0",
207 CatalogItemType::MaterializedView,
208 MZ_CATALOG_SCHEMA,
209 "mz_indexes",
210 ),
211 MigrationStep::replacement(
212 "26.30.0-dev.0",
213 CatalogItemType::MaterializedView,
214 MZ_CATALOG_SCHEMA,
215 "mz_clusters",
216 ),
217 MigrationStep::replacement(
218 "26.30.0-dev.0",
219 CatalogItemType::MaterializedView,
220 MZ_CATALOG_SCHEMA,
221 "mz_cluster_replicas",
222 ),
223 MigrationStep::replacement(
224 "26.30.0-dev.0",
225 CatalogItemType::MaterializedView,
226 MZ_INTERNAL_SCHEMA,
227 "mz_cluster_schedules",
228 ),
229 MigrationStep::replacement(
230 "26.30.0-dev.0",
231 CatalogItemType::MaterializedView,
232 MZ_CATALOG_SCHEMA,
233 "mz_default_privileges",
234 ),
235 MigrationStep::replacement(
236 "26.30.0-dev.0",
237 CatalogItemType::MaterializedView,
238 MZ_CATALOG_SCHEMA,
239 "mz_system_privileges",
240 ),
241 MigrationStep::replacement(
245 "26.31.0-dev.0",
246 CatalogItemType::MaterializedView,
247 MZ_CATALOG_SCHEMA,
248 "mz_cluster_replicas",
249 ),
250 MigrationStep::replacement(
251 "26.32.0-dev.0",
252 CatalogItemType::MaterializedView,
253 MZ_INTERNAL_SCHEMA,
254 "mz_comments",
255 ),
256 MigrationStep::replacement(
261 "26.32.0-dev.0",
262 CatalogItemType::MaterializedView,
263 MZ_CATALOG_SCHEMA,
264 "mz_indexes",
265 ),
266 MigrationStep::replacement(
267 "26.33.0-dev.0",
268 CatalogItemType::MaterializedView,
269 MZ_CATALOG_SCHEMA,
270 "mz_audit_events",
271 ),
272 MigrationStep::replacement(
284 "26.34.0-dev.0",
285 CatalogItemType::MaterializedView,
286 MZ_CATALOG_SCHEMA,
287 "mz_indexes",
288 ),
289 MigrationStep::replacement(
294 "26.34.0-dev.0",
295 CatalogItemType::MaterializedView,
296 MZ_INTERNAL_SCHEMA,
297 "mz_postgres_sources",
298 ),
299 MigrationStep::replacement(
300 "26.34.0-dev.0",
301 CatalogItemType::MaterializedView,
302 MZ_CATALOG_SCHEMA,
303 "mz_kafka_sources",
304 ),
305 MigrationStep::replacement(
309 "26.37.0-dev.0",
310 CatalogItemType::MaterializedView,
311 MZ_INTERNAL_SCHEMA,
312 "mz_postgres_source_tables",
313 ),
314 MigrationStep::replacement(
315 "26.37.0-dev.0",
316 CatalogItemType::MaterializedView,
317 MZ_INTERNAL_SCHEMA,
318 "mz_mysql_source_tables",
319 ),
320 MigrationStep::replacement(
321 "26.37.0-dev.0",
322 CatalogItemType::MaterializedView,
323 MZ_INTERNAL_SCHEMA,
324 "mz_sql_server_source_tables",
325 ),
326 MigrationStep::replacement(
327 "26.37.0-dev.0",
328 CatalogItemType::MaterializedView,
329 MZ_INTERNAL_SCHEMA,
330 "mz_kafka_source_tables",
331 ),
332 MigrationStep::replacement(
336 "26.40.0-dev.0",
337 CatalogItemType::Table,
338 MZ_INTERNAL_SCHEMA,
339 "mz_type_pg_metadata",
340 ),
341 MigrationStep::replacement(
345 "26.47.0-dev.0",
346 CatalogItemType::Table,
347 MZ_INTERNAL_SCHEMA,
348 "mz_type_pg_metadata",
349 ),
350 MigrationStep::replacement(
354 "26.37.0-dev.0",
355 CatalogItemType::MaterializedView,
356 MZ_CATALOG_SCHEMA,
357 "mz_kafka_connections",
358 ),
359 MigrationStep::replacement(
360 "26.37.0-dev.0",
361 CatalogItemType::MaterializedView,
362 MZ_CATALOG_SCHEMA,
363 "mz_ssh_tunnel_connections",
364 ),
365 MigrationStep::replacement(
366 "26.37.0-dev.0",
367 CatalogItemType::MaterializedView,
368 MZ_INTERNAL_SCHEMA,
369 "mz_aws_connections",
370 ),
371 MigrationStep::replacement(
372 "26.37.0-dev.0",
373 CatalogItemType::MaterializedView,
374 MZ_CATALOG_SCHEMA,
375 "mz_aws_privatelink_connections",
376 ),
377 MigrationStep::replacement(
383 "26.38.0-dev.0",
384 CatalogItemType::MaterializedView,
385 MZ_CATALOG_SCHEMA,
386 "mz_sinks",
387 ),
388 MigrationStep::replacement(
389 "26.38.0-dev.0",
390 CatalogItemType::MaterializedView,
391 MZ_CATALOG_SCHEMA,
392 "mz_kafka_sinks",
393 ),
394 MigrationStep::replacement(
395 "26.38.0-dev.0",
396 CatalogItemType::MaterializedView,
397 MZ_CATALOG_SCHEMA,
398 "mz_iceberg_sinks",
399 ),
400 MigrationStep::replacement(
403 "26.38.0-rc.2",
404 CatalogItemType::MaterializedView,
405 MZ_INTERNAL_SCHEMA,
406 "mz_cluster_reconfigurations",
407 ),
408 MigrationStep::replacement(
413 "26.39.0-dev.0",
414 CatalogItemType::MaterializedView,
415 MZ_CATALOG_SCHEMA,
416 "mz_audit_events",
417 ),
418 MigrationStep::replacement(
428 "26.40.0-dev.0",
429 CatalogItemType::MaterializedView,
430 MZ_CATALOG_SCHEMA,
431 "mz_indexes",
432 ),
433 MigrationStep::replacement(
439 "26.39.0-dev.0",
440 CatalogItemType::MaterializedView,
441 MZ_CATALOG_SCHEMA,
442 "mz_tables",
443 ),
444 MigrationStep::replacement(
445 "26.39.0-dev.0",
446 CatalogItemType::MaterializedView,
447 MZ_CATALOG_SCHEMA,
448 "mz_views",
449 ),
450 MigrationStep::replacement(
456 "26.40.0-dev.0",
457 CatalogItemType::MaterializedView,
458 MZ_CATALOG_SCHEMA,
459 "mz_indexes",
460 ),
461 MigrationStep::replacement(
462 "26.40.0-dev.0",
463 CatalogItemType::MaterializedView,
464 MZ_CATALOG_SCHEMA,
465 "mz_sources",
466 ),
467 MigrationStep::replacement(
473 "26.41.0-dev.0",
474 CatalogItemType::MaterializedView,
475 MZ_INTERNAL_SCHEMA,
476 "mz_object_dependencies",
477 ),
478 MigrationStep::evolution(
483 "26.43.0-dev.0",
484 CatalogItemType::Source,
485 MZ_INTERNAL_SCHEMA,
486 "mz_cluster_replica_metrics_history",
487 ),
488 MigrationStep::evolution(
489 "26.43.0-dev.0",
490 CatalogItemType::Table,
491 MZ_INTERNAL_SCHEMA,
492 "mz_replica_hydration_history",
493 ),
494 MigrationStep::replacement(
498 "26.44.0-dev.0",
499 CatalogItemType::MaterializedView,
500 MZ_INTERNAL_SCHEMA,
501 "mz_object_global_ids",
502 ),
503 MigrationStep::replacement(
507 "26.45.0-dev.0",
508 CatalogItemType::MaterializedView,
509 MZ_INTERNAL_SCHEMA,
510 "mz_source_references",
511 ),
512 MigrationStep::replacement(
516 "26.46.0-dev.0",
517 CatalogItemType::MaterializedView,
518 MZ_INTERNAL_SCHEMA,
519 "mz_replacements",
520 ),
521 MigrationStep::replacement(
525 "26.47.0-dev.0",
526 CatalogItemType::MaterializedView,
527 MZ_CATALOG_SCHEMA,
528 "mz_indexes",
529 ),
530 MigrationStep::replacement(
534 "26.47.0-dev.0",
535 CatalogItemType::MaterializedView,
536 MZ_CATALOG_SCHEMA,
537 "mz_sources",
538 ),
539 MigrationStep::replacement(
543 "26.47.0-dev.0",
544 CatalogItemType::MaterializedView,
545 MZ_INTERNAL_SCHEMA,
546 "mz_history_retention_strategies",
547 ),
548 MigrationStep::replacement(
554 "26.47.0-dev.0",
555 CatalogItemType::MaterializedView,
556 MZ_INTERNAL_SCHEMA,
557 "mz_materialized_view_refresh_strategies",
558 ),
559 MigrationStep::replacement(
563 "26.49.0-dev.0",
564 CatalogItemType::MaterializedView,
565 MZ_CATALOG_SCHEMA,
566 "mz_columns",
567 ),
568 MigrationStep::replacement(
572 "26.49.0-dev.0",
573 CatalogItemType::MaterializedView,
574 MZ_CATALOG_SCHEMA,
575 "mz_index_columns",
576 ),
577 MigrationStep::replacement(
580 "26.51.0-dev.0",
581 CatalogItemType::Table,
582 MZ_CATALOG_SCHEMA,
583 "mz_cluster_replica_sizes",
584 ),
585 MigrationStep::replacement(
589 "26.52.0-dev.0",
590 CatalogItemType::MaterializedView,
591 MZ_CATALOG_SCHEMA,
592 "mz_audit_events",
593 ),
594 MigrationStep::replacement(
595 "26.52.0-dev.0",
596 CatalogItemType::MaterializedView,
597 MZ_CATALOG_SCHEMA,
598 "mz_default_privileges",
599 ),
600 MigrationStep::replacement(
601 "26.52.0-dev.0",
602 CatalogItemType::MaterializedView,
603 MZ_INTERNAL_SCHEMA,
604 "mz_comments",
605 ),
606 ]
607});
608
609#[derive(Clone, Debug)]
611struct MigrationStep {
612 version: Version,
614 object: SystemObjectDescription,
616 mechanism: Mechanism,
618}
619
620impl MigrationStep {
621 fn evolution(version: &str, type_: CatalogItemType, schema: &str, name: &str) -> Self {
623 Self {
624 version: Version::parse(version).expect("valid"),
625 object: SystemObjectDescription {
626 schema_name: schema.into(),
627 object_type: type_,
628 object_name: name.into(),
629 },
630 mechanism: Mechanism::Evolution,
631 }
632 }
633
634 fn replacement(version: &str, type_: CatalogItemType, schema: &str, name: &str) -> Self {
636 Self {
637 version: Version::parse(version).expect("valid"),
638 object: SystemObjectDescription {
639 schema_name: schema.into(),
640 object_type: type_,
641 object_name: name.into(),
642 },
643 mechanism: Mechanism::Replacement,
644 }
645 }
646}
647
648#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
650#[allow(dead_code)]
651enum Mechanism {
652 Evolution,
657 Replacement,
661}
662
663pub(super) struct MigrationResult {
665 pub replaced_items: BTreeSet<CatalogItemId>,
668 pub cleanup_action: BoxFuture<'static, ()>,
670}
671
672impl Default for MigrationResult {
673 fn default() -> Self {
674 Self {
675 replaced_items: Default::default(),
676 cleanup_action: async {}.boxed(),
677 }
678 }
679}
680
681pub(super) async fn run(
687 build_info: &BuildInfo,
688 deploy_generation: u64,
689 txn: &mut Transaction<'_>,
690 config: BuiltinItemMigrationConfig,
691) -> Result<MigrationResult, Error> {
692 assert_eq!(config.read_only, txn.is_savepoint());
694
695 if *build_info == DUMMY_BUILD_INFO {
698 return Ok(MigrationResult::default());
699 }
700
701 let Some(durable_version) = get_migration_version(txn) else {
702 return Ok(MigrationResult::default());
704 };
705 let build_version = build_info.semver_version();
706
707 let collection_metadata = txn.get_collection_metadata();
708 let system_objects = txn
709 .get_system_object_mappings()
710 .map(|m| {
711 let object = m.description;
712 let global_id = m.unique_identifier.global_id;
713 let shard_id = collection_metadata.get(&global_id).copied();
714 let Some((_, builtin)) = BUILTIN_LOOKUP.get(&object) else {
715 panic!("missing builtin {object:?}");
716 };
717 let info = ObjectInfo {
718 global_id,
719 shard_id,
720 builtin,
721 fingerprint: m.unique_identifier.fingerprint,
722 };
723 (object, info)
724 })
725 .collect();
726
727 let migration_shard = txn.get_builtin_migration_shard().expect("must exist");
728
729 let migration = Migration {
730 source_version: durable_version.clone(),
731 target_version: build_version.clone(),
732 deploy_generation,
733 system_objects,
734 migration_shard,
735 config,
736 };
737
738 let result = migration.run(&MIGRATIONS).await.map_err(|e| {
739 Error::new(ErrorKind::FailedBuiltinSchemaMigration {
740 last_seen_version: durable_version.to_string(),
741 this_version: build_version.to_string(),
742 cause: e.to_string(),
743 })
744 })?;
745
746 result.apply(txn);
747
748 let replaced_items = txn
749 .get_system_object_mappings()
750 .map(|m| m.unique_identifier)
751 .filter(|ids| result.new_shards.contains_key(&ids.global_id))
752 .map(|ids| ids.catalog_id)
753 .collect();
754
755 Ok(MigrationResult {
756 replaced_items,
757 cleanup_action: result.cleanup_action,
758 })
759}
760
761struct MigrationRunResult {
763 new_shards: BTreeMap<GlobalId, ShardId>,
764 new_fingerprints: BTreeMap<SystemObjectDescription, String>,
765 shards_to_finalize: BTreeSet<ShardId>,
766 cleanup_action: BoxFuture<'static, ()>,
767}
768
769impl Default for MigrationRunResult {
770 fn default() -> Self {
771 Self {
772 new_shards: BTreeMap::new(),
773 new_fingerprints: BTreeMap::new(),
774 shards_to_finalize: BTreeSet::new(),
775 cleanup_action: async {}.boxed(),
776 }
777 }
778}
779
780impl MigrationRunResult {
781 fn apply(&self, txn: &mut Transaction<'_>) {
783 let replaced_ids = self.new_shards.keys().copied().collect();
785 let old_metadata = txn.delete_collection_metadata(replaced_ids);
786 txn.insert_collection_metadata(self.new_shards.clone())
787 .expect("inserting unique shards IDs after deleting existing entries");
788
789 let mut unfinalized_shards: BTreeSet<_> =
791 old_metadata.into_iter().map(|(_, sid)| sid).collect();
792 unfinalized_shards.extend(self.shards_to_finalize.iter().copied());
793 txn.insert_unfinalized_shards(unfinalized_shards)
794 .expect("cannot fail");
795
796 let mappings = txn
798 .get_system_object_mappings()
799 .filter_map(|m| {
800 let fingerprint = self.new_fingerprints.get(&m.description)?;
801 Some(SystemObjectMapping {
802 description: m.description,
803 unique_identifier: SystemObjectUniqueIdentifier {
804 catalog_id: m.unique_identifier.catalog_id,
805 global_id: m.unique_identifier.global_id,
806 fingerprint: fingerprint.clone(),
807 },
808 })
809 })
810 .collect();
811 txn.set_system_object_mappings(mappings)
812 .expect("filtered existing mappings remain unique");
813 }
814}
815
816#[derive(Clone, Debug)]
818struct ObjectInfo {
819 global_id: GlobalId,
820 shard_id: Option<ShardId>,
821 builtin: &'static Builtin<NameReference>,
822 fingerprint: String,
823}
824
825struct Migration {
827 source_version: Version,
832 target_version: Version,
836 deploy_generation: u64,
838 system_objects: BTreeMap<SystemObjectDescription, ObjectInfo>,
840 migration_shard: ShardId,
842 config: BuiltinItemMigrationConfig,
844}
845
846fn has_own_shard(builtin: &Builtin<NameReference>) -> bool {
848 use Builtin::*;
849 match builtin {
850 Table(..) | MaterializedView(..) => true,
851 Source(source) => **source != *MZ_CATALOG_RAW,
854 Log(..) | View(..) | Type(..) | Func(..) | Index(..) | Connection(..) => false,
855 }
856}
857
858fn participates_in_forced_migration(
860 builtin: &Builtin<NameReference>,
861 mechanism: Mechanism,
862) -> bool {
863 use Builtin::*;
864 match builtin {
865 Table(table) => {
877 **table != *MZ_STORAGE_USAGE_BY_SHARD
878 && (mechanism != Mechanism::Replacement
879 || (**table != *MZ_OBJECT_HYDRATION_HISTORY
880 && **table != *MZ_REPLICA_HYDRATION_HISTORY))
881 }
882 _ => has_own_shard(builtin),
883 }
884}
885
886impl Migration {
887 async fn run(self, steps: &[MigrationStep]) -> anyhow::Result<MigrationRunResult> {
888 info!(
889 deploy_generation = %self.deploy_generation,
890 "running builtin schema migration: {} -> {}",
891 self.source_version, self.target_version
892 );
893
894 self.validate_migration_steps(steps);
895
896 let force_migration = if self.source_version != self.target_version
899 && self.source_version.pre.as_str().starts_with("dev")
900 && self.config.force_migration.is_none()
901 {
902 Some("evolution".to_string())
903 } else {
904 self.config.force_migration.clone()
905 };
906
907 let (force, plan) = match force_migration.as_deref() {
908 None => (false, self.plan_migration(steps)),
909 Some("evolution") => (true, self.plan_forced_migration(Mechanism::Evolution)),
910 Some("replacement") => (true, self.plan_forced_migration(Mechanism::Replacement)),
911 Some(other) => panic!("unknown force migration mechanism: {other}"),
912 };
913 let plan = self.drop_shardless(plan);
914
915 if self.source_version == self.target_version && !force {
916 info!("skipping migration: already at target version");
917 return Ok(MigrationRunResult::default());
918 } else if self.source_version > self.target_version {
919 bail!("downgrade not supported");
920 }
921
922 if !self.config.read_only {
925 self.upgrade_migration_shard_version().await;
926 }
927
928 let allocate = self.plan_allocation();
929
930 info!(?allocate, "executing migration plan: {plan:?}");
931
932 self.migrate_evolve(&plan.evolve).await?;
933 let new_shards = self
934 .get_or_insert_shards(&[plan.replace.as_slice(), &allocate].concat())
935 .await?;
936
937 let mut migrated_objects = BTreeSet::new();
938 migrated_objects.extend(plan.evolve);
939 migrated_objects.extend(plan.replace);
940
941 let new_fingerprints = self.update_fingerprints(&migrated_objects)?;
942
943 let (shards_to_finalize, cleanup_action) = self.cleanup().await?;
944
945 Ok(MigrationRunResult {
946 new_shards,
947 new_fingerprints,
948 shards_to_finalize,
949 cleanup_action,
950 })
951 }
952
953 fn validate_migration_steps(&self, steps: &[MigrationStep]) {
957 for step in steps {
958 assert!(
959 step.version <= self.target_version,
960 "migration step version greater than target version: {} > {}",
961 step.version,
962 self.target_version,
963 );
964
965 let object = &step.object;
966
967 assert_ne!(
975 &*MZ_STORAGE_USAGE_BY_SHARD_DESCRIPTION, object,
976 "mz_storage_usage_by_shard cannot be migrated or else the table will be truncated"
977 );
978
979 assert_ne!(
983 &*MZ_OBJECT_ARRANGEMENT_SIZE_HISTORY_DESCRIPTION, object,
984 "mz_object_arrangement_size_history cannot be migrated or else the table will be truncated"
985 );
986
987 if step.mechanism == Mechanism::Replacement {
998 assert_ne!(
999 &*MZ_OBJECT_HYDRATION_HISTORY_DESCRIPTION, object,
1000 "replacing mz_object_hydration_history clears it, see the comment above"
1001 );
1002 assert_ne!(
1003 &*MZ_REPLICA_HYDRATION_HISTORY_DESCRIPTION, object,
1004 "replacing mz_replica_hydration_history clears it, see the comment above"
1005 );
1006 }
1007
1008 assert_ne!(
1011 &*MZ_CATALOG_RAW_DESCRIPTION, object,
1012 "mz_catalog_raw cannot be migrated"
1013 );
1014
1015 assert_ne!(
1020 &*MZ_CLUSTER_REPLICA_FRONTIERS_DESCRIPTION, object,
1021 "mz_cluster_replica_frontiers cannot be migrated or else the 0dt caught-up gate loses its live-frontier reference"
1022 );
1023 assert_ne!(
1024 &*MZ_COMPUTE_HYDRATION_TIMES_DESCRIPTION, object,
1025 "mz_compute_hydration_times cannot be migrated or else the 0dt caught-up gate loses its leader-hydration reference"
1026 );
1027
1028 let Some(object_info) = self.system_objects.get(object) else {
1029 panic!("migration step for non-existent builtin: {object:?}");
1030 };
1031
1032 let builtin = object_info.builtin;
1033 assert!(
1034 has_own_shard(builtin),
1035 "schema migration not supported for builtin: {builtin:?}",
1036 );
1037 }
1038 }
1039
1040 fn plan_migration(&self, steps: &[MigrationStep]) -> Plan {
1042 let steps = steps.iter().filter(|s| s.version > self.source_version);
1044
1045 let mut by_object = BTreeMap::new();
1049 for step in steps {
1050 if let Some(entry) = by_object.get_mut(&step.object) {
1051 *entry = match (step.mechanism, *entry) {
1052 (Mechanism::Evolution, Mechanism::Evolution) => Mechanism::Evolution,
1053 (Mechanism::Replacement, _) | (_, Mechanism::Replacement) => {
1054 Mechanism::Replacement
1055 }
1056 };
1057 } else {
1058 by_object.insert(step.object.clone(), step.mechanism);
1059 }
1060 }
1061
1062 let mut plan = Plan::default();
1063 for (object, mechanism) in by_object {
1064 match mechanism {
1065 Mechanism::Evolution => plan.evolve.push(object),
1066 Mechanism::Replacement => plan.replace.push(object),
1067 }
1068 }
1069
1070 plan
1071 }
1072
1073 fn plan_forced_migration(&self, mechanism: Mechanism) -> Plan {
1075 let objects = self
1076 .system_objects
1077 .iter()
1078 .filter(|(_, info)| participates_in_forced_migration(info.builtin, mechanism))
1079 .map(|(object, _)| object.clone())
1080 .collect();
1081
1082 let mut plan = Plan::default();
1083 match mechanism {
1084 Mechanism::Evolution => plan.evolve = objects,
1085 Mechanism::Replacement => plan.replace = objects,
1086 }
1087
1088 plan
1089 }
1090
1091 fn drop_shardless(&self, mut plan: Plan) -> Plan {
1101 let has_shard = |object: &SystemObjectDescription| {
1102 self.system_objects
1103 .get(object)
1104 .is_none_or(|info| info.shard_id.is_some())
1105 };
1106 plan.evolve.retain(has_shard);
1107 plan.replace.retain(has_shard);
1108 plan
1109 }
1110
1111 fn plan_allocation(&self) -> Vec<SystemObjectDescription> {
1120 self.system_objects
1121 .iter()
1122 .filter(|(_, info)| info.shard_id.is_none() && has_own_shard(info.builtin))
1123 .map(|(object, _)| object.clone())
1124 .collect()
1125 }
1126
1127 async fn upgrade_migration_shard_version(&self) {
1129 let persist = &self.config.persist_client;
1130 let diagnostics = Diagnostics {
1131 shard_name: "builtin_migration".to_string(),
1132 handle_purpose: format!("migration shard upgrade @ {}", self.target_version),
1133 };
1134
1135 persist
1136 .upgrade_version::<migration_shard::Key, ShardId, Timestamp, StorageDiff>(
1137 self.migration_shard,
1138 diagnostics,
1139 )
1140 .await
1141 .expect("valid usage");
1142 }
1143
1144 async fn migrate_evolve(&self, objects: &[SystemObjectDescription]) -> anyhow::Result<()> {
1146 for object in objects {
1147 self.migrate_evolve_one(object).await?;
1148 }
1149 Ok(())
1150 }
1151
1152 async fn migrate_evolve_one(&self, object: &SystemObjectDescription) -> anyhow::Result<()> {
1153 let persist = &self.config.persist_client;
1154
1155 let Some(object_info) = self.system_objects.get(object) else {
1156 bail!("missing builtin {object:?}");
1157 };
1158 let id = object_info.global_id;
1159
1160 let Some(shard_id) = object_info.shard_id else {
1161 if self.config.read_only {
1169 bail!("missing shard ID for builtin {object:?} ({id})");
1170 } else {
1171 return Ok(());
1172 }
1173 };
1174
1175 let target_desc = match object_info.builtin {
1176 Builtin::Table(table) => &table.desc,
1177 Builtin::Source(source) => &source.desc,
1178 Builtin::MaterializedView(mv) => &mv.desc,
1179 _ => bail!("not a storage collection: {object:?}"),
1180 };
1181
1182 let diagnostics = Diagnostics {
1183 shard_name: id.to_string(),
1184 handle_purpose: format!("builtin schema migration @ {}", self.target_version),
1185 };
1186 let source_schema = persist
1187 .latest_schema::<SourceData, (), Timestamp, StorageDiff>(shard_id, diagnostics.clone())
1188 .await
1189 .expect("valid usage");
1190
1191 info!(?object, %id, %shard_id, ?source_schema, ?target_desc, "migrating by evolution");
1192
1193 if self.config.read_only {
1194 if let Some((_, source_desc, _)) = &source_schema {
1197 let old = mz_persist_types::columnar::data_type::<SourceData>(source_desc)?;
1198 let new = mz_persist_types::columnar::data_type::<SourceData>(target_desc)?;
1199 if backward_compatible(&old, &new).is_none() {
1200 bail!(
1201 "incompatible schema evolution for {object:?}: \
1202 {source_desc:?} -> {target_desc:?}"
1203 );
1204 }
1205 }
1206
1207 return Ok(());
1208 }
1209
1210 let (mut schema_id, mut source_desc) = match source_schema {
1211 Some((schema_id, source_desc, _)) => (schema_id, source_desc),
1212 None => {
1213 debug!(%id, %shard_id, "no previous schema found; registering initial one");
1218 let schema_id = persist
1219 .register_schema::<SourceData, (), Timestamp, StorageDiff>(
1220 shard_id,
1221 target_desc,
1222 &UnitSchema,
1223 diagnostics.clone(),
1224 )
1225 .await
1226 .expect("valid usage");
1227 if schema_id.is_some() {
1228 return Ok(());
1229 }
1230
1231 debug!(%id, %shard_id, "schema registration failed; falling back to CaES");
1232 let (schema_id, source_desc, _) = persist
1233 .latest_schema::<SourceData, (), Timestamp, StorageDiff>(
1234 shard_id,
1235 diagnostics.clone(),
1236 )
1237 .await
1238 .expect("valid usage")
1239 .expect("known to exist");
1240
1241 (schema_id, source_desc)
1242 }
1243 };
1244
1245 loop {
1246 debug!(%id, %shard_id, %schema_id, ?source_desc, ?target_desc, "attempting CaES");
1251 let result = persist
1252 .compare_and_evolve_schema::<SourceData, (), Timestamp, StorageDiff>(
1253 shard_id,
1254 schema_id,
1255 target_desc,
1256 &UnitSchema,
1257 diagnostics.clone(),
1258 )
1259 .await
1260 .expect("valid usage");
1261
1262 match result {
1263 CaESchema::Ok(schema_id) => {
1264 debug!(%id, %shard_id, %schema_id, "schema evolved successfully");
1265 break;
1266 }
1267 CaESchema::Incompatible => bail!(
1268 "incompatible schema evolution for {object:?}: \
1269 {source_desc:?} -> {target_desc:?}"
1270 ),
1271 CaESchema::ExpectedMismatch {
1272 schema_id: new_id,
1273 key,
1274 val: UnitSchema,
1275 } => {
1276 schema_id = new_id;
1277 source_desc = key;
1278 }
1279 }
1280 }
1281
1282 Ok(())
1283 }
1284
1285 async fn get_or_insert_shards(
1288 &self,
1289 objects: &[SystemObjectDescription],
1290 ) -> anyhow::Result<BTreeMap<GlobalId, ShardId>> {
1291 if objects.is_empty() {
1292 return Ok(Default::default());
1293 }
1294
1295 let mut wanted = BTreeSet::new();
1296 for object in objects {
1297 let Some(info) = self.system_objects.get(object) else {
1298 bail!("missing id for builtin {object:?}");
1299 };
1300 let entry_object = info.shard_id.is_none().then(|| object.into());
1305 wanted.insert((info.global_id, entry_object));
1306 }
1307
1308 let diagnostics = Diagnostics {
1309 shard_name: "builtin_migration".to_string(),
1310 handle_purpose: format!("builtin schema migration @ {}", self.target_version),
1311 };
1312 let (mut persist_write, mut persist_read) =
1313 self.open_migration_shard(diagnostics.clone()).await;
1314
1315 info!(
1316 ?objects,
1317 ?wanted,
1318 "allocating shards from the migration shard"
1319 );
1320
1321 let replaced_shards = loop {
1324 if let Some(shards) = self
1325 .try_get_or_insert_shards(&wanted, &mut persist_write, &mut persist_read)
1326 .await?
1327 {
1328 break shards;
1329 }
1330 };
1331
1332 Ok(replaced_shards)
1333 }
1334
1335 async fn try_get_or_insert_shards(
1346 &self,
1347 wanted: &BTreeSet<(GlobalId, Option<migration_shard::ObjectKey>)>,
1348 persist_write: &mut WriteHandle<migration_shard::Key, ShardId, Timestamp, StorageDiff>,
1349 persist_read: &mut ReadHandle<migration_shard::Key, ShardId, Timestamp, StorageDiff>,
1350 ) -> anyhow::Result<Option<BTreeMap<GlobalId, ShardId>>> {
1351 let upper = persist_write.fetch_recent_upper().await;
1352 let write_ts = *upper.as_option().expect("migration shard not sealed");
1353
1354 let mut todo = wanted.clone();
1355 let mut replaced_shards = BTreeMap::new();
1356
1357 if let Some(read_ts) = write_ts.step_back() {
1365 let pred = |key: &migration_shard::Key| {
1366 key.build_version == self.target_version
1367 && key.deploy_generation == Some(self.deploy_generation)
1368 };
1369 if let Some(entries) = read_migration_shard(persist_read, read_ts, pred).await {
1370 for (key, shard_id) in entries {
1371 let id = GlobalId::System(key.global_id);
1372 if todo.remove(&(id, key.object)) {
1373 replaced_shards.insert(id, shard_id);
1374 }
1375 }
1376
1377 debug!(
1378 %read_ts, ?replaced_shards, ?todo,
1379 "found existing entries in migration shard",
1380 );
1381 }
1382
1383 if todo.is_empty() {
1384 return Ok(Some(replaced_shards));
1385 }
1386 }
1387
1388 let mut updates = Vec::new();
1392 for (id, object) in todo {
1393 let shard_id = ShardId::new();
1394 replaced_shards.insert(id, shard_id);
1395
1396 let GlobalId::System(global_id) = id else {
1397 bail!("attempt to migrate a non-system collection: {id}");
1398 };
1399 let key = migration_shard::Key {
1400 global_id,
1401 build_version: self.target_version.clone(),
1402 deploy_generation: Some(self.deploy_generation),
1403 object,
1404 };
1405 updates.push(((key, shard_id), write_ts, 1));
1406 }
1407
1408 let upper = Antichain::from_elem(write_ts);
1409 let new_upper = Antichain::from_elem(write_ts.step_forward());
1410 debug!(%write_ts, "attempting insert into migration shard");
1411 let result = persist_write
1412 .compare_and_append(updates, upper, new_upper)
1413 .await
1414 .expect("valid usage");
1415
1416 match result {
1417 Ok(()) => {
1418 debug!(
1419 %write_ts, ?replaced_shards,
1420 "successfully inserted into migration shard"
1421 );
1422 Ok(Some(replaced_shards))
1423 }
1424 Err(_mismatch) => Ok(None),
1425 }
1426 }
1427
1428 async fn open_migration_shard(
1430 &self,
1431 diagnostics: Diagnostics,
1432 ) -> (
1433 WriteHandle<migration_shard::Key, ShardId, Timestamp, StorageDiff>,
1434 ReadHandle<migration_shard::Key, ShardId, Timestamp, StorageDiff>,
1435 ) {
1436 let persist = &self.config.persist_client;
1437
1438 persist
1439 .open(
1440 self.migration_shard,
1441 Arc::new(migration_shard::KeySchema),
1442 Arc::new(ShardIdSchema),
1443 diagnostics,
1444 USE_CRITICAL_SINCE_CATALOG.get(persist.dyncfgs()),
1445 )
1446 .await
1447 .expect("valid usage")
1448 }
1449
1450 async fn open_migration_shard_since(
1452 &self,
1453 diagnostics: Diagnostics,
1454 ) -> SinceHandle<migration_shard::Key, ShardId, Timestamp, StorageDiff> {
1455 self.config
1456 .persist_client
1457 .open_critical_since(
1458 self.migration_shard,
1459 PersistClient::CONTROLLER_CRITICAL_SINCE,
1462 Opaque::encode(&i64::MIN),
1463 diagnostics.clone(),
1464 )
1465 .await
1466 .expect("valid usage")
1467 }
1468
1469 fn update_fingerprints(
1474 &self,
1475 migrated_items: &BTreeSet<SystemObjectDescription>,
1476 ) -> anyhow::Result<BTreeMap<SystemObjectDescription, String>> {
1477 let mut new_fingerprints = BTreeMap::new();
1478 for (object, object_info) in &self.system_objects {
1479 let id = object_info.global_id;
1480 let builtin = object_info.builtin;
1481
1482 let fingerprint = builtin.fingerprint();
1483 if fingerprint == object_info.fingerprint {
1484 continue; }
1486
1487 let migrated = migrated_items.contains(object);
1489 let ephemeral = matches!(
1491 builtin,
1492 Builtin::Log(_) | Builtin::View(_) | Builtin::Index(_),
1493 );
1494
1495 if migrated || ephemeral {
1496 new_fingerprints.insert(object.clone(), fingerprint);
1497 } else if builtin.runtime_alterable() {
1498 assert_eq!(
1501 object_info.fingerprint, RUNTIME_ALTERABLE_FINGERPRINT_SENTINEL,
1502 "fingerprint mismatch for runtime-alterable builtin {object:?} ({id})",
1503 );
1504 } else {
1505 panic!(
1506 "fingerprint mismatch for builtin {builtin:?} ({id}): {} != {}",
1507 fingerprint, object_info.fingerprint,
1508 );
1509 }
1510 }
1511
1512 Ok(new_fingerprints)
1513 }
1514
1515 async fn cleanup(&self) -> anyhow::Result<(BTreeSet<ShardId>, BoxFuture<'static, ()>)> {
1532 let noop_action = async {}.boxed();
1533 let noop_result = (BTreeSet::new(), noop_action);
1534
1535 if self.config.read_only {
1536 return Ok(noop_result);
1537 }
1538
1539 let diagnostics = Diagnostics {
1540 shard_name: "builtin_migration".to_string(),
1541 handle_purpose: "builtin schema migration cleanup".into(),
1542 };
1543 let (mut persist_write, mut persist_read) =
1544 self.open_migration_shard(diagnostics.clone()).await;
1545 let mut persist_since = self.open_migration_shard_since(diagnostics.clone()).await;
1546
1547 let upper = persist_write.fetch_recent_upper().await.clone();
1548 let write_ts = *upper.as_option().expect("migration shard not sealed");
1549 let Some(read_ts) = write_ts.step_back() else {
1550 return Ok(noop_result);
1551 };
1552
1553 let pred = |key: &migration_shard::Key| key.build_version < self.target_version;
1555 let Some(stale_entries) = read_migration_shard(&mut persist_read, read_ts, pred).await
1556 else {
1557 return Ok(noop_result);
1558 };
1559
1560 debug!(
1561 ?stale_entries,
1562 "cleaning migration shard up to version {}", self.target_version,
1563 );
1564
1565 let current_shards: BTreeMap<_, _> = self
1566 .system_objects
1567 .values()
1568 .filter_map(|o| o.shard_id.map(|shard_id| (o.global_id, shard_id)))
1569 .collect();
1570
1571 let mut shards_to_finalize = BTreeSet::new();
1572 let mut retractions = Vec::new();
1573 for (key, shard_id) in stale_entries {
1574 let gid = GlobalId::System(key.global_id);
1578 if current_shards.get(&gid) != Some(&shard_id) {
1579 shards_to_finalize.insert(shard_id);
1580 }
1581
1582 retractions.push(((key, shard_id), write_ts, -1));
1583 }
1584
1585 let cleanup_action = async move {
1586 if !retractions.is_empty() {
1587 let new_upper = Antichain::from_elem(write_ts.step_forward());
1588 let result = persist_write
1589 .compare_and_append(retractions, upper, new_upper)
1590 .await
1591 .expect("valid usage");
1592 match result {
1593 Ok(()) => debug!("cleaned up migration shard"),
1594 Err(mismatch) => debug!(?mismatch, "migration shard cleanup failed"),
1595 }
1596 }
1597 }
1598 .boxed();
1599
1600 let o = persist_since.opaque().clone();
1602 let new_since = Antichain::from_elem(read_ts);
1603 let result = persist_since
1604 .maybe_compare_and_downgrade_since(&o, (&o, &new_since))
1605 .await;
1606 soft_assert_or_log!(result.is_none_or(|r| r.is_ok()), "opaque mismatch");
1607
1608 Ok((shards_to_finalize, cleanup_action))
1609 }
1610}
1611
1612async fn read_migration_shard<P>(
1618 persist_read: &mut ReadHandle<migration_shard::Key, ShardId, Timestamp, StorageDiff>,
1619 read_ts: Timestamp,
1620 predicate: P,
1621) -> Option<Vec<(migration_shard::Key, ShardId)>>
1622where
1623 P: Fn(&migration_shard::Key) -> bool,
1624{
1625 let as_of = Antichain::from_elem(read_ts);
1626 let updates = persist_read.snapshot_and_fetch(as_of).await.ok()?;
1627
1628 assert!(
1629 updates.iter().all(|(_, _, diff)| *diff == 1),
1630 "migration shard contains invalid diffs: {updates:?}",
1631 );
1632
1633 let entries: Vec<_> = updates
1634 .into_iter()
1635 .map(|(data, _, _)| data)
1636 .filter(move |(key, _)| predicate(key))
1637 .collect();
1638
1639 (!entries.is_empty()).then_some(entries)
1640}
1641
1642#[derive(Debug, Default)]
1644struct Plan {
1645 evolve: Vec<SystemObjectDescription>,
1647 replace: Vec<SystemObjectDescription>,
1649}
1650
1651mod migration_shard {
1654 use std::fmt;
1655 use std::str::FromStr;
1656
1657 use arrow::array::{StringArray, StringBuilder};
1658 use bytes::{BufMut, Bytes};
1659 use mz_catalog::durable::SystemObjectDescription;
1660 use mz_persist_types::Codec;
1661 use mz_persist_types::codec_impls::{
1662 SimpleColumnarData, SimpleColumnarDecoder, SimpleColumnarEncoder,
1663 };
1664 use mz_persist_types::columnar::Schema;
1665 use mz_persist_types::stats::NoneStats;
1666 use semver::Version;
1667 use serde::{Deserialize, Serialize};
1668
1669 #[derive(Debug, Clone, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
1670 pub(super) struct Key {
1671 pub(super) global_id: u64,
1672 pub(super) build_version: Version,
1673 pub(super) deploy_generation: Option<u64>,
1677 #[serde(skip_serializing_if = "Option::is_none")]
1687 pub(super) object: Option<ObjectKey>,
1688 }
1689
1690 #[derive(Debug, Clone, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
1692 pub(super) struct ObjectKey {
1693 schema_name: String,
1694 object_name: String,
1695 object_type: String,
1696 }
1697
1698 impl From<&SystemObjectDescription> for ObjectKey {
1699 fn from(object: &SystemObjectDescription) -> Self {
1700 Self {
1701 schema_name: object.schema_name.clone(),
1702 object_name: object.object_name.clone(),
1703 object_type: object.object_type.to_string(),
1704 }
1705 }
1706 }
1707
1708 impl fmt::Display for Key {
1709 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1710 if self.deploy_generation.is_some() {
1711 let s = serde_json::to_string(self).expect("JSON serializable");
1713 f.write_str(&s)
1714 } else {
1715 write!(f, "{}-{}", self.global_id, self.build_version)
1717 }
1718 }
1719 }
1720
1721 impl FromStr for Key {
1722 type Err = String;
1723
1724 fn from_str(s: &str) -> Result<Self, String> {
1725 if let Ok(key) = serde_json::from_str(s) {
1727 return Ok(key);
1728 };
1729
1730 let parts: Vec<_> = s.splitn(2, '-').collect();
1732 let &[global_id, build_version] = parts.as_slice() else {
1733 return Err(format!("invalid Key '{s}'"));
1734 };
1735 let global_id = global_id.parse::<u64>().map_err(|e| e.to_string())?;
1736 let build_version = build_version
1737 .parse::<Version>()
1738 .map_err(|e| e.to_string())?;
1739 Ok(Key {
1740 global_id,
1741 build_version,
1742 deploy_generation: None,
1743 object: None,
1744 })
1745 }
1746 }
1747
1748 impl Default for Key {
1749 fn default() -> Self {
1750 Self {
1751 global_id: Default::default(),
1752 build_version: Version::new(0, 0, 0),
1753 deploy_generation: Some(0),
1754 object: None,
1755 }
1756 }
1757 }
1758
1759 impl Codec for Key {
1760 type Schema = KeySchema;
1761 type Storage = ();
1762
1763 fn codec_name() -> String {
1764 "TableKey".into()
1765 }
1766
1767 fn encode<B: BufMut>(&self, buf: &mut B) {
1768 buf.put(self.to_string().as_bytes())
1769 }
1770
1771 fn decode<'a>(buf: &'a [u8], _schema: &KeySchema) -> Result<Self, String> {
1772 let s = str::from_utf8(buf).map_err(|e| e.to_string())?;
1773 s.parse()
1774 }
1775
1776 fn encode_schema(_schema: &KeySchema) -> Bytes {
1777 Bytes::new()
1778 }
1779
1780 fn decode_schema(buf: &Bytes) -> Self::Schema {
1781 assert_eq!(*buf, Bytes::new());
1782 KeySchema
1783 }
1784 }
1785
1786 impl SimpleColumnarData for Key {
1787 type ArrowBuilder = StringBuilder;
1788 type ArrowColumn = StringArray;
1789
1790 fn goodbytes(builder: &Self::ArrowBuilder) -> usize {
1791 builder.values_slice().len()
1792 }
1793
1794 fn push(&self, builder: &mut Self::ArrowBuilder) {
1795 builder.append_value(&self.to_string());
1796 }
1797
1798 fn push_null(builder: &mut Self::ArrowBuilder) {
1799 builder.append_null();
1800 }
1801
1802 fn read(&mut self, idx: usize, column: &Self::ArrowColumn) {
1803 *self = column.value(idx).parse().expect("valid Key");
1804 }
1805 }
1806
1807 #[derive(Debug, PartialEq)]
1808 pub(super) struct KeySchema;
1809
1810 impl Schema<Key> for KeySchema {
1811 type ArrowColumn = StringArray;
1812 type Statistics = NoneStats;
1813 type Decoder = SimpleColumnarDecoder<Key>;
1814 type Encoder = SimpleColumnarEncoder<Key>;
1815
1816 fn encoder(&self) -> anyhow::Result<SimpleColumnarEncoder<Key>> {
1817 Ok(SimpleColumnarEncoder::default())
1818 }
1819
1820 fn decoder(&self, col: StringArray) -> anyhow::Result<SimpleColumnarDecoder<Key>> {
1821 Ok(SimpleColumnarDecoder::new(col))
1822 }
1823 }
1824}
1825
1826#[cfg(test)]
1827#[path = "builtin_schema_migration_tests.rs"]
1828mod tests;