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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Every rule this pass states, each put to a declaration that breaks it — and what the accepted
//! ones mount.
//!
//! The refusals are asserted here rather than only as fixtures, because a `trybuild` file pins the
//! MESSAGE a user sees and this pins the rule: a pass that stopped checking would still print
//! nothing, and an empty error list is what both look like from the outside.

use quote::ToTokens as _;

use super::Journal;

/// The pass under test, over a declaration written the way the derive took one.
fn parse(input: &syn::DeriveInput) -> syn::Result<Journal> {
  let (host, arguments) = crate::host::split(input);
  super::parse(&host, &arguments)
}

/// Parse a declaration, expecting it to be accepted.
fn accepted(input: proc_macro2::TokenStream) -> Journal {
  parse(&syn::parse2(input).expect("the declaration parses")).expect("the declaration is a journal")
}

/// Parse a declaration, expecting the refusal it earns.
fn refused(input: proc_macro2::TokenStream) -> String {
  parse(&syn::parse2(input).expect("the declaration parses"))
    .err()
    .expect("this declaration breaks a rule")
    .into_iter()
    .map(|error| error.to_string())
    .collect::<Vec<_>>()
    .join("\n")
}

/// The mounted record's columns, in declared order, as `name: Type`.
fn columns(journal: &Journal) -> Vec<String> {
  journal
    .model
    .record
    .fields
    .iter()
    .map(|field| {
      format!(
        "{}: {}",
        field.column.name,
        field
          .column
          .ty
          .to_token_stream()
          .to_string()
          .replace(' ', "")
      )
    })
    .collect()
}

/// **THE RULED LINE, parsed** — and what it mounts is the canonical four.
#[test]
fn the_ruled_line_mounts_the_canonical_record() {
  let journal = accepted(quote::quote! {
    #[ingraph(root = "MediaId", sqlite)]
    pub struct VideoJournal;
  });

  assert_eq!(journal.model.record.record, "VideoJournal");
  assert_eq!(
    journal.model.root.to_token_stream().to_string(),
    "MediaId",
    "the root travels to the row contract as the type the declaration named"
  );
  assert_eq!(
    columns(&journal),
    [
      "root: MediaId",
      "node: ::std::string::String",
      "station: ::std::string::String",
      "at: ::ingraph::__private::primitives::Timestamp",
    ]
  );
}

/// **`(root, node)` is the emitted key**, and nothing in the declaration says so: the root is the
/// lineage and `node` carries the id, so the record law spells the pair the entry is replaced on.
#[test]
fn the_key_is_the_pair_an_entry_is_replaced_on() {
  let journal = accepted(quote::quote! {
    #[ingraph(root = "MediaId", sqlite)]
    pub struct VideoJournal;
  });
  let key = &journal.model.record.key;

  assert_eq!(
    key
      .path
      .iter()
      .map(|column| column.name.to_string())
      .collect::<Vec<_>>(),
    ["root"],
    "the lineage is the root, and only the root"
  );
  assert_eq!(
    key.id.name, "node",
    "and the id is the node, so the pair is `(root, node)`"
  );
}

/// The passthrough is UNINTERPRETED here and read by the record grammar — so a database block, a
/// table name and a per-database option all arrive with their meanings intact.
#[test]
fn the_persist_block_passes_through_whole() {
  let journal = accepted(quote::quote! {
    #[ingraph(
      root = "MediaId",
      table = "video_journal", sqlite(alias(depth = 12)), postgres)]
    pub struct VideoJournal;
  });
  let persist = journal
    .model
    .record
    .persist
    .as_ref()
    .expect("the block reached the record grammar");

  assert_eq!(
    persist.table.as_ref().map(ToString::to_string),
    Some("video_journal".to_owned())
  );
  assert_eq!(
    persist
      .backends
      .iter()
      .map(|db| db.kind().as_str())
      .collect::<Vec<_>>(),
    ["sqlite", "postgres"]
  );
}

/// A journal with no block is the PURE-COMPUTE record the hand corpus already declares — the row
/// contract is what the word is for, and where the row lands is a second question.
#[test]
fn a_journal_may_name_no_database() {
  let journal = accepted(quote::quote! {
    #[ingraph(root = "MediaId")]
    pub struct VideoJournal;
  });
  assert!(journal.model.record.persist.is_none());
  assert_eq!(columns(&journal).len(), 4, "and the four columns are there");
}

/// `crate = "…"` moves every emitted path, including the `at` column's own declared type.
#[test]
fn a_journal_can_name_the_crate() {
  let journal = accepted(quote::quote! {
    #[ingraph(crate = "crate::shim", root = "MediaId")]
    pub struct VideoJournal;
  });

  assert_eq!(
    journal.model.record.krate.to_token_stream().to_string(),
    "crate :: shim"
  );
  assert!(
    columns(&journal)
      .last()
      .is_some_and(|at| at == "at: crate::shim::__private::primitives::Timestamp"),
    "{:?}",
    columns(&journal)
  );
}

/// The AUTHOR's own attributes survive onto the mounted host — an attribute macro replaces the item
/// it sits on, so anything dropped here is dropped from the program.
#[test]
fn the_authors_own_attributes_reach_the_mounted_host() {
  let journal = accepted(quote::quote! {
    /// What the deployment calls it.
    #[derive(Debug, Clone)]
    #[ingraph(root = "MediaId")]
    pub struct VideoJournal;
  });
  let attrs = journal
    .host
    .attrs
    .iter()
    .map(|attr| attr.to_token_stream().to_string().replace(' ', ""))
    .collect::<Vec<_>>();

  assert_eq!(attrs.len(), 2, "{attrs:?}");
  assert!(attrs[0].contains("Whatthedeploymentcallsit."), "{attrs:?}");
  assert_eq!(attrs[1], "#[derive(Debug,Clone)]");
  assert!(
    !attrs.iter().any(|attr| attr.contains("ingraph")),
    "the word's own arguments are taken out, so the record pass does not report them twice: \
     {attrs:?}"
  );
  assert_eq!(journal.host.vis.to_token_stream().to_string(), "pub");
}

/// **A journal with no root is refused**, because there is one journal table per root family and
/// nothing else says which family.
#[test]
fn a_journal_names_its_root() {
  let refusal = refused(quote::quote! {
    #[ingraph(sqlite)]
    pub struct VideoJournal;
  });
  assert!(
    refusal.contains("a journal needs `root = \"…\"`"),
    "{refusal}"
  );
}

/// **A struct with fields is the TEACHING refusal** — custom columns are what the hand path is for,
/// and the message says so rather than reporting a shape error.
#[test]
fn a_host_carrying_fields_is_sent_to_the_hand_path() {
  let refusal = refused(quote::quote! {
    #[ingraph(root = "MediaId")]
    pub struct VideoJournal {
      detail: Option<String>,
    }
  });
  assert!(
    refusal.contains("a journal's host is a MARKER"),
    "{refusal}"
  );
  assert!(refusal.contains("HAND path"), "{refusal}");
  assert!(
    refusal.contains("implement `JournalRow` on it"),
    "{refusal}"
  );
}

/// A tuple struct is the same rule: the shape is the marker.
#[test]
fn a_positional_host_is_refused_the_same_way() {
  let refusal = refused(quote::quote! {
    #[ingraph(root = "MediaId")]
    pub struct VideoJournal(String);
  });
  assert!(
    refusal.contains("a journal's host is a MARKER"),
    "{refusal}"
  );
}

/// An enum mounts nothing: the word mounts a RECORD, and a record is a struct.
#[test]
fn an_enum_host_is_refused() {
  let refusal = refused(quote::quote! {
    #[ingraph(root = "MediaId")]
    pub enum VideoJournal { A }
  });
  assert!(
    refusal.contains("a journal's host is a marker STRUCT"),
    "{refusal}"
  );
}

/// A generic host is refused for the record's own reason, restated in this word's terms.
#[test]
fn a_generic_host_is_refused() {
  let refusal = refused(quote::quote! {
    #[ingraph(root = "MediaId")]
    pub struct VideoJournal<Root>;
  });
  assert!(
    refusal.contains("a journal takes no generic parameter"),
    "{refusal}"
  );
}

/// Every FIXED word is refused BY NAME, and every refusal points at the path that is not going away.
#[test]
fn the_words_a_canonical_shape_has_already_decided_are_refused_by_name() {
  for (word, written) in [
    ("lineage", quote::quote!(lineage(fields(root)))),
    ("key", quote::quote!(key(rename = "Address"))),
    ("graphql", quote::quote!(graphql)),
    ("implements", quote::quote!(implements(media::Media))),
    ("subscribe", quote::quote!(subscribe = "media::Media")),
    ("upstream", quote::quote!(upstream(node = "media::Media"))),
  ] {
    let refusal = refused(quote::quote! {
      #[ingraph(root = "MediaId", #written)]
      pub struct VideoJournal;
    });
    assert!(
      refusal.contains(&format!("`{word}` decides something a CANONICAL journal")),
      "{word}: {refusal}"
    );
    assert!(refusal.contains("HAND path"), "{word}: {refusal}");
  }
}

/// The three other storage words are refused for the one-storage law's reason, exactly as a record
/// refuses them.
#[test]
fn the_other_storages_are_refused_as_nodes_of_their_own() {
  for word in ["fulltext", "vector", "blob"] {
    let entry = syn::Ident::new(word, proc_macro2::Span::call_site());
    let refusal = refused(quote::quote! {
      #[ingraph(root = "MediaId", #entry(tantivy))]
      pub struct VideoJournal;
    });
    assert!(
      refusal.contains("a journal holds ROWS") && refusal.contains("its OWN node"),
      "{word}: {refusal}"
    );
    assert!(
      refusal.contains(&format!("the `{word}` macro")),
      "{word}: {refusal}"
    );
  }
}

/// An unrecognised entry is refused rather than ignored, and the message names the whole grammar.
#[test]
fn an_unknown_word_names_what_a_journal_takes() {
  let refusal = refused(quote::quote! {
    #[ingraph(root = "MediaId", retention = "30d")]
    pub struct VideoJournal;
  });
  assert!(
    refusal.contains("unknown `ingraph` journal attribute"),
    "{refusal}"
  );
  assert!(
    refusal.contains("which is what CANONICAL means"),
    "{refusal}"
  );
}

/// A root that is not a type is refused HERE, spanned at the string, rather than pasted into the
/// expansion to fail somewhere downstream.
#[test]
fn a_root_that_is_not_a_type_is_refused_at_the_string() {
  let refusal = refused(quote::quote! {
    #[ingraph(root = "not a type")]
    pub struct VideoJournal;
  });
  assert!(
    refusal.contains("`root = \"…\"` names the chain root"),
    "{refusal}"
  );
}

/// Each of the three words is declared once.
///
/// The middle row moved with the store it is about: it used to be `persist(…)` written twice, which
/// this grammar held to one block of its own. A journal names its stores BARE now and forwards them
/// raw, so the repeat an author can write is a store WORD's — and the answer comes from the record
/// grammar the words are handed to, which is what forwarding them uninterpreted is for.
#[test]
fn each_word_is_declared_once() {
  let root = refused(quote::quote! {
    #[ingraph(root = "MediaId", root = "OtherId")]
    pub struct VideoJournal;
  });
  assert!(root.contains("`root` is declared more than once"), "{root}");

  let store = refused(quote::quote! {
    #[ingraph(root = "MediaId", sqlite, sqlite)]
    pub struct VideoJournal;
  });
  assert!(
    store.contains("`sqlite` is declared more than once"),
    "{store}"
  );

  let krate = refused(quote::quote! {
    #[ingraph(crate = "a::b", crate = "c::d", root = "MediaId")]
    pub struct VideoJournal;
  });
  assert!(
    krate.contains("`crate` is declared more than once"),
    "{krate}"
  );
}

/// `persist` is REFUSED in every spelling, and the refusal carries the migration.
///
/// The rule used to be about the shape alone — the word opened a block, so there was nothing for it
/// to be equal to, and `persist = "sqlite"` was told which spelling the grammar took. The grammar
/// takes neither now: a journal's stores sit bare at the head on the record's own unwrap, so the
/// word is answered by where its contents went rather than by how it was written, and the value
/// spelling and the block spelling reach one sentence.
#[test]
fn persist_is_refused_in_every_spelling() {
  for written in [
    quote::quote!(persist = "sqlite"),
    quote::quote!(persist(sqlite)),
    quote::quote!(persist),
  ] {
    let refusal = refused(quote::quote! {
      #[ingraph(root = "MediaId", #written)]
      pub struct VideoJournal;
    });
    assert!(
      refusal.contains("`persist(…)` is gone — a journal names its stores BARE"),
      "{refusal}"
    );
  }
}

/// **Every rule the declaration breaks is reported at once**, which is what the accumulating pass is
/// for: a marker with fields, a word that has already been decided and a missing root are three
/// mistakes and one compile.
#[test]
fn one_compile_reports_the_whole_declaration() {
  let refusal = refused(quote::quote! {
    #[ingraph(lineage(fields(media)))]
    pub struct VideoJournal {
      media: MediaId,
    }
  });
  assert!(refusal.contains("`lineage` decides something"), "{refusal}");
  assert!(
    refusal.contains("a journal's host is a MARKER"),
    "{refusal}"
  );
  assert!(
    refusal.contains("a journal needs `root = \"…\"`"),
    "{refusal}"
  );
}