ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
//! WHAT A UNIQUE FIELD CREATES — one CONSTRAINT-bearing statement per field, the same naming rule
//! [`super::index_tests`] states for a plain one, and the ONE statement a field wearing BOTH words
//! renders.
//!
//! A suite of its own beside [`super::index_tests`], for the reason that suite already gives: what
//! is asserted here is ONE word's effect on the schema, held apart from the graph's own statements
//! and from `indexed`'s so a change to any one of the three stays visible.
//!
//! # It carries THREE marked fields, which is what the four-state ruling asks to be shown at once
//!
//! `label` is `indexed` alone, `checksum` is `unique` alone, and `slug` is BOTH — the fourth
//! state, `notes`, asks for neither and gets nothing. The interesting claim is `slug`'s: a field
//! wearing both words renders ONE statement, a `CREATE UNIQUE INDEX`, and not two — see
//! [`Table::create`]'s own note, which is the argument this suite pins rather than restates.
//!
//! # What was MEASURED, and what was only RENDERED
//!
//! SQLite is put to an engine, for two claims a rendering assertion cannot make on its own: that an
//! index the catalogue holds is actually UNIQUE, and that the engine itself refuses a value
//! colliding with one — by name, whether the write that tried it was a plain `INSERT` or a KEYED
//! REPLACE landing on a different row's constraint. PostgreSQL and MySQL are RENDERED, this
//! repository's usual posture where no server is provisioned.
//!
//! The write-lane tests below run raw statements rather than this crate's own [`insert`]/[`upsert`]
//! — what they measure is the DDL's own constraint reaching the engine, which the statement TEXT
//! already proves is the same text those functions render over a `unique` column; a second, hand
//! written `SqlWrite` fixture would re-prove the write lane's binding machinery that
//! `query::sql::write::tests` already covers, and not this suite's own subject.
//!
//! [`insert`]: super::super::insert
//! [`upsert`]: super::super::upsert

#![cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]

use crate::{Column, Describe, FieldName, RecordAddress, Table, TypeVisitor, query::sql::Create};

/// A record with THREE marked fields — INDEXED alone, UNIQUE alone, and BOTH — and one that
/// asks for neither.
struct Media;

const MEDIA: RecordAddress = RecordAddress::new(FieldName::new("media"), &[FieldName::new("id")]);

/// The fields `indexed` names — one of them (`slug`) ALSO `unique`.
const INDEXED: &[&FieldName] = &[FieldName::new("label"), FieldName::new("slug")];

/// The fields `unique` names — one of them (`slug`) ALSO `indexed`.
const UNIQUE: &[&FieldName] = &[FieldName::new("checksum"), FieldName::new("slug")];

#[cfg(feature = "sqlite")]
impl Describe<sqlx::Sqlite> for Media {
  const BLUEPRINT: Table = Table::new(
    MEDIA,
    &[
      Column::new(FieldName::new("id"), "INTEGER", false),
      Column::new(FieldName::new("label"), "TEXT", false),
      Column::new(FieldName::new("checksum"), "TEXT", false),
      Column::new(FieldName::new("slug"), "TEXT", false),
      Column::new(FieldName::new("notes"), "TEXT", true),
    ],
  )
  .with_indexes(INDEXED)
  .with_uniques(UNIQUE);
}

#[cfg(feature = "postgres")]
impl Describe<sqlx::Postgres> for Media {
  const BLUEPRINT: Table = Table::new(
    MEDIA,
    &[
      Column::new(FieldName::new("id"), "bigint", false),
      Column::new(FieldName::new("label"), "text", false),
      Column::new(FieldName::new("checksum"), "text", false),
      Column::new(FieldName::new("slug"), "text", false),
      Column::new(FieldName::new("notes"), "text", true),
    ],
  )
  .with_indexes(INDEXED)
  .with_uniques(UNIQUE);
}

#[cfg(feature = "mysql")]
impl Describe<sqlx::MySql> for Media {
  const BLUEPRINT: Table = Table::new(
    MEDIA,
    &[
      Column::new(FieldName::new("id"), "BIGINT", false),
      Column::new(FieldName::new("label"), "VARCHAR(255)", false),
      Column::new(FieldName::new("checksum"), "VARCHAR(255)", false),
      Column::new(FieldName::new("slug"), "VARCHAR(255)", false),
      Column::new(FieldName::new("notes"), "VARCHAR(255)", true),
    ],
  )
  .with_indexes(INDEXED)
  .with_uniques(UNIQUE);
}

/// The walk a graph root writes, over the one node this suite declares.
fn type_iter<V>(v: &mut V) -> Result<(), V::Error>
where
  V: TypeVisitor,
  Media: Describe<V::Db>,
{
  v.next_type::<Media>()
}

/// Every statement the node renders for one dialect, in walk order.
fn schema<Db>() -> Vec<String>
where
  Db: super::AsyncSchemaDialect,
  Media: Describe<Db>,
{
  let mut create = Create::<Db>::new();
  type_iter(&mut create).expect("this descriptor renders");
  create.statements().to_vec()
}

/// SQLite: the table, then ONE `CREATE UNIQUE INDEX` per unique field — `checksum` first and
/// `slug` second, the order [`UNIQUE`] names them in — and then ONE `CREATE INDEX` for the field
/// that is `indexed` and not ALSO `unique`. `slug` does not appear twice: it is `indexed` too, and
/// the plain statement it would otherwise have earned is exactly the one [`Table::create`]'s note
/// says never renders.
#[cfg(feature = "sqlite")]
#[test]
fn sqlite_dedups_the_field_wearing_both_words_to_one_unique_statement() {
  assert_eq!(
    schema::<sqlx::Sqlite>(),
    [
      r#"CREATE TABLE IF NOT EXISTS "media" ("id" INTEGER NOT NULL, "label" TEXT NOT NULL, "checksum" TEXT NOT NULL, "slug" TEXT NOT NULL, "notes" TEXT, PRIMARY KEY ("id"))"#,
      r#"CREATE UNIQUE INDEX IF NOT EXISTS "__ig_media_checksum" ON "media" ("checksum")"#,
      r#"CREATE UNIQUE INDEX IF NOT EXISTS "__ig_media_slug" ON "media" ("slug")"#,
      r#"CREATE INDEX IF NOT EXISTS "__ig_media_label" ON "media" ("label")"#,
    ]
  );
}

/// PostgreSQL: the same four statements, in this dialect's own type words.
#[cfg(feature = "postgres")]
#[test]
fn postgres_dedups_the_field_wearing_both_words_to_one_unique_statement() {
  assert_eq!(
    schema::<sqlx::Postgres>(),
    [
      r#"CREATE TABLE IF NOT EXISTS "media" ("id" bigint NOT NULL, "label" text NOT NULL, "checksum" text NOT NULL, "slug" text NOT NULL, "notes" text, PRIMARY KEY ("id"))"#,
      r#"CREATE UNIQUE INDEX IF NOT EXISTS "__ig_media_checksum" ON "media" ("checksum")"#,
      r#"CREATE UNIQUE INDEX IF NOT EXISTS "__ig_media_slug" ON "media" ("slug")"#,
      r#"CREATE INDEX IF NOT EXISTS "__ig_media_label" ON "media" ("label")"#,
    ]
  );
}

/// MySQL: the backtick bracket, and the same posture [`super::index_tests`] records — this
/// dialect's own `CREATE INDEX`/`CREATE UNIQUE INDEX` take no `IF NOT EXISTS`, so this golden is
/// what MySQL is SENT and not what an engine answered.
#[cfg(feature = "mysql")]
#[test]
fn mysql_dedups_the_field_wearing_both_words_to_one_unique_statement() {
  assert_eq!(
    schema::<sqlx::MySql>(),
    [
      "CREATE TABLE IF NOT EXISTS `media` (`id` BIGINT NOT NULL, `label` VARCHAR(255) NOT NULL, \
       `checksum` VARCHAR(255) NOT NULL, `slug` VARCHAR(255) NOT NULL, `notes` VARCHAR(255), \
       PRIMARY KEY (`id`))",
      "CREATE UNIQUE INDEX IF NOT EXISTS `__ig_media_checksum` ON `media` (`checksum`)",
      "CREATE UNIQUE INDEX IF NOT EXISTS `__ig_media_slug` ON `media` (`slug`)",
      "CREATE INDEX IF NOT EXISTS `__ig_media_label` ON `media` (`label`)",
    ]
  );
}

/// **A DESCRIPTOR THAT ASKS FOR NOTHING GETS NOTHING** — [`super::index_tests`]'s own claim,
/// pinned again over [`Table::uniques`] rather than [`Table::indexes`].
#[cfg(feature = "sqlite")]
#[test]
fn a_table_with_no_unique_field_renders_no_unique_index() {
  const BARE: Table = Table::new(
    MEDIA,
    &[Column::new(FieldName::new("id"), "INTEGER", false)],
  );

  assert!(BARE.uniques().is_empty());
  assert_eq!(
    BARE
      .create::<sqlx::Sqlite>()
      .expect("this descriptor renders"),
    [r#"CREATE TABLE IF NOT EXISTS "media" ("id" INTEGER NOT NULL, PRIMARY KEY ("id"))"#]
  );
}

/// The half no statement's text can show, put to a real engine.
#[cfg(feature = "sqlite")]
mod live {
  use super::type_iter;
  use crate::query::sql::{Create, SqlSchemaError};

  /// An EMPTY in-memory database, on ONE connection — [`super::super::index_tests::live`]'s own
  /// reason for a bare connection over a pool.
  async fn empty() -> sqlx::sqlite::SqliteConnection {
    use sqlx::Connection as _;

    sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
      .await
      .expect("an in-memory database")
  }

  /// Create this suite's schema on `db`.
  async fn create(db: &mut sqlx::sqlite::SqliteConnection) -> Result<(), SqlSchemaError> {
    let mut create = Create::<sqlx::Sqlite>::new();
    type_iter(&mut create)?;
    create.run(db).await
  }

  /// Every index SQLite holds for `table`, in name order, with whether the catalogue calls it
  /// UNIQUE — `PRAGMA index_list`'s own answer, which is the only party that can say a `CREATE
  /// UNIQUE INDEX` actually became a unique constraint rather than merely a statement that
  /// rendered.
  async fn index_flags(
    db: &mut sqlx::sqlite::SqliteConnection,
    table: &str,
  ) -> Vec<(String, bool)> {
    sqlx::query_as::<_, (String, i64)>(
      r#"SELECT name, "unique" FROM pragma_index_list(?) ORDER BY name"#,
    )
    .bind(table)
    .fetch_all(db)
    .await
    .expect("the catalogue answers")
    .into_iter()
    .map(|(name, unique)| (name, unique != 0))
    .collect()
  }

  /// **EVERY UNIQUE FIELD'S INDEX IS MARKED UNIQUE, AND NO OTHER ONE IS** — the claim no
  /// rendering assertion can make, since the TEXT of a `CREATE UNIQUE INDEX` could still be sent
  /// to an engine that silently downgraded it. It also pins the dedup a second way: `__ig_media_slug`
  /// appears exactly ONCE in this list, which it could not if the plain statement `slug` would
  /// otherwise have earned had also rendered.
  #[tokio::test]
  async fn the_engine_marks_each_index_unique_exactly_where_the_word_was_written() {
    let mut db = empty().await;
    create(&mut db).await.expect("an empty database takes it");

    assert_eq!(
      index_flags(&mut db, "media").await,
      [
        ("__ig_media_checksum".to_owned(), true),
        ("__ig_media_label".to_owned(), false),
        ("__ig_media_slug".to_owned(), true),
      ]
    );
  }

  /// **A SECOND CREATE IS THE SAME CREATE** — [`super::super::index_tests::live`]'s own claim,
  /// over a schema that also carries `UNIQUE` constraints this time.
  #[tokio::test]
  async fn a_second_create_adds_no_second_unique_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!(
      index_flags(&mut db, "media").await,
      [
        ("__ig_media_checksum".to_owned(), true),
        ("__ig_media_label".to_owned(), false),
        ("__ig_media_slug".to_owned(), true),
      ]
    );
  }

  /// One row, written with a RAW statement — see the module note for why this suite binds
  /// directly rather than through this crate's own [`insert`](crate::query::sql::insert): the
  /// statement TEXT is what a plain `INSERT` over these columns already is, and what this suite
  /// measures is the engine's reaction to it, not the write lane's own binding machinery.
  async fn insert_row(
    db: &mut sqlx::sqlite::SqliteConnection,
    id: i64,
    label: &str,
    checksum: &str,
    slug: &str,
  ) -> Result<sqlx::sqlite::SqliteQueryResult, sqlx::Error> {
    sqlx::query(r#"INSERT INTO "media" ("id", "label", "checksum", "slug") VALUES (?, ?, ?, ?)"#)
      .bind(id)
      .bind(label)
      .bind(checksum)
      .bind(slug)
      .execute(db)
      .await
  }

  /// The SAME row, through the KEYED REPLACE this crate's `upsert` renders for SQLite —
  /// `ON CONFLICT ("id") DO UPDATE SET …` — see
  /// [`Upsert::push_upsert`](crate::query::sql::Upsert).
  async fn upsert_row(
    db: &mut sqlx::sqlite::SqliteConnection,
    id: i64,
    label: &str,
    checksum: &str,
    slug: &str,
  ) -> Result<sqlx::sqlite::SqliteQueryResult, sqlx::Error> {
    sqlx::query(
      r#"INSERT INTO "media" ("id", "label", "checksum", "slug") VALUES (?, ?, ?, ?)
         ON CONFLICT ("id") DO UPDATE SET "label" = excluded."label",
           "checksum" = excluded."checksum", "slug" = excluded."slug""#,
    )
    .bind(id)
    .bind(label)
    .bind(checksum)
    .bind(slug)
    .execute(db)
    .await
  }

  /// **A DUPLICATE INSERT INTO A UNIQUE COLUMN REFUSES BY NAME** — a [`sqlx::Error::Database`]
  /// the driver itself calls a unique violation, naming the COLUMN in its own sentence, never a
  /// panic.
  #[tokio::test]
  async fn a_duplicate_insert_into_a_unique_column_refuses_by_name() {
    let mut db = empty().await;
    create(&mut db).await.expect("an empty database takes it");
    insert_row(&mut db, 1, "a", "sha256:aaa", "slug-a")
      .await
      .expect("the first row lands");

    let refused = insert_row(&mut db, 2, "b", "sha256:aaa", "slug-b").await;
    let Err(sqlx::Error::Database(why)) = refused else {
      panic!("a colliding unique column is the engine's own refusal, not a panic: {refused:?}");
    };
    assert!(
      why.is_unique_violation(),
      "the driver names it as one: {why}"
    );
    assert!(
      why.message().contains("media.checksum"),
      "the engine's own sentence names the TABLE and the COLUMN: {why}"
    );
    assert_eq!(
      sqlx::query_scalar::<_, i64>(r#"SELECT count(*) FROM "media""#)
        .fetch_one(&mut db)
        .await
        .expect("the parent table is there"),
      1,
      "and nothing was written twice"
    );
  }

  /// **AN UPSERT-BY-ID UPDATING A UNIQUE COLUMN TO A COLLIDING VALUE REFUSES.**
  ///
  /// The KEYED REPLACE targets `id = 2` alone — [`insert`](crate::query::sql::insert)'s own note
  /// argues why `upsert` does not also read `checksum`'s constraint: it is row 1's, a DIFFERENT
  /// row's, and a value colliding with it still answers here exactly as a first `insert` would.
  ///
  /// Row 2 is asserted UNCHANGED afterwards, which is the half no rendered statement can show: the
  /// failed `DO UPDATE` touches nothing, rather than leaving row 2 partially written.
  #[tokio::test]
  async fn an_upsert_by_id_updating_a_unique_column_to_a_colliding_value_refuses() {
    let mut db = empty().await;
    create(&mut db).await.expect("an empty database takes it");
    insert_row(&mut db, 1, "a", "sha256:aaa", "slug-a")
      .await
      .expect("the first row lands");
    upsert_row(&mut db, 2, "b", "sha256:bbb", "slug-b")
      .await
      .expect("a fresh address is a plain insert");

    let refused = upsert_row(&mut db, 2, "b2", "sha256:aaa", "slug-b2").await;
    let Err(sqlx::Error::Database(why)) = refused else {
      panic!("a colliding unique column is the engine's own refusal, not a panic: {refused:?}");
    };
    assert!(
      why.is_unique_violation(),
      "the driver names it as one: {why}"
    );
    assert!(
      why.message().contains("checksum"),
      "the engine's own sentence names the COLUMN: {why}"
    );

    let (label, checksum, slug): (String, String, String) =
      sqlx::query_as(r#"SELECT "label", "checksum", "slug" FROM "media" WHERE "id" = 2"#)
        .fetch_one(&mut db)
        .await
        .expect("row 2 is still there");
    assert_eq!(
      (label.as_str(), checksum.as_str(), slug.as_str()),
      ("b", "sha256:bbb", "slug-b"),
      "the failed keyed replace touched nothing"
    );
  }
}