#[path = "support/containers.rs"]
mod containers;
#[path = "support/exit_slot.rs"]
mod exit_slot;
#[path = "support/pg18.rs"]
mod pg18;
#[path = "support/postgres.rs"]
mod postgres;
use std::{
cmp::Ordering,
hash::{BuildHasher, RandomState},
};
use diesel::PgConnection;
use pg18::{connect, pg_order, pg_text, quoted};
use sql_values::postgres::{
ArrayDim, BuiltinType, CastError, CharLength, InputContext, NumericTypmod, PgArray, PgDate,
PgTimestamp, PgValue,
};
fn dim(lower: i32, length: u32) -> ArrayDim {
ArrayDim::new(lower, length).expect("a bound")
}
fn ints(values: &[Option<i64>]) -> Vec<Option<PgValue>> {
values
.iter()
.map(|value| value.map(PgValue::Integer))
.collect()
}
fn texts(values: &[Option<&str>]) -> Vec<Option<PgValue>> {
values
.iter()
.map(|value| value.map(|text| PgValue::Text(text.into())))
.collect()
}
fn check(
conn: &mut PgConnection,
mismatches: &mut Vec<String>,
expression: &str,
got: Result<String, CastError>,
) {
let expected = pg_text(conn, expression);
if got != expected {
mismatches.push(format!(
"{expression}: crate {got:?}, PostgreSQL {expected:?}"
));
}
}
fn parsed(literal: &str, target: BuiltinType, type_name: &str) -> PgArray {
PgArray::parse(literal, target)
.unwrap_or_else(|error| panic!("{literal:?}::{type_name}: {error}"))
}
fn element_targets() -> Vec<(&'static str, BuiltinType)> {
vec![
("smallint", BuiltinType::Smallint),
("integer", BuiltinType::Integer),
("bigint", BuiltinType::Bigint),
("numeric", BuiltinType::Numeric(None)),
(
"numeric(3,1)",
BuiltinType::Numeric(Some(NumericTypmod::new(3, 1).expect("a typmod"))),
),
("text", BuiltinType::Text),
(
"varchar(3)",
BuiltinType::Varchar(Some(CharLength::new(3).expect("a length"))),
),
("date", BuiltinType::Date),
("timestamp", BuiltinType::Timestamp(None)),
("boolean", BuiltinType::Boolean),
("uuid", BuiltinType::Uuid),
]
}
const LITERALS: &[&str] = &[
"{}",
"{{}}",
"{ }",
"",
" ",
"{1}",
"{1,2}",
"{1,2,3}",
" { 1 , 2 } ",
"{1,2} ",
"{-1}",
"{+5}",
"{nUlL}",
"{null }",
"{ NULL }",
"{NULL,1}",
"{1,NULL,2}",
"{40000}",
"{2147483647}",
"{-2147483648}",
"{2147483648}",
"{99999999999999999999999}",
"{0x1F}",
"{1_000}",
"{1 2}",
"{abc}",
"{1.5}",
"{1e2}",
"{-}",
"{t}",
"{\"\"}",
"{\"1\"}",
"{\" 1 \"}",
"{\"a\"}",
"{\"a\" , 1}",
"{\"a\" \"b\"}",
"{a\"b}",
"{\"x\"y}",
"{\"a\\b\"}",
"{a\\ b c}",
"{\\}",
"{'a'}",
"{1,}",
"{,1}",
"{1,,2}",
"{1,2}x",
"{1,2}{}",
"{1",
"{\"a",
"{",
"{a\\",
"{\"1\"{2}}",
"{ {1}2 }",
"{\"a\"",
"{{1,2},{3,4}}",
"{ {1,2}, {3} }",
"{1,{2,3}}",
"{{1,2},{3}}",
"{{{{{{1}}}}}}",
"{{{{{{{1}}}}}}}",
"[0:1]={1,2}",
"[2:3]={1,2}",
"[-2:-1]={1,2}",
"[+1:2]={1,2}",
"[1:2]={1,2}",
"[1:2]={1}",
"[1:2][1:2]={{1,2},{3,4}}",
"[1:1][1:2]={{1,2},{3,4}}",
"[1:1][1:1]=",
"[1:0]={1,2}",
"[-1:2147483646]=",
"[1:2147483647]=",
"[2147483648:2]=",
"[-2147483649:2]=",
"[99999999999999999999:1]=",
"[--:1]=",
"[1",
"[1][1][1][1][1][1][1]=",
"[1][1][1][1][1][6]={1,2,3,4,5,6}",
"[1:2]{1,2}",
"[1] = {1}",
"[1] [2] {1,2,3,4}",
"[]",
"[a]=",
"[1.5:2]=",
"[1+2:3]=",
"[1_2:3]=",
"[1:]=",
"[ ]=",
"{}[1:1]",
"{1,2}[1:1]",
"{2026-01-01}",
"{2026-01-01,4714-11-24 BC}",
"{2026-13-01}",
"{infinity}",
"{today}",
"{2026-01-01 23:00}",
"{2026-01-01 24:00}",
"{294277-01-01}",
"{4714-11-23 23:00-02 BC}",
"{294276-12-31 23:59:59.999999}",
"{NaN}",
"{Infinity}",
"{1e131072}",
"{12.345}",
"{-0.00}",
"{1_000.5}",
"{t,f}",
"{TRUE,false}",
"{1,0}",
"{tr}",
"{of}",
"{onn}",
"{A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11,a0eebc999c0b4ef8bb6d6bb9bd380a11}",
"{\"{a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11}\"}",
"{{a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11}}",
"{a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a1}",
];
#[test]
fn pg18_reads_every_array_literal_with_every_element_type() {
let mut conn = connect();
let mut mismatches = Vec::new();
let mut answered = 0;
let targets = element_targets();
for literal in LITERALS {
for &(type_name, target) in &targets {
let got = match PgArray::parse(literal, target) {
Err(CastError::Unsupported) => continue,
parsed => parsed.map(|array| array.to_string()),
};
answered += 1;
let expression = format!("{}::{type_name}[]", quoted(literal));
check(&mut conn, &mut mismatches, &expression, got);
}
}
assert!(mismatches.is_empty(), "{}", mismatches.join("\n"));
assert!(answered > 500, "only {answered} arrays answered");
}
fn shapes() -> Vec<(&'static str, PgArray)> {
let day = PgDate::parse("2026-01-01", InputContext::new()).expect("a date");
let min_day = PgDate::parse("4714-11-24 BC", InputContext::new()).expect("a date");
let instant =
PgTimestamp::parse("2026-01-01 23:00:00.5", InputContext::new()).expect("a timestamp");
vec![
(
"array[1]",
PgArray::with_dims(vec![dim(1, 1)], ints(&[Some(1)])).unwrap(),
),
(
"array[1,2,3]",
PgArray::with_dims(vec![dim(1, 3)], ints(&[Some(1), Some(2), Some(3)])).unwrap(),
),
(
"array[NULL,1,2]",
PgArray::with_dims(vec![dim(1, 3)], ints(&[None, Some(1), Some(2)])).unwrap(),
),
(
"'[0:1]={1,2}'::int[]",
PgArray::with_dims(vec![dim(0, 2)], ints(&[Some(1), Some(2)])).unwrap(),
),
(
"'[0:0]={7}'::int[]",
PgArray::with_dims(vec![dim(0, 1)], ints(&[Some(7)])).unwrap(),
),
(
"'[2:3]={1,2}'::int[]",
PgArray::with_dims(vec![dim(2, 2)], ints(&[Some(1), Some(2)])).unwrap(),
),
(
"'[-2:-1]={1,2}'::int[]",
PgArray::with_dims(vec![dim(-2, 2)], ints(&[Some(1), Some(2)])).unwrap(),
),
(
"array[array[1,2],array[3,4]]",
PgArray::with_dims(
vec![dim(1, 2), dim(1, 2)],
ints(&[Some(1), Some(2), Some(3), Some(4)]),
)
.unwrap(),
),
(
"'[1:2][0:1]={{1,2},{3,4}}'::int[]",
PgArray::with_dims(
vec![dim(1, 2), dim(0, 2)],
ints(&[Some(1), Some(2), Some(3), Some(4)]),
)
.unwrap(),
),
(
"array[array[array[1,2]],array[array[3,4]]]",
PgArray::with_dims(
vec![dim(1, 2), dim(1, 1), dim(1, 2)],
ints(&[Some(1), Some(2), Some(3), Some(4)]),
)
.unwrap(),
),
(
"'{{{{{{1}}}}}}'::int[1][1][1][1][1][1]",
PgArray::with_dims(vec![dim(1, 1); 6], ints(&[Some(1)])).unwrap(),
),
("'{}'::int[]", PgArray::new(Vec::new())),
(
"'{}'::int[1][2]",
PgArray::with_dims(vec![dim(1, 0)], Vec::new()).unwrap(),
),
(
r#"array['a b','a"b','a\b','"','NULL','null','','a,b','a{b',' a','a ','1','nUll',NULL]"#,
PgArray::with_dims(
vec![dim(1, 14)],
texts(&[
Some("a b"),
Some("a\"b"),
Some("a\\b"),
Some("\""),
Some("NULL"),
Some("null"),
Some(""),
Some("a,b"),
Some("a{b"),
Some(" a"),
Some("a "),
Some("1"),
Some("nUll"),
None,
]),
)
.unwrap(),
),
(
"array['2026-01-01'::date,'4714-11-24 BC'::date,NULL]",
PgArray::with_dims(
vec![dim(1, 3)],
vec![Some(PgValue::Date(day)), Some(PgValue::Date(min_day)), None],
)
.unwrap(),
),
(
"array['2026-01-01 23:00:00.5'::timestamp,'4714-11-24 00:00:00 BC'::timestamp]",
PgArray::with_dims(
vec![dim(1, 2)],
vec![
Some(PgValue::Timestamp(instant)),
Some(PgValue::Timestamp(
PgTimestamp::parse("4714-11-24 00:00:00 BC", InputContext::new())
.expect("a timestamp"),
)),
],
)
.unwrap(),
),
]
}
#[test]
fn pg18_prints_every_array_shape() {
let mut conn = connect();
let mut mismatches = Vec::new();
for (expression, array) in shapes() {
check(
&mut conn,
&mut mismatches,
expression,
Ok(array.to_string()),
);
}
assert!(mismatches.is_empty(), "{}", mismatches.join("\n"));
}
fn ordered() -> Vec<(&'static str, String, PgArray)> {
let literals: &[(&str, BuiltinType, &str)] = &[
("{}", BuiltinType::Integer, "int[]"),
("{{}}", BuiltinType::Integer, "int[]"),
("{1}", BuiltinType::Integer, "int[]"),
("{1,2}", BuiltinType::Integer, "int[]"),
("{1,2,3}", BuiltinType::Integer, "int[]"),
("{0}", BuiltinType::Integer, "int[]"),
("{2}", BuiltinType::Integer, "int[]"),
("{-1}", BuiltinType::Integer, "int[]"),
("{10}", BuiltinType::Integer, "int[]"),
("{1,10}", BuiltinType::Integer, "int[]"),
("{NULL}", BuiltinType::Integer, "int[]"),
("{1,NULL}", BuiltinType::Integer, "int[]"),
("{NULL,1}", BuiltinType::Integer, "int[]"),
("{NULL,2}", BuiltinType::Integer, "int[]"),
("{{1,2},{3,4}}", BuiltinType::Integer, "int[]"),
("{{1,2},{3,5}}", BuiltinType::Integer, "int[]"),
("{{1}}", BuiltinType::Integer, "int[]"),
("{{1,2}}", BuiltinType::Integer, "int[]"),
("{{{1,2}}}", BuiltinType::Integer, "int[]"),
("[0:0]={7}", BuiltinType::Integer, "int[]"),
("[0:1]={1,2}", BuiltinType::Integer, "int[]"),
("[1:2]={1,2}", BuiltinType::Integer, "int[]"),
("[2:3]={1,2}", BuiltinType::Integer, "int[]"),
("[-2:-1]={1,2}", BuiltinType::Integer, "int[]"),
("{a}", BuiltinType::Text, "text[]"),
("{\"a\"}", BuiltinType::Text, "text[]"),
("{a,b}", BuiltinType::Text, "text[]"),
("{a,b,c}", BuiltinType::Text, "text[]"),
("{b}", BuiltinType::Text, "text[]"),
("{A}", BuiltinType::Text, "text[]"),
("{a b}", BuiltinType::Text, "text[]"),
("{\"a b\"}", BuiltinType::Text, "text[]"),
("{NULL}", BuiltinType::Text, "text[]"),
("{nUlL}", BuiltinType::Text, "text[]"),
("{NULL,a}", BuiltinType::Text, "text[]"),
("{a,NULL}", BuiltinType::Text, "text[]"),
("{a,a}", BuiltinType::Text, "text[]"),
("{\"\"}", BuiltinType::Text, "text[]"),
];
literals
.iter()
.map(|&(literal, target, type_name)| {
let array = parsed(literal, target, type_name);
let collation = if type_name == "text[]" {
" COLLATE \"C\""
} else {
""
};
(
type_name,
format!("{}::{type_name}{collation}", quoted(literal)),
array,
)
})
.collect()
}
#[test]
fn pg18_orders_and_equates_every_array_pair() {
let arrays = ordered();
let mut conn = connect();
let hasher = RandomState::new();
let mut mismatches = Vec::new();
for (left_type, left_sql, left) in &arrays {
for (right_type, right_sql, right) in &arrays {
if left_type != right_type {
continue;
}
let got = left.cmp(right);
let expected = pg_order(&mut conn, left_sql, right_sql).unwrap();
if got != expected {
mismatches.push(format!(
"{left_sql} vs {right_sql}: crate {got:?}, PostgreSQL {expected:?}",
));
}
if got == Ordering::Equal && hasher.hash_one(left) != hasher.hash_one(right) {
mismatches.push(format!(
"{left_sql} and {right_sql} are equal but hash apart"
));
}
}
}
assert!(mismatches.is_empty(), "{}", mismatches.join("\n"));
}
#[test]
fn pg18_casts_every_array_to_every_element_type() {
let length = |n| Some(CharLength::new(n).expect("a length"));
let typmod = |p, s| Some(NumericTypmod::new(p, s).expect("a typmod"));
let sources: &[(&str, &str, BuiltinType)] = &[
("{1,2}", "int[]", BuiltinType::Integer),
("{40000}", "int[]", BuiltinType::Integer),
("{2147483647}", "int[]", BuiltinType::Integer),
("{-2147483648}", "int[]", BuiltinType::Integer),
("{NULL,2}", "int[]", BuiltinType::Integer),
("{{1,2},{3,4}}", "int[]", BuiltinType::Integer),
("[0:1][0:1]={{1,2},{3,4}}", "int[]", BuiltinType::Integer),
("{32767,-32768}", "smallint[]", BuiltinType::Smallint),
(
"{9223372036854775807,-9223372036854775808}",
"bigint[]",
BuiltinType::Bigint,
),
("{1.5,-2.5}", "numeric[]", BuiltinType::Numeric(None)),
("{NaN}", "numeric[]", BuiltinType::Numeric(None)),
("{Infinity}", "numeric[]", BuiltinType::Numeric(None)),
("{12.345}", "numeric[]", BuiltinType::Numeric(None)),
("{1.5,abc,t,2026-01-01}", "text[]", BuiltinType::Text),
("{\"a b\"}", "text[]", BuiltinType::Text),
("{t,f}", "boolean[]", BuiltinType::Boolean),
("{2026-01-01,4714-11-24 BC}", "date[]", BuiltinType::Date),
(
"{2026-01-01 23:00:00.6}",
"timestamp[]",
BuiltinType::Timestamp(None),
),
(
"{2026-01-01 10:00:00.5}",
"varchar(5)[]",
BuiltinType::Varchar(length(5)),
),
];
let targets: &[(&str, BuiltinType)] = &[
("smallint[]", BuiltinType::Smallint),
("integer[]", BuiltinType::Integer),
("bigint[]", BuiltinType::Bigint),
("numeric[]", BuiltinType::Numeric(None)),
("numeric(2,1)[]", BuiltinType::Numeric(typmod(2, 1))),
("text[]", BuiltinType::Text),
("varchar(3)[]", BuiltinType::Varchar(length(3))),
("date[]", BuiltinType::Date),
("timestamp[]", BuiltinType::Timestamp(None)),
("boolean[]", BuiltinType::Boolean),
];
let mut conn = connect();
let mut mismatches = Vec::new();
let mut answered = 0;
for &(literal, source_name, source) in sources {
let array = parsed(literal, source, source_name);
for &(target_name, target) in targets {
if source_name == "smallint[]" && target_name == "boolean[]" {
continue;
}
let got = match array.cast(target) {
Err(CastError::Unsupported) | Err(CastError::CannotCast { .. }) => continue,
casted => casted.map(|array| array.to_string()),
};
answered += 1;
let expression = format!("({}::{source_name})::{target_name}", quoted(literal));
check(&mut conn, &mut mismatches, &expression, got);
}
}
assert!(mismatches.is_empty(), "{}", mismatches.join("\n"));
assert!(answered > 100, "only {answered} casts answered");
}