-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathtable.rs
More file actions
1552 lines (1399 loc) · 57.8 KB
/
table.rs
File metadata and controls
1552 lines (1399 loc) · 57.8 KB
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::sats;
use crate::sym;
use crate::util::{check_duplicate, check_duplicate_msg, match_meta};
use core::slice;
use heck::ToSnakeCase;
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote, quote_spanned, ToTokens};
use std::borrow::Cow;
use syn::ext::IdentExt;
use syn::meta::ParseNestedMeta;
use syn::parse::Parse;
use syn::parse::Parser as _;
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::LitStr;
use syn::{parse_quote, Ident, Path, Token};
pub(crate) struct TableArgs {
access: Option<TableAccess>,
name: Option<LitStr>,
scheduled: Option<ScheduledArg>,
accessor: Ident,
indices: Vec<IndexArg>,
event: Option<Span>,
outbox: Option<OutboxArg>,
}
/// Parsed from `outbox(remote_reducer_fn, on_result = local_reducer_fn)`.
///
/// For backwards compatibility, `on_result(local_reducer_fn)` is also accepted as a sibling
/// table attribute and attached to the previously-declared outbox.
struct OutboxArg {
span: Span,
/// Path to the remote-side reducer function, used only for its final path segment.
remote_reducer: Path,
/// Path to the local `on_result` reducer, if any.
on_result_reducer: Option<Path>,
}
fn path_tail_name(path: &Path) -> LitStr {
let segment = path
.segments
.last()
.expect("syn::Path should always contain at least one segment");
LitStr::new(&segment.ident.to_string(), segment.ident.span())
}
enum TableAccess {
Public(Span),
Private(Span),
}
impl TableAccess {
fn to_value(&self) -> TokenStream {
let (TableAccess::Public(span) | TableAccess::Private(span)) = *self;
let name = match self {
TableAccess::Public(_) => "Public",
TableAccess::Private(_) => "Private",
};
let ident = Ident::new(name, span);
quote_spanned!(span => spacetimedb::table::TableAccess::#ident)
}
}
struct ScheduledArg {
span: Span,
reducer_or_procedure: Path,
at: Option<Ident>,
}
struct IndexArg {
accessor: Ident,
canonical_name: Option<LitStr>,
is_unique: bool,
kind: IndexType,
}
impl IndexArg {
fn new(accessor: Ident, kind: IndexType, canonical_name: Option<LitStr>) -> Self {
// We don't know if its unique yet.
// We'll discover this once we have collected constraints.
let is_unique = false;
Self {
canonical_name,
accessor,
is_unique,
kind,
}
}
}
enum IndexType {
BTree { columns: Vec<Ident> },
Hash { columns: Vec<Ident> },
Direct { column: Ident },
}
impl TableArgs {
pub(crate) fn parse(input: TokenStream, struct_ident: &Ident) -> syn::Result<Self> {
let mut access = None;
let mut scheduled = None;
let mut accessor = None;
let mut name: Option<LitStr> = None;
let mut indices = Vec::new();
let mut event = None;
let mut outbox: Option<OutboxArg> = None;
syn::meta::parser(|meta| {
match_meta!(match meta {
sym::public => {
check_duplicate_msg(&access, &meta, "already specified access level")?;
access = Some(TableAccess::Public(meta.path.span()));
}
sym::private => {
check_duplicate_msg(&access, &meta, "already specified access level")?;
access = Some(TableAccess::Private(meta.path.span()));
}
sym::accessor => {
check_duplicate(&accessor, &meta)?;
let value = meta.value()?;
accessor = Some(value.parse()?);
}
sym::name => {
check_duplicate(&name, &meta)?;
let value = meta.value()?;
// `fork` as a way to do lookahead `peek`, so that below when we parse as the `LitStr` we actually want,
// it works.
if let Ok(sym) = value.fork().parse::<Ident>() {
// The update from SpacetimeDB 1.* to 2.* changes `name =` to `accessor =`,
// and uses `name =` for a different thing. Now, only `accessor =` is mandatory,
// and `name =` accepts a string literal rather than an identifier.
// Detect the specific case where the user specifies a 1.*-style `name = ident`,
// and offer a diagnostic with a simple migration path.
// Unfortunately, we can't hook in to rustc's system for providing quick fixes in compiler errors,
// until [this ancient issue](https://github.com/rust-lang/rust/issues/54140) gets stabilized.
return Err(
if accessor.is_some() {
// If we've already encountered an `accessor`,
// then probably the user is actually trying to overwrite the `name`,
// so tell them to use a string literal instead of an ident.
// This is a best-effort check, and we won't hit it if the user specifies `name` first,
// but we're prioritizing the migration UX here.
meta.error(format_args!(
"Expected a string literal for `name`, but found an identifier.
To overwrite the canonical name of the table, replace `name = {sym}` with `name = \"{sym}\"`."
))
} else {
// FIXME: Ideally, this error span would point to the full pair `name = my_table`,
// but I (pgoldman 2026-02-18) can only figure out how to get it at either `name` or `my_table`.
// This version points at `name`, which, :shrug:.
// Note that, if the user specifies `name = {ident}` followed by `accessor = {ident}`,
// we'll hit this branch, even though the diagnostic doesn't apply and we'd prefer not to.
// I (pgoldman 2026-02-18) don't see a good way to distinguish this case
// without making our parsing dramatically more complicated,
// and it seems unlikely to occur.
meta.error(format_args!(
"Expected a string literal for `name`, but found an identifier. Did you mean to specify an `accessor`?
If you're migrating from SpacetimeDB 1.*, replace `name = {sym}` with `accessor = {sym}`."
))
})
}
name = Some(value.parse()?);
}
sym::index => indices.push(IndexArg::parse_meta(meta)?),
sym::scheduled => {
check_duplicate(&scheduled, &meta)?;
scheduled = Some(ScheduledArg::parse_meta(meta)?);
}
sym::event => {
check_duplicate(&event, &meta)?;
event = Some(meta.path.span());
}
sym::outbox => {
check_duplicate_msg(&outbox, &meta, "already specified outbox")?;
outbox = Some(OutboxArg::parse_meta(meta)?);
}
sym::on_result => {
// `on_result` must be specified alongside `outbox`.
// We parse it here and attach it to the outbox arg below.
let span = meta.path.span();
let on_result_path = OutboxArg::parse_single_path_meta(meta)?;
match &mut outbox {
Some(ob) => {
if ob.on_result_reducer.is_some() {
return Err(syn::Error::new(span, "already specified on_result"));
}
ob.on_result_reducer = Some(on_result_path);
}
None => {
return Err(syn::Error::new(
span,
"on_result requires outbox to be specified first: `outbox(remote_reducer), on_result(local_reducer)`",
))
}
}
}
});
Ok(())
})
.parse2(input)?;
let accessor = accessor.ok_or_else(|| {
if let Some(name_str) = &name {
// If a user's gotten partway through migrating from 1.* to 2.* in a misguided way,
// they may end up with a `table` invocation that specifies `name = "my_table_name"` and no `accessor`.
// In this case, they probably intended to change `name =` to `accessor =`,
// but were misled into keeping `name =` and changing the name from an ident into a lit string.
// Detect that and offer a diagnostic with a simple fix.
// Unfortunately, we can't hook in to rustc's system for providing quick fixes in compiler errors,
// until [this ancient issue](https://github.com/rust-lang/rust/issues/54140) gets stabilized.
let name_str_value = name_str.value();
syn::Error::new_spanned(
name_str,
format_args!(
"Expected an `accessor` in table definition, but got only a `name`.
Did you mean to specify `accessor` instead?
`accessor` is required, but `name` is optional.
If you're migrating from SpacetimeDB 1.*, replace `name = {name_str_value:?}` with `accessor = {name_str_value}`",
),
)
} else {
let table = struct_ident.to_string().to_snake_case();
syn::Error::new(
Span::call_site(),
format_args!("must specify table accessor, e.g. `#[spacetimedb::table(accessor = {table})]"),
)
}
})?;
Ok(TableArgs {
access,
scheduled,
accessor,
indices,
name,
event,
outbox,
})
}
}
impl ScheduledArg {
fn parse_meta(meta: ParseNestedMeta) -> syn::Result<Self> {
let span = meta.path.span();
let mut reducer_or_procedure = None;
let mut at = None;
meta.parse_nested_meta(|meta| {
if meta.input.peek(syn::Token![=]) || meta.input.peek(syn::token::Paren) {
match_meta!(match meta {
sym::at => {
check_duplicate(&at, &meta)?;
let ident = meta.value()?.parse()?;
at = Some(ident);
}
})
} else {
check_duplicate_msg(
&reducer_or_procedure,
&meta,
"can only specify one scheduled reducer or procedure",
)?;
reducer_or_procedure = Some(meta.path);
}
Ok(())
})?;
let reducer_or_procedure = reducer_or_procedure.ok_or_else(|| {
meta.error(
"must specify scheduled reducer or procedure associated with the table: scheduled(function_name)",
)
})?;
Ok(Self {
span,
reducer_or_procedure,
at,
})
}
}
impl OutboxArg {
/// Parse `outbox(remote_reducer_path, on_result = local_reducer_path)`.
///
/// For backwards compatibility, `on_result` may also be parsed separately via
/// `parse_single_path_meta` and attached afterwards.
fn parse_meta(meta: ParseNestedMeta) -> syn::Result<Self> {
let span = meta.path.span();
let mut remote_reducer: Option<Path> = None;
let mut on_result_reducer: Option<Path> = None;
meta.parse_nested_meta(|meta| {
if meta.input.peek(Token![=]) {
if meta.path.is_ident("on_result") {
check_duplicate_msg(
&on_result_reducer,
&meta,
"can only specify one on_result reducer",
)?;
on_result_reducer = Some(meta.value()?.parse()?);
Ok(())
} else {
Err(meta.error(
"outbox only supports `on_result = my_local_reducer` as a named argument",
))
}
} else if meta.input.peek(syn::token::Paren) {
Err(meta.error(
"outbox expects a remote reducer path and optional `on_result = my_local_reducer`, e.g. `outbox(my_remote_reducer, on_result = my_local_reducer)`",
))
} else if meta.path.is_ident("on_result") {
Err(meta.error(
"outbox `on_result` must use `=`, e.g. `outbox(my_remote_reducer, on_result = my_local_reducer)`",
))
} else {
check_duplicate_msg(
&remote_reducer,
&meta,
"can only specify one remote reducer for outbox",
)?;
remote_reducer = Some(meta.path);
Ok(())
}
})?;
let remote_reducer = remote_reducer
.ok_or_else(|| syn::Error::new(span, "outbox requires a remote reducer: `outbox(my_remote_reducer)`"))?;
Ok(Self {
span,
remote_reducer,
on_result_reducer,
})
}
/// Parse `on_result(local_reducer_path)` and return the path.
fn parse_single_path_meta(meta: ParseNestedMeta) -> syn::Result<Path> {
let span = meta.path.span();
let mut result: Option<Path> = None;
meta.parse_nested_meta(|meta| {
if meta.input.peek(syn::Token![=]) || meta.input.peek(syn::token::Paren) {
Err(meta.error("on_result takes a single function path, e.g. `on_result(my_local_reducer)`"))
} else {
check_duplicate_msg(&result, &meta, "can only specify one on_result reducer")?;
result = Some(meta.path);
Ok(())
}
})?;
result.ok_or_else(|| {
syn::Error::new(
span,
"on_result requires a local reducer: `on_result(my_local_reducer)`",
)
})
}
}
impl IndexArg {
fn parse_meta(meta: ParseNestedMeta) -> syn::Result<Self> {
let mut accessor = None;
let mut canonical_name = None;
let mut algo = None;
meta.parse_nested_meta(|meta| {
match_meta!(match meta {
sym::accessor => {
check_duplicate(&accessor, &meta)?;
accessor = Some(meta.value()?.parse()?);
}
sym::name => {
check_duplicate(&canonical_name, &meta)?;
canonical_name = Some(meta.value()?.parse()?);
}
sym::btree => {
check_duplicate_msg(&algo, &meta, "index algorithm specified twice")?;
algo = Some(Self::parse_btree(meta)?);
}
sym::hash => {
check_duplicate_msg(&algo, &meta, "index algorithm specified twice")?;
algo = Some(Self::parse_hash(meta)?);
}
sym::direct => {
check_duplicate_msg(&algo, &meta, "index algorithm specified twice")?;
algo = Some(Self::parse_direct(meta)?);
}
sym::name => {
// If the user is trying to specify a `name`, do a bit of guessing at what their goal is.
// This is going to be best-effort, and we're not going to try to do lookahead or anything.
return Err(if accessor.is_some() {
// If the user's already specified an `accessor`,
// then probably they're trying to specify the canonical name,
// like you can for tables.
// Print an error that says this is unsupported.
meta.error(
"Unexpected argument `name` in index definition.
Overwriting the `name` of an index is currently unsupported.",
)
} else if let Ok(sym) = meta.value().and_then(|val| val.parse::<Ident>()) {
// If we haven't seen an `accessor` yet, and the value is an ident,
// then probably this is 1.* syntax that needs a migration.
// Note that, if the user specifies `name = {ident}` followed by `accessor = {ident}`,
// we'll hit this branch, even though the diagnostic doesn't apply and we'd prefer not to.
// I (pgoldman 2026-02-18) don't see a good way to distinguish this case
// without making our parsing dramatically more complicated,
// and it seems unlikely to occur.
meta.error(format_args!(
"Expected an `accessor` in index definition, but got a `name` instead.
If you're migrating from SpacetimeDB 1.*, replace `name = {sym}` with `accessor = {sym}`."
))
} else {
// If we haven't seen an `accessor` yet, but the value is not an ident,
// then we're not really sure what's going wrong, so print a more generic error message.
meta.error(format_args!(
"Unexpected argument `name` in index definition.
Overwriting the `name` of an index is currently unsupported.
Did you mean to specify an `accessor` instead? Do so with `accessor = my_index`, where `my_index` is an unquoted identifier."
))
});
}
});
Ok(())
})?;
let accessor = accessor.ok_or_else(|| meta.error("missing index accessor, e.g. `accessor = my_index`"))?;
let kind = algo.ok_or_else(|| {
meta.error(
"missing index algorithm, e.g., `btree(columns = [col1, col2])`, \
`hash(columns = [col1, col2])`, or `direct(column = col1)`",
)
})?;
Ok(IndexArg::new(accessor, kind, canonical_name))
}
fn parse_columns(meta: &ParseNestedMeta) -> syn::Result<Option<Vec<Ident>>> {
let mut columns = None;
meta.parse_nested_meta(|meta| {
match_meta!(match meta {
sym::columns => {
check_duplicate(&columns, &meta)?;
let value = meta.value()?;
let inner;
syn::bracketed!(inner in value);
columns = Some(
Punctuated::<Ident, Token![,]>::parse_terminated(&inner)?
.into_iter()
.collect::<Vec<_>>(),
);
}
});
Ok(())
})?;
Ok(columns)
}
fn parse_btree(meta: ParseNestedMeta) -> syn::Result<IndexType> {
let columns = Self::parse_columns(&meta)?;
let columns = columns
.ok_or_else(|| meta.error("must specify columns for btree index, e.g. `btree(columns = [col1, col2])`"))?;
Ok(IndexType::BTree { columns })
}
fn parse_hash(meta: ParseNestedMeta) -> syn::Result<IndexType> {
let columns = Self::parse_columns(&meta)?;
let columns = columns
.ok_or_else(|| meta.error("must specify columns for hash index, e.g. `hash(columns = [col1, col2])`"))?;
Ok(IndexType::Hash { columns })
}
fn parse_direct(meta: ParseNestedMeta) -> syn::Result<IndexType> {
let mut column = None;
meta.parse_nested_meta(|meta| {
match_meta!(match meta {
sym::column => {
check_duplicate(&column, &meta)?;
let value = meta.value()?;
let inner;
syn::bracketed!(inner in value);
column = Some(Ident::parse(&inner)?);
}
});
Ok(())
})?;
let column = column
.ok_or_else(|| meta.error("must specify the column for direct index, e.g. `direct(column = col1)`"))?;
Ok(IndexType::Direct { column })
}
/// Parses an inline `#[index(btree)]`, `#[index(hash)]`, or `#[index(direct)]` attribute on a field.
fn parse_index_attr(field: &Ident, attr: &syn::Attribute) -> syn::Result<Self> {
let mut kind = None;
attr.parse_nested_meta(|meta| {
match_meta!(match meta {
sym::btree => {
check_duplicate_msg(&kind, &meta, "index type specified twice")?;
kind = Some(IndexType::BTree {
columns: vec![field.clone()],
});
}
sym::hash => {
check_duplicate_msg(&kind, &meta, "index type specified twice")?;
kind = Some(IndexType::Hash {
columns: vec![field.clone()],
});
}
sym::direct => {
check_duplicate_msg(&kind, &meta, "index type specified twice")?;
kind = Some(IndexType::Direct { column: field.clone() })
}
});
Ok(())
})?;
let kind =
kind.ok_or_else(|| syn::Error::new_spanned(&attr.meta, "must specify kind of index (`btree` , `direct`)"))?;
// Default accessor = field name if not provided
let accessor = field.clone();
Ok(IndexArg::new(accessor, kind, None))
}
fn validate<'a>(&'a self, table_name: &str, cols: &'a [Column<'a>]) -> syn::Result<ValidatedIndex<'a>> {
let find_column = |ident| find_column(cols, ident);
let (kind, kind_str) = match &self.kind {
IndexType::BTree { columns } => {
let cols = columns.iter().map(find_column).collect::<syn::Result<Vec<_>>>()?;
(ValidatedIndexType::BTree { cols }, "btree")
}
IndexType::Hash { columns } => {
let cols = columns.iter().map(find_column).collect::<syn::Result<Vec<_>>>()?;
(ValidatedIndexType::Hash { cols }, "hash")
}
IndexType::Direct { column } => {
let col = find_column(column)?;
if !self.is_unique {
return Err(syn::Error::new(
column.span(),
"a direct index must be paired with a `#[unique] constraint",
));
}
(ValidatedIndexType::Direct { col }, "direct")
}
};
let gen_index_name = || {
// See crates/schema/src/validate/v9.rs for the format of index names.
// It's slightly unnerving that we just trust that component to generate this format correctly,
// but what can you do.
let cols = kind.columns();
let cols = cols.iter().map(|col| col.ident.to_string()).collect::<Vec<_>>();
let cols = cols.join("_");
format!("{table_name}_{cols}_idx_{kind_str}")
};
Ok(ValidatedIndex {
is_unique: self.is_unique,
// This must be the canonical name (name used internally in database),
// as it is used in `index_id_from_name` abi.
index_name: gen_index_name(),
accessor_name: &self.accessor,
kind,
canonical_name: self.canonical_name.as_ref().map(|s| s.value()),
})
}
}
enum AccessorType {
Read,
ReadWrite,
}
impl AccessorType {
fn unique(&self) -> proc_macro2::TokenStream {
match self {
AccessorType::Read => quote!(spacetimedb::UniqueColumnReadOnly),
AccessorType::ReadWrite => quote!(spacetimedb::UniqueColumn),
}
}
fn range(&self) -> proc_macro2::TokenStream {
match self {
AccessorType::Read => quote!(spacetimedb::RangedIndexReadOnly),
AccessorType::ReadWrite => quote!(spacetimedb::RangedIndex),
}
}
fn point(&self) -> proc_macro2::TokenStream {
match self {
AccessorType::Read => quote!(spacetimedb::PointIndexReadOnly),
AccessorType::ReadWrite => quote!(spacetimedb::PointIndex),
}
}
fn unique_doc_typename(&self) -> &'static str {
match self {
AccessorType::Read => "UniqueColumnReadOnly",
AccessorType::ReadWrite => "UniqueColumn",
}
}
fn range_doc_typename(&self) -> &'static str {
match self {
AccessorType::Read => "RangedIndexReadOnly",
AccessorType::ReadWrite => "RangedIndex",
}
}
fn point_doc_typename(&self) -> &'static str {
match self {
AccessorType::Read => "PointIndexReadOnly",
AccessorType::ReadWrite => "PointIndex",
}
}
}
struct ValidatedIndex<'a> {
index_name: String,
accessor_name: &'a Ident,
is_unique: bool,
kind: ValidatedIndexType<'a>,
canonical_name: Option<String>,
}
enum ValidatedIndexType<'a> {
BTree { cols: Vec<&'a Column<'a>> },
Hash { cols: Vec<&'a Column<'a>> },
Direct { col: &'a Column<'a> },
}
impl ValidatedIndexType<'_> {
fn columns(&self) -> &[&Column<'_>] {
match self {
Self::BTree { cols } | Self::Hash { cols } => cols,
Self::Direct { col } => slice::from_ref(col),
}
}
fn one_col(&self) -> Option<&Column<'_>> {
match self.columns() {
[col] => Some(col),
_ => None,
}
}
}
impl ValidatedIndex<'_> {
fn desc(&self) -> TokenStream {
let algo = match &self.kind {
ValidatedIndexType::BTree { cols } => {
let col_ids = cols.iter().map(|col| col.index);
quote!(spacetimedb::table::IndexAlgo::BTree {
columns: &[#(#col_ids),*]
})
}
ValidatedIndexType::Hash { cols } => {
let col_ids = cols.iter().map(|col| col.index);
quote!(spacetimedb::table::IndexAlgo::Hash {
columns: &[#(#col_ids),*]
})
}
ValidatedIndexType::Direct { col } => {
let col_id = col.index;
quote!(spacetimedb::table::IndexAlgo::Direct {
column: #col_id
})
}
};
let source_name = self.index_name.clone();
let accessor_name = self.accessor_name.to_string();
// Note: we do not pass the index_name through here.
// We trust the schema validation logic to reconstruct the name we've stored in `self.name`.
//TODO(shub): pass generated index name instead of accessor name as source_name
quote!(spacetimedb::table::IndexDesc {
source_name: #source_name,
accessor_name: #accessor_name,
algo: #algo,
})
}
fn accessor(
&self,
vis: &syn::Visibility,
row_type_ident: &Ident,
tbl_type_ident: &Ident,
flavor: AccessorType,
) -> TokenStream {
if self.is_unique {
self.unique_accessor(row_type_ident, tbl_type_ident, flavor)
} else {
self.non_unique_accessor(vis, row_type_ident, tbl_type_ident, flavor)
}
}
fn unique_accessor(&self, row_type_ident: &Ident, tbl_type_ident: &Ident, flavor: AccessorType) -> TokenStream {
let col = self.kind.one_col().unwrap();
let index_ident = self.accessor_name;
let vis = col.vis;
let col_ty = col.ty;
let column_ident = col.ident;
let unique_ty = flavor.unique();
let tbl_token = quote!(#tbl_type_ident);
let doc_type = flavor.unique_doc_typename();
let doc = format!(
"Gets the [`{doc_type}`][spacetimedb::{doc_type}] for the \
[`{column_ident}`][{row_type_ident}::{column_ident}] column."
);
quote! {
#[doc = #doc]
#vis fn #column_ident(&self) -> #unique_ty<#tbl_token, #col_ty, __indices::#index_ident> {
#unique_ty::__NEW
}
}
}
fn non_unique_accessor(
&self,
vis: &syn::Visibility,
row_type_ident: &Ident,
tbl_type_ident: &Ident,
flavor: AccessorType,
) -> TokenStream {
let index_ident = self.accessor_name;
let cols = self.kind.columns();
let col_tys = cols.iter().map(|c| c.ty);
let (handle_ty, doc_type, kind_doc) = match &self.kind {
ValidatedIndexType::BTree { .. } => (flavor.range(), flavor.range_doc_typename(), "B-tree"),
// Should be unreachable, but we might as well include this.
ValidatedIndexType::Direct { .. } => (flavor.range(), flavor.range_doc_typename(), "Direct"),
ValidatedIndexType::Hash { .. } => (flavor.point(), flavor.point_doc_typename(), "Hash"),
};
let mut doc = format!(
"Gets the `{index_ident}` [`{doc_type}`][spacetimedb::{doc_type}] as defined \
on this table.\n\nThis {kind_doc} index is defined on the following columns, in order:\n"
);
for col in cols {
use std::fmt::Write;
writeln!(
doc,
"- [`{ident}`][{row_type_ident}#structfield.{ident}]: [`{ty}`]",
ident = col.ident,
ty = col.ty.to_token_stream()
)
.unwrap();
}
let tbl_token = quote!(#tbl_type_ident);
quote! {
#[doc = #doc]
#vis fn #index_ident(&self) -> #handle_ty<#tbl_token, (#(#col_tys,)*), __indices::#index_ident> {
#handle_ty::__NEW
}
}
}
fn marker_type(
&self,
vis: &syn::Visibility,
tablehandle_ident: &Ident,
primary_key_column: Option<&Column<'_>>,
) -> TokenStream {
let index_ident = self.accessor_name;
let index_name = &self.index_name;
let (typeck_direct_index, is_ranged) = match &self.kind {
ValidatedIndexType::BTree { .. } => (None, true),
ValidatedIndexType::Direct { col } => {
let col_ty = col.ty;
let typeck = quote_spanned!(col_ty.span()=>
const _: () = {
spacetimedb::spacetimedb_lib::assert_column_type_valid_for_direct_index::<#col_ty>();
};
);
(Some(typeck), true)
}
ValidatedIndexType::Hash { .. } => (None, false),
};
let vis = if self.is_unique {
self.kind.one_col().unwrap().vis
} else {
vis
};
let vis = superize_vis(vis);
let cols = self.kind.columns();
let num_cols = cols.len();
let index_kind_trait = if is_ranged {
quote!(IndexIsRanged)
} else {
quote!(IndexIsPointed)
};
let mut decl = quote! {
#typeck_direct_index
#vis struct #index_ident;
impl spacetimedb::table::#index_kind_trait for #index_ident {}
impl spacetimedb::table::Index for #index_ident {
const NUM_COLS_INDEXED: usize = #num_cols;
fn index_id() -> spacetimedb::table::IndexId {
static INDEX_ID: std::sync::OnceLock<spacetimedb::table::IndexId> = std::sync::OnceLock::new();
*INDEX_ID.get_or_init(|| {
spacetimedb::sys::index_id_from_name(#index_name).unwrap()
})
}
}
};
if self.is_unique {
let col = self.kind.one_col().unwrap();
let col_ty = col.ty;
let col_name = col.ident.to_string();
let field_ident = col.ident;
decl.extend(quote! {
impl spacetimedb::table::Column for #index_ident {
type Table = #tablehandle_ident;
type ColType = #col_ty;
const COLUMN_NAME: &'static str = #col_name;
fn get_field(row: &<Self::Table as spacetimedb::Table>::Row) -> &Self::ColType {
&row.#field_ident
}
}
});
if primary_key_column.is_some_and(|pk| col.ident == pk.ident) {
decl.extend(quote!(impl spacetimedb::table::PrimaryKey for #index_ident {}));
}
}
decl
}
}
/// Transform a visibility marker to one with the same effective visibility, but
/// for use in a child module of the module of the original marker.
fn superize_vis(vis: &syn::Visibility) -> Cow<'_, syn::Visibility> {
match vis {
syn::Visibility::Public(_) => Cow::Borrowed(vis),
syn::Visibility::Restricted(vis_r) => {
let first = &vis_r.path.segments[0];
if first.ident == "crate" || vis_r.path.leading_colon.is_some() {
Cow::Borrowed(vis)
} else {
let mut vis_r = vis_r.clone();
if first.ident == "super" {
vis_r.path.segments.insert(0, first.clone())
} else if first.ident == "self" {
vis_r.path.segments[0].ident = Ident::new("super", Span::call_site())
}
Cow::Owned(syn::Visibility::Restricted(vis_r))
}
}
syn::Visibility::Inherited => Cow::Owned(parse_quote!(pub(super))),
}
}
#[derive(Clone)]
struct Column<'a> {
index: u16,
vis: &'a syn::Visibility,
ident: &'a syn::Ident,
ty: &'a syn::Type,
default_value: Option<syn::Expr>,
}
fn try_find_column<'a, 'b, T: ?Sized>(cols: &'a [Column<'b>], name: &T) -> Option<&'a Column<'b>>
where
Ident: PartialEq<T>,
{
cols.iter().find(|col| col.ident == name)
}
fn find_column<'a, 'b>(cols: &'a [Column<'b>], name: &Ident) -> syn::Result<&'a Column<'b>> {
try_find_column(cols, name).ok_or_else(|| syn::Error::new(name.span(), "not a column of the table"))
}
enum ColumnAttr {
Unique(Span),
AutoInc(Span),
PrimaryKey(Span),
Index(IndexArg),
Default(syn::Expr, Span),
}
impl ColumnAttr {
fn parse(attr: &syn::Attribute, field_ident: &Ident) -> syn::Result<Option<Self>> {
let Some(ident) = attr.path().get_ident() else {
return Ok(None);
};
Ok(if ident == sym::index {
let index = IndexArg::parse_index_attr(field_ident, attr)?;
Some(ColumnAttr::Index(index))
} else if ident == sym::unique {
attr.meta.require_path_only()?;
Some(ColumnAttr::Unique(ident.span()))
} else if ident == sym::auto_inc {
attr.meta.require_path_only()?;
Some(ColumnAttr::AutoInc(ident.span()))
} else if ident == sym::primary_key {
attr.meta.require_path_only()?;
Some(ColumnAttr::PrimaryKey(ident.span()))
} else if ident == sym::default {
Some(parse_default_attr(attr, ident)?)
} else {
None
})
}
}
fn parse_default_attr(attr: &syn::Attribute, ident: &Ident) -> syn::Result<ColumnAttr> {
if let Ok(expr) = attr.parse_args::<syn::Expr>() {
return Ok(ColumnAttr::Default(expr, ident.span()));
}
Err(syn::Error::new_spanned(
&attr.meta,
"expected default value in format `#[default(CONSTANT_VALUE)]`",
))
}
use std::collections::HashSet;
use std::sync::Mutex;
// Same struct can be annotated with `#[spacetimedb::table]` multiple times.
// This mutex keeps track of which structs we've already generated code for.
// This avoids duplicate definitions when the same struct is annotated multiple times.
static GENERATED_STRUCTS: std::sync::LazyLock<Mutex<HashSet<String>>> =
std::sync::LazyLock::new(|| Mutex::new(HashSet::new()));
fn is_first_appearance(struct_name: &str) -> bool {
let mut set = GENERATED_STRUCTS.lock().expect("mutex poisoned");
set.insert(struct_name.to_string())
}
pub(crate) fn table_impl(mut args: TableArgs, item: &syn::DeriveInput) -> syn::Result<TokenStream> {
let vis = &item.vis;
let sats_ty = sats::sats_type_from_derive(item, quote!(spacetimedb::spacetimedb_lib))?;
let original_struct_ident = sats_ty.ident;
let table_ident = &args.accessor;
let explicit_table_name = args.name.as_ref().map(|s| s.value());
let view_trait_ident = format_ident!("{}__view", table_ident);
let query_trait_ident = format_ident!("{}__query", table_ident);
let query_cols_struct = format_ident!("{}Cols", original_struct_ident);
let query_ix_cols_struct = format_ident!("{}IxCols", original_struct_ident);
let table_name = table_ident.unraw().to_string();
let sats::SatsTypeData::Product(fields) = &sats_ty.data else {
return Err(syn::Error::new(Span::call_site(), "spacetimedb table must be a struct"));
};
for param in &item.generics.params {
let err = |msg| syn::Error::new_spanned(param, msg);
match param {
syn::GenericParam::Lifetime(_) => {}
syn::GenericParam::Type(_) => return Err(err("type parameters are not allowed on tables")),
syn::GenericParam::Const(_) => return Err(err("const parameters are not allowed on tables")),
}
}
let table_id_from_name_func = quote! {
fn table_id() -> spacetimedb::TableId {
static TABLE_ID: std::sync::OnceLock<spacetimedb::TableId> = std::sync::OnceLock::new();
*TABLE_ID.get_or_init(|| {
spacetimedb::table_id_from_name(<Self as spacetimedb::table::TableInternal>::TABLE_NAME)
})
}
};
if fields.len() > u16::MAX.into() {
return Err(syn::Error::new_spanned(
item,
"too many columns; the most a table can have is 2^16",
));
}
let mut columns = vec![];
let mut unique_columns = vec![];
let mut sequenced_columns = vec![];
let mut primary_key_column = None;
for (i, field) in fields.iter().enumerate() {
let col_num = i as u16;
let field_ident = field.ident.unwrap();
let mut unique = None;
let mut auto_inc = None;
let mut primary_key = None;
let mut default_value = None;
for attr in field.original_attrs {
let Some(attr) = ColumnAttr::parse(attr, field_ident)? else {
continue;
};
match attr {
ColumnAttr::Unique(span) => {
check_duplicate(&unique, span)?;
unique = Some(span);