#![cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
use crate::{Column, Describe, FieldName, RecordAddress, Table, TypeVisitor, query::sql::Create};
struct Asset;
const ASSET: RecordAddress = RecordAddress::new(FieldName::new("asset"), &[FieldName::new("id")]);
const INDEXED: &[&FieldName] = &[FieldName::new("title"), FieldName::new("codec")];
#[cfg(feature = "sqlite")]
impl Describe<sqlx::Sqlite> for Asset {
const BLUEPRINT: Table = Table::new(
ASSET,
&[
Column::new(FieldName::new("id"), "INTEGER", false),
Column::new(FieldName::new("title"), "TEXT", false),
Column::new(FieldName::new("codec"), "TEXT", false),
Column::new(FieldName::new("notes"), "TEXT", true),
],
)
.with_indexes(INDEXED);
}
#[cfg(feature = "postgres")]
impl Describe<sqlx::Postgres> for Asset {
const BLUEPRINT: Table = Table::new(
ASSET,
&[
Column::new(FieldName::new("id"), "bigint", false),
Column::new(FieldName::new("title"), "text", false),
Column::new(FieldName::new("codec"), "text", false),
Column::new(FieldName::new("notes"), "text", true),
],
)
.with_indexes(INDEXED);
}
#[cfg(feature = "mysql")]
impl Describe<sqlx::MySql> for Asset {
const BLUEPRINT: Table = Table::new(
ASSET,
&[
Column::new(FieldName::new("id"), "BIGINT", false),
Column::new(FieldName::new("title"), "VARCHAR(255)", false),
Column::new(FieldName::new("codec"), "VARCHAR(255)", false),
Column::new(FieldName::new("notes"), "VARCHAR(255)", true),
],
)
.with_indexes(INDEXED);
}
fn type_iter<V>(v: &mut V) -> Result<(), V::Error>
where
V: TypeVisitor,
Asset: Describe<V::Db>,
{
v.next_type::<Asset>()
}
fn schema<Db>() -> Vec<String>
where
Db: super::AsyncSchemaDialect,
Asset: Describe<Db>,
{
let mut create = Create::<Db>::new();
type_iter(&mut create).expect("this descriptor renders");
create.statements().to_vec()
}
#[cfg(feature = "sqlite")]
#[test]
fn sqlite_creates_one_index_per_indexed_field() {
assert_eq!(
schema::<sqlx::Sqlite>(),
[
r#"CREATE TABLE IF NOT EXISTS "asset" ("id" INTEGER NOT NULL, "title" TEXT NOT NULL, "codec" TEXT NOT NULL, "notes" TEXT, PRIMARY KEY ("id"))"#,
r#"CREATE INDEX IF NOT EXISTS "__ig_asset_title" ON "asset" ("title")"#,
r#"CREATE INDEX IF NOT EXISTS "__ig_asset_codec" ON "asset" ("codec")"#,
]
);
}
#[cfg(feature = "sqlite")]
#[test]
fn the_derived_name_wears_the_domain_prefix() {
let statements = schema::<sqlx::Sqlite>();
let create_index = &statements[1];
let start = create_index
.find('"')
.expect("the statement quotes the index name");
let end = create_index[start + 1..]
.find('"')
.expect("the quote closes")
+ start
+ 1;
let derived_name = &create_index[start + 1..end];
assert_eq!(
derived_name, "__ig_asset_title",
"`__ig_<table>_<field>` is the whole rule, and `asset`/`title` are this suite's own \
table/column — a name that stopped starting with `__ig_` would still pass every OTHER \
assertion in this file that only checks the statement contains its own name",
);
}
#[cfg(feature = "postgres")]
#[test]
fn postgres_creates_one_index_per_indexed_field() {
assert_eq!(
schema::<sqlx::Postgres>(),
[
r#"CREATE TABLE IF NOT EXISTS "asset" ("id" bigint NOT NULL, "title" text NOT NULL, "codec" text NOT NULL, "notes" text, PRIMARY KEY ("id"))"#,
r#"CREATE INDEX IF NOT EXISTS "__ig_asset_title" ON "asset" ("title")"#,
r#"CREATE INDEX IF NOT EXISTS "__ig_asset_codec" ON "asset" ("codec")"#,
]
);
}
#[cfg(feature = "mysql")]
#[test]
fn mysql_brackets_the_index_name_with_its_own_quote() {
assert_eq!(
schema::<sqlx::MySql>(),
[
"CREATE TABLE IF NOT EXISTS `asset` (`id` BIGINT NOT NULL, `title` VARCHAR(255) NOT NULL, \
`codec` VARCHAR(255) NOT NULL, `notes` VARCHAR(255), PRIMARY KEY (`id`))",
"CREATE INDEX IF NOT EXISTS `__ig_asset_title` ON `asset` (`title`)",
"CREATE INDEX IF NOT EXISTS `__ig_asset_codec` ON `asset` (`codec`)",
]
);
}
#[cfg(feature = "sqlite")]
#[test]
fn a_table_with_no_indexed_field_renders_no_index() {
const BARE: Table = Table::new(
ASSET,
&[Column::new(FieldName::new("id"), "INTEGER", false)],
);
assert!(BARE.indexes().is_empty());
assert_eq!(
BARE
.create::<sqlx::Sqlite>()
.expect("this descriptor renders"),
[r#"CREATE TABLE IF NOT EXISTS "asset" ("id" INTEGER NOT NULL, PRIMARY KEY ("id"))"#]
);
}
#[cfg(feature = "sqlite")]
mod live {
use sqlx::Sqlite;
use super::type_iter;
use crate::query::sql::{Create, SqlSchemaError};
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
}
async fn indexes(db: &mut sqlx::sqlite::SqliteConnection) -> Vec<String> {
sqlx::query_scalar::<_, String>(
"SELECT name FROM sqlite_schema WHERE type = 'index' AND sql IS NOT NULL ORDER BY name",
)
.fetch_all(db)
.await
.expect("the catalogue answers")
}
async fn columns_of(db: &mut sqlx::sqlite::SqliteConnection, index: &str) -> Vec<String> {
sqlx::query_scalar::<_, String>("SELECT name FROM pragma_index_info(?) ORDER BY seqno")
.bind(index)
.fetch_all(db)
.await
.expect("the catalogue answers")
}
#[tokio::test]
async fn the_engine_builds_one_index_per_indexed_field() {
let mut db = empty().await;
create(&mut db).await.expect("an empty database takes it");
assert_eq!(
indexes(&mut db).await,
["__ig_asset_codec", "__ig_asset_title"]
);
assert_eq!(columns_of(&mut db, "__ig_asset_title").await, ["title"]);
assert_eq!(columns_of(&mut db, "__ig_asset_codec").await, ["codec"]);
}
#[tokio::test]
async fn a_second_create_adds_no_second_index() {
let mut db = empty().await;
create(&mut db).await.expect("the first create lands");
create(&mut db).await.expect("and so does the second");
assert_eq!(
indexes(&mut db).await,
["__ig_asset_codec", "__ig_asset_title"]
);
}
}