-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathtable.rs
More file actions
1458 lines (1323 loc) · 55.4 KB
/
table.rs
File metadata and controls
1458 lines (1323 loc) · 55.4 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::{bsatn, rt::ExplicitNames, sys, DeserializeOwned, IterBuf, Serialize, SpacetimeType, TableId};
use core::borrow::Borrow;
use core::convert::Infallible;
use core::fmt;
use core::marker::PhantomData;
pub use spacetimedb_lib::db::raw_def::v9::TableAccess;
use spacetimedb_lib::{
buffer::{BufReader, Cursor, DecodeError},
AlgebraicValue,
};
use spacetimedb_lib::{FilterableValue, IndexScanRangeBoundsTerminator};
pub use spacetimedb_primitives::{ColId, IndexId};
/// Implemented for every `TableHandle` struct generated by the [`table`](macro@crate::table) macro.
/// Contains methods that are present for every table, regardless of what unique constraints
/// and indexes are present.
///
/// To get a `TableHandle`
// TODO: should we rename this `TableHandle`? Documenting this, I think that's much clearer.
pub trait Table: TableInternal + ExplicitNames {
/// The type of rows stored in this table.
type Row: SpacetimeType + Serialize + DeserializeOwned + Sized + 'static;
/// Returns the number of rows in this table.
///
/// This reads datastore metadata, so it runs in constant time.
/// It also takes into account modifications by the current transaction.
fn count(&self) -> u64 {
count::<Self>()
}
/// Iterate over all rows of the table.
///
/// For large tables, this can be a slow operation!
/// Prefer [filtering](RangedIndex::filter) a [`RangedIndex`] or [finding](UniqueColumn::find) a [`UniqueColumn`] if
/// possible.
///
/// (This keeps track of changes made to the table since the start of this reducer invocation. For example, if rows have been deleted since the start of this reducer invocation, those rows will not be returned by `iter`. Similarly, inserted rows WILL be returned.)
#[inline]
fn iter(&self) -> impl Iterator<Item = Self::Row> {
let table_id = Self::table_id();
let iter = sys::datastore_table_scan_bsatn(table_id).expect("datastore_table_scan_bsatn() call failed");
TableIter::new(iter)
}
/// Inserts `row` into the table.
///
/// The return value is the inserted row, with any auto-incrementing columns replaced with computed values.
/// The `insert` method always returns the inserted row,
/// even when the table contains no auto-incrementing columns.
///
/// (The returned row is a copy of the row in the database.
/// Modifying this copy does not directly modify the database.
/// See [`UniqueColumn::update`] if you want to update the row.)
///
/// May panic if inserting the row violates any constraints.
/// Callers which intend to handle constraint violation errors should instead use [`Self::try_insert`].
///
/// Inserting an exact duplicate of a row already present in the table is a no-op,
/// as SpacetimeDB is a set-semantic database.
/// This is true even for tables with unique constraints;
/// inserting an exact duplicate of an already-present row will not panic.
#[track_caller]
fn insert(&self, row: Self::Row) -> Self::Row {
self.try_insert(row).unwrap_or_else(|e| panic!("{e}"))
}
/// The error type for this table for unique constraint violations. Will either be
/// [`UniqueConstraintViolation`] if the table has any unique constraints, or [`Infallible`]
/// otherwise.
type UniqueConstraintViolation: MaybeError<UniqueConstraintViolation>;
/// The error type for this table for auto-increment overflows. Will either be
/// [`AutoIncOverflow`] if the table has any auto-incrementing columns, or [`Infallible`]
/// otherwise.
type AutoIncOverflow: MaybeError<AutoIncOverflow>;
/// Counterpart to [`Self::insert`] which allows handling failed insertions.
///
/// For tables with constraints, this method returns an `Err` when the insertion fails rather than panicking.
/// For tables without any constraints, [`Self::UniqueConstraintViolation`] and [`Self::AutoIncOverflow`]
/// will be [`std::convert::Infallible`], and this will be a more-verbose [`Self::insert`].
///
/// Inserting an exact duplicate of a row already present in the table is a no-op and returns `Ok`,
/// as SpacetimeDB is a set-semantic database.
/// This is true even for tables with unique constraints;
/// inserting an exact duplicate of an already-present row will return `Ok`.
#[track_caller]
fn try_insert(&self, row: Self::Row) -> Result<Self::Row, TryInsertError<Self>> {
insert::<Self>(row, IterBuf::take())
}
/// Deletes a row equal to `row` from the table.
///
/// Returns `true` if the row was present and has been deleted,
/// or `false` if the row was not present and therefore the tables have not changed.
///
/// Unlike [`Self::insert`], there is no need to return the deleted row,
/// as it must necessarily have been exactly equal to the `row` argument.
/// No analogue to auto-increment placeholders exists for deletions.
///
/// May panic if deleting the row violates any constraints.
fn delete(&self, row: Self::Row) -> bool {
// Note that as of writing deletion is infallible, but future work may define new constraints,
// e.g. foreign keys, which cause deletion to fail in some cases.
// If and when these new constraints are added,
// we should define `Self::ForeignKeyViolation`,
// analogous to [`Self::UniqueConstraintViolation`].
let relation = std::slice::from_ref(&row);
let buf = IterBuf::serialize(relation).unwrap();
let count = sys::datastore_delete_all_by_eq_bsatn(Self::table_id(), &buf).unwrap();
count > 0
}
/// Clears the table of all rows.
///
/// Returns the number of rows that were deleted,
/// i.e., the value of [`self.count()`](Table::count) before this call.
fn clear(&self) -> u64 {
sys::datastore_clear(Self::table_id()).expect("datastore_clear() call failed")
}
// Re-integrates the BSATN of the `generated_cols` into `row`.
#[doc(hidden)]
fn integrate_generated_columns(row: &mut Self::Row, generated_cols: &[u8]);
}
#[doc(hidden)]
#[inline]
pub fn count<Tbl: Table>() -> u64 {
sys::datastore_table_row_count(Tbl::table_id()).expect("datastore_table_row_count() call failed")
}
#[doc(hidden)]
pub trait TableInternal: Sized {
const TABLE_NAME: &'static str;
const TABLE_ACCESS: TableAccess = TableAccess::Private;
const UNIQUE_COLUMNS: &'static [u16];
const INDEXES: &'static [IndexDesc<'static>];
const PRIMARY_KEY: Option<u16> = None;
const SEQUENCES: &'static [u16];
const SCHEDULE: Option<ScheduleDesc<'static>> = None;
const IS_EVENT: bool = false;
const OUTBOX: Option<OutboxDesc<'static>> = None;
/// Returns the ID of this table.
fn table_id() -> TableId;
fn get_default_col_values() -> Vec<ColumnDefault>;
}
/// Describe a named index with an index type over a set of columns identified by their IDs.
#[derive(Clone, Copy)]
pub struct IndexDesc<'a> {
pub source_name: &'a str,
pub accessor_name: &'a str,
pub algo: IndexAlgo<'a>,
}
#[derive(Clone, Copy)]
pub enum IndexAlgo<'a> {
BTree { columns: &'a [u16] },
Hash { columns: &'a [u16] },
Direct { column: u16 },
}
pub struct ScheduleDesc<'a> {
pub reducer_or_procedure_name: &'a str,
pub scheduled_at_column: u16,
}
/// Describes the outbox configuration of a table, for inter-database communication.
pub struct OutboxDesc<'a> {
/// The name of the remote reducer to invoke on the target database.
pub remote_reducer_name: &'a str,
/// The local reducer to call with the delivery result, if any.
pub on_result_reducer_name: Option<&'a str>,
}
#[derive(Debug, Clone)]
pub struct ColumnDefault {
pub col_id: u16,
pub value: AlgebraicValue,
}
/// A row operation was attempted that would violate a unique constraint.
// TODO: add column name for better error message
#[derive(Debug)]
#[non_exhaustive]
pub struct UniqueConstraintViolation;
impl fmt::Display for UniqueConstraintViolation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "duplicate unique column")
}
}
impl std::error::Error for UniqueConstraintViolation {}
/// An auto-inc column overflowed its data type.
#[derive(Debug)]
#[non_exhaustive]
// TODO: add column name for better error message
pub struct AutoIncOverflow;
impl fmt::Display for AutoIncOverflow {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "auto-inc sequence overflowed its column type")
}
}
impl std::error::Error for AutoIncOverflow {}
/// The error type returned from [`Table::try_insert()`], signalling a constraint violation.
pub enum TryInsertError<Tbl: Table> {
/// A [`UniqueConstraintViolation`].
///
/// Returned from [`Table::try_insert`] if an attempted insertion
/// has the same value in a unique column as an already-present row.
///
/// This variant is only possible if the table has at least one unique column,
/// and is otherwise [`std::convert::Infallible`].
UniqueConstraintViolation(Tbl::UniqueConstraintViolation),
/// An [`AutoIncOverflow`].
///
/// Returned from [`Table::try_insert`] if an attempted insertion
/// advances an auto-inc sequence past the bounds of the column type.
///
/// This variant is only possible if the table has at least one auto-inc column,
/// and is otherwise [`std::convert::Infallible`].
AutoIncOverflow(Tbl::AutoIncOverflow),
}
impl<Tbl: Table> fmt::Debug for TryInsertError<Tbl> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "TryInsertError::<{}>::", Tbl::TABLE_NAME)?;
match self {
Self::UniqueConstraintViolation(e) => fmt::Debug::fmt(e, f),
Self::AutoIncOverflow(e) => fmt::Debug::fmt(e, f),
}
}
}
impl<Tbl: Table> fmt::Display for TryInsertError<Tbl> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "insertion error on table `{}`:", Tbl::TABLE_NAME)?;
match self {
Self::UniqueConstraintViolation(e) => fmt::Display::fmt(e, f),
Self::AutoIncOverflow(e) => fmt::Display::fmt(e, f),
}
}
}
impl<Tbl: Table> std::error::Error for TryInsertError<Tbl> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(match self {
Self::UniqueConstraintViolation(e) => e,
Self::AutoIncOverflow(e) => e,
})
}
}
impl<Tbl: Table> From<TryInsertError<Tbl>> for String {
fn from(err: TryInsertError<Tbl>) -> Self {
err.to_string()
}
}
#[doc(hidden)]
pub trait MaybeError<E = Self>: std::error::Error + Send + Sync + Sized + 'static {
fn get() -> Option<Self>;
}
impl<E> MaybeError<E> for Infallible {
fn get() -> Option<Self> {
None
}
}
impl MaybeError for UniqueConstraintViolation {
fn get() -> Option<Self> {
Some(UniqueConstraintViolation)
}
}
impl MaybeError for AutoIncOverflow {
fn get() -> Option<AutoIncOverflow> {
Some(AutoIncOverflow)
}
}
pub trait Column {
type Table: Table;
type ColType: SpacetimeType + Serialize + DeserializeOwned;
const COLUMN_NAME: &'static str;
fn get_field(row: &<Self::Table as Table>::Row) -> &Self::ColType;
}
/// A marker trait for columns that are the primary key of their table.
///
/// This is used to restrict [`UniqueColumn::update`] to only work on primary key columns.
pub trait PrimaryKey {}
/// A handle to a unique index on a column.
/// Available for `#[unique]` and `#[primary_key]` columns.
///
/// For a table *table* with a column *column*, use `ctx.db.{table}().{column}()`
/// to get a `UniqueColumn` from a [`ReducerContext`](crate::ReducerContext).
///
/// Example:
///
/// ```no_run
/// # #[cfg(target_arch = "wasm32")] mod demo {
/// use spacetimedb::{table, UniqueColumn, ReducerContext, DbContext};
///
/// #[table(accessor = user)]
/// struct User {
/// #[primary_key]
/// id: u32,
/// #[unique]
/// username: String,
/// dog_count: u64
/// }
///
/// fn demo(ctx: &ReducerContext) {
/// let user = ctx.db().user();
///
/// let by_id: UniqueColumn<_, u32, _> = user.id();
///
/// let mut example_user: User = by_id.find(357).unwrap();
/// example_user.dog_count += 5;
/// by_id.update(example_user);
///
/// let by_username: UniqueColumn<_, String, _> = user.username();
/// by_username.delete(&"Evil Bob".to_string());
/// }
/// # }
/// ```
///
/// <!-- TODO: do we need integer type suffixes on literal arguments, like for RangedIndex? -->
pub struct UniqueColumn<Tbl, ColType, Col> {
_marker: PhantomData<(Tbl, ColType, Col)>,
}
impl<Tbl: Table, Col: Index + Column<Table = Tbl>> UniqueColumn<Tbl, Col::ColType, Col> {
#[doc(hidden)]
pub const __NEW: Self = Self { _marker: PhantomData };
/// Finds and returns the row where the value in the unique column matches the supplied `col_val`,
/// or `None` if no such row is present in the database state.
//
// TODO: consider whether we should accept the sought value by ref or by value.
// Should be consistent with the implementors of `IndexScanRangeBounds` (see below).
// By-value makes passing `Copy` fields more convenient,
// whereas by-ref makes passing `!Copy` fields more performant.
// Can we do something smart with `std::borrow::Borrow`?
#[inline]
pub fn find(&self, col_val: impl Borrow<Col::ColType>) -> Option<Tbl::Row>
where
for<'a> &'a Col::ColType: FilterableValue,
{
find::<Tbl, Col>(col_val.borrow())
}
/// Deletes the row where the value in the unique column matches the supplied `col_val`,
/// if any such row is present in the database state.
///
/// Returns `true` if a row with the specified `col_val` was previously present and has been deleted,
/// or `false` if no such row was present.
#[inline]
pub fn delete(&self, col_val: impl Borrow<Col::ColType>) -> bool {
self._delete(col_val.borrow()).0
}
fn _delete(&self, col_val: &Col::ColType) -> (bool, IterBuf) {
let index_id = Col::index_id();
let point = IterBuf::serialize(col_val).unwrap();
let n_del = sys::datastore_delete_by_index_scan_point_bsatn(index_id, &point).unwrap_or_else(|e| {
panic!("unique: unexpected error from datastore_delete_by_index_scan_point_bsatn: {e}")
});
(n_del > 0, point)
}
/// Deletes the row where the value in the unique column matches that in the corresponding field of `new_row`, and
/// then inserts the `new_row`.
///
/// Returns the new row as actually inserted, with computed values substituted for any auto-inc placeholders.
///
/// This method can only be called on primary key columns, not any unique column.
/// This prevents confusion regarding what constitutes a row update vs. a delete+insert.
/// To perform this operation for a non-primary unique column, call
/// `.delete(key)` followed by `.insert(row)`.
///
/// # Panics
/// Panics if no row was previously present with the matching value in the unique column,
/// or if either the delete or the insertion would violate a constraint.
#[track_caller]
pub fn update(&self, new_row: Tbl::Row) -> Tbl::Row
where
Col: PrimaryKey,
{
let buf = IterBuf::take();
update::<Tbl>(Col::index_id(), new_row, buf)
}
/// Inserts `new_row` into the table, first checking for an existing
/// row with a matching value in the unique column and deleting it if present.
///
/// Be careful: in case of a constraint violation, this method will return Err,
/// but the previous row will be deleted. If you propagate the error, SpacetimeDB will
/// rollback the transaction and the old row will be restored. If you ignore the error,
/// the old row will be lost.
#[track_caller]
#[doc(alias = "try_upsert")]
#[cfg(feature = "unstable")]
pub fn try_insert_or_update(&self, new_row: Tbl::Row) -> Result<Tbl::Row, TryInsertError<Tbl>> {
let col_val = Col::get_field(&new_row);
// If the row doesn't exist, delete will return false, which we ignore.
let _ = self.delete(col_val);
// Then, insert the new row.
let buf = IterBuf::take();
insert::<Tbl>(new_row, buf)
}
/// Inserts `new_row` into the table, first checking for an existing
/// row with a matching value in the unique column and deleting it if present.
///
/// # Panics
/// Panics if either the delete or the insertion would violate a constraint.
#[track_caller]
#[doc(alias = "upsert")]
#[cfg(feature = "unstable")]
pub fn insert_or_update(&self, new_row: Tbl::Row) -> Tbl::Row {
self.try_insert_or_update(new_row).unwrap_or_else(|e| panic!("{e}"))
}
}
#[inline]
fn find<Tbl: Table, Col: Index + Column<Table = Tbl>>(col_val: &Col::ColType) -> Option<Tbl::Row> {
// Find the row with a match.
let index_id = Col::index_id();
let point = IterBuf::serialize(col_val).unwrap();
let iter = sys::datastore_index_scan_point_bsatn(index_id, &point)
.unwrap_or_else(|e| panic!("unique: unexpected error from `datastore_index_scan_point_bsatn`: {e}"));
let mut iter = TableIter::new_with_buf(iter, point);
// We will always find either 0 or 1 rows here due to the unique constraint.
let row = iter.next();
assert!(
iter.is_exhausted(),
"`datastore_index_scan_point_bsatn` on unique field cannot return >1 rows"
);
row
}
/// A read-only handle to a unique (single-column) index.
///
/// This is the read-only version of [`UniqueColumn`].
/// It mirrors [`UniqueColumn`] but only exposes read APIs.
/// It cannot insert or delete rows.
/// It is used by `{table}__ViewHandle` to keep view code read-only at compile time.
///
/// Note, the `Tbl` generic is the read-write table handle `{table}__TableHandle`.
/// This is because read-only indexes still need [`Table`] metadata.
/// The view handle itself deliberately does not implement `Table`.
pub struct UniqueColumnReadOnly<Tbl, ColType, Col> {
_marker: PhantomData<(Tbl, ColType, Col)>,
}
impl<Tbl: Table, Col: Index + Column<Table = Tbl>> UniqueColumnReadOnly<Tbl, Col::ColType, Col> {
#[doc(hidden)]
pub const __NEW: Self = Self { _marker: PhantomData };
#[inline]
pub fn find(&self, col_val: impl Borrow<Col::ColType>) -> Option<Tbl::Row>
where
for<'a> &'a Col::ColType: FilterableValue,
{
find::<Tbl, Col>(col_val.borrow())
}
}
/// Information about the `index_id` of an index
/// and the number of columns the index indexes.
pub trait Index {
/// The number of columns the index indexes.
///
/// Used to determine whether a scan for e.g., `(a, b)`,
/// is actually a point scan or whether there's a suffix, e.g., `(c, d)`.
const NUM_COLS_INDEXED: usize;
/// Determine the `IndexId` of this index.
///
/// For generated implementations,
/// this results in a *memoized* syscall to determine the index,
/// based on the hard coded name of the index.
fn index_id() -> IndexId;
}
/// Marks an index as only having point query capabilities.
///
/// This applies to Hash indices but not BTree and Direct indices.
pub trait IndexIsPointed: Index {}
/// A handle to a Hash index on a table.
///
/// To get one of these from a `ReducerContext`, use:
/// ```text
/// ctx.db.{table}().{index}()
/// ```
/// for a table *table* and an index *index*.
///
/// Example:
///
/// ```no_run
/// # #[cfg(target_arch = "wasm32")] mod demo {
/// use spacetimedb::{table, PointIndex, ReducerContext, DbContext};
///
/// #[table(accessor = user,
/// index(accessor = dogs_and_name, hash(columns = [dogs, name])))]
/// struct User {
/// id: u32,
/// name: String,
/// /// Number of dogs owned by the user.
/// dogs: u64
/// }
///
/// fn demo(ctx: &ReducerContext) {
/// let by_dogs_and_name: PointIndex<_, (u64, String), _> = ctx.db.user().dogs_and_name();
/// }
/// # }
/// ```
///
/// For single-column indexes, use the name of the column:
///
/// ```no_run
/// # #[cfg(target_arch = "wasm32")] mod demo {
/// use spacetimedb::{table, PointIndex, ReducerContext, DbContext};
///
/// #[table(accessor = user)]
/// struct User {
/// id: u32,
/// username: String,
/// #[index(btree)]
/// dogs: u64
/// }
///
/// fn demo(ctx: &ReducerContext) {
/// let by_dogs: PointIndex<_, (u64,), _> = ctx.db().user().dogs();
/// }
/// # }
/// ```
///
pub struct PointIndex<Tbl: Table, IndexType, Idx: Index> {
_marker: PhantomData<(Tbl, IndexType, Idx)>,
}
impl<Tbl: Table, IndexType, Idx: IndexIsPointed> PointIndex<Tbl, IndexType, Idx> {
#[doc(hidden)]
pub const __NEW: Self = Self { _marker: PhantomData };
/// Returns an iterator over all rows in the database state
/// where the indexed column(s) equal `point`.
///
/// Unlike for ranged indices,
/// this method only accepts a `point` and not any prefix or range.
///
/// For example:
///
/// ```no_run
/// # #[cfg(target_arch = "wasm32")] mod demo {
/// use spacetimedb::{table, ReducerContext, PointIndex};
///
/// #[table(accessor = user,
/// index(accessor = dogs_and_name, hash(columns = [dogs, name])))]
/// struct User {
/// id: u32,
/// name: String,
/// dogs: u64
/// }
///
/// fn demo(ctx: &ReducerContext) {
/// let by_dogs_and_name: PointIndex<_, (u64, String), _> = ctx.db.user().dogs_and_name();
///
/// // Find user with exactly 25 dogs and exactly the name "Joseph".
/// for user in by_dogs_and_name.filter((25u64, "Joseph")) {
/// /* ... */
/// }
///
/// // You can also pass arguments by reference if desired.
/// for user in by_dogs_and_name.filter((&25u64, &"Joseph".to_string())) {
/// /* ... */
/// }
/// }
/// # }
/// ```
pub fn filter<P, K>(&self, point: P) -> impl Iterator<Item = Tbl::Row> + use<P, K, Tbl, IndexType, Idx>
where
P: WithPointArg<K>,
{
filter_point::<Tbl, Idx, K>(point)
}
/// Deletes all rows in the database state
/// where the indexed column(s) equal `point`.
///
/// Unlike for ranged indices,
/// this method only accepts a `point` and not any prefix or range.
///
/// For example:
///
/// ```no_run
/// # #[cfg(target_arch = "wasm32")] mod demo {
/// use spacetimedb::{table, ReducerContext, PointIndex};
///
/// #[table(accessor = user,
/// index(accessor = dogs_and_name, hash(columns = [dogs, name])))]
/// struct User {
/// id: u32,
/// name: String,
/// dogs: u64
/// }
///
/// fn demo(ctx: &ReducerContext) {
/// let by_dogs_and_name: PointIndex<_, (u64, String), _> = ctx.db.user().dogs_and_name();
///
/// // Delete users with exactly 25 dogs, and exactly the name "Joseph".
/// by_dogs_and_name.delete((25u64, "Joseph"));
///
/// // You can also pass arguments by reference if desired.
/// by_dogs_and_name.delete((&25u64, &"Joseph".to_string()));
/// }
/// # }
/// ```
///
/// May panic if deleting any one of the rows would violate a constraint,
/// though at present no such constraints exist.
pub fn delete<P, K>(&self, point: P) -> u64
where
P: WithPointArg<K>,
{
let index_id = Idx::index_id();
point.with_point_arg(|point| {
sys::datastore_delete_by_index_scan_point_bsatn(index_id, point)
.unwrap_or_else(|e| panic!("unexpected error from `datastore_delete_by_index_scan_point_bsatn`: {e}"))
.into()
})
}
}
/// Scans `Tbl` for `point` using the index `Idx`.
///
/// The type parameter `K` is either `()` or [`SingleBound`]
/// and is used to workaround the orphan rule.
fn filter_point<Tbl, Idx, K>(point: impl WithPointArg<K>) -> impl Iterator<Item = Tbl::Row>
where
Tbl: Table,
Idx: IndexIsPointed,
{
let index_id = Idx::index_id();
let iter = point.with_point_arg(|point| {
sys::datastore_index_scan_point_bsatn(index_id, point)
.unwrap_or_else(|e| panic!("unexpected error from `datastore_index_scan_point_bsatn`: {e}"))
});
TableIter::new(iter)
}
/// A read-only handle to a Hash index.
///
/// This is the read-only version of [`PointIndex`].
/// It mirrors [`PointIndex`] but exposes only `.filter(..)`, not `.delete(..)`.
/// It is used by `{table}__ViewHandle` to keep view code read-only at compile time.
///
/// Note, the `Tbl` generic is the read-write table handle `{table}__TableHandle`.
/// This is because read-only indexes still need [`Table`] metadata.
/// The view handle itself deliberately does not implement `Table`.
pub struct PointIndexReadOnly<Tbl: Table, IndexType, Idx: Index> {
_marker: PhantomData<(Tbl, IndexType, Idx)>,
}
impl<Tbl: Table, IndexType, Idx: IndexIsPointed> PointIndexReadOnly<Tbl, IndexType, Idx> {
#[doc(hidden)]
pub const __NEW: Self = Self { _marker: PhantomData };
pub fn filter<P, K>(&self, point: P) -> impl Iterator<Item = Tbl::Row> + use<P, K, Tbl, IndexType, Idx>
where
P: WithPointArg<K>,
{
filter_point::<Tbl, Idx, K>(point)
}
}
/// Trait used for running point index scans.
///
/// The type parameter `K` is either `()` or [`SingleBound`]
/// and is used to workaround the orphan rule.
pub trait WithPointArg<K = ()> {
/// Runs `run` with the BSATN-serialized point to pass to the index scan.
// TODO(perf, centril): once we have stable specialization,
// just use `to_le_bytes` internally instead.
#[doc(hidden)]
fn with_point_arg<R>(&self, run: impl FnOnce(&[u8]) -> R) -> R;
}
impl<Arg: FilterableValue> WithPointArg<SingleBound> for Arg {
fn with_point_arg<R>(&self, run: impl FnOnce(&[u8]) -> R) -> R {
run(&IterBuf::serialize(self).unwrap())
}
}
macro_rules! impl_with_point_arg {
($($arg:ident),+) => {
impl<$($arg: FilterableValue),+> WithPointArg for ($($arg,)+) {
fn with_point_arg<R>(&self, run: impl FnOnce(&[u8]) -> R) -> R {
// We can assume here that we have a point bound.
let mut data = IterBuf::take();
// Destructure the argument tuple into variables with the same names as their types.
#[allow(non_snake_case)]
let ($($arg,)+) = self;
// For each part in the tuple queried, serialize it into the `data` buffer.
Ok(())
$(.and_then(|()| data.serialize_into($arg)))+
.unwrap();
run(&*data)
}
}
};
}
impl_with_point_arg!(A);
impl_with_point_arg!(A, B);
impl_with_point_arg!(A, B, C);
impl_with_point_arg!(A, B, C, D);
impl_with_point_arg!(A, B, C, D, E);
impl_with_point_arg!(A, B, C, D, E, F);
/// Marks an index as having range query capabilities.
///
/// This applies to BTree and Direct indices but not Hash indices.
pub trait IndexIsRanged: Index {}
/// A handle to a B-Tree or Direct index on a table.
///
/// To get one of these from a `ReducerContext`, use:
/// ```text
/// ctx.db.{table}().{index}()
/// ```
/// for a table *table* and an index *index*.
///
/// Example:
///
/// ```no_run
/// # #[cfg(target_arch = "wasm32")] mod demo {
/// use spacetimedb::{table, RangedIndex, ReducerContext, DbContext};
///
/// #[table(accessor = user,
/// index(accessor = dogs_and_name, btree(columns = [dogs, name])))]
/// struct User {
/// id: u32,
/// name: String,
/// /// Number of dogs owned by the user.
/// dogs: u64
/// }
///
/// fn demo(ctx: &ReducerContext) {
/// let by_dogs_and_name: RangedIndex<_, (u64, String), _> = ctx.db.user().dogs_and_name();
/// }
/// # }
/// ```
///
/// For single-column indexes, use the name of the column:
///
/// ```no_run
/// # #[cfg(target_arch = "wasm32")] mod demo {
/// use spacetimedb::{table, RangedIndex, ReducerContext, DbContext};
///
/// #[table(accessor = user)]
/// struct User {
/// id: u32,
/// username: String,
/// #[index(btree)]
/// dogs: u64
/// }
///
/// fn demo(ctx: &ReducerContext) {
/// let by_dogs: RangedIndex<_, (u64,), _> = ctx.db().user().dogs();
/// }
/// # }
/// ```
///
pub struct RangedIndex<Tbl: Table, IndexType, Idx: IndexIsRanged> {
_marker: PhantomData<(Tbl, IndexType, Idx)>,
}
impl<Tbl: Table, IndexType, Idx: IndexIsRanged> RangedIndex<Tbl, IndexType, Idx> {
#[doc(hidden)]
pub const __NEW: Self = Self { _marker: PhantomData };
/// Returns an iterator over all rows in the database state where the indexed column(s) match the bounds `b`.
///
/// This method accepts a variable numbers of arguments using the [`IndexScanRangeBounds`] trait.
/// This depends on the type of the B-Tree index. `b` may be:
/// - A value for the first indexed column.
/// - A range of values for the first indexed column.
/// - A tuple of values for any prefix of the indexed columns, optionally terminated by a range for the next.
///
/// For example:
///
/// ```no_run
/// # #[cfg(target_arch = "wasm32")] mod demo {
/// use spacetimedb::{table, ReducerContext, RangedIndex};
///
/// #[table(accessor = user,
/// index(accessor = dogs_and_name, btree(columns = [dogs, name])))]
/// struct User {
/// id: u32,
/// name: String,
/// dogs: u64
/// }
///
/// fn demo(ctx: &ReducerContext) {
/// let by_dogs_and_name: RangedIndex<_, (u64, String), _> = ctx.db.user().dogs_and_name();
///
/// // Find user with exactly 25 dogs.
/// for user in by_dogs_and_name.filter(25u64) { // The `u64` is required, see below.
/// /* ... */
/// }
///
/// // Find user with at least 25 dogs.
/// for user in by_dogs_and_name.filter(25u64..) {
/// /* ... */
/// }
///
/// // Find user with exactly 25 dogs, and a name beginning with "J".
/// for user in by_dogs_and_name.filter((25u64, "J".."K")) {
/// /* ... */
/// }
///
/// // Find user with exactly 25 dogs, and exactly the name "Joseph".
/// for user in by_dogs_and_name.filter((25u64, "Joseph")) {
/// /* ... */
/// }
///
/// // You can also pass arguments by reference if desired.
/// for user in by_dogs_and_name.filter((&25u64, &"Joseph".to_string())) {
/// /* ... */
/// }
/// }
/// # }
/// ```
///
/// **NOTE:** An unfortunate interaction between Rust's trait solver and integer literal defaulting rules means that you must specify the types of integer literals passed to `filter` and `find` methods via the suffix syntax, like `21u32`.
///
/// If you don't, you'll see a compiler error like:
/// > ```text
/// > error[E0271]: type mismatch resolving `<i32 as FilterableValue>::Column == u32`
/// > --> modules/rust-wasm-test/src/lib.rs:356:48
/// > |
/// > 356 | for person in ctx.db.person().age().filter(21) {
/// > | ------ ^^ expected `u32`, found `i32`
/// > | |
/// > | required by a bound introduced by this call
/// > |
/// > = note: required for `i32` to implement `IndexScanRangeBounds<(u32,), SingleBound>`
/// > note: required by a bound in `RangedIndex::<Tbl, IndexType, Idx>::filter`
/// > |
/// > 410 | pub fn filter<B, K>(&self, b: B) -> impl Iterator<Item = Tbl::Row>
/// > | ------ required by a bound in this associated function
/// > 411 | where
/// > 412 | B: IndexScanRangeBounds<IndexType, K>,
/// > | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `RangedIndex::<Tbl, IndexType, Idx>::filter`
/// > ```
/// <!-- TODO: check if that error is up to date! -->
pub fn filter<B, K>(&self, b: B) -> impl Iterator<Item = Tbl::Row> + use<B, K, Tbl, IndexType, Idx>
where
B: IndexScanRangeBounds<IndexType, K>,
{
filter::<Tbl, Idx, IndexType, B, K>(b)
}
/// Deletes all rows in the database state where the indexed column(s) match the bounds `b`.
///
/// This method accepts a variable numbers of arguments using the [`IndexScanRangeBounds`] trait.
/// This depends on the type of the B-Tree index. `b` may be:
/// - A value for the first indexed column.
/// - A range of values for the first indexed column.
/// - A tuple of values for any prefix of the indexed columns, optionally terminated by a range for the next.
///
/// For example:
///
/// ```no_run
/// # #[cfg(target_arch = "wasm32")] mod demo {
/// use spacetimedb::{table, ReducerContext, RangedIndex};
///
/// #[table(accessor = user,
/// index(accessor = dogs_and_name, btree(columns = [dogs, name])))]
/// struct User {
/// id: u32,
/// name: String,
/// dogs: u64
/// }
///
/// fn demo(ctx: &ReducerContext) {
/// let by_dogs_and_name: RangedIndex<_, (u64, String), _> = ctx.db.user().dogs_and_name();
///
/// // Delete users with exactly 25 dogs.
/// by_dogs_and_name.delete(25u64); // The `u64` is required, see below.
///
/// // Delete users with at least 25 dogs.
/// by_dogs_and_name.delete(25u64..);
///
/// // Delete users with exactly 25 dogs, and a name beginning with "J".
/// by_dogs_and_name.delete((25u64, "J".."K"));
///
/// // Delete users with exactly 25 dogs, and exactly the name "Joseph".
/// by_dogs_and_name.delete((25u64, "Joseph"));
///
/// // You can also pass arguments by reference if desired.
/// by_dogs_and_name.delete((&25u64, &"Joseph".to_string()));
/// }
/// # }
/// ```
///
/// **NOTE:** An unfortunate interaction between Rust's trait solver and integer literal defaulting rules means that you must specify the types of integer literals passed to `filter` and `find` methods via the suffix syntax, like `21u32`.
///
/// If you don't, you'll see a compiler error like:
/// > ```text
/// > error[E0271]: type mismatch resolving `<i32 as FilterableValue>::Column == u32`
/// > --> modules/rust-wasm-test/src/lib.rs:356:48
/// > |
/// > 356 | for person in ctx.db.person().age().filter(21) {
/// > | ------ ^^ expected `u32`, found `i32`
/// > | |
/// > | required by a bound introduced by this call
/// > |
/// > = note: required for `i32` to implement `IndexScanRangeBounds<(u32,), SingleBound>`
/// > note: required by a bound in `RangedIndex::<Tbl, IndexType, Idx>::filter`
/// > |
/// > 410 | pub fn filter<B, K>(&self, b: B) -> impl Iterator<Item = Tbl::Row>
/// > | ------ required by a bound in this associated function
/// > 411 | where
/// > 412 | B: IndexScanRangeBounds<IndexType, K>,
/// > | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `RangedIndex::<Tbl, IndexType, Idx>::filter`
/// > ```
///
/// May panic if deleting any one of the rows would violate a constraint,
/// though at present no such constraints exist.
pub fn delete<B, K>(&self, b: B) -> u64
where
B: IndexScanRangeBounds<IndexType, K>,
{
let index_id = Idx::index_id();
if const { is_point_scan::<Idx, B, _, _>() } {
b.with_point_arg(|point| {
sys::datastore_delete_by_index_scan_point_bsatn(index_id, point)
.unwrap_or_else(|e| {
panic!("unexpected error from `datastore_delete_by_index_scan_point_bsatn`: {e}")
})
.into()
})
} else {
let args = b.get_range_args();
let (prefix, prefix_elems, rstart, rend) = args.args_for_syscall();
sys::datastore_delete_by_index_scan_range_bsatn(index_id, prefix, prefix_elems, rstart, rend)
.unwrap_or_else(|e| panic!("unexpected error from `datastore_delete_by_index_scan_range_bsatn`: {e}"))
.into()
}
}
}
/// Performs a ranged scan using the range arguments `B` in `Tbl` using `Idx`.
///
/// The type parameter `K` is either `()` or [`SingleBound`]
/// and is used to workaround the orphan rule.
fn filter<Tbl, Idx, IndexType, B, K>(b: B) -> impl Iterator<Item = Tbl::Row>
where
Tbl: Table,
Idx: Index,
B: IndexScanRangeBounds<IndexType, K>,
{
let index_id = Idx::index_id();
let iter = if const { is_point_scan::<Idx, B, _, _>() } {
b.with_point_arg(|point| {
sys::datastore_index_scan_point_bsatn(index_id, point)
.unwrap_or_else(|e| panic!("unexpected error from `datastore_index_scan_point_bsatn`: {e}"))
})
} else {
let args = b.get_range_args();
let (prefix, prefix_elems, rstart, rend) = args.args_for_syscall();
sys::datastore_index_scan_range_bsatn(index_id, prefix, prefix_elems, rstart, rend)
.unwrap_or_else(|e| panic!("unexpected error from `datastore_index_scan_range_bsatn`: {e}"))