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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
// ^ if you are working on docs, go read the top comment of README.md please.
use ;
use Deref;
use bsatn;
use Rc;
pub use spacetimedb_query_builder as query_builder;
pub use Filter;
pub use log;
pub use rand08 as rand;
use RngCore;
pub use StdbRng;
pub use SpacetimeType;
pub use __TableHelper;
pub use spacetimedb_bindings_sys as sys;
pub use spacetimedb_lib;
pub use CaseConversionPolicy;
pub use ;
pub use sats;
pub use Serialize;
pub use AlgebraicValue;
pub use ConnectionId;
// `FilterableValue` re-exported purely for rustdoc.
pub use FilterableValue;
pub use Identity;
pub use ScheduleAt;
pub use TimeDuration;
pub use Timestamp;
pub use Uuid;
pub use TableId;
pub use Errno;
pub use ;
pub type ReducerResult = Result;
pub type ProcedureResult = ;
pub use duration;
/// Generates code for registering a row-level security rule.
///
/// This attribute must be applied to a `const` binding of type [`Filter`].
/// It will be interpreted as a filter on the table to which it applies, for all client queries.
/// If a module contains multiple `client_visibility_filter`s for the same table,
/// they will be unioned together as if by SQL `OR`,
/// so that any row permitted by at least one filter is visible.
///
/// The `const` binding's identifier must be unique within the module.
///
/// The query follows the same syntax as a subscription query.
///
/// ## Example:
///
/// ```no_run
/// # #[cfg(target_arch = "wasm32")] mod demo {
/// use spacetimedb::{client_visibility_filter, Filter};
///
/// /// Players can only see what's in their chunk
/// #[client_visibility_filter]
/// const PLAYERS_SEE_ENTITIES_IN_SAME_CHUNK: Filter = Filter::Sql("
/// SELECT * FROM LocationState WHERE chunk_index IN (
/// SELECT chunk_index FROM LocationState WHERE entity_id IN (
/// SELECT entity_id FROM UserState WHERE identity = :sender
/// )
/// )
/// ");
/// # }
/// ```
///
/// Queries are not checked for syntactic or semantic validity
/// until they are processed by the SpacetimeDB host.
/// This means that errors in queries, such as syntax errors, type errors or unknown tables,
/// will be reported during `spacetime publish`, not at compile time.
// TODO: RLS filters are currently unimplemented, and are not enforced.
pub use client_visibility_filter;
/// Declare a module-level setting.
///
/// Apply this attribute to a `const` item whose name is a known setting:
///
/// ```ignore
/// use spacetimedb::CaseConversionPolicy;
///
/// #[spacetimedb::settings]
/// const CASE_CONVERSION_POLICY: CaseConversionPolicy = CaseConversionPolicy::SnakeCase;
/// ```
///
/// # Known Settings
///
/// | Const Name | Type | Default | Description |
/// |---|---|---|---|
/// | `CASE_CONVERSION_POLICY` | [`CaseConversionPolicy`] | `SnakeCase` | How identifiers are converted to canonical names |
///
/// # Errors
///
/// - Unknown setting name: compile error listing known settings
/// - Duplicate setting: linker error (duplicate symbol)
pub use settings;
/// Declares a table with a particular row type.
///
/// This attribute is applied to a struct type with named fields.
/// This derives [`Serialize`], [`Deserialize`], [`SpacetimeType`], and [`Debug`] for the annotated struct.
///
/// Elements of the struct type are NOT automatically inserted into any global table.
/// They are regular structs, with no special behavior.
/// In particular, modifying them does not automatically modify the database!
///
/// Instead, a type implementing [`Table<Row = Self>`] is generated. This can be looked up in a [`ReducerContext`]
/// using `ctx.db.{table_name}()`. This type represents a handle to a database table, and can be used to
/// iterate and modify the table's elements. It is a view of the entire table -- the entire set of rows at the time of the reducer call.
///
/// # Example
///
/// ```ignore
/// use spacetimedb::{table, ReducerContext};
///
/// #[table(accessor = user, public,
/// index(accessor = popularity_and_username, btree(columns = [popularity, username])),
/// )]
/// pub struct User {
/// #[auto_inc]
/// #[primary_key]
/// pub id: u32,
/// #[unique]
/// pub username: String,
/// #[index(btree)]
/// pub popularity: u32,
/// }
///
/// fn demo(ctx: &ReducerContext) {
/// // Use the name of the table to get a struct
/// // implementing `spacetimedb::Table<Row = User>`.
/// let user: user__TableHandle = ctx.db.user();
///
/// // You can use methods from `spacetimedb::Table`
/// // on the table.
/// log::debug!("User count: {}", user.count());
/// for user in user.iter() {
/// log::debug!("{:?}", user);
/// }
///
/// // For every `#[index(btree)]`, the table has an extra method
/// // for getting a corresponding `spacetimedb::BTreeIndex`.
/// let by_popularity: RangedIndex<_, (u32,), _> =
/// user.popularity();
/// for popular_user in by_popularity.filter(95..) {
/// log::debug!("Popular user: {:?}", popular_user);
/// }
///
/// // There are similar methods for multi-column indexes.
/// let by_popularity_and_username: RangedIndex<_, (u32, String), _> = user.popularity_and_username();
/// for popular_user in by_popularity.filter((100, "a"..)) {
/// log::debug!("Popular user whose name starts with 'a': {:?}", popular_user);
/// }
///
/// // For every `#[unique]` or `#[primary_key]` field,
/// // the table has an extra method that allows getting a
/// // corresponding `spacetimedb::UniqueColumn`.
/// let by_username: spacetimedb::UniqueColumn<_, String, _> = user.id();
/// by_username.delete(&"test_user".to_string());
/// }
/// ```
///
/// See [`Table`], [`RangedIndex`], and [`UniqueColumn`] for more information on the methods available on these types.
///
/// # Browsing generated documentation
///
/// The `#[table]` macro generates different APIs depending on the contents of your table.
///
/// To browse the complete generated API for your tables, run `cargo doc` in your SpacetimeDB module project. Navigate to `[YOUR PROJECT/target/doc/spacetime_module/index.html` in your file explorer, and right click -> open it in a web browser.
///
/// For the example above, we would see three items:
/// - A struct `User`. This is the struct you declared. It stores rows of the table `user`.
/// - A struct `user__TableHandle`. This is an opaque handle that allows you to interact with the table `user`.
/// - A trait `user` containing a single `fn user(&self) -> user__TableHandle`.
/// This trait is implemented for the `db` field of a [`ReducerContext`], allowing you to get a
/// `user__TableHandle` using `ctx.db.user()`.
///
/// # Macro arguments
///
/// The `#[table(...)]` attribute accepts any number of the following arguments, separated by commas.
///
/// Multiple `table` annotations can be present on the same type. This will generate
/// multiple tables of the same row type, but with different names.
///
/// ### `name`
///
/// Specify the name of the table in the database. The name can be any valid Rust identifier.
///
/// The table name is used to get a handle to the table from a [`ReducerContext`].
/// For a table *table*, use `ctx.db.{table}()` to do this.
/// For example:
/// ```ignore
/// #[table(accessor = user)]
/// pub struct User {
/// #[auto_inc]
/// #[primary_key]
/// pub id: u32,
/// #[unique]
/// pub username: String,
/// #[index(btree)]
/// pub popularity: u32,
/// }
/// #[reducer]
/// fn demo(ctx: &ReducerContext) {
/// let user: user__TableHandle = ctx.db.user();
/// }
/// ```
///
/// ### `public` and `private`
///
/// Tables are private by default. This means that clients cannot read their contents
/// or see that they exist.
///
/// If you'd like to make your table publicly accessible by clients,
/// put `public` in the macro arguments (e.g.
/// `#[spacetimedb::table(public)]`). You can also specify `private` if
/// you'd like to be specific.
///
/// This is fully separate from Rust's module visibility
/// system; `pub struct` or `pub(crate) struct` do not affect the table visibility, only
/// the visibility of the items in your own source code.
///
/// ### `index(...)`
///
/// You can specify an index on one or more of the table's columns with the syntax:
/// `index(accessor = my_index, btree(columns = [a, b, c]))`
///
/// You can also just put `#[index(btree)]` on the field itself if you only need
/// a single-column index; see column attributes below.
///
/// A table may declare any number of indexes.
///
/// You can use indexes to efficiently [`filter`](crate::RangedIndex::filter) and
/// [`delete`](crate::RangedIndex::delete) rows. This is encapsulated in the struct [`RangedIndex`].
///
/// For a table *table* and an index *index*, use:
/// ```text
/// ctx.db.{table}().{index}()
/// ```
/// to get a [`RangedIndex`] for a [`ReducerContext`].
///
/// For example:
/// ```ignore
/// let by_id_and_username: spacetimedb::RangedIndex<_, (u32, String), _> =
/// ctx.db.user().by_id_and_username();
/// ```
///
/// ### `scheduled(reducer_name)`
///
/// Used to declare a [scheduled reducer](macro@crate::reducer#scheduled-reducers).
///
/// The annotated struct type must have at least the following fields:
/// - `scheduled_id: u64`
/// - [`scheduled_at: ScheduleAt`](crate::ScheduleAt)
///
/// # Column (field) attributes
///
/// ### `#[auto_inc]`
///
/// Creates an auto-increment constraint.
///
/// When a row is inserted with the annotated field set to `0` (zero),
/// the sequence is incremented, and this value is used instead.
///
/// Can only be used on numeric types.
///
/// May be combined with indexes or unique constraints.
///
/// Note that using `#[auto_inc]` on a field does not also imply `#[primary_key]` or `#[unique]`.
/// If those semantics are desired, those attributes should also be used.
///
/// When `#[auto_inc]` is combined with a unique key,
/// be wary not to manually insert values larger than the allocated sequence value.
/// In this case, the sequence will eventually catch up, allocate a value that's already present,
/// and cause a unique constraint violation.
///
/// ### `#[unique]`
///
/// Creates an unique constraint and index for the annotated field.
///
/// You can [`find`](crate::UniqueColumn::find), [`update`](crate::UniqueColumn::update),
/// and [`delete`](crate::UniqueColumn::delete) rows by their unique columns.
/// This is encapsulated in the struct [`UniqueColumn`].
///
/// For a table *table* and a column *column*, use:
/// ```text
/// ctx.db.{table}().{column}()`
/// ```
/// to get a [`UniqueColumn`] from a [`ReducerContext`].
///
/// For example:
/// ```ignore
/// let by_username: spacetimedb::UniqueColumn<_, String, _> = ctx.db.user().username();
/// ```
///
/// When there is a unique column constraint on the table, insertion can fail if a uniqueness constraint is violated.
/// If we insert two rows which have the same value of a unique column, the second will fail.
/// This will be via a panic with [`Table::insert`] or via a `Result::Err` with [`Table::try_insert`].
///
/// For example:
/// ```no_run
/// # #[cfg(target_arch = "wasm32")] mod demo {
/// use spacetimedb::{
/// table,
/// reducer,
/// ReducerContext,
/// // Make sure to import the `Table` trait to use `insert` or `try_insert`.
/// Table
/// };
///
/// type CountryCode = String;
///
/// #[table(accessor = country)]
/// struct Country {
/// #[unique]
/// code: CountryCode,
/// national_bird: String
/// }
///
/// #[reducer]
/// fn insert_unique_demo(ctx: &ReducerContext) {
/// let result = ctx.db.country().try_insert(Country {
/// code: "AU".into(), national_bird: "Emu".into()
/// });
/// assert!(result.is_ok());
///
/// let result = ctx.db.country().try_insert(Country {
/// code: "AU".into(), national_bird: "Great Egret".into()
/// // Whoops, this was Austria's national bird, not Australia's.
/// // We should have used the country code "AT", not "AU".
/// });
/// // since there's already a country in the database with the code "AU",
/// // SpacetimeDB gives us an error.
/// assert!(result.is_err());
///
/// // The following line would panic, since we use `insert` rather than `try_insert`.
/// // let result = ctx.db.country().insert(Country { code: "CN".into(), national_bird: "Blue Magpie".into() });
///
/// // If we wanted to *update* the row for Australia, we can use the `update` method of `UniqueIndex`.
/// // The following line will succeed:
/// ctx.db.country().code().update(Country {
/// code: "AU".into(), national_bird: "Australian Emu".into()
/// });
/// }
/// # }
/// ```
///
/// ### `#[primary_key]`
///
/// Implies `#[unique]`. Also generates additional methods client-side for handling updates to the table.
/// <!-- TODO: link to client-side documentation. -->
///
/// ### `#[index(btree)]`
///
/// Creates a single-column index with the specified algorithm.
///
/// It is an error to specify this attribute together with `#[unique]`.
/// Unique constraints implicitly create a unique index, which is accessed using the [`UniqueColumn`] struct instead of the
/// [`RangedIndex`] struct.
///
/// The created index has the same name as the column.
///
/// For a table *table* and an indexed *column*, use:
/// ```text
/// ctx.db.{table}().{column}()
/// ```
/// to get a [`RangedIndex`] from a [`ReducerContext`].
///
/// For example:
///
/// ```ignore
/// ctx.db.cities().latitude()
/// ```
///
/// # Generated code
///
/// For each `[table(accessor = {name})]` annotation on a type `{T}`, generates a struct
/// `{name}__TableHandle` implementing [`Table<Row={T}>`](crate::Table), and a trait that allows looking up such a
/// `{name}Handle` in a [`ReducerContext`].
///
/// The struct `{name}__TableHandle` is public and lives next to the row struct.
/// Users are encouraged not to write the name of this table handle struct,
/// or to store table handles in variables; operate through a `ReducerContext` instead.
///
/// For each named index declaration, add a method to `{name}__TableHandle` for getting a corresponding
/// [`RangedIndex`].
///
/// For each field with a `#[unique]` or `#[primary_key]` annotation,
/// add a method to `{name}Handle` for getting a corresponding [`UniqueColumn`].
///
/// The following pseudocode illustrates the general idea. Curly braces are used to indicate templated
/// names.
///
/// ```ignore
/// use spacetimedb::{RangedIndex, UniqueColumn, Table, DbView};
///
/// // This generated struct is hidden and cannot be directly accessed.
/// struct {name}__TableHandle { /* ... */ };
///
/// // It is a table handle.
/// impl Table for {name}__TableHandle {
/// type Row = {T};
/// /* ... */
/// }
///
/// // It can be looked up in a `ReducerContext`,
/// // using `ctx.db().{name}()`.
/// trait {name} {
/// fn {name}(&self) -> Row = {T}>;
/// }
/// impl {name} for <ReducerContext as DbContext>::DbView { /* ... */ }
///
/// // Once looked up, it can be used to look up indexes.
/// impl {name}Handle {
/// // For each `#[unique]` or `#[primary_key]` field `{field}` of type `{F}`:
/// fn {field}(&self) -> UniqueColumn<_, {F}, _> { /* ... */ };
///
/// // For each named index `{index}` on fields of type `{(F1, ..., FN)}`:
/// fn {index}(&self) -> RangedIndex<_, {(F1, ..., FN)}, _>;
/// }
/// ```
///
/// [`Table<Row = Self>`]: `Table`
pub use table;
/// Marks a function as a spacetimedb reducer.
///
/// A reducer is a function with read/write access to the database
/// that can be invoked remotely by [clients].
///
/// Each reducer call runs in its own database transaction,
/// and its updates to the database are only committed if the reducer returns successfully.
///
/// The first argument of a reducer is always a [`&ReducerContext`]. This context object
/// allows accessing the database and viewing information about the caller, among other things.
///
/// After this, a reducer can take any number of arguments.
/// These arguments must implement the [`SpacetimeType`], [`Serialize`], and [`Deserialize`] traits.
/// All of these traits can be derived at once by marking a type with `#[derive(SpacetimeType)]`.
///
/// Reducers may return either `()` or `Result<(), E>` where [`E: std::fmt::Display`](std::fmt::Display).
///
/// ```no_run
/// # #[cfg(target_arch = "wasm32")] mod demo {
/// use spacetimedb::{reducer, SpacetimeType, ReducerContext};
/// use log::info;
/// use std::fmt;
///
/// #[reducer]
/// pub fn hello_world(context: &ReducerContext) {
/// info!("Hello, World!");
/// }
///
/// #[reducer]
/// pub fn add_person(context: &ReducerContext, name: String, age: u16) {
/// // add a "person" to the database.
/// }
///
/// #[derive(SpacetimeType, Debug)]
/// struct Coordinates {
/// x: f32,
/// y: f32,
/// }
///
/// enum AddPlaceError {
/// InvalidCoordinates(Coordinates),
/// InvalidName(String),
/// }
///
/// impl fmt::Display for AddPlaceError {
/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
/// match self {
/// AddPlaceError::InvalidCoordinates(coords) => {
/// write!(f, "invalid coordinates: {coords:?}")
/// },
/// AddPlaceError::InvalidName(name) => {
/// write!(f, "invalid name: {name:?}")
/// },
/// }
/// }
/// }
///
/// #[reducer]
/// pub fn add_place(
/// context: &ReducerContext,
/// name: String,
/// x: f32,
/// y: f32,
/// area: f32,
/// ) -> Result<(), AddPlaceError> {
/// // ... add a place to the database...
/// # Ok(())
/// }
/// # }
/// ```
///
/// Reducers may fail by returning a [`Result::Err`](std::result::Result) or by [panicking](std::panic!).
/// Failures will abort the active database transaction.
/// Any changes to the database made by the failed reducer call will be rolled back.
///
/// Reducers are limited in their ability to interact with the outside world.
/// They do not directly return data aside from errors, and have no access to any
/// network or filesystem interfaces.
/// Calling methods from [`std::io`], [`std::net`], or [`std::fs`]
/// inside a reducer will result in runtime errors.
///
/// Reducers can communicate information to the outside world in two ways:
/// - They can modify tables in the database.
/// See the `#[table]`(#table) macro documentation for information on how to declare and use tables.
/// - They can call logging macros from the [`log`] crate.
/// This writes to a private debug log attached to the database.
/// Run `spacetime logs <DATABASE_IDENTITY>` to browse these.
///
/// Reducers are permitted to call other reducers, simply by passing their `ReducerContext` as the first argument.
/// This is a regular function call, and does not involve any network communication. The callee will run within the
/// caller's transaction, and any changes made by the callee will be committed or rolled back with the caller.
///
/// # Lifecycle Reducers
///
/// You can specify special lifecycle reducers that are run at set points in
/// the module's lifecycle. You can have one of each per module.
///
/// These reducers cannot be called manually
/// and may not have any parameters except for `ReducerContext`.
///
/// ### The `init` reducer
///
/// This reducer is marked with `#[spacetimedb::reducer(init)]`. It is run the first time a module is published
/// and any time the database is cleared. (It does not have to be named `init`.)
///
/// If an error occurs when initializing, the module will not be published.
///
/// This reducer can be used to configure any static data tables used by your module. It can also be used to start running [scheduled reducers](#scheduled-reducers).
///
/// ### The `client_connected` reducer
///
/// This reducer is marked with `#[spacetimedb::reducer(client_connected)]`. It is run when a client connects to the SpacetimeDB module.
/// Their identity can be found in the sender value of the `ReducerContext`.
///
/// If an error occurs in the reducer, the client will be disconnected.
///
/// ### The `client_disconnected` reducer
///
/// This reducer is marked with `#[spacetimedb::reducer(client_disconnected)]`. It is run when a client disconnects from the SpacetimeDB module.
/// Their identity can be found in the sender value of the `ReducerContext`.
///
/// If an error occurs in the disconnect reducer,
/// the client is still recorded as disconnected.
///
// TODO(docs): Move these docs to be on `table`, rather than `reducer`. This will reduce duplication with procedure docs.
/// # Scheduled reducers
///
/// In addition to life cycle annotations, reducers can be made **scheduled**.
/// This allows calling the reducers at a particular time, or in a loop.
/// This can be used for game loops.
///
/// The scheduling information for a reducer is stored in a table.
/// This table has two mandatory fields:
/// - A primary key that identifies scheduled reducer calls.
/// - A [`ScheduleAt`] field that says when to call the reducer.
///
/// Managing timers with a scheduled table is as simple as inserting or deleting rows from the table.
/// This makes scheduling transactional in SpacetimeDB. If a reducer A first schedules B but then errors for some other reason, B will not be scheduled to run.
///
/// A [`ScheduleAt`] can be created from a [`spacetimedb::Timestamp`](crate::Timestamp), in which case the reducer will be scheduled once,
/// or from a [`std::time::Duration`], in which case the reducer will be scheduled in a loop. In either case the conversion can be performed using [`Into::into`].
///
/// ```no_run
/// # #[cfg(target_arch = "wasm32")] mod demo {
/// use spacetimedb::{table, reducer, ReducerContext, Timestamp, TimeDuration, ScheduleAt, Table};
/// use log::debug;
///
/// // First, we declare the table with scheduling information.
///
/// #[table(accessor = send_message_schedule, scheduled(send_message))]
/// struct SendMessageSchedule {
/// // Mandatory fields:
/// // ============================
///
/// /// An identifier for the scheduled reducer call.
/// #[primary_key]
/// #[auto_inc]
/// scheduled_id: u64,
///
/// /// Information about when the reducer should be called.
/// scheduled_at: ScheduleAt,
///
/// // In addition to the mandatory fields, any number of fields can be added.
/// // These can be used to provide extra information to the scheduled reducer.
///
/// // Custom fields:
/// // ============================
///
/// /// The text of the scheduled message to send.
/// text: String,
/// }
///
/// // Then, we declare the scheduled reducer.
/// // The first argument of the reducer should be, as always, a `&ReducerContext`.
/// // The second argument should be a row of the scheduling information table.
///
/// #[reducer]
/// fn send_message(ctx: &ReducerContext, arg: SendMessageSchedule) -> Result<(), String> {
/// let message_to_send = arg.text;
///
/// // ... send the message ...
///
/// Ok(())
/// }
///
/// // Now, we want to actually start scheduling reducers.
/// // It's convenient to do this inside the `init` reducer.
/// #[reducer(init)]
/// fn init(ctx: &ReducerContext) {
///
/// let current_time = ctx.timestamp;
///
/// let ten_seconds = TimeDuration::from_micros(10_000_000);
///
/// let future_timestamp: Timestamp = ctx.timestamp + ten_seconds;
/// ctx.db.send_message_schedule().insert(SendMessageSchedule {
/// scheduled_id: 1,
/// text:"I'm a bot sending a message one time".to_string(),
///
/// // Creating a `ScheduleAt` from a `Timestamp` results in the reducer
/// // being called once, at exactly the time `future_timestamp`.
/// scheduled_at: future_timestamp.into()
/// });
///
/// let loop_duration: TimeDuration = ten_seconds;
/// ctx.db.send_message_schedule().insert(SendMessageSchedule {
/// scheduled_id: 0,
/// text:"I'm a bot sending a message every 10 seconds".to_string(),
///
/// // Creating a `ScheduleAt` from a `Duration` results in the reducer
/// // being called in a loop, once every `loop_duration`.
/// scheduled_at: loop_duration.into()
/// });
/// }
/// # }
/// ```
///
/// Scheduled reducers are called on a best-effort basis and may be slightly delayed in their execution
/// when a database is under heavy load.
///
/// ### Restricting scheduled reducers
///
/// Scheduled reducers are normal reducers, and may still be called by clients.
/// If a scheduled reducer should only be called by the scheduler,
/// consider beginning it with a check that the caller `Identity` is the module:
///
/// ```no_run
/// # #[cfg(target_arch = "wasm32")] mod demo {
/// use spacetimedb::{reducer, ReducerContext};
///
/// # #[derive(spacetimedb::SpacetimeType)] struct ScheduledArgs {}
///
/// #[reducer]
/// fn scheduled(ctx: &ReducerContext, args: ScheduledArgs) -> Result<(), String> {
/// if ctx.sender() != ctx.identity() {
/// return Err("Reducer `scheduled` may not be invoked by clients, only via scheduling.".into());
/// }
/// // Reducer body...
/// # Ok(())
/// }
/// # }
/// ```
///
/// <!-- TODO: SLAs? -->
///
/// [`&ReducerContext`]: `ReducerContext`
/// [clients]: https://spacetimedb.com/docs/#client
pub use reducer;
/// Marks a function as a SpacetimeDB procedure.
///
/// A procedure is a function that runs within the database and can be invoked remotely by [clients],
/// but unlike a [`reducer`], a procedure is not automatically transactional.
/// This allows procedures to perform certain side-effecting operations,
/// but also means that module developers must be more careful not to corrupt the database state
/// when execution aborts or operations fail.
///
/// When in doubt, prefer writing [`reducer`]s unless you need to perform an operation only available to procedures.
///
/// The first argument of a procedure is always `&mut ProcedureContext`.
/// The [`ProcedureContext`] exposes information about the caller and allows side-effecting operations.
///
/// After this, a procedure can take any number of arguments.
/// These arguments must implement the [`SpacetimeType`], [`Serialize`], and [`Deserialize`] traits.
/// All of these traits can be derived at once by marking a type with `#[derive(SpacetimeType)]`.
///
/// A procedure may return any type that implements [`SpacetimeType`], [`Serialize`] and [`Deserialize`].
/// Unlike [reducer]s, SpacetimeDB does not assign any special semantics to [`Result`] return values.
///
/// If a procedure returns successfully (as opposed to panicking), its return value will be sent to the calling client.
/// If a procedure panics, its panic message will be sent to the calling client instead.
/// Procedure arguments and return values are not otherwise broadcast to clients.
///
/// ```no_run
/// # use spacetimedb::{procedure, SpacetimeType, ProcedureContext, Timestamp};
/// #[procedure]
/// fn return_value(ctx: &mut ProcedureContext, arg: MyArgument) -> MyReturnValue {
/// MyReturnValue {
/// a: format!("Hello, {}", ctx.sender()),
/// b: ctx.timestamp,
/// }
/// }
///
/// #[derive(SpacetimeType)]
/// struct MyArgument {
/// val: u32,
/// }
///
/// #[derive(SpacetimeType)]
/// struct MyReturnValue {
/// a: String,
/// b: Timestamp,
/// }
/// ```
///
/// # Blocking operations
///
/// Procedures are allowed to perform certain operations which take time.
/// During the execution of these operations, the procedure's execution will be suspended,
/// allowing other database operations to run in parallel.
///
/// Procedures must not hold open a transaction while performing a blocking operation.
// TODO(procedure-http): add example with an HTTP request.
// TODO(procedure-transaction): document obtaining and using a transaction within a procedure.
///
/// # Scheduled procedures
// TODO(docs): after moving scheduled reducer docs into table section, link there.
///
/// Like [reducer]s, procedures can be made **scheduled**.
/// This allows calling procedures at a particular time, or in a loop.
/// It also allows reducers to enqueue procedure runs.
///
/// Scheduled procedures are called on a best-effort basis and may be slightly delayed in their execution
/// when a database is under heavy load.
///
/// [clients]: https://spacetimedb.com/docs/#client
// TODO(procedure-async): update docs and examples with `async`-ness.
pub use procedure;
/// Marks a function as a spacetimedb view.
///
/// A view is a function with read-only access to the database.
///
/// The first argument of a view is always a [`&ViewContext`] or [`&AnonymousViewContext`].
/// The former can only read from the database whereas latter can also access info about the caller.
///
/// After this, a view can take any number of arguments just like reducers.
/// These arguments must implement the [`SpacetimeType`], [`Serialize`], and [`Deserialize`] traits.
/// All of these traits can be derived at once by marking a type with `#[derive(SpacetimeType)]`.
///
/// Views return `Vec<T>` or `Option<T>` where `T` is a `SpacetimeType`.
///
/// ```no_run
/// # mod demo {
/// use spacetimedb::{view, table, AnonymousViewContext, SpacetimeType, ViewContext};
/// use spacetimedb_lib::Identity;
///
/// #[table(accessor = player)]
/// struct Player {
/// #[auto_inc]
/// #[primary_key]
/// id: u64,
///
/// #[unique]
/// identity: Identity,
///
/// #[index(btree)]
/// level: u32,
/// }
///
/// impl Player {
/// fn merge(self, location: Location) -> PlayerAndLocation {
/// PlayerAndLocation {
/// player_id: self.id,
/// level: self.level,
/// x: location.x,
/// y: location.y,
/// }
/// }
/// }
///
/// #[derive(SpacetimeType)]
/// struct PlayerId {
/// id: u64,
/// }
///
/// #[derive(SpacetimeType)]
/// struct PlayerCount {
/// count: u64,
/// }
///
/// #[table(accessor = location, index(accessor = coordinates, btree(columns = [x, y])))]
/// struct Location {
/// #[unique]
/// player_id: u64,
/// x: u64,
/// y: u64,
/// }
///
/// #[derive(SpacetimeType)]
/// struct PlayerAndLocation {
/// player_id: u64,
/// level: u32,
/// x: u64,
/// y: u64,
/// }
///
/// // A view that selects at most one row from a table
/// #[view(accessor = my_player, public)]
/// fn my_player(ctx: &ViewContext) -> Option<Player> {
/// ctx.db.player().identity().find(ctx.sender())
/// }
///
/// // An example of column projection
/// #[view(accessor = my_player_id, public)]
/// fn my_player_id(ctx: &ViewContext) -> Option<PlayerId> {
/// ctx.db.player().identity().find(ctx.sender()).map(|Player { id, .. }| PlayerId { id })
/// }
///
/// // A view that counts the number of rows in a table
/// #[view(accessor = player_count, public)]
/// fn player_count(ctx: &AnonymousViewContext) -> Option<PlayerCount> {
/// Some(PlayerCount {
/// count: ctx.db.player().count(),
/// })
/// }
///
/// // An example that is analogous to a semijoin in sql
/// #[view(accessor = players_at_coordinates, public)]
/// fn players_at_coordinates(ctx: &AnonymousViewContext) -> Vec<Player> {
/// ctx
/// .db
/// .location()
/// .coordinates()
/// .filter((3u64, 5u64))
/// .filter_map(|location| ctx.db.player().id().find(location.player_id))
/// .collect()
/// }
///
/// // An example of a join that combines fields from two different tables
/// #[view(accessor = players_with_coordinates, public)]
/// fn players_with_coordinates(ctx: &AnonymousViewContext) -> Vec<PlayerAndLocation> {
/// ctx
/// .db
/// .location()
/// .coordinates()
/// .filter((3u64, 5u64))
/// .filter_map(|location| ctx
/// .db
/// .player()
/// .id()
/// .find(location.player_id)
/// .map(|player| player.merge(location))
/// )
/// .collect()
/// }
/// # }
/// ```
///
/// Just like reducers, views are limited in their ability to interact with the outside world.
/// They have no access to any network or filesystem interfaces.
/// Calling methods from [`std::io`], [`std::net`], or [`std::fs`] will result in runtime errors.
///
/// Views are callable by reducers and other views simply by passing their `ViewContext`..
/// This is a regular function call.
/// The callee will run within the caller's transaction.
///
///
/// [`&ViewContext`]: `ViewContext`
/// [`&AnonymousViewContext`]: `AnonymousViewContext`
pub use view;
pub use ;
/// One of two possible types that can be passed as the first argument to a `#[view]`.
/// The other is [`ViewContext`].
/// Use this type if the view does not depend on the caller's identity.
/// One of two possible types that can be passed as the first argument to a `#[view]`.
/// The other is [`AnonymousViewContext`].
/// Use this type if the view depends on the caller's identity.
/// The context that any reducer is provided with.
///
/// This must be the first argument of the reducer. Clients of the module will
/// only see arguments after the `ReducerContext`.
///
/// Includes information about the client calling the reducer and the time of invocation,
/// as well as a view into the module's database.
///
/// If the crate was compiled with the `rand` feature, also includes faculties for random
/// number generation.
///
/// Implements the `DbContext` trait for accessing views into a database.
/// The context that an anonymous transaction
/// in [`ProcedureContext::with_tx`] is provided with.
///
/// Includes information about the client starting the transaction
/// and the time of the procedure/reducer,
/// as well as a view into the module's database.
///
/// If the crate was compiled with the `rand` feature, also includes faculties for random
/// number generation.
///
/// Implements the `DbContext` trait for accessing views into a database.
;
/// The context that any procedure is provided with.
///
/// Each procedure must accept `&mut ProcedureContext` as its first argument.
///
/// Includes information about the client calling the procedure and the time of invocation,
/// and exposes methods for running transactions and performing side-effecting operations.
/// A handle on a database with a particular table schema.
// `ProcedureContext` is *not* a `DbContext`
// but a `TxContext` derived from it is.
/// Allows accessing the local database attached to the module.
///
/// This slightly strange type appears to have no methods, but that is misleading.
/// The `#[table]` macro uses the trait system to add table accessors to this type.
/// These are generated methods that allow you to access specific tables.
/// The [JWT] of an [`AuthCtx`].
///
/// [JWT]: https://en.wikipedia.org/wiki/JSON_Web_Token
/// Authentication information for the caller of a reducer.
/// The read-only version of [`Local`]
// #[cfg(target_arch = "wasm32")]
// #[global_allocator]
// static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
// This should guarantee in most cases that we don't have to reallocate an iterator
// buffer, unless there's a single row that serializes to >1 MiB.
const DEFAULT_BUFFER_CAPACITY: usize = ROW_ITER_CHUNK_SIZE * 2;
/// Queries and returns the `table_id` associated with the given (table) `name`.
///
/// Panics if the table does not exist.
thread_local!
;
=> ;
=> ;
=> ;
}