use super::{ColumnName, ColumnShape, distinct, joins, width};
use crate::{FieldName, comparison::Path};
const NUM: &FieldName = FieldName::new("num");
const DEN: &FieldName = FieldName::new("den");
const TB: &FieldName = FieldName::new("tb");
const TIMEBASE: &[ColumnShape] = &[
ColumnShape::Plain(ColumnName::of(NUM)),
ColumnShape::Plain(ColumnName::of(DEN)),
];
#[test]
fn a_composite_is_one_entry_and_several_columns() {
const COLUMNS: &[ColumnShape] = &[
ColumnShape::Plain(ColumnName::new("id")),
ColumnShape::Composite {
field: Some(ColumnName::of(TB)),
segments: TIMEBASE,
},
];
assert_eq!(COLUMNS.len(), 2);
assert_eq!(width(COLUMNS), 3);
}
#[test]
fn width_counts_leaves_through_any_depth() {
const RATIO: &[ColumnShape] = &[ColumnShape::Composite {
field: Some(ColumnName::new("rate")),
segments: TIMEBASE,
}];
const COLUMNS: &[ColumnShape] = &[ColumnShape::Composite {
field: Some(ColumnName::of(TB)),
segments: RATIO,
}];
assert_eq!(COLUMNS.len(), 1);
assert_eq!(width(COLUMNS), 2);
}
#[test]
fn a_flattened_composite_is_as_wide_as_a_prefixed_one() {
const FLATTEN: &[ColumnShape] = &[ColumnShape::Composite {
field: None,
segments: TIMEBASE,
}];
const PREFIXED: &[ColumnShape] = &[ColumnShape::Composite {
field: Some(ColumnName::of(TB)),
segments: TIMEBASE,
}];
assert_eq!(width(FLATTEN), width(PREFIXED));
}
#[test]
fn joins_compares_against_the_name_the_renderer_will_send() {
let tb = Path::under(TB, None);
let num = Path::under(NUM, Some(&tb));
assert!(joins(&num, FieldName::new("tb_num")));
assert!(!joins(&num, FieldName::new("tbnum")));
assert!(!joins(&num, FieldName::new("clip_tb_num")));
assert!(!joins(&num, FieldName::new("tb_denum")));
}
#[test]
fn a_top_level_segment_joins_to_itself() {
let tb = Path::under(TB, None);
assert!(joins(&tb, TB));
assert!(!joins(&tb, FieldName::new("t")));
}
#[test]
fn a_flattened_segment_meets_a_column_the_holder_already_has() {
const PREFIXED: &[ColumnShape] = &[
ColumnShape::Plain(ColumnName::of(NUM)),
ColumnShape::Composite {
field: Some(ColumnName::of(TB)),
segments: TIMEBASE,
},
];
const FLATTENED: &[ColumnShape] = &[
ColumnShape::Plain(ColumnName::of(NUM)),
ColumnShape::Composite {
field: None,
segments: TIMEBASE,
},
];
assert!(distinct(PREFIXED, 1));
assert!(!distinct(FLATTENED, 1));
assert!(distinct(FLATTENED, 0));
}
#[test]
fn two_flattened_composites_collide_with_each_other() {
const COLUMNS: &[ColumnShape] = &[
ColumnShape::Composite {
field: None,
segments: TIMEBASE,
},
ColumnShape::Composite {
field: None,
segments: TIMEBASE,
},
];
assert!(distinct(COLUMNS, 0));
assert!(!distinct(COLUMNS, 1));
}
#[test]
fn a_composite_can_collide_with_its_own_segment() {
const INNER: &[ColumnShape] = &[ColumnShape::Plain(ColumnName::new("num"))];
const SELF_COLLIDING: &[ColumnShape] = &[ColumnShape::Composite {
field: None,
segments: &[
ColumnShape::Composite {
field: Some(ColumnName::of(TB)),
segments: INNER,
},
ColumnShape::Plain(ColumnName::new("tb_num")),
],
}];
assert!(!distinct(SELF_COLLIDING, 0));
}
#[cfg(feature = "sqlite")]
#[test]
fn the_decode_asks_for_the_name_the_select_renders() {
use crate::comparison::sql::{column_name, fold_columns};
const ID: &FieldName = FieldName::new("id");
const COLUMNS: &[ColumnShape] = &[
ColumnShape::Plain(ColumnName::of(ID)),
ColumnShape::Composite {
field: Some(ColumnName::of(TB)),
segments: TIMEBASE,
},
];
let rendered =
fold_columns::<sqlx::Sqlite, Vec<String>>(COLUMNS, Vec::new(), &mut |mut names, column| {
names.push(column.as_str().to_owned());
names
});
let tb = Path::under(TB, None);
let read = [
column_name(&Path::under(ID, None)),
column_name(&Path::under(NUM, Some(&tb))),
column_name(&Path::under(DEN, Some(&tb))),
];
assert_eq!(rendered, [r#""id""#, r#""tb_num""#, r#""tb_den""#]);
assert_eq!(
rendered,
read
.iter()
.map(|name| format!("\"{name}\""))
.collect::<Vec<_>>(),
"the read's name is the rendered one with the dialect's brackets taken off"
);
}
#[cfg(feature = "sqlx")]
#[test]
fn only_a_composites_leaf_allocates_its_name() {
use std::borrow::Cow;
use crate::comparison::sql::column_name;
let tb = Path::under(TB, None);
assert!(matches!(column_name(&tb), Cow::Borrowed("tb")));
assert!(matches!(
column_name(&Path::under(NUM, Some(&tb))),
Cow::Owned(_)
));
}
#[test]
fn the_shipped_instant_is_two_columns() {
use crate::{ColumnKind, Timestamp, shape};
const AT: &FieldName = FieldName::new("at");
const COLUMNS: &[ColumnShape] = &[
ColumnShape::Plain(ColumnName::new("id")),
shape::<Timestamp>(ColumnName::of(AT)),
];
assert_eq!(COLUMNS.len(), 2, "an id and an instant");
assert_eq!(width(COLUMNS), 3, "which is three columns");
assert_eq!(<Timestamp as ColumnKind>::SEGMENTS.len(), 2);
let at = Path::under(AT, None);
assert!(joins(
&Path::under(FieldName::new("secs"), Some(&at)),
FieldName::new("at_secs")
));
assert!(joins(
&Path::under(FieldName::new("nanos"), Some(&at)),
FieldName::new("at_nanos")
));
}
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn an_instant_decodes_from_both_of_its_columns_and_refuses_a_pair_it_did_not_write() {
use sqlx::Connection as _;
use crate::{Assemble, Timestamp, assembled};
let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
.await
.expect("an in-memory database");
for statement in [
r#"CREATE TABLE "stamps" ("id" INTEGER, "at_secs" BIGINT, "at_nanos" INT)"#,
r#"INSERT INTO "stamps" VALUES (1, 1786310043, 123456789)"#,
r#"INSERT INTO "stamps" VALUES (2, 2, -999999999)"#,
] {
sqlx::query(statement)
.execute(&mut db)
.await
.expect("the fixture's own DDL");
}
let read = |id: i64| {
sqlx::query(r#"SELECT "at_nanos", "id", "at_secs" FROM "stamps" WHERE "id" = ?"#).bind(id)
};
let stored = read(1).fetch_one(&mut db).await.expect("one row");
let at: Timestamp = assembled(&stored, FieldName::new("at"), None).expect("the pair decodes");
assert_eq!(at.to_string(), "2026-08-09T21:14:03.123456789Z");
let forged = read(2).fetch_one(&mut db).await.expect("one row");
let refused =
<Timestamp as Assemble<_>>::assemble(&forged, Some(&Path::under(FieldName::new("at"), None)))
.expect_err("a sign-crossing pair is not an instant");
assert!(
matches!(&refused, sqlx::Error::ColumnDecode { index, .. } if index == "at_nanos"),
"{refused:?}"
);
}
#[test]
fn the_three_leaf_words_answer_two_independent_bits() {
const PLAIN: ColumnShape = ColumnShape::Plain(ColumnName::new("pts"));
const NULLABLE: ColumnShape = ColumnShape::Nullable(ColumnName::new("nanos"));
const DERIVED: ColumnShape = ColumnShape::Derived(ColumnName::new("area"));
let table: Vec<_> = [PLAIN, NULLABLE, DERIVED]
.into_iter()
.map(|shape| (shape.holds_value(), shape.self_nullable()))
.collect();
assert_eq!(
table,
[(true, false), (false, true), (false, false)],
"plain: value, never null · nullable: index, may be null · derived: index, never null"
);
assert_eq!(
[PLAIN, NULLABLE, DERIVED].map(|shape| shape.width()),
[1, 1, 1],
"all three are ONE column the DDL creates and the write binds"
);
const LEAVES: &[ColumnShape] = &[PLAIN, NULLABLE, DERIVED];
const _: () = assert!(width(LEAVES) == 3);
const _: () = assert!(super::value_width(LEAVES) == 1);
const COMPOSITE: ColumnShape = ColumnShape::Composite {
field: Some(ColumnName::of(TB)),
segments: TIMEBASE,
};
assert!(COMPOSITE.holds_value());
assert!(!COMPOSITE.self_nullable());
assert_eq!(super::value_width(&[COMPOSITE]), 2);
}
#[test]
fn the_two_derived_words_are_named_alike_and_counted_alike() {
const PARTIAL: &[ColumnShape] = &[
ColumnShape::Plain(ColumnName::new("pts")),
ColumnShape::Nullable(ColumnName::new("index")),
];
const TOTAL: &[ColumnShape] = &[
ColumnShape::Plain(ColumnName::new("pts")),
ColumnShape::Derived(ColumnName::new("index")),
];
assert_eq!(width(PARTIAL), width(TOTAL), "both are two COLUMNS");
assert_eq!(
super::value_width(PARTIAL),
super::value_width(TOTAL),
"and one VALUE column apiece"
);
assert_eq!(
super::stored_column(TOTAL, "index").map(FieldName::as_str),
Some("index"),
"a lookup answers a total index's stored spelling as it answers a partial one's"
);
assert!(
distinct(TOTAL, 1),
"and a derived leaf takes part in the collision fence like any other column"
);
}
#[cfg(all(feature = "sqlite", feature = "regex"))]
#[tokio::test]
async fn a_pattern_column_round_trips_as_text_and_refuses_one_that_no_longer_compiles() {
use sqlx::Connection as _;
use crate::Assemble;
let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
.await
.expect("an in-memory database");
for statement in [
r#"CREATE TABLE "watches" ("id" INTEGER, "include" TEXT)"#,
r#"INSERT INTO "watches" VALUES (1, '^[a-z]+(?:-[0-9]+)?$')"#,
r#"INSERT INTO "watches" VALUES (2, NULL)"#,
r#"INSERT INTO "watches" VALUES (3, 'a(b')"#,
] {
sqlx::query(statement)
.execute(&mut db)
.await
.expect("the fixture's own DDL");
}
let read = |id: i64| sqlx::query(r#"SELECT "include" FROM "watches" WHERE "id" = ?"#).bind(id);
let under = Path::under(FieldName::new("include"), None);
let stored = read(1).fetch_one(&mut db).await.expect("one row");
let pattern =
<regex::Regex as Assemble<_>>::assemble(&stored, Some(&under)).expect("the pattern compiles");
assert_eq!(
pattern.as_str(),
"^[a-z]+(?:-[0-9]+)?$",
"what comes back is the text that was stored"
);
assert!(
pattern.is_match("alpha-7") && !pattern.is_match("Alpha"),
"and the value that comes back is the automaton that text names"
);
let absent = read(2).fetch_one(&mut db).await.expect("one row");
let none = <Option<regex::Regex> as Assemble<_>>::assemble(&absent, Some(&under))
.expect("a NULL is a value of the optional column");
assert!(none.is_none(), "an absent pattern comes back absent");
let forged = read(3).fetch_one(&mut db).await.expect("one row");
let refused = <regex::Regex as Assemble<_>>::assemble(&forged, Some(&under))
.expect_err("`a(b` is not a pattern this build compiles");
assert!(
matches!(&refused, sqlx::Error::ColumnDecode { index, .. } if index == "include"),
"the refusal names the COLUMN: {refused:?}"
);
let source = std::error::Error::source(&refused).expect("the refusal carries its cause");
assert!(
source
.to_string()
.contains("the stored pattern does not compile"),
"and the cause says what went wrong: {source}"
);
let refused_optional = <Option<regex::Regex> as Assemble<_>>::assemble(&forged, Some(&under))
.expect_err("an optional pattern column has the same teeth");
assert!(
matches!(&refused_optional, sqlx::Error::ColumnDecode { index, .. } if index == "include"),
"{refused_optional:?}"
);
}
#[cfg(feature = "regex")]
#[test]
fn a_pattern_is_one_column_wide_whether_or_not_it_is_optional() {
use crate::{ColumnKind, ColumnName, shape, width};
assert!(
<regex::Regex as ColumnKind>::SEGMENTS.is_empty(),
"a pattern is a SCALAR"
);
const FIELD: ColumnName = ColumnName::new("include");
assert_eq!(width(&[shape::<regex::Regex>(FIELD)]), 1);
assert_eq!(width(&[shape::<Option<regex::Regex>>(FIELD)]), 1);
}