use core::convert::Infallible;
use super::SqlScalarComparison;
use crate::{ScalarFilter, Score, comparison::TryFromFilter};
fn permille(score: Score) -> Result<i32, Infallible> {
Ok((score.get() * 1000.0) as i32)
}
#[test]
fn a_crossing_replaces_the_operand_with_its_stored_form() {
let filter = ScalarFilter::<Score>::new()
.with_eq(Score::new(0.75).unwrap())
.with_in_([Score::ZERO, Score::ONE]);
let crossed = SqlScalarComparison::<i32, ()>::try_from_filter_with(filter, permille).unwrap();
assert_eq!(crossed.eq(), Some(&750));
assert_eq!(crossed.in_(), Some(&[0, 1000][..]));
}
#[test]
fn a_list_crossing_stops_at_the_first_refusal() {
let filter = ScalarFilter::<i64>::new().with_in_([1i64, 300, 2]);
let crossed = SqlScalarComparison::<u8, ()>::try_from_filter(filter);
assert!(crossed.is_err());
let all_fit = ScalarFilter::<i64>::new().with_in_([1i64, 2, 3]);
let crossed = SqlScalarComparison::<u8, ()>::try_from_filter(all_fit).unwrap();
assert_eq!(crossed.in_(), Some(&[1u8, 2, 3][..]));
}
#[test]
fn an_empty_membership_list_stays_present() {
let filter = ScalarFilter::<i64>::new().with_in_(Vec::<i64>::new());
let crossed = SqlScalarComparison::<i64, ()>::try_from_filter(filter).unwrap();
assert_eq!(crossed.in_(), Some(&[][..]));
assert!(!crossed.is_empty());
assert_eq!(crossed.conjuncts(), 1);
}
#[test]
fn the_identity_crossing_cannot_fail() {
let filter = ScalarFilter::<i64>::new().with_eq(1i64);
let crossed: Result<SqlScalarComparison<i64, ()>, Infallible> =
SqlScalarComparison::try_from_filter(filter);
assert_eq!(crossed.unwrap().eq(), Some(&1));
}
#[test]
fn the_operators_still_compare_whole_comparisons() {
let one =
SqlScalarComparison::<i64, ()>::try_from_filter(ScalarFilter::<i64>::new().with_eq(1i64))
.unwrap();
let same =
SqlScalarComparison::<i64, ()>::try_from_filter(ScalarFilter::<i64>::new().with_eq(1i64))
.unwrap();
let other =
SqlScalarComparison::<i64, ()>::try_from_filter(ScalarFilter::<i64>::new().with_eq(2i64))
.unwrap();
assert_eq!(one, same);
assert!(one == same);
assert!(one != other);
assert_eq!(one.eq(), Some(&1));
}
#[cfg(feature = "sqlite")]
mod sqlite {
use core::cell::RefCell;
use super::{SqlScalarComparison, permille};
use crate::{
At, BeU64, ComplexComparison, FieldName, ScalarFilter, Score,
comparison::{
TryFromFilter,
sql::{
QueryBuilder, SelectClause, SqlConjunction,
tests::{Probe, ROW, render, threaded},
},
},
};
#[test]
fn a_threaded_comparison_hands_the_accumulator_back_for_the_next_one() {
let cmp = SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(
ScalarFilter::<i64>::new().with_eq(1i64).with_gt(3i64),
)
.unwrap();
let mut builder = QueryBuilder::<SelectClause, sqlx::Sqlite>::select()
.push_field("\"id\"")
.from("\"t\"")
.begin_where();
{
let accumulator = SqlConjunction::new(builder.inner_mut());
let accumulator = cmp
.apply(At::new(&ROW).frame(FieldName::new("n")).at(), accumulator)
.unwrap();
cmp
.apply(At::new(&ROW).frame(FieldName::new("m")).at(), accumulator)
.unwrap();
}
assert_eq!(
builder.finalize().into_string(),
"SELECT \"id\" FROM \"t\" WHERE \"n\" = ? AND \"n\" > ? AND \"m\" = ? AND \"m\" > ?"
);
}
fn probed<'a>(
filter: ScalarFilter<i64>,
bound: &'a RefCell<Vec<i64>>,
) -> SqlScalarComparison<Probe<'a>, sqlx::Sqlite> {
SqlScalarComparison::try_from_filter_with(filter, |value| {
Ok::<_, core::convert::Infallible>(Probe { value, bound })
})
.unwrap()
}
fn apply_probed(comparison: &SqlScalarComparison<Probe<'_>, sqlx::Sqlite>) -> String {
threaded::<sqlx::Sqlite, _>("n", comparison)
}
#[test]
fn every_operand_the_comparison_holds_is_bound() {
let bound = RefCell::new(Vec::new());
let cmp = probed(ScalarFilter::new().with_eq(1i64).with_gt(3i64), &bound);
apply_probed(&cmp);
assert_eq!(*bound.borrow(), [1, 3]);
}
#[test]
fn two_comparisons_render_alike_and_bind_differently() {
let ascending = RefCell::new(Vec::new());
let descending = RefCell::new(Vec::new());
let sql = apply_probed(&probed(
ScalarFilter::new().with_eq(1i64).with_gt(3i64),
&ascending,
));
let same_sql = apply_probed(&probed(
ScalarFilter::new().with_eq(3i64).with_gt(1i64),
&descending,
));
assert_eq!(sql, same_sql);
assert_eq!(*ascending.borrow(), [1, 3]);
assert_eq!(*descending.borrow(), [3, 1]);
}
#[test]
fn every_operator_renders_its_own_conjunct() {
let filter = ScalarFilter::<i64>::new()
.with_eq(1i64)
.with_ne(2i64)
.with_gt(3i64)
.with_gte(4i64)
.with_lt(5i64)
.with_lte(6i64)
.with_in_([7i64, 8])
.with_not_in([9i64]);
let crossed = SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(filter).unwrap();
assert_eq!(crossed.conjuncts(), 8);
assert_eq!(
render::<sqlx::Sqlite, _>("n", &crossed),
(
"\"n\" = ? AND NOT ( \"n\" = ? ) AND \"n\" > ? AND \"n\" >= ? AND \"n\" < ? AND \
\"n\" <= ? AND \"n\" IN (?, ?) AND NOT ( \"n\" IN (?) )"
.to_owned(),
9
)
);
}
#[test]
fn the_carrier_is_invisible_in_the_sql() {
let native = SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(
ScalarFilter::<i64>::new().with_eq(1i64),
)
.unwrap();
let blob = SqlScalarComparison::<BeU64, sqlx::Sqlite>::try_from_filter(
ScalarFilter::<u64>::new().with_eq(1u64),
)
.unwrap();
assert_eq!(blob.eq(), Some(&BeU64(1)));
assert_eq!(
render::<sqlx::Sqlite, _>("n", &native),
render::<sqlx::Sqlite, _>("n", &blob)
);
}
#[test]
fn an_empty_membership_list_renders_a_contradiction() {
let in_ = SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(
ScalarFilter::<i64>::new().with_in_(Vec::<i64>::new()),
)
.unwrap();
let not_in = SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(
ScalarFilter::<i64>::new().with_not_in(Vec::<i64>::new()),
)
.unwrap();
assert_eq!(
render::<sqlx::Sqlite, _>("n", &in_),
("1 = 0".to_owned(), 0)
);
assert_eq!(
render::<sqlx::Sqlite, _>("n", ¬_in),
("NOT ( 1 = 0 )".to_owned(), 0)
);
}
#[test]
fn a_borrowed_operand_lowers_as_the_owned_one_does() {
let owned = SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(
ScalarFilter::<i64>::new().with_eq(1i64),
)
.unwrap();
let value = 1i64;
let borrowed = SqlScalarComparison::<&i64, sqlx::Sqlite>::try_from_filter(
ScalarFilter::<&i64>::new().with_eq(&value),
)
.unwrap();
assert_eq!(
render::<sqlx::Sqlite, _>("n", &owned),
render::<sqlx::Sqlite, _>("n", &borrowed)
);
}
#[test]
fn a_declared_converter_renders_what_the_trait_path_does() {
let declared = SqlScalarComparison::<i32, sqlx::Sqlite>::try_from_filter_with(
ScalarFilter::<Score>::new().with_eq(Score::new(0.75).unwrap()),
permille,
)
.unwrap();
let plain = SqlScalarComparison::<i32, sqlx::Sqlite>::try_from_filter(
ScalarFilter::<i32>::new().with_eq(750i32),
)
.unwrap();
assert_eq!(declared, plain);
assert_eq!(
render::<sqlx::Sqlite, _>("s", &declared),
("\"s\" = ?".to_owned(), 1)
);
}
}
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
mod composite {
use super::SqlScalarComparison;
use crate::{ScalarFilter, Timestamp, comparison::TryFromFilter};
fn at() -> Timestamp {
"2026-08-09T21:14:03.123456789Z"
.parse()
.expect("the fixture parses")
}
fn before_epoch() -> Timestamp {
"1969-12-31T23:59:58.5Z"
.parse()
.expect("the fixture parses")
}
fn crossed<Db>(filter: ScalarFilter<Timestamp>) -> SqlScalarComparison<Timestamp, Db> {
SqlScalarComparison::try_from_filter(filter).expect("the identity crossing cannot fail")
}
#[cfg(feature = "sqlite")]
#[test]
fn every_operator_of_an_instant_is_a_row_value() {
use crate::comparison::sql::tests::render;
let filter = ScalarFilter::new()
.with_eq(at())
.with_ne(before_epoch())
.with_gt(at())
.with_gte(at())
.with_lt(at())
.with_lte(at())
.with_in_([at(), before_epoch()])
.with_not_in([before_epoch()]);
let comparison = crossed::<sqlx::Sqlite>(filter);
assert_eq!(comparison.conjuncts(), 8);
assert_eq!(
render::<sqlx::Sqlite, _>("at", &comparison),
(
"(\"at_secs\", \"at_nanos\") = (?, ?) AND \
NOT ( (\"at_secs\", \"at_nanos\") = (?, ?) ) AND \
(\"at_secs\", \"at_nanos\") > (?, ?) AND \
(\"at_secs\", \"at_nanos\") >= (?, ?) AND \
(\"at_secs\", \"at_nanos\") < (?, ?) AND \
(\"at_secs\", \"at_nanos\") <= (?, ?) AND \
(\"at_secs\", \"at_nanos\") IN ((?, ?), (?, ?)) AND \
NOT ( (\"at_secs\", \"at_nanos\") IN ((?, ?)) )"
.to_owned(),
18
)
);
}
#[cfg(feature = "sqlite")]
#[test]
fn an_instants_membership_is_the_pairs_and_not_their_product() {
use crate::comparison::sql::tests::render;
let (sql, binds) = render::<sqlx::Sqlite, _>(
"at",
&crossed::<sqlx::Sqlite>(ScalarFilter::new().with_in_([at(), before_epoch()])),
);
assert_eq!(sql, "(\"at_secs\", \"at_nanos\") IN ((?, ?), (?, ?))");
assert_eq!(binds, 4);
assert!(
!sql.contains(" AND "),
"a membership that decomposed would show the conjunction here: {sql}"
);
}
#[cfg(feature = "sqlite")]
#[test]
fn an_empty_instant_membership_degenerates_as_a_scalars_does() {
use crate::comparison::sql::tests::render;
assert_eq!(
render::<sqlx::Sqlite, _>(
"at",
&crossed::<sqlx::Sqlite>(ScalarFilter::new().with_in_(Vec::<Timestamp>::new()))
),
("1 = 0".to_owned(), 0)
);
assert_eq!(
render::<sqlx::Sqlite, _>(
"at",
&crossed::<sqlx::Sqlite>(ScalarFilter::new().with_not_in(Vec::<Timestamp>::new()))
),
("NOT ( 1 = 0 )".to_owned(), 0)
);
}
#[cfg(feature = "sqlite")]
#[test]
fn a_scalar_operand_still_names_one_column() {
use crate::comparison::sql::tests::render;
let comparison = SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(
ScalarFilter::<i64>::new().with_lt(7i64),
)
.unwrap();
assert_eq!(
render::<sqlx::Sqlite, _>("n", &comparison),
("\"n\" < ?".to_owned(), 1)
);
}
#[cfg(feature = "postgres")]
#[test]
fn the_postgres_row_value_numbers_both_placeholders() {
use crate::comparison::sql::tests::render;
assert_eq!(
render::<sqlx::Postgres, _>(
"at",
&crossed::<sqlx::Postgres>(ScalarFilter::new().with_gte(at()).with_lt(before_epoch()))
),
(
"(\"at_secs\", \"at_nanos\") >= ($1, $2) AND (\"at_secs\", \"at_nanos\") < ($3, $4)"
.to_owned(),
4
)
);
}
#[cfg(feature = "mysql")]
#[test]
fn the_mysql_row_value_brackets_with_backticks() {
use crate::comparison::sql::tests::render;
assert_eq!(
render::<sqlx::MySql, _>(
"at",
&crossed::<sqlx::MySql>(ScalarFilter::new().with_gte(at()).with_lt(before_epoch()))
),
(
"(`at_secs`, `at_nanos`) >= (?, ?) AND (`at_secs`, `at_nanos`) < (?, ?)".to_owned(),
4
)
);
}
}
#[cfg(all(
feature = "mediatime",
any(feature = "sqlite", feature = "postgres", feature = "mysql")
))]
mod derived_leaf {
use core::num::NonZeroI32;
use super::SqlScalarComparison;
use crate::MediaTimestamp;
const VALUE: &str = "(\"at_pts\", \"at_timebase_num\", \"at_timebase_den\")";
const WHOLE: &str = "(\"at_pts\", \"at_timebase_num\", \"at_timebase_den\", \"at_nanos\")";
fn placeable() -> MediaTimestamp {
instant(90_000, 1, 90_000)
}
fn later() -> MediaTimestamp {
instant(180_000, 1, 90_000)
}
fn unplaceable() -> MediaTimestamp {
let extreme = instant(i64::MAX, 1, 1);
assert!(
extreme.to_nanos().is_err(),
"the fixture is only a fixture while its position has nowhere to land"
);
extreme
}
fn instant(pts: i64, num: i32, den: i32) -> MediaTimestamp {
MediaTimestamp::new(mediatime::Timestamp::new(
pts,
mediatime::Timebase::new(
num,
NonZeroI32::new(den).expect("a denominator is never zero"),
),
))
}
fn eq_of<Db>(value: MediaTimestamp) -> SqlScalarComparison<MediaTimestamp, Db> {
let mut comparison = SqlScalarComparison::new();
comparison.eq = Some(value);
comparison
}
#[cfg(feature = "sqlite")]
#[test]
fn the_identity_operators_name_the_value_columns_and_the_bound_ones_name_them_all() {
use crate::comparison::sql::tests::render;
let mut comparison = SqlScalarComparison::<MediaTimestamp, sqlx::Sqlite>::new();
comparison.eq = Some(placeable());
comparison.ne = Some(later());
comparison.gt = Some(placeable());
comparison.gte = Some(placeable());
comparison.lt = Some(later());
comparison.lte = Some(later());
comparison.in_ = Some(Box::new([placeable(), later()]));
comparison.not_in = Some(Box::new([later()]));
assert_eq!(comparison.conjuncts(), 8);
assert_eq!(
render::<sqlx::Sqlite, _>("at", &comparison),
(
format!(
"{VALUE} = (?, ?, ?) AND \
NOT ( {VALUE} = (?, ?, ?) ) AND \
{WHOLE} > (?, ?, ?, ?) AND \
{WHOLE} >= (?, ?, ?, ?) AND \
{WHOLE} < (?, ?, ?, ?) AND \
{WHOLE} <= (?, ?, ?, ?) AND \
{VALUE} IN ((?, ?, ?), (?, ?, ?)) AND \
NOT ( {VALUE} IN ((?, ?, ?)) )"
),
31
)
);
}
#[cfg(feature = "sqlite")]
#[test]
fn an_instant_past_the_ceiling_is_matched_by_the_pair_that_wrote_it() {
use crate::comparison::sql::tests::render;
let (sql, binds) = render::<sqlx::Sqlite, _>("at", &eq_of::<sqlx::Sqlite>(unplaceable()));
assert_eq!(sql, format!("{VALUE} = (?, ?, ?)"));
assert_eq!(
binds, 3,
"the derived leaf is not an operand of an identity"
);
assert!(
!sql.contains("at_nanos"),
"the derived column is absent by NAME, which is the claim the column list could satisfy by \
accident: {sql}"
);
assert!(
!sql.contains("NULL"),
"and the `NULL` it would have bound is nowhere in the statement: {sql}"
);
}
#[cfg(feature = "sqlite")]
#[test]
fn a_negated_identity_over_an_unplaceable_instant_is_the_value_columns_alone() {
use crate::comparison::sql::tests::render;
let mut comparison = SqlScalarComparison::<MediaTimestamp, sqlx::Sqlite>::new();
comparison.ne = Some(unplaceable());
comparison.not_in = Some(Box::new([unplaceable(), placeable()]));
let (sql, binds) = render::<sqlx::Sqlite, _>("at", &comparison);
assert_eq!(
sql,
format!("NOT ( {VALUE} = (?, ?, ?) ) AND NOT ( {VALUE} IN ((?, ?, ?), (?, ?, ?)) )")
);
assert_eq!(binds, 9, "three operands at three value columns each");
assert!(!sql.contains("NULL"), "{sql}");
}
#[cfg(feature = "sqlite")]
#[test]
fn a_membership_holding_an_unplaceable_instant_binds_only_value_columns() {
use crate::comparison::sql::tests::render;
let mut comparison = SqlScalarComparison::<MediaTimestamp, sqlx::Sqlite>::new();
comparison.in_ = Some(Box::new([unplaceable(), placeable(), later()]));
let (sql, binds) = render::<sqlx::Sqlite, _>("at", &comparison);
assert_eq!(sql, format!("{VALUE} IN ((?, ?, ?), (?, ?, ?), (?, ?, ?))"));
assert_eq!(binds, 9, "three elements at three value columns each");
}
#[cfg(feature = "sqlite")]
#[test]
fn a_bound_over_an_unplaceable_instant_keeps_the_whole_width_and_writes_the_keyword() {
use crate::comparison::sql::tests::render;
let mut comparison = SqlScalarComparison::<MediaTimestamp, sqlx::Sqlite>::new();
comparison.gt = Some(unplaceable());
let (sql, binds) = render::<sqlx::Sqlite, _>("at", &comparison);
assert_eq!(sql, format!("{WHOLE} > (?, ?, ?, NULL)"));
assert_eq!(binds, 3, "the keyword is written, not bound");
}
#[cfg(feature = "postgres")]
#[test]
fn the_postgres_row_value_numbers_only_the_value_columns() {
use crate::comparison::sql::tests::render;
let mut comparison = SqlScalarComparison::<MediaTimestamp, sqlx::Postgres>::new();
comparison.eq = Some(unplaceable());
comparison.gt = Some(placeable());
comparison.in_ = Some(Box::new([placeable(), later()]));
assert_eq!(
render::<sqlx::Postgres, _>("at", &comparison),
(
format!(
"{VALUE} = ($1, $2, $3) AND \
{WHOLE} > ($4, $5, $6, $7) AND \
{VALUE} IN (($8, $9, $10), ($11, $12, $13))"
),
13
)
);
}
#[cfg(feature = "mysql")]
#[test]
fn the_mysql_row_value_backticks_only_the_value_columns() {
use crate::comparison::sql::tests::render;
let mut comparison = SqlScalarComparison::<MediaTimestamp, sqlx::MySql>::new();
comparison.eq = Some(unplaceable());
comparison.in_ = Some(Box::new([placeable(), later()]));
assert_eq!(
render::<sqlx::MySql, _>("at", &comparison),
(
"(`at_pts`, `at_timebase_num`, `at_timebase_den`) = (?, ?, ?) AND \
(`at_pts`, `at_timebase_num`, `at_timebase_den`) IN ((?, ?, ?), (?, ?, ?))"
.to_owned(),
9
)
);
}
#[cfg(feature = "sqlite")]
#[test]
fn a_scalar_renders_byte_identically_through_both_forms() {
use crate::{
At, FieldName,
comparison::sql::{push_operand_cmp, push_value_operand_cmp, tests::ROW},
};
let frame = At::new(&ROW).frame(FieldName::new("id"));
let rendered = |whole: bool| {
let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
if whole {
push_operand_cmp(&mut qb, frame.at(), " = ", &7i64, false);
} else {
push_value_operand_cmp(&mut qb, frame.at(), " = ", &7i64, false);
}
qb.sql().to_owned()
};
assert_eq!(rendered(false), rendered(true));
assert_eq!(rendered(false), "\"id\" = ?");
}
}
#[test]
fn one_threshold_crosses_into_each_width_at_that_widths_precision() {
use crate::{Confidence, ConfidenceFilter, ConfidenceOperand};
let filter = || {
ConfidenceFilter::new()
.with_gte(ConfidenceOperand::decimal("0.1").expect("a confidence"))
.with_lt(ConfidenceOperand::number(1.0).expect("a confidence"))
};
let narrow: SqlScalarComparison<Confidence<f32>, ()> =
TryFromFilter::try_from_filter(filter()).expect("f32 holds both");
assert_eq!(narrow.gte(), Confidence::<f32>::new(0.1).as_ref());
assert_eq!(narrow.lt(), Some(&Confidence::<f32>::ONE));
let wide: SqlScalarComparison<Confidence<f64>, ()> =
TryFromFilter::try_from_filter(filter()).expect("f64 holds both");
assert_eq!(wide.gte(), Confidence::<f64>::new(0.1).as_ref());
assert_ne!(f64::from(narrow.gte().expect("set").get()), 0.1_f64);
assert_eq!(wide.gte().expect("set").get(), 0.1_f64);
assert_eq!(narrow.in_(), None);
assert_eq!(narrow.not_in(), None);
assert_eq!(narrow.conjuncts(), 2);
}
#[cfg(feature = "rust_decimal")]
#[test]
fn an_inexpressible_threshold_refuses_at_the_crossing() {
use crate::{Confidence, ConfidenceFilter, ConfidenceOperand};
let filter = ConfidenceFilter::new()
.with_gte(ConfidenceOperand::decimal("0.1000000000000000000000000000001").expect("in range"));
let refused: Result<SqlScalarComparison<Confidence<rust_decimal::Decimal>, ()>, _> =
TryFromFilter::try_from_filter(filter);
let why = refused.expect_err("the scale cannot carry it");
assert_eq!(why.width(), "f128");
}