use sql_values::postgres::{BuiltinType, ConstExpr, ConstExprContext, NumericTypmod, ShowType};
#[test]
fn constant_modes() {
for (output, target, implicit, explicit, omitted) in [
(Some("1"), BuiltinType::Integer, "1", "1::integer", "1"),
(
Some("-1"),
BuiltinType::Integer,
"'-1'::integer",
"'-1'::integer",
"'-1'",
),
(
Some("t"),
BuiltinType::Boolean,
"true",
"true::boolean",
"true",
),
(
Some("f"),
BuiltinType::Boolean,
"false",
"false::boolean",
"false",
),
(
Some("1.00"),
BuiltinType::Numeric(None),
"1.00",
"1.00::numeric",
"1.00",
),
(
Some("1.00"),
BuiltinType::Numeric(NumericTypmod::new(8, 2)),
"1.00::numeric(8,2)",
"1.00::numeric(8,2)",
"1.00",
),
(
Some("1e2"),
BuiltinType::Numeric(None),
"1e2",
"1e2::numeric",
"1e2",
),
(
Some("1E2"),
BuiltinType::Numeric(None),
"1E2",
"1E2::numeric",
"1E2",
),
(
Some("-1.25"),
BuiltinType::Numeric(None),
"'-1.25'::numeric",
"'-1.25'::numeric",
"'-1.25'",
),
(
Some("NaN"),
BuiltinType::Numeric(None),
"'NaN'::numeric",
"'NaN'::numeric",
"'NaN'",
),
(
Some("abc"),
BuiltinType::Unknown,
"'abc'",
"'abc'::unknown",
"'abc'",
),
(
None,
BuiltinType::Unknown,
"NULL::unknown",
"NULL::unknown",
"NULL",
),
(
None,
BuiltinType::Integer,
"NULL::integer",
"NULL::integer",
"NULL",
),
] {
for (mode, expected) in [
(ShowType::IfNeeded, implicit),
(ShowType::Always, explicit),
(ShowType::Never, omitted),
] {
assert_eq!(ConstExpr::new(output, target, mode).to_string(), expected);
assert_eq!(
ConstExpr::new(output, target, mode).needs_type_label(),
expected.contains("::")
);
}
}
}
#[test]
fn collation_is_suppressed_with_type() {
let context = ConstExprContext {
standard_conforming_strings: true,
collation: Some("pg_catalog.\"C\""),
};
for output in [Some("a'\\b"), None] {
for mode in [ShowType::IfNeeded, ShowType::Always, ShowType::Never] {
let constant = ConstExpr::new(output, BuiltinType::Text, mode);
let expected = if mode == ShowType::Never {
constant.to_string()
} else {
format!("{constant} COLLATE pg_catalog.\"C\"")
};
assert_eq!(constant.with_context(context).to_string(), expected);
}
}
}
#[test]
fn session_string_quoting() {
for (standard_conforming_strings, expected) in [
(true, "'''\\''\\é'::text"),
(false, "'''\\\\''\\\\é'::text"),
] {
let context = ConstExprContext {
standard_conforming_strings,
collation: None,
};
assert_eq!(
ConstExpr::new(Some("'\\'\\é"), BuiltinType::Text, ShowType::IfNeeded)
.with_context(context)
.to_string(),
expected
);
}
}