use core::convert::Infallible;
use super::SqlBooleanComparison;
use crate::{BooleanFilter, comparison::TryFromFilter};
fn yes_no(value: bool) -> Result<String, Infallible> {
Ok(if value { "Y" } else { "N" }.to_owned())
}
#[test]
fn a_parameterless_filter_crosses_into_a_parameterised_comparison() {
let filter = BooleanFilter::new().with_eq(true).with_in_([true, false]);
let crossed = SqlBooleanComparison::<String, ()>::try_from_filter_with(filter, yes_no).unwrap();
assert_eq!(crossed.eq().map(String::as_str), Some("Y"));
assert_eq!(crossed.in_().unwrap(), ["Y".to_owned(), "N".to_owned()]);
}
#[test]
fn the_native_crossing_is_the_identity() {
let crossed: Result<SqlBooleanComparison<bool, ()>, Infallible> =
SqlBooleanComparison::try_from_filter(BooleanFilter::new().with_ne(false));
assert_eq!(crossed.unwrap().ne(), Some(&false));
}
#[test]
fn an_empty_membership_list_is_not_an_absent_operator() {
let empty = SqlBooleanComparison::<bool, ()>::try_from_filter(
BooleanFilter::new().with_in_(Vec::<bool>::new()),
)
.unwrap();
let absent = SqlBooleanComparison::<bool, ()>::try_from_filter(BooleanFilter::new()).unwrap();
assert_eq!(empty.conjuncts(), 1);
assert_eq!(absent.conjuncts(), 0);
assert!(absent.is_empty());
}
#[cfg(feature = "sqlite")]
mod sqlite {
use core::{cell::RefCell, convert::Infallible};
use super::SqlBooleanComparison;
use crate::{
BooleanFilter,
comparison::{
TryFromFilter,
sql::tests::{Probe, render, threaded},
},
};
#[test]
fn a_stored_form_renders_the_same_sql_as_the_native_one() {
let native = SqlBooleanComparison::<bool, sqlx::Sqlite>::try_from_filter(
BooleanFilter::new().with_eq(true),
)
.unwrap();
let integer = SqlBooleanComparison::<i32, sqlx::Sqlite>::try_from_filter_with(
BooleanFilter::new().with_eq(true),
|value: bool| Ok::<_, Infallible>(i32::from(value)),
)
.unwrap();
assert_eq!(integer.eq(), Some(&1));
assert_eq!(
render::<sqlx::Sqlite, _>("flag", &native),
("\"flag\" = ?".to_owned(), 1)
);
assert_eq!(
render::<sqlx::Sqlite, _>("flag", &native),
render::<sqlx::Sqlite, _>("flag", &integer)
);
}
#[test]
fn the_threaded_lowering_renders_the_same_conjuncts() {
let crossed = SqlBooleanComparison::<bool, sqlx::Sqlite>::try_from_filter(
BooleanFilter::new()
.with_eq(true)
.with_ne(false)
.with_in_([true, false])
.with_not_in([true]),
)
.unwrap();
assert_eq!(
threaded::<sqlx::Sqlite, _>("flag", &crossed),
"SELECT \"id\" FROM \"t\" WHERE \"flag\" = ? AND NOT ( \"flag\" = ? ) \
AND \"flag\" IN (?, ?) AND NOT ( \"flag\" IN (?) )"
);
}
#[test]
fn every_operand_the_comparison_holds_is_bound() {
let bound = RefCell::new(Vec::new());
let crossed = SqlBooleanComparison::<Probe<'_>, sqlx::Sqlite>::try_from_filter_with(
BooleanFilter::new()
.with_eq(true)
.with_ne(false)
.with_in_([false, true]),
|value: bool| {
Ok::<_, Infallible>(Probe {
value: i64::from(value),
bound: &bound,
})
},
)
.unwrap();
threaded::<sqlx::Sqlite, _>("flag", &crossed);
assert_eq!(*bound.borrow(), [1, 0, 0, 1]);
}
}