1use 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#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
84pub struct IngestionDescription<S: 'static = (), C: ConnectionAccess = InlinedConnection> {
85 pub desc: SourceDesc<C>,
87 pub source_exports: BTreeMap<GlobalId, SourceExport<S>>,
103 pub instance_id: StorageInstanceId,
105 pub remap_collection_id: GlobalId,
107 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 pub fn collection_ids(&self) -> impl Iterator<Item = GlobalId> + '_ {
133 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 pub storage_metadata: S,
251 pub details: SourceExportDetails,
253 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#[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
338impl 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
352impl 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
382impl 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#[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,
453 External(String),
457 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
513pub trait SourceConnection: Debug + Clone + PartialEq + AlterCompatible {
515 fn name(&self) -> &'static str;
517
518 fn external_reference(&self) -> Option<&str>;
520
521 fn default_key_desc(&self) -> RelationDesc;
525
526 fn default_value_desc(&self) -> RelationDesc;
530
531 fn timestamp_desc(&self) -> RelationDesc;
534
535 fn connection_id(&self) -> Option<CatalogItemId>;
538
539 fn supports_read_only(&self) -> bool;
541
542 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#[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 pub fn monotonic(&self, connection: &GenericSourceConnection<C>) -> bool {
614 match &self.envelope {
615 SourceEnvelope::Upsert(_) | SourceEnvelope::CdcV2 => false,
617 SourceEnvelope::None(_) => {
618 match connection {
619 GenericSourceConnection::Postgres(_) => false,
621 GenericSourceConnection::MySql(_) => false,
623 GenericSourceConnection::SqlServer(_) => false,
625 GenericSourceConnection::LoadGenerator(g) => g.load_generator.is_monotonic(),
627 GenericSourceConnection::Kafka(_) => true,
629 }
630 }
631 }
632 }
633}
634
635#[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 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: _,
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#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
868pub enum SourceExportDetails {
869 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
906pub enum SourceExportStatementDetails {
912 Postgres {
913 table: mz_postgres_util::desc::PostgresTableDesc,
914 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 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 (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 (kind, _) => {
1125 let proto = ProtoSourceData { kind };
1126 *self = proto.into_rust().map_err(|err| err.to_string())?;
1127 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#[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
1169pub trait ExternalCatalogReference {
1177 fn schema_name(&self) -> &str;
1179 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
1213impl<'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#[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 pub fn new<T: ExternalCatalogReference>(
1257 database: &str,
1258 referenceable_items: &'a [T],
1259 ) -> Result<SourceReferenceResolver, ExternalReferenceResolutionError> {
1260 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 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 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 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 if !(1..=3).contains(&name.len()) {
1355 Err(ExternalReferenceResolutionError::DoesNotExist {
1356 name: get_provided_name(),
1357 })?;
1358 }
1359
1360 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#[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 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 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 let row_null_count = len - self.err_decoder.null_count();
1551 let row_stats = match &self.row_decoder {
1552 SourceDataRowColumnarDecoder::Row(encoder) => {
1553 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#[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 assert!(!col.is_nullable());
1774
1775 let col = realloc_array(&col, &metrics);
1777
1778 {
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 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 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 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 let stats = <RelationDesc as Schema<SourceData>>::decoder_any(desc, &rnd_col)
1822 .expect("valid decoder")
1823 .stats();
1824
1825 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 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 {
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 {
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 let encoded_schema = SourceData::encode_schema(desc);
1880 let roundtrip_desc = SourceData::decode_schema(&encoded_schema);
1881 assert_eq!(desc, &roundtrip_desc);
1882
1883 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 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)] 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 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 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 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 let should_be_compatible = diffs.iter().all(|diff| match diff {
2035 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)] 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 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)] 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 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)] fn source_proto_serialization_stability() {
2126 let min_protos = 10;
2127 let encoded = include_str!("snapshots/source-datas.txt");
2128
2129 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 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 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 assert_eq!(
2189 encoded,
2190 reencoded.as_str(),
2191 "SourceData serde should be stable"
2192 )
2193 }
2194}