#![cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
use super::{
EdgeWrite, SideWrite, SqlWrite, Upsert, delete_statements, insert_statement, statements,
upsert_statement,
};
use crate::{
Carrier, ColumnName, ColumnShape, ComplexComparison, FieldName, Identifiable, Record,
RecordAddress, Transformer,
comparison::{Backend, sql::SqlKeyIn},
query::sql::{
CrossingError, ELEMENT, EdgeCollection, EdgeShape, SqlDialect, SqlQuery, distribute,
},
};
#[derive(Debug, Clone, PartialEq, Eq)]
struct Clip {
media: i64,
id: i64,
title: String,
bit_rate: u64,
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, Eq)]
struct ClipRow {
media: i64,
id: i64,
title: String,
bit_rate: i64,
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>,
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")?,
bit_rate: row.try_get("bit_rate")?,
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,
)
}
fn tags_len(row: &ClipRow) -> usize {
row.tags.len()
}
fn tags_element<Db>(row: &ClipRow, at: usize, qb: &mut sqlx::QueryBuilder<Db>)
where
Db: sqlx::Database,
String: Carrier<Db>,
{
row.tags[at].push_bind(qb);
}
fn notes_len(row: &ClipRow) -> usize {
row.notes.len()
}
fn notes_element<Db>(row: &ClipRow, at: usize, qb: &mut sqlx::QueryBuilder<Db>)
where
Db: sqlx::Database,
String: Carrier<Db>,
{
row.notes[at].push_bind(qb);
}
impl<Db> Record<Db> for Clip
where
Db: Backend,
{
type Row = ClipRow;
type Comparison = SqlKeyIn<i64, Db, 1>;
type OrderBy = ();
}
impl<Db> SqlQuery<Db> for ClipRow
where
Db: Backend + sqlx::Database,
SqlKeyIn<i64, 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<i64, 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("bit_rate")),
];
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| [*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,
bit_rate: u64::try_from(self.bit_rate)?,
tags: self.tags,
notes: self.notes,
})
}
}
impl<Db> SqlWrite<Db> for ClipRow
where
Db: Backend + sqlx::Database,
SqlKeyIn<i64, Db, 1>: ComplexComparison<Db>,
i64: Carrier<Db>,
String: 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>,
{
const EDGES: &'static [EdgeWrite<Self, Db>] = &[
EdgeWrite::new(
&[FieldName::new("tags")],
EdgeShape::Sequence,
tags_len,
tags_element::<Db>,
),
EdgeWrite::new(
&[FieldName::new("notes")],
EdgeShape::Set,
notes_len,
notes_element::<Db>,
),
];
fn row(record: Clip) -> Result<Self, CrossingError> {
Ok(Self {
media: record.media,
id: record.id,
title: record.title,
bit_rate: i64::try_from(record.bit_rate)?,
tags: record.tags,
notes: record.notes,
})
}
fn bind(&self, at: usize, qb: &mut sqlx::QueryBuilder<Db>) {
match at {
0 => self.media.push_bind(qb),
1 => self.id.push_bind(qb),
2 => self.title.push_bind(qb),
_ => self.bit_rate.push_bind(qb),
}
}
fn bind_address(&self, at: usize, qb: &mut sqlx::QueryBuilder<Db>) {
match at {
0 => self.media.push_bind(qb),
_ => self.id.push_bind(qb),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Caption {
id: i64,
from: CaptionSource,
text: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum CaptionSource {
Frame { media: i64, frame: i64 },
Turn { turn: i64 },
}
impl CaptionSource {
const fn word(&self) -> &'static str {
match self {
Self::Frame { .. } => "Frame",
Self::Turn { .. } => "Turn",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct CaptionKey {
from: CaptionSource,
id: i64,
}
impl Identifiable for Caption {
type Id = i64;
fn id_ref(&self) -> &i64 {
&self.id
}
}
impl Transformer for Caption {
type Key = CaptionKey;
type Lineage = CaptionSource;
type Record = Self;
type Graphql = ();
fn key(&self) -> CaptionKey {
CaptionKey {
from: self.from.clone(),
id: self.id,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct CaptionRow {
id: i64,
from: CaptionSource,
text: String,
}
fn caption_frame<Db>(row: &CaptionRow, at: usize, qb: &mut sqlx::QueryBuilder<Db>)
where
Db: sqlx::Database,
i64: Carrier<Db>,
{
let CaptionSource::Frame { media, frame } = &row.from else {
panic!("this plan is reached through `side`, which selects it by the row's own variant")
};
match at {
0 => media.push_bind(qb),
_ => frame.push_bind(qb),
}
}
fn caption_turn<Db>(row: &CaptionRow, _at: usize, qb: &mut sqlx::QueryBuilder<Db>)
where
Db: sqlx::Database,
i64: Carrier<Db>,
{
let CaptionSource::Turn { turn } = &row.from else {
panic!("this plan is reached through `side`, which selects it by the row's own variant")
};
turn.push_bind(qb);
}
impl<Db> Record<Db> for Caption
where
Db: Backend,
{
type Row = CaptionRow;
type Comparison = SqlKeyIn<i64, Db, 1>;
type OrderBy = ();
}
impl<Db> SqlQuery<Db> for CaptionRow
where
Db: Backend + sqlx::Database,
SqlKeyIn<i64, Db, 1>: ComplexComparison<Db>,
i64: Carrier<Db>,
{
type Record = Caption;
type Address = SqlKeyIn<i64, Db, 1>;
const ADDRESS: RecordAddress =
RecordAddress::new(FieldName::new("caption"), &[FieldName::new("id")]);
const ALIASES: &'static [&'static str] = &[
"__ig_caption_0__",
"__ig_caption_1__",
"__ig_caption_2__",
"__ig_caption_3__",
"__ig_caption_4__",
"__ig_caption_5__",
"__ig_caption_6__",
"__ig_caption_7__",
];
const COLUMNS: &'static [ColumnShape] = &[
ColumnShape::Plain(ColumnName::new("id")),
ColumnShape::Plain(ColumnName::new("__ig_source__")),
ColumnShape::Plain(ColumnName::new("text")),
];
fn addresses(ids: &[i64]) -> Result<Self::Address, CrossingError> {
Ok(SqlKeyIn::new(
["id"],
ids.iter().map(|id| [*id]).collect::<Vec<_>>(),
))
}
fn id(&self) -> Result<i64, CrossingError> {
Ok(self.id)
}
fn record(self) -> Result<Caption, CrossingError> {
Ok(Caption {
id: self.id,
from: self.from,
text: self.text,
})
}
}
impl<Db> SqlWrite<Db> for CaptionRow
where
Db: Backend + sqlx::Database,
SqlKeyIn<i64, Db, 1>: ComplexComparison<Db>,
i64: Carrier<Db>,
String: Carrier<Db>,
{
const SIDES: &'static [SideWrite<Self, Db>] = &[
SideWrite::new(
FieldName::new("caption_frame"),
&[FieldName::new("media_id"), FieldName::new("frame")],
caption_frame::<Db>,
),
SideWrite::new(
FieldName::new("caption_turn"),
&[FieldName::new("turn")],
caption_turn::<Db>,
),
];
fn side(&self) -> Option<&'static SideWrite<Self, Db>> {
Some(match self.from {
CaptionSource::Frame { .. } => &Self::SIDES[0],
CaptionSource::Turn { .. } => &Self::SIDES[1],
})
}
fn row(record: Caption) -> Result<Self, CrossingError> {
Ok(Self {
id: record.id,
from: record.from,
text: record.text,
})
}
fn bind(&self, at: usize, qb: &mut sqlx::QueryBuilder<Db>) {
match at {
0 => self.id.push_bind(qb),
1 => self.from.word().to_owned().push_bind(qb),
_ => self.text.push_bind(qb),
}
}
fn bind_address(&self, _at: usize, qb: &mut sqlx::QueryBuilder<Db>) {
self.id.push_bind(qb);
}
}
#[cfg(feature = "sqlite")]
impl crate::Describe<sqlx::Sqlite> for Caption {
const BLUEPRINT: crate::Table = crate::Table::new(
<CaptionRow as SqlQuery<sqlx::Sqlite>>::ADDRESS,
&[
crate::Column::new(FieldName::new("id"), "INTEGER", false),
crate::Column::new(
FieldName::new("__ig_source__"),
<sqlx::Sqlite as crate::query::sql::AsyncSchemaDialect>::DISCRIMINANT,
false,
),
crate::Column::new(FieldName::new("text"), "TEXT", false),
],
)
.with_provenance(
FieldName::new("__ig_source__"),
&[
crate::SideTable::new(
FieldName::new("caption_frame"),
&[
crate::Column::new(FieldName::new("media_id"), "INTEGER", false),
crate::Column::new(FieldName::new("frame"), "INTEGER", false),
],
),
crate::SideTable::new(
FieldName::new("caption_turn"),
&[crate::Column::new(FieldName::new("turn"), "INTEGER", false)],
),
],
);
}
#[cfg(feature = "sqlite")]
const _: () = assert!(crate::describes(
&<Caption as crate::Describe<sqlx::Sqlite>>::BLUEPRINT,
<CaptionRow as SqlQuery<sqlx::Sqlite>>::COLUMNS
));
#[cfg(feature = "sqlite")]
impl crate::Describe<sqlx::Sqlite> for Clip {
const BLUEPRINT: crate::Table = crate::Table::new(
<ClipRow as SqlQuery<sqlx::Sqlite>>::ADDRESS,
&[
crate::Column::new(FieldName::new("media_id"), "INTEGER", false),
crate::Column::new(FieldName::new("id"), "INTEGER", false),
crate::Column::new(FieldName::new("title"), "TEXT", false),
crate::Column::new(FieldName::new("bit_rate"), "INTEGER", false),
],
)
.with_edges(&[
crate::EdgeTable::new(&[FieldName::new("tags")], EdgeShape::Sequence, "TEXT"),
crate::EdgeTable::new(&[FieldName::new("notes")], EdgeShape::Set, "TEXT"),
]);
}
#[cfg(feature = "sqlite")]
const _: () = assert!(crate::describes(
&<Clip as crate::Describe<sqlx::Sqlite>>::BLUEPRINT,
<ClipRow as SqlQuery<sqlx::Sqlite>>::COLUMNS
));
fn clip(tags: &[&str], notes: &[&str]) -> Clip {
Clip {
media: 1,
id: 7,
title: "alpha".to_owned(),
bit_rate: 320,
tags: tags.iter().map(|tag| (*tag).to_owned()).collect(),
notes: notes.iter().map(|note| (*note).to_owned()).collect(),
}
}
fn caption(from: CaptionSource) -> Caption {
Caption {
id: 7,
from,
text: "hello".to_owned(),
}
}
fn caption_row<Db>(from: CaptionSource) -> CaptionRow
where
CaptionRow: SqlWrite<Db, Record = Caption>,
Db: Backend + sqlx::Database,
{
<CaptionRow as SqlWrite<Db>>::row(caption(from)).expect("this crossing refuses nothing")
}
fn row<Db>(tags: &[&str], notes: &[&str]) -> ClipRow
where
ClipRow: SqlWrite<Db, Record = Clip>,
Db: Backend + sqlx::Database,
{
<ClipRow as SqlWrite<Db>>::row(clip(tags, notes)).expect("a bit rate of 320 is inside `i64`")
}
fn rendered<Row, Db>(row: &Row, replace: bool) -> Vec<(String, usize)>
where
Row: SqlWrite<Db>,
Db: SqlDialect + Upsert,
i64: Carrier<Db>,
<Db as sqlx::Database>::Arguments: sqlx::IntoArguments<Db>,
{
let parent = if replace {
upsert_statement::<Row, Db>(row)
} else {
insert_statement::<Row, Db>(row)
};
statements::<Row, Db>(row, parent, replace)
.expect("the fixture's collections are inside every ceiling")
.into_iter()
.map(|mut statement| {
use sqlx::Execute as _;
let mut built = statement.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)
})
.collect()
}
fn removed<Row, Db, P>(filter: &P) -> Vec<(String, usize)>
where
Row: SqlWrite<Db>,
Db: SqlDialect,
P: ComplexComparison<Db>,
<Db as sqlx::Database>::Arguments: sqlx::IntoArguments<Db>,
{
delete_statements::<Row, Db, P>(filter)
.expect("the fixture's filter names a row")
.into_iter()
.map(|mut statement| {
use sqlx::Execute as _;
let mut built = statement.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)
})
.collect()
}
fn matching<Db: Backend>(column: &'static str, values: &[i64]) -> SqlKeyIn<i64, Db, 1> {
SqlKeyIn::new(
[column],
values.iter().map(|value| [*value]).collect::<Vec<_>>(),
)
}
struct Overcounting;
impl<Db: Backend> ComplexComparison<Db> for Overcounting {
fn conjuncts(&self) -> usize {
1
}
fn apply<'q>(
&'q self,
_at: crate::At<'_>,
builder: Db::Builder<'q>,
) -> Result<Db::Builder<'q>, Db::Error> {
Ok(builder)
}
}
mod composite;
mod flattened;
#[cfg(feature = "sqlite")]
mod sqlite {
use sqlx::Sqlite;
use super::{
CaptionRow, CaptionSource, ClipRow, caption_row, clip, delete_statements, matching, removed,
rendered, row,
};
use crate::{
comparison::sql::{BindCeiling, SqlKeyIn, SqlLoweringError},
query::sql::{SqlQuery, SqlWrite, SqlWriteError},
};
#[test]
fn an_insert_names_every_column_and_binds_one_value_row() {
assert_eq!(
rendered::<ClipRow, Sqlite>(&row::<Sqlite>(&[], &[]), false),
[(
"INSERT INTO \"clip\" (\"media_id\", \"id\", \"title\", \"bit_rate\") VALUES (?, ?, ?, ?)"
.to_owned(),
4
)],
"a record whose collections are empty is one statement"
);
}
#[test]
fn an_upsert_replaces_on_the_address_and_assigns_every_column() {
assert_eq!(
rendered::<ClipRow, Sqlite>(&row::<Sqlite>(&[], &[]), true)[0],
(
"INSERT INTO \"clip\" (\"media_id\", \"id\", \"title\", \"bit_rate\") VALUES (?, ?, ?, ?) \
ON CONFLICT (\"media_id\", \"id\") DO UPDATE SET \"media_id\" = \"excluded\".\"media_id\", \
\"id\" = \"excluded\".\"id\", \"title\" = \"excluded\".\"title\", \
\"bit_rate\" = \"excluded\".\"bit_rate\""
.to_owned(),
4
),
"the conflict target is the address and the assignment list is the row"
);
}
#[test]
fn a_sequence_writes_its_ordinal_and_a_set_writes_none() {
let statements = rendered::<ClipRow, Sqlite>(&row::<Sqlite>(&["a", "b"], &["n"]), false);
assert_eq!(
statements.len(),
3,
"the parent, then one insert per collection"
);
assert_eq!(
statements[1],
(
"INSERT INTO \"clip_tags\" (\"media_id\", \"id\", \"tags_ordinal\", \"tags\") \
VALUES (?, ?, ?, ?), (?, ?, ?, ?)"
.to_owned(),
8
),
"two elements, four binds each: the key twice over, the ordinal and the value"
);
assert_eq!(
statements[2],
(
"INSERT INTO \"clip_notes\" (\"media_id\", \"id\", \"notes\") VALUES (?, ?, ?)".to_owned(),
3
),
"a set's edge table has no ordinal column, so none is named and none is bound"
);
}
#[test]
fn a_replacement_deletes_the_parents_edge_rows_before_it_writes_them() {
let statements = rendered::<ClipRow, Sqlite>(&row::<Sqlite>(&["a"], &["n"]), true);
assert_eq!(
statements.len(),
5,
"the parent, then a delete and an insert per collection"
);
assert_eq!(
statements[1],
(
"DELETE FROM \"clip_tags\" WHERE \"media_id\" = ? AND \"id\" = ?".to_owned(),
2
)
);
assert_eq!(
statements[3],
(
"DELETE FROM \"clip_notes\" WHERE \"media_id\" = ? AND \"id\" = ?".to_owned(),
2
)
);
}
#[test]
fn an_empty_collection_writes_no_edge_row_and_still_clears_the_old_ones() {
assert_eq!(
rendered::<ClipRow, Sqlite>(&row::<Sqlite>(&[], &["n"]), false).len(),
2,
"the parent and the set — an empty sequence renders nothing"
);
let replaced = rendered::<ClipRow, Sqlite>(&row::<Sqlite>(&[], &["n"]), true);
assert_eq!(replaced.len(), 4, "both deletes run, one insert does not");
assert_eq!(
replaced[1].0, "DELETE FROM \"clip_tags\" WHERE \"media_id\" = ? AND \"id\" = ?",
"an emptied collection is cleared rather than left alone"
);
}
#[test]
fn a_collection_past_the_bind_ceiling_is_refused_rather_than_split() {
let elements = <Sqlite as BindCeiling>::MAX_BIND_PARAMETERS / 4 + 1;
let mut wide = row::<Sqlite>(&[], &[]);
wide.tags = (0..elements).map(|at| at.to_string()).collect();
let parent = super::insert_statement::<ClipRow, Sqlite>(&wide);
let refused = super::statements::<ClipRow, Sqlite>(&wide, parent, false);
let Err(SqlWriteError::Lowering(SqlLoweringError::BindCeiling(why))) = refused else {
panic!("a collection past the ceiling is refused rather than chunked");
};
assert_eq!(why.keys(), elements);
assert_eq!(
why.columns(),
4,
"the key's two columns, the ordinal and the value"
);
assert_eq!(why.ceiling(), <Sqlite as BindCeiling>::MAX_BIND_PARAMETERS);
}
#[test]
fn a_record_that_will_not_cross_renders_nothing() {
let mut record = clip(&[], &[]);
record.bit_rate = u64::MAX;
assert!(
<ClipRow as SqlWrite<Sqlite>>::row(record).is_err(),
"a bit rate past `i64::MAX` is not this row's column"
);
}
#[test]
fn the_write_names_the_same_columns_the_read_selects() {
let bound = <ClipRow as SqlQuery<Sqlite>>::COLUMNS.len();
assert_eq!(
rendered::<ClipRow, Sqlite>(&row::<Sqlite>(&["a"], &["n"]), false)[0].1,
bound
);
assert_eq!(
<ClipRow as SqlWrite<Sqlite>>::EDGES.len(),
<ClipRow as SqlQuery<Sqlite>>::COLLECTIONS.len(),
"one write plan entry per collection the read plan materializes"
);
}
#[test]
fn a_fan_in_writes_the_common_row_and_the_one_provenance_row() {
assert_eq!(
rendered::<CaptionRow, Sqlite>(
&caption_row::<Sqlite>(CaptionSource::Frame { media: 1, frame: 5 }),
false
),
[
(
"INSERT INTO \"caption\" (\"id\", \"__ig_source__\", \"text\") VALUES (?, ?, ?)"
.to_owned(),
3
),
(
"INSERT INTO \"caption_frame\" (\"id\", \"media_id\", \"frame\") VALUES (?, ?, ?)"
.to_owned(),
3
),
],
"the id leads the provenance row, then that variant's ancestors"
);
}
#[test]
fn the_other_upstream_renders_its_own_table_at_its_own_width() {
assert_eq!(
rendered::<CaptionRow, Sqlite>(
&caption_row::<Sqlite>(CaptionSource::Turn { turn: 9 }),
false
)[1],
(
"INSERT INTO \"caption_turn\" (\"id\", \"turn\") VALUES (?, ?)".to_owned(),
2
)
);
}
#[test]
fn a_replacement_clears_every_provenance_table_before_it_writes_one() {
let statements = rendered::<CaptionRow, Sqlite>(
&caption_row::<Sqlite>(CaptionSource::Turn { turn: 9 }),
true,
);
assert_eq!(
statements.len(),
4,
"the common row, a delete per upstream, and the one insert"
);
assert_eq!(
statements[1],
(
"DELETE FROM \"caption_frame\" WHERE \"id\" = ?".to_owned(),
1
),
"the upstream this row did NOT come from is cleared too"
);
assert_eq!(
statements[2],
(
"DELETE FROM \"caption_turn\" WHERE \"id\" = ?".to_owned(),
1
),
"and so is the one it did, which is what makes the insert after it a replacement"
);
}
#[test]
fn a_record_whose_ancestry_is_its_own_columns_writes_no_provenance_row() {
assert!(<ClipRow as SqlWrite<Sqlite>>::SIDES.is_empty());
assert!(<ClipRow as SqlWrite<Sqlite>>::side(&row::<Sqlite>(&[], &[])).is_none());
}
#[test]
fn a_removal_clears_every_collection_before_it_removes_the_rows() {
assert_eq!(
removed::<ClipRow, Sqlite, _>(&matching::<Sqlite>("id", &[7])),
[
(
"DELETE FROM \"clip_tags\" WHERE \"id\" IN (SELECT \"id\" FROM \"clip\" \
WHERE (\"id\") IN ((?)))"
.to_owned(),
1
),
(
"DELETE FROM \"clip_notes\" WHERE \"id\" IN (SELECT \"id\" FROM \"clip\" \
WHERE (\"id\") IN ((?)))"
.to_owned(),
1
),
("DELETE FROM \"clip\" WHERE (\"id\") IN ((?))".to_owned(), 1),
],
"the collections lead, the rows follow, and the predicate is the same one throughout"
);
}
#[test]
fn the_cascade_correlates_on_the_id_where_the_edge_rows_carry_the_whole_key() {
let keys = <ClipRow as SqlQuery<Sqlite>>::ADDRESS.keys();
assert_eq!(keys.len(), 2, "the fixture's key is compound");
let statements = removed::<ClipRow, Sqlite, _>(&matching::<Sqlite>("id", &[7]));
assert!(
!statements[0].0.contains("media_id"),
"the first key column has no part in the correlation: {}",
statements[0].0
);
}
#[test]
fn a_removal_clears_every_provenance_table() {
assert_eq!(
removed::<CaptionRow, Sqlite, _>(&matching::<Sqlite>("id", &[3])),
[
(
"DELETE FROM \"caption_frame\" WHERE \"id\" IN (SELECT \"id\" FROM \"caption\" \
WHERE (\"id\") IN ((?)))"
.to_owned(),
1
),
(
"DELETE FROM \"caption_turn\" WHERE \"id\" IN (SELECT \"id\" FROM \"caption\" \
WHERE (\"id\") IN ((?)))"
.to_owned(),
1
),
(
"DELETE FROM \"caption\" WHERE (\"id\") IN ((?))".to_owned(),
1
),
],
"one delete per upstream, then the common rows"
);
}
#[test]
fn a_filter_that_lowers_to_no_predicate_is_refused_rather_than_run() {
let unscoped: Option<SqlKeyIn<i64, Sqlite, 1>> = None;
let Err(SqlWriteError::Unscoped(table)) = delete_statements::<ClipRow, Sqlite, _>(&unscoped)
else {
panic!("a filter naming no row is refused rather than run");
};
assert!(table.is("clip"), "the refusal names the table it saved");
}
#[test]
fn a_comparison_whose_count_and_rendering_disagree_is_refused_at_the_statement() {
let Err(SqlWriteError::Unscoped(table)) =
delete_statements::<ClipRow, Sqlite, _>(&super::Overcounting)
else {
panic!("a filter that renders nothing is refused however it counts itself");
};
assert!(table.is("clip"));
}
#[test]
fn a_membership_of_nothing_is_a_statement_rather_than_a_refusal() {
assert_eq!(
removed::<ClipRow, Sqlite, _>(&matching::<Sqlite>("id", &[]))[2],
("DELETE FROM \"clip\" WHERE 1 = 0".to_owned(), 0),
"an empty membership asks for no rows rather than for all of them"
);
}
}
#[cfg(feature = "postgres")]
mod postgres {
use sqlx::Postgres;
use super::{ClipRow, matching, removed, rendered, row};
#[test]
fn the_keyed_replace_is_the_standard_conflict_clause() {
assert_eq!(
rendered::<ClipRow, Postgres>(&row::<Postgres>(&[], &[]), true)[0],
(
"INSERT INTO \"clip\" (\"media_id\", \"id\", \"title\", \"bit_rate\") \
VALUES ($1, $2, $3, $4) ON CONFLICT (\"media_id\", \"id\") DO UPDATE SET \
\"media_id\" = \"excluded\".\"media_id\", \"id\" = \"excluded\".\"id\", \
\"title\" = \"excluded\".\"title\", \"bit_rate\" = \"excluded\".\"bit_rate\""
.to_owned(),
4
)
);
}
#[test]
fn the_edge_statements_number_their_binds_across_the_value_rows() {
let statements = rendered::<ClipRow, Postgres>(&row::<Postgres>(&["a", "b"], &["n"]), true);
assert_eq!(
statements[1],
(
"DELETE FROM \"clip_tags\" WHERE \"media_id\" = $1 AND \"id\" = $2".to_owned(),
2
)
);
assert_eq!(
statements[2],
(
"INSERT INTO \"clip_tags\" (\"media_id\", \"id\", \"tags_ordinal\", \"tags\") \
VALUES ($1, $2, $3, $4), ($5, $6, $7, $8)"
.to_owned(),
8
)
);
assert_eq!(
statements[4],
(
"INSERT INTO \"clip_notes\" (\"media_id\", \"id\", \"notes\") VALUES ($1, $2, $3)"
.to_owned(),
3
)
);
}
#[test]
fn the_removal_numbers_its_binds_through_the_subquery() {
assert_eq!(
removed::<ClipRow, Postgres, _>(&matching::<Postgres>("media_id", &[4, 5])),
[
(
"DELETE FROM \"clip_tags\" WHERE \"id\" IN (SELECT \"id\" FROM \"clip\" \
WHERE (\"media_id\") IN (($1), ($2)))"
.to_owned(),
2
),
(
"DELETE FROM \"clip_notes\" WHERE \"id\" IN (SELECT \"id\" FROM \"clip\" \
WHERE (\"media_id\") IN (($1), ($2)))"
.to_owned(),
2
),
(
"DELETE FROM \"clip\" WHERE (\"media_id\") IN (($1), ($2))".to_owned(),
2
),
],
"each statement numbers from one, and each binds the whole membership"
);
}
}
#[cfg(feature = "mysql")]
mod mysql {
use sqlx::MySql;
use super::{ClipRow, matching, removed, rendered, row};
#[test]
fn the_keyed_replace_names_no_target_and_reads_the_row_back_through_values() {
assert_eq!(
rendered::<ClipRow, MySql>(&row::<MySql>(&[], &[]), true)[0],
(
"INSERT INTO `clip` (`media_id`, `id`, `title`, `bit_rate`) VALUES (?, ?, ?, ?) \
ON DUPLICATE KEY UPDATE `media_id` = VALUES(`media_id`), `id` = VALUES(`id`), \
`title` = VALUES(`title`), `bit_rate` = VALUES(`bit_rate`)"
.to_owned(),
4
)
);
}
#[test]
fn the_edge_statements_carry_the_dialects_own_bracketing() {
let statements = rendered::<ClipRow, MySql>(&row::<MySql>(&["a", "b"], &["n"]), true);
assert_eq!(
statements[1],
(
"DELETE FROM `clip_tags` WHERE `media_id` = ? AND `id` = ?".to_owned(),
2
)
);
assert_eq!(
statements[2],
(
"INSERT INTO `clip_tags` (`media_id`, `id`, `tags_ordinal`, `tags`) \
VALUES (?, ?, ?, ?), (?, ?, ?, ?)"
.to_owned(),
8
)
);
}
#[test]
fn the_removal_carries_the_dialects_own_bracketing() {
assert_eq!(
removed::<ClipRow, MySql, _>(&matching::<MySql>("id", &[7]))[0],
(
"DELETE FROM `clip_tags` WHERE `id` IN (SELECT `id` FROM `clip` WHERE (`id`) IN ((?)))"
.to_owned(),
1
)
);
}
}
#[cfg(feature = "sqlite")]
mod live {
use sqlx::Sqlite;
use super::{Caption, CaptionRow, CaptionSource, Clip, ClipRow, caption, clip};
use crate::query::sql::{SqlWriteError, delete, delete_where, get, insert, upsert};
async fn empty() -> sqlx::sqlite::SqliteConnection {
use sqlx::Connection as _;
use crate::{TypeVisitor as _, query::sql::Create};
let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
.await
.expect("an in-memory database");
sqlx::query("PRAGMA foreign_keys = ON")
.execute(&mut db)
.await
.expect("the connection enforces what the schema declares");
let mut create = Create::<Sqlite>::new();
create
.next_type::<Clip>()
.expect("this descriptor renders for SQLite");
create
.next_type::<Caption>()
.expect("and so does the fan-in's");
create.run(&mut db).await.expect("and the engine takes it");
db
}
async fn from_frame(db: &mut sqlx::sqlite::SqliteConnection) -> Vec<String> {
sqlx::query_scalar::<_, String>(
r#"SELECT "id" || ':' || "media_id" || ':' || "frame" FROM "caption_frame" ORDER BY "id""#,
)
.fetch_all(db)
.await
.expect("the provenance table is there")
}
async fn from_turn(db: &mut sqlx::sqlite::SqliteConnection) -> Vec<String> {
sqlx::query_scalar::<_, String>(
r#"SELECT "id" || ':' || "turn" FROM "caption_turn" ORDER BY "id""#,
)
.fetch_all(db)
.await
.expect("the provenance table is there")
}
async fn parents(db: &mut sqlx::sqlite::SqliteConnection) -> i64 {
sqlx::query_scalar::<_, i64>(r#"SELECT count(*) FROM "clip""#)
.fetch_one(db)
.await
.expect("the parent table is there")
}
async fn tag_rows(db: &mut sqlx::sqlite::SqliteConnection) -> i64 {
sqlx::query_scalar::<_, i64>(r#"SELECT count(*) FROM "clip_tags""#)
.fetch_one(db)
.await
.expect("the sequence's edge table is there")
}
async fn note_rows(db: &mut sqlx::sqlite::SqliteConnection) -> i64 {
sqlx::query_scalar::<_, i64>(r#"SELECT count(*) FROM "clip_notes""#)
.fetch_one(db)
.await
.expect("the set's edge table is there")
}
#[tokio::test]
async fn an_inserted_record_reads_back_through_its_own_conversions() {
let mut db = empty().await;
let stored = clip(&["a", "b", "c"], &["beta-note", "alpha-note"]);
insert::<ClipRow, Sqlite, _>(&mut db, stored.clone())
.await
.expect("an empty table takes the record");
assert_eq!(
get::<ClipRow, Sqlite, _>(&mut db, &7, false)
.await
.expect("the record is there"),
Some(Clip {
notes: vec!["alpha-note".to_owned(), "beta-note".to_owned()],
..stored
}),
"the sequence keeps the order it was written in and the set comes back in its own"
);
}
#[tokio::test]
async fn a_second_insert_at_a_taken_address_is_the_engines_own_refusal() {
let mut db = empty().await;
insert::<ClipRow, Sqlite, _>(&mut db, clip(&["a"], &[]))
.await
.expect("the first write lands");
let refused = insert::<ClipRow, Sqlite, _>(&mut db, clip(&["b"], &[])).await;
let Err(SqlWriteError::Sql(why)) = refused else {
panic!("a taken address is the dialect's own constraint violation");
};
assert!(
why.to_string().contains("UNIQUE constraint failed"),
"the engine's own sentence reaches the caller: {why}"
);
assert_eq!(parents(&mut db).await, 1, "and nothing was written twice");
}
#[tokio::test]
async fn an_upsert_replaces_the_payload_at_one_address() {
let mut db = empty().await;
upsert::<ClipRow, Sqlite, _>(&mut db, clip(&[], &[]))
.await
.expect("an upsert onto nothing is an insert");
assert_eq!(parents(&mut db).await, 1);
let mut replacement = clip(&[], &[]);
replacement.title = "omega".to_owned();
replacement.bit_rate = 128;
upsert::<ClipRow, Sqlite, _>(&mut db, replacement.clone())
.await
.expect("an upsert onto a stored row replaces it");
assert_eq!(parents(&mut db).await, 1, "one address, one row");
assert_eq!(
get::<ClipRow, Sqlite, _>(&mut db, &7, false)
.await
.expect("the record is there"),
Some(replacement),
"the old payload is gone rather than merged with the new one"
);
}
#[tokio::test]
async fn an_upsert_replaces_the_edge_set_and_the_ordinals_are_the_new_collections() {
let mut db = empty().await;
upsert::<ClipRow, Sqlite, _>(&mut db, clip(&["a", "b"], &["one", "two"]))
.await
.expect("the first write lands");
upsert::<ClipRow, Sqlite, _>(&mut db, clip(&["c"], &["three"]))
.await
.expect("the replacement lands");
assert_eq!(
get::<ClipRow, Sqlite, _>(&mut db, &7, false)
.await
.expect("the record is there")
.map(|clip| (clip.tags, clip.notes)),
Some((vec!["c".to_owned()], vec!["three".to_owned()])),
"the old elements are gone rather than kept beside the new ones"
);
assert_eq!(
sqlx::query_scalar::<_, i64>(
r#"SELECT "tags_ordinal" FROM "clip_tags" ORDER BY "tags_ordinal""#
)
.fetch_all(&mut db)
.await
.expect("the edge table is there"),
[0],
"the replacement's ordinals start at zero rather than after the old collection's"
);
}
#[tokio::test]
async fn an_emptied_collection_comes_back_empty_rather_than_holding_what_it_held() {
let mut db = empty().await;
upsert::<ClipRow, Sqlite, _>(&mut db, clip(&["a", "b"], &["one", "two"]))
.await
.expect("the first write lands");
upsert::<ClipRow, Sqlite, _>(&mut db, clip(&[], &["three"]))
.await
.expect("the replacement lands");
assert_eq!(
get::<ClipRow, Sqlite, _>(&mut db, &7, false)
.await
.expect("the record is there")
.map(|clip| (clip.tags, clip.notes)),
Some((Vec::new(), vec!["three".to_owned()])),
"an emptied sequence keeps nothing, and a set is replaced rather than merged"
);
}
#[tokio::test]
async fn the_multi_statement_write_lands_whole() {
let mut db = empty().await;
insert::<ClipRow, Sqlite, _>(&mut db, clip(&["a", "b"], &["n"]))
.await
.expect("three statements, one transaction");
assert_eq!(parents(&mut db).await, 1);
assert_eq!(
get::<ClipRow, Sqlite, _>(&mut db, &7, false)
.await
.expect("the record is there")
.map(|clip| clip.tags),
Some(vec!["a".to_owned(), "b".to_owned()])
);
}
#[tokio::test]
async fn a_failure_part_way_through_leaves_no_parent_row() {
let mut db = empty().await;
sqlx::query(r#"DROP TABLE "clip_tags""#)
.execute(&mut db)
.await
.expect("the sequence's edge table goes away");
assert!(
insert::<ClipRow, Sqlite, _>(&mut db, clip(&["a", "b"], &["n"]))
.await
.is_err(),
"the second statement has no table to write to"
);
assert_eq!(
parents(&mut db).await,
0,
"and the parent statement that already ran is rolled back with it"
);
}
#[tokio::test]
async fn a_fan_ins_common_row_and_its_provenance_row_land_together() {
let mut db = empty().await;
insert::<CaptionRow, Sqlite, _>(
&mut db,
caption(CaptionSource::Frame { media: 1, frame: 5 }),
)
.await
.expect("two statements, one transaction");
assert_eq!(from_frame(&mut db).await, ["7:1:5"]);
assert!(
from_turn(&mut db).await.is_empty(),
"a row descends from ONE upstream, so the other table holds nothing for it"
);
assert_eq!(
sqlx::query_scalar::<_, String>(r#"SELECT "__ig_source__" FROM "caption""#)
.fetch_one(&mut db)
.await
.expect("the common row is there"),
"Frame",
"and the discriminant names the table the provenance row went in"
);
}
#[tokio::test]
async fn a_replacement_that_changes_upstream_leaves_one_ancestry() {
let mut db = empty().await;
upsert::<CaptionRow, Sqlite, _>(
&mut db,
caption(CaptionSource::Frame { media: 1, frame: 5 }),
)
.await
.expect("the first write lands");
upsert::<CaptionRow, Sqlite, _>(&mut db, caption(CaptionSource::Turn { turn: 9 }))
.await
.expect("and the replacement lands");
assert!(
from_frame(&mut db).await.is_empty(),
"the ancestry the row no longer has is gone"
);
assert_eq!(from_turn(&mut db).await, ["7:9"]);
}
#[tokio::test]
async fn a_fan_ins_torn_write_leaves_neither_row() {
let mut db = empty().await;
sqlx::query(r#"DROP TABLE "caption_frame""#)
.execute(&mut db)
.await
.expect("the provenance table goes away");
assert!(
insert::<CaptionRow, Sqlite, _>(
&mut db,
caption(CaptionSource::Frame { media: 1, frame: 5 })
)
.await
.is_err(),
"the second statement has no table to write to"
);
assert_eq!(
sqlx::query_scalar::<_, i64>(r#"SELECT count(*) FROM "caption""#)
.fetch_one(&mut db)
.await
.expect("the common table is there"),
0,
"and the common statement that already ran is rolled back with it"
);
}
#[tokio::test]
async fn a_shortened_reindex_leaves_no_ghost_rows_behind() {
let mut db = empty().await;
for id in 0..14 {
let mut segment = clip(&["a"], &["n"]);
segment.id = id;
insert::<ClipRow, Sqlite, _>(&mut db, segment)
.await
.expect("the first indexing pass writes fourteen segments");
}
assert_eq!(parents(&mut db).await, 14);
let removed =
delete_where::<ClipRow, Sqlite, _>(&mut db, &super::matching::<Sqlite>("media_id", &[1]))
.await
.expect("the media's rows are removed by their own predicate");
assert_eq!(removed, 14, "the count is the RECORDS that went");
assert_eq!(parents(&mut db).await, 0);
for id in 0..9 {
let mut segment = clip(&["a"], &["n"]);
segment.id = id;
insert::<ClipRow, Sqlite, _>(&mut db, segment)
.await
.expect("the second pass writes nine");
}
assert_eq!(
parents(&mut db).await,
9,
"exactly nine, where a lane without this verb would answer fourteen"
);
assert_eq!(
get::<ClipRow, Sqlite, _>(&mut db, &12, false)
.await
.expect("the read runs"),
None,
"segment 12 is GONE rather than orphaned — the ghost a search used to hit"
);
assert!(
get::<ClipRow, Sqlite, _>(&mut db, &8, false)
.await
.expect("the read runs")
.is_some(),
"and the nine the source still produces are there"
);
}
#[tokio::test]
async fn a_removal_takes_the_records_collection_rows_with_it() {
let mut db = empty().await;
insert::<ClipRow, Sqlite, _>(&mut db, clip(&["a", "b", "c"], &["one", "two"]))
.await
.expect("the record and its two collections land");
assert_eq!(tag_rows(&mut db).await, 3);
assert_eq!(note_rows(&mut db).await, 2);
assert!(
delete::<ClipRow, Sqlite, _>(&mut db, &7)
.await
.expect("the removal runs"),
"a row was there"
);
assert_eq!(parents(&mut db).await, 0);
assert_eq!(
tag_rows(&mut db).await,
0,
"the sequence's rows went with the record rather than outliving it"
);
assert_eq!(note_rows(&mut db).await, 0, "and so did the set's");
}
#[tokio::test]
async fn the_cascade_reaches_the_removed_records_rows_and_no_others() {
let mut db = empty().await;
insert::<ClipRow, Sqlite, _>(&mut db, clip(&["a", "b"], &["one"]))
.await
.expect("the first record lands");
let mut second = clip(&["c", "d", "e"], &["two", "three"]);
second.id = 8;
insert::<ClipRow, Sqlite, _>(&mut db, second)
.await
.expect("and the second");
assert!(
delete::<ClipRow, Sqlite, _>(&mut db, &7)
.await
.expect("the removal runs")
);
assert_eq!(parents(&mut db).await, 1);
assert_eq!(
tag_rows(&mut db).await,
3,
"the surviving record keeps its whole sequence"
);
assert_eq!(note_rows(&mut db).await, 2, "and its whole set");
assert_eq!(
get::<ClipRow, Sqlite, _>(&mut db, &8, false)
.await
.expect("the read runs")
.map(|clip| (clip.tags.len(), clip.notes.len())),
Some((3, 2)),
"and reads back complete"
);
}
#[tokio::test]
async fn a_removal_at_an_empty_address_is_false_rather_than_an_error() {
let mut db = empty().await;
assert!(
!delete::<ClipRow, Sqlite, _>(&mut db, &7)
.await
.expect("a miss is not an error"),
"nothing was there"
);
}
#[tokio::test]
async fn a_removal_takes_the_records_ancestry_with_it() {
let mut db = empty().await;
insert::<CaptionRow, Sqlite, _>(
&mut db,
caption(CaptionSource::Frame { media: 1, frame: 5 }),
)
.await
.expect("the common row and its provenance row land");
assert_eq!(from_frame(&mut db).await, ["7:1:5"]);
assert!(
delete::<CaptionRow, Sqlite, _>(&mut db, &7)
.await
.expect("the removal runs — the constraint is satisfied by the ORDER"),
"a row was there"
);
assert!(
from_frame(&mut db).await.is_empty(),
"the ancestry went with the row it belonged to"
);
assert_eq!(
sqlx::query_scalar::<_, i64>(r#"SELECT count(*) FROM "caption""#)
.fetch_one(&mut db)
.await
.expect("the common table is there"),
0
);
}
#[tokio::test]
async fn an_unscoped_filter_leaves_every_row_where_it_was() {
let mut db = empty().await;
insert::<ClipRow, Sqlite, _>(&mut db, clip(&["a"], &["n"]))
.await
.expect("the record lands");
let unscoped: Option<crate::comparison::sql::SqlKeyIn<i64, Sqlite, 1>> = None;
let Err(SqlWriteError::Unscoped(table)) =
super::delete_statements::<ClipRow, Sqlite, _>(&unscoped)
else {
panic!("an unscoped filter is refused");
};
assert!(table.is("clip"));
assert_eq!(
parents(&mut db).await,
1,
"and the row a filterless statement would have taken is still there"
);
}
#[tokio::test]
async fn a_write_inside_a_callers_transaction_is_subject_to_the_callers_rollback() {
use sqlx::Acquire as _;
let mut db = empty().await;
let mut held = db.begin().await.expect("the caller's own transaction");
insert::<ClipRow, Sqlite, _>(&mut held, clip(&["a"], &[]))
.await
.expect("the write passes through");
let mut second = clip(&["b"], &[]);
second.id = 8;
insert::<ClipRow, Sqlite, _>(&mut held, second)
.await
.expect("and so does the one beside it");
held.rollback().await.expect("the caller abandons both");
assert_eq!(
parents(&mut db).await,
0,
"neither write opened a transaction of its own to commit"
);
}
}