Skip to main content

mz_storage_types/
sources.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Types and traits related to the introduction of changing collections into `dataflow`.
11
12use std::collections::BTreeMap;
13use std::fmt::Debug;
14use std::hash::Hash;
15use std::ops::{Add, AddAssign, Deref, DerefMut};
16use std::str::FromStr;
17use std::sync::Arc;
18use std::time::Duration;
19
20use arrow::array::{Array, ArrayRef, BinaryArray, BinaryBuilder, NullArray, StructArray};
21use arrow::datatypes::{Field, Fields};
22use bytes::{BufMut, Bytes};
23use columnation::Columnation;
24use itertools::EitherOrBoth::Both;
25use itertools::Itertools;
26use kafka::KafkaSourceExportDetails;
27use load_generator::{LoadGeneratorOutput, LoadGeneratorSourceExportDetails};
28use mz_ore::assert_none;
29use mz_persist_types::Codec;
30use mz_persist_types::arrow::ArrayOrd;
31use mz_persist_types::columnar::{ColumnDecoder, ColumnEncoder, Schema};
32use mz_persist_types::stats::{
33    ColumnNullStats, ColumnStatKinds, ColumnarStats, ColumnarStatsBuilder, PrimitiveStats,
34    StructStats,
35};
36use mz_proto::{IntoRustIfSome, ProtoType, RustType, TryFromProtoError};
37#[cfg(any(test, feature = "proptest"))]
38use mz_repr::arb_row_for_relation;
39use mz_repr::{
40    CatalogItemId, Datum, GlobalId, ProtoRelationDesc, ProtoRow, RelationDesc, Row,
41    RowColumnarDecoder, RowColumnarEncoder,
42};
43use mz_sql_parser::ast::{Ident, IdentError, UnresolvedItemName};
44#[cfg(any(test, feature = "proptest"))]
45use proptest::prelude::any;
46#[cfg(any(test, feature = "proptest"))]
47use proptest::strategy::Strategy;
48use prost::Message;
49use serde::{Deserialize, Serialize};
50use timely::order::{PartialOrder, TotalOrder};
51use timely::progress::timestamp::Refines;
52use timely::progress::{PathSummary, Timestamp};
53
54use crate::AlterCompatible;
55use crate::connections::inline::{
56    ConnectionAccess, ConnectionResolver, InlinedConnection, IntoInlineConnection,
57    ReferencedConnection,
58};
59use crate::controller::AlterError;
60use crate::errors::{DataflowError, ProtoDataflowError};
61use crate::instances::StorageInstanceId;
62use crate::sources::sql_server::SqlServerSourceExportDetails;
63
64pub mod casts;
65pub mod encoding;
66pub mod envelope;
67pub mod kafka;
68pub mod load_generator;
69pub mod mysql;
70pub mod postgres;
71pub mod sql_server;
72
73pub use crate::sources::envelope::SourceEnvelope;
74pub use crate::sources::kafka::KafkaSourceConnection;
75pub use crate::sources::load_generator::LoadGeneratorSourceConnection;
76pub use crate::sources::mysql::{MySqlSourceConnection, MySqlSourceExportDetails};
77pub use crate::sources::postgres::{PostgresSourceConnection, PostgresSourceExportDetails};
78pub use crate::sources::sql_server::{SqlServerSourceConnection, SqlServerSourceExtras};
79
80include!(concat!(env!("OUT_DIR"), "/mz_storage_types.sources.rs"));
81
82/// A description of a source ingestion
83#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
84pub struct IngestionDescription<S: 'static = (), C: ConnectionAccess = InlinedConnection> {
85    /// The source description.
86    pub desc: SourceDesc<C>,
87    /// Collections to be exported by this ingestion.
88    ///
89    /// # Notes
90    /// - For multi-output sources:
91    ///     - Add exports by adding a new [`SourceExport`].
92    ///     - Remove exports by removing the [`SourceExport`].
93    ///
94    ///   Re-rendering/executing the source after making these modifications
95    ///   adds and drops the subsource, respectively.
96    /// - For old-syntax sources this field includes the primary source's ID,
97    ///   which might need to be filtered out to understand which exports are
98    ///   explicit ingestion exports. New-syntax sources (with source tables)
99    ///   list only their exports here.
100    /// - This field does _not_ include the remap collection, which is tracked
101    ///   in its own field.
102    pub source_exports: BTreeMap<GlobalId, SourceExport<S>>,
103    /// The ID of the instance in which to install the source.
104    pub instance_id: StorageInstanceId,
105    /// The ID of this ingestion's remap/progress collection.
106    pub remap_collection_id: GlobalId,
107    /// The storage metadata for the remap/progress collection
108    pub remap_metadata: S,
109}
110
111impl IngestionDescription {
112    pub fn new(
113        desc: SourceDesc,
114        instance_id: StorageInstanceId,
115        remap_collection_id: GlobalId,
116    ) -> Self {
117        Self {
118            desc,
119            remap_metadata: (),
120            source_exports: BTreeMap::new(),
121            instance_id,
122            remap_collection_id,
123        }
124    }
125}
126
127impl<S> IngestionDescription<S> {
128    /// Return an iterator over the `GlobalId`s of `self`'s collections.
129    /// This will contain ids for the remap collection, subsources,
130    /// tables for this source, and the primary collection ID, even if
131    /// no data will be exported to the primary collection.
132    pub fn collection_ids(&self) -> impl Iterator<Item = GlobalId> + '_ {
133        // Expand self so that any new fields added generate a compiler error to
134        // increase the likelihood of developers seeing this function.
135        let IngestionDescription {
136            desc: _,
137            remap_metadata: _,
138            source_exports,
139            instance_id: _,
140            remap_collection_id,
141        } = &self;
142
143        source_exports
144            .keys()
145            .copied()
146            .chain(std::iter::once(*remap_collection_id))
147    }
148}
149
150impl<S: Debug + Eq + PartialEq + AlterCompatible> AlterCompatible for IngestionDescription<S> {
151    fn alter_compatible(
152        &self,
153        id: GlobalId,
154        other: &IngestionDescription<S>,
155    ) -> Result<(), AlterError> {
156        if self == other {
157            return Ok(());
158        }
159        let IngestionDescription {
160            desc,
161            remap_metadata,
162            source_exports,
163            instance_id,
164            remap_collection_id,
165        } = self;
166
167        let compatibility_checks = [
168            (desc.alter_compatible(id, &other.desc).is_ok(), "desc"),
169            (remap_metadata == &other.remap_metadata, "remap_metadata"),
170            (
171                source_exports
172                    .iter()
173                    .merge_join_by(&other.source_exports, |(l_key, _), (r_key, _)| {
174                        l_key.cmp(r_key)
175                    })
176                    .all(|r| match r {
177                        Both(
178                            (
179                                _,
180                                SourceExport {
181                                    storage_metadata: l_metadata,
182                                    details: l_details,
183                                    data_config: l_data_config,
184                                },
185                            ),
186                            (
187                                _,
188                                SourceExport {
189                                    storage_metadata: r_metadata,
190                                    details: r_details,
191                                    data_config: r_data_config,
192                                },
193                            ),
194                        ) => {
195                            l_metadata.alter_compatible(id, r_metadata).is_ok()
196                                && l_details.alter_compatible(id, r_details).is_ok()
197                                && l_data_config.alter_compatible(id, r_data_config).is_ok()
198                        }
199                        _ => true,
200                    }),
201                "source_exports",
202            ),
203            (instance_id == &other.instance_id, "instance_id"),
204            (
205                remap_collection_id == &other.remap_collection_id,
206                "remap_collection_id",
207            ),
208        ];
209        for (compatible, field) in compatibility_checks {
210            if !compatible {
211                tracing::warn!(
212                    "IngestionDescription incompatible at {field}:\nself:\n{:#?}\n\nother\n{:#?}",
213                    self,
214                    other
215                );
216
217                return Err(AlterError { id });
218            }
219        }
220
221        Ok(())
222    }
223}
224
225impl<R: ConnectionResolver> IntoInlineConnection<IngestionDescription, R>
226    for IngestionDescription<(), ReferencedConnection>
227{
228    fn into_inline_connection(self, r: R) -> IngestionDescription {
229        let IngestionDescription {
230            desc,
231            remap_metadata,
232            source_exports,
233            instance_id,
234            remap_collection_id,
235        } = self;
236
237        IngestionDescription {
238            desc: desc.into_inline_connection(r),
239            remap_metadata,
240            source_exports,
241            instance_id,
242            remap_collection_id,
243        }
244    }
245}
246
247#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
248pub struct SourceExport<S = (), C: ConnectionAccess = InlinedConnection> {
249    /// The collection metadata needed to write the exported data
250    pub storage_metadata: S,
251    /// Details necessary for the source to export data to this export's collection.
252    pub details: SourceExportDetails,
253    /// Config necessary to handle (e.g. decode and envelope) the data for this export.
254    pub data_config: SourceExportDataConfig<C>,
255}
256
257pub trait SourceTimestamp:
258    Timestamp + Columnation + Refines<()> + std::fmt::Display + Sync
259{
260    fn encode_row(&self) -> Row;
261    fn decode_row(row: &Row) -> Self;
262}
263
264impl SourceTimestamp for MzOffset {
265    fn encode_row(&self) -> Row {
266        Row::pack([Datum::UInt64(self.offset)])
267    }
268
269    fn decode_row(row: &Row) -> Self {
270        let mut datums = row.iter();
271        match (datums.next(), datums.next()) {
272            (Some(Datum::UInt64(offset)), None) => MzOffset::from(offset),
273            _ => panic!("invalid row {row:?}"),
274        }
275    }
276}
277
278/// Universal language for describing message positions in Materialize, in a source independent
279/// way. Individual sources like Kafka or File sources should explicitly implement their own offset
280/// type that converts to/From MzOffsets. A 0-MzOffset denotes an empty stream.
281#[derive(
282    Copy,
283    Clone,
284    Default,
285    Debug,
286    PartialEq,
287    PartialOrd,
288    Eq,
289    Ord,
290    Hash,
291    Serialize,
292    Deserialize
293)]
294pub struct MzOffset {
295    pub offset: u64,
296}
297
298impl differential_dataflow::difference::Semigroup for MzOffset {
299    fn plus_equals(&mut self, rhs: &Self) {
300        self.offset.plus_equals(&rhs.offset)
301    }
302}
303
304impl differential_dataflow::difference::IsZero for MzOffset {
305    fn is_zero(&self) -> bool {
306        self.offset.is_zero()
307    }
308}
309
310impl mz_persist_types::Codec64 for MzOffset {
311    fn codec_name() -> String {
312        "MzOffset".to_string()
313    }
314
315    fn encode(&self) -> [u8; 8] {
316        mz_persist_types::Codec64::encode(&self.offset)
317    }
318
319    fn decode(buf: [u8; 8]) -> Self {
320        Self {
321            offset: mz_persist_types::Codec64::decode(buf),
322        }
323    }
324}
325
326impl columnation::Columnation for MzOffset {
327    type InnerRegion = columnation::CopyRegion<MzOffset>;
328}
329
330impl MzOffset {
331    pub fn checked_sub(self, other: Self) -> Option<Self> {
332        self.offset
333            .checked_sub(other.offset)
334            .map(|offset| Self { offset })
335    }
336}
337
338/// Convert from MzOffset to Kafka::Offset as long as
339/// the offset is not negative
340impl From<u64> for MzOffset {
341    fn from(offset: u64) -> Self {
342        Self { offset }
343    }
344}
345
346impl std::fmt::Display for MzOffset {
347    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
348        write!(f, "{}", self.offset)
349    }
350}
351
352// Assume overflow does not occur for addition
353impl Add<u64> for MzOffset {
354    type Output = MzOffset;
355
356    fn add(self, x: u64) -> MzOffset {
357        MzOffset {
358            offset: self.offset + x,
359        }
360    }
361}
362impl Add<Self> for MzOffset {
363    type Output = Self;
364
365    fn add(self, x: Self) -> Self {
366        MzOffset {
367            offset: self.offset + x.offset,
368        }
369    }
370}
371impl AddAssign<u64> for MzOffset {
372    fn add_assign(&mut self, x: u64) {
373        self.offset += x;
374    }
375}
376impl AddAssign<Self> for MzOffset {
377    fn add_assign(&mut self, x: Self) {
378        self.offset += x.offset;
379    }
380}
381
382/// Convert from `PgLsn` to MzOffset
383impl From<tokio_postgres::types::PgLsn> for MzOffset {
384    fn from(lsn: tokio_postgres::types::PgLsn) -> Self {
385        MzOffset { offset: lsn.into() }
386    }
387}
388
389impl Timestamp for MzOffset {
390    type Summary = MzOffset;
391
392    fn minimum() -> Self {
393        MzOffset {
394            offset: Timestamp::minimum(),
395        }
396    }
397}
398
399impl PathSummary<MzOffset> for MzOffset {
400    fn results_in(&self, src: &MzOffset) -> Option<MzOffset> {
401        Some(MzOffset {
402            offset: self.offset.results_in(&src.offset)?,
403        })
404    }
405
406    fn followed_by(&self, other: &Self) -> Option<Self> {
407        Some(MzOffset {
408            offset: PathSummary::<u64>::followed_by(&self.offset, &other.offset)?,
409        })
410    }
411}
412
413impl Refines<()> for MzOffset {
414    fn to_inner(_: ()) -> Self {
415        MzOffset::minimum()
416    }
417    fn to_outer(self) {}
418    fn summarize(_: Self::Summary) {}
419}
420
421impl PartialOrder for MzOffset {
422    #[inline]
423    fn less_equal(&self, other: &Self) -> bool {
424        self.offset.less_equal(&other.offset)
425    }
426}
427
428impl TotalOrder for MzOffset {}
429
430/// The meaning of the timestamp number produced by data sources. This type
431/// is not concerned with the source of the timestamp (like if the data came
432/// from a Debezium consistency topic or a CDCv2 stream), instead only what the
433/// timestamp number means.
434///
435/// Some variants here have attached data used to differentiate incomparable
436/// instantiations. These attached data types should be expanded in the future
437/// if we need to tell apart more kinds of sources.
438#[derive(
439    Clone,
440    Debug,
441    Ord,
442    PartialOrd,
443    Eq,
444    PartialEq,
445    Serialize,
446    Deserialize,
447    Hash
448)]
449pub enum Timeline {
450    /// EpochMilliseconds means the timestamp is the number of milliseconds since
451    /// the Unix epoch.
452    EpochMilliseconds,
453    /// External means the timestamp comes from an external data source and we
454    /// don't know what the number means. The attached String is the source's name,
455    /// which will result in different sources being incomparable.
456    External(String),
457    /// User means the user has manually specified a timeline. The attached
458    /// String is specified by the user, allowing them to decide sources that are
459    /// joinable.
460    User(String),
461}
462
463impl Timeline {
464    const EPOCH_MILLISECOND_ID_CHAR: char = 'M';
465    const EXTERNAL_ID_CHAR: char = 'E';
466    const USER_ID_CHAR: char = 'U';
467
468    fn id_char(&self) -> char {
469        match self {
470            Self::EpochMilliseconds => Self::EPOCH_MILLISECOND_ID_CHAR,
471            Self::External(_) => Self::EXTERNAL_ID_CHAR,
472            Self::User(_) => Self::USER_ID_CHAR,
473        }
474    }
475}
476
477impl ToString for Timeline {
478    fn to_string(&self) -> String {
479        match self {
480            Self::EpochMilliseconds => format!("{}", self.id_char()),
481            Self::External(id) => format!("{}.{id}", self.id_char()),
482            Self::User(id) => format!("{}.{id}", self.id_char()),
483        }
484    }
485}
486
487impl FromStr for Timeline {
488    type Err = String;
489
490    fn from_str(s: &str) -> Result<Self, Self::Err> {
491        if s.is_empty() {
492            return Err("empty timeline".to_string());
493        }
494        let mut chars = s.chars();
495        match chars.next().expect("non-empty string") {
496            Self::EPOCH_MILLISECOND_ID_CHAR => match chars.next() {
497                None => Ok(Self::EpochMilliseconds),
498                Some(_) => Err(format!("unknown timeline: {s}")),
499            },
500            Self::EXTERNAL_ID_CHAR => match chars.next() {
501                Some('.') => Ok(Self::External(chars.as_str().to_string())),
502                _ => Err(format!("unknown timeline: {s}")),
503            },
504            Self::USER_ID_CHAR => match chars.next() {
505                Some('.') => Ok(Self::User(chars.as_str().to_string())),
506                _ => Err(format!("unknown timeline: {s}")),
507            },
508            _ => Err(format!("unknown timeline: {s}")),
509        }
510    }
511}
512
513/// A connection to an external system
514pub trait SourceConnection: Debug + Clone + PartialEq + AlterCompatible {
515    /// The name of the external system (e.g kafka, postgres, etc).
516    fn name(&self) -> &'static str;
517
518    /// The name of the resource in the external system (e.g kafka topic) if any
519    fn external_reference(&self) -> Option<&str>;
520
521    /// Defines the key schema to use by default for this source connection type.
522    /// This will be used for the primary export of the source and as the default
523    /// pre-encoding key schema for the source.
524    fn default_key_desc(&self) -> RelationDesc;
525
526    /// Defines the value schema to use by default for this source connection type.
527    /// This will be used for the primary export of the source and as the default
528    /// pre-encoding value schema for the source.
529    fn default_value_desc(&self) -> RelationDesc;
530
531    /// The schema of this connection's timestamp type. This will also be the schema of the
532    /// progress relation.
533    fn timestamp_desc(&self) -> RelationDesc;
534
535    /// The id of the connection object (i.e the one obtained from running `CREATE CONNECTION`) in
536    /// the catalog, if any.
537    fn connection_id(&self) -> Option<CatalogItemId>;
538
539    /// Whether the source type supports read only mode.
540    fn supports_read_only(&self) -> bool;
541
542    /// Whether the source type prefers to run on only one replica of a multi-replica cluster.
543    fn prefers_single_replica(&self) -> bool;
544}
545
546#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
547pub enum Compression {
548    Gzip,
549    None,
550}
551
552/// Defines the configuration for how to handle data that is exported for a given
553/// Source Export.
554#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
555pub struct SourceExportDataConfig<C: ConnectionAccess = InlinedConnection> {
556    pub encoding: Option<encoding::SourceDataEncoding<C>>,
557    pub envelope: SourceEnvelope,
558}
559
560impl<R: ConnectionResolver> IntoInlineConnection<SourceExportDataConfig, R>
561    for SourceExportDataConfig<ReferencedConnection>
562{
563    fn into_inline_connection(self, r: R) -> SourceExportDataConfig {
564        let SourceExportDataConfig { encoding, envelope } = self;
565
566        SourceExportDataConfig {
567            encoding: encoding.map(|e| e.into_inline_connection(r)),
568            envelope,
569        }
570    }
571}
572
573impl<C: ConnectionAccess> AlterCompatible for SourceExportDataConfig<C> {
574    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
575        if self == other {
576            return Ok(());
577        }
578        let Self { encoding, envelope } = &self;
579
580        let compatibility_checks = [
581            (
582                match (encoding, &other.encoding) {
583                    (Some(s), Some(o)) => s.alter_compatible(id, o).is_ok(),
584                    (s, o) => s == o,
585                },
586                "encoding",
587            ),
588            (envelope == &other.envelope, "envelope"),
589        ];
590
591        for (compatible, field) in compatibility_checks {
592            if !compatible {
593                tracing::warn!(
594                    "SourceDesc incompatible {field}:\nself:\n{:#?}\n\nother\n{:#?}",
595                    self,
596                    other
597                );
598
599                return Err(AlterError { id });
600            }
601        }
602        Ok(())
603    }
604}
605
606impl<C: ConnectionAccess> SourceExportDataConfig<C> {
607    /// Returns `true` if this connection yields data that is
608    /// append-only/monotonic. Append-monly means the source
609    /// never produces retractions.
610    // TODO(guswynn): consider enforcing this more completely at the
611    // parsing/typechecking level, by not using an `envelope`
612    // for sources like pg
613    pub fn monotonic(&self, connection: &GenericSourceConnection<C>) -> bool {
614        match &self.envelope {
615            // Upsert and CdcV2 may produce retractions.
616            SourceEnvelope::Upsert(_) | SourceEnvelope::CdcV2 => false,
617            SourceEnvelope::None(_) => {
618                match connection {
619                    // Postgres can produce retractions (deletes).
620                    GenericSourceConnection::Postgres(_) => false,
621                    // MySQL can produce retractions (deletes).
622                    GenericSourceConnection::MySql(_) => false,
623                    // SQL Server can produce retractions (deletes).
624                    GenericSourceConnection::SqlServer(_) => false,
625                    // Whether or not a Loadgen source can produce retractions varies.
626                    GenericSourceConnection::LoadGenerator(g) => g.load_generator.is_monotonic(),
627                    // Kafka exports with `None` envelope are append-only.
628                    GenericSourceConnection::Kafka(_) => true,
629                }
630            }
631        }
632    }
633}
634
635/// An external source of updates for a relational collection.
636#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
637pub struct SourceDesc<C: ConnectionAccess = InlinedConnection> {
638    pub connection: GenericSourceConnection<C>,
639    pub timestamp_interval: Duration,
640}
641
642impl<R: ConnectionResolver> IntoInlineConnection<SourceDesc, R>
643    for SourceDesc<ReferencedConnection>
644{
645    fn into_inline_connection(self, r: R) -> SourceDesc {
646        let SourceDesc {
647            connection,
648            timestamp_interval,
649        } = self;
650
651        SourceDesc {
652            connection: connection.into_inline_connection(&r),
653            timestamp_interval,
654        }
655    }
656}
657
658impl<C: ConnectionAccess> AlterCompatible for SourceDesc<C> {
659    /// Determines if `self` is compatible with another `SourceDesc`, in such a
660    /// way that it is possible to turn `self` into `other` through a valid
661    /// series of transformations (e.g. no transformation or `ALTER SOURCE`).
662    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
663        if self == other {
664            return Ok(());
665        }
666        let Self {
667            connection,
668            // timestamp_interval is allowed to change via ALTER SOURCE
669            timestamp_interval: _,
670        } = &self;
671
672        let compatibility_checks = [(
673            connection.alter_compatible(id, &other.connection).is_ok(),
674            "connection",
675        )];
676
677        for (compatible, field) in compatibility_checks {
678            if !compatible {
679                tracing::warn!(
680                    "SourceDesc incompatible {field}:\nself:\n{:#?}\n\nother\n{:#?}",
681                    self,
682                    other
683                );
684
685                return Err(AlterError { id });
686            }
687        }
688
689        Ok(())
690    }
691}
692
693#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
694pub enum GenericSourceConnection<C: ConnectionAccess = InlinedConnection> {
695    Kafka(KafkaSourceConnection<C>),
696    Postgres(PostgresSourceConnection<C>),
697    MySql(MySqlSourceConnection<C>),
698    SqlServer(SqlServerSourceConnection<C>),
699    LoadGenerator(LoadGeneratorSourceConnection),
700}
701
702impl<C: ConnectionAccess> From<KafkaSourceConnection<C>> for GenericSourceConnection<C> {
703    fn from(conn: KafkaSourceConnection<C>) -> Self {
704        Self::Kafka(conn)
705    }
706}
707
708impl<C: ConnectionAccess> From<PostgresSourceConnection<C>> for GenericSourceConnection<C> {
709    fn from(conn: PostgresSourceConnection<C>) -> Self {
710        Self::Postgres(conn)
711    }
712}
713
714impl<C: ConnectionAccess> From<MySqlSourceConnection<C>> for GenericSourceConnection<C> {
715    fn from(conn: MySqlSourceConnection<C>) -> Self {
716        Self::MySql(conn)
717    }
718}
719
720impl<C: ConnectionAccess> From<SqlServerSourceConnection<C>> for GenericSourceConnection<C> {
721    fn from(conn: SqlServerSourceConnection<C>) -> Self {
722        Self::SqlServer(conn)
723    }
724}
725
726impl<C: ConnectionAccess> From<LoadGeneratorSourceConnection> for GenericSourceConnection<C> {
727    fn from(conn: LoadGeneratorSourceConnection) -> Self {
728        Self::LoadGenerator(conn)
729    }
730}
731
732impl<R: ConnectionResolver> IntoInlineConnection<GenericSourceConnection, R>
733    for GenericSourceConnection<ReferencedConnection>
734{
735    fn into_inline_connection(self, r: R) -> GenericSourceConnection {
736        match self {
737            GenericSourceConnection::Kafka(kafka) => {
738                GenericSourceConnection::Kafka(kafka.into_inline_connection(r))
739            }
740            GenericSourceConnection::Postgres(pg) => {
741                GenericSourceConnection::Postgres(pg.into_inline_connection(r))
742            }
743            GenericSourceConnection::MySql(mysql) => {
744                GenericSourceConnection::MySql(mysql.into_inline_connection(r))
745            }
746            GenericSourceConnection::SqlServer(sql_server) => {
747                GenericSourceConnection::SqlServer(sql_server.into_inline_connection(r))
748            }
749            GenericSourceConnection::LoadGenerator(lg) => {
750                GenericSourceConnection::LoadGenerator(lg)
751            }
752        }
753    }
754}
755
756impl<C: ConnectionAccess> SourceConnection for GenericSourceConnection<C> {
757    fn name(&self) -> &'static str {
758        match self {
759            Self::Kafka(conn) => conn.name(),
760            Self::Postgres(conn) => conn.name(),
761            Self::MySql(conn) => conn.name(),
762            Self::SqlServer(conn) => conn.name(),
763            Self::LoadGenerator(conn) => conn.name(),
764        }
765    }
766
767    fn external_reference(&self) -> Option<&str> {
768        match self {
769            Self::Kafka(conn) => conn.external_reference(),
770            Self::Postgres(conn) => conn.external_reference(),
771            Self::MySql(conn) => conn.external_reference(),
772            Self::SqlServer(conn) => conn.external_reference(),
773            Self::LoadGenerator(conn) => conn.external_reference(),
774        }
775    }
776
777    fn default_key_desc(&self) -> RelationDesc {
778        match self {
779            Self::Kafka(conn) => conn.default_key_desc(),
780            Self::Postgres(conn) => conn.default_key_desc(),
781            Self::MySql(conn) => conn.default_key_desc(),
782            Self::SqlServer(conn) => conn.default_key_desc(),
783            Self::LoadGenerator(conn) => conn.default_key_desc(),
784        }
785    }
786
787    fn default_value_desc(&self) -> RelationDesc {
788        match self {
789            Self::Kafka(conn) => conn.default_value_desc(),
790            Self::Postgres(conn) => conn.default_value_desc(),
791            Self::MySql(conn) => conn.default_value_desc(),
792            Self::SqlServer(conn) => conn.default_value_desc(),
793            Self::LoadGenerator(conn) => conn.default_value_desc(),
794        }
795    }
796
797    fn timestamp_desc(&self) -> RelationDesc {
798        match self {
799            Self::Kafka(conn) => conn.timestamp_desc(),
800            Self::Postgres(conn) => conn.timestamp_desc(),
801            Self::MySql(conn) => conn.timestamp_desc(),
802            Self::SqlServer(conn) => conn.timestamp_desc(),
803            Self::LoadGenerator(conn) => conn.timestamp_desc(),
804        }
805    }
806
807    fn connection_id(&self) -> Option<CatalogItemId> {
808        match self {
809            Self::Kafka(conn) => conn.connection_id(),
810            Self::Postgres(conn) => conn.connection_id(),
811            Self::MySql(conn) => conn.connection_id(),
812            Self::SqlServer(conn) => conn.connection_id(),
813            Self::LoadGenerator(conn) => conn.connection_id(),
814        }
815    }
816
817    fn supports_read_only(&self) -> bool {
818        match self {
819            GenericSourceConnection::Kafka(conn) => conn.supports_read_only(),
820            GenericSourceConnection::Postgres(conn) => conn.supports_read_only(),
821            GenericSourceConnection::MySql(conn) => conn.supports_read_only(),
822            GenericSourceConnection::SqlServer(conn) => conn.supports_read_only(),
823            GenericSourceConnection::LoadGenerator(conn) => conn.supports_read_only(),
824        }
825    }
826
827    fn prefers_single_replica(&self) -> bool {
828        match self {
829            GenericSourceConnection::Kafka(conn) => conn.prefers_single_replica(),
830            GenericSourceConnection::Postgres(conn) => conn.prefers_single_replica(),
831            GenericSourceConnection::MySql(conn) => conn.prefers_single_replica(),
832            GenericSourceConnection::SqlServer(conn) => conn.prefers_single_replica(),
833            GenericSourceConnection::LoadGenerator(conn) => conn.prefers_single_replica(),
834        }
835    }
836}
837impl<C: ConnectionAccess> crate::AlterCompatible for GenericSourceConnection<C> {
838    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
839        if self == other {
840            return Ok(());
841        }
842        let r = match (self, other) {
843            (Self::Kafka(conn), Self::Kafka(other)) => conn.alter_compatible(id, other),
844            (Self::Postgres(conn), Self::Postgres(other)) => conn.alter_compatible(id, other),
845            (Self::MySql(conn), Self::MySql(other)) => conn.alter_compatible(id, other),
846            (Self::SqlServer(conn), Self::SqlServer(other)) => conn.alter_compatible(id, other),
847            (Self::LoadGenerator(conn), Self::LoadGenerator(other)) => {
848                conn.alter_compatible(id, other)
849            }
850            _ => Err(AlterError { id }),
851        };
852
853        if r.is_err() {
854            tracing::warn!(
855                "GenericSourceConnection incompatible:\nself:\n{:#?}\n\nother\n{:#?}",
856                self,
857                other
858            );
859        }
860
861        r
862    }
863}
864
865/// Details necessary for each source export to allow the source implementations
866/// to export data to the export's collection.
867#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
868pub enum SourceExportDetails {
869    /// Used when the primary collection of a source isn't an export to
870    /// output to.
871    None,
872    Kafka(KafkaSourceExportDetails),
873    Postgres(PostgresSourceExportDetails),
874    MySql(MySqlSourceExportDetails),
875    SqlServer(SqlServerSourceExportDetails),
876    LoadGenerator(LoadGeneratorSourceExportDetails),
877}
878
879impl crate::AlterCompatible for SourceExportDetails {
880    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
881        if self == other {
882            return Ok(());
883        }
884        let r = match (self, other) {
885            (Self::None, Self::None) => Ok(()),
886            (Self::Kafka(s), Self::Kafka(o)) => s.alter_compatible(id, o),
887            (Self::Postgres(s), Self::Postgres(o)) => s.alter_compatible(id, o),
888            (Self::MySql(s), Self::MySql(o)) => s.alter_compatible(id, o),
889            (Self::SqlServer(s), Self::SqlServer(o)) => s.alter_compatible(id, o),
890            (Self::LoadGenerator(s), Self::LoadGenerator(o)) => s.alter_compatible(id, o),
891            _ => Err(AlterError { id }),
892        };
893
894        if r.is_err() {
895            tracing::warn!(
896                "SourceExportDetails incompatible:\nself:\n{:#?}\n\nother\n{:#?}",
897                self,
898                other
899            );
900        }
901
902        r
903    }
904}
905
906/// Details necessary to store in the `Details` option of a source export
907/// statement (`CREATE SUBSOURCE` and `CREATE TABLE .. FROM SOURCE` statements),
908/// to generate the appropriate `SourceExportDetails` struct during planning.
909/// NOTE that this is serialized as proto to the catalog, so any changes here
910/// must be backwards compatible or will require a migration.
911pub enum SourceExportStatementDetails {
912    Postgres {
913        table: mz_postgres_util::desc::PostgresTableDesc,
914        /// Whether the text-to-oid cast for this export accepts the full `u32`
915        /// range. Exports created before the cast was widened decode as
916        /// `false` and must keep the legacy `i32`-range cast forever, because
917        /// replication re-casts old tuples on delete and the persisted rows
918        /// were ingested under the legacy semantics.
919        cast_oid_full_range: bool,
920    },
921    MySql {
922        table: mz_mysql_util::MySqlTableDesc,
923        initial_gtid_set: String,
924        binlog_full_metadata: bool,
925    },
926    SqlServer {
927        table: mz_sql_server_util::desc::SqlServerTableDesc,
928        capture_instance: Arc<str>,
929        initial_lsn: mz_sql_server_util::cdc::Lsn,
930    },
931    LoadGenerator {
932        output: LoadGeneratorOutput,
933    },
934    Kafka {},
935}
936
937impl RustType<ProtoSourceExportStatementDetails> for SourceExportStatementDetails {
938    fn into_proto(&self) -> ProtoSourceExportStatementDetails {
939        match self {
940            SourceExportStatementDetails::Postgres {
941                table,
942                cast_oid_full_range,
943            } => ProtoSourceExportStatementDetails {
944                kind: Some(proto_source_export_statement_details::Kind::Postgres(
945                    postgres::ProtoPostgresSourceExportStatementDetails {
946                        table: Some(table.into_proto()),
947                        cast_oid_full_range: *cast_oid_full_range,
948                    },
949                )),
950            },
951            SourceExportStatementDetails::MySql {
952                table,
953                initial_gtid_set,
954                binlog_full_metadata,
955            } => ProtoSourceExportStatementDetails {
956                kind: Some(proto_source_export_statement_details::Kind::Mysql(
957                    mysql::ProtoMySqlSourceExportStatementDetails {
958                        table: Some(table.into_proto()),
959                        initial_gtid_set: initial_gtid_set.clone(),
960                        binlog_full_metadata: *binlog_full_metadata,
961                    },
962                )),
963            },
964            SourceExportStatementDetails::SqlServer {
965                table,
966                capture_instance,
967                initial_lsn,
968            } => ProtoSourceExportStatementDetails {
969                kind: Some(proto_source_export_statement_details::Kind::SqlServer(
970                    sql_server::ProtoSqlServerSourceExportStatementDetails {
971                        table: Some(table.into_proto()),
972                        capture_instance: capture_instance.to_string(),
973                        initial_lsn: initial_lsn.as_bytes().to_vec(),
974                    },
975                )),
976            },
977            SourceExportStatementDetails::LoadGenerator { output } => {
978                ProtoSourceExportStatementDetails {
979                    kind: Some(proto_source_export_statement_details::Kind::Loadgen(
980                        load_generator::ProtoLoadGeneratorSourceExportStatementDetails {
981                            output: output.into_proto().into(),
982                        },
983                    )),
984                }
985            }
986            SourceExportStatementDetails::Kafka {} => ProtoSourceExportStatementDetails {
987                kind: Some(proto_source_export_statement_details::Kind::Kafka(
988                    kafka::ProtoKafkaSourceExportStatementDetails {},
989                )),
990            },
991        }
992    }
993
994    fn from_proto(proto: ProtoSourceExportStatementDetails) -> Result<Self, TryFromProtoError> {
995        use proto_source_export_statement_details::Kind;
996        Ok(match proto.kind {
997            Some(Kind::Postgres(details)) => SourceExportStatementDetails::Postgres {
998                table: details
999                    .table
1000                    .into_rust_if_some("ProtoPostgresSourceExportStatementDetails::table")?,
1001                cast_oid_full_range: details.cast_oid_full_range,
1002            },
1003            Some(Kind::Mysql(details)) => SourceExportStatementDetails::MySql {
1004                table: details
1005                    .table
1006                    .into_rust_if_some("ProtoMySqlSourceExportStatementDetails::table")?,
1007
1008                initial_gtid_set: details.initial_gtid_set,
1009                binlog_full_metadata: details.binlog_full_metadata,
1010            },
1011            Some(Kind::SqlServer(details)) => SourceExportStatementDetails::SqlServer {
1012                table: details
1013                    .table
1014                    .into_rust_if_some("ProtoSqlServerSourceExportStatementDetails::table")?,
1015                capture_instance: details.capture_instance.into(),
1016                initial_lsn: mz_sql_server_util::cdc::Lsn::try_from(details.initial_lsn.as_slice())
1017                    .map_err(|e| TryFromProtoError::InvalidFieldError(e.to_string()))?,
1018            },
1019            Some(Kind::Loadgen(details)) => SourceExportStatementDetails::LoadGenerator {
1020                output: details
1021                    .output
1022                    .into_rust_if_some("ProtoLoadGeneratorSourceExportStatementDetails::output")?,
1023            },
1024            Some(Kind::Kafka(_details)) => SourceExportStatementDetails::Kafka {},
1025            None => {
1026                return Err(TryFromProtoError::missing_field(
1027                    "ProtoSourceExportStatementDetails::kind",
1028                ));
1029            }
1030        })
1031    }
1032}
1033
1034#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1035#[repr(transparent)]
1036pub struct SourceData(pub Result<Row, DataflowError>);
1037
1038impl Default for SourceData {
1039    fn default() -> Self {
1040        SourceData(Ok(Row::default()))
1041    }
1042}
1043
1044impl Deref for SourceData {
1045    type Target = Result<Row, DataflowError>;
1046
1047    fn deref(&self) -> &Self::Target {
1048        &self.0
1049    }
1050}
1051
1052impl DerefMut for SourceData {
1053    fn deref_mut(&mut self) -> &mut Self::Target {
1054        &mut self.0
1055    }
1056}
1057
1058impl RustType<ProtoSourceData> for SourceData {
1059    fn into_proto(&self) -> ProtoSourceData {
1060        use proto_source_data::Kind;
1061        ProtoSourceData {
1062            kind: Some(match &**self {
1063                Ok(row) => Kind::Ok(row.into_proto()),
1064                Err(err) => Kind::Err(err.into_proto()),
1065            }),
1066        }
1067    }
1068
1069    fn from_proto(proto: ProtoSourceData) -> Result<Self, TryFromProtoError> {
1070        use proto_source_data::Kind;
1071        match proto.kind {
1072            Some(kind) => match kind {
1073                Kind::Ok(row) => Ok(SourceData(Ok(row.into_rust()?))),
1074                Kind::Err(err) => Ok(SourceData(Err(err.into_rust()?))),
1075            },
1076            None => Result::Err(TryFromProtoError::missing_field("ProtoSourceData::kind")),
1077        }
1078    }
1079}
1080
1081impl Codec for SourceData {
1082    type Storage = ProtoRow;
1083    type Schema = RelationDesc;
1084
1085    fn codec_name() -> String {
1086        "protobuf[SourceData]".into()
1087    }
1088
1089    fn encode<B: BufMut>(&self, buf: &mut B) {
1090        self.into_proto()
1091            .encode(buf)
1092            .expect("no required fields means no initialization errors");
1093    }
1094
1095    fn decode(buf: &[u8], schema: &RelationDesc) -> Result<Self, String> {
1096        let mut val = SourceData::default();
1097        <Self as Codec>::decode_from(&mut val, buf, &mut None, schema)?;
1098        Ok(val)
1099    }
1100
1101    fn decode_from<'a>(
1102        &mut self,
1103        buf: &'a [u8],
1104        storage: &mut Option<ProtoRow>,
1105        schema: &RelationDesc,
1106    ) -> Result<(), String> {
1107        // Optimize for common case of `Ok` by leaving a (cleared) `ProtoRow` in
1108        // the `Ok` variant of `ProtoSourceData`. prost's `Message::merge` impl
1109        // is smart about reusing the `Vec<Datum>` when it can.
1110        let mut proto = storage.take().unwrap_or_default();
1111        proto.clear();
1112        let mut proto = ProtoSourceData {
1113            kind: Some(proto_source_data::Kind::Ok(proto)),
1114        };
1115        proto.merge(buf).map_err(|err| err.to_string())?;
1116        match (proto.kind, &mut self.0) {
1117            // Again, optimize for the common case...
1118            (Some(proto_source_data::Kind::Ok(proto)), Ok(row)) => {
1119                let ret = row.decode_from_proto(&proto, schema);
1120                storage.replace(proto);
1121                ret
1122            }
1123            // ...otherwise fall back to the obvious thing.
1124            (kind, _) => {
1125                let proto = ProtoSourceData { kind };
1126                *self = proto.into_rust().map_err(|err| err.to_string())?;
1127                // Nothing to put back in storage.
1128                Ok(())
1129            }
1130        }
1131    }
1132
1133    fn validate(val: &Self, desc: &Self::Schema) -> Result<(), String> {
1134        match &val.0 {
1135            Ok(row) => Row::validate(row, desc),
1136            Err(_) => Ok(()),
1137        }
1138    }
1139
1140    fn encode_schema(schema: &Self::Schema) -> Bytes {
1141        schema.into_proto().encode_to_vec().into()
1142    }
1143
1144    fn decode_schema(buf: &Bytes) -> Self::Schema {
1145        let proto = ProtoRelationDesc::decode(buf.as_ref()).expect("valid schema");
1146        proto.into_rust().expect("valid schema")
1147    }
1148}
1149
1150/// Given a [`RelationDesc`] returns an arbitrary [`SourceData`].
1151#[cfg(any(test, feature = "proptest"))]
1152pub fn arb_source_data_for_relation_desc(
1153    desc: &RelationDesc,
1154) -> impl Strategy<Value = SourceData> + use<> {
1155    let row_strat = arb_row_for_relation(desc).no_shrink();
1156
1157    proptest::strategy::Union::new_weighted(vec![
1158        (50, row_strat.prop_map(|row| SourceData(Ok(row))).boxed()),
1159        (
1160            1,
1161            any::<DataflowError>()
1162                .prop_map(|err| SourceData(Err(err)))
1163                .no_shrink()
1164                .boxed(),
1165        ),
1166    ])
1167}
1168
1169/// Describes how external references should be organized in a multi-level
1170/// hierarchy.
1171///
1172/// For both PostgreSQL and MySQL sources, these levels of reference are
1173/// intrinsic to the items which we're referencing. If there are other naming
1174/// schemas for other types of sources we discover, we might need to revisit
1175/// this.
1176pub trait ExternalCatalogReference {
1177    /// The "second" level of namespacing for the reference.
1178    fn schema_name(&self) -> &str;
1179    /// The lowest level of namespacing for the reference.
1180    fn item_name(&self) -> &str;
1181}
1182
1183impl ExternalCatalogReference for &mz_mysql_util::MySqlTableDesc {
1184    fn schema_name(&self) -> &str {
1185        &self.schema_name
1186    }
1187
1188    fn item_name(&self) -> &str {
1189        &self.name
1190    }
1191}
1192
1193impl ExternalCatalogReference for mz_postgres_util::desc::PostgresTableDesc {
1194    fn schema_name(&self) -> &str {
1195        &self.namespace
1196    }
1197
1198    fn item_name(&self) -> &str {
1199        &self.name
1200    }
1201}
1202
1203impl ExternalCatalogReference for &mz_sql_server_util::desc::SqlServerTableDesc {
1204    fn schema_name(&self) -> &str {
1205        &*self.schema_name
1206    }
1207
1208    fn item_name(&self) -> &str {
1209        &*self.name
1210    }
1211}
1212
1213// This implementation provides a means of converting arbitrary objects into a
1214// `SubsourceCatalogReference`, e.g. load generator view names.
1215impl<'a> ExternalCatalogReference for (&'a str, &'a str) {
1216    fn schema_name(&self) -> &str {
1217        self.0
1218    }
1219
1220    fn item_name(&self) -> &str {
1221        self.1
1222    }
1223}
1224
1225/// Stores and resolves references to a `&[T: ExternalCatalogReference]`.
1226///
1227/// This is meant to provide an API to quickly look up a source's subsources.
1228///
1229/// For sources that do not provide any subsources, use the `Default`
1230/// implementation, which is empty and will not be able to resolve any
1231/// references.
1232#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1233pub struct SourceReferenceResolver {
1234    inner: BTreeMap<Ident, BTreeMap<Ident, BTreeMap<Ident, usize>>>,
1235}
1236
1237#[derive(Debug, Clone, thiserror::Error)]
1238pub enum ExternalReferenceResolutionError {
1239    #[error("reference to {name} not found in source")]
1240    DoesNotExist { name: String },
1241    #[error(
1242        "reference {name} is ambiguous, consider specifying an additional \
1243    layer of qualification"
1244    )]
1245    Ambiguous { name: String },
1246    #[error("invalid identifier: {0}")]
1247    Ident(#[from] IdentError),
1248}
1249
1250impl<'a> SourceReferenceResolver {
1251    /// Constructs a new `SourceReferenceResolver` from a slice of `T:
1252    /// SubsourceCatalogReference`.
1253    ///
1254    /// # Errors
1255    /// - If any `&str` provided cannot be taken to an [`Ident`].
1256    pub fn new<T: ExternalCatalogReference>(
1257        database: &str,
1258        referenceable_items: &'a [T],
1259    ) -> Result<SourceReferenceResolver, ExternalReferenceResolutionError> {
1260        // An index from table name -> schema name -> database name -> index in
1261        // `referenceable_items`.
1262        let mut inner = BTreeMap::new();
1263
1264        let database = Ident::new(database)?;
1265
1266        for (reference_idx, item) in referenceable_items.iter().enumerate() {
1267            let item_name = Ident::new(item.item_name())?;
1268            let schema_name = Ident::new(item.schema_name())?;
1269
1270            inner
1271                .entry(item_name)
1272                .or_insert_with(BTreeMap::new)
1273                .entry(schema_name)
1274                .or_insert_with(BTreeMap::new)
1275                .entry(database.clone())
1276                .or_insert(reference_idx);
1277        }
1278
1279        Ok(SourceReferenceResolver { inner })
1280    }
1281
1282    /// Returns the canonical reference and index from which it originated in
1283    /// the `referenceable_items` provided to [`Self::new`].
1284    ///
1285    /// # Args
1286    /// - `name` is `&[Ident]` to let users provide the inner element of
1287    ///   [`UnresolvedItemName`].
1288    /// - `canonicalize_to_width` limits the number of elements in the returned
1289    ///   [`UnresolvedItemName`];this is useful if the source type requires
1290    ///   contriving database and schema names that a subsource should not
1291    ///   persist as its reference.
1292    ///
1293    /// # Errors
1294    /// - If `name` does not resolve to an item in `self.inner`.
1295    ///
1296    /// # Panics
1297    /// - If `canonicalize_to_width`` is not in `1..=3`.
1298    pub fn resolve(
1299        &self,
1300        name: &[Ident],
1301        canonicalize_to_width: usize,
1302    ) -> Result<(UnresolvedItemName, usize), ExternalReferenceResolutionError> {
1303        let (db, schema, idx) = self.resolve_inner(name)?;
1304
1305        let item = name.last().expect("must have provided at least 1 element");
1306
1307        let canonical_name = match canonicalize_to_width {
1308            1 => vec![item.clone()],
1309            2 => vec![schema.clone(), item.clone()],
1310            3 => vec![db.clone(), schema.clone(), item.clone()],
1311            o => panic!("canonicalize_to_width values must be 1..=3, but got {}", o),
1312        };
1313
1314        Ok((UnresolvedItemName(canonical_name), idx))
1315    }
1316
1317    /// Returns the index from which it originated in the `referenceable_items`
1318    /// provided to [`Self::new`].
1319    ///
1320    /// # Args
1321    /// `name` is `&[Ident]` to let users provide the inner element of
1322    /// [`UnresolvedItemName`].
1323    ///
1324    /// # Errors
1325    /// - If `name` does not resolve to an item in `self.inner`.
1326    pub fn resolve_idx(&self, name: &[Ident]) -> Result<usize, ExternalReferenceResolutionError> {
1327        let (_db, _schema, idx) = self.resolve_inner(name)?;
1328        Ok(idx)
1329    }
1330
1331    /// Returns the index from which it originated in the `referenceable_items`
1332    /// provided to [`Self::new`].
1333    ///
1334    /// # Args
1335    /// `name` is `&[Ident]` to let users provide the inner element of
1336    /// [`UnresolvedItemName`].
1337    ///
1338    /// # Return
1339    /// Returns a tuple whose elements are:
1340    /// 1. The "database"- or top-level namespace of the reference.
1341    /// 2. The "schema"- or second-level namespace of the reference.
1342    /// 3. The index to find the item in `referenceable_items` argument provided
1343    ///    to `SourceReferenceResolver::new`.
1344    ///
1345    /// # Errors
1346    /// - If `name` does not resolve to an item in `self.inner`.
1347    fn resolve_inner<'name: 'a>(
1348        &'a self,
1349        name: &'name [Ident],
1350    ) -> Result<(&'a Ident, &'a Ident, usize), ExternalReferenceResolutionError> {
1351        let get_provided_name = || UnresolvedItemName(name.to_vec()).to_string();
1352
1353        // Names must be composed of 1..=3 elements.
1354        if !(1..=3).contains(&name.len()) {
1355            Err(ExternalReferenceResolutionError::DoesNotExist {
1356                name: get_provided_name(),
1357            })?;
1358        }
1359
1360        // Fill on the leading elements with `None` if they aren't present.
1361        let mut names = std::iter::repeat(None)
1362            .take(3 - name.len())
1363            .chain(name.iter().map(Some));
1364
1365        let database = names.next().flatten();
1366        let schema = names.next().flatten();
1367        let item = names
1368            .next()
1369            .flatten()
1370            .expect("must have provided the item name");
1371
1372        assert_none!(names.next(), "expected a 3-element iterator");
1373
1374        let schemas =
1375            self.inner
1376                .get(item)
1377                .ok_or_else(|| ExternalReferenceResolutionError::DoesNotExist {
1378                    name: get_provided_name(),
1379                })?;
1380
1381        let schema = match schema {
1382            Some(schema) => schema,
1383            None => schemas.keys().exactly_one().map_err(|_e| {
1384                ExternalReferenceResolutionError::Ambiguous {
1385                    name: get_provided_name(),
1386                }
1387            })?,
1388        };
1389
1390        let databases =
1391            schemas
1392                .get(schema)
1393                .ok_or_else(|| ExternalReferenceResolutionError::DoesNotExist {
1394                    name: get_provided_name(),
1395                })?;
1396
1397        let database = match database {
1398            Some(database) => database,
1399            None => databases.keys().exactly_one().map_err(|_e| {
1400                ExternalReferenceResolutionError::Ambiguous {
1401                    name: get_provided_name(),
1402                }
1403            })?,
1404        };
1405
1406        let reference_idx = databases.get(database).ok_or_else(|| {
1407            ExternalReferenceResolutionError::DoesNotExist {
1408                name: get_provided_name(),
1409            }
1410        })?;
1411
1412        Ok((database, schema, *reference_idx))
1413    }
1414}
1415
1416/// A decoder for [`Row`]s within [`SourceData`].
1417///
1418/// This type exists as a wrapper around [`RowColumnarDecoder`] to handle the
1419/// case where the [`RelationDesc`] we're encoding with has no columns. See
1420/// [`SourceDataRowColumnarEncoder`] for more details.
1421#[derive(Debug)]
1422pub enum SourceDataRowColumnarDecoder {
1423    Row(RowColumnarDecoder),
1424    EmptyRow,
1425}
1426
1427impl SourceDataRowColumnarDecoder {
1428    pub fn decode(&self, idx: usize, row: &mut Row) {
1429        match self {
1430            SourceDataRowColumnarDecoder::Row(decoder) => decoder.decode(idx, row),
1431            SourceDataRowColumnarDecoder::EmptyRow => {
1432                // Create a packer just to clear the Row.
1433                row.packer();
1434            }
1435        }
1436    }
1437
1438    pub fn goodbytes(&self) -> usize {
1439        match self {
1440            SourceDataRowColumnarDecoder::Row(decoder) => decoder.goodbytes(),
1441            SourceDataRowColumnarDecoder::EmptyRow => 0,
1442        }
1443    }
1444}
1445
1446#[derive(Debug)]
1447pub struct SourceDataColumnarDecoder {
1448    row_decoder: SourceDataRowColumnarDecoder,
1449    err_decoder: BinaryArray,
1450}
1451
1452impl SourceDataColumnarDecoder {
1453    pub fn new(col: StructArray, desc: &RelationDesc) -> Result<Self, anyhow::Error> {
1454        // TODO(parkmcar): We should validate the fields here.
1455        let (_fields, arrays, nullability) = col.into_parts();
1456
1457        if nullability.is_some() {
1458            anyhow::bail!("SourceData is not nullable, but found {nullability:?}");
1459        }
1460        if arrays.len() != 2 {
1461            anyhow::bail!("SourceData should only have two fields, found {arrays:?}");
1462        }
1463
1464        let errs = arrays[1]
1465            .as_any()
1466            .downcast_ref::<BinaryArray>()
1467            .ok_or_else(|| anyhow::anyhow!("expected BinaryArray, found {:?}", arrays[1]))?;
1468
1469        let row_decoder = match arrays[0].data_type() {
1470            arrow::datatypes::DataType::Struct(_) => {
1471                let rows = arrays[0]
1472                    .as_any()
1473                    .downcast_ref::<StructArray>()
1474                    .ok_or_else(|| {
1475                        anyhow::anyhow!("expected StructArray, found {:?}", arrays[0])
1476                    })?;
1477                let decoder = RowColumnarDecoder::new(rows.clone(), desc)?;
1478                SourceDataRowColumnarDecoder::Row(decoder)
1479            }
1480            arrow::datatypes::DataType::Null => SourceDataRowColumnarDecoder::EmptyRow,
1481            other => anyhow::bail!("expected Struct or Null Array, found {other:?}"),
1482        };
1483
1484        Ok(SourceDataColumnarDecoder {
1485            row_decoder,
1486            err_decoder: errs.clone(),
1487        })
1488    }
1489}
1490
1491impl ColumnDecoder<SourceData> for SourceDataColumnarDecoder {
1492    fn decode(&self, idx: usize, val: &mut SourceData) {
1493        let err_null = self.err_decoder.is_null(idx);
1494        let row_null = match &self.row_decoder {
1495            SourceDataRowColumnarDecoder::Row(decoder) => decoder.is_null(idx),
1496            SourceDataRowColumnarDecoder::EmptyRow => !err_null,
1497        };
1498
1499        match (row_null, err_null) {
1500            (true, false) => {
1501                let err = self.err_decoder.value(idx);
1502                let err = ProtoDataflowError::decode(err)
1503                    .expect("proto should be valid")
1504                    .into_rust()
1505                    .expect("error should be valid");
1506                val.0 = Err(err);
1507            }
1508            (false, true) => {
1509                let row = match val.0.as_mut() {
1510                    Ok(row) => row,
1511                    Err(_) => {
1512                        val.0 = Ok(Row::default());
1513                        val.0.as_mut().unwrap()
1514                    }
1515                };
1516                self.row_decoder.decode(idx, row);
1517            }
1518            (true, true) => panic!("should have one of 'ok' or 'err'"),
1519            (false, false) => panic!("cannot have both 'ok' and 'err'"),
1520        }
1521    }
1522
1523    fn is_null(&self, idx: usize) -> bool {
1524        let err_null = self.err_decoder.is_null(idx);
1525        let row_null = match &self.row_decoder {
1526            SourceDataRowColumnarDecoder::Row(decoder) => decoder.is_null(idx),
1527            SourceDataRowColumnarDecoder::EmptyRow => !err_null,
1528        };
1529        assert!(!err_null || !row_null, "SourceData should never be null!");
1530
1531        false
1532    }
1533
1534    fn goodbytes(&self) -> usize {
1535        self.row_decoder.goodbytes() + ArrayOrd::Binary(self.err_decoder.clone()).goodbytes()
1536    }
1537
1538    fn stats(&self) -> StructStats {
1539        let len = self.err_decoder.len();
1540        let err_stats = ColumnarStats {
1541            nulls: Some(ColumnNullStats {
1542                count: self.err_decoder.null_count(),
1543            }),
1544            values: PrimitiveStats::<Vec<u8>>::from_column(&self.err_decoder).into(),
1545        };
1546        // The top level struct is non-nullable and every entry is either an
1547        // `Ok(Row)` or an `Err(String)`. As a result, we can compute the number
1548        // of `Ok` entries by subtracting the number of `Err` entries from the
1549        // total count.
1550        let row_null_count = len - self.err_decoder.null_count();
1551        let row_stats = match &self.row_decoder {
1552            SourceDataRowColumnarDecoder::Row(encoder) => {
1553                // Sanity check that the number of row nulls/nones we calculated
1554                // using the error column matches what the row column thinks it
1555                // has.
1556                assert_eq!(encoder.null_count(), row_null_count);
1557                encoder.stats()
1558            }
1559            SourceDataRowColumnarDecoder::EmptyRow => StructStats {
1560                len,
1561                cols: BTreeMap::default(),
1562            },
1563        };
1564        let row_stats = ColumnarStats {
1565            nulls: Some(ColumnNullStats {
1566                count: row_null_count,
1567            }),
1568            values: ColumnStatKinds::Struct(row_stats),
1569        };
1570
1571        let stats = [
1572            (
1573                SourceDataColumnarEncoder::OK_COLUMN_NAME.to_string(),
1574                row_stats,
1575            ),
1576            (
1577                SourceDataColumnarEncoder::ERR_COLUMN_NAME.to_string(),
1578                err_stats,
1579            ),
1580        ];
1581        StructStats {
1582            len,
1583            cols: stats.into_iter().map(|(name, s)| (name, s)).collect(),
1584        }
1585    }
1586}
1587
1588/// An encoder for [`Row`]s within [`SourceData`].
1589///
1590/// This type exists as a wrapper around [`RowColumnarEncoder`] to support
1591/// encoding empty [`Row`]s. A [`RowColumnarEncoder`] finishes as a
1592/// [`StructArray`] which is required to have at least one column, and thus
1593/// cannot support empty [`Row`]s.
1594#[derive(Debug)]
1595pub enum SourceDataRowColumnarEncoder {
1596    Row(RowColumnarEncoder),
1597    EmptyRow,
1598}
1599
1600impl SourceDataRowColumnarEncoder {
1601    pub(crate) fn goodbytes(&self) -> usize {
1602        match self {
1603            SourceDataRowColumnarEncoder::Row(e) => e.goodbytes(),
1604            SourceDataRowColumnarEncoder::EmptyRow => 0,
1605        }
1606    }
1607
1608    pub fn append(&mut self, row: &Row) {
1609        match self {
1610            SourceDataRowColumnarEncoder::Row(encoder) => encoder.append(row),
1611            SourceDataRowColumnarEncoder::EmptyRow => {
1612                assert_eq!(row.iter().count(), 0)
1613            }
1614        }
1615    }
1616
1617    pub fn append_null(&mut self) {
1618        match self {
1619            SourceDataRowColumnarEncoder::Row(encoder) => encoder.append_null(),
1620            SourceDataRowColumnarEncoder::EmptyRow => (),
1621        }
1622    }
1623}
1624
1625#[derive(Debug)]
1626pub struct SourceDataColumnarEncoder {
1627    row_encoder: SourceDataRowColumnarEncoder,
1628    err_encoder: BinaryBuilder,
1629}
1630
1631impl SourceDataColumnarEncoder {
1632    const OK_COLUMN_NAME: &'static str = "ok";
1633    const ERR_COLUMN_NAME: &'static str = "err";
1634
1635    pub fn new(desc: &RelationDesc) -> Self {
1636        let row_encoder = match RowColumnarEncoder::new(desc) {
1637            Some(encoder) => SourceDataRowColumnarEncoder::Row(encoder),
1638            None => {
1639                assert!(desc.typ().columns().is_empty());
1640                SourceDataRowColumnarEncoder::EmptyRow
1641            }
1642        };
1643        let err_encoder = BinaryBuilder::new();
1644
1645        SourceDataColumnarEncoder {
1646            row_encoder,
1647            err_encoder,
1648        }
1649    }
1650}
1651
1652impl ColumnEncoder<SourceData> for SourceDataColumnarEncoder {
1653    type FinishedColumn = StructArray;
1654
1655    fn goodbytes(&self) -> usize {
1656        self.row_encoder.goodbytes() + self.err_encoder.values_slice().len()
1657    }
1658
1659    #[inline]
1660    fn append(&mut self, val: &SourceData) {
1661        match val.0.as_ref() {
1662            Ok(row) => {
1663                self.row_encoder.append(row);
1664                self.err_encoder.append_null();
1665            }
1666            Err(err) => {
1667                self.row_encoder.append_null();
1668                self.err_encoder
1669                    .append_value(err.into_proto().encode_to_vec());
1670            }
1671        }
1672    }
1673
1674    #[inline]
1675    fn append_null(&mut self) {
1676        panic!("appending a null into SourceDataColumnarEncoder is not supported");
1677    }
1678
1679    fn finish(self) -> Self::FinishedColumn {
1680        let SourceDataColumnarEncoder {
1681            row_encoder,
1682            mut err_encoder,
1683        } = self;
1684
1685        let err_column = BinaryBuilder::finish(&mut err_encoder);
1686        let row_column: ArrayRef = match row_encoder {
1687            SourceDataRowColumnarEncoder::Row(encoder) => {
1688                let column = encoder.finish();
1689                Arc::new(column)
1690            }
1691            SourceDataRowColumnarEncoder::EmptyRow => Arc::new(NullArray::new(err_column.len())),
1692        };
1693
1694        assert_eq!(row_column.len(), err_column.len());
1695
1696        let fields = vec![
1697            Field::new(Self::OK_COLUMN_NAME, row_column.data_type().clone(), true),
1698            Field::new(Self::ERR_COLUMN_NAME, err_column.data_type().clone(), true),
1699        ];
1700        let arrays: Vec<Arc<dyn Array>> = vec![row_column, Arc::new(err_column)];
1701        StructArray::new(Fields::from(fields), arrays, None)
1702    }
1703}
1704
1705impl Schema<SourceData> for RelationDesc {
1706    type ArrowColumn = StructArray;
1707    type Statistics = StructStats;
1708
1709    type Decoder = SourceDataColumnarDecoder;
1710    type Encoder = SourceDataColumnarEncoder;
1711
1712    fn decoder(&self, col: Self::ArrowColumn) -> Result<Self::Decoder, anyhow::Error> {
1713        SourceDataColumnarDecoder::new(col, self)
1714    }
1715
1716    fn encoder(&self) -> Result<Self::Encoder, anyhow::Error> {
1717        Ok(SourceDataColumnarEncoder::new(self))
1718    }
1719}
1720
1721#[cfg(test)]
1722mod tests {
1723    use arrow::array::{ArrayData, make_comparator};
1724    use base64::Engine;
1725    use bytes::Bytes;
1726    use mz_expr::EvalError;
1727    use mz_ore::assert_err;
1728    use mz_ore::metrics::MetricsRegistry;
1729    use mz_persist::indexed::columnar::arrow::{realloc_any, realloc_array};
1730    use mz_persist::metrics::ColumnarMetrics;
1731    use mz_persist_types::parquet::EncodingConfig;
1732    use mz_persist_types::schema::{Migration, backward_compatible};
1733    use mz_persist_types::stats::{PartStats, PartStatsMetrics};
1734    use mz_repr::{
1735        ColumnIndex, DatumVec, PropRelationDescDiff, ProtoRelationDesc, RelationDescBuilder,
1736        RowArena, SqlScalarType, arb_relation_desc_diff, arb_relation_desc_projection,
1737    };
1738    use proptest::prelude::*;
1739    use proptest::strategy::{Union, ValueTree};
1740
1741    use crate::stats::RelationPartStats;
1742
1743    use super::*;
1744
1745    #[mz_ore::test]
1746    fn test_timeline_parsing() {
1747        assert_eq!(Ok(Timeline::EpochMilliseconds), "M".parse());
1748        assert_eq!(Ok(Timeline::External("JOE".to_string())), "E.JOE".parse());
1749        assert_eq!(Ok(Timeline::User("MIKE".to_string())), "U.MIKE".parse());
1750
1751        assert_err!("Materialize".parse::<Timeline>());
1752        assert_err!("Ejoe".parse::<Timeline>());
1753        assert_err!("Umike".parse::<Timeline>());
1754        assert_err!("Dance".parse::<Timeline>());
1755        assert_err!("".parse::<Timeline>());
1756    }
1757
1758    #[track_caller]
1759    fn roundtrip_source_data(
1760        desc: &RelationDesc,
1761        datas: Vec<SourceData>,
1762        read_desc: &RelationDesc,
1763        config: &EncodingConfig,
1764    ) {
1765        let metrics = ColumnarMetrics::disconnected();
1766        let mut encoder = <RelationDesc as Schema<SourceData>>::encoder(desc).unwrap();
1767        for data in &datas {
1768            encoder.append(data);
1769        }
1770        let col = encoder.finish();
1771
1772        // The top-level StructArray for SourceData should always be non-nullable.
1773        assert!(!col.is_nullable());
1774
1775        // Reallocate our arrays with lgalloc.
1776        let col = realloc_array(&col, &metrics);
1777
1778        // Roundtrip through ProtoArray format.
1779        {
1780            let proto = col.to_data().into_proto();
1781            let bytes = proto.encode_to_vec();
1782            let proto = mz_persist_types::arrow::ProtoArrayData::decode(&bytes[..]).unwrap();
1783            let array_data: ArrayData = proto.into_rust().unwrap();
1784
1785            let col_rnd = StructArray::from(array_data.clone());
1786            assert_eq!(col, col_rnd);
1787
1788            let col_dyn = arrow::array::make_array(array_data);
1789            let col_dyn = col_dyn.as_any().downcast_ref::<StructArray>().unwrap();
1790            assert_eq!(&col, col_dyn);
1791        }
1792
1793        // Encode to Parquet.
1794        let mut buf = Vec::new();
1795        let fields = Fields::from(vec![Field::new("k", col.data_type().clone(), false)]);
1796        let arrays: Vec<Arc<dyn Array>> = vec![Arc::new(col.clone())];
1797        mz_persist_types::parquet::encode_arrays(&mut buf, fields, arrays, config).unwrap();
1798
1799        // Decode from Parquet.
1800        let buf = Bytes::from(buf);
1801        let mut reader = mz_persist_types::parquet::decode_arrays(buf).unwrap();
1802        let maybe_batch = reader.next();
1803
1804        // If we didn't encode any data then our record_batch will be empty.
1805        let Some(record_batch) = maybe_batch else {
1806            assert!(datas.is_empty());
1807            return;
1808        };
1809        let record_batch = record_batch.unwrap();
1810
1811        assert_eq!(record_batch.columns().len(), 1);
1812        let rnd_col = &record_batch.columns()[0];
1813        let rnd_col = realloc_any(Arc::clone(rnd_col), &metrics);
1814        let rnd_col = rnd_col
1815            .as_any()
1816            .downcast_ref::<StructArray>()
1817            .unwrap()
1818            .clone();
1819
1820        // Try generating stats for the data, just to make sure we don't panic.
1821        let stats = <RelationDesc as Schema<SourceData>>::decoder_any(desc, &rnd_col)
1822            .expect("valid decoder")
1823            .stats();
1824
1825        // Read back all of our data and assert it roundtrips.
1826        let mut rnd_data = SourceData(Ok(Row::default()));
1827        let decoder = <RelationDesc as Schema<SourceData>>::decoder(desc, rnd_col.clone()).unwrap();
1828        for (idx, og_data) in datas.iter().enumerate() {
1829            decoder.decode(idx, &mut rnd_data);
1830            assert_eq!(og_data, &rnd_data);
1831        }
1832
1833        // Read back all of our data a second time with a projection applied, and make sure the
1834        // stats are valid.
1835        let stats_metrics = PartStatsMetrics::new(&MetricsRegistry::new());
1836        let stats = RelationPartStats {
1837            name: "test",
1838            metrics: &stats_metrics,
1839            stats: &PartStats { key: stats },
1840            desc: read_desc,
1841        };
1842        let mut datum_vec = DatumVec::new();
1843        let arena = RowArena::default();
1844        let decoder = <RelationDesc as Schema<SourceData>>::decoder(read_desc, rnd_col).unwrap();
1845
1846        for (idx, og_data) in datas.iter().enumerate() {
1847            decoder.decode(idx, &mut rnd_data);
1848            match (&og_data.0, &rnd_data.0) {
1849                (Ok(og_row), Ok(rnd_row)) => {
1850                    // Filter down to just the Datums in the projection schema.
1851                    {
1852                        let datums = datum_vec.borrow_with(og_row);
1853                        let projected_datums =
1854                            datums.iter().enumerate().filter_map(|(idx, datum)| {
1855                                read_desc
1856                                    .contains_index(&ColumnIndex::from_raw(idx))
1857                                    .then_some(datum)
1858                            });
1859                        let og_projected_row = Row::pack(projected_datums);
1860                        assert_eq!(&og_projected_row, rnd_row);
1861                    }
1862
1863                    // Validate the stats for all of our projected columns.
1864                    {
1865                        let proj_datums = datum_vec.borrow_with(rnd_row);
1866                        for (pos, (idx, _, _)) in read_desc.iter_all().enumerate() {
1867                            let spec = stats.col_stats(idx, &arena);
1868                            assert!(spec.may_contain(proj_datums[pos]));
1869                        }
1870                    }
1871                }
1872                (Err(_), Err(_)) => assert_eq!(og_data, &rnd_data),
1873                (_, _) => panic!("decoded to a different type? {og_data:?} {rnd_data:?}"),
1874            }
1875        }
1876
1877        // Verify that the RelationDesc itself roundtrips through
1878        // {encode,decode}_schema.
1879        let encoded_schema = SourceData::encode_schema(desc);
1880        let roundtrip_desc = SourceData::decode_schema(&encoded_schema);
1881        assert_eq!(desc, &roundtrip_desc);
1882
1883        // Verify that the RelationDesc is backward compatible with itself (this
1884        // mostly checks for `unimplemented!` type panics).
1885        let migration =
1886            mz_persist_types::schema::backward_compatible(col.data_type(), col.data_type());
1887        let migration = migration.expect("should be backward compatible with self");
1888        // Also verify that the Fn doesn't do anything wonky.
1889        let migrated = migration.migrate(Arc::new(col.clone()));
1890        assert_eq!(col.data_type(), migrated.data_type());
1891    }
1892
1893    #[mz_ore::test]
1894    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `decContextDefault` on OS `linux`
1895    fn all_source_data_roundtrips() {
1896        let mut weights = vec![(500, Just(0..8)), (50, Just(8..32))];
1897        if std::env::var("PROPTEST_LARGE_DATA").is_ok() {
1898            weights.extend([
1899                (10, Just(32..128)),
1900                (5, Just(128..512)),
1901                (3, Just(512..2048)),
1902                (1, Just(2048..8192)),
1903            ]);
1904        }
1905        let num_rows = Union::new_weighted(weights);
1906
1907        // TODO(parkmycar): There are so many clones going on here, and maybe we can avoid them?
1908        let strat = (any::<RelationDesc>(), num_rows)
1909            .prop_flat_map(|(desc, num_rows)| {
1910                arb_relation_desc_projection(desc.clone())
1911                    .prop_map(move |read_desc| (desc.clone(), read_desc, num_rows.clone()))
1912            })
1913            .prop_flat_map(|(desc, read_desc, num_rows)| {
1914                proptest::collection::vec(arb_source_data_for_relation_desc(&desc), num_rows)
1915                    .prop_map(move |datas| (desc.clone(), datas, read_desc.clone()))
1916            });
1917
1918        let combined_strat = (any::<EncodingConfig>(), strat);
1919        proptest!(|((config, (desc, source_datas, read_desc)) in combined_strat)| {
1920            roundtrip_source_data(&desc, source_datas, &read_desc, &config);
1921        });
1922    }
1923
1924    #[mz_ore::test]
1925    fn roundtrip_error_nulls() {
1926        let desc = RelationDescBuilder::default()
1927            .with_column(
1928                "ts",
1929                SqlScalarType::TimestampTz { precision: None }.nullable(false),
1930            )
1931            .finish();
1932        let source_datas = vec![SourceData(Err(DataflowError::EvalError(
1933            EvalError::DateOutOfRange.into(),
1934        )))];
1935        let config = EncodingConfig::default();
1936        roundtrip_source_data(&desc, source_datas, &desc, &config);
1937    }
1938
1939    fn is_sorted(array: &dyn Array) -> bool {
1940        let sort_options = arrow::compute::SortOptions::default();
1941        let Ok(cmp) = make_comparator(array, array, sort_options) else {
1942            // TODO: arrow v51.0.0 doesn't support comparing structs. When
1943            // we migrate to v52+, the `build_compare` function is
1944            // deprecated and replaced by `make_comparator`, which does
1945            // support structs. At which point, this will work (and we
1946            // should switch this early return to an expect, if possible).
1947            return false;
1948        };
1949        (0..array.len())
1950            .tuple_windows()
1951            .all(|(i, j)| cmp(i, j).is_le())
1952    }
1953
1954    fn get_data_type(schema: &impl Schema<SourceData>) -> arrow::datatypes::DataType {
1955        use mz_persist_types::columnar::ColumnEncoder;
1956        let array = Schema::encoder(schema).expect("valid schema").finish();
1957        Array::data_type(&array).clone()
1958    }
1959
1960    #[track_caller]
1961    fn backward_compatible_testcase(
1962        old: &RelationDesc,
1963        new: &RelationDesc,
1964        migration: Migration,
1965        datas: &[SourceData],
1966    ) {
1967        let mut encoder = Schema::<SourceData>::encoder(old).expect("valid schema");
1968        for data in datas {
1969            encoder.append(data);
1970        }
1971        let old = encoder.finish();
1972        let new = Schema::<SourceData>::encoder(new)
1973            .expect("valid schema")
1974            .finish();
1975        let old: Arc<dyn Array> = Arc::new(old);
1976        let new: Arc<dyn Array> = Arc::new(new);
1977        let migrated = migration.migrate(Arc::clone(&old));
1978        assert_eq!(migrated.data_type(), new.data_type());
1979
1980        // Check the sortedness preservation, if we can.
1981        if migration.preserves_order() && is_sorted(&old) {
1982            assert!(is_sorted(&new))
1983        }
1984    }
1985
1986    #[mz_ore::test]
1987    fn backward_compatible_empty_add_column() {
1988        let old = RelationDesc::empty();
1989        let new = RelationDesc::from_names_and_types([("a", SqlScalarType::Bool.nullable(true))]);
1990
1991        let old_data_type = get_data_type(&old);
1992        let new_data_type = get_data_type(&new);
1993
1994        let migration = backward_compatible(&old_data_type, &new_data_type);
1995        assert!(migration.is_some());
1996    }
1997
1998    #[mz_ore::test]
1999    fn backward_compatible_project_away_all() {
2000        let old = RelationDesc::from_names_and_types([("a", SqlScalarType::Bool.nullable(true))]);
2001        let new = RelationDesc::empty();
2002
2003        let old_data_type = get_data_type(&old);
2004        let new_data_type = get_data_type(&new);
2005
2006        let migration = backward_compatible(&old_data_type, &new_data_type);
2007        assert!(migration.is_some());
2008    }
2009
2010    #[mz_ore::test]
2011    #[cfg_attr(miri, ignore)]
2012    fn backward_compatible_migrate() {
2013        let strat = (any::<RelationDesc>(), any::<RelationDesc>()).prop_flat_map(|(old, new)| {
2014            proptest::collection::vec(arb_source_data_for_relation_desc(&old), 2)
2015                .prop_map(move |datas| (old.clone(), new.clone(), datas))
2016        });
2017
2018        proptest!(|((old, new, datas) in strat)| {
2019            let old_data_type = get_data_type(&old);
2020            let new_data_type = get_data_type(&new);
2021
2022            if let Some(migration) = backward_compatible(&old_data_type, &new_data_type) {
2023                backward_compatible_testcase(&old, &new, migration, &datas);
2024            };
2025        });
2026    }
2027
2028    #[mz_ore::test]
2029    #[cfg_attr(miri, ignore)]
2030    fn backward_compatible_migrate_from_common() {
2031        use mz_repr::SqlColumnType;
2032        fn test_case(old: RelationDesc, diffs: Vec<PropRelationDescDiff>, datas: Vec<SourceData>) {
2033            // TODO(parkmycar): As we iterate on schema migrations more things should become compatible.
2034            let should_be_compatible = diffs.iter().all(|diff| match diff {
2035                // We only support adding nullable columns.
2036                PropRelationDescDiff::AddColumn {
2037                    typ: SqlColumnType { nullable, .. },
2038                    ..
2039                } => *nullable,
2040                PropRelationDescDiff::DropColumn { .. } => true,
2041                _ => false,
2042            });
2043
2044            let mut new = old.clone();
2045            for diff in diffs.into_iter() {
2046                diff.apply(&mut new)
2047            }
2048
2049            let old_data_type = get_data_type(&old);
2050            let new_data_type = get_data_type(&new);
2051
2052            if let Some(migration) = backward_compatible(&old_data_type, &new_data_type) {
2053                backward_compatible_testcase(&old, &new, migration, &datas);
2054            } else if should_be_compatible {
2055                panic!("new DataType was not compatible when it should have been!");
2056            }
2057        }
2058
2059        let strat = any::<RelationDesc>()
2060            .prop_flat_map(|desc| {
2061                proptest::collection::vec(arb_source_data_for_relation_desc(&desc), 2)
2062                    .no_shrink()
2063                    .prop_map(move |datas| (desc.clone(), datas))
2064            })
2065            .prop_flat_map(|(desc, datas)| {
2066                arb_relation_desc_diff(&desc)
2067                    .prop_map(move |diffs| (desc.clone(), diffs, datas.clone()))
2068            });
2069
2070        proptest!(|((old, diffs, datas) in strat)| {
2071            test_case(old, diffs, datas);
2072        });
2073    }
2074
2075    #[mz_ore::test]
2076    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `decContextDefault` on OS `linux`
2077    fn empty_relation_desc_roundtrips() {
2078        let empty = RelationDesc::empty();
2079        let rows = proptest::collection::vec(arb_source_data_for_relation_desc(&empty), 0..8)
2080            .prop_map(move |datas| (empty.clone(), datas));
2081
2082        // Note: This case should be covered by the `all_source_data_roundtrips` test above, but
2083        // it's a special case that we explicitly want to exercise.
2084        proptest!(|((config, (desc, source_datas)) in (any::<EncodingConfig>(), rows))| {
2085            roundtrip_source_data(&desc, source_datas, &desc, &config);
2086        });
2087    }
2088
2089    #[mz_ore::test]
2090    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `decContextDefault` on OS `linux`
2091    fn arrow_datatype_consistent() {
2092        fn test_case(desc: RelationDesc, datas: Vec<SourceData>) {
2093            let half = datas.len() / 2;
2094
2095            let mut encoder_a = <RelationDesc as Schema<SourceData>>::encoder(&desc).unwrap();
2096            for data in &datas[..half] {
2097                encoder_a.append(data);
2098            }
2099            let col_a = encoder_a.finish();
2100
2101            let mut encoder_b = <RelationDesc as Schema<SourceData>>::encoder(&desc).unwrap();
2102            for data in &datas[half..] {
2103                encoder_b.append(data);
2104            }
2105            let col_b = encoder_b.finish();
2106
2107            // The DataType of the resulting column should not change based on what data was
2108            // encoded.
2109            assert_eq!(col_a.data_type(), col_b.data_type());
2110        }
2111
2112        let num_rows = 12;
2113        let strat = any::<RelationDesc>().prop_flat_map(|desc| {
2114            proptest::collection::vec(arb_source_data_for_relation_desc(&desc), num_rows)
2115                .prop_map(move |datas| (desc.clone(), datas))
2116        });
2117
2118        proptest!(|((desc, data) in strat)| {
2119            test_case(desc, data);
2120        });
2121    }
2122
2123    #[mz_ore::test]
2124    #[cfg_attr(miri, ignore)] // too slow
2125    fn source_proto_serialization_stability() {
2126        let min_protos = 10;
2127        let encoded = include_str!("snapshots/source-datas.txt");
2128
2129        // Decode the pre-generated source datas
2130        let mut decoded: Vec<(RelationDesc, SourceData)> = encoded
2131            .lines()
2132            .map(|s| {
2133                let (desc, data) = s.split_once(',').expect("comma separated data");
2134                let desc = base64::engine::general_purpose::STANDARD
2135                    .decode(desc)
2136                    .expect("valid base64");
2137                let data = base64::engine::general_purpose::STANDARD
2138                    .decode(data)
2139                    .expect("valid base64");
2140                (desc, data)
2141            })
2142            .map(|(desc, data)| {
2143                let desc = ProtoRelationDesc::decode(&desc[..]).expect("valid proto");
2144                let desc = desc.into_rust().expect("valid proto");
2145                let data = SourceData::decode(&data, &desc).expect("valid proto");
2146                (desc, data)
2147            })
2148            .collect();
2149
2150        // If there are fewer than the minimum examples, generate some new ones arbitrarily
2151        let mut runner = proptest::test_runner::TestRunner::deterministic();
2152        let strategy = RelationDesc::arbitrary().prop_flat_map(|desc| {
2153            arb_source_data_for_relation_desc(&desc).prop_map(move |data| (desc.clone(), data))
2154        });
2155        while decoded.len() < min_protos {
2156            let arbitrary_data = strategy
2157                .new_tree(&mut runner)
2158                .expect("source data")
2159                .current();
2160            decoded.push(arbitrary_data);
2161        }
2162
2163        // Reencode and compare the strings
2164        let mut reencoded = String::new();
2165        let mut buf = vec![];
2166        for (desc, data) in decoded {
2167            buf.clear();
2168            desc.into_proto().encode(&mut buf).expect("success");
2169            base64::engine::general_purpose::STANDARD.encode_string(buf.as_slice(), &mut reencoded);
2170            reencoded.push(',');
2171
2172            buf.clear();
2173            data.encode(&mut buf);
2174            base64::engine::general_purpose::STANDARD.encode_string(buf.as_slice(), &mut reencoded);
2175            reencoded.push('\n');
2176        }
2177
2178        // Optimizations in Persist, particularly consolidation on read,
2179        // depend on a stable serialization for the serialized data.
2180        // For example, reordering proto fields could cause us
2181        // to generate a different (equivalent) serialization for a record,
2182        // and the two versions would not consolidate out.
2183        // This can impact correctness!
2184        //
2185        // If you need to change how SourceDatas are encoded, that's still fine...
2186        // but we'll also need to increase
2187        // the MINIMUM_CONSOLIDATED_VERSION as part of the same release.
2188        assert_eq!(
2189            encoded,
2190            reencoded.as_str(),
2191            "SourceData serde should be stable"
2192        )
2193    }
2194}