use super::{At, RecordAddress};
#[cfg(feature = "sqlite")]
use super::{ComplexComparison, Frame};
use crate::FieldName;
#[cfg(feature = "sqlite")]
use crate::{
Backend, Carrier, Nullable, ScalarFilter,
comparison::{
TryFromFilter,
sql::{
QueryBuilder, SelectClause, SqlConjunction, SqlLoweringError, SqlNullable,
SqlScalarComparison,
},
},
};
#[cfg(feature = "sqlite")]
const ROW: RecordAddress = RecordAddress::new(FieldName::new("p"), &[FieldName::new("id")]);
#[cfg(feature = "sqlite")]
fn frame(column: &str) -> Frame<'_> {
At::new(&ROW).frame(FieldName::new(column))
}
#[cfg(feature = "sqlite")]
struct Counted(usize);
#[cfg(feature = "sqlite")]
impl ComplexComparison<sqlx::Sqlite> for Counted {
fn conjuncts(&self) -> usize {
self.0
}
fn apply<'q>(
&'q self,
_at: At<'_>,
builder: <sqlx::Sqlite as Backend>::Builder<'q>,
) -> Result<<sqlx::Sqlite as Backend>::Builder<'q>, SqlLoweringError> {
Ok(builder)
}
}
#[cfg(feature = "sqlite")]
#[test]
fn emptiness_follows_the_conjunct_count() {
assert!(Counted(0).is_empty());
assert!(!Counted(1).is_empty());
}
#[cfg(feature = "sqlite")]
#[test]
fn an_empty_comparison_writes_nothing_and_leaves_nothing_dangling() {
let empty =
SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(ScalarFilter::<i64>::new()).unwrap();
let set = SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(
ScalarFilter::<i64>::new().with_eq(1i64),
)
.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 = empty.apply(frame("n").at(), accumulator).unwrap();
let accumulator = set.apply(frame("m").at(), accumulator).unwrap();
assert_eq!(accumulator.written(), 1);
}
assert_eq!(
builder.finalize().into_string(),
"SELECT \"id\" FROM \"t\" WHERE \"m\" = ?"
);
}
#[cfg(feature = "sqlite")]
#[test]
fn a_statement_whose_comparisons_are_all_empty_opens_no_clause() {
let empty =
SqlScalarComparison::<i64, sqlx::Sqlite>::try_from_filter(ScalarFilter::<i64>::new()).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 = empty.apply(frame("n").at(), accumulator).unwrap();
let accumulator = empty.apply(frame("m").at(), accumulator).unwrap();
assert_eq!(accumulator.written(), 0);
}
assert_eq!(builder.finalize().into_string(), "SELECT \"id\" FROM \"t\"");
}
#[test]
fn a_row_keeps_the_table_and_the_key_columns_it_was_given() {
const SEGMENT: RecordAddress = RecordAddress::new(
FieldName::new("segment"),
&[FieldName::new("media_id"), FieldName::new("segment_id")],
);
assert_eq!(SEGMENT.table(), FieldName::new("segment"));
assert_eq!(
SEGMENT.keys(),
[FieldName::new("media_id"), FieldName::new("segment_id")]
);
}
#[test]
fn the_top_level_names_a_row_and_no_column() {
const SEGMENT: RecordAddress =
RecordAddress::new(FieldName::new("segment"), &[FieldName::new("media_id")]);
let at = At::new(&SEGMENT);
assert!(at.path().is_none());
assert_eq!(at.record(), &SEGMENT);
}
#[test]
fn a_frame_extends_the_path_by_one_segment_and_keeps_the_row() {
const SEGMENT: RecordAddress =
RecordAddress::new(FieldName::new("segment"), &[FieldName::new("media_id")]);
let at = At::new(&SEGMENT);
let timebase = at.frame(FieldName::new("timebase"));
let child = timebase.at();
let path = child.path().expect("a frame names a column");
assert_eq!(path.name(), FieldName::new("timebase"));
assert!(path.parent().is_none());
assert_eq!(child.record(), &SEGMENT);
assert!(at.path().is_none());
}
#[test]
fn the_segments_compose_and_no_layer_knows_the_whole_path() {
const SEGMENT: RecordAddress =
RecordAddress::new(FieldName::new("segment"), &[FieldName::new("media_id")]);
let at = At::new(&SEGMENT);
let a = at.frame(FieldName::new("a"));
let num = a.at().frame(FieldName::new("num"));
let den = num.at().frame(FieldName::new("den"));
let mut segments = Vec::new();
let mut cursor = den.at().path();
while let Some(path) = cursor {
segments.push(path.name());
cursor = path.parent();
}
segments.reverse();
assert_eq!(
segments,
[
FieldName::new("a"),
FieldName::new("num"),
FieldName::new("den")
]
);
}
#[cfg(feature = "sqlite")]
struct Probe<'a> {
value: i64,
bound: &'a core::cell::RefCell<Vec<i64>>,
}
#[cfg(feature = "sqlite")]
impl Carrier<sqlx::Sqlite> for Probe<'_> {
fn push_bind(&self, qb: &mut sqlx::QueryBuilder<sqlx::Sqlite>) {
self.bound.borrow_mut().push(self.value);
qb.push_bind(self.value);
}
}
#[cfg(feature = "sqlite")]
impl crate::ColumnKind for Probe<'_> {}
#[cfg(feature = "sqlite")]
struct Ratio<N, D> {
num: N,
den: D,
}
#[cfg(feature = "sqlite")]
impl<N, D> ComplexComparison<sqlx::Sqlite> for Ratio<N, D>
where
N: ComplexComparison<sqlx::Sqlite>,
D: ComplexComparison<sqlx::Sqlite>,
{
fn conjuncts(&self) -> usize {
self.num.conjuncts() + self.den.conjuncts()
}
fn apply<'q>(
&'q self,
at: At<'_>,
builder: <sqlx::Sqlite as Backend>::Builder<'q>,
) -> Result<<sqlx::Sqlite as Backend>::Builder<'q>, SqlLoweringError> {
let num = at.frame(FieldName::new("num"));
let builder = self.num.apply(num.at(), builder)?;
let den = at.frame(FieldName::new("den"));
self.den.apply(den.at(), builder)
}
}
#[cfg(feature = "sqlite")]
fn rendered<C>(field: &str, comparison: &C) -> String
where
C: ComplexComparison<sqlx::Sqlite>,
{
let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
{
let accumulator = SqlConjunction::with_lead(&mut qb, "");
comparison.apply(frame(field).at(), accumulator).unwrap();
}
qb.sql().as_str().to_owned()
}
#[cfg(feature = "sqlite")]
fn rendered_at_top_level<C>(comparison: &C) -> String
where
C: ComplexComparison<sqlx::Sqlite>,
{
let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
{
let accumulator = SqlConjunction::with_lead(&mut qb, "");
comparison.apply(At::new(&ROW), accumulator).unwrap();
}
qb.sql().as_str().to_owned()
}
#[cfg(feature = "sqlite")]
fn eq(
value: i64,
bound: &core::cell::RefCell<Vec<i64>>,
) -> SqlScalarComparison<Probe<'_>, sqlx::Sqlite> {
SqlScalarComparison::try_from_filter_with(
ScalarFilter::<i64>::new().with_eq(value),
|value: i64| Ok::<_, core::convert::Infallible>(Probe { value, bound }),
)
.unwrap()
}
#[cfg(feature = "sqlite")]
#[test]
fn a_composite_addresses_its_parts_from_the_one_name_it_was_given() {
let bound = core::cell::RefCell::new(Vec::new());
let ratio = Ratio {
num: eq(1, &bound),
den: eq(90000, &bound),
};
assert_eq!(ratio.conjuncts(), 2);
assert_eq!(
rendered("timebase", &ratio),
"\"timebase_num\" = ? AND \"timebase_den\" = ?"
);
assert_eq!(*bound.borrow(), [1, 90000]);
}
#[cfg(feature = "sqlite")]
#[test]
fn a_composite_at_the_top_level_renders_its_parts_bare() {
let bound = core::cell::RefCell::new(Vec::new());
let ratio = Ratio {
num: eq(1, &bound),
den: eq(90000, &bound),
};
assert_eq!(rendered_at_top_level(&ratio), "\"num\" = ? AND \"den\" = ?");
assert_eq!(*bound.borrow(), [1, 90000]);
}
#[cfg(feature = "sqlite")]
#[test]
fn the_suffixes_compose_three_levels_deep() {
let bound = core::cell::RefCell::new(Vec::new());
let nested = Ratio {
num: Ratio {
num: eq(1, &bound),
den: eq(2, &bound),
},
den: eq(3, &bound),
};
assert_eq!(nested.conjuncts(), 3);
assert_eq!(
rendered("a", &nested),
"\"a_num_num\" = ? AND \"a_num_den\" = ? AND \"a_den\" = ?"
);
assert_eq!(*bound.borrow(), [1, 2, 3]);
}
#[cfg(feature = "sqlite")]
#[test]
fn a_same_column_wrapper_inside_a_composite_extends_nothing() {
let bound = core::cell::RefCell::new(Vec::new());
let ratio = Ratio {
num: SqlNullable::<_, i64>::try_from_filter_with_inner(
Nullable::new(ScalarFilter::<i64>::new().with_eq(1i64)).with_null(false),
|inner| {
SqlScalarComparison::try_from_filter_with(inner, |value: i64| {
Ok::<_, core::convert::Infallible>(Probe {
value,
bound: &bound,
})
})
},
)
.unwrap(),
den: eq(2, &bound),
};
assert_eq!(ratio.conjuncts(), 3);
assert_eq!(
rendered("a", &ratio),
"\"a_num\" = ? AND \"a_num\" IS NOT NULL AND \"a_den\" = ?"
);
assert_eq!(*bound.borrow(), [1, 2]);
}
#[cfg(feature = "sqlite")]
#[test]
fn a_composite_name_that_needs_quoting_reaches_its_columns() {
let bound = core::cell::RefCell::new(Vec::new());
let ratio = Ratio {
num: eq(1, &bound),
den: eq(2, &bound),
};
assert_eq!(
rendered("time base", &ratio),
"\"time base_num\" = ? AND \"time base_den\" = ?"
);
assert_eq!(
rendered("time\"base", &ratio),
"\"time\"\"base_num\" = ? AND \"time\"\"base_den\" = ?"
);
}