Skip to main content

mz_sql/pure/
postgres.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//! Postgres utilities for SQL purification.
11
12use std::collections::{BTreeMap, BTreeSet};
13
14use mz_postgres_util::desc::PostgresTableDesc;
15use mz_proto::RustType;
16use mz_repr::{Datum, ReprColumnType, ReprScalarType, Row, SqlScalarType};
17use mz_sql_parser::ast::display::AstDisplay;
18use mz_sql_parser::ast::{
19    ColumnDef, CreateSubsourceOption, CreateSubsourceOptionName, CreateSubsourceStatement,
20    ExternalReferences, Ident, PgConfigOptionName, TableConstraint, UnresolvedItemName, Value,
21    WithOptionValue,
22};
23use mz_storage_types::sources::SourceExportStatementDetails;
24use mz_storage_types::sources::casts::{CastFunc, StorageScalarExpr};
25use mz_storage_types::sources::postgres::CastType;
26use prost::Message;
27use tokio_postgres::Client;
28use tokio_postgres::types::Oid;
29
30use crate::names::{Aug, ResolvedItemName};
31use crate::normalize;
32use crate::plan::{PlanError, StatementContext};
33
34use super::error::PgSourcePurificationError;
35use super::references::RetrievedSourceReferences;
36use super::{PartialItemName, PurifiedExportDetails, PurifiedSourceExport, SourceReferencePolicy};
37
38/// Ensure that we have select permissions on all tables; we have to do this before we
39/// start snapshotting because if we discover we cannot `COPY` from a table while
40/// snapshotting, we break the entire source.
41pub(super) async fn validate_requested_references_privileges(
42    client: &Client,
43    table_oids: &[Oid],
44) -> Result<(), PlanError> {
45    privileges::check_table_privileges(client, table_oids).await?;
46    privileges::check_rls_privileges(client, table_oids).await?;
47    replica_identity::check_replica_identity_full(client, table_oids).await?;
48
49    Ok(())
50}
51
52/// Map a list of column references to a map of table oids to column names.
53///
54/// Additionally, modify `columns` so that they contain database-qualified
55/// references to the columns.
56pub(super) fn map_column_refs(
57    retrieved_references: &RetrievedSourceReferences,
58    columns: &mut [UnresolvedItemName],
59    option_type: PgConfigOptionName,
60) -> Result<BTreeMap<u32, BTreeSet<String>>, PlanError> {
61    let mut cols_map: BTreeMap<u32, BTreeSet<String>> = BTreeMap::new();
62
63    for name in columns {
64        let (qual, col) = match name.0.split_last().expect("must have at least one element") {
65            (col, []) => {
66                return Err(PlanError::InvalidOptionValue {
67                    option_name: option_type.to_ast_string_simple(),
68                    err: Box::new(PlanError::UnderqualifiedColumnName(
69                        col.as_str().to_string(),
70                    )),
71                });
72            }
73            (col, qual) => (qual.to_vec(), col.as_str().to_string()),
74        };
75
76        let resolved_reference = retrieved_references.resolve_name(&qual)?;
77        let mut fully_qualified_name =
78            resolved_reference
79                .external_reference()
80                .map_err(|e| PlanError::InvalidOptionValue {
81                    option_name: option_type.to_ast_string_simple(),
82                    err: Box::new(e.into()),
83                })?;
84
85        let desc = resolved_reference
86            .postgres_desc()
87            .expect("known to be postgres");
88
89        if !desc.columns.iter().any(|column| column.name == col) {
90            let column = mz_repr::ColumnName::from(col);
91            let similar = desc
92                .columns
93                .iter()
94                .filter_map(|c| {
95                    let c_name = mz_repr::ColumnName::from(c.name.clone());
96                    c_name.is_similar(&column).then_some(c_name)
97                })
98                .collect();
99            return Err(PlanError::InvalidOptionValue {
100                option_name: option_type.to_ast_string_simple(),
101                err: Box::new(PlanError::UnknownColumn {
102                    table: Some(
103                        normalize::unresolved_item_name(fully_qualified_name)
104                            .expect("known to be of valid len"),
105                    ),
106                    column,
107                    similar,
108                }),
109            });
110        }
111
112        // Rewrite fully qualified name.
113        let col_ident = Ident::new(col.as_str().to_string())?;
114        fully_qualified_name.0.push(col_ident);
115        *name = fully_qualified_name;
116
117        let new = cols_map
118            .entry(desc.oid)
119            .or_default()
120            .insert(col.as_str().to_string());
121
122        if !new {
123            return Err(PlanError::InvalidOptionValue {
124                option_name: option_type.to_ast_string_simple(),
125                err: Box::new(PlanError::UnexpectedDuplicateReference { name: name.clone() }),
126            });
127        }
128    }
129
130    Ok(cols_map)
131}
132
133pub fn generate_create_subsource_statements(
134    scx: &StatementContext,
135    source_name: ResolvedItemName,
136    requested_subsources: BTreeMap<UnresolvedItemName, PurifiedSourceExport>,
137) -> Result<Vec<CreateSubsourceStatement<Aug>>, PlanError> {
138    // Aggregate all unrecognized types.
139    let mut unsupported_cols = vec![];
140
141    // Now that we have an explicit list of validated requested subsources we can create them
142    let mut subsources = Vec::with_capacity(requested_subsources.len());
143
144    for (subsource_name, purified_export) in requested_subsources {
145        let PostgresExportStatementValues {
146            columns,
147            constraints,
148            text_columns,
149            exclude_columns,
150            details,
151            external_reference,
152        } = generate_source_export_statement_values(scx, purified_export, &mut unsupported_cols)?;
153
154        let mut with_options = vec![
155            CreateSubsourceOption {
156                name: CreateSubsourceOptionName::ExternalReference,
157                value: Some(WithOptionValue::UnresolvedItemName(external_reference)),
158            },
159            CreateSubsourceOption {
160                name: CreateSubsourceOptionName::Details,
161                value: Some(WithOptionValue::Value(Value::String(hex::encode(
162                    details.into_proto().encode_to_vec(),
163                )))),
164            },
165        ];
166
167        if let Some(text_columns) = text_columns {
168            with_options.push(CreateSubsourceOption {
169                name: CreateSubsourceOptionName::TextColumns,
170                value: Some(WithOptionValue::Sequence(text_columns)),
171            });
172        }
173
174        if let Some(exclude_columns) = exclude_columns {
175            with_options.push(CreateSubsourceOption {
176                name: CreateSubsourceOptionName::ExcludeColumns,
177                value: Some(WithOptionValue::Sequence(exclude_columns)),
178            });
179        }
180
181        // Create the subsource statement
182        let subsource = CreateSubsourceStatement {
183            name: subsource_name,
184            columns,
185            // We might not know the primary source's `GlobalId` yet; if not,
186            // we'll fill it in once we generate it.
187            of_source: Some(source_name.clone()),
188            // TODO(petrosagg): nothing stops us from getting the constraints of the
189            // upstream tables and mirroring them here which will lead to more optimization
190            // opportunities if for example there is a primary key or an index.
191            //
192            // If we ever do that we must triple check that we will get notified *in the
193            // replication stream*, if our assumptions change. Failure to do that could
194            // mean that an upstream table that started with an index was then altered to
195            // one without and now we're producing garbage data.
196            constraints,
197            if_not_exists: false,
198            with_options,
199        };
200        subsources.push(subsource);
201    }
202
203    if !unsupported_cols.is_empty() {
204        unsupported_cols.sort();
205        Err(PgSourcePurificationError::UnrecognizedTypes {
206            cols: unsupported_cols,
207        })?;
208    }
209
210    Ok(subsources)
211}
212
213pub(super) struct PostgresExportStatementValues {
214    pub(super) columns: Vec<ColumnDef<Aug>>,
215    pub(super) constraints: Vec<TableConstraint<Aug>>,
216    pub(super) text_columns: Option<Vec<WithOptionValue<Aug>>>,
217    pub(super) exclude_columns: Option<Vec<WithOptionValue<Aug>>>,
218    pub(super) details: SourceExportStatementDetails,
219    pub(super) external_reference: UnresolvedItemName,
220}
221
222pub(super) fn generate_source_export_statement_values(
223    scx: &StatementContext,
224    purified_export: PurifiedSourceExport,
225    unsupported_cols: &mut Vec<(String, mz_repr::adt::system::Oid)>,
226) -> Result<PostgresExportStatementValues, PlanError> {
227    let PurifiedExportDetails::Postgres {
228        table,
229        text_columns,
230        exclude_columns,
231    } = purified_export.details
232    else {
233        bail_internal!("purified export details must be postgres");
234    };
235
236    let text_column_set = BTreeSet::from_iter(text_columns.iter().flatten().map(Ident::as_str));
237    let exclude_column_set =
238        BTreeSet::from_iter(exclude_columns.iter().flatten().map(Ident::as_str));
239
240    // Figure out the schema of the subsource
241    let mut columns = vec![];
242    for c in table.columns.iter() {
243        let name = Ident::new(c.name.clone())?;
244
245        if exclude_column_set.contains(c.name.as_str()) {
246            continue;
247        }
248
249        let ty = if text_column_set.contains(c.name.as_str()) {
250            mz_pgrepr::Type::Text
251        } else {
252            match mz_pgrepr::Type::from_oid_and_typmod(c.type_oid, c.type_mod) {
253                Ok(t) => t,
254                Err(_) => {
255                    let mut full_name = purified_export.external_reference.0.clone();
256                    full_name.push(name);
257                    unsupported_cols.push((
258                        UnresolvedItemName(full_name).to_ast_string_simple(),
259                        mz_repr::adt::system::Oid(c.type_oid),
260                    ));
261                    continue;
262                }
263            }
264        };
265
266        let data_type = scx.resolve_type(ty)?;
267        let mut options = vec![];
268
269        if !c.nullable {
270            options.push(mz_sql_parser::ast::ColumnOptionDef {
271                name: None,
272                option: mz_sql_parser::ast::ColumnOption::NotNull,
273            });
274        }
275
276        columns.push(ColumnDef {
277            name,
278            data_type,
279            collation: None,
280            options,
281        });
282    }
283
284    let mut constraints = vec![];
285    for key in table.keys.clone() {
286        let mut key_columns = vec![];
287        let mut all_key_cols_included = true;
288
289        for col_num in key.cols {
290            match table.columns.iter().find(|col| col.col_num == col_num) {
291                Some(col) => {
292                    let ident = Ident::new(col.name.clone())?;
293                    key_columns.push(ident);
294                }
295                None => {
296                    all_key_cols_included = false;
297                    break;
298                }
299            }
300        }
301        if !all_key_cols_included {
302            continue;
303        }
304
305        let constraint = mz_sql_parser::ast::TableConstraint::Unique {
306            name: Some(Ident::new(key.name)?),
307            columns: key_columns,
308            is_primary: key.is_primary,
309            nulls_not_distinct: key.nulls_not_distinct,
310        };
311
312        // We take the first constraint available to be the primary key.
313        if key.is_primary {
314            constraints.insert(0, constraint);
315        } else {
316            constraints.push(constraint);
317        }
318    }
319    // Newly purified exports always take the full-range oid cast. The flag is
320    // persisted in the statement details so replanning keeps the choice stable
321    // for the lifetime of the export, while exports whose details predate the
322    // flag decode as `false` and stay on the legacy cast.
323    let details = SourceExportStatementDetails::Postgres {
324        table,
325        cast_oid_full_range: true,
326    };
327
328    let text_columns = text_columns.map(|mut columns| {
329        columns.sort();
330        columns
331            .into_iter()
332            .map(WithOptionValue::Ident::<Aug>)
333            .collect()
334    });
335
336    let exclude_columns = exclude_columns.map(|mut columns| {
337        columns.sort();
338        columns
339            .into_iter()
340            .map(WithOptionValue::Ident::<Aug>)
341            .collect()
342    });
343
344    Ok(PostgresExportStatementValues {
345        columns,
346        constraints,
347        text_columns,
348        exclude_columns,
349        details,
350        external_reference: purified_export.external_reference,
351    })
352}
353
354pub(super) struct PurifiedSourceExports {
355    pub(super) source_exports: BTreeMap<UnresolvedItemName, PurifiedSourceExport>,
356    // NOTE(roshan): The text columns are already part of their
357    // appropriate `source_exports` above, but these are returned to allow
358    // round-tripping a `CREATE SOURCE` statement while we still allow creating
359    // implicit subsources from `CREATE SOURCE`. Remove once
360    // fully deprecating that feature and forcing users to use explicit
361    // `CREATE TABLE .. FROM SOURCE` statements.
362    pub(super) normalized_text_columns: Vec<WithOptionValue<Aug>>,
363}
364
365// Purify the requested external references, returning a set of purified
366// source exports corresponding to external tables, and and additional
367// fields necessary to generate relevant statements and update statement options
368pub(super) async fn purify_source_exports(
369    client: &Client,
370    retrieved_references: &RetrievedSourceReferences,
371    requested_references: &Option<ExternalReferences>,
372    mut text_columns: Vec<UnresolvedItemName>,
373    mut exclude_columns: Vec<UnresolvedItemName>,
374    unresolved_source_name: &UnresolvedItemName,
375    reference_policy: &SourceReferencePolicy,
376) -> Result<PurifiedSourceExports, PlanError> {
377    let requested_exports = match requested_references.as_ref() {
378        Some(requested) if matches!(reference_policy, SourceReferencePolicy::NotAllowed) => {
379            Err(PlanError::UseTablesForSources(requested.to_string()))?
380        }
381        Some(requested) => retrieved_references
382            .requested_source_exports(Some(requested), unresolved_source_name)?,
383        None => {
384            if matches!(reference_policy, SourceReferencePolicy::Required) {
385                Err(PgSourcePurificationError::RequiresExternalReferences)?
386            }
387
388            // If no external reference is specified, it does not make sense to include
389            // text columns.
390            if !text_columns.is_empty() {
391                Err(
392                    PgSourcePurificationError::UnnecessaryOptionsWithoutReferences(
393                        "TEXT COLUMNS".to_string(),
394                    ),
395                )?
396            }
397
398            // If no external reference is specified, it does not make sense to include
399            // exclude columns.
400            if !exclude_columns.is_empty() {
401                Err(
402                    PgSourcePurificationError::UnnecessaryOptionsWithoutReferences(
403                        "EXCLUDE COLUMNS".to_string(),
404                    ),
405                )?
406            }
407
408            return Ok(PurifiedSourceExports {
409                source_exports: BTreeMap::new(),
410                normalized_text_columns: vec![],
411            });
412        }
413    };
414
415    if requested_exports.is_empty() {
416        sql_bail!(
417            "[internal error]: Postgres reference {} did not match any tables",
418            requested_references
419                .as_ref()
420                .unwrap()
421                .to_ast_string_simple()
422        );
423    }
424
425    super::validate_source_export_names(&requested_exports)?;
426
427    let table_oids: Vec<_> = requested_exports
428        .iter()
429        .map(|r| r.meta.postgres_desc().expect("is postgres").oid)
430        .collect();
431
432    validate_requested_references_privileges(client, &table_oids).await?;
433
434    let mut text_column_map = map_column_refs(
435        retrieved_references,
436        &mut text_columns,
437        PgConfigOptionName::TextColumns,
438    )?;
439    let mut exclude_column_map = map_column_refs(
440        retrieved_references,
441        &mut exclude_columns,
442        PgConfigOptionName::ExcludeColumns,
443    )?;
444
445    // Normalize options to contain full qualified values.
446    text_columns.sort();
447    text_columns.dedup();
448    let normalized_text_columns: Vec<_> = text_columns
449        .into_iter()
450        .map(WithOptionValue::UnresolvedItemName)
451        .collect();
452
453    let source_exports = requested_exports
454        .into_iter()
455        .map(|r| {
456            let mut desc = r.meta.postgres_desc().expect("known postgres").clone();
457            let text_columns = text_column_map.remove(&desc.oid);
458            let exclude_columns = exclude_column_map.remove(&desc.oid);
459
460            if let Some(exclude_cols) = &exclude_columns {
461                let excluded_col_nums: BTreeSet<u16> = desc
462                    .columns
463                    .iter()
464                    .filter(|c| exclude_cols.contains(&c.name))
465                    .map(|c| c.col_num)
466                    .collect();
467                desc.columns.retain(|c| !exclude_cols.contains(&c.name));
468                // A key naming an excluded column can never be re-verified against
469                // upstream, since the column (and any constraint on it) can be
470                // dropped independently of the columns we still track. Drop such
471                // keys now rather than carrying a stale key that will look like an
472                // incompatible schema change once the excluded column disappears.
473                desc.keys
474                    .retain(|k| k.cols.iter().all(|c| !excluded_col_nums.contains(c)));
475            }
476
477            if let (Some(text_cols), Some(exclude_cols)) = (&text_columns, &exclude_columns) {
478                let intersection: Vec<_> = text_cols.intersection(exclude_cols).collect();
479                if !intersection.is_empty() {
480                    return Err(PgSourcePurificationError::DuplicatedColumnNames(
481                        intersection.iter().map(|s| (*s).to_string()).collect(),
482                    ));
483                }
484            }
485            Ok((
486                r.name,
487                PurifiedSourceExport {
488                    external_reference: r.external_reference,
489                    details: PurifiedExportDetails::Postgres {
490                        text_columns: text_columns.map(|v| {
491                            v.into_iter()
492                                .map(|s| Ident::new(s).expect("validated above"))
493                                .collect()
494                        }),
495                        exclude_columns: exclude_columns.map(|v| {
496                            v.into_iter()
497                                .map(|s| Ident::new(s).expect("validated above"))
498                                .collect()
499                        }),
500                        table: desc,
501                    },
502                },
503            ))
504        })
505        .collect::<Result<BTreeMap<_, _>, _>>()?;
506
507    if !text_column_map.is_empty() {
508        // If any any item was not removed from the text_column_map, it wasn't being
509        // added.
510        let mut dangling_text_column_refs = vec![];
511        let all_references = retrieved_references.all_references();
512
513        for id in text_column_map.keys() {
514            let desc = all_references
515                .iter()
516                .find_map(|reference| {
517                    let desc = reference.postgres_desc().expect("is postgres");
518                    if desc.oid == *id { Some(desc) } else { None }
519                })
520                .expect("validated when generating text columns");
521
522            dangling_text_column_refs.push(PartialItemName {
523                database: None,
524                schema: Some(desc.namespace.clone()),
525                item: desc.name.clone(),
526            });
527        }
528
529        dangling_text_column_refs.sort();
530        return Err(PlanError::from(
531            PgSourcePurificationError::DanglingTextColumns {
532                items: dangling_text_column_refs,
533            },
534        ));
535    }
536
537    if !exclude_column_map.is_empty() {
538        // If any any item was not removed from the exclude_column_map, it wasn't being
539        // added.
540        let mut dangling_exclude_column_refs = vec![];
541        let all_references = retrieved_references.all_references();
542
543        for id in exclude_column_map.keys() {
544            let desc = all_references
545                .iter()
546                .find_map(|reference| {
547                    let desc = reference.postgres_desc().expect("is postgres");
548                    if desc.oid == *id { Some(desc) } else { None }
549                })
550                .expect("validated when generating exclude columns");
551
552            dangling_exclude_column_refs.push(PartialItemName {
553                database: None,
554                schema: Some(desc.namespace.clone()),
555                item: desc.name.clone(),
556            });
557        }
558
559        dangling_exclude_column_refs.sort();
560        return Err(PlanError::from(
561            PgSourcePurificationError::DanglingExcludeColumns {
562                items: dangling_exclude_column_refs,
563            },
564        ));
565    }
566
567    Ok(PurifiedSourceExports {
568        source_exports,
569        normalized_text_columns,
570    })
571}
572
573pub(crate) fn generate_column_casts(
574    scx: &StatementContext,
575    table: &PostgresTableDesc,
576    text_columns: &Vec<Ident>,
577    cast_oid_full_range: bool,
578) -> Result<Vec<(CastType, StorageScalarExpr)>, PlanError> {
579    // Generate the cast expressions required to convert the text encoded columns into
580    // the appropriate target types, creating a Vec<StorageScalarExpr>.
581    // The postgres source reader will then eval each of those on the incoming rows.
582
583    let text_columns = BTreeSet::from_iter(text_columns.iter().map(Ident::as_str));
584
585    let mut table_cast = vec![];
586    for (i, column) in table.columns.iter().enumerate() {
587        let (cast_type, ty) = if text_columns.contains(column.name.as_str()) {
588            // Treat the column as text if it was referenced in
589            // `TEXT COLUMNS`. This is the only place we need to
590            // perform this logic; even if the type is unsupported,
591            // we'll be able to ingest its values as text in
592            // storage.
593            (CastType::Text, mz_pgrepr::Type::Text)
594        } else {
595            match mz_pgrepr::Type::from_oid_and_typmod(column.type_oid, column.type_mod) {
596                Ok(t) => (CastType::Natural, t),
597                // If this reference survived purification, we
598                // do not expect it to be from a table that the
599                // user will consume., i.e. expect this table to
600                // be filtered out of table casts.
601                Err(_) => {
602                    table_cast.push((
603                        CastType::Natural,
604                        StorageScalarExpr::ErrorIfNull(
605                            Box::new(StorageScalarExpr::Literal(
606                                Row::pack_slice(&[Datum::Null]),
607                                ReprColumnType {
608                                    nullable: true,
609                                    scalar_type: ReprScalarType::String,
610                                },
611                            )),
612                            format!("Unsupported type with OID {}", column.type_oid),
613                        ),
614                    ));
615                    continue;
616                }
617            }
618        };
619
620        let cast_expr = match pg_type_to_cast_func(scx, &ty, cast_oid_full_range) {
621            Ok(None) => {
622                // No cast needed (e.g. Text → String identity).
623                StorageScalarExpr::Column(i)
624            }
625            Ok(Some(cast_func)) => {
626                StorageScalarExpr::CallUnary(cast_func, Box::new(StorageScalarExpr::Column(i)))
627            }
628            Err(PlanError::TableContainsUningestableTypes { type_, .. }) => {
629                // We expect only reg* types and similar to encounter
630                // this. Users can ingest the data as text if they need
631                // to. This is acceptable because we don't expect the
632                // OIDs from an external PG source to be unilaterally
633                // usable in resolving item names in MZ.
634                return Err(PlanError::TableContainsUningestableTypes {
635                    name: table.name.to_string(),
636                    type_,
637                    column: column.name.to_string(),
638                });
639            }
640            Err(e) => return Err(e),
641        };
642
643        let cast = if column.nullable {
644            cast_expr
645        } else {
646            // We must enforce nullability constraint on cast
647            // because PG replication stream does not propagate
648            // constraint changes and we want to error subsource if
649            // e.g. the constraint is dropped and we don't notice
650            // it.
651            let message = format!(
652                "PG column {}.{}.{} contained NULL data, despite having NOT NULL constraint",
653                table.namespace, table.name, column.name
654            );
655            StorageScalarExpr::ErrorIfNull(Box::new(cast_expr), message)
656        };
657
658        table_cast.push((cast_type, cast));
659    }
660    Ok(table_cast)
661}
662
663/// Resolve a PG type to its corresponding `SqlScalarType` via the catalog.
664fn resolve_pg_type_to_scalar_type(
665    scx: &StatementContext,
666    ty: &mz_pgrepr::Type,
667) -> Result<SqlScalarType, PlanError> {
668    let data_type = scx.resolve_type(ty.clone())?;
669    crate::plan::query::scalar_type_from_sql(scx, &data_type)
670}
671
672/// Map a PG type to the corresponding `CastFunc` variant. Returns:
673/// - `Ok(Some(func))` for types that need a cast
674/// - `Ok(None)` for types that need no cast (Text → String identity)
675/// - `Err(PlanError::TableContainsUningestableTypes { .. })` for types
676///   that cannot be ingested. The error uses placeholder strings for
677///   table/column name; callers with context should use
678///   `pg_type_to_cast_func_or_uningestable` instead.
679fn pg_type_to_cast_func(
680    scx: &StatementContext,
681    ty: &mz_pgrepr::Type,
682    cast_oid_full_range: bool,
683) -> Result<Option<CastFunc>, PlanError> {
684    use mz_pgrepr::Type;
685
686    let cast_func = match ty {
687        Type::Bool => CastFunc::CastStringToBool,
688        Type::Bytea => CastFunc::CastStringToBytes,
689        Type::Char => CastFunc::CastStringToPgLegacyChar,
690        Type::Date => CastFunc::CastStringToDate,
691        Type::Float4 => CastFunc::CastStringToFloat32,
692        Type::Float8 => CastFunc::CastStringToFloat64,
693        Type::Int2 => CastFunc::CastStringToInt16,
694        Type::Int4 => CastFunc::CastStringToInt32,
695        Type::Int8 => CastFunc::CastStringToInt64,
696        Type::UInt2 => CastFunc::CastStringToUint16,
697        Type::UInt4 => CastFunc::CastStringToUint32,
698        Type::UInt8 => CastFunc::CastStringToUint64,
699        Type::Interval { .. } => CastFunc::CastStringToInterval,
700        Type::Jsonb => CastFunc::CastStringToJsonb,
701        Type::Name => CastFunc::CastStringToPgLegacyName,
702        Type::Numeric { .. } => {
703            // Resolve through the catalog to get the repr NumericMaxScale type.
704            let scalar_type = resolve_pg_type_to_scalar_type(scx, ty)?;
705            match scalar_type {
706                SqlScalarType::Numeric { max_scale } => CastFunc::CastStringToNumeric(max_scale),
707                _ => unreachable!("Numeric must resolve to Numeric"),
708            }
709        }
710        Type::Oid => {
711            if cast_oid_full_range {
712                CastFunc::CastStringToOidFullRange
713            } else {
714                CastFunc::CastStringToOid
715            }
716        }
717        Type::Text => return Ok(None),
718        Type::BpChar { .. } => {
719            // Resolve through the catalog to get the repr CharLength type.
720            let scalar_type = resolve_pg_type_to_scalar_type(scx, ty)?;
721            match scalar_type {
722                SqlScalarType::Char { length } => CastFunc::CastStringToChar {
723                    length,
724                    fail_on_len: true,
725                },
726                _ => unreachable!("BpChar must resolve to Char"),
727            }
728        }
729        Type::VarChar { .. } => {
730            // Resolve through the catalog to get the repr VarCharMaxLength type.
731            let scalar_type = resolve_pg_type_to_scalar_type(scx, ty)?;
732            match scalar_type {
733                SqlScalarType::VarChar { max_length } => CastFunc::CastStringToVarChar {
734                    length: max_length,
735                    fail_on_len: true,
736                },
737                _ => unreachable!("VarChar must resolve to VarChar"),
738            }
739        }
740        Type::Time { .. } => {
741            // Time precision is not yet fully supported; resolve_type strips precision.
742            CastFunc::CastStringToTime
743        }
744        Type::Timestamp { .. } => {
745            // Resolve through the catalog to get the repr TimestampPrecision type.
746            let scalar_type = resolve_pg_type_to_scalar_type(scx, ty)?;
747            match scalar_type {
748                SqlScalarType::Timestamp { precision } => {
749                    CastFunc::CastStringToTimestamp(precision)
750                }
751                _ => unreachable!("Timestamp must resolve to Timestamp"),
752            }
753        }
754        Type::TimestampTz { .. } => {
755            // Resolve through the catalog to get the repr TimestampPrecision type.
756            let scalar_type = resolve_pg_type_to_scalar_type(scx, ty)?;
757            match scalar_type {
758                SqlScalarType::TimestampTz { precision } => {
759                    CastFunc::CastStringToTimestampTz(precision)
760                }
761                _ => unreachable!("TimestampTz must resolve to TimestampTz"),
762            }
763        }
764        Type::Uuid => CastFunc::CastStringToUuid,
765        Type::Int2Vector => CastFunc::CastStringToInt2Vector,
766        Type::MzTimestamp => CastFunc::CastStringToMzTimestamp,
767        // JSON is ingested as JSONB (same as the old plan_cast path).
768        Type::Json => CastFunc::CastStringToJsonb,
769        Type::Array(elem) => {
770            let return_ty = resolve_pg_type_to_scalar_type(scx, ty)?;
771            let elem_cast = build_element_cast_expr(scx, elem, cast_oid_full_range)?;
772            CastFunc::CastStringToArray {
773                return_ty,
774                cast_expr: Box::new(elem_cast),
775            }
776        }
777        Type::List(elem) => {
778            let return_ty = resolve_pg_type_to_scalar_type(scx, ty)?;
779            let elem_cast = build_element_cast_expr(scx, elem, cast_oid_full_range)?;
780            CastFunc::CastStringToList {
781                return_ty,
782                cast_expr: Box::new(elem_cast),
783            }
784        }
785        Type::Map { value_type } => {
786            let return_ty = resolve_pg_type_to_scalar_type(scx, ty)?;
787            let value_cast = build_element_cast_expr(scx, value_type, cast_oid_full_range)?;
788            CastFunc::CastStringToMap {
789                return_ty,
790                cast_expr: Box::new(value_cast),
791            }
792        }
793        Type::Range { element_type } => {
794            let return_ty = resolve_pg_type_to_scalar_type(scx, ty)?;
795            let elem_cast = build_element_cast_expr(scx, element_type, cast_oid_full_range)?;
796            CastFunc::CastStringToRange {
797                return_ty,
798                cast_expr: Box::new(elem_cast),
799            }
800        }
801        // reg* types require subquery-based casts that storage cannot
802        // evaluate. Users can ingest them as text via TEXT COLUMNS.
803        Type::RegType | Type::RegClass | Type::RegProc => {
804            return Err(PlanError::TableContainsUningestableTypes {
805                name: String::new(),
806                type_: ty.name().to_string(),
807                column: String::new(),
808            });
809        }
810        other => {
811            return Err(PlanError::TableContainsUningestableTypes {
812                name: String::new(),
813                type_: other.name().to_string(),
814                column: String::new(),
815            });
816        }
817    };
818    Ok(Some(cast_func))
819}
820
821/// Build the element cast expression for container types (Array, List, Map,
822/// Range). The element expression operates on a single-column input row
823/// containing the text-encoded element at column 0.
824fn build_element_cast_expr(
825    scx: &StatementContext,
826    elem_ty: &mz_pgrepr::Type,
827    cast_oid_full_range: bool,
828) -> Result<StorageScalarExpr, PlanError> {
829    match pg_type_to_cast_func(scx, elem_ty, cast_oid_full_range)? {
830        None => Ok(StorageScalarExpr::Column(0)),
831        Some(cast_func) => Ok(StorageScalarExpr::CallUnary(
832            cast_func,
833            Box::new(StorageScalarExpr::Column(0)),
834        )),
835    }
836}
837
838mod privileges {
839    use mz_postgres_util::{PostgresError, query, sql};
840
841    use super::*;
842    use crate::plan::PlanError;
843    use crate::pure::PgSourcePurificationError;
844
845    async fn check_schema_privileges(client: &Client, table_oids: &[Oid]) -> Result<(), PlanError> {
846        let invalid_schema_privileges_rows = query(
847            client,
848            sql!(
849                "
850                WITH distinct_namespace AS (
851                    SELECT
852                        DISTINCT n.oid, n.nspname AS schema_name
853                    FROM unnest($1::OID[]) AS oids (oid)
854                    JOIN pg_class AS c ON c.oid = oids.oid
855                    JOIN pg_namespace AS n ON c.relnamespace = n.oid
856                )
857                SELECT d.schema_name
858                FROM distinct_namespace AS d
859                WHERE
860                    NOT has_schema_privilege(CURRENT_USER::TEXT, d.oid, 'usage')"
861            ),
862            &[&table_oids],
863        )
864        .await?;
865
866        let mut invalid_schema_privileges = invalid_schema_privileges_rows
867            .into_iter()
868            .map(|row| row.get("schema_name"))
869            .collect::<Vec<String>>();
870
871        if invalid_schema_privileges.is_empty() {
872            Ok(())
873        } else {
874            invalid_schema_privileges.sort();
875            Err(PgSourcePurificationError::UserLacksUsageOnSchemas {
876                schemas: invalid_schema_privileges,
877            })?
878        }
879    }
880
881    /// Ensure that the user specified in `config` has:
882    ///
883    /// -`SELECT` privileges for the identified `tables`.
884    ///
885    ///  `tables`'s elements should be of the structure `[<schema name>, <table name>]`.
886    ///
887    /// - `USAGE` privileges on the schemas references in `tables`.
888    ///
889    /// # Panics
890    /// If `config` does not specify a user.
891    pub async fn check_table_privileges(
892        client: &Client,
893        table_oids: &[Oid],
894    ) -> Result<(), PlanError> {
895        check_schema_privileges(client, table_oids).await?;
896
897        let invalid_table_privileges_rows = query(
898            client,
899            sql!(
900                "
901            SELECT
902                format('%I.%I', n.nspname, c.relname) AS schema_qualified_table_name
903             FROM unnest($1::oid[]) AS oids (oid)
904             JOIN
905                 pg_class c ON c.oid = oids.oid
906             JOIN
907                 pg_namespace n ON c.relnamespace = n.oid
908             WHERE NOT has_table_privilege(CURRENT_USER::text, c.oid, 'select')"
909            ),
910            &[&table_oids],
911        )
912        .await?;
913
914        let mut invalid_table_privileges = invalid_table_privileges_rows
915            .into_iter()
916            .map(|row| row.get("schema_qualified_table_name"))
917            .collect::<Vec<String>>();
918
919        if invalid_table_privileges.is_empty() {
920            Ok(())
921        } else {
922            invalid_table_privileges.sort();
923            Err(PgSourcePurificationError::UserLacksSelectOnTables {
924                tables: invalid_table_privileges,
925            })?
926        }
927    }
928
929    /// Ensure that the user specified in `config` can read data from tables if row level security
930    /// (RLS) is enabled. If the user/role does not have the BYPASSRLS attribute set, there is
931    /// the possibility that MZ may not be able to read all data during the snapshot, which would
932    /// result in missing data.
933    pub async fn check_rls_privileges(
934        client: &Client,
935        table_oids: &[Oid],
936    ) -> Result<(), PlanError> {
937        match mz_postgres_util::validate_no_rls_policies(client, table_oids).await {
938            Ok(_) => Ok(()),
939            Err(err) => match err {
940                // This is a little gross to do, but PlanError::PostgresConnectionErr implements
941                // From<PostgresError>, and the error in that case would be
942                // "failed to connect to PostgreSQL database", which doesn't make any sense.
943                PostgresError::BypassRLSRequired(tables) => {
944                    Err(PgSourcePurificationError::BypassRLSRequired { tables })?
945                }
946                _ => Err(err)?,
947            },
948        }
949    }
950}
951
952mod replica_identity {
953    use mz_postgres_util::{query, sql};
954
955    use super::*;
956    use crate::plan::PlanError;
957    use crate::pure::PgSourcePurificationError;
958
959    /// Ensures that all provided OIDs are tables with `REPLICA IDENTITY FULL`.
960    pub async fn check_replica_identity_full(
961        client: &Client,
962        table_oids: &[Oid],
963    ) -> Result<(), PlanError> {
964        let invalid_replica_identity_rows = query(
965            client,
966            sql!(
967                "
968            SELECT
969                format('%I.%I', n.nspname, c.relname) AS schema_qualified_table_name
970             FROM unnest($1::oid[]) AS oids (oid)
971             JOIN
972                 pg_class c ON c.oid = oids.oid
973             JOIN
974                 pg_namespace n ON c.relnamespace = n.oid
975             WHERE relreplident != 'f' OR relreplident IS NULL;"
976            ),
977            &[&table_oids],
978        )
979        .await?;
980
981        let mut invalid_replica_identity = invalid_replica_identity_rows
982            .into_iter()
983            .map(|row| row.get("schema_qualified_table_name"))
984            .collect::<Vec<String>>();
985
986        if invalid_replica_identity.is_empty() {
987            Ok(())
988        } else {
989            invalid_replica_identity.sort();
990            Err(PgSourcePurificationError::NotTablesWReplicaIdentityFull {
991                items: invalid_replica_identity,
992            })?
993        }
994    }
995}