ingraph_codegen/interface/
page.rs1use quote::{format_ident, quote};
37
38use crate::{
39 emit::{leading, parameter},
40 interface::{InterfaceField, InterfaceModel},
41 model::DatabaseKind,
42 unit,
43};
44
45const KIND_VARIANT: &str = "__IgKind";
49
50const ADDRESS_VARIANT: &str = "__IgAddress";
52
53impl InterfaceModel {
54 #[must_use]
56 pub fn cursor_name(&self, kind: DatabaseKind) -> syn::Ident {
57 format_ident!("{}{}Cursor", self.name, kind.suffix())
58 }
59
60 #[must_use]
62 pub fn comparison_name(&self, kind: DatabaseKind) -> syn::Ident {
63 format_ident!("{}{}Comparison", self.name, kind.suffix())
64 }
65
66 pub(crate) fn page(&self) -> proc_macro2::TokenStream {
68 if !self.projects() {
69 return quote!();
70 }
71 let address = self.address_carrier();
72 let databases = self.sql_databases().into_iter().map(|kind| {
73 let cursor = self.cursor_value(kind);
74 let comparison = self.comparison(kind);
75 quote! {
76 #cursor
77 #comparison
78 }
79 });
80 quote! {
81 #address
82 #(#databases)*
83 }
84 }
85
86 fn address_carrier(&self) -> proc_macro2::TokenStream {
93 let name = super::default_id_name(&self.name);
94 let identifiable = self.framework(&["transform"], "Identifiable");
95 let cursor_value = self.framework(&["cursor"], "CursorValue");
96 let carrier = self.framework(&["comparison", "sql"], "Carrier");
97 let database = self.framework(&["sqlx"], "Database");
98 let held = self.framework(&["sqlx"], "QueryBuilder");
99 let db = parameter("DB");
100
101 let writes = self.members.iter().enumerate().map(|(tag, member)| {
102 let variant = &member.ident;
103 let tag = u8::try_from(tag).unwrap_or(u8::MAX);
104 quote! {
105 Self::#variant(__ingraph_value) => {
106 __ingraph_out.push(#tag);
107 #cursor_value::write_cursor(__ingraph_value, __ingraph_out);
108 }
109 }
110 });
111 let reads = self.members.iter().enumerate().map(|(tag, member)| {
112 let (variant, ty) = (&member.ident, &member.ty);
113 let tag = u8::try_from(tag).unwrap_or(u8::MAX);
114 quote! {
115 #tag => ::core::option::Option::map(
116 <<#ty as #identifiable>::Id as #cursor_value>::read_cursor(__ingraph_rest),
117 Self::#variant,
118 ),
119 }
120 });
121 let binds = self.members.iter().map(|member| {
122 let variant = &member.ident;
123 quote!(Self::#variant(__ingraph_value) => #carrier::push_bind(__ingraph_value, __ingraph_qb),)
124 });
125 let codecs = self.members.iter().map(|member| {
126 let ty = &member.ty;
127 quote!(<#ty as #identifiable>::Id: #cursor_value,)
128 });
129 let bounds = self.members.iter().map(|member| {
130 let ty = &member.ty;
131 quote!(<#ty as #identifiable>::Id: #carrier<#db>,)
132 });
133
134 let write_doc = leading("Append this address's member tag and that member's own id bytes.");
135 let read_doc = leading("The address `bytes` hold, or `None` where they name no member.");
136 let bind_doc = leading("Bind this address, in the type its own member's table stores.");
137 quote! {
138 #[automatically_derived]
139 impl #cursor_value for #name
140 where
141 #(#codecs)*
142 {
143 #[doc = #write_doc]
144 fn write_cursor(&self, __ingraph_out: &mut ::std::vec::Vec<::core::primitive::u8>) {
145 match self {
146 #(#writes)*
147 }
148 }
149
150 #[doc = #read_doc]
151 fn read_cursor(__ingraph_bytes: &[::core::primitive::u8]) -> ::core::option::Option<Self> {
152 let (__ingraph_tag, __ingraph_rest) =
153 <[::core::primitive::u8]>::split_first(__ingraph_bytes)?;
154 match *__ingraph_tag {
155 #(#reads)*
156 _ => ::core::option::Option::None,
157 }
158 }
159 }
160
161 #[automatically_derived]
162 impl<#db> #carrier<#db> for #name
163 where
164 #db: #database,
165 #(#bounds)*
166 {
167 #[doc = #bind_doc]
168 fn push_bind(&self, __ingraph_qb: &mut #held<#db>) {
169 match self {
170 #(#binds)*
171 }
172 }
173 }
174 }
175 }
176
177 fn cursor_value(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
188 let vis = &self.vis;
189 let interface = &self.name;
190 let name = self.cursor_name(kind);
191 let vocabulary = super::default_kind_name(interface);
192 let address = super::default_id_name(interface);
193 let kind_variant = format_ident!("{KIND_VARIANT}");
194 let address_variant = format_ident!("{ADDRESS_VARIANT}");
195
196 let cursor_value = self.framework(&["cursor"], "CursorValue");
197 let dialect_cursor = self.framework(&["cursor"], "DialectCursor");
202 let (module, item) = kind.dialect();
203 let backend = self.framework(module, item);
204 let carrier = self.framework(&["comparison", "sql"], "Carrier");
205 let capability = self.framework(&["interface"], "InterfaceKind");
206 let database = self.framework(&["sqlx"], "Database");
207 let held = self.framework(&["sqlx"], "QueryBuilder");
208 let db = parameter("DB");
209
210 let stored: Vec<&InterfaceField> = self.projected().collect();
218 let variants = stored.iter().map(|field| {
219 let variant = variant_of(field);
220 let ty = self.stored_at(field, kind);
221 let doc = leading(&format!("The `{}` column's value.", field.name));
222 quote! {
223 #[doc = #doc]
224 #variant(#ty),
225 }
226 });
227 let writes = stored.iter().enumerate().map(|(tag, field)| {
228 let variant = variant_of(field);
229 let ty = self.stored_at(field, kind);
230 let tag = u8::try_from(tag).unwrap_or(u8::MAX);
231 quote! {
232 Self::#variant(__ingraph_value) => {
233 __ingraph_out.push(#tag);
234 <#ty as #dialect_cursor<#backend>>::write_cursor_at(__ingraph_value, __ingraph_out);
235 }
236 }
237 });
238 let reads = stored.iter().enumerate().map(|(tag, field)| {
239 let variant = variant_of(field);
240 let ty = self.stored_at(field, kind);
241 let tag = u8::try_from(tag).unwrap_or(u8::MAX);
242 quote! {
243 #tag => ::core::option::Option::map(
244 <#ty as #dialect_cursor<#backend>>::read_cursor_at(__ingraph_rest),
245 Self::#variant,
246 ),
247 }
248 });
249 let binds = stored.iter().map(|field| {
250 let variant = variant_of(field);
251 quote!(Self::#variant(__ingraph_value) => #carrier::push_bind(__ingraph_value, __ingraph_qb),)
252 });
253 let codecs = stored.iter().map(|field| {
254 let ty = self.stored_at(field, kind);
255 quote!(#ty: #dialect_cursor<#backend>,)
256 });
257 let bounds = stored.iter().map(|field| {
258 let ty = self.stored_at(field, kind);
259 quote!(#ty: #carrier<#db>,)
260 });
261 let kind_tag = u8::try_from(stored.len()).unwrap_or(u8::MAX);
264 let address_tag = kind_tag.saturating_add(1);
265
266 let what = super::row::what(kind);
267 let doc = leading(&format!(
268 "One slot of a cursor over a page of [`{interface}`] in {what} — which column, and the value \
269 it held at the boundary row.\n\nThe last two are the framework's own: an interface's total \
270 order ends `…, __ig_kind__, id`, because an id is `UNIQUE` only within its own member's \
271 table and the discriminant is what tells two members' rows apart."
272 ));
273 let kind_doc = leading(
274 "The DISCRIMINANT the boundary row carried. Minted from the address rather than carried \
275 beside it, so the pair cannot disagree.",
276 );
277 let address_doc =
278 leading("The boundary row's ADDRESS — which member, and that member's own id.");
279 let write_doc = leading("Append this slot's tag and its value's own bytes.");
280 let read_doc = leading("The slot `bytes` hold, or `None` where they name no column.");
281 let bind_doc = leading("Bind this slot's value, in the type this database stores.");
282 quote! {
283 #[doc = #doc]
284 #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
285 #vis enum #name {
286 #(#variants)*
287 #[doc = #kind_doc]
288 #kind_variant(#vocabulary),
289 #[doc = #address_doc]
290 #address_variant(#address),
291 }
292
293 #[automatically_derived]
294 impl #cursor_value for #name
295 where
296 #(#codecs)*
297 #address: #cursor_value,
298 {
299 #[doc = #write_doc]
300 fn write_cursor(&self, __ingraph_out: &mut ::std::vec::Vec<::core::primitive::u8>) {
301 match self {
302 #(#writes)*
303 Self::#kind_variant(__ingraph_value) => {
304 __ingraph_out.push(#kind_tag);
305 #cursor_value::write_cursor(
306 &::std::borrow::ToOwned::to_owned(#capability::as_str(*__ingraph_value)),
307 __ingraph_out,
308 );
309 }
310 Self::#address_variant(__ingraph_value) => {
311 __ingraph_out.push(#address_tag);
312 #cursor_value::write_cursor(__ingraph_value, __ingraph_out);
313 }
314 }
315 }
316
317 #[doc = #read_doc]
318 fn read_cursor(__ingraph_bytes: &[::core::primitive::u8]) -> ::core::option::Option<Self> {
319 let (__ingraph_tag, __ingraph_rest) =
320 <[::core::primitive::u8]>::split_first(__ingraph_bytes)?;
321 match *__ingraph_tag {
322 #(#reads)*
323 #kind_tag => ::core::option::Option::map(
324 ::core::result::Result::ok(<#vocabulary as #capability>::parse(
325 &<::std::string::String as #cursor_value>::read_cursor(__ingraph_rest)?,
326 )),
327 Self::#kind_variant,
328 ),
329 #address_tag => ::core::option::Option::map(
330 <#address as #cursor_value>::read_cursor(__ingraph_rest),
331 Self::#address_variant,
332 ),
333 _ => ::core::option::Option::None,
334 }
335 }
336 }
337
338 #[automatically_derived]
339 impl<#db> #carrier<#db> for #name
340 where
341 #db: #database,
342 #(#bounds)*
343 ::std::string::String: #carrier<#db>,
344 #address: #carrier<#db>,
345 {
346 #[doc = #bind_doc]
347 fn push_bind(&self, __ingraph_qb: &mut #held<#db>) {
348 match self {
349 #(#binds)*
350 Self::#kind_variant(__ingraph_value) => #carrier::push_bind(
353 &::std::borrow::ToOwned::to_owned(#capability::as_str(*__ingraph_value)),
354 __ingraph_qb,
355 ),
356 Self::#address_variant(__ingraph_value) =>
357 #carrier::push_bind(__ingraph_value, __ingraph_qb),
358 }
359 }
360 }
361 }
362 }
363
364 fn comparison(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
386 let interface = &self.name;
387 let name = self.comparison_name(kind);
388 let db = parameter("DB");
389
390 let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
391 let crossings = self.crossings(kind);
392
393 let rows: Vec<unit::ComparisonColumn> = self
397 .stored()
398 .map(|field| {
399 let (filter, stored) = (self.filter_of(field), self.stored_at(field, kind));
400 unit::ComparisonColumn {
401 gate: proc_macro2::TokenStream::new(),
404 member: field.name.clone(),
405 name: format!("shared `{}` column", field.name),
406 held: quote!(<#filter as #to_comparison<#stored, #db>>::Comparison),
407 }
408 })
409 .collect();
410 let header = unit::UnitHeader {
411 vis: &self.vis,
412 name: name.clone(),
413 subject: format!("[`{interface}`]"),
414 note: Some(
415 "Written in the INTERFACE's vocabulary and lowered ONCE, above the union — a member that \
416 calls a shared column something else has already aliased it in its own arm, so one \
417 predicate answers whichever member the row came from."
418 .to_owned(),
419 ),
420 };
421 let (declaration, methods) = unit::comparison(&header, &db, &crossings, &rows);
422
423 let seats = unit::LoweringSeats {
429 backend: self.framework(&["comparison"], "Backend"),
430 complex: self.framework(&["comparison"], "ComplexComparison"),
431 frame: self.framework(&["comparison"], "Frame"),
432 at: self.framework(&["comparison"], "At"),
433 field_name: self.framework(&["field"], "FieldName"),
434 };
435 let lowered: Vec<unit::LoweringColumn> = self
440 .projected()
441 .map(|field| unit::LoweringColumn {
442 gate: proc_macro2::TokenStream::new(),
445 member: field.name.clone(),
446 rendered: field.name.to_string(),
447 flatten: false,
448 through: None,
449 })
450 .collect();
451 let lowering = unit::comparison_lowering(&name, &db, &crossings, &seats, &lowered);
452
453 quote! {
454 #declaration
455 #methods
456 #lowering
457 }
458 }
459
460 fn crossings(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
468 let db = parameter("DB");
469 let backend = self.framework(&["comparison"], "Backend");
470 let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
471 let crossings = self.stored().map(|field| {
472 let (filter, stored) = (self.filter_of(field), self.stored_at(field, kind));
473 quote!(#filter: #to_comparison<#stored, #db>,)
474 });
475 quote! {
476 #db: #backend,
477 #(#crossings)*
478 }
479 }
480
481 pub(super) fn filter_of(&self, field: &InterfaceField) -> proc_macro2::TokenStream {
493 crate::emit::filter_of(
496 &self.krate,
497 &field.ty,
498 field.marker.as_ref(),
499 crate::emit::FilterFace::Column,
500 )
501 }
502}
503
504fn variant_of(field: &InterfaceField) -> syn::Ident {
507 crate::emit::upper_camel(&field.name.to_string())
508}