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 AN INDEXED FIELD CREATES — one statement per field, named from the table it is on, and the
//! order the walk sends them in.
//!
//! A suite of its own beside [`super::tests`], for the reason the `sortable` suite next to it gives:
//! what is asserted here is ONE word's effect on the schema — which fields get a statement, what each
//! is called, and what a field that asked for nothing gets — and holding that apart from the graph's
//! own statements keeps a change to either visible.
//!
//! # It carries TWO indexed fields, which the graph corpus never has
//!
//! [`super::tests`] declares one indexed field across its whole graph, so two questions have never
//! been put to the walk: whether a second field gets a statement of its own rather than joining the
//! first, and whether the two arrive in the order the descriptor named them. A composite index is
//! not expressible — [`Table::with_indexes`](crate::Table::with_indexes) says so — and this is the
//! suite that shows what the list does instead.
//!
//! # What was MEASURED, and what was only RENDERED
//!
//! SQLite is put to an engine: the two indexes are read back out of the catalogue and a second create
//! runs over the same connection. PostgreSQL and MySQL are RENDERED — this repository provisions no
//! server, which is the posture the whole SQL family takes.
//!
//! One consequence of that posture is worth writing down where the golden is: **MySQL's own
//! `CREATE INDEX` grammar has no `IF NOT EXISTS` clause** (it is a MariaDB extension; `CREATE TABLE
//! IF NOT EXISTS` is a different statement and MySQL does take that one). So the MySQL golden below
//! records what this dialect is SENT and not what an engine answered, and whether the send is taken
//! is a question no test in this repository can ask today.

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

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

/// A record with TWO indexed fields and one that asked for nothing.
///
/// One key column, so the statements below are about the indexes and not about a key chain: a
/// single-column key is already unique under its own `PRIMARY KEY`, so no `UNIQUE` clause joins them
/// either.
struct Asset;

const ASSET: RecordAddress = RecordAddress::new(FieldName::new("asset"), &[FieldName::new("id")]);

/// The two fields an index is asked for at, in the order the descriptor names them — which is the
/// order the walk is expected to send, and the whole point of naming two.
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);
}

/// 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,
  Asset: Describe<V::Db>,
{
  v.next_type::<Asset>()
}

/// Every statement the node renders for one dialect, in walk order.
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()
}

/// SQLite: the table, then ONE statement per indexed field, each named `__ig_<table>_<field>` — and the
/// field that asked for nothing has none.
#[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")"#,
    ]
  );
}

/// **THE PREFIX, PINNED ALONE** — the 2026-08-30 ruling's own domain mark, asserted apart from the
/// fuller statement goldens around it so a future de-prefixing is a deliberate red HERE rather than
/// a diff a reader has to notice inside a longer string. `__ig_<table>_<field>` is the whole rule:
/// this is `asset` and `title`, the known table/column this suite already declares, and the derived
/// name is checked as its own value rather than as a substring of the statement that carries it.
#[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",
  );
}

/// PostgreSQL: the same three statements, in this dialect's own type words. The identifier bracket is
/// the double quote here as it is for SQLite, so what this golden holds apart from its neighbour is
/// the TYPES and not the quoting.
#[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")"#,
    ]
  );
}

/// MySQL: the BACKTICK is this dialect's identifier bracket, and the index name is bracketed exactly
/// as the table and the column are.
///
/// This golden records what MySQL is SENT. See the module note: MySQL's `CREATE INDEX` takes no
/// `IF NOT EXISTS`, so what an engine answers to this is a question no test here can ask.
#[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`)",
    ]
  );
}

/// **A DESCRIPTOR THAT ASKS FOR NOTHING GETS NOTHING.** The absent list is the common case — see
/// [`Table::new`](crate::Table::new), which leaves it empty — and a walk that indexed a column by
/// default would be one no declaration had asked for.
///
/// It is asserted rather than assumed because the default is what a future emitter would have to keep:
/// a record whose fields carry no word must render the same statements it renders today.
#[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"))"#]
  );
}

/// The half no statement's text can show, put to a real engine.
#[cfg(feature = "sqlite")]
mod live {
  use sqlx::Sqlite;

  use super::type_iter;
  use crate::query::sql::{Create, SqlSchemaError};

  /// An EMPTY in-memory database, on ONE connection.
  ///
  /// A bare [`SqliteConnection`](sqlx::sqlite::SqliteConnection) and never a `Pool`, for the reason
  /// the graph corpus beside this one states: this crate enables no sqlx runtime, so a pool would
  /// panic spawning its reaper. No foreign-key pragma here — this suite declares no provenance table,
  /// so there is no constraint for one to switch on.
  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::<Sqlite>::new();
    type_iter(&mut create)?;
    create.run(db).await
  }

  /// Every index SQLite holds that a `CREATE INDEX` made, in name order. The implicit ones a `UNIQUE`
  /// or a primary key builds are excluded — they carry no `sql`, which is exactly what tells them
  /// apart.
  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")
  }

  /// Which columns SQLite says one index is over, in index order — `PRAGMA index_info`'s own answer,
  /// which is the only party that can say an index is over the column the declaration named rather
  /// than merely that a name exists.
  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")
  }

  /// **BOTH INDEXES EXIST**, and each is over the ONE column its field named — which no rendering
  /// assertion can say, and which is the claim a single-column index word rests on.
  #[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"]);
  }

  /// **A SECOND CREATE IS THE SAME CREATE.** `IF NOT EXISTS` is what makes a boot sequence safe to
  /// re-run, and an index is the statement where that matters most: the lane opens no transaction, so
  /// a run that stopped between two of them finishes on the next one rather than refusing.
  #[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"]
    );
  }
}