ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! WHAT THE `sortable` WORD EMITS — the write plan's companion entry, the term's subject, and the
//! dialect that emits neither.
//!
//! A suite of its own beside [`crate::tests`], for the reason the tracing word's is: what is
//! asserted here is ONE word's emission — which items it grows, per dialect — and a build that never
//! wrote the word getting back exactly the tokens it got before it existed.
//!
//! # The three rows, which are the ruling read off the emission
//!
//! | dialect | the collection lives | what the word emits |
//! |---|---|---|
//! | SQLite, MySQL | an edge table, always | `SHADOWS`, and a term whose subject is the companion |
//! | PostgreSQL, no `edge` word | a native array on the row | NOTHING — the array orders itself |
//!
//! The PostgreSQL row is the one worth an assertion of its own. The word is DECLARED there just as
//! loudly, and the answer is per backend rather than per declaration: a dialect that already orders
//! the collection has nothing for a companion to carry, so emitting one would be a column written on
//! every insert and read by nothing.

use crate::{
  alias::sort_column,
  model::RecordModel,
  prefix::EmissionPrefix,
  tests::{gathered, gathered_in_mysql, gathered_in_postgres},
};

/// The same model with its collection carrying the STORAGE word — `sortable`, the field's
/// own fact beside its label rather than inside it.
///
/// `pub(super)` so the CURSOR half beside this suite spends the same fixture rather than a second
/// copy of it: two models with one name are two things free to drift apart.
pub(super) fn sortable(mut model: RecordModel) -> RecordModel {
  let field = model
    .fields
    .iter_mut()
    .find(|field| field.column.source == "chapters")
    .expect("the collection column is a field of the record");
  assert!(
    field.marker.is_some(),
    "the collection declared one of the framework's words"
  );
  field.sortable = true;
  model
}

/// The emission's tokens as text, GATES AND ALL — the road the tracing suite already reads by, and
/// for its reason: a gate is a macro invocation, so its contents are tokens rather than items until
/// the macro runs, and the write plan a companion joins rides one.
fn emitted(model: &RecordModel) -> String {
  model.emit().to_string()
}

/// **THE WRITE PLAN GROWS A COMPANION**, named under the synthesized-column law and filled from the
/// framework's own encoding of the row's collection.
#[test]
fn a_sortable_collection_emits_its_companion() {
  let tokens = emitted(&sortable(gathered()));

  assert!(
    tokens.contains("const SHADOWS"),
    "the write plan states the companion: {tokens}"
  );
  assert!(
    tokens.contains("\"__ig_chapters_sort__\""),
    "under the synthesized-column law: {tokens}"
  );
  assert!(
    tokens.contains("collection_sort_key"),
    "filled from the framework's own encoding: {tokens}"
  );
}

/// **AND THE TERM RENDERS IT**, with the collection's own identity beside it — the one term whose
/// two names come apart.
#[test]
fn a_sortable_collection_orders_by_the_companion() {
  let tokens = emitted(&sortable(gathered()));

  assert!(
    tokens.contains("OrderTerm :: shadow"),
    "the subject is the companion's: {tokens}"
  );
  assert!(
    tokens.contains("TermName :: new (\"chapters\")"),
    "and the identity is still the field's: {tokens}"
  );
}

/// **MYSQL ANSWERS THE SAME**, being the other dialect with no array type — so the row is the
/// STORAGE FORM's and not one dialect's.
#[test]
fn the_other_edge_dialect_answers_alike() {
  let tokens = emitted(&sortable(gathered_in_mysql()));

  assert!(tokens.contains("const SHADOWS"), "{tokens}");
  assert!(tokens.contains("OrderTerm :: shadow"), "{tokens}");
}

/// **POSTGRES EMITS NOTHING FOR THE WORD.** Its collection rides the row as a native array, which it
/// orders element by element itself, so there is no remainder for a companion to buy back.
#[test]
fn an_array_stored_collection_emits_no_companion() {
  let tokens = emitted(&sortable(gathered_in_postgres()));

  assert!(
    !tokens.contains("const SHADOWS"),
    "a native array orders itself: {tokens}"
  );
  assert!(
    !tokens.contains("__ig_chapters_sort__"),
    "so no column is created, written or ordered by: {tokens}"
  );
  assert!(
    tokens.contains("OrderTerm :: array"),
    "and the term is the array's, as it was: {tokens}"
  );
}

/// **NO WORD IS TODAY'S WORLD EXACTLY**, token for token — the claim that makes the word free for
/// every declaration written before it.
#[test]
fn a_collection_without_the_word_emits_what_it_always_did() {
  let plain = emitted(&gathered());

  assert!(!plain.contains("const SHADOWS"), "{plain}");
  assert!(!plain.contains("collection_sort_key"), "{plain}");
  assert!(
    plain.contains("OrderTerm :: edge"),
    "the term is the remainder it was: {plain}"
  );
}

/// **THE COMPANION FOLLOWS A RENAME**, because it is a column of the table the collection's own
/// column is in — so a deployment that moved the column moved its order with it.
#[test]
fn the_companion_is_named_from_the_stored_column() {
  let mut model = sortable(gathered());
  let Some(persist) = model.persist.as_mut() else {
    panic!("the model stores its columns")
  };
  let columns = match &mut persist.backends[0] {
    crate::model::DatabaseBackend::Sqlite(db) => &mut db.storage.columns,
    _ => panic!("this model's first backend is SQLite"),
  };
  let at = columns
    .iter()
    .position(|column| column.source == "chapters")
    .expect("the collection column is stored");
  columns[at].name = crate::name::RustSafeName::new("acts", proc_macro2::Span::call_site());

  let tokens = emitted(&model);
  assert!(
    tokens.contains("\"__ig_acts_sort__\"") && !tokens.contains("__ig_chapters_sort__"),
    "the companion wears the column's stored name: {tokens}"
  );
}

/// **THE COMPANION FOLLOWS THE DATABASE'S OWN NAMESPACE**, and this is a COLLISION closed rather
/// than a knob widened.
///
/// `ingraph-derive`'s fence refuses a declared column inside the union of every prefix its
/// databases still mint in — so a record that overrode the prefix on every one of them has had
/// `__ig*` HANDED BACK, and may legally declare a column called `__ig_chapters_sort__`. The
/// companion used to be minted there anyway, from the framework's constant, which put a
/// framework-invented column and an author-declared one at one name with nothing refusing either.
#[test]
fn the_companion_is_minted_in_the_namespace_its_database_mints_in() {
  let mut model = sortable(gathered());
  let Some(persist) = model.persist.as_mut() else {
    panic!("the model stores its columns")
  };
  match &mut persist.backends[0] {
    crate::model::DatabaseBackend::Sqlite(db) => {
      db.storage.aliases.prefix = Some(String::from("__mine"));
    }
    _ => panic!("this model's first backend is SQLite"),
  }

  let tokens = emitted(&model);
  assert!(
    tokens.contains("\"__mine_chapters_sort__\""),
    "the companion is a column of THIS database, so it wears this database's mark: {tokens}"
  );
  assert!(
    !tokens.contains("__ig_chapters_sort__"),
    "and the namespace the fence handed back is not written into: {tokens}"
  );
}

/// **THE MODEL's SEAT IS THE FALLBACK**, which is how a platform's own declarations get their
/// companions without writing `alias(prefix = …)` on every database block.
#[test]
fn a_database_that_names_nothing_falls_back_to_the_models_own_mark() {
  let mut model = sortable(gathered());
  model.prefix = EmissionPrefix::new("__mg");

  let tokens = emitted(&model);
  assert!(
    tokens.contains("\"__mg_chapters_sort__\"") && !tokens.contains("__ig_chapters_sort__"),
    "an absent `prefix = …` resolves to whichever framework built the model: {tokens}"
  );
}

/// **THE MINT IS INJECTIVE, and the collision it is defending against is spellable.**
///
/// A record may declare a field called `tags_sort` beside one called `tags`. Under the closure's
/// sketch — `<field>_sort` — the first field's own column and the second's companion would be one
/// name, and the engine would refuse the `CREATE TABLE` at best and answer from the wrong column at
/// worst. Under the synthesized-column law neither name is one a declaration can write, and the two
/// companions are still distinct: the field is everything between a fixed prefix and a fixed suffix.
#[test]
fn two_fields_cannot_reach_one_companion() {
  let mark = EmissionPrefix::default();
  assert_eq!(sort_column(mark.mark(), "tags"), "__ig_tags_sort__");
  assert_eq!(
    sort_column(mark.mark(), "tags_sort"),
    "__ig_tags_sort_sort__"
  );
  assert_ne!(
    sort_column(mark.mark(), "tags"),
    sort_column(mark.mark(), "tags_sort")
  );
}