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.
911#[derive(Debug, Eq, PartialEq)]
912pub enum SourceExportStatementDetails {
913    Postgres {
914        table: mz_postgres_util::desc::PostgresTableDesc,
915        /// Whether the text-to-oid cast for this export accepts the full `u32`
916        /// range. Exports created before the cast was widened decode as
917        /// `false` and must keep the legacy `i32`-range cast forever, because
918        /// replication re-casts old tuples on delete and the persisted rows
919        /// were ingested under the legacy semantics.
920        cast_oid_full_range: bool,
921    },
922    MySql {
923        table: mz_mysql_util::MySqlTableDesc,
924        initial_gtid_set: String,
925        binlog_full_metadata: bool,
926    },
927    SqlServer {
928        table: mz_sql_server_util::desc::SqlServerTableDesc,
929        capture_instance: Arc<str>,
930        initial_lsn: mz_sql_server_util::cdc::Lsn,
931    },
932    LoadGenerator {
933        output: LoadGeneratorOutput,
934    },
935    Kafka {},
936}
937
938impl RustType<ProtoSourceExportStatementDetails> for SourceExportStatementDetails {
939    fn into_proto(&self) -> ProtoSourceExportStatementDetails {
940        match self {
941            SourceExportStatementDetails::Postgres {
942                table,
943                cast_oid_full_range,
944            } => ProtoSourceExportStatementDetails {
945                kind: Some(proto_source_export_statement_details::Kind::Postgres(
946                    postgres::ProtoPostgresSourceExportStatementDetails {
947                        table: Some(table.into_proto()),
948                        cast_oid_full_range: *cast_oid_full_range,
949                    },
950                )),
951            },
952            SourceExportStatementDetails::MySql {
953                table,
954                initial_gtid_set,
955                binlog_full_metadata,
956            } => ProtoSourceExportStatementDetails {
957                kind: Some(proto_source_export_statement_details::Kind::Mysql(
958                    mysql::ProtoMySqlSourceExportStatementDetails {
959                        table: Some(table.into_proto()),
960                        initial_gtid_set: initial_gtid_set.clone(),
961                        binlog_full_metadata: *binlog_full_metadata,
962                    },
963                )),
964            },
965            SourceExportStatementDetails::SqlServer {
966                table,
967                capture_instance,
968                initial_lsn,
969            } => ProtoSourceExportStatementDetails {
970                kind: Some(proto_source_export_statement_details::Kind::SqlServer(
971                    sql_server::ProtoSqlServerSourceExportStatementDetails {
972                        table: Some(table.into_proto()),
973                        capture_instance: capture_instance.to_string(),
974                        initial_lsn: initial_lsn.as_bytes().to_vec(),
975                    },
976                )),
977            },
978            SourceExportStatementDetails::LoadGenerator { output } => {
979                ProtoSourceExportStatementDetails {
980                    kind: Some(proto_source_export_statement_details::Kind::Loadgen(
981                        load_generator::ProtoLoadGeneratorSourceExportStatementDetails {
982                            output: output.into_proto().into(),
983                        },
984                    )),
985                }
986            }
987            SourceExportStatementDetails::Kafka {} => ProtoSourceExportStatementDetails {
988                kind: Some(proto_source_export_statement_details::Kind::Kafka(
989                    kafka::ProtoKafkaSourceExportStatementDetails {},
990                )),
991            },
992        }
993    }
994
995    fn from_proto(proto: ProtoSourceExportStatementDetails) -> Result<Self, TryFromProtoError> {
996        use proto_source_export_statement_details::Kind;
997        Ok(match proto.kind {
998            Some(Kind::Postgres(details)) => SourceExportStatementDetails::Postgres {
999                table: details
1000                    .table
1001                    .into_rust_if_some("ProtoPostgresSourceExportStatementDetails::table")?,
1002                cast_oid_full_range: details.cast_oid_full_range,
1003            },
1004            Some(Kind::Mysql(details)) => SourceExportStatementDetails::MySql {
1005                table: details
1006                    .table
1007                    .into_rust_if_some("ProtoMySqlSourceExportStatementDetails::table")?,
1008
1009                initial_gtid_set: details.initial_gtid_set,
1010                binlog_full_metadata: details.binlog_full_metadata,
1011            },
1012            Some(Kind::SqlServer(details)) => SourceExportStatementDetails::SqlServer {
1013                table: details
1014                    .table
1015                    .into_rust_if_some("ProtoSqlServerSourceExportStatementDetails::table")?,
1016                capture_instance: details.capture_instance.into(),
1017                initial_lsn: mz_sql_server_util::cdc::Lsn::try_from(details.initial_lsn.as_slice())
1018                    .map_err(|e| TryFromProtoError::InvalidFieldError(e.to_string()))?,
1019            },
1020            Some(Kind::Loadgen(details)) => SourceExportStatementDetails::LoadGenerator {
1021                output: details
1022                    .output
1023                    .into_rust_if_some("ProtoLoadGeneratorSourceExportStatementDetails::output")?,
1024            },
1025            Some(Kind::Kafka(_details)) => SourceExportStatementDetails::Kafka {},
1026            None => {
1027                return Err(TryFromProtoError::missing_field(
1028                    "ProtoSourceExportStatementDetails::kind",
1029                ));
1030            }
1031        })
1032    }
1033}
1034
1035#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1036#[repr(transparent)]
1037pub struct SourceData(pub Result<Row, DataflowError>);
1038
1039impl Default for SourceData {
1040    fn default() -> Self {
1041        SourceData(Ok(Row::default()))
1042    }
1043}
1044
1045impl Deref for SourceData {
1046    type Target = Result<Row, DataflowError>;
1047
1048    fn deref(&self) -> &Self::Target {
1049        &self.0
1050    }
1051}
1052
1053impl DerefMut for SourceData {
1054    fn deref_mut(&mut self) -> &mut Self::Target {
1055        &mut self.0
1056    }
1057}
1058
1059impl RustType<ProtoSourceData> for SourceData {
1060    fn into_proto(&self) -> ProtoSourceData {
1061        use proto_source_data::Kind;
1062        ProtoSourceData {
1063            kind: Some(match &**self {
1064                Ok(row) => Kind::Ok(row.into_proto()),
1065                Err(err) => Kind::Err(err.into_proto()),
1066            }),
1067        }
1068    }
1069
1070    fn from_proto(proto: ProtoSourceData) -> Result<Self, TryFromProtoError> {
1071        use proto_source_data::Kind;
1072        match proto.kind {
1073            Some(kind) => match kind {
1074                Kind::Ok(row) => Ok(SourceData(Ok(row.into_rust()?))),
1075                Kind::Err(err) => Ok(SourceData(Err(err.into_rust()?))),
1076            },
1077            None => Result::Err(TryFromProtoError::missing_field("ProtoSourceData::kind")),
1078        }
1079    }
1080}
1081
1082impl Codec for SourceData {
1083    type Storage = ProtoRow;
1084    type Schema = RelationDesc;
1085
1086    fn codec_name() -> String {
1087        "protobuf[SourceData]".into()
1088    }
1089
1090    fn encode<B: BufMut>(&self, buf: &mut B) {
1091        self.into_proto()
1092            .encode(buf)
1093            .expect("no required fields means no initialization errors");
1094    }
1095
1096    fn decode(buf: &[u8], schema: &RelationDesc) -> Result<Self, String> {
1097        let mut val = SourceData::default();
1098        <Self as Codec>::decode_from(&mut val, buf, &mut None, schema)?;
1099        Ok(val)
1100    }
1101
1102    fn decode_from<'a>(
1103        &mut self,
1104        buf: &'a [u8],
1105        storage: &mut Option<ProtoRow>,
1106        schema: &RelationDesc,
1107    ) -> Result<(), String> {
1108        // Optimize for common case of `Ok` by leaving a (cleared) `ProtoRow` in
1109        // the `Ok` variant of `ProtoSourceData`. prost's `Message::merge` impl
1110        // is smart about reusing the `Vec<Datum>` when it can.
1111        let mut proto = storage.take().unwrap_or_default();
1112        proto.clear();
1113        let mut proto = ProtoSourceData {
1114            kind: Some(proto_source_data::Kind::Ok(proto)),
1115        };
1116        proto.merge(buf).map_err(|err| err.to_string())?;
1117        match (proto.kind, &mut self.0) {
1118            // Again, optimize for the common case...
1119            (Some(proto_source_data::Kind::Ok(proto)), Ok(row)) => {
1120                let ret = row.decode_from_proto(&proto, schema);
1121                storage.replace(proto);
1122                ret
1123            }
1124            // ...otherwise fall back to the obvious thing.
1125            (kind, _) => {
1126                let proto = ProtoSourceData { kind };
1127                *self = proto.into_rust().map_err(|err| err.to_string())?;
1128                // Nothing to put back in storage.
1129                Ok(())
1130            }
1131        }
1132    }
1133
1134    fn validate(val: &Self, desc: &Self::Schema) -> Result<(), String> {
1135        match &val.0 {
1136            Ok(row) => Row::validate(row, desc),
1137            Err(_) => Ok(()),
1138        }
1139    }
1140
1141    fn encode_schema(schema: &Self::Schema) -> Bytes {
1142        schema.into_proto().encode_to_vec().into()
1143    }
1144
1145    fn decode_schema(buf: &Bytes) -> Self::Schema {
1146        let proto = ProtoRelationDesc::decode(buf.as_ref()).expect("valid schema");
1147        proto.into_rust().expect("valid schema")
1148    }
1149}
1150
1151/// Given a [`RelationDesc`] returns an arbitrary [`SourceData`].
1152#[cfg(any(test, feature = "proptest"))]
1153pub fn arb_source_data_for_relation_desc(
1154    desc: &RelationDesc,
1155) -> impl Strategy<Value = SourceData> + use<> {
1156    let row_strat = arb_row_for_relation(desc).no_shrink();
1157
1158    proptest::strategy::Union::new_weighted(vec![
1159        (50, row_strat.prop_map(|row| SourceData(Ok(row))).boxed()),
1160        (
1161            1,
1162            any::<DataflowError>()
1163                .prop_map(|err| SourceData(Err(err)))
1164                .no_shrink()
1165                .boxed(),
1166        ),
1167    ])
1168}
1169
1170/// Describes how external references should be organized in a multi-level
1171/// hierarchy.
1172///
1173/// For both PostgreSQL and MySQL sources, these levels of reference are
1174/// intrinsic to the items which we're referencing. If there are other naming
1175/// schemas for other types of sources we discover, we might need to revisit
1176/// this.
1177pub trait ExternalCatalogReference {
1178    /// The "second" level of namespacing for the reference.
1179    fn schema_name(&self) -> &str;
1180    /// The lowest level of namespacing for the reference.
1181    fn item_name(&self) -> &str;
1182}
1183
1184impl ExternalCatalogReference for &mz_mysql_util::MySqlTableDesc {
1185    fn schema_name(&self) -> &str {
1186        &self.schema_name
1187    }
1188
1189    fn item_name(&self) -> &str {
1190        &self.name
1191    }
1192}
1193
1194impl ExternalCatalogReference for mz_postgres_util::desc::PostgresTableDesc {
1195    fn schema_name(&self) -> &str {
1196        &self.namespace
1197    }
1198
1199    fn item_name(&self) -> &str {
1200        &self.name
1201    }
1202}
1203
1204impl ExternalCatalogReference for &mz_sql_server_util::desc::SqlServerTableDesc {
1205    fn schema_name(&self) -> &str {
1206        &*self.schema_name
1207    }
1208
1209    fn item_name(&self) -> &str {
1210        &*self.name
1211    }
1212}
1213
1214// This implementation provides a means of converting arbitrary objects into a
1215// `SubsourceCatalogReference`, e.g. load generator view names.
1216impl<'a> ExternalCatalogReference for (&'a str, &'a str) {
1217    fn schema_name(&self) -> &str {
1218        self.0
1219    }
1220
1221    fn item_name(&self) -> &str {
1222        self.1
1223    }
1224}
1225
1226/// Stores and resolves references to a `&[T: ExternalCatalogReference]`.
1227///
1228/// This is meant to provide an API to quickly look up a source's subsources.
1229///
1230/// For sources that do not provide any subsources, use the `Default`
1231/// implementation, which is empty and will not be able to resolve any
1232/// references.
1233#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1234pub struct SourceReferenceResolver {
1235    inner: BTreeMap<Ident, BTreeMap<Ident, BTreeMap<Ident, usize>>>,
1236}
1237
1238#[derive(Debug, Clone, thiserror::Error)]
1239pub enum ExternalReferenceResolutionError {
1240    #[error("reference to {name} not found in source")]
1241    DoesNotExist { name: String },
1242    #[error(
1243        "reference {name} is ambiguous, consider specifying an additional \
1244    layer of qualification"
1245    )]
1246    Ambiguous { name: String },
1247    #[error("invalid identifier: {0}")]
1248    Ident(#[from] IdentError),
1249}
1250
1251impl<'a> SourceReferenceResolver {
1252    /// Constructs a new `SourceReferenceResolver` from a slice of `T:
1253    /// SubsourceCatalogReference`.
1254    ///
1255    /// # Errors
1256    /// - If any `&str` provided cannot be taken to an [`Ident`].
1257    pub fn new<T: ExternalCatalogReference>(
1258        database: &str,
1259        referenceable_items: &'a [T],
1260    ) -> Result<SourceReferenceResolver, ExternalReferenceResolutionError> {
1261        // An index from table name -> schema name -> database name -> index in
1262        // `referenceable_items`.
1263        let mut inner = BTreeMap::new();
1264
1265        let database = Ident::new(database)?;
1266
1267        for (reference_idx, item) in referenceable_items.iter().enumerate() {
1268            let item_name = Ident::new(item.item_name())?;
1269            let schema_name = Ident::new(item.schema_name())?;
1270
1271            inner
1272                .entry(item_name)
1273                .or_insert_with(BTreeMap::new)
1274                .entry(schema_name)
1275                .or_insert_with(BTreeMap::new)
1276                .entry(database.clone())
1277                .or_insert(reference_idx);
1278        }
1279
1280        Ok(SourceReferenceResolver { inner })
1281    }
1282
1283    /// Returns the canonical reference and index from which it originated in
1284    /// the `referenceable_items` provided to [`Self::new`].
1285    ///
1286    /// # Args
1287    /// - `name` is `&[Ident]` to let users provide the inner element of
1288    ///   [`UnresolvedItemName`].
1289    /// - `canonicalize_to_width` limits the number of elements in the returned
1290    ///   [`UnresolvedItemName`];this is useful if the source type requires
1291    ///   contriving database and schema names that a subsource should not
1292    ///   persist as its reference.
1293    ///
1294    /// # Errors
1295    /// - If `name` does not resolve to an item in `self.inner`.
1296    ///
1297    /// # Panics
1298    /// - If `canonicalize_to_width`` is not in `1..=3`.
1299    pub fn resolve(
1300        &self,
1301        name: &[Ident],
1302        canonicalize_to_width: usize,
1303    ) -> Result<(UnresolvedItemName, usize), ExternalReferenceResolutionError> {
1304        let (db, schema, idx) = self.resolve_inner(name)?;
1305
1306        let item = name.last().expect("must have provided at least 1 element");
1307
1308        let canonical_name = match canonicalize_to_width {
1309            1 => vec![item.clone()],
1310            2 => vec![schema.clone(), item.clone()],
1311            3 => vec![db.clone(), schema.clone(), item.clone()],
1312            o => panic!("canonicalize_to_width values must be 1..=3, but got {}", o),
1313        };
1314
1315        Ok((UnresolvedItemName(canonical_name), idx))
1316    }
1317
1318    /// Returns the index from which it originated in the `referenceable_items`
1319    /// provided to [`Self::new`].
1320    ///
1321    /// # Args
1322    /// `name` is `&[Ident]` to let users provide the inner element of
1323    /// [`UnresolvedItemName`].
1324    ///
1325    /// # Errors
1326    /// - If `name` does not resolve to an item in `self.inner`.
1327    pub fn resolve_idx(&self, name: &[Ident]) -> Result<usize, ExternalReferenceResolutionError> {
1328        let (_db, _schema, idx) = self.resolve_inner(name)?;
1329        Ok(idx)
1330    }
1331
1332    /// Returns the index from which it originated in the `referenceable_items`
1333    /// provided to [`Self::new`].
1334    ///
1335    /// # Args
1336    /// `name` is `&[Ident]` to let users provide the inner element of
1337    /// [`UnresolvedItemName`].
1338    ///
1339    /// # Return
1340    /// Returns a tuple whose elements are:
1341    /// 1. The "database"- or top-level namespace of the reference.
1342    /// 2. The "schema"- or second-level namespace of the reference.
1343    /// 3. The index to find the item in `referenceable_items` argument provided
1344    ///    to `SourceReferenceResolver::new`.
1345    ///
1346    /// # Errors
1347    /// - If `name` does not resolve to an item in `self.inner`.
1348    fn resolve_inner<'name: 'a>(
1349        &'a self,
1350        name: &'name [Ident],
1351    ) -> Result<(&'a Ident, &'a Ident, usize), ExternalReferenceResolutionError> {
1352        let get_provided_name = || UnresolvedItemName(name.to_vec()).to_string();
1353
1354        // Names must be composed of 1..=3 elements.
1355        if !(1..=3).contains(&name.len()) {
1356            Err(ExternalReferenceResolutionError::DoesNotExist {
1357                name: get_provided_name(),
1358            })?;
1359        }
1360
1361        // Fill on the leading elements with `None` if they aren't present.
1362        let mut names = std::iter::repeat(None)
1363            .take(3 - name.len())
1364            .chain(name.iter().map(Some));
1365
1366        let database = names.next().flatten();
1367        let schema = names.next().flatten();
1368        let item = names
1369            .next()
1370            .flatten()
1371            .expect("must have provided the item name");
1372
1373        assert_none!(names.next(), "expected a 3-element iterator");
1374
1375        let schemas =
1376            self.inner
1377                .get(item)
1378                .ok_or_else(|| ExternalReferenceResolutionError::DoesNotExist {
1379                    name: get_provided_name(),
1380                })?;
1381
1382        let schema = match schema {
1383            Some(schema) => schema,
1384            None => schemas.keys().exactly_one().map_err(|_e| {
1385                ExternalReferenceResolutionError::Ambiguous {
1386                    name: get_provided_name(),
1387                }
1388            })?,
1389        };
1390
1391        let databases =
1392            schemas
1393                .get(schema)
1394                .ok_or_else(|| ExternalReferenceResolutionError::DoesNotExist {
1395                    name: get_provided_name(),
1396                })?;
1397
1398        let database = match database {
1399            Some(database) => database,
1400            None => databases.keys().exactly_one().map_err(|_e| {
1401                ExternalReferenceResolutionError::Ambiguous {
1402                    name: get_provided_name(),
1403                }
1404            })?,
1405        };
1406
1407        let reference_idx = databases.get(database).ok_or_else(|| {
1408            ExternalReferenceResolutionError::DoesNotExist {
1409                name: get_provided_name(),
1410            }
1411        })?;
1412
1413        Ok((database, schema, *reference_idx))
1414    }
1415}
1416
1417/// A decoder for [`Row`]s within [`SourceData`].
1418///
1419/// This type exists as a wrapper around [`RowColumnarDecoder`] to handle the
1420/// case where the [`RelationDesc`] we're encoding with has no columns. See
1421/// [`SourceDataRowColumnarEncoder`] for more details.
1422#[derive(Debug)]
1423pub enum SourceDataRowColumnarDecoder {
1424    Row(RowColumnarDecoder),
1425    EmptyRow,
1426}
1427
1428impl SourceDataRowColumnarDecoder {
1429    pub fn decode(&self, idx: usize, row: &mut Row) {
1430        match self {
1431            SourceDataRowColumnarDecoder::Row(decoder) => decoder.decode(idx, row),
1432            SourceDataRowColumnarDecoder::EmptyRow => {
1433                // Create a packer just to clear the Row.
1434                row.packer();
1435            }
1436        }
1437    }
1438
1439    pub fn goodbytes(&self) -> usize {
1440        match self {
1441            SourceDataRowColumnarDecoder::Row(decoder) => decoder.goodbytes(),
1442            SourceDataRowColumnarDecoder::EmptyRow => 0,
1443        }
1444    }
1445}
1446
1447#[derive(Debug)]
1448pub struct SourceDataColumnarDecoder {
1449    row_decoder: SourceDataRowColumnarDecoder,
1450    err_decoder: BinaryArray,
1451}
1452
1453impl SourceDataColumnarDecoder {
1454    pub fn new(col: StructArray, desc: &RelationDesc) -> Result<Self, anyhow::Error> {
1455        // TODO(parkmcar): We should validate the fields here.
1456        let (_fields, arrays, nullability) = col.into_parts();
1457
1458        if nullability.is_some() {
1459            anyhow::bail!("SourceData is not nullable, but found {nullability:?}");
1460        }
1461        if arrays.len() != 2 {
1462            anyhow::bail!("SourceData should only have two fields, found {arrays:?}");
1463        }
1464
1465        let errs = arrays[1]
1466            .as_any()
1467            .downcast_ref::<BinaryArray>()
1468            .ok_or_else(|| anyhow::anyhow!("expected BinaryArray, found {:?}", arrays[1]))?;
1469
1470        let row_decoder = match arrays[0].data_type() {
1471            arrow::datatypes::DataType::Struct(_) => {
1472                let rows = arrays[0]
1473                    .as_any()
1474                    .downcast_ref::<StructArray>()
1475                    .ok_or_else(|| {
1476                        anyhow::anyhow!("expected StructArray, found {:?}", arrays[0])
1477                    })?;
1478                let decoder = RowColumnarDecoder::new(rows.clone(), desc)?;
1479                SourceDataRowColumnarDecoder::Row(decoder)
1480            }
1481            arrow::datatypes::DataType::Null => SourceDataRowColumnarDecoder::EmptyRow,
1482            other => anyhow::bail!("expected Struct or Null Array, found {other:?}"),
1483        };
1484
1485        Ok(SourceDataColumnarDecoder {
1486            row_decoder,
1487            err_decoder: errs.clone(),
1488        })
1489    }
1490}
1491
1492impl ColumnDecoder<SourceData> for SourceDataColumnarDecoder {
1493    fn decode(&self, idx: usize, val: &mut SourceData) {
1494        let err_null = self.err_decoder.is_null(idx);
1495        let row_null = match &self.row_decoder {
1496            SourceDataRowColumnarDecoder::Row(decoder) => decoder.is_null(idx),
1497            SourceDataRowColumnarDecoder::EmptyRow => !err_null,
1498        };
1499
1500        match (row_null, err_null) {
1501            (true, false) => {
1502                let err = self.err_decoder.value(idx);
1503                let err = ProtoDataflowError::decode(err)
1504                    .expect("proto should be valid")
1505                    .into_rust()
1506                    .expect("error should be valid");
1507                val.0 = Err(err);
1508            }
1509            (false, true) => {
1510                let row = match val.0.as_mut() {
1511                    Ok(row) => row,
1512                    Err(_) => {
1513                        val.0 = Ok(Row::default());
1514                        val.0.as_mut().unwrap()
1515                    }
1516                };
1517                self.row_decoder.decode(idx, row);
1518            }
1519            (true, true) => panic!("should have one of 'ok' or 'err'"),
1520            (false, false) => panic!("cannot have both 'ok' and 'err'"),
1521        }
1522    }
1523
1524    fn is_null(&self, idx: usize) -> bool {
1525        let err_null = self.err_decoder.is_null(idx);
1526        let row_null = match &self.row_decoder {
1527            SourceDataRowColumnarDecoder::Row(decoder) => decoder.is_null(idx),
1528            SourceDataRowColumnarDecoder::EmptyRow => !err_null,
1529        };
1530        assert!(!err_null || !row_null, "SourceData should never be null!");
1531
1532        false
1533    }
1534
1535    fn goodbytes(&self) -> usize {
1536        self.row_decoder.goodbytes() + ArrayOrd::Binary(self.err_decoder.clone()).goodbytes()
1537    }
1538
1539    fn stats(&self) -> StructStats {
1540        let len = self.err_decoder.len();
1541        let err_stats = ColumnarStats {
1542            nulls: Some(ColumnNullStats {
1543                count: self.err_decoder.null_count(),
1544            }),
1545            values: PrimitiveStats::<Vec<u8>>::from_column(&self.err_decoder).into(),
1546        };
1547        // The top level struct is non-nullable and every entry is either an
1548        // `Ok(Row)` or an `Err(String)`. As a result, we can compute the number
1549        // of `Ok` entries by subtracting the number of `Err` entries from the
1550        // total count.
1551        let row_null_count = len - self.err_decoder.null_count();
1552        let row_stats = match &self.row_decoder {
1553            SourceDataRowColumnarDecoder::Row(encoder) => {
1554                // Sanity check that the number of row nulls/nones we calculated
1555                // using the error column matches what the row column thinks it
1556                // has.
1557                assert_eq!(encoder.null_count(), row_null_count);
1558                encoder.stats()
1559            }
1560            SourceDataRowColumnarDecoder::EmptyRow => StructStats {
1561                len,
1562                cols: BTreeMap::default(),
1563            },
1564        };
1565        let row_stats = ColumnarStats {
1566            nulls: Some(ColumnNullStats {
1567                count: row_null_count,
1568            }),
1569            values: ColumnStatKinds::Struct(row_stats),
1570        };
1571
1572        let stats = [
1573            (
1574                SourceDataColumnarEncoder::OK_COLUMN_NAME.to_string(),
1575                row_stats,
1576            ),
1577            (
1578                SourceDataColumnarEncoder::ERR_COLUMN_NAME.to_string(),
1579                err_stats,
1580            ),
1581        ];
1582        StructStats {
1583            len,
1584            cols: stats.into_iter().map(|(name, s)| (name, s)).collect(),
1585        }
1586    }
1587}
1588
1589/// An encoder for [`Row`]s within [`SourceData`].
1590///
1591/// This type exists as a wrapper around [`RowColumnarEncoder`] to support
1592/// encoding empty [`Row`]s. A [`RowColumnarEncoder`] finishes as a
1593/// [`StructArray`] which is required to have at least one column, and thus
1594/// cannot support empty [`Row`]s.
1595#[derive(Debug)]
1596pub enum SourceDataRowColumnarEncoder {
1597    Row(RowColumnarEncoder),
1598    EmptyRow,
1599}
1600
1601impl SourceDataRowColumnarEncoder {
1602    pub(crate) fn goodbytes(&self) -> usize {
1603        match self {
1604            SourceDataRowColumnarEncoder::Row(e) => e.goodbytes(),
1605            SourceDataRowColumnarEncoder::EmptyRow => 0,
1606        }
1607    }
1608
1609    pub fn append(&mut self, row: &Row) {
1610        match self {
1611            SourceDataRowColumnarEncoder::Row(encoder) => encoder.append(row),
1612            SourceDataRowColumnarEncoder::EmptyRow => {
1613                assert_eq!(row.iter().count(), 0)
1614            }
1615        }
1616    }
1617
1618    pub fn append_null(&mut self) {
1619        match self {
1620            SourceDataRowColumnarEncoder::Row(encoder) => encoder.append_null(),
1621            SourceDataRowColumnarEncoder::EmptyRow => (),
1622        }
1623    }
1624}
1625
1626#[derive(Debug)]
1627pub struct SourceDataColumnarEncoder {
1628    row_encoder: SourceDataRowColumnarEncoder,
1629    err_encoder: BinaryBuilder,
1630}
1631
1632impl SourceDataColumnarEncoder {
1633    const OK_COLUMN_NAME: &'static str = "ok";
1634    const ERR_COLUMN_NAME: &'static str = "err";
1635
1636    pub fn new(desc: &RelationDesc) -> Self {
1637        let row_encoder = match RowColumnarEncoder::new(desc) {
1638            Some(encoder) => SourceDataRowColumnarEncoder::Row(encoder),
1639            None => {
1640                assert!(desc.typ().columns().is_empty());
1641                SourceDataRowColumnarEncoder::EmptyRow
1642            }
1643        };
1644        let err_encoder = BinaryBuilder::new();
1645
1646        SourceDataColumnarEncoder {
1647            row_encoder,
1648            err_encoder,
1649        }
1650    }
1651}
1652
1653impl ColumnEncoder<SourceData> for SourceDataColumnarEncoder {
1654    type FinishedColumn = StructArray;
1655
1656    fn goodbytes(&self) -> usize {
1657        self.row_encoder.goodbytes() + self.err_encoder.values_slice().len()
1658    }
1659
1660    #[inline]
1661    fn append(&mut self, val: &SourceData) {
1662        match val.0.as_ref() {
1663            Ok(row) => {
1664                self.row_encoder.append(row);
1665                self.err_encoder.append_null();
1666            }
1667            Err(err) => {
1668                self.row_encoder.append_null();
1669                self.err_encoder
1670                    .append_value(err.into_proto().encode_to_vec());
1671            }
1672        }
1673    }
1674
1675    #[inline]
1676    fn append_null(&mut self) {
1677        panic!("appending a null into SourceDataColumnarEncoder is not supported");
1678    }
1679
1680    fn finish(self) -> Self::FinishedColumn {
1681        let SourceDataColumnarEncoder {
1682            row_encoder,
1683            mut err_encoder,
1684        } = self;
1685
1686        let err_column = BinaryBuilder::finish(&mut err_encoder);
1687        let row_column: ArrayRef = match row_encoder {
1688            SourceDataRowColumnarEncoder::Row(encoder) => {
1689                let column = encoder.finish();
1690                Arc::new(column)
1691            }
1692            SourceDataRowColumnarEncoder::EmptyRow => Arc::new(NullArray::new(err_column.len())),
1693        };
1694
1695        assert_eq!(row_column.len(), err_column.len());
1696
1697        let fields = vec![
1698            Field::new(Self::OK_COLUMN_NAME, row_column.data_type().clone(), true),
1699            Field::new(Self::ERR_COLUMN_NAME, err_column.data_type().clone(), true),
1700        ];
1701        let arrays: Vec<Arc<dyn Array>> = vec![row_column, Arc::new(err_column)];
1702        StructArray::new(Fields::from(fields), arrays, None)
1703    }
1704}
1705
1706impl Schema<SourceData> for RelationDesc {
1707    type ArrowColumn = StructArray;
1708    type Statistics = StructStats;
1709
1710    type Decoder = SourceDataColumnarDecoder;
1711    type Encoder = SourceDataColumnarEncoder;
1712
1713    fn decoder(&self, col: Self::ArrowColumn) -> Result<Self::Decoder, anyhow::Error> {
1714        SourceDataColumnarDecoder::new(col, self)
1715    }
1716
1717    fn encoder(&self) -> Result<Self::Encoder, anyhow::Error> {
1718        Ok(SourceDataColumnarEncoder::new(self))
1719    }
1720}
1721
1722#[cfg(test)]
1723mod tests {
1724    use arrow::array::{ArrayData, make_comparator};
1725    use base64::Engine;
1726    use bytes::Bytes;
1727    use mz_expr::EvalError;
1728    use mz_ore::assert_err;
1729    use mz_ore::metrics::MetricsRegistry;
1730    use mz_persist::indexed::columnar::arrow::{realloc_any, realloc_array};
1731    use mz_persist::metrics::ColumnarMetrics;
1732    use mz_persist_types::parquet::EncodingConfig;
1733    use mz_persist_types::schema::{Migration, backward_compatible};
1734    use mz_persist_types::stats::{PartStats, PartStatsMetrics};
1735    use mz_repr::{
1736        ColumnIndex, DatumVec, PropRelationDescDiff, ProtoRelationDesc, RelationDescBuilder,
1737        RowArena, SqlScalarType, arb_relation_desc_diff, arb_relation_desc_projection,
1738    };
1739    use proptest::prelude::*;
1740    use proptest::strategy::{Union, ValueTree};
1741
1742    use crate::stats::RelationPartStats;
1743
1744    use super::*;
1745
1746    #[mz_ore::test]
1747    fn test_timeline_parsing() {
1748        assert_eq!(Ok(Timeline::EpochMilliseconds), "M".parse());
1749        assert_eq!(Ok(Timeline::External("JOE".to_string())), "E.JOE".parse());
1750        assert_eq!(Ok(Timeline::User("MIKE".to_string())), "U.MIKE".parse());
1751
1752        assert_err!("Materialize".parse::<Timeline>());
1753        assert_err!("Ejoe".parse::<Timeline>());
1754        assert_err!("Umike".parse::<Timeline>());
1755        assert_err!("Dance".parse::<Timeline>());
1756        assert_err!("".parse::<Timeline>());
1757    }
1758
1759    #[track_caller]
1760    fn roundtrip_source_data(
1761        desc: &RelationDesc,
1762        datas: Vec<SourceData>,
1763        read_desc: &RelationDesc,
1764        config: &EncodingConfig,
1765    ) {
1766        let metrics = ColumnarMetrics::disconnected();
1767        let mut encoder = <RelationDesc as Schema<SourceData>>::encoder(desc).unwrap();
1768        for data in &datas {
1769            encoder.append(data);
1770        }
1771        let col = encoder.finish();
1772
1773        // The top-level StructArray for SourceData should always be non-nullable.
1774        assert!(!col.is_nullable());
1775
1776        // Reallocate our arrays with lgalloc.
1777        let col = realloc_array(&col, &metrics);
1778
1779        // Roundtrip through ProtoArray format.
1780        {
1781            let proto = col.to_data().into_proto();
1782            let bytes = proto.encode_to_vec();
1783            let proto = mz_persist_types::arrow::ProtoArrayData::decode(&bytes[..]).unwrap();
1784            let array_data: ArrayData = proto.into_rust().unwrap();
1785
1786            let col_rnd = StructArray::from(array_data.clone());
1787            assert_eq!(col, col_rnd);
1788
1789            let col_dyn = arrow::array::make_array(array_data);
1790            let col_dyn = col_dyn.as_any().downcast_ref::<StructArray>().unwrap();
1791            assert_eq!(&col, col_dyn);
1792        }
1793
1794        // Encode to Parquet.
1795        let mut buf = Vec::new();
1796        let fields = Fields::from(vec![Field::new("k", col.data_type().clone(), false)]);
1797        let arrays: Vec<Arc<dyn Array>> = vec![Arc::new(col.clone())];
1798        mz_persist_types::parquet::encode_arrays(&mut buf, fields, arrays, config).unwrap();
1799
1800        // Decode from Parquet.
1801        let buf = Bytes::from(buf);
1802        let mut reader = mz_persist_types::parquet::decode_arrays(buf).unwrap();
1803        let maybe_batch = reader.next();
1804
1805        // If we didn't encode any data then our record_batch will be empty.
1806        let Some(record_batch) = maybe_batch else {
1807            assert!(datas.is_empty());
1808            return;
1809        };
1810        let record_batch = record_batch.unwrap();
1811
1812        assert_eq!(record_batch.columns().len(), 1);
1813        let rnd_col = &record_batch.columns()[0];
1814        let rnd_col = realloc_any(Arc::clone(rnd_col), &metrics);
1815        let rnd_col = rnd_col
1816            .as_any()
1817            .downcast_ref::<StructArray>()
1818            .unwrap()
1819            .clone();
1820
1821        // Try generating stats for the data, just to make sure we don't panic.
1822        let stats = <RelationDesc as Schema<SourceData>>::decoder_any(desc, &rnd_col)
1823            .expect("valid decoder")
1824            .stats();
1825
1826        // Read back all of our data and assert it roundtrips.
1827        let mut rnd_data = SourceData(Ok(Row::default()));
1828        let decoder = <RelationDesc as Schema<SourceData>>::decoder(desc, rnd_col.clone()).unwrap();
1829        for (idx, og_data) in datas.iter().enumerate() {
1830            decoder.decode(idx, &mut rnd_data);
1831            assert_eq!(og_data, &rnd_data);
1832        }
1833
1834        // Read back all of our data a second time with a projection applied, and make sure the
1835        // stats are valid.
1836        let stats_metrics = PartStatsMetrics::new(&MetricsRegistry::new());
1837        let stats = RelationPartStats {
1838            name: "test",
1839            metrics: &stats_metrics,
1840            stats: &PartStats { key: stats },
1841            desc: read_desc,
1842        };
1843        let mut datum_vec = DatumVec::new();
1844        let arena = RowArena::default();
1845        let decoder = <RelationDesc as Schema<SourceData>>::decoder(read_desc, rnd_col).unwrap();
1846
1847        for (idx, og_data) in datas.iter().enumerate() {
1848            decoder.decode(idx, &mut rnd_data);
1849            match (&og_data.0, &rnd_data.0) {
1850                (Ok(og_row), Ok(rnd_row)) => {
1851                    // Filter down to just the Datums in the projection schema.
1852                    {
1853                        let datums = datum_vec.borrow_with(og_row);
1854                        let projected_datums =
1855                            datums.iter().enumerate().filter_map(|(idx, datum)| {
1856                                read_desc
1857                                    .contains_index(&ColumnIndex::from_raw(idx))
1858                                    .then_some(datum)
1859                            });
1860                        let og_projected_row = Row::pack(projected_datums);
1861                        assert_eq!(&og_projected_row, rnd_row);
1862                    }
1863
1864                    // Validate the stats for all of our projected columns.
1865                    {
1866                        let proj_datums = datum_vec.borrow_with(rnd_row);
1867                        for (pos, (idx, _, _)) in read_desc.iter_all().enumerate() {
1868                            let spec = stats.col_stats(idx, &arena);
1869                            assert!(spec.may_contain(proj_datums[pos]));
1870                        }
1871                    }
1872                }
1873                (Err(_), Err(_)) => assert_eq!(og_data, &rnd_data),
1874                (_, _) => panic!("decoded to a different type? {og_data:?} {rnd_data:?}"),
1875            }
1876        }
1877
1878        // Verify that the RelationDesc itself roundtrips through
1879        // {encode,decode}_schema.
1880        let encoded_schema = SourceData::encode_schema(desc);
1881        let roundtrip_desc = SourceData::decode_schema(&encoded_schema);
1882        assert_eq!(desc, &roundtrip_desc);
1883
1884        // Verify that the RelationDesc is backward compatible with itself (this
1885        // mostly checks for `unimplemented!` type panics).
1886        let migration =
1887            mz_persist_types::schema::backward_compatible(col.data_type(), col.data_type());
1888        let migration = migration.expect("should be backward compatible with self");
1889        // Also verify that the Fn doesn't do anything wonky.
1890        let migrated = migration.migrate(Arc::new(col.clone()));
1891        assert_eq!(col.data_type(), migrated.data_type());
1892    }
1893
1894    #[mz_ore::test]
1895    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `decContextDefault` on OS `linux`
1896    fn all_source_data_roundtrips() {
1897        let mut weights = vec![(500, Just(0..8)), (50, Just(8..32))];
1898        if std::env::var("PROPTEST_LARGE_DATA").is_ok() {
1899            weights.extend([
1900                (10, Just(32..128)),
1901                (5, Just(128..512)),
1902                (3, Just(512..2048)),
1903                (1, Just(2048..8192)),
1904            ]);
1905        }
1906        let num_rows = Union::new_weighted(weights);
1907
1908        // TODO(parkmycar): There are so many clones going on here, and maybe we can avoid them?
1909        let strat = (any::<RelationDesc>(), num_rows)
1910            .prop_flat_map(|(desc, num_rows)| {
1911                arb_relation_desc_projection(desc.clone())
1912                    .prop_map(move |read_desc| (desc.clone(), read_desc, num_rows.clone()))
1913            })
1914            .prop_flat_map(|(desc, read_desc, num_rows)| {
1915                proptest::collection::vec(arb_source_data_for_relation_desc(&desc), num_rows)
1916                    .prop_map(move |datas| (desc.clone(), datas, read_desc.clone()))
1917            });
1918
1919        let combined_strat = (any::<EncodingConfig>(), strat);
1920        proptest!(|((config, (desc, source_datas, read_desc)) in combined_strat)| {
1921            roundtrip_source_data(&desc, source_datas, &read_desc, &config);
1922        });
1923    }
1924
1925    #[mz_ore::test]
1926    fn roundtrip_error_nulls() {
1927        let desc = RelationDescBuilder::default()
1928            .with_column(
1929                "ts",
1930                SqlScalarType::TimestampTz { precision: None }.nullable(false),
1931            )
1932            .finish();
1933        let source_datas = vec![SourceData(Err(DataflowError::EvalError(
1934            EvalError::DateOutOfRange.into(),
1935        )))];
1936        let config = EncodingConfig::default();
1937        roundtrip_source_data(&desc, source_datas, &desc, &config);
1938    }
1939
1940    fn is_sorted(array: &dyn Array) -> bool {
1941        let sort_options = arrow::compute::SortOptions::default();
1942        let Ok(cmp) = make_comparator(array, array, sort_options) else {
1943            // TODO: arrow v51.0.0 doesn't support comparing structs. When
1944            // we migrate to v52+, the `build_compare` function is
1945            // deprecated and replaced by `make_comparator`, which does
1946            // support structs. At which point, this will work (and we
1947            // should switch this early return to an expect, if possible).
1948            return false;
1949        };
1950        (0..array.len())
1951            .tuple_windows()
1952            .all(|(i, j)| cmp(i, j).is_le())
1953    }
1954
1955    fn get_data_type(schema: &impl Schema<SourceData>) -> arrow::datatypes::DataType {
1956        use mz_persist_types::columnar::ColumnEncoder;
1957        let array = Schema::encoder(schema).expect("valid schema").finish();
1958        Array::data_type(&array).clone()
1959    }
1960
1961    #[track_caller]
1962    fn backward_compatible_testcase(
1963        old: &RelationDesc,
1964        new: &RelationDesc,
1965        migration: Migration,
1966        datas: &[SourceData],
1967    ) {
1968        let mut encoder = Schema::<SourceData>::encoder(old).expect("valid schema");
1969        for data in datas {
1970            encoder.append(data);
1971        }
1972        let old = encoder.finish();
1973        let new = Schema::<SourceData>::encoder(new)
1974            .expect("valid schema")
1975            .finish();
1976        let old: Arc<dyn Array> = Arc::new(old);
1977        let new: Arc<dyn Array> = Arc::new(new);
1978        let migrated = migration.migrate(Arc::clone(&old));
1979        assert_eq!(migrated.data_type(), new.data_type());
1980
1981        // Check the sortedness preservation, if we can.
1982        if migration.preserves_order() && is_sorted(&old) {
1983            assert!(is_sorted(&new))
1984        }
1985    }
1986
1987    #[mz_ore::test]
1988    fn backward_compatible_empty_add_column() {
1989        let old = RelationDesc::empty();
1990        let new = RelationDesc::from_names_and_types([("a", SqlScalarType::Bool.nullable(true))]);
1991
1992        let old_data_type = get_data_type(&old);
1993        let new_data_type = get_data_type(&new);
1994
1995        let migration = backward_compatible(&old_data_type, &new_data_type);
1996        assert!(migration.is_some());
1997    }
1998
1999    #[mz_ore::test]
2000    fn backward_compatible_project_away_all() {
2001        let old = RelationDesc::from_names_and_types([("a", SqlScalarType::Bool.nullable(true))]);
2002        let new = RelationDesc::empty();
2003
2004        let old_data_type = get_data_type(&old);
2005        let new_data_type = get_data_type(&new);
2006
2007        let migration = backward_compatible(&old_data_type, &new_data_type);
2008        assert!(migration.is_some());
2009    }
2010
2011    #[mz_ore::test]
2012    #[cfg_attr(miri, ignore)]
2013    fn backward_compatible_migrate() {
2014        let strat = (any::<RelationDesc>(), any::<RelationDesc>()).prop_flat_map(|(old, new)| {
2015            proptest::collection::vec(arb_source_data_for_relation_desc(&old), 2)
2016                .prop_map(move |datas| (old.clone(), new.clone(), datas))
2017        });
2018
2019        proptest!(|((old, new, datas) in strat)| {
2020            let old_data_type = get_data_type(&old);
2021            let new_data_type = get_data_type(&new);
2022
2023            if let Some(migration) = backward_compatible(&old_data_type, &new_data_type) {
2024                backward_compatible_testcase(&old, &new, migration, &datas);
2025            };
2026        });
2027    }
2028
2029    #[mz_ore::test]
2030    #[cfg_attr(miri, ignore)]
2031    fn backward_compatible_migrate_from_common() {
2032        use mz_repr::SqlColumnType;
2033        fn test_case(old: RelationDesc, diffs: Vec<PropRelationDescDiff>, datas: Vec<SourceData>) {
2034            // TODO(parkmycar): As we iterate on schema migrations more things should become compatible.
2035            let should_be_compatible = diffs.iter().all(|diff| match diff {
2036                // We only support adding nullable columns.
2037                PropRelationDescDiff::AddColumn {
2038                    typ: SqlColumnType { nullable, .. },
2039                    ..
2040                } => *nullable,
2041                PropRelationDescDiff::DropColumn { .. } => true,
2042                _ => false,
2043            });
2044
2045            let mut new = old.clone();
2046            for diff in diffs.into_iter() {
2047                diff.apply(&mut new)
2048            }
2049
2050            let old_data_type = get_data_type(&old);
2051            let new_data_type = get_data_type(&new);
2052
2053            if let Some(migration) = backward_compatible(&old_data_type, &new_data_type) {
2054                backward_compatible_testcase(&old, &new, migration, &datas);
2055            } else if should_be_compatible {
2056                panic!("new DataType was not compatible when it should have been!");
2057            }
2058        }
2059
2060        let strat = any::<RelationDesc>()
2061            .prop_flat_map(|desc| {
2062                proptest::collection::vec(arb_source_data_for_relation_desc(&desc), 2)
2063                    .no_shrink()
2064                    .prop_map(move |datas| (desc.clone(), datas))
2065            })
2066            .prop_flat_map(|(desc, datas)| {
2067                arb_relation_desc_diff(&desc)
2068                    .prop_map(move |diffs| (desc.clone(), diffs, datas.clone()))
2069            });
2070
2071        proptest!(|((old, diffs, datas) in strat)| {
2072            test_case(old, diffs, datas);
2073        });
2074    }
2075
2076    #[mz_ore::test]
2077    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `decContextDefault` on OS `linux`
2078    fn empty_relation_desc_roundtrips() {
2079        let empty = RelationDesc::empty();
2080        let rows = proptest::collection::vec(arb_source_data_for_relation_desc(&empty), 0..8)
2081            .prop_map(move |datas| (empty.clone(), datas));
2082
2083        // Note: This case should be covered by the `all_source_data_roundtrips` test above, but
2084        // it's a special case that we explicitly want to exercise.
2085        proptest!(|((config, (desc, source_datas)) in (any::<EncodingConfig>(), rows))| {
2086            roundtrip_source_data(&desc, source_datas, &desc, &config);
2087        });
2088    }
2089
2090    #[mz_ore::test]
2091    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `decContextDefault` on OS `linux`
2092    fn arrow_datatype_consistent() {
2093        fn test_case(desc: RelationDesc, datas: Vec<SourceData>) {
2094            let half = datas.len() / 2;
2095
2096            let mut encoder_a = <RelationDesc as Schema<SourceData>>::encoder(&desc).unwrap();
2097            for data in &datas[..half] {
2098                encoder_a.append(data);
2099            }
2100            let col_a = encoder_a.finish();
2101
2102            let mut encoder_b = <RelationDesc as Schema<SourceData>>::encoder(&desc).unwrap();
2103            for data in &datas[half..] {
2104                encoder_b.append(data);
2105            }
2106            let col_b = encoder_b.finish();
2107
2108            // The DataType of the resulting column should not change based on what data was
2109            // encoded.
2110            assert_eq!(col_a.data_type(), col_b.data_type());
2111        }
2112
2113        let num_rows = 12;
2114        let strat = any::<RelationDesc>().prop_flat_map(|desc| {
2115            proptest::collection::vec(arb_source_data_for_relation_desc(&desc), num_rows)
2116                .prop_map(move |datas| (desc.clone(), datas))
2117        });
2118
2119        proptest!(|((desc, data) in strat)| {
2120            test_case(desc, data);
2121        });
2122    }
2123
2124    #[mz_ore::test]
2125    #[cfg_attr(miri, ignore)] // too slow
2126    fn source_proto_serialization_stability() {
2127        let min_protos = 10;
2128        let encoded = include_str!("snapshots/source-datas.txt");
2129
2130        // Decode the pre-generated source datas
2131        let mut decoded: Vec<(RelationDesc, SourceData)> = encoded
2132            .lines()
2133            .map(|s| {
2134                let (desc, data) = s.split_once(',').expect("comma separated data");
2135                let desc = base64::engine::general_purpose::STANDARD
2136                    .decode(desc)
2137                    .expect("valid base64");
2138                let data = base64::engine::general_purpose::STANDARD
2139                    .decode(data)
2140                    .expect("valid base64");
2141                (desc, data)
2142            })
2143            .map(|(desc, data)| {
2144                let desc = ProtoRelationDesc::decode(&desc[..]).expect("valid proto");
2145                let desc = desc.into_rust().expect("valid proto");
2146                let data = SourceData::decode(&data, &desc).expect("valid proto");
2147                (desc, data)
2148            })
2149            .collect();
2150
2151        // If there are fewer than the minimum examples, generate some new ones arbitrarily
2152        let mut runner = proptest::test_runner::TestRunner::deterministic();
2153        let strategy = RelationDesc::arbitrary().prop_flat_map(|desc| {
2154            arb_source_data_for_relation_desc(&desc).prop_map(move |data| (desc.clone(), data))
2155        });
2156        while decoded.len() < min_protos {
2157            let arbitrary_data = strategy
2158                .new_tree(&mut runner)
2159                .expect("source data")
2160                .current();
2161            decoded.push(arbitrary_data);
2162        }
2163
2164        // Reencode and compare the strings
2165        let mut reencoded = String::new();
2166        let mut buf = vec![];
2167        for (desc, data) in decoded {
2168            buf.clear();
2169            desc.into_proto().encode(&mut buf).expect("success");
2170            base64::engine::general_purpose::STANDARD.encode_string(buf.as_slice(), &mut reencoded);
2171            reencoded.push(',');
2172
2173            buf.clear();
2174            data.encode(&mut buf);
2175            base64::engine::general_purpose::STANDARD.encode_string(buf.as_slice(), &mut reencoded);
2176            reencoded.push('\n');
2177        }
2178
2179        // Optimizations in Persist, particularly consolidation on read,
2180        // depend on a stable serialization for the serialized data.
2181        // For example, reordering proto fields could cause us
2182        // to generate a different (equivalent) serialization for a record,
2183        // and the two versions would not consolidate out.
2184        // This can impact correctness!
2185        //
2186        // If you need to change how SourceDatas are encoded, that's still fine...
2187        // but we'll also need to increase
2188        // the MINIMUM_CONSOLIDATED_VERSION as part of the same release.
2189        assert_eq!(
2190            encoded,
2191            reencoded.as_str(),
2192            "SourceData serde should be stable"
2193        )
2194    }
2195}