#![cfg(feature = "sqlite")]
use sqlx::{Connection as _, Sqlite};
use super::SqlGather;
use crate::{
Carrier, ColumnName, ColumnShape, ComplexComparison, FieldName, Identifiable, Record,
RecordAddress, ScalarFilter, Transformer,
comparison::{
At, Backend, Frame, TryFromFilter,
sql::{SqlKeyIn, SqlLoweringError, SqlScalarComparison},
},
query::sql::{CrossingError, SqlQuery},
retrieve::AsyncGather,
};
#[derive(Debug, Clone, PartialEq)]
struct Shot {
id: ShotId,
slate: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct ShotId {
reel: i64,
ordinal: i64,
}
impl Identifiable for Shot {
type Id = ShotId;
fn id_ref(&self) -> &ShotId {
&self.id
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct ShotKey(ShotId);
impl Identifiable for ShotKey {
type Id = ShotId;
fn id_ref(&self) -> &ShotId {
&self.0
}
}
fn shot_key(reel: i64, ordinal: i64) -> ShotKey {
ShotKey(ShotId { reel, ordinal })
}
impl Transformer for Shot {
type Key = ShotKey;
type Lineage = i64;
type Record = Self;
type Graphql = ();
fn key(&self) -> ShotKey {
ShotKey(self.id.clone())
}
}
#[derive(Debug, Clone, PartialEq)]
struct ShotRow {
reel: i64,
ordinal: i64,
slate: String,
}
impl<'r, R> sqlx::FromRow<'r, R> for ShotRow
where
R: sqlx::Row,
i64: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
String: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
for<'a> &'a str: sqlx::ColumnIndex<R>,
{
fn from_row(row: &'r R) -> Result<Self, sqlx::Error> {
Ok(Self {
reel: row.try_get("reel_id")?,
ordinal: row.try_get("ordinal")?,
slate: row.try_get("slate")?,
})
}
}
struct ShotFilter<Db> {
slate: SqlScalarComparison<String, Db>,
}
impl<Db> ComplexComparison<Db> for ShotFilter<Db>
where
Db: Backend<Error = SqlLoweringError>,
SqlScalarComparison<String, Db>: ComplexComparison<Db>,
{
fn conjuncts(&self) -> usize {
ComplexComparison::<Db>::conjuncts(&self.slate)
}
fn apply<'q>(
&'q self,
at: At<'_>,
builder: <Db as Backend>::Builder<'q>,
) -> Result<<Db as Backend>::Builder<'q>, <Db as Backend>::Error> {
let frame = At::frame(at, FieldName::new("slate"));
ComplexComparison::<Db>::apply(&self.slate, Frame::at(&frame), builder)
}
}
fn slated(slate: &str) -> ShotFilter<Sqlite> {
ShotFilter {
slate: SqlScalarComparison::try_from_filter(
ScalarFilter::<std::string::String>::new().with_eq(slate.to_owned()),
)
.expect("a text equality crosses into SQLite"),
}
}
impl<Db> Record<Db> for Shot
where
Db: Backend,
ShotFilter<Db>: ComplexComparison<Db>,
{
type Row = ShotRow;
type Comparison = ShotFilter<Db>;
type OrderBy = ();
}
impl<Db> SqlQuery<Db> for ShotRow
where
Db: Backend + sqlx::Database,
ShotFilter<Db>: ComplexComparison<Db>,
SqlKeyIn<i64, Db, 2>: ComplexComparison<Db>,
i64: Carrier<Db>,
for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
for<'r> String: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
type Record = Shot;
type Address = SqlKeyIn<i64, Db, 2>;
const ADDRESS: RecordAddress = RecordAddress::new(
FieldName::new("shot"),
&[FieldName::new("reel_id"), FieldName::new("ordinal")],
);
const ALIASES: &'static [&'static str] = &["__ig_shot_0__", "__ig_shot_1__"];
const COLUMNS: &'static [ColumnShape] = &[
ColumnShape::Plain(ColumnName::new("reel_id")),
ColumnShape::Plain(ColumnName::new("ordinal")),
ColumnShape::Plain(ColumnName::new("slate")),
];
fn addresses(ids: &[ShotId]) -> Result<Self::Address, CrossingError> {
Ok(SqlKeyIn::new(
["reel_id", "ordinal"],
ids
.iter()
.map(|id| [id.reel, id.ordinal])
.collect::<Vec<_>>(),
))
}
fn id(&self) -> Result<ShotId, CrossingError> {
Ok(ShotId {
reel: self.reel,
ordinal: self.ordinal,
})
}
fn record(self) -> Result<Shot, CrossingError> {
Ok(Shot {
id: ShotId {
reel: self.reel,
ordinal: self.ordinal,
},
slate: self.slate,
})
}
}
async fn store() -> sqlx::sqlite::SqliteConnection {
let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
.await
.expect("an in-memory database");
sqlx::query(
r#"CREATE TABLE "shot" ("reel_id" INTEGER NOT NULL, "ordinal" INTEGER NOT NULL,
"slate" TEXT NOT NULL, PRIMARY KEY ("reel_id", "ordinal"))"#,
)
.execute(&mut db)
.await
.expect("the table");
for (reel, ordinal, slate) in [
(1_i64, 10_i64, "alpha"),
(1, 20, "bravo"),
(2, 10, "charlie"),
(2, 20, "delta"),
] {
sqlx::query(r#"INSERT INTO "shot" VALUES (?, ?, ?)"#)
.bind(reel)
.bind(ordinal)
.bind(slate)
.execute(&mut db)
.await
.expect("a shot");
}
db
}
fn slates(found: &[Option<Shot>]) -> Vec<Option<&str>> {
found
.iter()
.map(|slot| slot.as_ref().map(|shot| shot.slate.as_str()))
.collect()
}
#[tokio::test]
async fn a_compound_key_gather_is_not_the_cartesian_product() {
let mut db = store().await;
let mut gather = SqlGather::<ShotRow, Sqlite>::new(&mut db);
let found = gather
.gather(&[shot_key(1, 10), shot_key(2, 20)], None)
.await
.expect("the gather runs");
assert_eq!(slates(&found), vec![Some("alpha"), Some("delta")]);
}
#[tokio::test]
async fn the_answer_is_in_the_key_lists_order() {
let mut db = store().await;
let mut gather = SqlGather::<ShotRow, Sqlite>::new(&mut db);
let found = gather
.gather(&[shot_key(2, 20), shot_key(1, 10), shot_key(2, 10)], None)
.await
.expect("the gather runs");
assert_eq!(
slates(&found),
vec![Some("delta"), Some("alpha"), Some("charlie")]
);
}
#[tokio::test]
async fn the_filter_prunes_inside_the_one_composed_statement() {
let mut db = store().await;
let mut gather = SqlGather::<ShotRow, Sqlite>::new(&mut db);
let only = slated("delta");
let found = gather
.gather(&[shot_key(1, 10), shot_key(2, 20)], Some(&only))
.await
.expect("the gather runs");
assert_eq!(slates(&found), vec![None, Some("delta")]);
}
#[tokio::test]
async fn a_key_with_no_row_is_an_empty_slot() {
let mut db = store().await;
let mut gather = SqlGather::<ShotRow, Sqlite>::new(&mut db);
let found = gather
.gather(&[shot_key(1, 10), shot_key(9, 99)], None)
.await
.expect("the gather runs");
assert_eq!(slates(&found), vec![Some("alpha"), None]);
}
#[tokio::test]
async fn an_empty_batch_asks_for_no_rows() {
let mut db = store().await;
let mut gather: SqlGather<'_, ShotRow, Sqlite> = SqlGather::new(&mut db);
let found: Vec<Option<Shot>> = gather
.gather(&[] as &[ShotKey], None)
.await
.expect("the gather runs");
assert!(found.is_empty());
}