#[cfg(all(feature = "jiff", feature = "time"))]
#[test]
fn a_temporal_filter_crosses_without_naming_a_converter() {
use jiff::civil;
use crate::{
ScalarFilter, Temporal,
comparison::{TryFromFilter, sql::SqlScalarComparison},
};
let instant: jiff::Timestamp = "2024-05-06T07:08:09.123456789Z".parse().unwrap();
let crossed = SqlScalarComparison::<Temporal<time::OffsetDateTime>, ()>::try_from_filter(
ScalarFilter::<jiff::Timestamp>::new().with_gte(instant),
)
.unwrap();
assert_eq!(
crossed.gte().unwrap().get().unix_timestamp_nanos(),
instant.as_nanosecond()
);
let zoned = SqlScalarComparison::<Temporal<time::OffsetDateTime>, ()>::try_from_filter(
ScalarFilter::<jiff::Zoned>::new().with_lt(instant.to_zoned(jiff::tz::TimeZone::UTC)),
)
.unwrap();
assert_eq!(zoned.lt().unwrap().get().nanosecond(), 123_456_789);
let date = SqlScalarComparison::<Temporal<time::Date>, ()>::try_from_filter(
ScalarFilter::<jiff::civil::Date>::new().with_eq(civil::date(2024, 5, 6)),
)
.unwrap();
assert_eq!(date.eq().unwrap().get().year(), 2024);
let at = SqlScalarComparison::<Temporal<time::Time>, ()>::try_from_filter(
ScalarFilter::<jiff::civil::Time>::new()
.with_in_([civil::Time::new(7, 8, 9, 123_456_789).unwrap()]),
)
.unwrap();
assert_eq!(at.in_().unwrap()[0].get().nanosecond(), 123_456_789);
}
#[cfg(all(feature = "jiff", feature = "time", feature = "sqlite"))]
#[test]
fn the_codegen_projection_resolves_for_a_temporal_field() {
use crate::{
DefaultMarker, Temporal, ToGraphqlFilter,
comparison::{ToDatabaseComparison, TryFromFilter, sql::SqlScalarComparison},
};
type Comparison<F, S> = <F as ToDatabaseComparison<S, sqlx::Sqlite>>::Comparison;
type Filter<T> = <<T as DefaultMarker>::Marker as ToGraphqlFilter>::Filter;
type Projected<T, S> = Comparison<Filter<T>, S>;
let crossed: Projected<jiff::Timestamp, Temporal<time::OffsetDateTime>> =
TryFromFilter::try_from_filter(
Filter::<jiff::Timestamp>::new().with_eq(jiff::Timestamp::UNIX_EPOCH),
)
.unwrap();
let _: SqlScalarComparison<Temporal<time::OffsetDateTime>, sqlx::Sqlite> = crossed;
}
#[cfg(all(feature = "jiff", feature = "time"))]
#[test]
fn the_temporal_crossing_cannot_fail() {
use crate::{
ScalarFilter, Temporal,
comparison::{TryFromFilter, sql::SqlScalarComparison},
};
let crossed: Result<
SqlScalarComparison<Temporal<time::OffsetDateTime>, ()>,
core::convert::Infallible,
> = SqlScalarComparison::try_from_filter(
ScalarFilter::<jiff::Timestamp>::new().with_eq(jiff::Timestamp::UNIX_EPOCH),
);
assert_eq!(
crossed.unwrap().eq().unwrap().get(),
&time::OffsetDateTime::UNIX_EPOCH
);
}
#[cfg(feature = "sqlite")]
mod sqlite {
use crate::{BeU64, Carrier, Score, TypedId};
#[test]
fn a_row_pushes_exactly_one_placeholder() {
struct Scene;
fn placeholder<V: Carrier<sqlx::Sqlite>>(value: &V) -> String {
let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
value.push_bind(&mut qb);
qb.sql().as_str().to_owned()
}
assert_eq!(placeholder(&1i64), "?");
assert_eq!(placeholder(&BeU64(1)), "?");
assert_eq!(placeholder(&Score::ONE), "?");
assert_eq!(placeholder(&&1i64), "?");
assert_eq!(placeholder(&TypedId::<i64, Scene>::new(1)), "?");
}
}
#[cfg(feature = "postgres")]
mod postgres {
use crate::Carrier;
fn bound<V: Carrier<sqlx::Postgres>>(value: &V) -> (String, usize) {
use sqlx::Execute;
let mut qb = sqlx::QueryBuilder::<sqlx::Postgres>::default();
value.push_bind(&mut qb);
let mut built = qb.build();
let binds = match built.take_arguments() {
Ok(Some(args)) => sqlx::Arguments::len(&args),
Ok(None) | Err(_) => 0,
};
(built.sql().as_str().to_owned(), binds)
}
#[test]
fn a_collection_binds_as_one_array_parameter() {
assert_eq!(bound(&Vec::<i64>::new()), ("$1".to_owned(), 1));
assert_eq!(bound(&vec![1i64]), ("$1".to_owned(), 1));
assert_eq!(bound(&vec![1i64, 2, 3, 4, 5]), ("$1".to_owned(), 1));
assert_eq!(
bound(&vec!["hdr".to_owned(), "sdr".to_owned()]),
("$1".to_owned(), 1)
);
assert_eq!(bound(&vec![true, false]), ("$1".to_owned(), 1));
assert_eq!(bound(&vec![1.5f64, 2.5]), ("$1".to_owned(), 1));
assert_eq!(bound(&vec![vec![1u8, 2], vec![3]]), ("$1".to_owned(), 1));
}
#[test]
fn a_byte_column_and_a_list_of_byte_strings_are_two_rows() {
let column = bound(&vec![1u8, 2]);
let list = bound(&vec![vec![1u8, 2]]);
assert_eq!(column, ("$1".to_owned(), 1));
assert_eq!(list, ("$1".to_owned(), 1));
let mut scalar = sqlx::postgres::PgArgumentBuffer::default();
let _ =
sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&[1u8, 2].as_slice(), &mut scalar).unwrap();
let mut array = sqlx::postgres::PgArgumentBuffer::default();
let _ = sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&[vec![1u8, 2]].as_slice(), &mut array)
.unwrap();
assert_eq!(scalar.to_vec(), [1, 2]);
assert_ne!(array.to_vec(), [1, 2]);
}
}
#[cfg(all(
feature = "jiff",
feature = "time",
feature = "sqlite",
feature = "postgres",
feature = "mysql"
))]
#[test]
fn a_temporal_comparison_lowers_the_same_in_every_dialect() {
use crate::{
ScalarFilter, Temporal,
comparison::{
TryFromFilter,
sql::{SqlScalarComparison, tests::render},
},
};
fn gte<Db>() -> SqlScalarComparison<Temporal<time::OffsetDateTime>, Db> {
let at: jiff::Timestamp = "2024-05-06T07:08:09.123456789Z".parse().unwrap();
SqlScalarComparison::try_from_filter(ScalarFilter::<jiff::Timestamp>::new().with_gte(at))
.unwrap()
}
assert_eq!(
render::<sqlx::Sqlite, _>("at", >e()),
("\"at\" >= ?".to_owned(), 1)
);
assert_eq!(
render::<sqlx::Postgres, _>("at", >e()),
("\"at\" >= $1".to_owned(), 1)
);
assert_eq!(
render::<sqlx::MySql, _>("at", >e()),
("`at` >= ?".to_owned(), 1)
);
}
#[cfg(all(feature = "jiff", feature = "time", feature = "postgres"))]
mod bound_bytes {
use core::cell::RefCell;
use std::rc::Rc;
use crate::{Carrier, Temporal, TemporalStorage, TypedId};
#[derive(Clone, Default)]
struct Probe(Rc<RefCell<Vec<u8>>>);
impl sqlx::Type<sqlx::Postgres> for Probe {
fn type_info() -> <sqlx::Postgres as sqlx::Database>::TypeInfo {
<i32 as sqlx::Type<sqlx::Postgres>>::type_info()
}
}
impl sqlx::Encode<'_, sqlx::Postgres> for Probe {
fn encode_by_ref(
&self,
buf: &mut <sqlx::Postgres as sqlx::Database>::ArgumentBuffer,
) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
*self.0.borrow_mut() = buf.to_vec();
Ok(sqlx::encode::IsNull::Yes)
}
}
fn pushed<V: Carrier<sqlx::Postgres>>(value: &V) -> Vec<u8> {
let before = Probe::default();
let after = Probe::default();
let mut qb = sqlx::QueryBuilder::<sqlx::Postgres>::default();
qb.push_bind(before.clone());
value.push_bind(&mut qb);
qb.push_bind(after.clone());
let start = before.0.borrow().len();
let buffer = after.0.borrow();
buffer[start..buffer.len() - 4].to_vec()
}
#[test]
fn the_wrapper_binds_exactly_what_it_wraps() {
let at: jiff::Timestamp = "2024-05-06T07:08:09.123456789Z".parse().unwrap();
let stored = at.to_storage();
assert_eq!(pushed(&Temporal::from(at)), pushed(&stored));
assert!(!pushed(&Temporal::from(at)).is_empty());
}
#[test]
fn a_typed_id_binds_exactly_the_id_it_holds() {
struct Scene;
struct Keyframe;
assert_eq!(pushed(&TypedId::<i64, Scene>::new(7)), pushed(&7i64));
assert_eq!(
pushed(&TypedId::<i64, Scene>::new(7)),
pushed(&TypedId::<i64, Keyframe>::new(7))
);
assert!(!pushed(&TypedId::<i64, Scene>::new(7)).is_empty());
}
#[test]
fn each_temporal_row_pushes_its_own_type() {
use jiff::civil;
let at: jiff::Timestamp = "2024-05-06T07:08:09.123456789Z".parse().unwrap();
let instant = pushed(&Temporal::from(at));
let date = pushed(&Temporal::from(civil::date(2024, 5, 6)));
let time = pushed(&Temporal::from(
civil::Time::new(7, 8, 9, 123_456_789).unwrap(),
));
assert_ne!(instant, date);
assert_ne!(instant, time);
assert_ne!(date, time);
assert_eq!(date.len(), 4 + 4);
assert_eq!(instant.len(), 4 + 8);
assert_eq!(time.len(), 4 + 8);
}
#[test]
fn a_different_operand_pushes_different_bytes() {
let at: jiff::Timestamp = "2024-05-06T07:08:09.123456789Z".parse().unwrap();
let later: jiff::Timestamp = "2024-05-06T07:08:09.123457789Z".parse().unwrap();
assert_ne!(pushed(&Temporal::from(at)), pushed(&Temporal::from(later)));
}
#[test]
fn the_carrier_row_and_sqlxs_encoder_bind_the_same_bytes() {
let at: jiff::Timestamp = "2024-05-06T07:08:09.123456789Z".parse().unwrap();
let wrapped = Temporal::from(at);
let mut buf = sqlx::postgres::PgArgumentBuffer::default();
let _ = sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&wrapped, &mut buf).unwrap();
let encoded = buf.to_vec();
let mut expected = i32::try_from(encoded.len()).unwrap().to_be_bytes().to_vec();
expected.extend_from_slice(&encoded);
assert!(!encoded.is_empty());
assert_eq!(pushed(&wrapped), expected);
}
#[test]
fn the_bind_is_where_postgres_loses_the_last_three_digits() {
let at: jiff::Timestamp = "2024-05-06T07:08:09.123456789Z".parse().unwrap();
let rounded: jiff::Timestamp = "2024-05-06T07:08:09.123456000Z".parse().unwrap();
assert_ne!(at.to_storage(), rounded.to_storage());
assert_eq!(
pushed(&Temporal::from(at)),
pushed(&Temporal::from(rounded))
);
}
}
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
mod instant {
use crate::{Carrier, Timestamp};
fn pushed<Db, V>(value: &V) -> (String, usize)
where
Db: sqlx::Database,
V: Carrier<Db>,
<Db as sqlx::Database>::Arguments: sqlx::IntoArguments<Db>,
{
use sqlx::Execute as _;
let mut qb = sqlx::QueryBuilder::<Db>::default();
value.push_bind(&mut qb);
let mut built = qb.build();
let binds = match built.take_arguments() {
Ok(Some(arguments)) => sqlx::Arguments::len(&arguments),
Ok(None) | Err(_) => 0,
};
(built.sql().as_str().to_owned(), binds)
}
fn at() -> Timestamp {
"2026-08-09T21:14:03.123456789Z"
.parse()
.expect("the fixture parses")
}
#[cfg(feature = "sqlite")]
#[test]
fn sqlite_takes_two_placeholders() {
assert_eq!(pushed::<sqlx::Sqlite, _>(&at()), (String::from("?, ?"), 2));
assert_eq!(pushed::<sqlx::Sqlite, _>(&1i64), (String::from("?"), 1));
}
#[cfg(feature = "postgres")]
#[test]
fn postgres_numbers_them_both() {
assert_eq!(
pushed::<sqlx::Postgres, _>(&at()),
(String::from("$1, $2"), 2)
);
}
#[cfg(feature = "mysql")]
#[test]
fn mysql_takes_two_placeholders() {
assert_eq!(pushed::<sqlx::MySql, _>(&at()), (String::from("?, ?"), 2));
}
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn the_two_binds_are_the_seconds_and_then_the_nanoseconds() {
use sqlx::{Connection as _, Row as _};
let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
.await
.expect("an in-memory database");
sqlx::query(r#"CREATE TABLE "stamps" ("at_secs" BIGINT, "at_nanos" INT)"#)
.execute(&mut db)
.await
.expect("the fixture's own DDL");
let instant = at();
let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::new(r#"INSERT INTO "stamps" VALUES ("#);
instant.push_bind(&mut qb);
qb.push(")");
qb.build().execute(&mut db).await.expect("one row");
let stored = sqlx::query(r#"SELECT "at_secs", "at_nanos" FROM "stamps""#)
.fetch_one(&mut db)
.await
.expect("one row");
assert_eq!(
(
stored.get::<i64, _>("at_secs"),
stored.get::<i32, _>("at_nanos")
),
(instant.as_second(), instant.subsec_nanosecond())
);
assert_eq!(
stored.get::<i32, _>("at_nanos"),
123_456_789,
"all nine digits, which is what the second column exists for"
);
}
}
#[cfg(feature = "sqlite")]
mod cardinality {
use crate::{Carrier, Count};
async fn stored(count: Count) -> i64 {
use sqlx::{Connection as _, Row as _};
let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
.await
.expect("an in-memory database");
sqlx::query(r#"CREATE TABLE "tallies" ("n" INTEGER)"#)
.execute(&mut db)
.await
.expect("the fixture's own DDL");
let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::new(r#"INSERT INTO "tallies" VALUES ("#);
count.push_bind(&mut qb);
qb.push(")");
qb.build().execute(&mut db).await.expect("one row");
sqlx::query(r#"SELECT "n" FROM "tallies""#)
.fetch_one(&mut db)
.await
.expect("one row")
.get::<i64, _>("n")
}
#[tokio::test]
async fn a_count_binds_as_the_signed_form_its_own_codec_produces() {
assert_eq!(stored(Count::new(0)).await, 0);
assert_eq!(stored(Count::new(7)).await, 7);
assert_eq!(stored(Count::new(i64::MAX.unsigned_abs())).await, i64::MAX);
assert_eq!(stored(Count::new(u64::MAX)).await, i64::MAX);
}
#[tokio::test]
async fn a_negative_column_refuses_the_read_rather_than_clamping_it() {
use sqlx::{Connection as _, Row as _};
let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
.await
.expect("an in-memory database");
sqlx::query(r#"CREATE TABLE "tallies" ("n" INTEGER)"#)
.execute(&mut db)
.await
.expect("the fixture's own DDL");
sqlx::query(r#"INSERT INTO "tallies" VALUES (5), (-3)"#)
.execute(&mut db)
.await
.expect("one honest row and one nobody wrote");
let rows = sqlx::query(r#"SELECT "n" FROM "tallies" ORDER BY "n" DESC"#)
.fetch_all(&mut db)
.await
.expect("both rows");
assert_eq!(
rows[0].try_get::<Count, _>("n").expect("an ordinary count"),
Count::new(5)
);
let refused = rows[1]
.try_get::<Count, _>("n")
.expect_err("a negative column is not a cardinality");
let sqlx::Error::ColumnDecode { index, source } = &refused else {
panic!("the refusal names the column it read: {refused:?}");
};
assert_eq!(index.trim_matches('"'), "n");
assert!(
source.to_string().contains("-3"),
"and the sentence carries the value it refused: {source}"
);
}
}
#[cfg(feature = "mysql")]
#[test]
fn a_count_declares_the_unsigned_column_on_mysql() {
assert_eq!(
<crate::Count as sqlx::Type<sqlx::MySql>>::type_info(),
<u64 as sqlx::Type<sqlx::MySql>>::type_info(),
"MySQL holds a cardinality natively, so the row declares the width itself"
);
}
#[cfg(all(feature = "sqlite", feature = "regex"))]
#[test]
fn a_pattern_filter_lowers_to_a_text_predicate_over_the_pattern() {
use crate::{
At, ComplexComparison, FieldName, RecordAddress, ScalarFilter,
comparison::{
TryFromFilter,
sql::{SqlConjunction, SqlScalarComparison},
},
};
const ROW: RecordAddress = RecordAddress::new(FieldName::new("watches"), &[FieldName::new("id")]);
let filter = ScalarFilter::<regex::Regex>::new()
.with_eq(regex::Regex::new("^a+$").expect("a pattern"))
.with_gte(regex::Regex::new("^b").expect("a pattern"));
let crossed =
SqlScalarComparison::<regex::Regex, sqlx::Sqlite>::try_from_filter(filter).expect("it crosses");
let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
let out = SqlConjunction::with_lead(&mut qb, "");
let frame = At::new(&ROW).frame(FieldName::new("include"));
crossed.apply(frame.at(), out).expect("it lowers");
assert_eq!(qb.sql(), r#""include" = ? AND "include" >= ?"#);
}
#[cfg(all(feature = "sqlite", feature = "regex"))]
#[tokio::test]
async fn a_bound_pattern_reaches_the_driver_as_its_text() {
use sqlx::Connection as _;
use crate::Carrier as _;
let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
.await
.expect("an in-memory database");
let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
qb.push("SELECT ");
regex::Regex::new("^[a-z]+(?:-[0-9]+)?$")
.expect("a pattern")
.push_bind(&mut qb);
assert_eq!(qb.sql(), "SELECT ?", "one placeholder, one value");
let bound: String = qb
.build_query_scalar()
.fetch_one(&mut db)
.await
.expect("the driver takes the bind");
assert_eq!(bound, "^[a-z]+(?:-[0-9]+)?$");
}