#![cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
use crate::{
Column, ColumnName, ColumnShape, Describe, EdgeShape, EdgeTable, FieldName, RecordAddress,
StoredAs, Table, TableColumns, describes,
};
struct Asset;
const ASSET: RecordAddress = RecordAddress::new(FieldName::new("asset"), &[FieldName::new("id")]);
const ASSET_COLUMNS: &[ColumnShape] = &[
ColumnShape::Plain(ColumnName::new("id")),
ColumnShape::Plain(ColumnName::new("title")),
ColumnShape::Plain(ColumnName::new("checksum")),
];
const INDEXED: &[&FieldName] = &[FieldName::new("title")];
const UNIQUE: &[&FieldName] = &[FieldName::new("checksum")];
const TAGS: &[&FieldName] = &[FieldName::new("tags")];
#[cfg(feature = "sqlite")]
const SQLITE_INT: &str = <i64 as StoredAs<sqlx::Sqlite>>::WORDS[0];
#[cfg(feature = "sqlite")]
const SQLITE_TEXT: &str = <String as StoredAs<sqlx::Sqlite>>::WORDS[0];
#[cfg(feature = "postgres")]
const POSTGRES_TEXT: &str = <String as StoredAs<sqlx::Postgres>>::WORDS[0];
#[cfg(feature = "mysql")]
const MYSQL_TEXT: &str = <String as StoredAs<sqlx::MySql>>::WORDS[0];
#[cfg(feature = "sqlite")]
const SQLITE_TAGS: &[EdgeTable] = &[EdgeTable::new(TAGS, EdgeShape::Sequence, SQLITE_TEXT)];
#[cfg(feature = "postgres")]
const POSTGRES_TAGS: &[EdgeTable] = &[EdgeTable::new(TAGS, EdgeShape::Sequence, POSTGRES_TEXT)];
#[cfg(feature = "mysql")]
const MYSQL_TAGS: &[EdgeTable] = &[EdgeTable::new(TAGS, EdgeShape::Sequence, MYSQL_TEXT)];
#[cfg(feature = "sqlite")]
const SQLITE_ASSET_WORDS: &[&[&str]] = &[
<i64 as StoredAs<sqlx::Sqlite>>::WORDS,
<Option<String> as StoredAs<sqlx::Sqlite>>::WORDS,
<String as StoredAs<sqlx::Sqlite>>::WORDS,
];
#[cfg(feature = "postgres")]
const POSTGRES_ASSET_WORDS: &[&[&str]] = &[
<i64 as StoredAs<sqlx::Postgres>>::WORDS,
<Option<String> as StoredAs<sqlx::Postgres>>::WORDS,
<String as StoredAs<sqlx::Postgres>>::WORDS,
];
#[cfg(feature = "mysql")]
const MYSQL_ASSET_WORDS: &[&[&str]] = &[
<i64 as StoredAs<sqlx::MySql>>::WORDS,
<Option<String> as StoredAs<sqlx::MySql>>::WORDS,
<String as StoredAs<sqlx::MySql>>::WORDS,
];
const ASSET_NULLS: &[bool] = &[false, true, false];
#[cfg(feature = "sqlite")]
impl Describe<sqlx::Sqlite> for Asset {
const BLUEPRINT: Table = Table::shaped(ASSET, ASSET_COLUMNS, SQLITE_ASSET_WORDS, ASSET_NULLS)
.with_indexes(INDEXED)
.with_uniques(UNIQUE)
.with_edges(SQLITE_TAGS);
}
#[cfg(feature = "postgres")]
impl Describe<sqlx::Postgres> for Asset {
const BLUEPRINT: Table = Table::shaped(ASSET, ASSET_COLUMNS, POSTGRES_ASSET_WORDS, ASSET_NULLS)
.with_indexes(INDEXED)
.with_uniques(UNIQUE)
.with_edges(POSTGRES_TAGS);
}
#[cfg(feature = "mysql")]
impl Describe<sqlx::MySql> for Asset {
const BLUEPRINT: Table = Table::shaped(ASSET, ASSET_COLUMNS, MYSQL_ASSET_WORDS, ASSET_NULLS)
.with_indexes(INDEXED)
.with_uniques(UNIQUE)
.with_edges(MYSQL_TAGS);
}
#[cfg(feature = "sqlite")]
const ASSET_FLAT: Table = Table::new(ASSET, ASSET_FLAT_COLUMNS)
.with_indexes(INDEXED)
.with_uniques(UNIQUE)
.with_edges(SQLITE_TAGS);
#[cfg(feature = "sqlite")]
const ASSET_FLAT_COLUMNS: &[Column] = &[
Column::new(FieldName::new("id"), SQLITE_INT, false),
Column::new(FieldName::new("title"), SQLITE_TEXT, true),
Column::new(FieldName::new("checksum"), SQLITE_TEXT, false),
];
#[cfg(feature = "sqlite")]
const _: () = assert!(describes(
&<Asset as Describe<sqlx::Sqlite>>::BLUEPRINT,
ASSET_COLUMNS
));
#[cfg(feature = "postgres")]
const _: () = assert!(describes(
&<Asset as Describe<sqlx::Postgres>>::BLUEPRINT,
ASSET_COLUMNS
));
#[cfg(feature = "mysql")]
const _: () = assert!(describes(
&<Asset as Describe<sqlx::MySql>>::BLUEPRINT,
ASSET_COLUMNS
));
#[cfg(feature = "sqlite")]
#[test]
fn a_shaped_descriptor_answers_shapes_where_a_flat_one_answers_columns() {
let shaped = <Asset as Describe<sqlx::Sqlite>>::BLUEPRINT.columns();
assert!(shaped.flat().is_none());
assert_eq!(shaped.shapes(), Some(ASSET_COLUMNS));
assert_eq!(shaped.width(), 3);
let flat = ASSET_FLAT.columns();
assert!(flat.shapes().is_none());
assert_eq!(flat.flat().map(<[Column]>::len), Some(3));
assert_eq!(flat.width(), 3);
assert!(matches!(shaped, TableColumns::Shaped { .. }));
assert!(matches!(flat, TableColumns::Flat(_)));
}
#[cfg(all(feature = "mediatime", feature = "sqlite"))]
#[test]
fn a_shaped_descriptor_answers_a_columns_word_by_the_name_the_renderer_joins() {
const CLIP: Table = <Clip as Describe<sqlx::Sqlite>>::BLUEPRINT;
assert_eq!(CLIP.stored(FieldName::new("id")), "INTEGER");
assert_eq!(CLIP.stored(FieldName::new("tb_num")), "INTEGER");
assert_eq!(CLIP.stored(FieldName::new("tb_den")), "INTEGER");
}
#[cfg(feature = "sqlite")]
#[test]
fn a_key_naming_a_segment_is_admitted_and_typed_by_the_field_that_owns_it() {
const COLUMNS: &[ColumnShape] = &[ColumnShape::Composite {
field: Some(ColumnName::new("tb")),
segments: &[ColumnShape::Plain(ColumnName::new("num"))],
}];
const KEYED: Table = Table::shaped(
RecordAddress::new(FieldName::new("keyed"), &[FieldName::new("tb_num")]),
COLUMNS,
&[<i32 as StoredAs<sqlx::Sqlite>>::WORDS],
&[false],
);
assert_eq!(KEYED.stored(FieldName::new("tb_num")), "INTEGER");
assert_eq!(
KEYED.create::<sqlx::Sqlite>().expect("it renders"),
[r#"CREATE TABLE IF NOT EXISTS "keyed" ("tb_num" INTEGER NOT NULL, PRIMARY KEY ("tb_num"))"#]
);
}
#[cfg(feature = "mediatime")]
struct Clip;
#[cfg(feature = "mediatime")]
const CLIP: RecordAddress = RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]);
#[cfg(feature = "mediatime")]
const CLIP_COLUMNS: &[ColumnShape] = &[
ColumnShape::Plain(ColumnName::new("id")),
crate::shape::<crate::Timebase>(ColumnName::new("tb")),
crate::shape::<crate::MediaTimeRange>(ColumnName::new("span")),
ColumnShape::Plain(ColumnName::new("title")),
];
#[cfg(all(feature = "mediatime", feature = "sqlite"))]
impl Describe<sqlx::Sqlite> for Clip {
const BLUEPRINT: Table = Table::shaped(
CLIP,
CLIP_COLUMNS,
&[
<i64 as StoredAs<sqlx::Sqlite>>::WORDS,
<crate::Timebase as StoredAs<sqlx::Sqlite>>::WORDS,
<crate::MediaTimeRange as StoredAs<sqlx::Sqlite>>::WORDS,
<Option<String> as StoredAs<sqlx::Sqlite>>::WORDS,
],
&[false, false, false, true],
);
}
#[cfg(all(feature = "mediatime", feature = "postgres"))]
impl Describe<sqlx::Postgres> for Clip {
const BLUEPRINT: Table = Table::shaped(
CLIP,
CLIP_COLUMNS,
&[
<i64 as StoredAs<sqlx::Postgres>>::WORDS,
<crate::Timebase as StoredAs<sqlx::Postgres>>::WORDS,
<crate::MediaTimeRange as StoredAs<sqlx::Postgres>>::WORDS,
<Option<String> as StoredAs<sqlx::Postgres>>::WORDS,
],
&[false, false, false, true],
);
}
#[cfg(all(feature = "mediatime", feature = "mysql"))]
impl Describe<sqlx::MySql> for Clip {
const BLUEPRINT: Table = Table::shaped(
CLIP,
CLIP_COLUMNS,
&[
<i64 as StoredAs<sqlx::MySql>>::WORDS,
<crate::Timebase as StoredAs<sqlx::MySql>>::WORDS,
<crate::MediaTimeRange as StoredAs<sqlx::MySql>>::WORDS,
<Option<String> as StoredAs<sqlx::MySql>>::WORDS,
],
&[false, false, false, true],
);
}
#[cfg(all(feature = "mediatime", feature = "sqlite"))]
const CLIP_FLAT: Table = Table::new(CLIP, CLIP_FLAT_COLUMNS);
#[cfg(all(feature = "mediatime", feature = "sqlite"))]
const CLIP_FLAT_COLUMNS: &[Column] = &[
Column::new(FieldName::new("id"), SQLITE_INT, false),
Column::new(FieldName::new("tb_num"), SQLITE_INT, false),
Column::new(FieldName::new("tb_den"), SQLITE_INT, false),
Column::new(FieldName::new("span_start_pts"), SQLITE_INT, false),
Column::new(FieldName::new("span_end_pts"), SQLITE_INT, false),
Column::new(FieldName::new("span_timebase_num"), SQLITE_INT, false),
Column::new(FieldName::new("span_timebase_den"), SQLITE_INT, false),
Column::new(FieldName::new("span_start_nanos"), SQLITE_INT, true),
Column::new(FieldName::new("span_end_nanos"), SQLITE_INT, true),
Column::new(FieldName::new("title"), SQLITE_TEXT, true),
];
#[cfg(feature = "mediatime")]
const _: () = assert!(CLIP_COLUMNS[2].width() == 6);
fn type_iter<V>(v: &mut V) -> Result<(), V::Error>
where
V: crate::TypeVisitor,
Asset: Describe<V::Db>,
{
v.next_type::<Asset>()
}
fn statements<Db: super::AsyncSchemaDialect>(table: &Table) -> Vec<String> {
table.create::<Db>().expect("this descriptor renders")
}
#[cfg(feature = "sqlite")]
mod sqlite {
use super::{Asset, Describe, statements};
#[test]
fn a_shaped_all_leaf_record_renders_its_whole_schema() {
assert_eq!(
statements::<sqlx::Sqlite>(&<Asset as Describe<sqlx::Sqlite>>::BLUEPRINT),
[
r#"CREATE TABLE IF NOT EXISTS "asset" ("id" INTEGER NOT NULL, "title" TEXT, "checksum" TEXT NOT NULL, PRIMARY KEY ("id"))"#,
r#"CREATE UNIQUE INDEX IF NOT EXISTS "__ig_asset_checksum" ON "asset" ("checksum")"#,
r#"CREATE INDEX IF NOT EXISTS "__ig_asset_title" ON "asset" ("title")"#,
r#"CREATE TABLE IF NOT EXISTS "asset_tags" ("id" INTEGER NOT NULL, "tags_ordinal" INTEGER NOT NULL, "tags" TEXT NOT NULL, PRIMARY KEY ("id", "tags_ordinal"))"#,
r#"CREATE INDEX IF NOT EXISTS "__ig_asset_tags_element" ON "asset_tags" ("id", "tags")"#,
]
);
}
#[test]
fn a_shaped_blueprint_and_its_hand_flat_twin_render_one_statement_sequence() {
assert_eq!(
statements::<sqlx::Sqlite>(&<Asset as Describe<sqlx::Sqlite>>::BLUEPRINT),
statements::<sqlx::Sqlite>(&super::ASSET_FLAT)
);
}
#[cfg(feature = "mediatime")]
#[test]
fn a_composite_field_renders_the_columns_its_type_names() {
assert_eq!(
statements::<sqlx::Sqlite>(&<super::Clip as Describe<sqlx::Sqlite>>::BLUEPRINT),
[
r#"CREATE TABLE IF NOT EXISTS "clip" ("id" INTEGER NOT NULL, "tb_num" INTEGER NOT NULL, "tb_den" INTEGER NOT NULL, "span_start_pts" INTEGER NOT NULL, "span_end_pts" INTEGER NOT NULL, "span_timebase_num" INTEGER NOT NULL, "span_timebase_den" INTEGER NOT NULL, "span_start_nanos" INTEGER, "span_end_nanos" INTEGER, "title" TEXT, PRIMARY KEY ("id"))"#,
]
);
}
#[cfg(feature = "mediatime")]
#[test]
fn the_composite_shaped_blueprint_matches_its_hand_flat_twin_byte_for_byte() {
assert_eq!(
statements::<sqlx::Sqlite>(&<super::Clip as Describe<sqlx::Sqlite>>::BLUEPRINT),
statements::<sqlx::Sqlite>(&super::CLIP_FLAT)
);
}
#[cfg(feature = "mediatime")]
#[test]
fn a_nullable_composite_field_renders_every_one_of_its_columns_nullable() {
const NULLABLE: crate::Table = crate::Table::shaped(
super::CLIP,
super::CLIP_COLUMNS,
&[
<i64 as crate::StoredAs<sqlx::Sqlite>>::WORDS,
<crate::Timebase as crate::StoredAs<sqlx::Sqlite>>::WORDS,
<Option<crate::MediaTimeRange> as crate::StoredAs<sqlx::Sqlite>>::WORDS,
<Option<String> as crate::StoredAs<sqlx::Sqlite>>::WORDS,
],
&[false, false, true, true],
);
assert_eq!(
statements::<sqlx::Sqlite>(&NULLABLE),
[
r#"CREATE TABLE IF NOT EXISTS "clip" ("id" INTEGER NOT NULL, "tb_num" INTEGER NOT NULL, "tb_den" INTEGER NOT NULL, "span_start_pts" INTEGER, "span_end_pts" INTEGER, "span_timebase_num" INTEGER, "span_timebase_den" INTEGER, "span_start_nanos" INTEGER, "span_end_nanos" INTEGER, "title" TEXT, PRIMARY KEY ("id"))"#,
]
);
}
}
#[cfg(feature = "postgres")]
mod postgres {
use super::{Asset, Describe, statements};
#[test]
fn a_shaped_all_leaf_record_renders_its_whole_schema() {
assert_eq!(
statements::<sqlx::Postgres>(&<Asset as Describe<sqlx::Postgres>>::BLUEPRINT),
[
r#"CREATE TABLE IF NOT EXISTS "asset" ("id" bigint NOT NULL, "title" text, "checksum" text NOT NULL, PRIMARY KEY ("id"))"#,
r#"CREATE UNIQUE INDEX IF NOT EXISTS "__ig_asset_checksum" ON "asset" ("checksum")"#,
r#"CREATE INDEX IF NOT EXISTS "__ig_asset_title" ON "asset" ("title")"#,
r#"CREATE TABLE IF NOT EXISTS "asset_tags" ("id" bigint NOT NULL, "tags_ordinal" bigint NOT NULL, "tags" text NOT NULL, PRIMARY KEY ("id", "tags_ordinal"))"#,
r#"CREATE INDEX IF NOT EXISTS "__ig_asset_tags_element" ON "asset_tags" ("id", "tags")"#,
]
);
}
#[cfg(feature = "mediatime")]
#[test]
fn a_composite_field_renders_the_columns_its_type_names() {
assert_eq!(
statements::<sqlx::Postgres>(&<super::Clip as Describe<sqlx::Postgres>>::BLUEPRINT),
[
r#"CREATE TABLE IF NOT EXISTS "clip" ("id" bigint NOT NULL, "tb_num" integer NOT NULL, "tb_den" integer NOT NULL, "span_start_pts" bigint NOT NULL, "span_end_pts" bigint NOT NULL, "span_timebase_num" integer NOT NULL, "span_timebase_den" integer NOT NULL, "span_start_nanos" bigint, "span_end_nanos" bigint, "title" text, PRIMARY KEY ("id"))"#,
]
);
}
}
#[cfg(feature = "mysql")]
mod mysql {
use super::{Asset, Describe, statements};
#[test]
fn a_shaped_all_leaf_record_renders_its_whole_schema() {
assert_eq!(
statements::<sqlx::MySql>(&<Asset as Describe<sqlx::MySql>>::BLUEPRINT),
[
"CREATE TABLE IF NOT EXISTS `asset` (`id` bigint NOT NULL, `title` varchar(255), `checksum` varchar(255) NOT NULL, PRIMARY KEY (`id`))",
"CREATE UNIQUE INDEX IF NOT EXISTS `__ig_asset_checksum` ON `asset` (`checksum`)",
"CREATE INDEX IF NOT EXISTS `__ig_asset_title` ON `asset` (`title`)",
"CREATE TABLE IF NOT EXISTS `asset_tags` (`id` bigint NOT NULL, `tags_ordinal` BIGINT NOT NULL, `tags` varchar(255) NOT NULL, PRIMARY KEY (`id`, `tags_ordinal`))",
"CREATE INDEX IF NOT EXISTS `__ig_asset_tags_element` ON `asset_tags` (`id`, `tags`)",
]
);
}
#[cfg(feature = "mediatime")]
#[test]
fn a_composite_field_renders_the_columns_its_type_names() {
assert_eq!(
statements::<sqlx::MySql>(&<super::Clip as Describe<sqlx::MySql>>::BLUEPRINT),
[
"CREATE TABLE IF NOT EXISTS `clip` (`id` bigint NOT NULL, `tb_num` int NOT NULL, `tb_den` int NOT NULL, `span_start_pts` bigint NOT NULL, `span_end_pts` bigint NOT NULL, `span_timebase_num` int NOT NULL, `span_timebase_den` int NOT NULL, `span_start_nanos` bigint, `span_end_nanos` bigint, `title` varchar(255), PRIMARY KEY (`id`))",
]
);
}
}
#[cfg(feature = "sqlite")]
mod live {
use sqlx::Sqlite;
use super::type_iter;
use crate::query::sql::{Create, SqlSchemaError, Validate};
async fn empty() -> sqlx::sqlite::SqliteConnection {
use sqlx::Connection as _;
sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
.await
.expect("an in-memory database")
}
async fn create(db: &mut sqlx::sqlite::SqliteConnection) -> Result<(), SqlSchemaError> {
let mut create = Create::<Sqlite>::new();
type_iter(&mut create)?;
create.run(db).await
}
#[cfg(feature = "mediatime")]
async fn create_clip(db: &mut sqlx::sqlite::SqliteConnection) -> Result<(), SqlSchemaError> {
let mut create = Create::<Sqlite>::new();
crate::TypeVisitor::next_type::<super::Clip>(&mut create)?;
create.run(db).await
}
async fn validate(db: &mut sqlx::sqlite::SqliteConnection) -> Result<(), SqlSchemaError> {
let mut validate = Validate::<Sqlite>::new();
type_iter(&mut validate)?;
validate.audit(db).await
}
#[cfg(feature = "mediatime")]
async fn echoed(db: &mut sqlx::sqlite::SqliteConnection, table: &str) -> Vec<(String, String)> {
sqlx::query_as::<_, (String, String)>(
r#"SELECT "name", "type" FROM pragma_table_info(?) ORDER BY "cid""#,
)
.bind(table)
.fetch_all(db)
.await
.expect("the catalogue answers")
}
#[cfg(feature = "mediatime")]
#[tokio::test]
async fn a_live_engine_takes_the_joined_columns_and_names_them_back() {
let mut db = empty().await;
create_clip(&mut db).await.expect("the engine takes it");
assert_eq!(
echoed(&mut db, "clip").await,
[
("id", "INTEGER"),
("tb_num", "INTEGER"),
("tb_den", "INTEGER"),
("span_start_pts", "INTEGER"),
("span_end_pts", "INTEGER"),
("span_timebase_num", "INTEGER"),
("span_timebase_den", "INTEGER"),
("span_start_nanos", "INTEGER"),
("span_end_nanos", "INTEGER"),
("title", "TEXT"),
]
.map(|(name, ty)| (name.to_owned(), ty.to_owned()))
);
}
#[tokio::test]
async fn the_audit_passes_the_shaped_schema_the_create_made() {
let mut db = empty().await;
create(&mut db).await.expect("the schema is created");
validate(&mut db).await.expect("and it is the declared one");
}
#[cfg(feature = "mediatime")]
#[tokio::test]
async fn a_dropped_segment_column_is_named_as_the_renderer_joins_it() {
let mut db = empty().await;
create_clip(&mut db).await.expect("the schema is created");
sqlx::query(r#"ALTER TABLE "clip" DROP COLUMN "span_timebase_den""#)
.execute(&mut db)
.await
.expect("the drift is applied");
let mut validate = Validate::<Sqlite>::new();
crate::TypeVisitor::next_type::<super::Clip>(&mut validate)
.expect("collecting refuses nothing");
let Err(SqlSchemaError::Column { table, column }) = validate.audit(&mut db).await else {
panic!("a declared column that is gone is drift");
};
assert_eq!(table, crate::FieldName::new("clip"));
assert_eq!(column, "span_timebase_den");
}
#[tokio::test]
async fn a_second_create_over_the_same_database_changes_nothing() {
let mut db = empty().await;
create(&mut db).await.expect("the first create lands");
create(&mut db).await.expect("and so does the second");
validate(&mut db).await.expect("and it is still declared");
}
#[tokio::test]
async fn the_unique_word_on_a_shaped_descriptor_refuses_a_duplicate() {
let mut db = empty().await;
create(&mut db).await.expect("the schema is created");
sqlx::query(r#"INSERT INTO "asset" ("id", "checksum") VALUES (1, 'abc')"#)
.execute(&mut db)
.await
.expect("the first row lands");
let Err(why) = sqlx::query(r#"INSERT INTO "asset" ("id", "checksum") VALUES (2, 'abc')"#)
.execute(&mut db)
.await
else {
panic!("a second row with the same checksum is what the unique word refuses");
};
assert!(
why.to_string().contains("UNIQUE constraint failed"),
"the engine's own sentence: {why}"
);
}
}