use sqlx::QueryBuilder;
#[cfg(feature = "sqlite")]
use super::insert_statement;
use crate::{
Carrier, ColumnName, ColumnShape, ComplexComparison, FieldName, Identifiable, Record,
RecordAddress, Timestamp, Transformer,
comparison::{Backend, sql::SqlKeyIn},
query::sql::{
CrossingError, EdgeCollection, EdgeShape, EdgeWrite, SqlQuery, SqlWrite, distribute,
element_alias,
},
};
#[derive(Debug, Clone, PartialEq, Eq)]
struct Take {
id: i64,
stamps: Vec<Timestamp>,
marks: Vec<Timestamp>,
}
impl Identifiable for Take {
type Id = i64;
fn id_ref(&self) -> &i64 {
&self.id
}
}
impl Transformer for Take {
type Graphql = ();
type Key = i64;
type Lineage = i64;
type Record = Self;
fn key(&self) -> i64 {
self.id
}
}
impl<Db: Backend> Record<Db> for Take {
type Row = TakeRow;
type Comparison = SqlKeyIn<i64, Db, 1>;
type OrderBy = ();
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct TakeRow {
id: i64,
stamps: Vec<Timestamp>,
marks: Vec<Timestamp>,
}
const TAKE: RecordAddress = RecordAddress::new(FieldName::new("take"), &[FieldName::new("id")]);
const ALIASES: &[&str] = &["__ig_take_0__", "__ig_take_1__"];
const STAMPS: &[&FieldName] = &[FieldName::new("stamps")];
const MARKS: &[&FieldName] = &[FieldName::new("marks")];
const SEGMENTS: &[&FieldName] = &[FieldName::new("secs"), FieldName::new("nanos")];
const _: () = assert!(
crate::leaf_names(<Timestamp as crate::ColumnKind>::SEGMENTS, SEGMENTS),
"the plan's leaf names are the element type's own, joined as the renderer joins them"
);
fn take_key<Db>(row: &TakeRow, _index: usize, qb: &mut QueryBuilder<Db>)
where
Db: sqlx::Database,
i64: Carrier<Db>,
{
row.id.push_bind(qb);
}
fn gathered<Db>(
page: &mut [TakeRow],
rows: &[Db::Row],
into: fn(&mut TakeRow) -> &mut Vec<Timestamp>,
) -> Result<(), sqlx::Error>
where
Db: sqlx::Database,
for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
for<'r> i32: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
use sqlx::Row as _;
let secs = element_alias(FieldName::new("secs"));
let nanos = element_alias(FieldName::new("nanos"));
distribute(
page,
rows,
|row| row.id,
|row| row.try_get("id"),
|row| {
let second: i64 = row.try_get(secs.as_str())?;
let nanosecond: i32 = row.try_get(nanos.as_str())?;
Timestamp::from_parts(second, nanosecond)
.map_err(|error| sqlx::Error::Decode(Box::new(error)))
},
into,
)
}
fn take_stamps<Db>(page: &mut [TakeRow], rows: &[Db::Row]) -> Result<(), sqlx::Error>
where
Db: sqlx::Database,
for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
for<'r> i32: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
gathered::<Db>(page, rows, |row| &mut row.stamps)
}
fn take_marks<Db>(page: &mut [TakeRow], rows: &[Db::Row]) -> Result<(), sqlx::Error>
where
Db: sqlx::Database,
for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
for<'r> i32: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
gathered::<Db>(page, rows, |row| &mut row.marks)
}
fn stamps_len(row: &TakeRow) -> usize {
row.stamps.len()
}
fn marks_len(row: &TakeRow) -> usize {
row.marks.len()
}
fn stamps_element<Db>(row: &TakeRow, at: usize, qb: &mut QueryBuilder<Db>)
where
Db: sqlx::Database,
Timestamp: Carrier<Db>,
{
row.stamps[at].push_bind(qb);
}
fn marks_element<Db>(row: &TakeRow, at: usize, qb: &mut QueryBuilder<Db>)
where
Db: sqlx::Database,
Timestamp: Carrier<Db>,
{
row.marks[at].push_bind(qb);
}
impl<Db> SqlQuery<Db> for TakeRow
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> i32: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
type Record = Take;
type Address = SqlKeyIn<i64, Db, 1>;
const ADDRESS: RecordAddress = TAKE;
const ALIASES: &'static [&'static str] = ALIASES;
const COLUMNS: &'static [ColumnShape] = &[ColumnShape::Plain(ColumnName::new("id"))];
const COLLECTIONS: &'static [EdgeCollection<Self, Db>] = &[
EdgeCollection::gather_composite(
STAMPS,
EdgeShape::Sequence,
SEGMENTS,
take_key::<Db>,
take_stamps::<Db>,
),
EdgeCollection::gather_composite(
MARKS,
EdgeShape::Set,
SEGMENTS,
take_key::<Db>,
take_marks::<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<Take, CrossingError> {
Ok(Take {
id: self.id,
stamps: self.stamps,
marks: self.marks,
})
}
}
impl<Db> SqlWrite<Db> for TakeRow
where
Db: Backend + sqlx::Database,
SqlKeyIn<i64, Db, 1>: ComplexComparison<Db>,
i64: Carrier<Db>,
Timestamp: Carrier<Db>,
for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
for<'r> i32: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
const EDGES: &'static [EdgeWrite<Self, Db>] = &[
EdgeWrite::composite(
STAMPS,
EdgeShape::Sequence,
SEGMENTS,
stamps_len,
stamps_element::<Db>,
),
EdgeWrite::composite(
MARKS,
EdgeShape::Set,
SEGMENTS,
marks_len,
marks_element::<Db>,
),
];
fn row(record: Take) -> Result<Self, CrossingError> {
Ok(Self {
id: record.id,
stamps: record.stamps,
marks: record.marks,
})
}
fn bind(&self, _at: usize, qb: &mut QueryBuilder<Db>) {
self.id.push_bind(qb);
}
fn bind_address(&self, _at: usize, qb: &mut QueryBuilder<Db>) {
self.id.push_bind(qb);
}
}
impl<'a, R: sqlx::Row> sqlx::FromRow<'a, R> for TakeRow
where
i64: crate::Assemble<'a, R>,
{
fn from_row(row: &'a R) -> sqlx::Result<Self> {
Ok(Self {
id: crate::assembled(row, FieldName::new("id"), None)?,
stamps: Vec::new(),
marks: Vec::new(),
})
}
}
macro_rules! describe {
($db:ty, $int:literal, $big:literal) => {
impl crate::Describe<$db> for Take {
const BLUEPRINT: crate::Table = crate::Table::new(
TAKE,
&[crate::Column::new(FieldName::new("id"), $big, false)],
)
.with_edges(&[
crate::EdgeTable::composite(
STAMPS,
EdgeShape::Sequence,
&[
crate::Column::new(FieldName::new("secs"), $big, false),
crate::Column::new(FieldName::new("nanos"), $int, false),
],
),
crate::EdgeTable::composite(
MARKS,
EdgeShape::Set,
&[
crate::Column::new(FieldName::new("secs"), $big, false),
crate::Column::new(FieldName::new("nanos"), $int, false),
],
),
]);
}
};
}
#[cfg(feature = "sqlite")]
describe!(sqlx::Sqlite, "INTEGER", "BIGINT");
#[cfg(feature = "postgres")]
describe!(sqlx::Postgres, "integer", "bigint");
#[cfg(feature = "mysql")]
describe!(sqlx::MySql, "INT", "BIGINT");
#[cfg(feature = "sqlite")]
const _: () = assert!(crate::describes(
&<Take as crate::Describe<sqlx::Sqlite>>::BLUEPRINT,
<TakeRow as SqlQuery<sqlx::Sqlite>>::COLUMNS
));
fn schema<Db: crate::query::sql::AsyncSchemaDialect>() -> Vec<String>
where
Take: crate::Describe<Db>,
{
<Take as crate::Describe<Db>>::BLUEPRINT
.create::<Db>()
.expect("every collection names a field")
}
#[cfg(feature = "sqlite")]
fn edge_text<Db>(row: &TakeRow, which: usize) -> (String, usize)
where
TakeRow: SqlWrite<Db>,
Db: crate::query::sql::SqlDialect,
i64: Carrier<Db>,
<Db as sqlx::Database>::Arguments: sqlx::IntoArguments<Db>,
{
use sqlx::Execute as _;
let mut rendered = crate::query::sql::write::statements::<TakeRow, Db>(
row,
insert_statement::<TakeRow, Db>(row),
false,
)
.expect("every collection renders");
let mut built = rendered[which + 1].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)
}
#[cfg(feature = "sqlite")]
fn at(second: i64, nanosecond: i32) -> Timestamp {
Timestamp::from_parts(second, nanosecond).expect("a legal instant")
}
#[cfg(feature = "sqlite")]
fn take() -> Take {
Take {
id: 7,
stamps: vec![at(10, 250), at(90, 0)],
marks: vec![at(400, 1)],
}
}
#[cfg(feature = "sqlite")]
#[test]
fn both_table_forms_name_every_segment() {
assert_eq!(
schema::<sqlx::Sqlite>(),
[
r#"CREATE TABLE IF NOT EXISTS "take" ("id" BIGINT NOT NULL, PRIMARY KEY ("id"))"#,
r#"CREATE TABLE IF NOT EXISTS "take_stamps" ("id" BIGINT NOT NULL, "stamps_ordinal" INTEGER NOT NULL, "stamps_secs" BIGINT NOT NULL, "stamps_nanos" INTEGER NOT NULL, PRIMARY KEY ("id", "stamps_ordinal"))"#,
r#"CREATE INDEX IF NOT EXISTS "__ig_take_stamps_element" ON "take_stamps" ("id", "stamps_secs", "stamps_nanos")"#,
r#"CREATE TABLE IF NOT EXISTS "take_marks" ("id" BIGINT NOT NULL, "marks_secs" BIGINT NOT NULL, "marks_nanos" INTEGER NOT NULL, PRIMARY KEY ("id", "marks_secs", "marks_nanos"))"#,
]
);
}
#[cfg(feature = "postgres")]
#[test]
fn postgres_renders_both_table_forms() {
assert_eq!(
schema::<sqlx::Postgres>(),
[
r#"CREATE TABLE IF NOT EXISTS "take" ("id" bigint NOT NULL, PRIMARY KEY ("id"))"#,
r#"CREATE TABLE IF NOT EXISTS "take_stamps" ("id" bigint NOT NULL, "stamps_ordinal" bigint NOT NULL, "stamps_secs" bigint NOT NULL, "stamps_nanos" integer NOT NULL, PRIMARY KEY ("id", "stamps_ordinal"))"#,
r#"CREATE INDEX IF NOT EXISTS "__ig_take_stamps_element" ON "take_stamps" ("id", "stamps_secs", "stamps_nanos")"#,
r#"CREATE TABLE IF NOT EXISTS "take_marks" ("id" bigint NOT NULL, "marks_secs" bigint NOT NULL, "marks_nanos" integer NOT NULL, PRIMARY KEY ("id", "marks_secs", "marks_nanos"))"#,
]
);
}
#[cfg(feature = "mysql")]
#[test]
fn mysql_renders_both_table_forms() {
assert_eq!(
schema::<sqlx::MySql>(),
[
"CREATE TABLE IF NOT EXISTS `take` (`id` BIGINT NOT NULL, PRIMARY KEY (`id`))",
"CREATE TABLE IF NOT EXISTS `take_stamps` (`id` BIGINT NOT NULL, `stamps_ordinal` BIGINT NOT NULL, `stamps_secs` BIGINT NOT NULL, `stamps_nanos` INT NOT NULL, PRIMARY KEY (`id`, `stamps_ordinal`))",
"CREATE INDEX IF NOT EXISTS `__ig_take_stamps_element` ON `take_stamps` (`id`, `stamps_secs`, `stamps_nanos`)",
"CREATE TABLE IF NOT EXISTS `take_marks` (`id` BIGINT NOT NULL, `marks_secs` BIGINT NOT NULL, `marks_nanos` INT NOT NULL, PRIMARY KEY (`id`, `marks_secs`, `marks_nanos`))",
]
);
}
#[cfg(feature = "sqlite")]
#[test]
fn the_insert_binds_every_segment_of_every_element() {
let row = <TakeRow as SqlWrite<sqlx::Sqlite>>::row(take()).expect("nothing converts");
assert_eq!(
edge_text::<sqlx::Sqlite>(&row, 0),
(
concat!(
r#"INSERT INTO "take_stamps" ("id", "stamps_ordinal", "stamps_secs", "stamps_nanos")"#,
" VALUES (?, ?, ?, ?), (?, ?, ?, ?)"
)
.to_owned(),
8
)
);
assert_eq!(
edge_text::<sqlx::Sqlite>(&row, 1),
(
r#"INSERT INTO "take_marks" ("id", "marks_secs", "marks_nanos") VALUES (?, ?, ?)"#.to_owned(),
3
)
);
}
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn a_composite_collection_makes_the_whole_round_trip() {
use sqlx::Connection as _;
use crate::{
TypeVisitor as _,
query::sql::{Create, get, insert},
};
let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
.await
.expect("an in-memory database");
let mut create = Create::<sqlx::Sqlite>::new();
create
.next_type::<Take>()
.expect("this descriptor renders for SQLite");
create.run(&mut db).await.expect("and the engine takes it");
insert::<TakeRow, sqlx::Sqlite, _>(&mut db, take())
.await
.expect("four values for one element");
assert_eq!(
get::<TakeRow, sqlx::Sqlite, _>(&mut db, &7, false)
.await
.expect("the record is there"),
Some(take()),
"two columns per element, back into one instant, in the stored order"
);
let stored: Vec<(i64, i64, i32)> = sqlx::query_as(
r#"SELECT "stamps_ordinal", "stamps_secs", "stamps_nanos" FROM "take_stamps" ORDER BY "stamps_ordinal""#,
)
.fetch_all(&mut db)
.await
.expect("the segment columns are what the schema holds");
assert_eq!(stored, [(0, 10, 250), (1, 90, 0)]);
}
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn a_removal_takes_every_segment_of_every_element_with_it() {
use sqlx::Connection as _;
use crate::{
TypeVisitor as _,
comparison::sql::SqlKeyIn,
query::sql::{Create, delete, delete_where, get, insert},
};
async fn rows(db: &mut sqlx::sqlite::SqliteConnection, id: i64) -> (i64, i64) {
let stamps: i64 = sqlx::query_scalar(r#"SELECT count(*) FROM "take_stamps" WHERE "id" = ?"#)
.bind(id)
.fetch_one(&mut *db)
.await
.expect("the sequence's table is there");
let marks: i64 = sqlx::query_scalar(r#"SELECT count(*) FROM "take_marks" WHERE "id" = ?"#)
.bind(id)
.fetch_one(&mut *db)
.await
.expect("the set's table is there");
(stamps, marks)
}
let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
.await
.expect("an in-memory database");
let mut create = Create::<sqlx::Sqlite>::new();
create.next_type::<Take>().expect("it renders");
create.run(&mut db).await.expect("and it is taken");
insert::<TakeRow, sqlx::Sqlite, _>(&mut db, take())
.await
.expect("the record and both collections land");
let mut beside = take();
beside.id = 8;
insert::<TakeRow, sqlx::Sqlite, _>(&mut db, beside)
.await
.expect("and a second record beside it");
assert_eq!(rows(&mut db, 7).await, (2, 1), "two stamps and one mark");
assert!(
delete::<TakeRow, sqlx::Sqlite, _>(&mut db, &7)
.await
.expect("the removal runs"),
"a row was there"
);
assert_eq!(
rows(&mut db, 7).await,
(0, 0),
"every segment of every element went with the record"
);
assert_eq!(
rows(&mut db, 8).await,
(2, 1),
"and the record beside it kept all of its own"
);
assert_eq!(
get::<TakeRow, sqlx::Sqlite, _>(&mut db, &7, false)
.await
.expect("the read runs"),
None
);
assert_eq!(
delete_where::<TakeRow, sqlx::Sqlite, _>(
&mut db,
&SqlKeyIn::<i64, sqlx::Sqlite, 1>::new(["id"], vec![[8]]),
)
.await
.expect("the purge runs"),
1,
"one record went"
);
assert_eq!(rows(&mut db, 8).await, (0, 0));
}
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn the_per_column_membership_admits_rows_the_row_value_does_not() {
use sqlx::{Connection as _, Executor as _, Row as _};
use crate::{
At, TypeVisitor as _,
comparison::sql::{
QueryBuilder as Statement, SelectClause, SqlCompositeEdgeComparison, SqlConjunction,
SqlScalarComparison,
},
query::sql::{Create, insert},
};
let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
.await
.expect("an in-memory database");
let mut create = Create::<sqlx::Sqlite>::new();
create.next_type::<Take>().expect("it renders");
create.run(&mut db).await.expect("and it is taken");
for record in [
Take {
id: 1,
stamps: vec![at(10, 250), at(90, 0)],
marks: Vec::new(),
},
Take {
id: 2,
stamps: vec![at(10, 0), at(90, 250)],
marks: Vec::new(),
},
Take {
id: 3,
stamps: vec![at(11, 11)],
marks: Vec::new(),
},
] {
insert::<TakeRow, sqlx::Sqlite, _>(&mut db, record)
.await
.expect("a take");
}
let mut comparison = SqlCompositeEdgeComparison::<
Timestamp,
SqlScalarComparison<i64, sqlx::Sqlite>,
sqlx::Sqlite,
>::new();
comparison.has_any_of = Some(Box::new([at(10, 250), at(90, 0)]));
let mut statement = Statement::<SelectClause, sqlx::Sqlite>::select()
.push_field("\"id\"")
.from("\"take\"")
.begin_where();
{
let frame = At::new(&TAKE).frame(FieldName::new("stamps"));
let accumulator = SqlConjunction::new(statement.inner_mut());
comparison
.apply(frame.at(), accumulator)
.expect("a rendered predicate");
}
let admitted: Vec<i64> = statement
.order_by(FieldName::new("id"), false)
.finalize()
.build()
.fetch_all(&mut db)
.await
.expect("the engine answers")
.iter()
.map(|row| row.get::<i64, _>(0))
.collect();
assert_eq!(
admitted,
[1],
"the row value admits exactly the take holding one of the two PAIRS"
);
let product: Vec<i64> = db
.fetch_all(
r#"SELECT "id" FROM "take" WHERE EXISTS (SELECT 1 FROM "take_stamps"
WHERE "take_stamps"."id" = "take"."id"
AND "take_stamps"."stamps_secs" IN (10, 90)
AND "take_stamps"."stamps_nanos" IN (250, 0)) ORDER BY "id""#,
)
.await
.expect("the engine answers this one too")
.iter()
.map(|row| row.get::<i64, _>(0))
.collect();
assert_eq!(
product,
[1, 2],
"the per-column spelling admits the CROSS pairs, which is the trap the row value closes"
);
}