Skip to main content

ic_db_macros/
lib.rs

1#![forbid(unsafe_code)]
2//! Attribute macros for IC DB schema declarations.
3//! Generates typed records/codecs and metadata, never endpoints or executors.
4//! All declarations use empty, nongeneric struct bodies without `where` clauses;
5//! unsupported Rust constraints are rejected rather than discarded during expansion.
6
7mod enumeration;
8mod field;
9mod insert;
10mod map;
11mod ownership;
12mod record;
13mod set;
14#[cfg(test)]
15mod tests;
16mod unique;
17mod wrapped;
18
19use proc_macro::TokenStream;
20use proc_macro2::TokenStream as Tokens;
21use quote::quote;
22use std::collections::BTreeSet;
23use syn::{Expr, ItemStruct, Lit, Meta, Token, parse::Parser, punctuated::Punctuated};
24
25use field::Field;
26
27/// Author a typed record with named fields, a supplied scalar key and indexes.
28///
29/// Each field has an associated name constant, e.g. `User::NAME` for `name`.
30/// Field types follow the implemented `ic_db::FieldType` contract, with explicit
31/// bounds for variable-size values. Secondary indexes admit supported ordered
32/// scalar fields and unit enums, including optional forms. Optional unique indexes require
33/// `present_only`, omitting a row when any optional key component is absent. Unsupported shapes
34/// refuse explicitly; this is not a retirement of the broader planned type surface.
35/// Entity names default to the type name; `name = "StableName"` overrides it.
36/// Index names default to comma-separated ordered fields; `name` overrides them.
37/// A unique index on `User(issuer, subject)` generates `UserByIssuerAndSubject`
38/// with named fields for `session.get_unique(&key)`. A sparse unique key takes
39/// the present component types. Equivalent unique indexes share a key type.
40/// Required or optional supported key fields may declare `references(entity = "path::Target")`;
41/// select the sole unfiltered index leading with this field, or use `index = "name"`.
42/// `None` has no target; every `Some(id)` requires that target in the final batch state.
43/// `entity = "path::Target"` lets Rust resolve an entity type (including imports
44/// and `Self`) to its logical identity. Numeric authoring IDs are unsupported.
45/// With the host-only `ic-db/build` feature, declarations also register their
46/// full Rust paths for second-stage schema assembly.
47/// Fields may declare `default = LITERAL` for integers, Bool, bounded Text and Blob.
48/// Blob defaults use Rust byte strings, e.g. `default = b"\x00\xff"`, never text/hex coercion.
49/// `Entity::insert()` builds typed omission-aware input for `Batch::insert_input`;
50/// explicit optional `None` is never replaced by a default. Primary-key and nested
51/// record defaults are not implemented. Defaults never run on decode/replacement.
52/// Required Timestamp fields and their scalar newtypes may declare `managed = "created_at"` or
53/// `managed = "updated_at"`, once per role. These fields have no insert setters;
54/// use `Batch::at(time)` to supply one operation time for the entire batch.
55#[proc_macro_attribute]
56pub fn entity(args: TokenStream, item: TokenStream) -> TokenStream {
57    expand(args.into(), item.into())
58        .unwrap_or_else(syn::Error::into_compile_error)
59        .into()
60}
61
62/// Declare a named enum using an empty struct and `variant(name = "...")` attributes.
63/// Supports 1–64 unit or typed payload variants. Canonical name order determines
64/// stored ordinals; source declaration order does not. Use item(indirect, is = "Self")
65/// for boxed recursion, with a finite base alternative.
66/// All-unit enums also convert by reference into `ic_db::IndexValue`, using the
67/// same canonical order. Any payload variant excludes the whole enum from indexes.
68#[proc_macro_attribute]
69pub fn enum_(args: TokenStream, item: TokenStream) -> TokenStream {
70    enumeration::expand(args.into(), item.into())
71        .unwrap_or_else(syn::Error::into_compile_error)
72        .into()
73}
74
75/// Declare a reusable ordered list with an item type and a shared maximum length.
76#[proc_macro_attribute]
77pub fn list(args: TokenStream, item: TokenStream) -> TokenStream {
78    wrapped::expand(args.into(), item.into(), true)
79        .unwrap_or_else(syn::Error::into_compile_error)
80        .into()
81}
82
83/// Declare a distinct Rust and schema type around one primitive, including its bounds.
84#[proc_macro_attribute]
85pub fn newtype(args: TokenStream, item: TokenStream) -> TokenStream {
86    wrapped::expand(args.into(), item.into(), false)
87        .unwrap_or_else(syn::Error::into_compile_error)
88        .into()
89}
90
91/// Declare a bounded ordered set with `item(...)` and `max_items = N` (0..256).
92/// Elements can be primitives, scalar newtypes or unit enums. The generated
93/// wrapper contains a `BTreeSet<T>`. Decoding requires strictly increasing keys.
94#[proc_macro_attribute]
95pub fn set(args: TokenStream, item: TokenStream) -> TokenStream {
96    set::expand(args.into(), item.into())
97        .unwrap_or_else(syn::Error::into_compile_error)
98        .into()
99}
100
101/// Declare a named `BTreeMap` wrapper using `key(...)`, `value(...)` and
102/// `max_items = N` (0..256). Keys are primitives, scalar newtypes or unit enums. Values use the
103/// ordinary optional/list/named field rules; stored duplicate keys refuse.
104#[proc_macro_attribute]
105pub fn map(args: TokenStream, item: TokenStream) -> TokenStream {
106    map::expand(args.into(), item.into())
107        .unwrap_or_else(syn::Error::into_compile_error)
108        .into()
109}
110
111/// Declare a named stored record using attribute-owned fields and an empty struct.
112#[proc_macro_attribute]
113pub fn record(args: TokenStream, item: TokenStream) -> TokenStream {
114    record::expand(args.into(), item.into())
115        .unwrap_or_else(syn::Error::into_compile_error)
116        .into()
117}
118
119/// Declare a logical database canister.
120#[proc_macro_attribute]
121pub fn canister(args: TokenStream, item: TokenStream) -> TokenStream {
122    ownership::expand(args.into(), item.into(), false)
123        .unwrap_or_else(syn::Error::into_compile_error)
124        .into()
125}
126
127/// Declare a store with a typed canister owner and an IC Storage allocation key.
128#[proc_macro_attribute]
129pub fn store(args: TokenStream, item: TokenStream) -> TokenStream {
130    ownership::expand(args.into(), item.into(), true)
131        .unwrap_or_else(syn::Error::into_compile_error)
132        .into()
133}
134
135fn membership(name: &syn::Ident) -> Tokens {
136    quote! {
137            const _: () = {
138                if let ::std::option::Option::Some(root) = ::std::option_env!("IC_DB_SCHEMA_ROOT") {
139                    const PATH: &str = ::std::concat!(::std::module_path!(), "::", ::std::stringify!(#name));
140                    ::std::assert!(
141                        ::ic_db::__private::check_schema_member(
142                            PATH, root,
143                            ::std::option_env!(::std::concat!("IC_DB_SCHEMA_MEMBER_", ::std::stringify!(#name))),
144                        ),
145                        ::std::concat!("declaration missing from host schema: ", ::std::module_path!(), "::", ::std::stringify!(#name)),
146                    );
147                }
148            };
149    }
150}
151
152fn owner_path(meta: &Meta) -> syn::Result<syn::Path> {
153    if let Meta::NameValue(pair) = meta
154        && let Expr::Path(path) = &pair.value
155    {
156        return Ok(path.path.clone());
157    }
158    Err(syn::Error::new_spanned(meta, "expected a Rust type path"))
159}
160
161struct Index {
162    name: String,
163    fields: Vec<String>,
164    unique: bool,
165    present_only: bool,
166}
167
168// Supply Serde through ic-db even in schema crates without a direct serde dependency.
169fn schema_attrs(attrs: &[syn::Attribute]) -> syn::Result<Tokens> {
170    let mut serialize = true;
171    let mut deserialize = true;
172    let mut supply_crate = true;
173    for attr in attrs {
174        if attr.path().is_ident("derive") {
175            for path in
176                attr.parse_args_with(Punctuated::<syn::Path, Token![,]>::parse_terminated)?
177            {
178                if let Some(name) = path.segments.last() {
179                    serialize &= name.ident != "Serialize";
180                    deserialize &= name.ident != "Deserialize";
181                }
182            }
183        } else if attr.path().is_ident("serde") {
184            supply_crate &= !meta_items(&attr.meta)?
185                .iter()
186                .any(|m| m.path().is_ident("crate"));
187        }
188    }
189    let ser = serialize.then(|| quote!(#[derive(::ic_db::__private::serde::Serialize)]));
190    let de = deserialize.then(|| quote!(#[derive(::ic_db::__private::serde::Deserialize)]));
191    let path = (supply_crate && (serialize || deserialize))
192        .then(|| quote!(#[serde(crate = "::ic_db::__private::serde")]));
193
194    Ok(quote!(#ser #de #(#attrs)* #path))
195}
196
197fn metas(tokens: Tokens) -> syn::Result<Vec<Meta>> {
198    Ok(Punctuated::<Meta, Token![,]>::parse_terminated
199        .parse2(tokens)?
200        .into_iter()
201        .collect())
202}
203
204fn meta_items(meta: &Meta) -> syn::Result<Vec<Meta>> {
205    match meta {
206        Meta::List(value) => metas(value.tokens.clone()),
207        _ => Err(syn::Error::new_spanned(meta, "expected attribute list")),
208    }
209}
210
211fn literal(meta: &Meta) -> syn::Result<&Lit> {
212    if let Meta::NameValue(value) = meta
213        && let Expr::Lit(value) = &value.value
214    {
215        return Ok(&value.lit);
216    }
217
218    Err(syn::Error::new_spanned(meta, "expected literal value"))
219}
220
221fn text(meta: &Meta) -> syn::Result<String> {
222    if let Lit::Str(value) = literal(meta)? {
223        return Ok(value.value());
224    }
225
226    Err(syn::Error::new_spanned(meta, "expected a string"))
227}
228
229fn once<T>(slot: &mut Option<T>, value: T, meta: &Meta) -> syn::Result<()> {
230    if slot.replace(value).is_some() {
231        return Err(syn::Error::new_spanned(meta, "duplicate attribute"));
232    }
233
234    Ok(())
235}
236
237fn fields(meta: &Meta) -> syn::Result<Vec<String>> {
238    if let Meta::NameValue(value) = meta
239        && let Expr::Array(values) = &value.value
240    {
241        return values
242            .elems
243            .iter()
244            .map(|value| {
245                if let Expr::Lit(value) = value
246                    && let Lit::Str(value) = &value.lit
247                {
248                    return Ok(value.value());
249                }
250
251                Err(syn::Error::new_spanned(value, "expected field name"))
252            })
253            .collect();
254    }
255
256    Err(syn::Error::new_spanned(
257        meta,
258        "expected an array of field names",
259    ))
260}
261
262fn declaration_name(name: Option<String>, ident: &syn::Ident, kind: &str) -> syn::Result<String> {
263    let name = name.unwrap_or_else(|| ident.to_string());
264    if !(1..=64).contains(&name.len()) {
265        return Err(syn::Error::new_spanned(
266            ident,
267            format!("{kind} name must contain 1..64 UTF-8 bytes"),
268        ));
269    }
270
271    Ok(name)
272}
273
274fn declaration(item: Tokens, kind: &str) -> syn::Result<ItemStruct> {
275    let item: ItemStruct = syn::parse2(item)?;
276    if !matches!(&item.fields, syn::Fields::Named(fields) if fields.named.is_empty())
277        || !item.generics.params.is_empty()
278        || item.generics.where_clause.is_some()
279    {
280        return Err(syn::Error::new_spanned(
281            &item,
282            format!("{kind} requires an empty, nongeneric struct body without a where clause"),
283        ));
284    }
285
286    Ok(item)
287}
288
289fn expand(args: Tokens, item: Tokens) -> syn::Result<Tokens> {
290    let item = declaration(item, "entity")?;
291    let mut logical_name = None;
292    let mut primary = None;
293    let mut store = None;
294    let mut authored = None;
295    let mut timestamps = None;
296    let mut indexes = Vec::new();
297    for meta in metas(args)? {
298        if meta.path().is_ident("name") {
299            once(&mut logical_name, text(&meta)?, &meta)?;
300        } else if meta.path().is_ident("store") {
301            once(&mut store, owner_path(&meta)?, &meta)?;
302        } else if matches!(&meta, Meta::Path(path) if path.is_ident("timestamps")) {
303            once(&mut timestamps, (), &meta)?;
304        } else if meta.path().is_ident("pk") {
305            let mut key = None;
306            for part in meta_items(&meta)? {
307                if part.path().is_ident("field") {
308                    once(&mut key, text(&part)?, &part)?;
309                } else {
310                    return Err(syn::Error::new_spanned(
311                        part,
312                        "pk accepts only field = \"name\"",
313                    ));
314                }
315            }
316            let key = key.ok_or_else(|| syn::Error::new_spanned(&meta, "pk requires field"))?;
317            once(&mut primary, key, &meta)?;
318        } else if meta.path().is_ident("fields") {
319            let values = meta_items(&meta)?
320                .iter()
321                .map(Field::parse)
322                .collect::<syn::Result<Vec<_>>>()?;
323            once(&mut authored, values, &meta)?;
324        } else if meta.path().is_ident("index") {
325            let mut index_name = None;
326            let mut names = None;
327            let mut unique = false;
328            let mut present_only = false;
329            for part in meta_items(&meta)? {
330                if part.path().is_ident("name") {
331                    once(&mut index_name, text(&part)?, &part)?;
332                } else if part.path().is_ident("fields") {
333                    once(&mut names, fields(&part)?, &part)?;
334                } else if part.path().is_ident("field") {
335                    once(&mut names, vec![text(&part)?], &part)?;
336                } else if matches!(&part, Meta::Path(path) if path.is_ident("unique")) && !unique {
337                    unique = true;
338                } else if matches!(&part, Meta::Path(path) if path.is_ident("present_only"))
339                    && !present_only
340                {
341                    present_only = true;
342                } else {
343                    return Err(syn::Error::new_spanned(
344                        part,
345                        "unsupported or duplicate index option",
346                    ));
347                }
348            }
349            let fields =
350                names.ok_or_else(|| syn::Error::new_spanned(&meta, "index requires fields"))?;
351            indexes.push(Index {
352                name: index_name.unwrap_or_else(|| fields.join(",")),
353                fields,
354                unique,
355                present_only,
356            });
357        } else {
358            return Err(syn::Error::new_spanned(meta, "unsupported entity option"));
359        }
360    }
361    let fail = |message| syn::Error::new_spanned(&item.ident, message);
362    let logical_name = declaration_name(logical_name, &item.ident, "entity")?;
363    let store = store.ok_or_else(|| fail("entity requires store = StoreType"))?;
364    let primary = primary.ok_or_else(|| fail("entity requires pk"))?;
365    let mut authored = authored.ok_or_else(|| fail("entity requires fields"))?;
366    if timestamps.is_some() {
367        for (name, role) in [
368            ("created_at", field::Management::CreatedAt),
369            ("updated_at", field::Management::UpdatedAt),
370        ] {
371            authored.push(Field {
372                managed: Some(role),
373                ..Field::nested(name, field::Kind::Timestamp, false, None)
374            });
375        }
376    }
377    let names: BTreeSet<_> = authored.iter().map(|field| &field.name).collect();
378    if names.len() != authored.len()
379        || authored.is_empty()
380        || authored.len() > 16
381        || !names.contains(&primary)
382        || authored.iter().any(|field| field.name.len() > 64)
383    {
384        return Err(fail(
385            "invalid, duplicate or excessive fields/primary key (1..16 fields)",
386        ));
387    }
388    let field_ids: Vec<syn::Ident> = authored
389        .iter()
390        .map(|field| syn::parse_str(&field.name))
391        .collect::<syn::Result<_>>()?;
392    let mut constant_names = BTreeSet::new();
393    let mut field_constants = Vec::with_capacity(authored.len());
394    for field in &authored {
395        let source = &field.name;
396        let constant = source
397            .strip_prefix("r#")
398            .unwrap_or(source)
399            .to_ascii_uppercase();
400        if !constant_names.insert(constant.clone()) {
401            return Err(fail(&format!(
402                "fields generate the same associated constant `{constant}`"
403            )));
404        }
405        let ident = syn::parse_str::<syn::Ident>(&constant)?;
406        let doc = format!("Logical field name `{source}` for fluent queries.");
407        field_constants.push(quote! { #[doc = #doc] pub const #ident: &'static str = #source; });
408    }
409    let key_type = authored
410        .iter()
411        .find(|field| field.name == primary && field.required_key())
412        .ok_or_else(|| {
413            fail("primary key currently requires a non-optional integer, U256, Ulid, Principal, Account or Subaccount")
414        })?
415        .rust_type();
416    let key_id: syn::Ident = syn::parse_str(&primary)?;
417    indexes.sort_by(|left, right| left.name.cmp(&right.name));
418    if indexes.len() > 8
419        || indexes.windows(2).any(|pair| pair[0].name == pair[1].name)
420        || indexes
421            .iter()
422            .any(|index| index.name.is_empty() || index.name.len() > 64)
423    {
424        return Err(fail(
425            "indexes require distinct names of 1..64 bytes (maximum eight); use name to disambiguate",
426        ));
427    }
428    let mut descriptions = Vec::new();
429    let mut encoded_indexes = Vec::new();
430    for field in &mut authored {
431        if let Some((_, selected)) = &mut field.reference {
432            let candidates: Vec<_> = indexes
433                .iter()
434                .filter(|index| !index.present_only && index.fields.first() == Some(&field.name))
435                .map(|index| index.name.as_str())
436                .collect();
437            match (selected.as_deref(), candidates.as_slice()) {
438                (Some(name), _) if candidates.contains(&name) => {}
439                (None, [name]) => *selected = Some((*name).to_owned()),
440                (requested, eligible) => {
441                    let reason = match requested {
442                        Some(name) => format!("cannot use index {name:?}"),
443                        None => "requires one matching index".to_owned(),
444                    };
445                    let hint = if eligible.is_empty() {
446                        format!(
447                            "declare an unfiltered index beginning with {:?}",
448                            field.name
449                        )
450                    } else {
451                        format!("select one with `index = ...` from {eligible:?}")
452                    };
453                    return Err(fail(&format!(
454                        "reference {}.{} {reason}; {hint}",
455                        item.ident, field.name
456                    )));
457                }
458            }
459        }
460    }
461    let mut unique_keys = unique::Keys::default();
462    for index in indexes {
463        let unique_fields: BTreeSet<_> = index.fields.iter().collect();
464        if index.fields.is_empty()
465            || index.fields.len() > 4
466            || unique_fields.len() != index.fields.len()
467            || index.fields.iter().any(|name| {
468                !authored
469                    .iter()
470                    .any(|field| &field.name == name && field.indexable())
471            })
472        {
473            return Err(fail(
474                "index requires 1..4 distinct supported scalar or unit-enum fields",
475            ));
476        }
477        let fields: Vec<syn::Ident> = index
478            .fields
479            .iter()
480            .map(|name| syn::parse_str(name))
481            .collect::<syn::Result<_>>()?;
482        let index_name = index.name;
483        let unique = index.unique;
484        let present_only = index.present_only;
485        let has_optional = index.fields.iter().any(|name| {
486            authored
487                .iter()
488                .any(|field| &field.name == name && field.optional)
489        });
490        if (unique && has_optional && !present_only) || (present_only && (!unique || !has_optional))
491        {
492            return Err(fail(
493                "optional unique indexes require present_only; present_only requires uniqueness and an optional component",
494            ));
495        }
496        let operands: Vec<_> = index
497            .fields
498            .iter()
499            .zip(&fields)
500            .map(|(name, ident)| {
501                let field = authored
502                    .iter()
503                    .find(|field| &field.name == name)
504                    .expect("admitted index field");
505                let value = field.index_value(ident);
506                let optional = field.optional;
507
508                quote!((#value, #optional))
509            })
510            .collect();
511        if unique {
512            unique_keys.add(&item, &index_name, &fields, &authored, &index.fields);
513        }
514        let names = index.fields;
515        descriptions.push(quote! { ::ic_db::IndexSchema { id: ::ic_db::__private::handle(#index_name), name: #index_name, fields: &[#(#names),*], unique: #unique, present_only: #present_only } });
516        encoded_indexes
517            .push(quote! { ::ic_db::__private::encode_index(&[#(#operands),*], #present_only) });
518    }
519    let lookup_keys = unique_keys.declarations;
520    let name = &item.ident;
521    let attrs = crate::schema_attrs(&item.attrs)?;
522    let visibility = &item.vis;
523    let mut ordered: Vec<_> = authored.iter().collect();
524    ordered.sort_by_key(|field| &field.name);
525    let ordered_ids: Vec<syn::Ident> = ordered
526        .iter()
527        .map(|field| syn::parse_str(&field.name))
528        .collect::<syn::Result<_>>()?;
529    let nested_writes: Vec<_> = ordered
530        .iter()
531        .zip(&ordered_ids)
532        .filter(|(f, _)| f.many.is_some() || matches!(f.kind, field::Kind::Named(..)))
533        .map(|(f, id)| f.encode(id))
534        .collect();
535    let nested_validation = if nested_writes.is_empty() {
536        quote!()
537    } else {
538        quote! { let mut writer = ::ic_db::__private::Encoder::new(); #(#nested_writes)* }
539    };
540    let writes: Vec<_> = ordered
541        .iter()
542        .zip(&ordered_ids)
543        .map(|(field, id)| field.encode(id))
544        .collect();
545    let reads: Vec<_> = ordered
546        .iter()
547        .zip(&ordered_ids)
548        .map(|(field, id)| field.decode(id))
549        .collect();
550    let authored_types: Vec<_> = authored.iter().map(Field::rust_type).collect();
551    let descriptions_fields: Vec<_> = ordered.iter().map(|field| field.description()).collect();
552    let validations: Vec<_> = authored
553        .iter()
554        .zip(&field_ids)
555        .map(|(field, id)| field.validation(id))
556        .collect();
557    if authored
558        .iter()
559        .any(|field| field.name == primary && field.default.is_some())
560    {
561        return Err(syn::Error::new_spanned(
562            &item.ident,
563            "supplied primary keys cannot declare an insert default",
564        ));
565    }
566    let insert_input = insert::emit(&item, &authored)?;
567    let mut managed_fields = [None, None];
568    for (field, id) in authored.iter().zip(&field_ids) {
569        if let Some(policy) = field.managed {
570            let slot = usize::from(policy == field::Management::UpdatedAt);
571            let timestamp = if matches!(field.kind, field::Kind::Named(..)) {
572                quote!(#id.0)
573            } else {
574                quote!(#id)
575            };
576            if managed_fields[slot].replace(timestamp).is_some() {
577                return Err(syn::Error::new_spanned(
578                    id,
579                    "each managed timestamp role may appear once per entity",
580                ));
581            }
582        }
583    }
584    let managed_check = |owner: Tokens| {
585        if managed_fields.iter().all(Option::is_none) {
586            return quote!();
587        }
588        let values = managed_fields.iter().map(|field| {
589            field
590                .as_ref()
591                .map_or_else(|| quote!(None), |field| quote!(Some(#owner.#field)))
592        });
593
594        quote!(::ic_db::__private::validate_managed_order([#(#values),*])?;)
595    };
596    let membership = membership(name);
597    let reference_checks = authored.iter().filter_map(|field| field.reference.as_ref()).map(|(target,_)| quote! {
598        { fn same_store<T: ::ic_db::Entity<Store = #store>>() {} let _ = same_store::<#target>; }
599    });
600    let validate_managed = managed_check(quote!(self));
601    let decode_managed = managed_check(quote!(row));
602
603    Ok(quote! {
604        #insert_input
605        #(#lookup_keys)*
606        #attrs
607        #[derive(Clone, Debug, PartialEq, Eq)]
608        #visibility struct #name { #(#[doc = "Authored stored field."] pub #field_ids: #authored_types,)* }
609
610        impl #name { #(#field_constants)* }
611
612        impl ::ic_db::Entity for #name {
613            type Store = #store;
614            type Key = #key_type;
615            fn declaration_path() -> &'static str { #(#reference_checks)* concat!(module_path!(), "::", stringify!(#name)) }
616            const SCHEMA: &'static ::ic_db::EntitySchema = &::ic_db::EntitySchema {
617                id: ::ic_db::__private::handle(#logical_name), name: #logical_name, fields: &[#(#descriptions_fields),*], primary_key: #primary,
618                indexes: &[#(#descriptions),*],
619            };
620            fn key(&self) -> Self::Key { self.#key_id }
621
622            fn __row_info(&self) -> ::ic_db::__private::RowInfo {
623                let row = self;
624
625                ::ic_db::__private::RowInfo {
626                    key: ::ic_db::PrimaryKey::into_row_key(<Self as ::ic_db::Entity>::key(row)),
627                    indexes: ::std::vec![#(#encoded_indexes),*]
628                }
629            }
630
631            fn validate(&self) -> Result<(), ::ic_db::Error> {
632                #validate_managed
633                #(#validations)*
634                #nested_validation
635
636                Ok(())
637            }
638
639            fn encode(&self) -> Result<::std::vec::Vec<u8>, ::ic_db::Error> {
640                #validate_managed
641                let mut writer = ::ic_db::__private::Encoder::new();
642                #(#writes)*
643
644                Ok(writer.finish())
645            }
646
647            fn decode(bytes: &[u8]) -> Result<Self, ::ic_db::Error> {
648                let mut reader = ::ic_db::__private::Decoder::new(bytes)?;
649                let row = Self { #(#reads)* };
650                reader.finish()?;
651                #decode_managed
652
653                Ok(row)
654            }
655        }
656
657        impl ::ic_db::__private::ReferenceTarget for #name {
658            const NAME: &'static str = #logical_name;
659        }
660
661        #membership
662        ::ic_db::__register_schema!(#name);
663    })
664}