Skip to main content

datafusion_pg_catalog/sql/
rules.rs

1use std::collections::HashMap;
2use std::collections::HashSet;
3use std::fmt::Debug;
4use std::ops::ControlFlow;
5
6use crate::pg_catalog::PG_CATALOG_TABLES;
7
8use datafusion::sql::sqlparser::ast::Array;
9use datafusion::sql::sqlparser::ast::ArrayElemTypeDef;
10use datafusion::sql::sqlparser::ast::BinaryOperator;
11use datafusion::sql::sqlparser::ast::CastKind;
12use datafusion::sql::sqlparser::ast::DataType;
13use datafusion::sql::sqlparser::ast::Expr;
14use datafusion::sql::sqlparser::ast::Function;
15use datafusion::sql::sqlparser::ast::FunctionArg;
16use datafusion::sql::sqlparser::ast::FunctionArgExpr;
17use datafusion::sql::sqlparser::ast::FunctionArgumentList;
18use datafusion::sql::sqlparser::ast::FunctionArguments;
19use datafusion::sql::sqlparser::ast::Ident;
20use datafusion::sql::sqlparser::ast::LimitClause;
21use datafusion::sql::sqlparser::ast::ObjectName;
22use datafusion::sql::sqlparser::ast::ObjectNamePart;
23use datafusion::sql::sqlparser::ast::OrderByKind;
24use datafusion::sql::sqlparser::ast::Query;
25use datafusion::sql::sqlparser::ast::Select;
26use datafusion::sql::sqlparser::ast::SelectItem;
27use datafusion::sql::sqlparser::ast::SelectItemQualifiedWildcardKind;
28use datafusion::sql::sqlparser::ast::SetExpr;
29use datafusion::sql::sqlparser::ast::Statement;
30use datafusion::sql::sqlparser::ast::TableFactor;
31use datafusion::sql::sqlparser::ast::TableWithJoins;
32use datafusion::sql::sqlparser::ast::UnaryOperator;
33use datafusion::sql::sqlparser::ast::Value;
34use datafusion::sql::sqlparser::ast::ValueWithSpan;
35use datafusion::sql::sqlparser::ast::VisitMut;
36use datafusion::sql::sqlparser::ast::Visitor;
37use datafusion::sql::sqlparser::ast::VisitorMut;
38use datafusion::sql::sqlparser::dialect::PostgreSqlDialect;
39use datafusion::sql::sqlparser::parser::Parser;
40
41pub trait SqlStatementRewriteRule: Send + Sync + Debug {
42    fn rewrite(&self, s: Statement) -> Statement;
43}
44
45/// Rewrite rule for adding alias to duplicated projection
46///
47/// This rule is to deal with sql like `SELECT n.oid, n.* FROM n`, which is a
48/// valid statement in postgres. But datafusion treat it as illegal because of
49/// duplicated column oid in projection.
50///
51/// This rule will add alias to column, when there is a wildcard found in
52/// projection.
53#[derive(Debug)]
54pub struct AliasDuplicatedProjectionRewrite;
55
56impl AliasDuplicatedProjectionRewrite {
57    // Rewrites a SELECT statement to alias explicit columns from the same table as a qualified wildcard.
58    fn rewrite_select_with_alias(select: &mut Box<Select>) {
59        // 1. Collect all table aliases from qualified wildcards.
60        let mut wildcard_tables = Vec::new();
61        let mut has_simple_wildcard = false;
62        for p in &select.projection {
63            match p {
64                SelectItem::QualifiedWildcard(name, _) => match name {
65                    SelectItemQualifiedWildcardKind::ObjectName(objname) => {
66                        // for n.oid,
67                        let idents = objname
68                            .0
69                            .iter()
70                            .map(|v| v.as_ident().unwrap().value.clone())
71                            .collect::<Vec<_>>()
72                            .join(".");
73
74                        wildcard_tables.push(idents);
75                    }
76                    SelectItemQualifiedWildcardKind::Expr(_expr) => {
77                        // FIXME:
78                    }
79                },
80                SelectItem::Wildcard(_) => {
81                    has_simple_wildcard = true;
82                }
83                _ => {}
84            }
85        }
86
87        // If there are no qualified wildcards, there's nothing to do.
88        if wildcard_tables.is_empty() && !has_simple_wildcard {
89            return;
90        }
91
92        // 2. Rewrite the projection, adding aliases to matching columns.
93        let mut new_projection = vec![];
94        for p in select.projection.drain(..) {
95            match p {
96                SelectItem::UnnamedExpr(expr) => {
97                    let alias_partial = match &expr {
98                        // Case for `oid` (unqualified identifier)
99                        Expr::Identifier(ident) => Some(ident.clone()),
100                        // Case for `n.oid` (compound identifier)
101                        Expr::CompoundIdentifier(idents) => {
102                            // compare every ident but the last
103                            if idents.len() > 1 {
104                                let table_name = &idents[..idents.len() - 1]
105                                    .iter()
106                                    .map(|i| i.value.clone())
107                                    .collect::<Vec<_>>()
108                                    .join(".");
109                                if wildcard_tables.iter().any(|name| name == table_name) {
110                                    Some(idents[idents.len() - 1].clone())
111                                } else {
112                                    None
113                                }
114                            } else {
115                                None
116                            }
117                        }
118                        _ => None,
119                    };
120
121                    if let Some(name) = alias_partial {
122                        let alias = format!("__alias_{name}");
123                        new_projection.push(SelectItem::ExprWithAlias {
124                            expr,
125                            alias: Ident::new(alias),
126                        });
127                    } else {
128                        new_projection.push(SelectItem::UnnamedExpr(expr));
129                    }
130                }
131                // Preserve existing aliases and wildcards.
132                _ => new_projection.push(p),
133            }
134        }
135        select.projection = new_projection;
136    }
137}
138
139impl SqlStatementRewriteRule for AliasDuplicatedProjectionRewrite {
140    fn rewrite(&self, mut statement: Statement) -> Statement {
141        if let Statement::Query(query) = &mut statement
142            && let SetExpr::Select(select) = query.body.as_mut()
143        {
144            Self::rewrite_select_with_alias(select);
145        }
146
147        statement
148    }
149}
150
151/// Prepend qualifier for order by or filter when there is qualified wildcard
152///
153/// Postgres allows unqualified identifier in ORDER BY and FILTER but it's not
154/// accepted by datafusion.
155#[derive(Debug)]
156pub struct ResolveUnqualifiedIdentifier;
157
158impl ResolveUnqualifiedIdentifier {
159    fn rewrite_unqualified_identifiers(query: &mut Box<Query>) {
160        if let SetExpr::Select(select) = query.body.as_mut() {
161            // Step 1: Find all table aliases from FROM and JOIN clauses.
162            let table_aliases = Self::get_table_aliases(&select.from);
163
164            // Step 2: Check for a single qualified wildcard in the projection.
165            let qualified_wildcard_alias = Self::get_qualified_wildcard_alias(&select.projection);
166            if qualified_wildcard_alias.is_none() || table_aliases.is_empty() {
167                return; // Conditions not met.
168            }
169
170            let wildcard_alias = qualified_wildcard_alias.unwrap();
171
172            // Step 2.5: Collect all projection aliases to avoid rewriting them
173            let projection_aliases = Self::get_projection_aliases(&select.projection);
174
175            // Step 3: Rewrite expressions in the WHERE and ORDER BY clauses.
176            if let Some(selection) = &mut select.selection {
177                Self::rewrite_expr(
178                    selection,
179                    &wildcard_alias,
180                    &table_aliases,
181                    &projection_aliases,
182                );
183            }
184
185            if let Some(OrderByKind::Expressions(order_by_exprs)) =
186                query.order_by.as_mut().map(|o| &mut o.kind)
187            {
188                for order_by_expr in order_by_exprs {
189                    Self::rewrite_expr(
190                        &mut order_by_expr.expr,
191                        &wildcard_alias,
192                        &table_aliases,
193                        &projection_aliases,
194                    );
195                }
196            }
197        }
198    }
199
200    fn get_table_aliases(tables: &[TableWithJoins]) -> HashSet<String> {
201        let mut aliases = HashSet::new();
202        for table_with_joins in tables {
203            if let TableFactor::Table {
204                alias: Some(alias), ..
205            } = &table_with_joins.relation
206            {
207                aliases.insert(alias.name.value.clone());
208            }
209            for join in &table_with_joins.joins {
210                if let TableFactor::Table {
211                    alias: Some(alias), ..
212                } = &join.relation
213                {
214                    aliases.insert(alias.name.value.clone());
215                }
216            }
217        }
218        aliases
219    }
220
221    fn get_qualified_wildcard_alias(projection: &[SelectItem]) -> Option<String> {
222        let mut qualified_wildcards = projection
223            .iter()
224            .filter_map(|item| {
225                if let SelectItem::QualifiedWildcard(
226                    SelectItemQualifiedWildcardKind::ObjectName(objname),
227                    _,
228                ) = item
229                {
230                    Some(
231                        objname
232                            .0
233                            .iter()
234                            .map(|v| v.as_ident().unwrap().value.clone())
235                            .collect::<Vec<_>>()
236                            .join("."),
237                    )
238                } else {
239                    None
240                }
241            })
242            .collect::<Vec<_>>();
243
244        if qualified_wildcards.len() == 1 {
245            Some(qualified_wildcards.remove(0))
246        } else {
247            None
248        }
249    }
250
251    fn get_projection_aliases(projection: &[SelectItem]) -> HashSet<String> {
252        let mut aliases = HashSet::new();
253        for item in projection {
254            match item {
255                SelectItem::ExprWithAlias { alias, .. } => {
256                    aliases.insert(alias.value.clone());
257                }
258                SelectItem::UnnamedExpr(Expr::Identifier(ident)) => {
259                    aliases.insert(ident.value.clone());
260                }
261                _ => {}
262            }
263        }
264        aliases
265    }
266
267    fn rewrite_expr(
268        expr: &mut Expr,
269        wildcard_alias: &str,
270        table_aliases: &HashSet<String>,
271        projection_aliases: &HashSet<String>,
272    ) {
273        match expr {
274            // If the identifier is not a table alias itself and not already aliased in projection, rewrite it.
275            Expr::Identifier(ident)
276                if !table_aliases.contains(&ident.value)
277                    && !projection_aliases.contains(&ident.value) =>
278            {
279                *expr = Expr::CompoundIdentifier(vec![
280                    Ident::new(wildcard_alias.to_string()),
281                    ident.clone(),
282                ]);
283            }
284            Expr::BinaryOp { left, right, .. } => {
285                Self::rewrite_expr(left, wildcard_alias, table_aliases, projection_aliases);
286                Self::rewrite_expr(right, wildcard_alias, table_aliases, projection_aliases);
287            }
288            // Add more cases for other expression types as needed (e.g., `InList`, `Between`, etc.)
289            _ => {}
290        }
291    }
292}
293
294impl SqlStatementRewriteRule for ResolveUnqualifiedIdentifier {
295    fn rewrite(&self, mut statement: Statement) -> Statement {
296        if let Statement::Query(query) = &mut statement {
297            Self::rewrite_unqualified_identifiers(query);
298        }
299
300        statement
301    }
302}
303
304/// Rewrite the Postgres `ANY`/`ALL` quantified comparison operators over
305/// arrays into DataFusion's `array_contains` function.
306///
307/// Postgres `x <op> ANY (arr)` / `x <op> ALL (arr)` have no direct DataFusion
308/// equivalent, so this rule lowers the two cases that map cleanly onto
309/// membership:
310///
311/// * `x =  ANY(arr)`  -> `array_contains(arr, x)`  (x equals some element)
312/// * `x <> ALL(arr)`  -> `NOT array_contains(arr, x)` (x differs from every
313///   element, i.e. is not a member)
314///
315/// The other two combinations are **not** handled, because `array_contains`
316/// only expresses membership, not universal quantification:
317///
318/// * `x <> ANY(arr)` (x differs from *some* element) is true for essentially
319///   every non-empty array and has no faithful lowering to membership.
320/// * `x =  ALL(arr)` (x equals *every* element) needs "all elements are x",
321///   which membership cannot express without an additional length/count check.
322///
323/// These are left untouched; if a client query uses them, DataFusion reports
324/// the unsupported operator rather than silently producing wrong results.
325///
326/// # String-literal array form
327///
328/// Postgres allows an array as a single-quoted string literal, e.g.
329/// `x = ANY('{r, l, e}')`. When the right operand is such a literal this rule
330/// parses it into an `ARRAY[...]` expression first. The parsing is **naive**:
331/// it splits on commas and treats every element as a string. That is correct
332/// for the string-array case clients actually send (privilege/role char arrays,
333/// `contyp`/`stxkind` style columns), but it does not handle quoted elements
334/// containing commas, and it assumes string element types for non-string array
335/// literals. A non-string-literal right operand (a column, `ARRAY[...]`, or a
336/// function call) is passed through unchanged.
337#[derive(Debug)]
338pub struct RewriteArrayAnyAllOperation;
339
340struct RewriteArrayAnyAllOperationVisitor;
341
342impl RewriteArrayAnyAllOperationVisitor {
343    fn any_to_array_contains(&self, left: &Expr, right: &Expr) -> Expr {
344        let array = if let Expr::Value(ValueWithSpan {
345            value: Value::SingleQuotedString(array_literal),
346            ..
347        }) = right
348        {
349            let array_literal = array_literal.trim();
350            if array_literal.starts_with('{') && array_literal.ends_with('}') {
351                let items = array_literal.trim_matches(|c| c == '{' || c == '}' || c == ' ');
352                let items = items.split(',').map(|s| s.trim()).filter(|s| !s.is_empty());
353
354                // Elements are treated as strings -- see the rule-level doc
355                // comment for why this naive split is sufficient for the array
356                // literals clients actually send (string-typed arrays) but does
357                // not handle quoted elements containing commas.
358                let elems = items
359                    .map(|s| {
360                        Expr::Value(Value::SingleQuotedString(s.to_string()).with_empty_span())
361                    })
362                    .collect();
363                Expr::Array(Array {
364                    elem: elems,
365                    named: true,
366                })
367            } else {
368                right.clone()
369            }
370        } else {
371            right.clone()
372        };
373
374        Expr::Function(Function {
375            name: ObjectName::from(vec![Ident::new("array_contains")]),
376            args: FunctionArguments::List(FunctionArgumentList {
377                args: vec![
378                    FunctionArg::Unnamed(FunctionArgExpr::Expr(array)),
379                    FunctionArg::Unnamed(FunctionArgExpr::Expr(left.clone())),
380                ],
381                duplicate_treatment: None,
382                clauses: vec![],
383            }),
384            uses_odbc_syntax: false,
385            parameters: FunctionArguments::None,
386            filter: None,
387            null_treatment: None,
388            over: None,
389            within_group: vec![],
390        })
391    }
392}
393
394impl VisitorMut for RewriteArrayAnyAllOperationVisitor {
395    type Break = ();
396
397    fn pre_visit_expr(&mut self, expr: &mut Expr) -> ControlFlow<Self::Break> {
398        match expr {
399            Expr::AnyOp {
400                left,
401                compare_op,
402                right,
403                ..
404            } => match compare_op {
405                BinaryOperator::Eq => {
406                    *expr = self.any_to_array_contains(left.as_ref(), right.as_ref());
407                }
408                BinaryOperator::NotEq => {
409                    // x <> ANY(arr): true if x differs from SOME element. That
410                    // is true for almost every non-empty array and cannot be
411                    // lowered to `array_contains`; leave it for DataFusion to
412                    // report as unsupported.
413                }
414                _ => {}
415            },
416            Expr::AllOp {
417                left,
418                compare_op,
419                right,
420            } => match compare_op {
421                BinaryOperator::Eq => {
422                    // x = ALL(arr): true if EVERY element equals x. Membership
423                    // alone cannot express this; leave it for DataFusion to
424                    // report as unsupported.
425                }
426                BinaryOperator::NotEq => {
427                    *expr = Expr::UnaryOp {
428                        op: UnaryOperator::Not,
429                        expr: Box::new(self.any_to_array_contains(left.as_ref(), right.as_ref())),
430                    }
431                }
432                _ => {}
433            },
434            _ => {}
435        }
436
437        ControlFlow::Continue(())
438    }
439}
440
441impl SqlStatementRewriteRule for RewriteArrayAnyAllOperation {
442    fn rewrite(&self, mut s: Statement) -> Statement {
443        let mut visitor = RewriteArrayAnyAllOperationVisitor;
444
445        let _ = s.visit(&mut visitor);
446
447        s
448    }
449}
450
451/// Prepend qualifier to table_name
452///
453/// Postgres has pg_catalog in search_path by default so it allow access to
454/// `pg_namespace` without `pg_catalog.` qualifier.
455///
456/// Only names of known pg_catalog relations are qualified. A simple `pg_`
457/// prefix check would also rewrite user tables such as `pg_compat_test`.
458#[derive(Debug)]
459pub struct PrependUnqualifiedPgTableName;
460
461fn is_pg_catalog_table(name: &str) -> bool {
462    PG_CATALOG_TABLES
463        .iter()
464        .any(|table| table.eq_ignore_ascii_case(name))
465}
466
467struct PrependUnqualifiedPgTableNameVisitor;
468
469impl VisitorMut for PrependUnqualifiedPgTableNameVisitor {
470    type Break = ();
471
472    fn pre_visit_table_factor(
473        &mut self,
474        table_factor: &mut TableFactor,
475    ) -> ControlFlow<Self::Break> {
476        if let TableFactor::Table { name, args, .. } = table_factor {
477            // not a table function
478            if args.is_none()
479                && name.0.len() == 1
480                && let ObjectNamePart::Identifier(ident) = &name.0[0]
481                && is_pg_catalog_table(&ident.value)
482            {
483                *name = ObjectName(vec![
484                    ObjectNamePart::Identifier(Ident::new("pg_catalog")),
485                    name.0[0].clone(),
486                ]);
487            }
488        }
489
490        ControlFlow::Continue(())
491    }
492}
493
494impl SqlStatementRewriteRule for PrependUnqualifiedPgTableName {
495    fn rewrite(&self, mut s: Statement) -> Statement {
496        let mut visitor = PrependUnqualifiedPgTableNameVisitor;
497
498        let _ = s.visit(&mut visitor);
499        s
500    }
501}
502
503#[derive(Debug)]
504pub struct FixArrayLiteral;
505
506struct FixArrayLiteralVisitor;
507
508impl FixArrayLiteralVisitor {
509    fn is_string_type(dt: &DataType) -> bool {
510        matches!(
511            dt,
512            DataType::Text | DataType::Varchar(_) | DataType::Char(_) | DataType::String(_)
513        )
514    }
515}
516
517impl VisitorMut for FixArrayLiteralVisitor {
518    type Break = ();
519
520    fn pre_visit_expr(&mut self, expr: &mut Expr) -> ControlFlow<Self::Break> {
521        if let Expr::Cast {
522            kind,
523            expr,
524            data_type,
525            ..
526        } = expr
527            && kind == &CastKind::DoubleColon
528            && let DataType::Array(arr) = data_type
529        {
530            // cast some to
531            if let Expr::Value(ValueWithSpan {
532                value: Value::SingleQuotedString(array_literal),
533                ..
534            }) = expr.as_ref()
535            {
536                let items = array_literal.trim_matches(|c| c == '{' || c == '}' || c == ' ');
537                let items = items.split(',').map(|s| s.trim()).filter(|s| !s.is_empty());
538
539                let is_text = match arr {
540                    ArrayElemTypeDef::AngleBracket(dt) => Self::is_string_type(dt.as_ref()),
541                    ArrayElemTypeDef::SquareBracket(dt, _) => Self::is_string_type(dt.as_ref()),
542                    ArrayElemTypeDef::Parenthesis(dt) => Self::is_string_type(dt.as_ref()),
543                    _ => false,
544                };
545
546                let elems = items
547                    .map(|s| {
548                        if is_text {
549                            Expr::Value(Value::SingleQuotedString(s.to_string()).with_empty_span())
550                        } else {
551                            Expr::Value(Value::Number(s.to_string(), false).with_empty_span())
552                        }
553                    })
554                    .collect();
555                **expr = Expr::Array(Array {
556                    elem: elems,
557                    named: true,
558                });
559            }
560        }
561
562        ControlFlow::Continue(())
563    }
564}
565
566impl SqlStatementRewriteRule for FixArrayLiteral {
567    fn rewrite(&self, mut s: Statement) -> Statement {
568        let mut visitor = FixArrayLiteralVisitor;
569
570        let _ = s.visit(&mut visitor);
571        s
572    }
573}
574
575/// Strip the schema qualifier from callable names.
576///
577/// DataFusion resolves functions (including table functions) by bare name in
578/// a flat namespace -- it has no notion of a schema-qualified function path.
579/// Postgres clients routinely write the qualifier explicitly, most often
580/// `pg_catalog.` (e.g. `pg_catalog.array_to_string(...)`,
581/// `pg_catalog.pg_get_keywords()`), so this rule drops the leading
582/// identifier(s) from any multi-part function or table-function name and
583/// keeps only the last segment.
584///
585/// Type-cast qualifiers such as `pg_catalog.text` / `pg_catalog.int2[]` used
586/// to be handled here too, but are now resolved by the [`PgOidTypePlanner`]
587/// type planner (which sees the cast target type at planning time and maps the
588/// pg name to its Arrow type).
589///
590/// [`PgOidTypePlanner`]: crate::pg_catalog::oid_type_planner::PgOidTypePlanner
591#[derive(Debug)]
592pub struct StripCallableQualifier;
593
594struct StripCallableQualifierVisitor;
595
596impl VisitorMut for StripCallableQualifierVisitor {
597    type Break = ();
598
599    fn pre_visit_table_factor(
600        &mut self,
601        table_factor: &mut TableFactor,
602    ) -> ControlFlow<Self::Break> {
603        // Strip qualifier from table function names (any schema, not just
604        // pg_catalog): DF resolves table functions by bare name.
605        if let TableFactor::Table { name, args, .. } = table_factor
606            && args.is_some()
607        {
608            // multiple idents in name means it's a qualified table name
609            if name.0.len() > 1
610                && let Some(last_ident) = name.0.pop()
611            {
612                *name = ObjectName(vec![last_ident]);
613            }
614        }
615        ControlFlow::Continue(())
616    }
617
618    fn pre_visit_expr(&mut self, expr: &mut Expr) -> ControlFlow<Self::Break> {
619        // Strip qualifier from function names (any schema, not just
620        // pg_catalog): DF resolves functions by bare name.
621        if let Expr::Function(function) = expr {
622            let name = &mut function.name;
623            if name.0.len() > 1
624                && let Some(last_ident) = name.0.pop()
625            {
626                *name = ObjectName(vec![last_ident]);
627            }
628        }
629        ControlFlow::Continue(())
630    }
631}
632
633impl SqlStatementRewriteRule for StripCallableQualifier {
634    fn rewrite(&self, mut s: Statement) -> Statement {
635        let mut visitor = StripCallableQualifierVisitor;
636
637        let _ = s.visit(&mut visitor);
638        s
639    }
640}
641
642/// Rewrite postgres built-in special registers that may be referenced
643/// without parentheses into the function-call form DataFusion understands.
644///
645/// Postgres allows several built-in special registers to be used without
646/// parentheses -- e.g. `current_user`, `current_catalog`, `current_schema`.
647/// DataFusion only exposes these as function calls, so this rule rewrites the
648/// parenthesis-less forms. sqlparser represents them in two different ways,
649/// so the rule handles both:
650///
651///   * `current_user` and `current_catalog` are sqlparser-special-cased
652///     keywords that already parse as a zero-argument `Function` (with
653///     `FunctionArguments::None`). They only need renaming, because DataFusion
654///     exposes them under different names: `current_user` -> `session_user`,
655///     `current_catalog` -> `current_database`.
656///   * `current_schema` parses as a bare identifier and is wrapped into a
657///     zero-argument function call: `current_schema` -> `current_schema()`.
658///
659/// Because the rewritten AST is re-serialised and re-parsed by DataFusion
660/// (see `handlers.rs`), the emitted form must round-trip through the postgres
661/// dialect. sqlparser only accepts the parenthesis-less spelling for the
662/// special-cased keywords [`PARENTHESIS_LESS_KEYWORDS`]; every other target
663/// (e.g. `current_database`) must be emitted with explicit `()`.
664///
665/// Note: `version` is deliberately NOT handled here -- in postgres it is a
666/// regular function, not a special register, so `SELECT version` (no parens)
667/// is invalid and never reaches this rule.
668#[derive(Debug)]
669pub struct CurrentUserVariableToSessionUserFunctionCall;
670
671/// `(postgres function name, target function name)` for the parenthesis-less
672/// `Function` nodes produced by sqlparser that need renaming.
673const BUILTIN_FUNCTION_RENAME: &[(&str, &str)] = &[
674    ("current_user", "session_user"),
675    ("current_catalog", "current_database"),
676];
677
678/// sqlparser special-cases these keywords into a parenthesis-less zero-argument
679/// `Function` (see sqlparser's `Parser::parse_word`). They -- and only they --
680/// may be emitted without parentheses; `name()` does not re-parse for them, so
681/// any other target must be serialised as an explicit `name()` call.
682const PARENTHESIS_LESS_KEYWORDS: &[&str] =
683    &["current_catalog", "current_user", "session_user", "user"];
684
685/// `(identifier, target function name)` for bare identifiers that must be
686/// wrapped into a zero-argument function call.
687const BARE_IDENTIFIER_TO_FUNCTION: &[(&str, &str)] = &[("current_schema", "current_schema")];
688
689fn empty_function_call(name: &str) -> Expr {
690    Expr::Function(Function {
691        name: ObjectName::from(vec![Ident::new(name)]),
692        args: FunctionArguments::List(FunctionArgumentList {
693            args: vec![],
694            duplicate_treatment: None,
695            clauses: vec![],
696        }),
697        uses_odbc_syntax: false,
698        parameters: FunctionArguments::None,
699        filter: None,
700        null_treatment: None,
701        over: None,
702        within_group: vec![],
703    })
704}
705
706struct CurrentUserVariableToSessionUserFunctionCallVisitor;
707
708impl CurrentUserVariableToSessionUserFunctionCallVisitor {
709    fn last_ident_lower(name: &ObjectName) -> Option<String> {
710        name.0
711            .last()
712            .and_then(|part| part.as_ident())
713            .map(|ident| ident.value.to_lowercase())
714    }
715}
716
717impl VisitorMut for CurrentUserVariableToSessionUserFunctionCallVisitor {
718    type Break = ();
719
720    fn pre_visit_expr(&mut self, expr: &mut Expr) -> ControlFlow<Self::Break> {
721        // Bare identifier -> zero-argument function call.
722        if let Expr::Identifier(ident) = expr
723            && ident.quote_style.is_none()
724        {
725            let lower = ident.value.to_lowercase();
726            if let Some(&(_, target)) = BARE_IDENTIFIER_TO_FUNCTION
727                .iter()
728                .find(|(name, _)| *name == lower)
729            {
730                *expr = empty_function_call(target);
731            }
732        }
733
734        // Parenthesis-less `Function` (or explicit call) -> rename where needed.
735        // A parenthesis-less `FunctionArguments::None` is only kept as-is when
736        // the *target* is itself a parenthesis-less special keyword; otherwise
737        // it is normalised to an empty argument list so the rewritten SQL
738        // re-parses as a real `name()` call (the parenthesis-less spelling does
739        // not round-trip for non-special names such as `current_database`).
740        if let Expr::Function(func) = expr
741            && let Some(fname) = Self::last_ident_lower(&func.name)
742            && let Some(&(_, target)) = BUILTIN_FUNCTION_RENAME
743                .iter()
744                .find(|(name, _)| *name == fname)
745        {
746            func.name = ObjectName::from(vec![Ident::new(target)]);
747            if matches!(func.args, FunctionArguments::None)
748                && !PARENTHESIS_LESS_KEYWORDS.contains(&target)
749            {
750                func.args = FunctionArguments::List(FunctionArgumentList {
751                    args: vec![],
752                    duplicate_treatment: None,
753                    clauses: vec![],
754                });
755            }
756        }
757
758        ControlFlow::Continue(())
759    }
760}
761
762impl SqlStatementRewriteRule for CurrentUserVariableToSessionUserFunctionCall {
763    fn rewrite(&self, mut s: Statement) -> Statement {
764        let mut visitor = CurrentUserVariableToSessionUserFunctionCallVisitor;
765
766        let _ = s.visit(&mut visitor);
767        s
768    }
769}
770
771/// Strip Postgres `COLLATE` clauses.
772///
773/// Postgres allows trailing `COLLATE <schema>.<collation>` on expressions
774/// (e.g. `c.relname COLLATE pg_catalog.default`). DataFusion has no notion of
775/// collation and rejects this syntax at parse time, so strip the clause and
776/// keep the inner expression. The collation is irrelevant to DataFusion's
777/// byte-wise string comparison anyway.
778#[derive(Debug)]
779pub struct StripCollate;
780
781struct StripCollateVisitor;
782
783impl VisitorMut for StripCollateVisitor {
784    type Break = ();
785
786    fn pre_visit_expr(&mut self, expr: &mut Expr) -> ControlFlow<Self::Break> {
787        if let Expr::Collate { expr: inner, .. } = expr {
788            *expr = inner.as_ref().clone();
789        }
790        ControlFlow::Continue(())
791    }
792}
793
794impl SqlStatementRewriteRule for StripCollate {
795    fn rewrite(&self, mut s: Statement) -> Statement {
796        let mut visitor = StripCollateVisitor;
797        let _ = s.visit(&mut visitor);
798        s
799    }
800}
801
802/// Rewrite Postgres `OPERATOR(schema.name)` call syntax to the bare operator.
803///
804/// Postgres lets clients force an operator's schema with
805/// `lhs OPERATOR(pg_catalog.~) rhs`. sqlparser represents this as a
806/// [`BinaryOperator::PGCustomBinaryOperator`]; DataFusion only understands the
807/// built-in operator variants, so map every `pg_catalog.<regex-op>` we see
808/// back to its builtin form:
809///
810/// | pg_catalog name | builtin operator            |
811/// | --------------- | --------------------------- |
812/// | `~`             | `PGRegexMatch`    (`~`)     |
813/// | `~*`            | `PGRegexIMatch`   (`~*`)    |
814/// | `!~`            | `PGRegexNotMatch` (`!~`)    |
815/// | `!~*`           | `PGRegexNotIMatch`(`!~*`)   |
816///
817/// Only the four regex operators are mapped, because those are the ones
818/// clients emit via `OPERATOR(...)` in practice (psql's `\d` queries use
819/// `OPERATOR(pg_catalog.~)`). Any other operator name is left untouched for
820/// DataFusion to report.
821#[derive(Debug)]
822pub struct RewritePgCatalogOperator;
823
824struct RewritePgCatalogOperatorVisitor;
825
826impl VisitorMut for RewritePgCatalogOperatorVisitor {
827    type Break = ();
828
829    fn pre_visit_expr(&mut self, expr: &mut Expr) -> ControlFlow<Self::Break> {
830        if let Expr::BinaryOp { op, .. } = expr
831            && let BinaryOperator::PGCustomBinaryOperator(ops) = op
832            && ops.first().is_some_and(|s| s == "pg_catalog")
833            && let Some(name) = ops.last().map(String::as_str)
834        {
835            // Map every `OPERATOR(pg_catalog.<regex-op>)` to its builtin form.
836            // Match on the operator name (last segment); the schema is checked
837            // above. Only the four regex ops have a builtin equivalent
838            // DataFusion understands, so any other name is left untouched.
839            *op = match name {
840                "~" => BinaryOperator::PGRegexMatch,
841                "~*" => BinaryOperator::PGRegexIMatch,
842                "!~" => BinaryOperator::PGRegexNotMatch,
843                "!~*" => BinaryOperator::PGRegexNotIMatch,
844                _ => return ControlFlow::Continue(()),
845            };
846        }
847        ControlFlow::Continue(())
848    }
849}
850
851impl SqlStatementRewriteRule for RewritePgCatalogOperator {
852    fn rewrite(&self, mut s: Statement) -> Statement {
853        let mut visitor = RewritePgCatalogOperatorVisitor;
854        let _ = s.visit(&mut visitor);
855        s
856    }
857}
858
859/// Rewrite forward oid-alias casts (`'x'::regclass`, `'public'::regnamespace`,
860/// ...) to oid values the way Postgres does.
861///
862/// Postgres oid-alias types cast a *name* to the matching catalog oid;
863/// DataFusion has no such types. This rule rewrites the **forward** (name->oid)
864/// direction at the AST layer, before DataFusion plans the query:
865///
866/// * a **numeric** string operand (`'16417'`) becomes a literal oid --
867///   Postgres treats a numeric string as the oid itself, and emitting a literal
868///   avoids embedding a `(SELECT ...)` in contexts DataFusion can't decorrelate
869///   (e.g. `VALUES ('16417'::regclass)` inside `IN (...)`);
870/// * a **name** string operand (`'public'`) becomes a scalar subquery against
871///   the backing catalog table. The subquery is plain SQL, so DataFusion
872///   resolves `pg_catalog.pg_namespace` / `pg_class` / `pg_type` / `pg_proc`
873///   through the catalog at plan time -- **no `TableProvider` or catalog handle
874///   is needed in the rule**, which is why this lives at the SQL layer rather
875///   than as an analyzer rule.
876///
877/// Only the forward direction is rewritten (operand is a string literal or a
878/// prepared-statement `$N` placeholder). Reverse / column-operand casts such
879/// as `prorettype::regtype::text` (oid -> name for display) are left untouched;
880/// the `PgOidTypePlanner` maps those cast types to `Int32` so they still parse.
881///
882/// # Limitation vs an analyzer rule
883///
884/// Because the SQL layer has no schema, this rule can only resolve casts that
885/// *explicitly* name an oid-alias type. The **implicit** form
886/// `oid_col = 'public'` (bare string vs an oid column) is not recognized here
887/// -- there's no cast in the AST to key off. Resolving that would require
888/// schema awareness (an analyzer rule + a catalog provider). In practice the
889/// only client query affected is blacklisted.
890#[derive(Debug)]
891pub struct RewriteRegCastToSubquery {
892    /// Pre-parsed `(kind -> query template)` map. Each template contains a
893    /// single `$1` placeholder into which the cast operand is substituted.
894    templates: HashMap<String, Box<Query>>,
895}
896
897/// One oid-alias type plus the name->oid lookup query that resolves it. The
898/// query must contain exactly one `$1` placeholder, into which the cast
899/// operand is substituted verbatim.
900struct RegCastSpec {
901    /// Bare lowercased type name, e.g. `"regclass"`. Both `regclass` and
902    /// `pg_catalog.regclass` (and `REGCLASS`, which sqlparser uppercases) are
903    /// matched against this after normalization.
904    type_name: &'static str,
905    query: &'static str,
906}
907
908const REG_CAST_SPECS: &[RegCastSpec] = &[
909    // regclass: relation name -> pg_class.oid
910    RegCastSpec {
911        type_name: "regclass",
912        query: "SELECT c.oid FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid CROSS JOIN (SELECT parse_ident($1::TEXT) AS parts) WHERE array_length(parts, 1) IN (1, 2) AND ((array_length(parts, 1) = 1 AND n.nspname = current_schema() AND c.relname = parts[1]) OR (array_length(parts, 1) = 2 AND n.nspname = parts[1] AND c.relname = parts[2]))",
913    },
914    // regnamespace: schema name -> pg_namespace.oid
915    RegCastSpec {
916        type_name: "regnamespace",
917        query: "SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = $1",
918    },
919    // regtype: type name -> pg_type.oid
920    RegCastSpec {
921        type_name: "regtype",
922        query: "SELECT oid FROM pg_catalog.pg_type WHERE typname = $1",
923    },
924    // regproc: function name -> pg_proc.oid
925    RegCastSpec {
926        type_name: "regproc",
927        query: "SELECT oid FROM pg_catalog.pg_proc WHERE proname = $1",
928    },
929];
930
931impl Default for RewriteRegCastToSubquery {
932    fn default() -> Self {
933        Self::new()
934    }
935}
936
937impl RewriteRegCastToSubquery {
938    pub fn new() -> Self {
939        let dialect = PostgreSqlDialect {};
940        let mut templates = HashMap::new();
941        for spec in REG_CAST_SPECS {
942            let query = Parser::parse_sql(&dialect, spec.query)
943                .map(|mut stmts| match stmts.remove(0) {
944                    Statement::Query(query) => query,
945                    _ => unreachable!("REG_CAST_SPECS entries are all queries"),
946                })
947                .expect("REG_CAST_SPECS entries must parse");
948            templates.insert(spec.type_name.to_owned(), query);
949        }
950        Self { templates }
951    }
952}
953
954struct RewriteRegCastToSubqueryVisitor<'a> {
955    templates: &'a HashMap<String, Box<Query>>,
956}
957
958impl RewriteRegCastToSubqueryVisitor<'_> {
959    /// Normalize a cast's `DataType` to the bare lowercased type name used as a
960    /// key in [`REG_CAST_SPECS`]. sqlparser uppercases the dedicated
961    /// `REGCLASS` keyword (`DataType::Regclass` -> `"REGCLASS"`) and renders
962    /// schema-qualified types as `pg_catalog.regclass`, so lowercase and strip
963    /// the optional `pg_catalog.` prefix uniformly.
964    fn normalize_type_name(data_type: &DataType) -> String {
965        let lower = data_type.to_string().to_lowercase();
966        lower
967            .strip_prefix("pg_catalog.")
968            .unwrap_or(&lower)
969            .to_owned()
970    }
971
972    /// True when `expr` is the forward (name->oid) cast operand we rewrite: a
973    /// string literal or a prepared-statement placeholder. Column operands
974    /// (the reverse oid->name direction) are deliberately excluded so a cast
975    /// like `prorettype::regtype` is left for `PgOidTypePlanner`.
976    fn is_name_operand(expr: &Expr) -> bool {
977        matches!(
978            expr,
979            Expr::Value(ValueWithSpan {
980                value: Value::SingleQuotedString(_),
981                ..
982            }) | Expr::Value(ValueWithSpan {
983                value: Value::Placeholder(_),
984                ..
985            })
986        )
987    }
988
989    /// If `expr` is a single-quoted string whose contents are a base-10
990    /// integer, return it as a SQL number literal. See the rule-level doc for
991    /// why numeric strings resolve to a literal rather than a subquery.
992    fn numeric_string_to_literal(expr: &Expr) -> Option<Expr> {
993        if let Expr::Value(ValueWithSpan {
994            value: Value::SingleQuotedString(s),
995            ..
996        }) = expr
997            && !s.is_empty()
998            && s.bytes().all(|b| b.is_ascii_digit())
999        {
1000            return Some(Expr::Value(
1001                Value::Number(s.clone(), false).with_empty_span(),
1002            ));
1003        }
1004        None
1005    }
1006
1007    /// Build `(SELECT oid FROM pg_catalog.<table> WHERE <name_col> = <operand>)`
1008    /// by cloning the type's query template and substituting its `$1` with the
1009    /// cast operand.
1010    fn create_subquery(template: &Query, operand: &Expr) -> Expr {
1011        struct PlaceholderReplacer(Expr);
1012        impl VisitorMut for PlaceholderReplacer {
1013            type Break = ();
1014            fn pre_visit_expr(&mut self, e: &mut Expr) -> ControlFlow<Self::Break> {
1015                if let Expr::Value(ValueWithSpan {
1016                    value: Value::Placeholder(_),
1017                    ..
1018                }) = e
1019                {
1020                    *e = self.0.clone();
1021                }
1022                ControlFlow::Continue(())
1023            }
1024        }
1025
1026        let mut query = template.clone();
1027        let _ = query.visit(&mut PlaceholderReplacer(operand.clone()));
1028        Expr::Subquery(Box::new(query))
1029    }
1030}
1031
1032impl VisitorMut for RewriteRegCastToSubqueryVisitor<'_> {
1033    type Break = ();
1034
1035    fn pre_visit_expr(&mut self, expr: &mut Expr) -> ControlFlow<Self::Break> {
1036        if let Expr::Cast {
1037            expr: operand,
1038            data_type,
1039            ..
1040        } = expr
1041            && Self::is_name_operand(operand)
1042            && let Some(template) = self.templates.get(&Self::normalize_type_name(data_type))
1043        {
1044            *expr = if let Some(lit) = Self::numeric_string_to_literal(operand) {
1045                lit
1046            } else {
1047                Self::create_subquery(template, operand)
1048            };
1049        }
1050        ControlFlow::Continue(())
1051    }
1052}
1053
1054impl SqlStatementRewriteRule for RewriteRegCastToSubquery {
1055    fn rewrite(&self, mut s: Statement) -> Statement {
1056        let mut visitor = RewriteRegCastToSubqueryVisitor {
1057            templates: &self.templates,
1058        };
1059        let _ = s.visit(&mut visitor);
1060        s
1061    }
1062}
1063
1064/// A processor to replace unsupported subquery from projection with NULL.
1065///
1066/// It will also add `LIMIT 1` to supported subquery to ensure it returns scalar
1067/// value.
1068#[derive(Debug)]
1069pub struct RemoveSubqueryFromProjection;
1070
1071struct RemoveSubqueryFromProjectionVisitor;
1072
1073impl RemoveSubqueryFromProjectionVisitor {
1074    fn has_correlation(&self, query: &Query) -> bool {
1075        if let SetExpr::Select(select) = &*query.body {
1076            let table_aliases: HashSet<String> = select
1077                .from
1078                .iter()
1079                .flat_map(|twj| {
1080                    let mut aliases = HashSet::new();
1081                    Self::collect_table_aliases_from_table_factor(&twj.relation, &mut aliases);
1082                    for join in &twj.joins {
1083                        Self::collect_table_aliases_from_table_factor(&join.relation, &mut aliases);
1084                    }
1085                    aliases
1086                })
1087                .collect();
1088
1089            let mut has_correlation = false;
1090            let mut visitor = CorrelationCheckVisitor(&mut has_correlation, &table_aliases);
1091            let _ = datafusion::logical_expr::sqlparser::ast::Visit::visit(query, &mut visitor);
1092            has_correlation
1093        } else {
1094            false
1095        }
1096    }
1097
1098    fn has_limit(&self, query: &Query) -> bool {
1099        query.limit_clause.is_some() || query.fetch.is_some()
1100    }
1101
1102    fn collect_table_aliases_from_table_factor(
1103        table_factor: &TableFactor,
1104        aliases: &mut HashSet<String>,
1105    ) {
1106        if let TableFactor::Table {
1107            alias: Some(alias), ..
1108        } = table_factor
1109        {
1110            aliases.insert(alias.name.value.clone());
1111        }
1112    }
1113}
1114
1115struct CorrelationCheckVisitor<'a>(&'a mut bool, &'a HashSet<String>);
1116
1117impl Visitor for CorrelationCheckVisitor<'_> {
1118    type Break = ();
1119
1120    fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<Self::Break> {
1121        match expr {
1122            Expr::Value(ValueWithSpan {
1123                value: Value::Placeholder(_placeholder),
1124                ..
1125            }) => {
1126                *self.0 = true;
1127            }
1128            Expr::CompoundIdentifier(idents) if !idents.is_empty() => {
1129                let table_name = &idents[0].value;
1130                if !self.1.contains(table_name) {
1131                    *self.0 = true;
1132                }
1133            }
1134            _ => {}
1135        }
1136        ControlFlow::Continue(())
1137    }
1138}
1139
1140impl VisitorMut for RemoveSubqueryFromProjectionVisitor {
1141    type Break = ();
1142
1143    fn pre_visit_query(&mut self, query: &mut Query) -> ControlFlow<Self::Break> {
1144        if let SetExpr::Select(select) = query.body.as_mut() {
1145            for projection in &mut select.projection {
1146                match projection {
1147                    SelectItem::UnnamedExpr(expr) => {
1148                        if let Expr::Subquery(subquery) = expr {
1149                            if self.has_correlation(subquery) {
1150                                *expr = Expr::Value(Value::Null.with_empty_span());
1151                            } else if !self.has_limit(subquery) {
1152                                subquery.limit_clause = Some(LimitClause::LimitOffset {
1153                                    limit: Some(Expr::Value(
1154                                        Value::Number("1".to_string(), false).with_empty_span(),
1155                                    )),
1156                                    offset: None,
1157                                    limit_by: vec![],
1158                                });
1159                            }
1160                        }
1161                    }
1162                    SelectItem::ExprWithAlias { expr, .. } => {
1163                        if let Expr::Subquery(subquery) = expr {
1164                            if self.has_correlation(subquery) {
1165                                *expr = Expr::Value(Value::Null.with_empty_span());
1166                            } else if !self.has_limit(subquery) {
1167                                subquery.limit_clause = Some(LimitClause::LimitOffset {
1168                                    limit: Some(Expr::Value(
1169                                        Value::Number("1".to_string(), false).with_empty_span(),
1170                                    )),
1171                                    offset: None,
1172                                    limit_by: vec![],
1173                                });
1174                            }
1175                        }
1176                    }
1177                    _ => {}
1178                }
1179            }
1180        }
1181
1182        ControlFlow::Continue(())
1183    }
1184}
1185
1186impl SqlStatementRewriteRule for RemoveSubqueryFromProjection {
1187    fn rewrite(&self, mut s: Statement) -> Statement {
1188        let mut visitor = RemoveSubqueryFromProjectionVisitor;
1189        let _ = s.visit(&mut visitor);
1190
1191        s
1192    }
1193}
1194
1195/// `select version()` should return column named `version` not `version()`
1196#[derive(Debug)]
1197pub struct FixVersionColumnName;
1198
1199struct FixVersionColumnNameVisitor;
1200
1201impl VisitorMut for FixVersionColumnNameVisitor {
1202    type Break = ();
1203
1204    fn pre_visit_query(&mut self, query: &mut Query) -> ControlFlow<Self::Break> {
1205        if let SetExpr::Select(select) = query.body.as_mut() {
1206            for projection in &mut select.projection {
1207                if let SelectItem::UnnamedExpr(Expr::Function(f)) = projection
1208                    && f.name.0.len() == 1
1209                    && let ObjectNamePart::Identifier(part) = &f.name.0[0]
1210                    && part.value == "version"
1211                    && let FunctionArguments::List(args) = &f.args
1212                    && args.args.is_empty()
1213                {
1214                    *projection = SelectItem::ExprWithAlias {
1215                        expr: Expr::Function(f.clone()),
1216                        alias: Ident::new("version"),
1217                    }
1218                }
1219            }
1220        }
1221
1222        ControlFlow::Continue(())
1223    }
1224}
1225
1226impl SqlStatementRewriteRule for FixVersionColumnName {
1227    fn rewrite(&self, mut s: Statement) -> Statement {
1228        let mut visitor = FixVersionColumnNameVisitor;
1229        let _ = s.visit(&mut visitor);
1230
1231        s
1232    }
1233}
1234
1235#[cfg(test)]
1236mod tests {
1237    use super::*;
1238    use datafusion::sql::sqlparser::dialect::PostgreSqlDialect;
1239    use datafusion::sql::sqlparser::parser::{Parser, ParserError};
1240    use std::sync::Arc;
1241
1242    fn parse(sql: &str) -> Result<Vec<Statement>, ParserError> {
1243        let dialect = PostgreSqlDialect {};
1244
1245        Parser::parse_sql(&dialect, sql)
1246    }
1247
1248    fn rewrite(mut s: Statement, rules: &[Arc<dyn SqlStatementRewriteRule>]) -> Statement {
1249        for rule in rules {
1250            s = rule.rewrite(s);
1251        }
1252
1253        s
1254    }
1255
1256    macro_rules! assert_rewrite {
1257        ($rules:expr, $orig:expr, $rewt:expr) => {
1258            let sql = $orig;
1259            let statement = parse(sql).expect("Failed to parse").remove(0);
1260
1261            let statement = rewrite(statement, $rules);
1262            assert_eq!(statement.to_string(), $rewt);
1263        };
1264    }
1265
1266    #[test]
1267    fn test_alias_rewrite() {
1268        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> =
1269            vec![Arc::new(AliasDuplicatedProjectionRewrite)];
1270
1271        assert_rewrite!(
1272            &rules,
1273            "SELECT n.oid, n.* FROM pg_catalog.pg_namespace n",
1274            "SELECT n.oid AS __alias_oid, n.* FROM pg_catalog.pg_namespace n"
1275        );
1276
1277        assert_rewrite!(
1278            &rules,
1279            "SELECT oid, * FROM pg_catalog.pg_namespace",
1280            "SELECT oid AS __alias_oid, * FROM pg_catalog.pg_namespace"
1281        );
1282
1283        assert_rewrite!(
1284            &rules,
1285            "SELECT t1.oid, t2.* FROM tbl1 AS t1 JOIN tbl2 AS t2 ON t1.id = t2.id",
1286            "SELECT t1.oid, t2.* FROM tbl1 AS t1 JOIN tbl2 AS t2 ON t1.id = t2.id"
1287        );
1288
1289        let sql = "SELECT n.oid,n.*,d.description FROM pg_catalog.pg_namespace n LEFT OUTER JOIN pg_catalog.pg_description d ON d.objoid=n.oid AND d.objsubid=0 AND d.classoid='pg_namespace' ORDER BY nspsname";
1290        let statement = parse(sql).expect("Failed to parse").remove(0);
1291
1292        let statement = rewrite(statement, &rules);
1293        assert_eq!(
1294            statement.to_string(),
1295            "SELECT n.oid AS __alias_oid, n.*, d.description FROM pg_catalog.pg_namespace n LEFT OUTER JOIN pg_catalog.pg_description d ON d.objoid = n.oid AND d.objsubid = 0 AND d.classoid = 'pg_namespace' ORDER BY nspsname"
1296        );
1297    }
1298
1299    #[test]
1300    fn test_qualifier_prepend() {
1301        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> =
1302            vec![Arc::new(ResolveUnqualifiedIdentifier)];
1303
1304        assert_rewrite!(
1305            &rules,
1306            "SELECT n.* FROM pg_catalog.pg_namespace n WHERE nspname = 'pg_catalog' ORDER BY nspname",
1307            "SELECT n.* FROM pg_catalog.pg_namespace n WHERE n.nspname = 'pg_catalog' ORDER BY n.nspname"
1308        );
1309
1310        assert_rewrite!(
1311            &rules,
1312            "SELECT * FROM pg_catalog.pg_namespace ORDER BY nspname",
1313            "SELECT * FROM pg_catalog.pg_namespace ORDER BY nspname"
1314        );
1315
1316        assert_rewrite!(
1317            &rules,
1318            "SELECT n.oid,n.*,d.description FROM pg_catalog.pg_namespace n LEFT OUTER JOIN pg_catalog.pg_description d ON d.objoid=n.oid AND d.objsubid=0 AND d.classoid='pg_namespace' ORDER BY nspsname",
1319            "SELECT n.oid, n.*, d.description FROM pg_catalog.pg_namespace n LEFT OUTER JOIN pg_catalog.pg_description d ON d.objoid = n.oid AND d.objsubid = 0 AND d.classoid = 'pg_namespace' ORDER BY n.nspsname"
1320        );
1321
1322        assert_rewrite!(
1323            &rules,
1324            "SELECT i.*,i.indkey as keys,c.relname,c.relnamespace,c.relam,c.reltablespace,tc.relname as tabrelname,dsc.description FROM pg_catalog.pg_index i INNER JOIN pg_catalog.pg_class c ON c.oid=i.indexrelid INNER JOIN pg_catalog.pg_class tc ON tc.oid=i.indrelid LEFT OUTER JOIN pg_catalog.pg_description dsc ON i.indexrelid=dsc.objoid WHERE i.indrelid=1 ORDER BY tabrelname, c.relname",
1325            "SELECT i.*, i.indkey AS keys, c.relname, c.relnamespace, c.relam, c.reltablespace, tc.relname AS tabrelname, dsc.description FROM pg_catalog.pg_index i INNER JOIN pg_catalog.pg_class c ON c.oid = i.indexrelid INNER JOIN pg_catalog.pg_class tc ON tc.oid = i.indrelid LEFT OUTER JOIN pg_catalog.pg_description dsc ON i.indexrelid = dsc.objoid WHERE i.indrelid = 1 ORDER BY tabrelname, c.relname"
1326        );
1327    }
1328
1329    #[test]
1330    fn test_any_to_array_contains() {
1331        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> =
1332            vec![Arc::new(RewriteArrayAnyAllOperation)];
1333
1334        assert_rewrite!(
1335            &rules,
1336            "SELECT a = ANY(current_schemas(true))",
1337            "SELECT array_contains(current_schemas(true), a)"
1338        );
1339
1340        assert_rewrite!(
1341            &rules,
1342            "SELECT a <> ALL(current_schemas(true))",
1343            "SELECT NOT array_contains(current_schemas(true), a)"
1344        );
1345
1346        assert_rewrite!(
1347            &rules,
1348            "SELECT a = ANY('{r, l, e}')",
1349            "SELECT array_contains(ARRAY['r', 'l', 'e'], a)"
1350        );
1351
1352        assert_rewrite!(
1353            &rules,
1354            "SELECT a FROM tbl WHERE a = ANY(current_schemas(true))",
1355            "SELECT a FROM tbl WHERE array_contains(current_schemas(true), a)"
1356        );
1357    }
1358
1359    #[test]
1360    fn test_prepend_unqualified_table_name() {
1361        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> =
1362            vec![Arc::new(PrependUnqualifiedPgTableName)];
1363
1364        assert_rewrite!(
1365            &rules,
1366            "SELECT * FROM pg_catalog.pg_namespace",
1367            "SELECT * FROM pg_catalog.pg_namespace"
1368        );
1369
1370        assert_rewrite!(
1371            &rules,
1372            "SELECT * FROM pg_namespace",
1373            "SELECT * FROM pg_catalog.pg_namespace"
1374        );
1375
1376        assert_rewrite!(
1377            &rules,
1378            "SELECT * FROM pg_type",
1379            "SELECT * FROM pg_catalog.pg_type"
1380        );
1381
1382        assert_rewrite!(
1383            &rules,
1384            "SELECT typtype, typname, pg_type.oid FROM pg_catalog.pg_type LEFT JOIN pg_namespace as ns ON ns.oid = oid",
1385            "SELECT typtype, typname, pg_type.oid FROM pg_catalog.pg_type LEFT JOIN pg_catalog.pg_namespace AS ns ON ns.oid = oid"
1386        );
1387
1388        assert_rewrite!(
1389            &rules,
1390            "SELECT * FROM pg_compat_test",
1391            "SELECT * FROM pg_compat_test"
1392        );
1393
1394        assert_rewrite!(
1395            &rules,
1396            "SELECT * FROM pg_custom_table",
1397            "SELECT * FROM pg_custom_table"
1398        );
1399    }
1400
1401    #[test]
1402    fn test_array_literal_fix() {
1403        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> = vec![Arc::new(FixArrayLiteral)];
1404
1405        assert_rewrite!(
1406            &rules,
1407            "SELECT '{a, abc}'::text[]",
1408            "SELECT ARRAY['a', 'abc']::TEXT[]"
1409        );
1410
1411        assert_rewrite!(
1412            &rules,
1413            "SELECT '{1, 2}'::int[]",
1414            "SELECT ARRAY[1, 2]::INT[]"
1415        );
1416
1417        assert_rewrite!(
1418            &rules,
1419            "SELECT '{t, f}'::bool[]",
1420            "SELECT ARRAY[t, f]::BOOL[]"
1421        );
1422    }
1423
1424    #[test]
1425    fn test_strip_callable_qualifier_from_table_function() {
1426        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> = vec![Arc::new(StripCallableQualifier)];
1427
1428        assert_rewrite!(
1429            &rules,
1430            "SELECT * FROM pg_catalog.pg_get_keywords()",
1431            "SELECT * FROM pg_get_keywords()"
1432        );
1433    }
1434
1435    #[test]
1436    fn test_current_user() {
1437        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> =
1438            vec![Arc::new(CurrentUserVariableToSessionUserFunctionCall)];
1439
1440        // current_user -> session_user. `session_user` is a sqlparser-special
1441        // keyword, so it must stay parenthesis-less to round-trip through the
1442        // postgres dialect (re-parsed by DataFusion downstream).
1443        assert_rewrite!(&rules, "SELECT current_user", "SELECT session_user");
1444        assert_rewrite!(&rules, "SELECT CURRENT_USER", "SELECT session_user");
1445        assert_rewrite!(
1446            &rules,
1447            "SELECT is_null(current_user)",
1448            "SELECT is_null(session_user)"
1449        );
1450
1451        // current_catalog -> current_database. `current_database` is NOT a
1452        // special keyword, so it needs explicit `()` to re-parse as a call.
1453        assert_rewrite!(
1454            &rules,
1455            "SELECT current_catalog",
1456            "SELECT current_database()"
1457        );
1458
1459        // version is deliberately not rewritten: in postgres it is a regular
1460        // function, not a special register, so `SELECT version` (no parens) is
1461        // invalid and `SELECT version()` is already the canonical form.
1462        assert_rewrite!(&rules, "SELECT version", "SELECT version");
1463        assert_rewrite!(&rules, "SELECT version()", "SELECT version()");
1464
1465        // current_schema -> current_schema()
1466        assert_rewrite!(&rules, "SELECT current_schema", "SELECT current_schema()");
1467    }
1468
1469    #[test]
1470    fn test_strip_collate() {
1471        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> = vec![Arc::new(StripCollate)];
1472
1473        assert_rewrite!(
1474            &rules,
1475            "SELECT c.oid, c.relname FROM pg_catalog.pg_class c WHERE c.relname COLLATE pg_catalog.default = 'foo'",
1476            "SELECT c.oid, c.relname FROM pg_catalog.pg_class c WHERE c.relname = 'foo'"
1477        );
1478
1479        // Combined with OPERATOR(...) syntax: only COLLATE is stripped here;
1480        // the operator is left for RewritePgCatalogOperator (next test).
1481        assert_rewrite!(
1482            &rules,
1483            "SELECT c.oid, c.relname FROM pg_catalog.pg_class c WHERE c.relname OPERATOR(pg_catalog.~) '^(tablename)$' COLLATE pg_catalog.default ORDER BY 2, 3;",
1484            "SELECT c.oid, c.relname FROM pg_catalog.pg_class c WHERE c.relname OPERATOR(pg_catalog.~) '^(tablename)$' ORDER BY 2, 3"
1485        );
1486    }
1487
1488    #[test]
1489    fn test_rewrite_pg_catalog_operator() {
1490        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> = vec![Arc::new(RewritePgCatalogOperator)];
1491
1492        // All four pg_catalog regex operators map to their builtin forms.
1493        assert_rewrite!(
1494            &rules,
1495            "SELECT 'a' OPERATOR(pg_catalog.~) 'b'",
1496            "SELECT 'a' ~ 'b'"
1497        );
1498        assert_rewrite!(
1499            &rules,
1500            "SELECT 'a' OPERATOR(pg_catalog.~*) 'b'",
1501            "SELECT 'a' ~* 'b'"
1502        );
1503        assert_rewrite!(
1504            &rules,
1505            "SELECT 'a' OPERATOR(pg_catalog.!~) 'b'",
1506            "SELECT 'a' !~ 'b'"
1507        );
1508        assert_rewrite!(
1509            &rules,
1510            "SELECT 'a' OPERATOR(pg_catalog.!~*) 'b'",
1511            "SELECT 'a' !~* 'b'"
1512        );
1513
1514        // The original psql \d shape: OPERATOR + COLLATE together. The operator
1515        // arm fires; COLLATE is left for StripCollate.
1516        assert_rewrite!(
1517            &rules,
1518            "SELECT c.oid, c.relname FROM pg_catalog.pg_class c WHERE c.relname OPERATOR(pg_catalog.~) '^(tablename)$' COLLATE pg_catalog.default ORDER BY 2, 3;",
1519            "SELECT c.oid, c.relname FROM pg_catalog.pg_class c WHERE c.relname ~ '^(tablename)$' COLLATE pg_catalog.default ORDER BY 2, 3"
1520        );
1521    }
1522
1523    #[test]
1524    fn test_remove_subquery() {
1525        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> =
1526            vec![Arc::new(RemoveSubqueryFromProjection)];
1527
1528        assert_rewrite!(
1529            &rules,
1530            "SELECT a.attname, pg_catalog.format_type(a.atttypid, a.atttypmod), (SELECT pg_catalog.pg_get_expr(d.adbin, d.adrelid, true) FROM pg_catalog.pg_attrdef d WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef), a.attnotnull, (SELECT c.collname FROM pg_catalog.pg_collation c, pg_catalog.pg_type t WHERE c.oid = a.attcollation AND t.oid = a.atttypid AND a.attcollation <> t.typcollation LIMIT 1) AS attcollation, a.attidentity, a.attgenerated FROM pg_catalog.pg_attribute a WHERE a.attrelid = '16384' AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum;",
1531            "SELECT a.attname, pg_catalog.format_type(a.atttypid, a.atttypmod), NULL, a.attnotnull, NULL AS attcollation, a.attidentity, a.attgenerated FROM pg_catalog.pg_attribute a WHERE a.attrelid = '16384' AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum"
1532        );
1533    }
1534
1535    #[test]
1536    fn test_keep_simple_aggregated_subquery() {
1537        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> =
1538            vec![Arc::new(RemoveSubqueryFromProjection)];
1539
1540        assert_rewrite!(
1541            &rules,
1542            "SELECT id, (SELECT COUNT(*) FROM pg_catalog.pg_attribute) AS attr_count FROM pg_catalog.pg_class",
1543            "SELECT id, (SELECT COUNT(*) FROM pg_catalog.pg_attribute LIMIT 1) AS attr_count FROM pg_catalog.pg_class"
1544        );
1545    }
1546
1547    #[test]
1548    fn test_remove_correlated_subquery() {
1549        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> =
1550            vec![Arc::new(RemoveSubqueryFromProjection)];
1551
1552        assert_rewrite!(
1553            &rules,
1554            "SELECT a.attname, (SELECT COUNT(*) FROM pg_catalog.pg_attribute WHERE attrelid = a.oid) AS count FROM pg_catalog.pg_attribute a",
1555            "SELECT a.attname, NULL AS count FROM pg_catalog.pg_attribute a"
1556        );
1557    }
1558
1559    #[test]
1560    fn test_remove_non_aggregated_subquery() {
1561        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> =
1562            vec![Arc::new(RemoveSubqueryFromProjection)];
1563
1564        assert_rewrite!(
1565            &rules,
1566            "SELECT id, (SELECT attname FROM pg_catalog.pg_attribute LIMIT 1) AS first_attr FROM pg_catalog.pg_class",
1567            "SELECT id, (SELECT attname FROM pg_catalog.pg_attribute LIMIT 1) AS first_attr FROM pg_catalog.pg_class"
1568        );
1569    }
1570
1571    #[test]
1572    fn test_keep_simple_scalar_subquery() {
1573        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> =
1574            vec![Arc::new(RemoveSubqueryFromProjection)];
1575
1576        assert_rewrite!(
1577            &rules,
1578            "SELECT (SELECT 1) AS constant",
1579            "SELECT (SELECT 1 LIMIT 1) AS constant"
1580        );
1581
1582        assert_rewrite!(
1583            &rules,
1584            "SELECT (SELECT 'value') AS str_val",
1585            "SELECT (SELECT 'value' LIMIT 1) AS str_val"
1586        );
1587    }
1588
1589    #[test]
1590    fn test_version_rewrite() {
1591        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> = vec![Arc::new(FixVersionColumnName)];
1592
1593        assert_rewrite!(&rules, "SELECT version()", "SELECT version() AS version");
1594
1595        // Make sure we don't rewrite things we should leave alone
1596        assert_rewrite!(&rules, "SELECT version() as foo", "SELECT version() AS foo");
1597        assert_rewrite!(&rules, "SELECT version(foo)", "SELECT version(foo)");
1598        assert_rewrite!(&rules, "SELECT foo.version()", "SELECT foo.version()");
1599    }
1600
1601    #[test]
1602    fn test_rewrite_regcast_numeric_string_to_literal() {
1603        // A numeric string resolves directly to the literal oid (Postgres
1604        // semantics), avoiding a subquery.
1605        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> =
1606            vec![Arc::new(RewriteRegCastToSubquery::new())];
1607
1608        assert_rewrite!(&rules, "SELECT '16417'::regclass", "SELECT 16417");
1609        // pg_catalog.-qualified and uppercase spellings normalize to the same kind.
1610        assert_rewrite!(
1611            &rules,
1612            "SELECT '16417'::pg_catalog.regclass",
1613            "SELECT 16417"
1614        );
1615    }
1616
1617    #[test]
1618    fn test_rewrite_regcast_name_string_to_subquery() {
1619        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> =
1620            vec![Arc::new(RewriteRegCastToSubquery::new())];
1621
1622        // Name string -> scalar subquery against the backing catalog table.
1623        // The exact spelling of the subquery is part of the contract, so pin it.
1624        assert_rewrite!(
1625            &rules,
1626            "SELECT 'public'::regnamespace",
1627            "SELECT (SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = 'public')"
1628        );
1629        assert_rewrite!(
1630            &rules,
1631            "SELECT 'pg_class'::regclass",
1632            "SELECT (SELECT c.oid FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid CROSS JOIN (SELECT parse_ident('pg_class'::TEXT) AS parts) WHERE array_length(parts, 1) IN (1, 2) AND ((array_length(parts, 1) = 1 AND n.nspname = current_schema() AND c.relname = parts[1]) OR (array_length(parts, 1) = 2 AND n.nspname = parts[1] AND c.relname = parts[2])))"
1633        );
1634        assert_rewrite!(
1635            &rules,
1636            "SELECT 'array_in'::regproc",
1637            "SELECT (SELECT oid FROM pg_catalog.pg_proc WHERE proname = 'array_in')"
1638        );
1639        assert_rewrite!(
1640            &rules,
1641            "SELECT 'integer'::regtype",
1642            "SELECT (SELECT oid FROM pg_catalog.pg_type WHERE typname = 'integer')"
1643        );
1644
1645        // Works inside a comparison, where clients actually use it.
1646        assert_rewrite!(
1647            &rules,
1648            "SELECT 1 WHERE classoid = 'pg_class'::regclass",
1649            "SELECT 1 WHERE classoid = (SELECT c.oid FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid CROSS JOIN (SELECT parse_ident('pg_class'::TEXT) AS parts) WHERE array_length(parts, 1) IN (1, 2) AND ((array_length(parts, 1) = 1 AND n.nspname = current_schema() AND c.relname = parts[1]) OR (array_length(parts, 1) = 2 AND n.nspname = parts[1] AND c.relname = parts[2])))"
1650        );
1651    }
1652
1653    #[test]
1654    fn test_rewrite_regclass_uses_parse_ident_schema_aware_lookup() {
1655        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> =
1656            vec![Arc::new(RewriteRegCastToSubquery::new())];
1657
1658        let lookup = "SELECT c.oid FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid CROSS JOIN (SELECT parse_ident($1::TEXT) AS parts) WHERE array_length(parts, 1) IN (1, 2) AND ((array_length(parts, 1) = 1 AND n.nspname = current_schema() AND c.relname = parts[1]) OR (array_length(parts, 1) = 2 AND n.nspname = parts[1] AND c.relname = parts[2]))";
1659
1660        // A bound portal parameter remains a parameter through the parse_ident
1661        // lookup and outer oid cast.
1662        assert_rewrite!(
1663            &rules,
1664            "SELECT $1::regclass::oid",
1665            format!("SELECT ({lookup})::oid")
1666        );
1667        // The pg_catalog-qualified spelling normalizes to the same template.
1668        assert_rewrite!(
1669            &rules,
1670            "SELECT $1::pg_catalog.regclass",
1671            format!("SELECT ({lookup})")
1672        );
1673        // parse_ident preserves quoted, case-sensitive unqualified names.
1674        assert_rewrite!(
1675            &rules,
1676            "SELECT '\"Mixed Case\"'::regclass",
1677            format!("SELECT ({})", lookup.replace("$1", "'\"Mixed Case\"'"))
1678        );
1679        // Two explicit quoted components select the supplied schema and relation.
1680        assert_rewrite!(
1681            &rules,
1682            "SELECT '\"Mixed Schema\".\"Mixed Table\"'::regclass",
1683            format!(
1684                "SELECT ({})",
1685                lookup.replace("$1", "'\"Mixed Schema\".\"Mixed Table\"'")
1686            )
1687        );
1688        // Invalid and over-qualified names are guarded by the component count.
1689        assert_rewrite!(
1690            &rules,
1691            "SELECT 'too.many.parts'::regclass",
1692            format!("SELECT ({})", lookup.replace("$1", "'too.many.parts'"))
1693        );
1694        assert_rewrite!(
1695            &rules,
1696            "SELECT 'too..many'::regclass",
1697            format!("SELECT ({})", lookup.replace("$1", "'too..many'"))
1698        );
1699    }
1700
1701    #[test]
1702    fn test_rewrite_regclass_leaves_direct_relname_predicate_unchanged() {
1703        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> =
1704            vec![Arc::new(RewriteRegCastToSubquery::new())];
1705
1706        assert_rewrite!(
1707            &rules,
1708            "SELECT oid FROM pg_catalog.pg_class WHERE relname = $1",
1709            "SELECT oid FROM pg_catalog.pg_class WHERE relname = $1"
1710        );
1711    }
1712
1713    #[test]
1714    fn test_rewrite_regcast_leaves_reverse_and_unknown_alone() {
1715        let rules: Vec<Arc<dyn SqlStatementRewriteRule>> =
1716            vec![Arc::new(RewriteRegCastToSubquery::new())];
1717
1718        // Reverse direction (column operand) is NOT rewritten -- left for
1719        // PgOidTypePlanner so the cast still parses.
1720        assert_rewrite!(
1721            &rules,
1722            "SELECT prorettype::regtype",
1723            "SELECT prorettype::regtype"
1724        );
1725        // A cast whose type is not one of the four resolvable oid-alias kinds
1726        // is left alone (not crashed on, not rewritten).
1727        assert_rewrite!(&rules, "SELECT 'x'::regrole", "SELECT 'x'::regrole");
1728        // A numeric operand cast to a non-oid type is left alone.
1729        assert_rewrite!(&rules, "SELECT '1'::int4", "SELECT '1'::INT4");
1730    }
1731}