sql-values 0.8.0

SQL values, with PostgreSQL's value rules beside readers of the text PostgreSQL, MySQL and SQLite emit
Documentation
//! Constant expressions against PostgreSQL 18.

#[path = "support/containers.rs"]
mod containers;
#[path = "support/exit_slot.rs"]
mod exit_slot;
#[path = "support/pg18.rs"]
#[expect(
    dead_code,
    reason = "Only the PostgreSQL 18 slot and quoting are used."
)]
mod pg18;
#[path = "support/postgres.rs"]
mod postgres;

use diesel::{
    RunQueryDsl,
    connection::SimpleConnection,
    define_sql_function,
    sql_types::{Bool, Text},
};
use sql_values::postgres::{
    BuiltinType, ConstExpr, ConstExprContext, Literal, PgArray, PgValue, ShowType, TimePrecision,
    cast_literal,
};

define_sql_function!(fn pg_get_viewdef(name: Text, pretty: Bool) -> Text);
define_sql_function!(fn set_config(setting: Text, value: Text, is_local: Bool) -> Text);

#[test]
fn pg18_constant_expressions() {
    let mut connection = postgres::connect(&pg18::PG18, "18");
    for (setting, value) in [
        ("TimeZone", "UTC"),
        ("DateStyle", "ISO"),
        ("IntervalStyle", "postgres"),
    ] {
        diesel::select(set_config(setting, value, false))
            .get_result::<String>(&mut connection)
            .unwrap();
    }
    let groups: &[(BuiltinType, &[&str])] = &[
        (BuiltinType::Boolean, &["true", "false"]),
        (BuiltinType::Smallint, &["-32768", "0", "32767"]),
        (
            BuiltinType::Integer,
            &["-2147483648", "-1", "0", "2147483647"],
        ),
        (
            BuiltinType::Bigint,
            &["-9223372036854775808", "-1", "0", "9223372036854775807"],
        ),
        (
            BuiltinType::Numeric(None),
            &[
                "-1.25",
                "0",
                "0.00",
                "1",
                "1.00",
                "NaN",
                "Infinity",
                "-Infinity",
            ],
        ),
        (BuiltinType::Text, &["", "a'b", "a\\b", "a\n\tb", "é"]),
        (BuiltinType::Varchar(None), &["", "a'b", "a\\b"]),
        (BuiltinType::Bpchar(None), &["", "a  ", "a'b", "a\\b"]),
        (
            BuiltinType::Date,
            &["-infinity", "2000-01-01", "0001-01-01 BC", "infinity"],
        ),
        (
            BuiltinType::Timestamp(None),
            &["-infinity", "2000-01-01 12:34:56.1234", "infinity"],
        ),
        (
            BuiltinType::TimestampTz(None),
            &["-infinity", "2000-01-01 12:34:56.1234+02", "infinity"],
        ),
        (
            BuiltinType::Time(None),
            &["00:00", "24:00", "12:34:56.1234"],
        ),
        (
            BuiltinType::TimeTz(None),
            &["00:00+00", "24:00-02", "12:34:56.1234+01"],
        ),
        (
            BuiltinType::Interval(sql_values::postgres::IntervalTypmod::UNMODIFIED),
            &["-infinity", "-1 days +02:00", "1 mon", "infinity"],
        ),
        (
            BuiltinType::Jsonb,
            &["null", "[1, null]", "{\"a\":\"b'c\"}"],
        ),
        (
            BuiltinType::Uuid,
            &[
                "00000000-0000-0000-0000-000000000000",
                "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF",
            ],
        ),
    ];
    for standard_strings in [true, false] {
        diesel::select(set_config(
            "standard_conforming_strings",
            if standard_strings { "on" } else { "off" },
            false,
        ))
        .get_result::<String>(&mut connection)
        .unwrap();
        let context = ConstExprContext {
            standard_conforming_strings: standard_strings,
            collation: None,
        };
        for &(target, literals) in groups {
            for &literal in literals {
                let value = PgValue::from(cast_literal(Literal::Quoted(literal), target).unwrap());
                let output = value.to_string();
                let sql_literal =
                    format!("E'{}'", literal.replace('\\', "\\\\").replace('\'', "''"));
                let expression = format!("{sql_literal}::{target}");
                // View DDL preserves the parsed constant for the deparser.
                connection.batch_execute(&format!("DROP VIEW IF EXISTS const_probe; CREATE TEMP VIEW const_probe AS SELECT {expression} AS value")).unwrap();
                let actual = diesel::select(pg_get_viewdef("const_probe", false))
                    .get_result::<String>(&mut connection)
                    .unwrap();
                let expected = ConstExpr::new(Some(&output), target, ShowType::IfNeeded)
                    .with_context(context)
                    .to_string();
                assert_eq!(
                    actual.trim(),
                    format!("SELECT {expected} AS value;"),
                    "{expression}, standard_strings={standard_strings}"
                );
                let array_type = *BuiltinType::ALL
                    .iter()
                    .find(|candidate| {
                        candidate.catalog_name().strip_prefix('_') == Some(target.catalog_name())
                    })
                    .unwrap();
                let array = PgValue::Array(PgArray::new(vec![Some(value), None]));
                let array_output = array.to_string();
                let array_literal = format!(
                    "E'{}'",
                    array_output.replace('\\', "\\\\").replace('\'', "''")
                );
                connection.batch_execute(&format!("DROP VIEW const_probe; CREATE TEMP VIEW const_probe AS SELECT {array_literal}::{array_type} AS value")).unwrap();
                let actual = diesel::select(pg_get_viewdef("const_probe", false))
                    .get_result::<String>(&mut connection)
                    .unwrap();
                let expected = ConstExpr::new(Some(&array_output), array_type, ShowType::IfNeeded)
                    .with_context(context)
                    .to_string();
                assert_eq!(actual.trim(), format!("SELECT {expected} AS value;"));
            }
        }
        let array = PgValue::Array(PgArray::new(vec![
            Some(PgValue::Text("a'\\b".into())),
            None,
            Some(PgValue::Text("NULL".into())),
        ]));
        let output = array.to_string();
        let literal = format!("E'{}'", output.replace('\\', "\\\\").replace('\'', "''"));
        connection.batch_execute(&format!("DROP VIEW const_probe; CREATE TEMP VIEW const_probe AS SELECT {literal}::text[] AS value")).unwrap();
        let actual = diesel::select(pg_get_viewdef("const_probe", false))
            .get_result::<String>(&mut connection)
            .unwrap();
        let expected = ConstExpr::new(Some(&output), BuiltinType::TextArray, ShowType::IfNeeded)
            .with_context(context)
            .to_string();
        assert_eq!(actual.trim(), format!("SELECT {expected} AS value;"));
    }
}

#[test]
fn pg18_constant_type_contexts() {
    use sql_values::postgres::{CharLength, IntervalFields, IntervalTypmod, NumericTypmod};
    let mut connection = postgres::connect(&pg18::PG18, "18");
    let targets = [
        BuiltinType::Integer,
        BuiltinType::Boolean,
        BuiltinType::Text,
        BuiltinType::Numeric(NumericTypmod::new(8, 2)),
        BuiltinType::Bpchar(CharLength::new(4)),
        BuiltinType::Varchar(CharLength::new(4)),
        BuiltinType::Timestamp(Some(TimePrecision::new(3))),
        BuiltinType::TimestampTz(Some(TimePrecision::new(3))),
        BuiltinType::Time(Some(TimePrecision::new(3))),
        BuiltinType::TimeTz(Some(TimePrecision::new(3))),
        BuiltinType::Interval(
            IntervalTypmod::new(Some(IntervalFields::DayToSecond), Some(3)).unwrap(),
        ),
        BuiltinType::NumericArray(NumericTypmod::new(8, 2)),
    ];
    for target in targets {
        connection.batch_execute(&format!("DROP VIEW IF EXISTS const_probe; CREATE TEMP VIEW const_probe AS SELECT NULL::{target} AS value")).unwrap();
        let actual = diesel::select(pg_get_viewdef("const_probe", false))
            .get_result::<String>(&mut connection)
            .unwrap();
        let expected = ConstExpr::new(None, target, ShowType::IfNeeded).to_string();
        assert_eq!(actual.trim(), format!("SELECT {expected} AS value;"));
    }
    for (target, literal) in [
        (BuiltinType::Numeric(NumericTypmod::new(8, 2)), "-1.25"),
        (BuiltinType::Numeric(NumericTypmod::new(8, 2)), "1.25"),
        (BuiltinType::Bpchar(CharLength::new(4)), "ab"),
        (BuiltinType::Varchar(CharLength::new(4)), "ab"),
        (
            BuiltinType::Time(Some(TimePrecision::new(3))),
            "12:34:56.1234",
        ),
        (
            BuiltinType::Timestamp(Some(TimePrecision::new(3))),
            "2000-01-01 12:34:56.1234",
        ),
    ] {
        let output = cast_literal(Literal::Quoted(literal), target.pg_type())
            .unwrap()
            .to_string();
        connection.batch_execute(&format!("DROP VIEW const_probe; CREATE TEMP VIEW const_probe AS SELECT {}::{target} AS value", pg18::quoted(literal))).unwrap();
        let actual = diesel::select(pg_get_viewdef("const_probe", false))
            .get_result::<String>(&mut connection)
            .unwrap();
        let expected = ConstExpr::new(Some(&output), target.pg_type(), ShowType::Never).to_string();
        assert_eq!(
            actual.trim(),
            format!("SELECT {expected}::{target} AS value;")
        );
    }
    for (target, literal) in [
        (BuiltinType::Integer, "1"),
        (BuiltinType::Numeric(None), "1.25"),
        (BuiltinType::Boolean, "true"),
    ] {
        let output = cast_literal(Literal::Quoted(literal), target)
            .unwrap()
            .to_string();
        connection.batch_execute(&format!("DROP VIEW const_probe; CREATE TEMP VIEW const_probe AS SELECT count(*) AS value GROUP BY {}::{target}", pg18::quoted(literal))).unwrap();
        let actual = diesel::select(pg_get_viewdef("const_probe", false))
            .get_result::<String>(&mut connection)
            .unwrap();
        let expected = ConstExpr::new(Some(&output), target, ShowType::Always).to_string();
        assert!(
            actual.contains(&format!("GROUP BY {expected};")),
            "{actual}"
        );
    }
}

#[test]
fn pg18_float_constants() {
    let mut connection = postgres::connect(&pg18::PG18, "18");
    for target in [BuiltinType::Real, BuiltinType::DoublePrecision] {
        for literal in ["-0", "0", "-1.25", "1e20", "NaN", "Infinity", "-Infinity"] {
            let expression = format!("{}::{target}", pg18::quoted(literal));
            let output = pg18::pg_text(&mut connection, &expression).unwrap();
            connection.batch_execute(&format!("DROP VIEW IF EXISTS const_probe; CREATE TEMP VIEW const_probe AS SELECT {expression} AS value")).unwrap();
            let actual = diesel::select(pg_get_viewdef("const_probe", false))
                .get_result::<String>(&mut connection)
                .unwrap();
            let expected = ConstExpr::new(Some(&output), target, ShowType::IfNeeded).to_string();
            assert_eq!(actual.trim(), format!("SELECT {expected} AS value;"));
        }
    }
}