ingraph-derive 0.1.0

The attribute and derive macros for ingraph: the words a record, node, key, filter and vocabulary declaration is written in.
Documentation
//! THE `indexed` WORD — the seat it takes at a FIELD, the seat it keeps inside a database's block,
//! and the redirect that tells the two apart.
//!
//! A suite of its own beside [`crate::sortable_tests`], for that suite's reason: what is asserted
//! here is ONE word's grammar, and holding it apart from the label vocabulary's own suite keeps a
//! change to either visible.
//!
//! # ONE SPELLING, TWO SEATS, and reading it as one word is the whole trap this suite guards
//!
//! | written | subject | what it means |
//! |---|---|---|
//! | `#[ingraph(sqlite(indexed))]` | one COLUMN of the row, in ONE database | that database gets an index over it — a choice no client can observe, so it is a per-database one |
//! | `#[ingraph(list(scalar), indexed)]` | this COLLECTION, in EVERY database | the value-led access path: a second index on the elements' table, and on SQLite a case-tolerant column |
//!
//! A grammar that read one word at one seat would have had to pick, and both picks are wrong: a
//! collection has no single column for the first reading to be about, and the second cannot be per
//! database because on SQLite it FOLDS CASE — visible in a `set(…)`'s own identity, so a word
//! written for one store and withheld from the next would be a declaration meaning two different
//! things.
//!
//! So each seat reads the word and answers with its own rule, and both refusals name the other seat.
//! That is the shape `record(sortable)`/`sortable` already takes one namespace apart.

use ingraph_codegen::prelude::*;

use crate::{host, parse::parse};

/// The pass under test, at the kind this word is about — a record, being the only kind that stores.
fn record(input: &syn::DeriveInput) -> syn::Result<RecordModel> {
  let (host, options) = host::split(input);
  parse(&host, &options, NodeKind::Record)
}

/// One field of the record.
fn field<'a>(model: &'a RecordModel, source: &str) -> &'a Field {
  model
    .fields
    .iter()
    .find(|field| field.column.source == source)
    .unwrap_or_else(|| panic!("`{source}` is a field of the record"))
}

/// The refusal one declaration gets, as text.
fn refused(input: &syn::DeriveInput) -> String {
  record(input)
    .err()
    .map(|error| error.to_string())
    .unwrap_or_else(|| panic!("this declaration is refused"))
}

/// **THE WORD IS READ BARE ON THE FIELD**, beside the per-database blocks, and it lands on the FIELD
/// rather than on its marker — the storage/interpretation partition `sortable` already keeps.
#[test]
fn a_collection_declares_its_access_word_on_the_field() {
  let model = record(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: u128,
      #[ingraph(list(string), indexed)] tags: Vec<String>,
    }
  })
  .expect("a persisted collection may ask for the value-led access path");

  let Marker::Framework(FrameworkMarker { label, element }) = field(&model, "tags")
    .marker
    .as_ref()
    .expect("this field declared a label")
  else {
    panic!("a word resolves to one of the framework's markers")
  };
  assert_eq!(*label, Label::List);
  assert_eq!(*element, Some(Label::String));
  assert!(field(&model, "tags").indexed);
}

/// **A `set(…)` TAKES THE WORD**, where `sortable` is a list's alone — and the asymmetry is the two
/// words' subjects rather than an inconsistency.
///
/// A set declares that ORDER carries no meaning in it, which is why an ordering word has nothing to
/// preserve there. MEMBERSHIP is what a set is, and a set's primary key leads on the row's key just
/// as a sequence's derived index does — so *which rows hold this element* is exactly as unreachable
/// from a value, and exactly as much the thing this word buys.
#[test]
fn a_set_takes_the_access_word_that_an_ordering_word_refuses() {
  let model = record(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: u128,
      #[ingraph(set(string), indexed)] marks: Vec<String>,
    }
  })
  .expect("a set's membership is what the value-led path seeks");
  assert!(field(&model, "marks").indexed);
}

/// **THE TWO STORAGE WORDS COMPOSE**, one collection carrying both — they answer different
/// questions and neither reads the other.
#[test]
fn the_access_word_sits_beside_the_ordering_word() {
  let model = record(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: u128,
      #[ingraph(list(scalar), sortable, indexed)] marks: Vec<i64>,
    }
  })
  .expect("an order and an access path are two intents about one collection");
  assert!(field(&model, "marks").sortable);
  assert!(field(&model, "marks").indexed);
}

/// **EITHER ORDER IS ONE DECLARATION**, the entries of the field's attribute being a set — the
/// cross-entry rule this word inherits from the seat it shares.
#[test]
fn the_word_may_be_written_before_the_collection_word() {
  for declaration in [
    syn::parse_quote! {
      #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
      struct S {
        #[ingraph(id)] id: u128,
        #[ingraph(indexed, list(scalar))] marks: Vec<i64>,
      }
    },
    syn::parse_quote! {
      #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
      struct S {
        #[ingraph(id)] id: u128,
        #[ingraph(list(scalar), indexed)] marks: Vec<i64>,
      }
    },
  ] {
    let model: syn::DeriveInput = declaration;
    let model = record(&model).expect("either order is the same declaration");
    assert!(field(&model, "marks").indexed);
  }
}

/// **A FIELD WITH NO ELEMENTS IS REDIRECTED TO THE OTHER SEAT**, rather than told the word does not
/// exist.
///
/// This is the sentence that replaced the per-database list's for this word. It has to carry two
/// things: the block a single column's index is written in, and — since the author wrote the word on
/// something that is not a collection — what a collection word looks like.
#[test]
fn refuses_the_access_word_on_a_field_with_no_elements() {
  let e = refused(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: u128,
      #[ingraph(scalar, indexed)] bit_rate: u64,
    }
  });
  assert!(e.contains("is a COLLECTION's word"), "{e}");
  assert!(
    e.contains("#[ingraph(sqlite(indexed))]"),
    "it names the seat a single column's index is written at: {e}"
  );
  assert!(
    e.contains("#[ingraph(list(scalar), indexed)]"),
    "and the shape a collection's is: {e}"
  );
}

/// **A KEY-SIDE COLUMN GETS THE SAME SENTENCE**, where `sortable` has one of its own.
///
/// The difference is what the two words can mean at a scalar. `sortable` on one is a mistake with no
/// other seat — a stored scalar is already orderable — so its refusals differ by what the author
/// seems to have meant. `indexed` on one is the RIGHT idea at the WRONG seat, and the same redirect
/// is the useful answer wherever the field sits.
#[test]
fn a_key_side_column_is_redirected_alike() {
  let e = refused(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id, indexed)] id: u128,
      #[ingraph(list(string))] tags: Vec<String>,
    }
  });
  assert!(e.contains("is a COLLECTION's word"), "{e}");
  assert!(
    e.contains("#[ingraph(sqlite(indexed))]"),
    "the seat is named wherever the field sits: {e}"
  );
}

/// **A CUSTOM LABEL GETS THE ONE VARIANT**, and only because `label = "…"` names a marker this
/// grammar cannot classify — so *write a collection word* has to say which words those are.
#[test]
fn refuses_the_access_word_beside_a_custom_label() {
  let e = refused(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: u128,
      #[ingraph(label = "a::marker::Path", indexed)] tags: Vec<String>,
    }
  });
  assert!(e.contains("cannot classify"), "{e}");
  assert!(e.contains("`list(…)` or `set(…)`"), "{e}");
}

/// **WRITTEN TWICE IT IS REFUSED.** One collection, one access path.
#[test]
fn refuses_a_repeated_access_word() {
  let e = refused(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: u128,
      #[ingraph(list(scalar), indexed, indexed)] marks: Vec<i64>,
    }
  });
  assert!(e.contains("declared more than once"), "{e}");
}

/// **IT IS A BARE WORD**, carrying neither a value nor a block.
#[test]
fn refuses_the_access_word_carrying_anything() {
  for declaration in [
    syn::parse_quote! {
      #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
      struct S {
        #[ingraph(id)] id: u128,
        #[ingraph(list(scalar), indexed = "yes")] marks: Vec<i64>,
      }
    },
    syn::parse_quote! {
      #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
      struct S {
        #[ingraph(id)] id: u128,
        #[ingraph(list(scalar), indexed(sqlite))] marks: Vec<i64>,
      }
    },
  ] {
    let declaration: syn::DeriveInput = declaration;
    let _ = refused(&declaration);
  }
}

/// **THE OTHER SEAT'S WORD IS REFUSED ON A COLLECTION, AND POINTS HERE** — for BOTH storage forms,
/// which is what changed when this word arrived.
///
/// The edge-stored half was already refused: there is no column of the parent row for an index to be
/// over. The array-stored half was legal and INERT, left spellable against the day a word could
/// render it. That day is this word, and it is not that seat's — so both halves now redirect, and
/// the storage form stops being a fact the refusal has to read.
#[test]
fn the_per_database_word_on_a_collection_names_the_field_seat() {
  for declaration in [
    syn::parse_quote! {
      #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
      struct S {
        #[ingraph(id)] id: u128,
        #[ingraph(list(scalar), sqlite(indexed))] marks: Vec<i64>,
      }
    },
    syn::parse_quote! {
      #[ingraph(postgres, graphql(async_graphql, plural = "many"))]
      struct S {
        #[ingraph(id)] id: u128,
        #[ingraph(list(scalar), postgres(indexed))] marks: Vec<i64>,
      }
    },
  ] {
    let declaration: syn::DeriveInput = declaration;
    let e = refused(&declaration);
    assert!(e.contains("is a COLLECTION and"), "{e}");
    assert!(
      e.contains("#[ingraph(list(scalar), indexed)]"),
      "the refusal names the seat the word does have: {e}"
    );
    assert!(
      e.contains("folds case"),
      "and why that seat cannot be a database's: {e}"
    );
  }
}

/// **THE PER-DATABASE SEAT IS UNTOUCHED FOR A SCALAR**, which is the other half of the split: one
/// column's index in one database is still exactly what it was.
#[test]
fn a_scalar_keeps_its_per_database_index() {
  let model = record(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: u128,
      #[ingraph(scalar, sqlite(indexed))] bit_rate: u64,
    }
  })
  .expect("a column's index is its database's own word");
  assert!(
    model
      .persist
      .as_ref()
      .expect("the record stores")
      .backends
      .iter()
      .flat_map(DatabaseBackend::columns)
      .any(|column| column.source == "bit_rate" && column.indexed),
    "the per-database word still reaches the column it is about"
  );
}

/// **A DECLARATION WITHOUT THE WORD MEANS EXACTLY WHAT IT MEANT.** The word is a storage fact, so a
/// collection that never wrote one resolves to the same marker and carries `false`.
#[test]
fn a_collection_without_the_word_is_unchanged() {
  let model = record(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: u128,
      #[ingraph(list(string))] tags: Vec<String>,
    }
  })
  .expect("a collection needs no storage word");
  assert!(!field(&model, "tags").indexed);
  assert!(field(&model, "tags").marker.is_some());
}