#![cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
use sqlx::QueryBuilder;
use super::{ShadowWrite, insert_statement, statements, upsert_statement};
use crate::{
Carrier, ColumnName, ColumnShape, ComplexComparison, FieldName, Identifiable, Record,
RecordAddress, Transformer, collection_sort_key,
comparison::{Backend, sql::SqlKeyIn},
query::sql::{CrossingError, EdgeShape, EdgeWrite, SqlQuery, SqlWrite},
};
#[derive(Debug, Clone, PartialEq, Eq)]
struct Reel {
id: i64,
tags: Vec<String>,
}
impl Identifiable for Reel {
type Id = i64;
fn id_ref(&self) -> &i64 {
&self.id
}
}
impl Transformer for Reel {
type Graphql = ();
type Key = i64;
type Lineage = i64;
type Record = Self;
fn key(&self) -> i64 {
self.id
}
}
impl<Db: Backend> Record<Db> for Reel {
type Row = ReelRow;
type Comparison = SqlKeyIn<i64, Db, 1>;
type OrderBy = ();
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ReelRow {
id: i64,
tags: Vec<String>,
}
const REEL: RecordAddress = RecordAddress::new(FieldName::new("reel"), &[FieldName::new("id")]);
const TAGS_SORT: &FieldName = FieldName::new("__ig_tags_sort__");
impl<Db> SqlQuery<Db> for ReelRow
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<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
type Record = Reel;
type Address = SqlKeyIn<i64, Db, 1>;
const ADDRESS: RecordAddress = REEL;
const ALIASES: &'static [&'static str] = &["__ig_reel_0__", "__ig_reel_1__"];
const COLUMNS: &'static [ColumnShape] = &[ColumnShape::Plain(ColumnName::new("id"))];
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<Reel, CrossingError> {
Ok(Reel {
id: self.id,
tags: self.tags,
})
}
}
fn tags_len(row: &ReelRow) -> usize {
row.tags.len()
}
fn tags_element<Db>(row: &ReelRow, at: usize, qb: &mut QueryBuilder<Db>)
where
Db: sqlx::Database,
String: Carrier<Db>,
{
row.tags[at].push_bind(qb);
}
fn tags_sort<Db>(row: &ReelRow, qb: &mut QueryBuilder<Db>)
where
Db: sqlx::Database,
Vec<u8>: Carrier<Db>,
{
collection_sort_key(&row.tags).push_bind(qb);
}
impl<Db> SqlWrite<Db> for ReelRow
where
Db: Backend + sqlx::Database,
SqlKeyIn<i64, Db, 1>: ComplexComparison<Db>,
i64: Carrier<Db>,
String: Carrier<Db>,
Vec<u8>: Carrier<Db>,
for<'r> i64: 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>,
)];
const SHADOWS: &'static [ShadowWrite<Self, Db>] = &[ShadowWrite::new(TAGS_SORT, tags_sort::<Db>)];
fn row(record: Reel) -> Result<Self, CrossingError> {
Ok(Self {
id: record.id,
tags: record.tags,
})
}
fn bind(&self, at: usize, qb: &mut QueryBuilder<Db>) {
debug_assert_eq!(at, 0, "this row has one column");
self.id.push_bind(qb);
}
fn bind_address(&self, _at: usize, qb: &mut QueryBuilder<Db>) {
self.id.push_bind(qb);
}
}
fn reel(id: i64, tags: &[&str]) -> ReelRow {
ReelRow {
id,
tags: tags.iter().map(|tag| (*tag).to_owned()).collect(),
}
}
fn text<Db>(mut statement: QueryBuilder<Db>) -> String
where
Db: sqlx::Database,
<Db as sqlx::Database>::Arguments: sqlx::IntoArguments<Db>,
{
use sqlx::Execute as _;
statement.build().sql().as_str().to_owned()
}
fn inserted<Db>(row: &ReelRow) -> String
where
ReelRow: SqlWrite<Db>,
Db: crate::query::sql::SqlDialect,
<Db as sqlx::Database>::Arguments: sqlx::IntoArguments<Db>,
{
text(insert_statement::<ReelRow, Db>(row))
}
fn upserted<Db>(row: &ReelRow) -> String
where
ReelRow: SqlWrite<Db>,
Db: crate::query::sql::SqlDialect + super::Upsert,
<Db as sqlx::Database>::Arguments: sqlx::IntoArguments<Db>,
{
text(upsert_statement::<ReelRow, Db>(row))
}
#[cfg(feature = "sqlite")]
#[test]
fn the_insert_carries_the_companion() {
assert_eq!(
inserted::<sqlx::Sqlite>(&reel(1, &["a", "b"])),
r#"INSERT INTO "reel" ("id", "__ig_tags_sort__") VALUES (?, ?)"#
);
}
#[cfg(feature = "sqlite")]
#[test]
fn the_keyed_replace_assigns_the_companion() {
assert_eq!(
upserted::<sqlx::Sqlite>(&reel(1, &["a"])),
r#"INSERT INTO "reel" ("id", "__ig_tags_sort__") VALUES (?, ?) ON CONFLICT ("id") DO UPDATE SET "id" = "excluded"."id", "__ig_tags_sort__" = "excluded"."__ig_tags_sort__""#
);
}
#[cfg(feature = "postgres")]
#[test]
fn postgres_renders_the_companion_in_both_halves() {
assert_eq!(
upserted::<sqlx::Postgres>(&reel(1, &["a"])),
r#"INSERT INTO "reel" ("id", "__ig_tags_sort__") VALUES ($1, $2) ON CONFLICT ("id") DO UPDATE SET "id" = "excluded"."id", "__ig_tags_sort__" = "excluded"."__ig_tags_sort__""#
);
}
#[cfg(feature = "mysql")]
#[test]
fn mysql_renders_the_companion_in_both_halves() {
assert_eq!(
upserted::<sqlx::MySql>(&reel(1, &["a"])),
"INSERT INTO `reel` (`id`, `__ig_tags_sort__`) VALUES (?, ?) ON DUPLICATE KEY UPDATE `id` = \
VALUES(`id`), `__ig_tags_sort__` = VALUES(`__ig_tags_sort__`)"
);
}
#[cfg(feature = "sqlite")]
#[test]
fn the_companion_adds_no_statement_to_the_transaction() {
let row = reel(1, &["a", "b"]);
let rendered: Vec<String> = statements::<ReelRow, sqlx::Sqlite>(
&row,
upsert_statement::<ReelRow, sqlx::Sqlite>(&row),
true,
)
.expect("this row renders")
.into_iter()
.map(text)
.collect();
assert_eq!(rendered.len(), 3, "parent, edge delete, edge insert");
assert!(
rendered[0].contains("__ig_tags_sort__"),
"the companion is in the PARENT statement: {}",
rendered[0]
);
assert!(
rendered[1..]
.iter()
.all(|statement| !statement.contains("__ig_tags_sort__")),
"and in no other"
);
}
#[cfg(feature = "sqlite")]
mod live {
use sqlx::{Connection as _, Executor as _, sqlite::SqliteConnection};
use super::{Reel, ReelRow, reel};
use crate::{
collection_sort_key,
query::sql::{insert, upsert},
};
async fn empty() -> SqliteConnection {
let mut db = SqliteConnection::connect("sqlite::memory:")
.await
.expect("an in-memory database");
for ddl in [
r#"CREATE TABLE "reel" ("id" INTEGER PRIMARY KEY, "__ig_tags_sort__" BLOB NOT NULL)"#,
r#"CREATE TABLE "reel_tags" ("id" INTEGER, "tags_ordinal" INTEGER, "tags" TEXT,
PRIMARY KEY ("id", "tags_ordinal"))"#,
] {
db.execute(ddl).await.expect("a table");
}
db
}
async fn stored(db: &mut SqliteConnection, id: i64) -> Vec<u8> {
sqlx::query_scalar(r#"SELECT "__ig_tags_sort__" FROM "reel" WHERE "id" = ?"#)
.bind(id)
.fetch_one(db)
.await
.expect("the engine answers")
}
#[tokio::test]
async fn an_insert_stores_the_collections_order() {
let mut db = empty().await;
let row = reel(1, &["a", "b"]);
insert::<ReelRow, sqlx::Sqlite, _>(&mut db, Reel::from(row.clone()))
.await
.expect("the row is written");
assert_eq!(
stored(&mut db, 1).await,
collection_sort_key(&row.tags),
"the column holds the order of the collection that was written"
);
}
#[tokio::test]
async fn an_upsert_replaces_the_companion_beside_the_edge_set() {
let mut db = empty().await;
upsert::<ReelRow, sqlx::Sqlite, _>(&mut db, Reel::from(reel(1, &["b"])))
.await
.expect("the first write");
let first = stored(&mut db, 1).await;
let second = reel(1, &["a"]);
upsert::<ReelRow, sqlx::Sqlite, _>(&mut db, Reel::from(second.clone()))
.await
.expect("the second write");
assert_ne!(stored(&mut db, 1).await, first, "the order was replaced");
assert_eq!(
stored(&mut db, 1).await,
collection_sort_key(&second.tags),
"and replaced with the NEW collection's order"
);
let tags: Vec<String> = sqlx::query_scalar(
r#"SELECT "tags" FROM "reel_tags" WHERE "id" = ? ORDER BY "tags_ordinal""#,
)
.bind(1i64)
.fetch_all(&mut db)
.await
.expect("the engine answers");
assert_eq!(
tags,
["a"],
"the edge set was replaced too — the pair agrees"
);
}
#[tokio::test]
async fn an_empty_collection_stores_one_byte() {
let mut db = empty().await;
insert::<ReelRow, sqlx::Sqlite, _>(&mut db, Reel::from(reel(1, &[])))
.await
.expect("a reel with no tags");
assert_eq!(
stored(&mut db, 1).await,
collection_sort_key::<[&str; 0]>([])
);
assert_eq!(stored(&mut db, 1).await.len(), 1);
}
}
impl From<ReelRow> for Reel {
fn from(row: ReelRow) -> Self {
Self {
id: row.id,
tags: row.tags,
}
}
}