#![cfg(feature = "sqlite")]
use sqlx::Sqlite;
use super::{Find, Ordering, Position, SortValues, address, ordered, scan};
use crate::{
Carrier, ColumnName, ColumnShape, ComplexComparison, Cursor, CursorValue, FieldName,
Identifiable, OrderDirection, OrderTerm, Record, RecordAddress, ScalarFilter, TermName,
Transformer, Walk,
comparison::{
At, Backend, Frame, TryFromFilter,
sql::{
OrderSubjects, SqlKeyIn, SqlKeyset, SqlLoweringError, SqlOrder, SqlScalarComparison,
TermColumns,
},
},
query::{
DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE,
sql::{
CrossingError, ELEMENT, EdgeCollection, EdgeShape, SqlOrdering, SqlQuery, distribute,
hydrate::gathers,
},
},
};
#[derive(Debug, Clone, PartialEq)]
struct Clip {
media: i64,
id: i64,
title: String,
score: Option<f64>,
tags: Vec<String>,
notes: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ClipKey {
media: i64,
id: i64,
}
impl Identifiable for Clip {
type Id = i64;
fn id_ref(&self) -> &i64 {
&self.id
}
}
impl Transformer for Clip {
type Key = ClipKey;
type Lineage = i64;
type Record = Self;
type Graphql = ();
fn key(&self) -> ClipKey {
ClipKey {
media: self.media,
id: self.id,
}
}
}
#[derive(Debug, Clone, PartialEq)]
struct ClipRow {
media: i64,
id: i64,
title: String,
score: Option<f64>,
tags: Vec<String>,
notes: Vec<String>,
}
impl<'r, R> sqlx::FromRow<'r, R> for ClipRow
where
R: sqlx::Row,
i64: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
String: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
f64: 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 {
media: row.try_get("media_id")?,
id: row.try_get("id")?,
title: row.try_get("title")?,
score: row.try_get("score")?,
tags: Vec::new(),
notes: Vec::new(),
})
}
}
fn clip_key<Db>(row: &ClipRow, index: usize, qb: &mut sqlx::QueryBuilder<Db>)
where
Db: sqlx::Database,
i64: Carrier<Db>,
{
match index {
0 => row.media.push_bind(qb),
_ => row.id.push_bind(qb),
}
}
fn clip_tags<Db>(page: &mut [ClipRow], gathered: &[Db::Row]) -> Result<(), sqlx::Error>
where
Db: sqlx::Database,
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>,
{
use sqlx::Row as _;
let element: &str = ELEMENT;
distribute(
page,
gathered,
|row| (row.media, row.id),
|row| Ok((row.try_get("media_id")?, row.try_get("id")?)),
|row| row.try_get::<String, _>(element),
|row| &mut row.tags,
)
}
fn clip_notes<Db>(page: &mut [ClipRow], gathered: &[Db::Row]) -> Result<(), sqlx::Error>
where
Db: sqlx::Database,
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>,
{
use sqlx::Row as _;
let element: &str = ELEMENT;
distribute(
page,
gathered,
|row| (row.media, row.id),
|row| Ok((row.try_get("media_id")?, row.try_get("id")?)),
|row| row.try_get::<String, _>(element),
|row| &mut row.notes,
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ClipOrder {
Media(OrderDirection),
Id(OrderDirection),
Title(OrderDirection),
Score(OrderDirection),
}
#[derive(Debug, Clone, PartialEq)]
enum ClipValue {
Media(i64),
Id(i64),
Title(String),
Score(f64),
}
impl CursorValue for ClipValue {
fn write_cursor(&self, out: &mut Vec<u8>) {
match self {
Self::Media(value) => {
out.push(0);
value.write_cursor(out);
}
Self::Id(value) => {
out.push(1);
value.write_cursor(out);
}
Self::Title(value) => {
out.push(2);
value.write_cursor(out);
}
Self::Score(value) => {
out.push(3);
value.write_cursor(out);
}
}
}
fn read_cursor(bytes: &[u8]) -> Option<Self> {
let (tag, rest) = bytes.split_first()?;
match tag {
0 => i64::read_cursor(rest).map(Self::Media),
1 => i64::read_cursor(rest).map(Self::Id),
2 => String::read_cursor(rest).map(Self::Title),
3 => f64::read_cursor(rest).map(Self::Score),
_ => None,
}
}
}
impl<Db> Carrier<Db> for ClipValue
where
Db: sqlx::Database,
i64: Carrier<Db>,
String: Carrier<Db>,
f64: Carrier<Db>,
{
fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
match self {
Self::Media(value) | Self::Id(value) => value.push_bind(qb),
Self::Title(value) => value.push_bind(qb),
Self::Score(value) => value.push_bind(qb),
}
}
}
struct ClipFilter<Db> {
title: SqlScalarComparison<String, Db>,
}
impl<Db> ComplexComparison<Db> for ClipFilter<Db>
where
Db: Backend<Error = SqlLoweringError>,
SqlScalarComparison<String, Db>: ComplexComparison<Db>,
{
fn conjuncts(&self) -> usize {
ComplexComparison::<Db>::conjuncts(&self.title)
}
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("title"));
ComplexComparison::<Db>::apply(&self.title, Frame::at(&frame), builder)
}
}
impl<Db> Record<Db> for Clip
where
Db: Backend,
ClipFilter<Db>: ComplexComparison<Db>,
{
type Row = ClipRow;
type Comparison = ClipFilter<Db>;
type OrderBy = ClipOrder;
}
impl<Db> SqlQuery<Db> for ClipRow
where
Db: Backend + sqlx::Database,
ClipFilter<Db>: ComplexComparison<Db>,
SqlKeyIn<ClipValue, Db, 1>: 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 = Clip;
type Address = SqlKeyIn<ClipValue, Db, 1>;
const ADDRESS: RecordAddress = RecordAddress::new(
FieldName::new("clip"),
&[FieldName::new("media_id"), FieldName::new("id")],
);
const ALIASES: &'static [&'static str] = &[
"__ig_clip_0__",
"__ig_clip_1__",
"__ig_clip_2__",
"__ig_clip_3__",
"__ig_clip_4__",
"__ig_clip_5__",
"__ig_clip_6__",
"__ig_clip_7__",
];
const COLUMNS: &'static [ColumnShape] = &[
ColumnShape::Plain(ColumnName::new("media_id")),
ColumnShape::Plain(ColumnName::new("id")),
ColumnShape::Plain(ColumnName::new("title")),
ColumnShape::Plain(ColumnName::new("score")),
];
const COLLECTIONS: &'static [EdgeCollection<Self, Db>] = &[
EdgeCollection::gather(
&[FieldName::new("tags")],
EdgeShape::Sequence,
clip_key::<Db>,
clip_tags::<Db>,
),
EdgeCollection::gather(
&[FieldName::new("notes")],
EdgeShape::Set,
clip_key::<Db>,
clip_notes::<Db>,
),
];
fn addresses(ids: &[i64]) -> Result<Self::Address, CrossingError> {
Ok(SqlKeyIn::new(
["id"],
ids
.iter()
.map(|id| [ClipValue::Id(*id)])
.collect::<Vec<_>>(),
))
}
fn id(&self) -> Result<i64, CrossingError> {
Ok(self.id)
}
fn record(self) -> Result<Clip, CrossingError> {
Ok(Clip {
media: self.media,
id: self.id,
title: self.title,
score: self.score,
tags: self.tags,
notes: self.notes,
})
}
}
impl<Db> SqlOrdering<Db> for ClipRow
where
Db: Backend + sqlx::Database,
ClipFilter<Db>: ComplexComparison<Db>,
SqlKeyIn<ClipValue, Db, 1>: ComplexComparison<Db>,
ClipValue: Carrier<Db>,
TermColumns: OrderSubjects<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 Order = ClipOrder;
type Value = ClipValue;
type Subjects = TermColumns;
fn complete(written: &[ClipOrder]) -> Vec<ClipOrder> {
let mut order = written.to_vec();
for tail in [
ClipOrder::Media(OrderDirection::Asc),
ClipOrder::Id(OrderDirection::Asc),
] {
if !written
.iter()
.any(|term| core::mem::discriminant(term) == core::mem::discriminant(&tail))
{
order.push(tail);
}
}
order
}
fn subjects(_: &[ClipOrder]) -> TermColumns {
TermColumns
}
fn term(order: ClipOrder) -> OrderTerm {
match order {
ClipOrder::Media(direction) => OrderTerm::new(
TermName::new("media"),
FieldName::new("media_id"),
direction,
),
ClipOrder::Id(direction) => {
OrderTerm::new(TermName::new("id"), FieldName::new("id"), direction)
}
ClipOrder::Title(direction) => {
OrderTerm::new(TermName::new("title"), FieldName::new("title"), direction)
}
ClipOrder::Score(direction) => {
OrderTerm::nullable(TermName::new("score"), FieldName::new("score"), direction)
}
}
}
fn value(
&self,
order: ClipOrder,
_: usize,
_: &Db::Row,
_: &str,
) -> Result<Option<ClipValue>, sqlx::Error> {
Ok(match order {
ClipOrder::Media(_) => Some(ClipValue::Media(self.media)),
ClipOrder::Id(_) => Some(ClipValue::Id(self.id)),
ClipOrder::Title(_) => Some(ClipValue::Title(self.title.clone())),
ClipOrder::Score(_) => self.score.map(ClipValue::Score),
})
}
}
fn titled() -> ClipFilter<Sqlite> {
titled_as("a")
}
fn titled_as(operand: &str) -> ClipFilter<Sqlite> {
ClipFilter {
title: SqlScalarComparison::try_from_filter(
ScalarFilter::<std::string::String>::new().with_eq(operand.to_owned()),
)
.expect("a text equality crosses into SQLite"),
}
}
fn terms(written: &[ClipOrder]) -> Vec<OrderTerm> {
<ClipRow as SqlOrdering<Sqlite>>::complete(written)
.iter()
.map(|term| <ClipRow as SqlOrdering<Sqlite>>::term(*term))
.collect()
}
const SELECT: &str = "SELECT \"media_id\", \"id\", \"title\", \"score\" FROM \"clip\"";
#[test]
fn an_unordered_query_renders_no_order_by_at_all() {
let statement = scan::<ClipRow, Sqlite>(None, None, None).expect("no predicate lowers");
assert_eq!(statement.sql(), SELECT);
let filter = titled();
let filtered =
scan::<ClipRow, Sqlite>(Some(&filter), None, None).expect("a text equality lowers");
assert_eq!(filtered.sql(), format!("{SELECT} WHERE \"title\" = ?"));
}
#[test]
fn a_scope_renders_beside_the_filter_rather_than_replacing_it() {
let scope = titled_as("b");
let scoped = scan::<ClipRow, Sqlite>(None, Some(&scope), None).expect("a text equality lowers");
assert_eq!(scoped.sql(), format!("{SELECT} WHERE \"title\" = ?"));
let filter = titled();
let both =
scan::<ClipRow, Sqlite>(Some(&filter), Some(&scope), None).expect("two text equalities lower");
assert_eq!(
both.sql(),
format!("{SELECT} WHERE \"title\" = ? AND \"title\" = ?"),
"both operands reach the statement — a merge would have rendered one"
);
}
#[test]
fn a_row_ceiling_over_an_unordered_query_orders_nothing() {
let statement = scan::<ClipRow, Sqlite>(None, None, Some(10)).expect("no predicate lowers");
assert_eq!(statement.sql(), format!("{SELECT} LIMIT ?"));
let filter = titled();
let filtered =
scan::<ClipRow, Sqlite>(Some(&filter), None, Some(10)).expect("a text equality lowers");
assert_eq!(
filtered.sql(),
format!("{SELECT} WHERE \"title\" = ? LIMIT ?")
);
}
#[test]
fn a_written_order_is_completed_with_the_key() {
let terms = terms(&[ClipOrder::Title(OrderDirection::Desc)]);
let rendered = ordered::<ClipRow, Sqlite>(
None,
None,
Ordering {
order: SqlOrder::new(&terms).unwrap(),
subjects: &TermColumns,
keyset: None,
values: SortValues::Unread,
},
Walk::Forward,
None,
None,
)
.expect("an order over stored columns lowers");
assert_eq!(
rendered.sql(),
format!("{SELECT} ORDER BY \"title\" DESC, \"media_id\" ASC, \"id\" ASC")
);
assert_eq!(
<ClipRow as SqlOrdering<Sqlite>>::complete(&[ClipOrder::Id(OrderDirection::Desc)]),
[
ClipOrder::Id(OrderDirection::Desc),
ClipOrder::Media(OrderDirection::Asc)
],
"a term naming a key column moves it and does not repeat it"
);
}
#[test]
fn a_backward_walk_inverts_every_term() {
let terms = terms(&[ClipOrder::Score(OrderDirection::Asc)]);
let forward = ordered::<ClipRow, Sqlite>(
None,
None,
Ordering {
order: SqlOrder::new(&terms).unwrap(),
subjects: &TermColumns,
keyset: None,
values: SortValues::Unread,
},
Walk::Forward,
None,
None,
)
.expect("an order over stored columns lowers");
assert_eq!(
forward.sql(),
format!("{SELECT} ORDER BY \"score\" ASC, \"media_id\" ASC, \"id\" ASC")
);
let backward = ordered::<ClipRow, Sqlite>(
None,
None,
Ordering {
order: SqlOrder::new(&terms).unwrap(),
subjects: &TermColumns,
keyset: None,
values: SortValues::Unread,
},
Walk::Backward,
None,
None,
)
.expect("an order over stored columns lowers");
assert_eq!(
backward.sql(),
format!("{SELECT} ORDER BY \"score\" DESC, \"media_id\" DESC, \"id\" DESC")
);
}
#[test]
fn a_page_resumes_beside_the_filter_and_not_instead_of_it() {
let terms = terms(&[ClipOrder::Title(OrderDirection::Asc)]);
let order = SqlOrder::<Sqlite>::new(&terms).unwrap();
let cursor = Cursor::at(
&terms,
[
Some(ClipValue::Title("a".to_owned())),
Some(ClipValue::Media(1)),
Some(ClipValue::Id(2)),
],
);
let keyset = SqlKeyset::resume_with(order, &cursor, Walk::Forward, &TermColumns)
.expect("minted under this very order");
let filter = titled();
let statement = ordered::<ClipRow, Sqlite>(
Some(&filter),
None,
Ordering {
order,
subjects: &TermColumns,
keyset: Some(&keyset),
values: SortValues::Projected,
},
Walk::Forward,
Some(101),
Some(20),
)
.expect("a page over stored columns lowers");
assert_eq!(
statement.sql(),
format!(
"{SELECT} WHERE \"title\" = ? AND (\"title\" > ? OR (\"title\" = ? AND (\"media_id\" > ? OR \
(\"media_id\" = ? AND (\"id\" > ?))))) ORDER BY \"title\" ASC, \"media_id\" ASC, \"id\" ASC \
LIMIT ? OFFSET ?"
)
);
}
#[test]
fn an_address_names_the_id_column_alone() {
let statement = address::<ClipRow, Sqlite>(&[2]).expect("an address lowers");
assert_eq!(statement.sql(), format!("{SELECT} WHERE (\"id\") IN ((?))"));
let batch = address::<ClipRow, Sqlite>(&[2, 3, 5]).expect("a batch of addresses lowers");
assert_eq!(
batch.sql(),
format!("{SELECT} WHERE (\"id\") IN ((?), (?), (?))"),
"the id-gather lane is the SAME predicate at a wider `k`"
);
}
#[test]
fn a_page_size_is_clamped_to_the_framework_ceiling() {
assert_eq!(
Find::<ClipRow, Sqlite, ()>::new((), false)
.order(&[ClipOrder::Title(OrderDirection::Asc)])
.first(10)
.size(),
10
);
assert_eq!(
Find::<ClipRow, Sqlite, ()>::new((), false)
.order(&[])
.first(u32::MAX)
.size(),
MAX_PAGE_SIZE,
"the widest ask is narrowed to the cap"
);
assert_eq!(
Find::<ClipRow, Sqlite, ()>::new((), false)
.order(&[])
.last(5_000)
.size(),
MAX_PAGE_SIZE,
"and so is the backward walk's"
);
}
#[test]
fn a_default_page_asks_for_one_row_more_than_it_holds() {
let cursor = Cursor::at(
&[OrderTerm::new(
TermName::new("id"),
FieldName::new("id"),
OrderDirection::Asc,
)],
[Some(ClipValue::Id(1))],
);
let page = Find::<ClipRow, Sqlite, ()>::new((), false)
.order(&[])
.after(&cursor);
assert_eq!(page.size(), DEFAULT_PAGE_SIZE);
assert_eq!(page.window(), DEFAULT_PAGE_SIZE + 1);
}
#[test]
fn a_zero_skip_is_not_a_position() {
let zero = Position::<ClipValue>::Skip(0);
assert!(!zero.is_set());
assert_eq!(zero.offset().unwrap(), None);
let one = Position::<ClipValue>::Skip(1);
assert!(one.is_set());
assert_eq!(one.offset().unwrap(), Some(1));
assert!(!Position::<ClipValue>::Start.is_set());
}
#[test]
fn a_gather_names_the_edge_table_and_the_page_it_is_for() {
let page = [row(1, 2), row(1, 3)];
let gathers = gathers::<ClipRow, Sqlite>(&page).expect("two collections, two statements");
assert_eq!(gathers.len(), 2, "one statement per gathered collection");
assert_eq!(
gathers[0].0.sql(),
"SELECT \"media_id\", \"id\", \"tags\" AS \"__element\", \"tags_ordinal\" AS \"__ordinal\" \
FROM \"clip_tags\" WHERE (\"media_id\", \"id\") IN ((?, ?), (?, ?)) \
ORDER BY \"media_id\" ASC, \"id\" ASC, \"__ordinal\" ASC"
);
assert_eq!(
gathers[1].0.sql(),
"SELECT \"media_id\", \"id\", \"notes\" AS \"__element\" \
FROM \"clip_notes\" WHERE (\"media_id\", \"id\") IN ((?, ?), (?, ?)) \
ORDER BY \"media_id\" ASC, \"id\" ASC, \"__element\" ASC"
);
}
#[test]
fn a_gathered_collection_is_absent_from_every_page_statement() {
let scan = scan::<ClipRow, Sqlite>(None, None, None).expect("no predicate lowers");
assert_eq!(scan.sql(), SELECT);
assert!(!scan.sql().as_str().contains("tags"));
let addressed = address::<ClipRow, Sqlite>(&[2]).expect("an address lowers");
assert!(!addressed.sql().as_str().contains("tags"));
}
#[test]
fn an_empty_page_gathers_nothing() {
let empty: [ClipRow; 0] = [];
assert!(
gathers::<ClipRow, Sqlite>(&empty)
.expect("a plan over no rows lowers")
.is_empty()
);
}
fn row(media: i64, id: i64) -> ClipRow {
ClipRow {
media,
id,
title: String::new(),
score: None,
tags: Vec::new(),
notes: Vec::new(),
}
}
type CorpusRow = (i64, i64, &'static str, Option<f64>, &'static [&'static str]);
const NOTES: [(i64, i64, &[&str]); 2] = [(1, 1, &["beta-note", "alpha-note"]), (2, 5, &["solo"])];
const CORPUS: [CorpusRow; 6] = [
(1, 1, "alpha", Some(1.0), &["a", "b", "c"]),
(1, 2, "beta", None, &[]),
(1, 3, "gamma", Some(2.0), &["dup", "dup"]),
(1, 4, "delta", Some(3.0), &["z"]),
(2, 5, "epsilon", Some(4.0), &["m", "n"]),
(2, 6, "zeta", Some(5.0), &[]),
];
fn ordered_corpus() -> Vec<Clip> {
let mut clips: Vec<Clip> = CORPUS
.iter()
.map(|&(media, id, title, score, tags)| Clip {
media,
id,
title: title.to_owned(),
score,
tags: tags.iter().map(|&tag| tag.to_owned()).collect(),
notes: {
let mut notes: Vec<String> = NOTES
.iter()
.find(|&&(at_media, at_id, _)| at_media == media && at_id == id)
.map(|&(_, _, notes)| notes.iter().map(|¬e| note.to_owned()).collect())
.unwrap_or_default();
notes.sort();
notes
},
})
.collect();
clips.sort_by(|a, b| {
a.title
.cmp(&b.title)
.then(a.media.cmp(&b.media))
.then(a.id.cmp(&b.id))
});
clips
}
async fn corpus() -> sqlx::sqlite::SqliteConnection {
use sqlx::Connection as _;
let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
.await
.expect("an in-memory database");
sqlx::query(
r#"CREATE TABLE "clip" ("media_id" INTEGER, "id" INTEGER, "title" TEXT, "score" REAL,
PRIMARY KEY ("media_id", "id"), UNIQUE ("id"))"#,
)
.execute(&mut db)
.await
.expect("the row table");
sqlx::query(
r#"CREATE TABLE "clip_tags" ("media_id" INTEGER, "id" INTEGER, "tags_ordinal" INTEGER,
"tags" TEXT, PRIMARY KEY ("media_id", "id", "tags_ordinal"))"#,
)
.execute(&mut db)
.await
.expect("the sequence's edge table");
sqlx::query(
r#"CREATE TABLE "clip_notes" ("media_id" INTEGER, "id" INTEGER, "notes" TEXT,
PRIMARY KEY ("media_id", "id", "notes"))"#,
)
.execute(&mut db)
.await
.expect("the set's edge table");
for &(media, id, title, score, tags) in &CORPUS {
sqlx::query(r#"INSERT INTO "clip" VALUES (?, ?, ?, ?)"#)
.bind(media)
.bind(id)
.bind(title)
.bind(score)
.execute(&mut db)
.await
.expect("a clip");
for (ordinal, tag) in (0..tags.len()).rev().zip(tags.iter().rev()) {
sqlx::query(r#"INSERT INTO "clip_tags" VALUES (?, ?, ?, ?)"#)
.bind(media)
.bind(id)
.bind(i64::try_from(ordinal).expect("a corpus of four elements"))
.bind(*tag)
.execute(&mut db)
.await
.expect("an element");
}
}
for &(media, id, notes) in &NOTES {
for note in notes {
sqlx::query(r#"INSERT INTO "clip_notes" VALUES (?, ?, ?)"#)
.bind(media)
.bind(id)
.bind(*note)
.execute(&mut db)
.await
.expect("a member");
}
}
db
}
#[tokio::test]
async fn a_single_get_carries_the_collection_its_page_would() {
let mut db = corpus().await;
for expected in ordered_corpus() {
let got = crate::query::sql::get::<ClipRow, Sqlite, _>(&mut db, &expected.id, false)
.await
.expect("the corpus is there");
assert_eq!(got.as_ref(), Some(&expected));
assert_eq!(
got.map(|clip| clip.key()),
Some(ClipKey {
media: expected.media,
id: expected.id,
}),
"one column named the row, and the key it hands back is whole"
);
}
assert_eq!(
crate::query::sql::get::<ClipRow, Sqlite, _>(&mut db, &9, false)
.await
.expect("a miss is not an error"),
None,
"the miss stays `Ok(None)` with a collection plan on the row"
);
}
#[tokio::test]
async fn every_lane_hydrates_and_an_empty_collection_stays_empty() {
let mut db = corpus().await;
let mut scanned = Find::<ClipRow, Sqlite, _>::new(&mut db, false)
.fetch()
.await
.expect("the unordered scan");
scanned.sort_by(|a, b| {
a.title
.cmp(&b.title)
.then(a.media.cmp(&b.media))
.then(a.id.cmp(&b.id))
});
assert_eq!(scanned, ordered_corpus());
assert!(
scanned.iter().any(|clip| clip.tags.is_empty()),
"and the corpus really does hold a row with no elements"
);
assert_eq!(
scanned
.iter()
.find(|clip| clip.media == 1 && clip.id == 1)
.map(|clip| clip.notes.as_slice()),
Some(&["alpha-note".to_owned(), "beta-note".to_owned()][..]),
"the set comes back in its own value order, not the order its rows were written in"
);
let ceilinged = Find::<ClipRow, Sqlite, _>::new(&mut db, false)
.limit(2)
.fetch()
.await
.expect("the row ceiling");
assert_eq!(ceilinged.len(), 2);
let ordered = Find::<ClipRow, Sqlite, _>::new(&mut db, false)
.order(&[ClipOrder::Title(OrderDirection::Asc)])
.fetch()
.await
.expect("the ordered scan");
assert_eq!(ordered, ordered_corpus());
}
#[tokio::test]
async fn a_collection_survives_the_whole_walk_in_both_directions() {
let mut db = corpus().await;
let expected = ordered_corpus();
let order = [ClipOrder::Title(OrderDirection::Asc)];
let mut forward: Vec<Clip> = Vec::new();
let mut resume: Option<String> = None;
loop {
let page = match &resume {
None => Find::<ClipRow, Sqlite, _>::new(&mut db, false)
.order(&order)
.first(2)
.fetch()
.await
.expect("the first page"),
Some(encoded) => {
let cursor = Cursor::<ClipValue>::decode(encoded).expect("a cursor this engine minted");
Find::<ClipRow, Sqlite, _>::new(&mut db, false)
.order(&order)
.first(2)
.after(&cursor)
.fetch()
.await
.expect("the next page")
}
};
let more = page.has_next_page();
let last = page.edges().last().map(|edge| edge.cursor().encode());
forward.extend(
page
.into_edges()
.into_iter()
.map(|edge| edge.into_parts().0),
);
if !more {
break;
}
resume = last;
}
assert_eq!(forward, expected, "the forward walk is the ordered scan");
let mut backward: Vec<Clip> = Vec::new();
let mut resume: Option<String> = None;
loop {
let page = match &resume {
None => Find::<ClipRow, Sqlite, _>::new(&mut db, false)
.order(&order)
.last(2)
.fetch()
.await
.expect("the last page"),
Some(encoded) => {
let cursor = Cursor::<ClipValue>::decode(encoded).expect("a cursor this engine minted");
Find::<ClipRow, Sqlite, _>::new(&mut db, false)
.order(&order)
.last(2)
.before(&cursor)
.fetch()
.await
.expect("the page before")
}
};
let more = page.has_previous_page();
let first = page.edges().first().map(|edge| edge.cursor().encode());
let mut rows: Vec<Clip> = page
.into_edges()
.into_iter()
.map(|edge| edge.into_parts().0)
.collect();
rows.append(&mut backward);
backward = rows;
if !more {
break;
}
resume = first;
}
assert_eq!(
backward, expected,
"the backward walk comes back as the scan in display order, collections and all"
);
}
#[tokio::test]
async fn the_row_page_and_the_record_page_are_one_page() {
let mut db = corpus().await;
let order = [ClipOrder::Title(OrderDirection::Asc)];
let records = Find::<ClipRow, Sqlite, _>::new(&mut db, false)
.order(&order)
.first(3)
.fetch()
.await
.expect("the record leg");
let rows = Find::<ClipRow, Sqlite, _>::new(&mut db, false)
.order(&order)
.first(3)
.rows()
.await
.expect("the row leg");
assert!(
!records.edges().is_empty(),
"an empty page would make every equality below vacuous"
);
assert_eq!(records.edges().len(), rows.edges().len());
assert_eq!(records.has_next_page(), rows.has_next_page());
assert_eq!(records.has_previous_page(), rows.has_previous_page());
let mut materialized = false;
for (crossed, kept) in records.edges().iter().zip(rows.edges()) {
assert_eq!(crossed.cursor().encode(), kept.cursor().encode());
let crossed_here =
<ClipRow as SqlQuery<Sqlite>>::record(kept.node().clone()).expect("the row crosses");
assert_eq!(&crossed_here, crossed.node());
materialized |= !kept.node().tags.is_empty() || !kept.node().notes.is_empty();
}
assert!(
materialized,
"the collections are materialized onto the ROWS this leg hands back"
);
}
#[tokio::test]
async fn the_snapshot_wraps_the_page_and_its_gathers_alike() {
let mut db = corpus().await;
let ordered = Find::<ClipRow, Sqlite, _>::new(&mut db, true)
.order(&[ClipOrder::Title(OrderDirection::Asc)])
.fetch()
.await
.expect("the ordered scan inside a read transaction");
assert_eq!(ordered, ordered_corpus());
let paged = Find::<ClipRow, Sqlite, _>::new(&mut db, true)
.order(&[ClipOrder::Title(OrderDirection::Asc)])
.first(3)
.fetch()
.await
.expect("a page inside a read transaction");
assert_eq!(
paged
.edges()
.iter()
.map(|edge| edge.node().tags.clone())
.collect::<Vec<_>>(),
ordered_corpus()[..3]
.iter()
.map(|clip| clip.tags.clone())
.collect::<Vec<_>>()
);
}
#[cfg(feature = "postgres")]
mod aggregate {
use sqlx::Postgres;
use super::{
Clip, ClipFilter, ClipValue, ColumnName, ColumnShape, ComplexComparison, EdgeCollection,
EdgeShape, FieldName, RecordAddress, SqlKeyIn, scan,
};
use crate::query::sql::{CrossingError, SqlQuery, aggregated};
struct AggregatedRow {
media: i64,
id: i64,
title: String,
score: Option<f64>,
tags: Vec<String>,
notes: Vec<String>,
}
fn take_tags(
row: &mut AggregatedRow,
from: &sqlx::postgres::PgRow,
alias: &str,
) -> Result<(), sqlx::Error> {
row.tags = aggregated::<String, Postgres>(from, alias)?;
Ok(())
}
fn take_notes(
row: &mut AggregatedRow,
from: &sqlx::postgres::PgRow,
alias: &str,
) -> Result<(), sqlx::Error> {
row.notes = aggregated::<String, Postgres>(from, alias)?;
Ok(())
}
impl SqlQuery<Postgres> for AggregatedRow
where
ClipFilter<Postgres>: ComplexComparison<Postgres>,
{
type Record = Clip;
type Address = SqlKeyIn<ClipValue, Postgres, 1>;
const ADDRESS: RecordAddress = RecordAddress::new(
FieldName::new("clip"),
&[FieldName::new("media_id"), FieldName::new("id")],
);
const ALIASES: &'static [&'static str] = &[
"__ig_clip_0__",
"__ig_clip_1__",
"__ig_clip_2__",
"__ig_clip_3__",
"__ig_clip_4__",
"__ig_clip_5__",
"__ig_clip_6__",
"__ig_clip_7__",
];
const COLUMNS: &'static [ColumnShape] = &[
ColumnShape::Plain(ColumnName::new("media_id")),
ColumnShape::Plain(ColumnName::new("id")),
ColumnShape::Plain(ColumnName::new("title")),
ColumnShape::Plain(ColumnName::new("score")),
];
const COLLECTIONS: &'static [EdgeCollection<Self, Postgres>] = &[
EdgeCollection::aggregate(&[FieldName::new("tags")], EdgeShape::Sequence, take_tags),
EdgeCollection::aggregate(&[FieldName::new("notes")], EdgeShape::Set, take_notes),
];
fn addresses(ids: &[i64]) -> Result<Self::Address, CrossingError> {
Ok(SqlKeyIn::new(
["id"],
ids
.iter()
.map(|id| [ClipValue::Id(*id)])
.collect::<Vec<_>>(),
))
}
fn id(&self) -> Result<i64, CrossingError> {
Ok(self.id)
}
fn record(self) -> Result<Clip, CrossingError> {
Ok(Clip {
media: self.media,
id: self.id,
title: self.title,
score: self.score,
tags: self.tags,
notes: self.notes,
})
}
}
#[test]
fn every_aggregated_collection_rides_the_one_page_statement() {
let statement = scan::<AggregatedRow, Postgres>(None, None, None).expect("no predicate lowers");
assert_eq!(
statement.sql(),
"SELECT \"media_id\", \"id\", \"title\", \"score\", \
(SELECT array_agg(\"clip_tags\".\"tags\" ORDER BY \"clip_tags\".\"tags_ordinal\") \
FROM \"clip_tags\" \
WHERE \"clip_tags\".\"media_id\" = \"clip\".\"media_id\" \
AND \"clip_tags\".\"id\" = \"clip\".\"id\") AS \"__element_0\", \
(SELECT array_agg(\"clip_notes\".\"notes\" ORDER BY \"clip_notes\".\"notes\") \
FROM \"clip_notes\" \
WHERE \"clip_notes\".\"media_id\" = \"clip\".\"media_id\" \
AND \"clip_notes\".\"id\" = \"clip\".\"id\") AS \"__element_1\" \
FROM \"clip\""
);
}
}
#[cfg(feature = "mysql")]
mod mysql {
use sqlx::MySql;
use super::{ClipRow, gathers, row};
#[test]
fn both_gathers_render_in_mysqls_own_brackets() {
let page = [row(1, 2), row(1, 3)];
let gathers = gathers::<ClipRow, MySql>(&page).expect("two collections, two statements");
assert_eq!(gathers.len(), 2, "one statement per gathered collection");
assert_eq!(
gathers[0].0.sql(),
"SELECT `media_id`, `id`, `tags` AS `__element`, `tags_ordinal` AS `__ordinal` \
FROM `clip_tags` WHERE (`media_id`, `id`) IN ((?, ?), (?, ?)) \
ORDER BY `media_id` ASC, `id` ASC, `__ordinal` ASC"
);
assert_eq!(
gathers[1].0.sql(),
"SELECT `media_id`, `id`, `notes` AS `__element` \
FROM `clip_notes` WHERE (`media_id`, `id`) IN ((?, ?), (?, ?)) \
ORDER BY `media_id` ASC, `id` ASC, `__element` ASC"
);
}
#[test]
fn an_empty_page_gathers_nothing_here_either() {
let empty: [ClipRow; 0] = [];
assert!(
gathers::<ClipRow, MySql>(&empty)
.expect("a plan over no rows lowers")
.is_empty()
);
}
}
#[cfg(feature = "sqlite")]
mod nested {
use std::sync::Arc;
use sqlx::Sqlite;
use super::{Find, Ordering, SortValues, ordered};
use crate::{
Carrier, ColumnName, ColumnShape, ComplexComparison, Cursor, CursorError, CursorValue,
FieldName, Identifiable, OrderDirection, OrderTerm, Record, RecordAddress, TermName,
Transformer, Walk,
comparison::{
At, Backend,
sql::{
OrderSubjects, QuoteIdent, SqlKeyIn, SqlKeyset, SqlOrder, SubjectShape, SubjectSlot,
TermColumns, quote_ident, quote_qualified,
},
},
query::sql::{CrossingError, SqlOrdering, SqlQuery},
};
#[derive(Debug, Clone, PartialEq)]
struct Shot {
id: i64,
slate: String,
cover: Option<i64>,
hero: Option<i64>,
}
impl Identifiable for Shot {
type Id = i64;
fn id_ref(&self) -> &i64 {
&self.id
}
}
impl Transformer for Shot {
type Key = i64;
type Lineage = ();
type Record = Self;
type Graphql = ();
fn key(&self) -> i64 {
self.id
}
}
#[derive(Debug, Clone, PartialEq)]
struct ShotRow {
id: i64,
slate: String,
cover: Option<i64>,
hero: Option<i64>,
}
impl<'r, R> sqlx::FromRow<'r, R> for ShotRow
where
R: sqlx::Row,
i64: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
Option<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 {
id: row.try_get("id")?,
slate: row.try_get("slate")?,
cover: row.try_get("cover_id")?,
hero: row.try_get("hero_id")?,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum StripOrder {
Label(OrderDirection),
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum KeyframeOrder {
Title(OrderDirection),
Strip(Arc<StripOrder>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum ShotOrder {
Id(OrderDirection),
Slate(OrderDirection),
Cover(Arc<KeyframeOrder>),
Hero(Arc<KeyframeOrder>),
}
#[derive(Debug, Clone, PartialEq)]
enum ShotValue {
Id(i64),
Slate(String),
CoverTitle(String),
CoverStripLabel(String),
HeroTitle(String),
}
impl CursorValue for ShotValue {
fn write_cursor(&self, out: &mut Vec<u8>) {
match self {
Self::Id(value) => {
out.push(0);
value.write_cursor(out);
}
Self::Slate(value) => {
out.push(1);
value.write_cursor(out);
}
Self::CoverTitle(value) => {
out.push(2);
value.write_cursor(out);
}
Self::CoverStripLabel(value) => {
out.push(3);
value.write_cursor(out);
}
Self::HeroTitle(value) => {
out.push(4);
value.write_cursor(out);
}
}
}
fn read_cursor(bytes: &[u8]) -> Option<Self> {
let (tag, rest) = bytes.split_first()?;
match tag {
0 => i64::read_cursor(rest).map(Self::Id),
1 => String::read_cursor(rest).map(Self::Slate),
2 => String::read_cursor(rest).map(Self::CoverTitle),
3 => String::read_cursor(rest).map(Self::CoverStripLabel),
4 => String::read_cursor(rest).map(Self::HeroTitle),
_ => None,
}
}
}
impl<Db> Carrier<Db> for ShotValue
where
Db: sqlx::Database,
i64: Carrier<Db>,
String: Carrier<Db>,
{
fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
match self {
Self::Id(value) => value.push_bind(qb),
Self::Slate(value)
| Self::CoverTitle(value)
| Self::CoverStripLabel(value)
| Self::HeroTitle(value) => value.push_bind(qb),
}
}
}
struct ShotFilter;
impl<Db: Backend> ComplexComparison<Db> for ShotFilter {
fn conjuncts(&self) -> usize {
0
}
fn apply<'q>(
&'q self,
_: At<'_>,
builder: Db::Builder<'q>,
) -> Result<Db::Builder<'q>, Db::Error> {
Ok(builder)
}
}
impl<Db: Backend> Record<Db> for Shot {
type Row = ShotRow;
type Comparison = ShotFilter;
type OrderBy = ShotOrder;
}
#[derive(Debug, Clone, Copy)]
struct Hop {
from: &'static FieldName,
fk: &'static FieldName,
table: &'static FieldName,
id: &'static FieldName,
}
const SHOT: &FieldName = FieldName::new("shot");
const KEYFRAME: &FieldName = FieldName::new("keyframe");
const STRIP: &FieldName = FieldName::new("strip");
const ID: &FieldName = FieldName::new("id");
const VIA_COVER: Hop = Hop {
from: SHOT,
fk: FieldName::new("cover_id"),
table: KEYFRAME,
id: ID,
};
const VIA_HERO: Hop = Hop {
from: SHOT,
fk: FieldName::new("hero_id"),
table: KEYFRAME,
id: ID,
};
const VIA_STRIP: Hop = Hop {
from: KEYFRAME,
fk: FieldName::new("strip_id"),
table: STRIP,
id: ID,
};
#[derive(Debug, Clone)]
struct Nested {
hops: Vec<Hop>,
column: &'static FieldName,
}
impl Nested {
fn push_body<Db: sqlx::Database + QuoteIdent>(
&self,
qb: &mut sqlx::QueryBuilder<Db>,
hops: &[Hop],
) {
let (hop, rest) = hops
.split_first()
.expect("a nested subject is built from at least one hop");
qb.push("SELECT ");
self.push(qb, rest, hop.table);
qb.push(" FROM ");
qb.push(quote_ident::<Db>(hop.table));
qb.push(" WHERE ");
qb.push(quote_qualified::<Db>(hop.table, hop.id));
qb.push(" = ");
qb.push(quote_qualified::<Db>(hop.from, hop.fk));
}
fn push<Db: sqlx::Database + QuoteIdent>(
&self,
qb: &mut sqlx::QueryBuilder<Db>,
hops: &[Hop],
table: &FieldName,
) {
if hops.is_empty() {
qb.push(quote_qualified::<Db>(table, self.column));
return;
}
qb.push("(");
self.push_body(qb, hops);
qb.push(")");
}
}
#[derive(Debug, Clone)]
struct ShotSubjects(Vec<Option<Nested>>);
impl<Db: sqlx::Database + QuoteIdent + Backend<Buffer: core::fmt::Display>> OrderSubjects<Db>
for ShotSubjects
{
fn push_subject(
&self,
slot: SubjectSlot<'_, Db>,
at: At<'_>,
terms: &[OrderTerm],
level: usize,
) {
match &self.0[level] {
Some(nested) => slot.write(|qb| nested.push_body(qb, &nested.hops)),
None => TermColumns.push_subject(slot, at, terms, level),
}
}
fn shape(&self, terms: &[OrderTerm], level: usize) -> SubjectShape {
match &self.0[level] {
Some(_) => SubjectShape::SubSelect,
None => OrderSubjects::<Db>::shape(&TermColumns, terms, level),
}
}
}
fn nested(order: &ShotOrder) -> Option<Nested> {
let (hop, target) = match order {
ShotOrder::Id(_) | ShotOrder::Slate(_) => return None,
ShotOrder::Cover(target) => (VIA_COVER, target),
ShotOrder::Hero(target) => (VIA_HERO, target),
};
let mut nested = match &**target {
KeyframeOrder::Title(_) => Nested {
hops: Vec::new(),
column: FieldName::new("title"),
},
KeyframeOrder::Strip(strip) => match &**strip {
StripOrder::Label(_) => Nested {
hops: vec![VIA_STRIP],
column: FieldName::new("label"),
},
},
};
nested.hops.insert(0, hop);
Some(nested)
}
fn identity(order: &ShotOrder) -> (&'static TermName, OrderDirection) {
fn through(strip: &KeyframeOrder) -> (&'static str, OrderDirection) {
match strip {
KeyframeOrder::Title(direction) => ("title", *direction),
KeyframeOrder::Strip(strip) => match &**strip {
StripOrder::Label(direction) => ("strip_id.label", *direction),
},
}
}
match order {
ShotOrder::Id(direction) => (TermName::new("id"), *direction),
ShotOrder::Slate(direction) => (TermName::new("slate"), *direction),
ShotOrder::Cover(target) => match through(target) {
("title", direction) => (TermName::new("cover_id.title"), direction),
(_, direction) => (TermName::new("cover_id.strip_id.label"), direction),
},
ShotOrder::Hero(target) => match through(target) {
("title", direction) => (TermName::new("hero_id.title"), direction),
(_, direction) => (TermName::new("hero_id.strip_id.label"), direction),
},
}
}
impl<Db> SqlQuery<Db> for ShotRow
where
Db: Backend + sqlx::Database,
SqlKeyIn<ShotValue, Db, 1>: ComplexComparison<Db>,
ShotFilter: ComplexComparison<Db>,
i64: Carrier<Db>,
for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
for<'r> Option<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<ShotValue, Db, 1>;
const ADDRESS: RecordAddress = RecordAddress::new(SHOT, &[ID]);
const ALIASES: &'static [&'static str] = &[
"__ig_shot_0__",
"__ig_shot_1__",
"__ig_shot_2__",
"__ig_shot_3__",
"__ig_shot_4__",
"__ig_shot_5__",
"__ig_shot_6__",
"__ig_shot_7__",
];
const COLUMNS: &'static [ColumnShape] = &[
ColumnShape::Plain(ColumnName::of(ID)),
ColumnShape::Plain(ColumnName::new("slate")),
ColumnShape::Plain(ColumnName::new("cover_id")),
ColumnShape::Plain(ColumnName::new("hero_id")),
];
fn addresses(ids: &[i64]) -> Result<Self::Address, CrossingError> {
Ok(SqlKeyIn::new(
["id"],
ids
.iter()
.map(|id| [ShotValue::Id(*id)])
.collect::<Vec<_>>(),
))
}
fn id(&self) -> Result<i64, CrossingError> {
Ok(self.id)
}
fn record(self) -> Result<Shot, CrossingError> {
Ok(Shot {
id: self.id,
slate: self.slate,
cover: self.cover,
hero: self.hero,
})
}
}
impl<Db> SqlOrdering<Db> for ShotRow
where
Db: Backend + sqlx::Database + QuoteIdent,
SqlKeyIn<ShotValue, Db, 1>: ComplexComparison<Db>,
ShotFilter: ComplexComparison<Db>,
ShotValue: Carrier<Db>,
ShotSubjects: OrderSubjects<Db>,
i64: Carrier<Db>,
for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
for<'r> Option<i64>: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
for<'r> String: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
for<'r> Option<String>: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
type Order = ShotOrder;
type Value = ShotValue;
type Subjects = ShotSubjects;
fn complete(written: &[ShotOrder]) -> Vec<ShotOrder> {
let mut order = written.to_vec();
if !written.iter().any(|term| matches!(term, ShotOrder::Id(_))) {
order.push(ShotOrder::Id(OrderDirection::Asc));
}
order
}
fn subjects(order: &[ShotOrder]) -> ShotSubjects {
ShotSubjects(order.iter().map(nested).collect())
}
fn term(order: ShotOrder) -> OrderTerm {
let (identity, direction) = identity(&order);
match order {
ShotOrder::Id(_) => OrderTerm::new(identity, ID, direction),
ShotOrder::Slate(_) => OrderTerm::new(identity, FieldName::new("slate"), direction),
ShotOrder::Cover(_) => OrderTerm::nullable(identity, FieldName::new("cover_id"), direction),
ShotOrder::Hero(_) => OrderTerm::nullable(identity, FieldName::new("hero_id"), direction),
}
}
fn value(
&self,
order: ShotOrder,
_: usize,
raw: &Db::Row,
alias: &str,
) -> Result<Option<ShotValue>, sqlx::Error> {
let projected = |mint: fn(String) -> ShotValue| {
sqlx::Row::try_get::<Option<String>, _>(raw, alias).map(|value| value.map(mint))
};
match order {
ShotOrder::Id(_) => Ok(Some(ShotValue::Id(self.id))),
ShotOrder::Slate(_) => Ok(Some(ShotValue::Slate(self.slate.clone()))),
ShotOrder::Cover(target) => match &*target {
KeyframeOrder::Title(_) => projected(ShotValue::CoverTitle),
KeyframeOrder::Strip(_) => projected(ShotValue::CoverStripLabel),
},
ShotOrder::Hero(_) => projected(ShotValue::HeroTitle),
}
}
}
fn by_cover_title() -> [ShotOrder; 1] {
[ShotOrder::Cover(Arc::new(KeyframeOrder::Title(
OrderDirection::Asc,
)))]
}
fn by_hero_title() -> [ShotOrder; 1] {
[ShotOrder::Hero(Arc::new(KeyframeOrder::Title(
OrderDirection::Asc,
)))]
}
fn by_cover_strip_label() -> [ShotOrder; 1] {
[ShotOrder::Cover(Arc::new(KeyframeOrder::Strip(Arc::new(
StripOrder::Label(OrderDirection::Asc),
))))]
}
fn terms(written: &[ShotOrder]) -> Vec<OrderTerm> {
<ShotRow as SqlOrdering<Sqlite>>::complete(written)
.iter()
.map(|term| <ShotRow as SqlOrdering<Sqlite>>::term(term.clone()))
.collect()
}
fn subjects(written: &[ShotOrder]) -> ShotSubjects {
<ShotRow as SqlOrdering<Sqlite>>::subjects(&<ShotRow as SqlOrdering<Sqlite>>::complete(written))
}
const COVER_TITLE: &str = "(SELECT \"keyframe\".\"title\" FROM \"keyframe\" \
WHERE \"keyframe\".\"id\" = \"shot\".\"cover_id\")";
const COVER_STRIP_LABEL: &str = "(SELECT (SELECT \"strip\".\"label\" FROM \"strip\" WHERE \"strip\".\"id\" = \
\"keyframe\".\"strip_id\") FROM \"keyframe\" \
WHERE \"keyframe\".\"id\" = \"shot\".\"cover_id\")";
fn page(written: &[ShotOrder], cursor: &Cursor<ShotValue>) -> String {
let terms = terms(written);
let subjects = subjects(written);
let order = SqlOrder::<Sqlite>::new(&terms).expect("a renderable order");
let keyset = SqlKeyset::resume_with(order, cursor, Walk::Forward, &subjects)
.expect("minted under this very order");
ordered::<ShotRow, Sqlite>(
None,
None,
Ordering {
order,
subjects: &subjects,
keyset: Some(&keyset),
values: SortValues::Projected,
},
Walk::Forward,
Some(3),
None,
)
.expect("a nested page lowers")
.into_string()
}
#[test]
fn a_nested_page_renders_one_subject_in_three_positions() {
let cursor = Cursor::at(
&terms(&by_cover_title()),
[
Some(ShotValue::CoverTitle("Autumn".to_owned())),
Some(ShotValue::Id(1)),
],
);
assert_eq!(
page(&by_cover_title(), &cursor),
format!(
"SELECT \"id\", \"slate\", \"cover_id\", \"hero_id\", {COVER_TITLE} AS \"__ig_ord0__\" \
FROM \"shot\" \
WHERE ({COVER_TITLE} > ? OR ({COVER_TITLE} = ? AND (\"id\" > ?))) \
ORDER BY {COVER_TITLE} ASC, \"id\" ASC LIMIT ?"
)
);
}
#[test]
fn a_refs_ref_nests_one_subquery_inside_the_other() {
let cursor = Cursor::at(
&terms(&by_cover_strip_label()),
[
Some(ShotValue::CoverStripLabel("inner".to_owned())),
Some(ShotValue::Id(1)),
],
);
assert_eq!(
page(&by_cover_strip_label(), &cursor),
format!(
"SELECT \"id\", \"slate\", \"cover_id\", \"hero_id\", \
{COVER_STRIP_LABEL} AS \"__ig_ord0__\" FROM \"shot\" \
WHERE ({COVER_STRIP_LABEL} > ? OR ({COVER_STRIP_LABEL} = ? AND (\"id\" > ?))) \
ORDER BY {COVER_STRIP_LABEL} ASC, \"id\" ASC LIMIT ?"
)
);
}
#[test]
fn an_ordered_scan_orders_by_the_subquery_and_projects_none_of_it() {
let written = by_cover_title();
let terms = terms(&written);
let subjects = subjects(&written);
let order = SqlOrder::<Sqlite>::new(&terms).expect("a renderable order");
let statement = ordered::<ShotRow, Sqlite>(
None,
None,
Ordering {
order,
subjects: &subjects,
keyset: None,
values: SortValues::Unread,
},
Walk::Forward,
None,
None,
)
.expect("a nested order lowers");
assert_eq!(
statement.into_string(),
format!(
"SELECT \"id\", \"slate\", \"cover_id\", \"hero_id\" FROM \"shot\" \
ORDER BY {COVER_TITLE} ASC, \"id\" ASC"
)
);
}
#[test]
fn a_mixed_order_defers_its_plain_levels_and_aliases_by_position() {
let written = [
ShotOrder::Slate(OrderDirection::Asc),
ShotOrder::Cover(Arc::new(KeyframeOrder::Title(OrderDirection::Asc))),
];
let cursor = Cursor::at(
&terms(&written),
[
Some(ShotValue::Slate("alpha".to_owned())),
Some(ShotValue::CoverTitle("Autumn".to_owned())),
Some(ShotValue::Id(1)),
],
);
assert_eq!(
page(&written, &cursor),
format!(
"SELECT \"id\", \"slate\", \"cover_id\", \"hero_id\", {COVER_TITLE} AS \"__ig_ord1__\" \
FROM \"shot\" \
WHERE (\"slate\" > ? OR (\"slate\" = ? AND ({COVER_TITLE} > ? \
OR ({COVER_TITLE} = ? AND (\"id\" > ?))))) \
ORDER BY \"slate\" ASC, {COVER_TITLE} ASC, \"id\" ASC LIMIT ?"
)
);
}
#[test]
fn a_cursor_through_one_ref_is_refused_by_a_walk_through_the_other() {
let cover = terms(&by_cover_title());
let hero = terms(&by_hero_title());
assert_ne!(
crate::OrderSignature::of(&cover),
crate::OrderSignature::of(&hero),
"one target reached through two refs is two orders"
);
let cursor = Cursor::at(
&cover,
[
Some(ShotValue::CoverTitle("Autumn".to_owned())),
Some(ShotValue::Id(1)),
],
);
let subjects = subjects(&by_hero_title());
let order = SqlOrder::<Sqlite>::new(&hero).expect("a renderable order");
assert!(matches!(
SqlKeyset::resume_with(order, &cursor, Walk::Forward, &subjects),
Err(CursorError::Order { .. })
));
}
async fn corpus() -> sqlx::sqlite::SqliteConnection {
use sqlx::Connection as _;
let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
.await
.expect("an in-memory database");
for ddl in [
r#"CREATE TABLE "strip" ("id" INTEGER PRIMARY KEY, "label" TEXT NOT NULL)"#,
r#"CREATE TABLE "keyframe" ("id" INTEGER PRIMARY KEY, "title" TEXT NOT NULL,
"strip_id" INTEGER)"#,
r#"CREATE TABLE "shot" ("id" INTEGER PRIMARY KEY, "slate" TEXT NOT NULL,
"cover_id" INTEGER, "hero_id" INTEGER)"#,
] {
sqlx::query(ddl).execute(&mut db).await.expect("a table");
}
for (id, label) in [(20i64, "inner"), (21, "outer")] {
sqlx::query(r#"INSERT INTO "strip" VALUES (?, ?)"#)
.bind(id)
.bind(label)
.execute(&mut db)
.await
.expect("a strip");
}
for (id, title, strip) in [
(10i64, "Autumn", 20i64),
(11, "Meadow", 21),
(12, "Zebra", 20),
] {
sqlx::query(r#"INSERT INTO "keyframe" VALUES (?, ?, ?)"#)
.bind(id)
.bind(title)
.bind(strip)
.execute(&mut db)
.await
.expect("a keyframe");
}
for (id, slate, cover, hero) in [
(1i64, "alpha", Some(10i64), Some(11i64)),
(2, "bravo", Some(11), Some(10)),
(3, "delta", None, None),
(4, "echo", Some(12), Some(12)),
] {
sqlx::query(r#"INSERT INTO "shot" VALUES (?, ?, ?, ?)"#)
.bind(id)
.bind(slate)
.bind(cover)
.bind(hero)
.execute(&mut db)
.await
.expect("a shot");
}
db
}
async fn walk(
db: &mut sqlx::sqlite::SqliteConnection,
written: &[ShotOrder],
size: u32,
) -> Vec<i64> {
let mut ids = Vec::new();
let mut resume: Option<String> = None;
loop {
let page = match &resume {
None => Find::<ShotRow, Sqlite, _>::new(&mut *db, false)
.order(written)
.first(size)
.fetch()
.await
.expect("the first page"),
Some(encoded) => {
let cursor = Cursor::<ShotValue>::decode(encoded).expect("a cursor this engine minted");
Find::<ShotRow, Sqlite, _>::new(&mut *db, false)
.order(written)
.first(size)
.after(&cursor)
.fetch()
.await
.expect("the next page")
}
};
let more = page.has_next_page();
let last = page.edges().last().map(|edge| edge.cursor().encode());
ids.extend(
page
.into_edges()
.into_iter()
.map(|edge| edge.into_parts().0.id),
);
if !more {
break;
}
resume = last;
}
ids
}
#[tokio::test]
async fn a_nested_order_pages_exactly_and_puts_a_missing_target_below_everything() {
let mut db = corpus().await;
for size in [1, 2, 3, 9] {
assert_eq!(
walk(&mut db, &by_cover_title(), size).await,
[3, 1, 2, 4],
"by cover.title, {size} at a time — the shot with no cover first"
);
assert_eq!(
walk(&mut db, &by_hero_title(), size).await,
[3, 2, 1, 4],
"by hero.title, {size} at a time — the same targets, the other ref, another order"
);
assert_eq!(
walk(&mut db, &by_cover_strip_label(), size).await,
[3, 1, 4, 2],
"by cover.strip.label, {size} at a time — two hops, ties broken by the id tail"
);
assert_eq!(
walk(
&mut db,
&[
ShotOrder::Slate(OrderDirection::Asc),
ShotOrder::Cover(Arc::new(KeyframeOrder::Title(OrderDirection::Asc))),
],
size
)
.await,
[1, 2, 3, 4],
"and a MIXED order pages exactly too, {size} at a time — one column term, one nested"
);
}
}
#[tokio::test]
async fn a_rename_between_pages_cannot_drop_a_row_from_a_frozen_boundary() {
let mut db = corpus().await;
let written = by_cover_title();
let first = Find::<ShotRow, Sqlite, _>::new(&mut db, false)
.order(&written)
.first(2)
.fetch()
.await
.expect("the first page");
let ids: Vec<i64> = first.edges().iter().map(|edge| edge.node().id).collect();
assert_eq!(ids, [3, 1]);
let boundary = first
.edges()
.last()
.expect("a page of two")
.cursor()
.encode();
sqlx::query(r#"UPDATE "keyframe" SET "title" = 'Zebra' WHERE "id" = 10"#)
.execute(&mut db)
.await
.expect("the rename");
let frozen = Cursor::<ShotValue>::decode(&boundary).expect("a cursor this engine minted");
let resumed = Find::<ShotRow, Sqlite, _>::new(&mut db, false)
.order(&written)
.first(2)
.after(&frozen)
.fetch()
.await
.expect("the page after");
assert_eq!(
resumed
.edges()
.iter()
.map(|edge| edge.node().id)
.collect::<Vec<_>>(),
[2, 1],
"the boundary is where the page stopped, so `bravo` is still after it"
);
let terms = terms(&written);
let rederived = Cursor::at(
&terms,
[
Some(ShotValue::CoverTitle("Zebra".to_owned())),
Some(ShotValue::Id(1)),
],
);
let drifted = Find::<ShotRow, Sqlite, _>::new(&mut db, false)
.order(&written)
.first(2)
.after(&rederived)
.fetch()
.await
.expect("the page after the drifted boundary");
assert_eq!(
drifted
.edges()
.iter()
.map(|edge| edge.node().id)
.collect::<Vec<_>>(),
[4],
"`bravo` is gone — one row lost, no error anywhere, which is why the boundary freezes"
);
}
}
#[cfg(feature = "mongo")]
#[test]
fn a_sort_alias_is_one_spelling_across_the_two_families() {
for level in [0, 1, 7, 42] {
let sql = super::sort_alias(level);
assert_eq!(sql.as_str(), crate::query::mongo::sort_alias(level));
let body = sql
.as_str()
.strip_prefix("__ig_")
.and_then(|body| body.strip_suffix("__"))
.expect("a minted word wears the prefix and the terminator");
assert!(
!body.contains('_'),
"`{sql}` has a body a `<table>_<depth>` split could reach"
);
}
}