|
| 1 | +# Appendix |
| 2 | + |
| 3 | +## SEQUENCE |
| 4 | + |
| 5 | +For each table containing an `#[auto_inc]` column, SpacetimeDB creates a sequence number generator behind the scenes, which functions similarly to `postgres`'s `SEQUENCE`. |
| 6 | + |
| 7 | +### How It Works |
| 8 | + |
| 9 | +* Sequences in SpacetimeDB use Rust’s `i128` integer type. |
| 10 | +* The field type marked with `#[auto_inc]` is cast to `i128` and increments by `1` for each new row. |
| 11 | +* Sequences are pre-allocated in chunks of `4096` to speed up number generation, and then are only persisted to disk when the pre-allocated chunk is exhausted. |
| 12 | + |
| 13 | +> **⚠ Warning:** Sequence number generation is not transactional. |
| 14 | +
|
| 15 | +* Numbers are incremented even if a transaction is later rolled back. |
| 16 | +* Unused numbers are not reclaimed, meaning sequences may have *gaps*. |
| 17 | +* If the server restarts or a transaction rolls back, the sequence continues from the next pre-allocated chunk + `1`: |
| 18 | + |
| 19 | +**Example:** |
| 20 | + |
| 21 | +```rust |
| 22 | +#[spacetimedb::table(name = users, public)] |
| 23 | +struct Users { |
| 24 | + #[auto_inc] |
| 25 | + user_id: u64, |
| 26 | + name: String, |
| 27 | +} |
| 28 | + |
| 29 | +#[spacetimedb::reducer] |
| 30 | +pub fn insert_user(ctx: &ReducerContext, count: u8) { |
| 31 | + for i in 0..count { |
| 32 | + let name = format!("User {}", i); |
| 33 | + ctx.db.users().insert(Users { user_id: 0, name }); |
| 34 | + } |
| 35 | + // Query the table to see the effect of the `[auto_inc]` attribute: |
| 36 | + for user in ctx.db.users().iter() { |
| 37 | + log::info!("User: {:?}", user); |
| 38 | + } |
| 39 | +} |
| 40 | +``` |
| 41 | + |
| 42 | +Then: |
| 43 | + |
| 44 | +```bash |
| 45 | +❯ cargo run --bin spacetimedb-cli call sample insert_user 3 |
| 46 | + |
| 47 | +❯ spacetimedb-cli logs sample |
| 48 | +... |
| 49 | +.. User: Users { user_id: 1, name: "User 0" } |
| 50 | +.. User: Users { user_id: 2, name: "User 1" } |
| 51 | +.. User: Users { user_id: 3, name: "User 2" } |
| 52 | + |
| 53 | +# Database restart, then |
| 54 | + |
| 55 | +❯ cargo run --bin spacetimedb-cli call sample insert_user 1 |
| 56 | + |
| 57 | +❯ spacetimedb-cli logs sample |
| 58 | +... |
| 59 | +.. User: Users { user_id: 3, name: "User 2" } |
| 60 | +.. User: Users { user_id: 4098, name: "User 0" } |
| 61 | +``` |
0 commit comments