no-mistakes-postgres-sql 0.109.131

PostgreSQL SQL parsing, statement facts, and identifier extraction for no-mistakes
Documentation
use super::*;
use sqlparser::ast::{SelectItem, Statement};
use sqlparser::dialect::PostgreSqlDialect;
use sqlparser::parser::Parser;

#[test]
fn repeated_cte_layouts_resolve_the_external_source_once_per_inference() {
    let sql = include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-no-duplicate-keyed-lookups/fixture/review-aggregate-demand/output-labels-shared-ctes.sql"
    ));
    let statements = Parser::parse_sql(&PostgreSqlDialect {}, sql).unwrap();
    let [Statement::Query(query)] = statements.as_slice() else {
        panic!("expected a saved SELECT");
    };
    let calls = std::cell::Cell::new(0);
    let supplied = |name: &str| {
        assert_eq!(name, "supplied");
        calls.set(calls.get() + 1);
        Some(SingleOutput::Named("k".to_owned()))
    };
    assert_eq!(
        query_projection_labels_with_ctes(query, Some(&supplied), None),
        Some(vec![Some("k".to_owned())])
    );
    assert_eq!(calls.get(), 1);
    assert_eq!(
        query_projection_labels_with_ctes(query, Some(&|_| Some(SingleOutput::Unnamed)), None),
        Some(vec![None])
    );
}

#[test]
fn layout_inference_respects_external_and_recursive_cte_boundaries() {
    let statements = scope_boundary_statements();
    let query = |index: usize| match &statements[index] {
        Statement::Query(query) => query,
        _ => panic!("expected a saved SELECT"),
    };
    let named = |_: &str| Some(SingleOutput::Named("k".into()));
    let unnamed = |_: &str| Some(SingleOutput::Unnamed);
    assert_eq!(
        query_projection_labels_with_ctes(query(0), Some(&named), None),
        Some(vec![Some("k".into())])
    );
    assert_eq!(
        query_projection_labels_with_ctes(query(0), Some(&unnamed), None),
        Some(vec![None])
    );
    assert_eq!(
        query_projection_labels_with_ctes(query(0), None, None),
        Some(vec![None])
    );
    assert_eq!(
        query_projection_labels_with_ctes(query(1), None, None),
        Some(vec![Some("k".into())])
    );
    assert_eq!(
        query_projection_labels_with_ctes(query(2), None, None),
        Some(vec![None])
    );
}

#[test]
fn output_labels_follow_nested_join_scopes_and_recognized_syntax() {
    let statements = scope_boundary_statements();
    let labels: Vec<_> = statements[3..]
        .iter()
        .flat_map(|statement| {
            let Statement::Query(query) = statement else {
                panic!("expected a saved SELECT");
            };
            query.body.as_select().unwrap().projection.iter()
        })
        .map(|item| {
            let SelectItem::UnnamedExpr(expr) = item else {
                panic!("expected an unnamed projection");
            };
            implicit_output_label(expr)
        })
        .collect();
    assert_eq!(
        labels,
        [
            Some("k".into()),
            None,
            Some("k".into()),
            Some("k".into()),
            None,
            Some("point".into()),
            Some("substr".into()),
            None,
        ]
    );
}

fn scope_boundary_statements() -> Vec<Statement> {
    let sql = include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-no-duplicate-keyed-lookups/fixture/review-aggregate-demand/output-label-scope-boundaries.sql"
    ));
    Parser::parse_sql(&PostgreSqlDialect {}, sql).unwrap()
}

#[test]
fn scalar_and_conditional_output_labels_preserve_only_known_postgresql_names() {
    let sql = include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-no-duplicate-keyed-lookups/fixture/review-aggregate-demand/output-labels.sql"
    ));
    let stmts = Parser::parse_sql(&PostgreSqlDialect {}, sql).unwrap();
    let [Statement::Query(query)] = stmts.as_slice() else {
        panic!("expected one saved SELECT");
    };
    let select = query.body.as_select().unwrap();
    let labels: Vec<_> = select
        .projection
        .iter()
        .map(|item| {
            let SelectItem::UnnamedExpr(expr) = item else {
                panic!("expected unnamed output");
            };
            implicit_output_label(expr)
        })
        .collect();
    assert_eq!(
        labels,
        [
            Some("inner_name".into()),
            Some("v".into()),
            Some("bit".into()),
            Some("case".into()),
            Some("case".into()),
            Some("v".into()),
            Some("v".into()),
            Some("column1".into()),
            Some("union_label".into()),
            Some("bit".into()),
            Some("varbit".into()),
            Some("?column?".into()),
            Some("?column?".into()),
            Some("?column?".into()),
            Some("?column?".into()),
            Some("?column?".into()),
            Some("?column?".into()),
            Some("?column?".into()),
            Some("?column?".into()),
            Some("?column?".into()),
            Some("?column?".into()),
            Some("?column?".into()),
            Some("?column?".into()),
            Some("is_normalized".into()),
            Some("array".into()),
            Some("?column?".into()),
            Some("?column?".into()),
            Some("?column?".into()),
            Some("?column?".into()),
            Some("?column?".into()),
            Some("?column?".into()),
            Some("?column?".into()),
            Some("extract".into()),
            Some("substring".into()),
            Some("btrim".into()),
            Some("ltrim".into()),
            Some("rtrim".into()),
            Some("overlay".into()),
            Some("position".into()),
            Some("ceil".into()),
            Some("floor".into()),
            Some("timezone".into()),
            Some("varbit".into()),
            Some("interval".into()),
            Some("text".into()),
            Some("regclass".into()),
            Some("tsvector".into()),
            Some("tsquery".into()),
            Some("point".into()),
            Some("lseg".into()),
            Some("x".into()),
            Some("int2".into()),
            Some("numeric".into()),
            Some("float4".into()),
            Some("float8".into()),
            Some("score".into()),
            Some("nested_score".into()),
            Some("score".into()),
            Some("local_score".into()),
            Some("score".into()),
            Some("inner_score".into()),
            None,
            Some("n".into()),
            Some("score".into()),
            Some("score".into()),
        ]
    );
}
#[test]
fn scalar_wildcard_labels_follow_visible_select_inputs() {
    let sql = include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-no-duplicate-keyed-lookups/fixture/review-aggregate-demand/correlated-scalar-labels.sql"
    ));
    let statements = Parser::parse_sql(&PostgreSqlDialect {}, sql).unwrap();
    let labels: Vec<_> = statements
        .iter()
        .map(|statement| {
            let Statement::Query(query) = statement else {
                panic!("expected a saved SELECT");
            };
            let select = query.body.as_select().unwrap();
            let [SelectItem::UnnamedExpr(expr)] = select.projection.as_slice() else {
                panic!("expected a scalar expression");
            };
            implicit_label_in_from(expr, &select.from)
        })
        .collect();
    assert_eq!(
        labels,
        [
            Some("score".into()),
            Some("local_score".into()),
            None,
            Some("score".into()),
            Some("score".into()),
            Some("score".into()),
            Some("score".into()),
            None,
            Some("score".into()),
            Some("score".into()),
            None,
            Some("Score".into()),
            Some("local_score".into()),
            Some("outer_score".into()),
            Some("outer_score".into()),
            Some("unnest".into()),
            Some("Score".into())
        ]
    );
}

#[test]
fn review_output_labels_and_cte_single_output_paths() {
    let sql = include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-no-duplicate-keyed-lookups/fixture/review-aggregate-demand/review-output-labels.sql"
    ));
    let statements = Parser::parse_sql(&PostgreSqlDialect {}, sql).unwrap();
    let query = |index: usize| match &statements[index] {
        Statement::Query(query) => query,
        _ => panic!("expected SELECT"),
    };
    let expr_at =
        |stmt: usize, item: usize| match &query(stmt).body.as_select().unwrap().projection[item] {
            SelectItem::UnnamedExpr(expr) => expr,
            _ => panic!("expected unnamed expr"),
        };
    assert_eq!(implicit_output_label(expr_at(0, 0)), None);
    let q1 = query(1).body.as_select().unwrap();
    assert_eq!(implicit_label_in_from(expr_at(1, 1), &q1.from), None);
    let external = |name: &str| (name == "v").then(|| "view_col".to_owned());
    assert_eq!(
        implicit_label_in_visible_from(expr_at(1, 1), &[], Some(&external)),
        Some("view_col".into())
    );
    assert_eq!(implicit_output_label(expr_at(2, 0)), Some("id".into()));
    assert_eq!(implicit_output_label(expr_at(3, 0)), None);
    let q4 = query(4).body.as_select().unwrap();
    assert_eq!(implicit_label_in_from(expr_at(4, 0), &q4.from), None);
    assert_eq!(
        select_projection_labels_with_ctes(query(5).body.as_select().unwrap(), None, None),
        [
            Some("lower".into()),
            Some("jsonb".into()),
            Some("point".into()),
            Some("numeric".into()),
            Some("case".into()),
        ]
    );
}

#[test]
fn nested_join_output_labels_resolve_only_preceding_lateral_operands() {
    let sql = include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-no-duplicate-keyed-lookups/fixture/review-aggregate-demand/lateral-join-output-labels.sql"
    ));
    let statements = Parser::parse_sql(&PostgreSqlDialect {}, sql).unwrap();
    let labels: Vec<_> = statements
        .iter()
        .map(|statement| {
            let Statement::Query(query) = statement else {
                panic!("expected a saved SELECT");
            };
            let [SelectItem::UnnamedExpr(expr)] =
                query.body.as_select().unwrap().projection.as_slice()
            else {
                panic!("expected one scalar subquery");
            };
            implicit_output_label(expr)
        })
        .collect();
    assert_eq!(
        labels,
        [Some("k".into()), None, None, Some("k".into()), None, None]
    );
}

#[test]
fn nested_joins_ctes_and_using_aliases_resolve_only_proven_output_labels() {
    let sql = include_str!(concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../test-cases/rules/postgres-no-duplicate-keyed-lookups/fixture/review-aggregate-demand/output-labels-joins-and-ctes.sql"
    ));
    let statements = Parser::parse_sql(&PostgreSqlDialect {}, sql).unwrap();
    let query = |index: usize| match &statements[index] {
        Statement::Query(query) => query,
        _ => panic!("expected SELECT"),
    };
    let expr_at = |stmt: usize| match &query(stmt).body.as_select().unwrap().projection[0] {
        SelectItem::UnnamedExpr(expr) => expr,
        _ => panic!("expected unnamed expr"),
    };
    let labels: Vec<_> = (0..=13)
        .map(|index| implicit_output_label(expr_at(index)))
        .collect();
    assert_eq!(
        labels,
        [
            None,
            Some("x".into()),
            Some("x".into()),
            Some("x".into()),
            Some("renamed".into()),
            None,
            None,
            None,
            None,
            None,
            Some("id".into()),
            None,
            Some("column1".into()),
            Some("id".into()),
        ]
    );
    assert!(cte_single_outputs(query(14), None).is_empty());
    assert_eq!(
        query_projection_labels_with_ctes(query(15), None, None),
        Some(vec![Some("k".into())])
    );
    assert_eq!(
        implicit_label_in_from(expr_at(16), &query(16).body.as_select().unwrap().from),
        None
    );
    assert_eq!(
        implicit_label_in_from(expr_at(17), &query(17).body.as_select().unwrap().from),
        None
    );
    let labels: Vec<_> = (18..statements.len())
        .map(|index| implicit_output_label(expr_at(index)))
        .collect();
    assert_eq!(
        labels,
        [
            Some("k".into()),
            Some("k".into()),
            Some("k".into()),
            None,
            None,
            None,
            Some("k".into()),
            Some("k".into())
        ]
    );
}