### SpacetimeDB Installation and Getting Started
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/index.md
Instructions for installing the SpacetimeDB CLI tool and getting started with a standalone instance. Links to installation and getting started guides are provided.
```markdown
You can find the instructions to install the CLI tool for your platform [here](/install).
To get started running your own standalone instance of SpacetimeDB check out our [Getting Started Guide](/docs/getting-started).
```
--------------------------------
### Project Setup and Dependencies (Bash)
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/typescript/quickstart.md
Commands to set up a new client project using Vite with React and TypeScript, install dependencies, and add the SpacetimeDB SDK.
```Bash
cd quickstart-chat
pnpm create vite@latest client -- --template react-ts
cd client
pnpm install
pnpm install @clockworklabs/spacetimedb-sdk
```
--------------------------------
### Log in to SpacetimeDB
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/getting-started.md
Logs the user into SpacetimeDB using GitHub authentication. This is required for publishing modules and other authenticated actions. The command opens a browser for the login process.
```bash
spacetime login
```
--------------------------------
### SpacetimeDB Complete Code Example Location
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/STYLE.md
Instructs on how to provide a link to the complete code for a tutorial project, typically hosted on GitHub. It specifies that the linked repository or folder should contain a README.md file detailing the project's name, setup instructions, dependency links, and a back-link to the tutorial.
```English
If the tutorial involved writing code, add a link to the complete code. This should be somewhere on GitHub, either as its own repo, or as an example project within an existing repo. Ensure the linked folder has a README.md file which includes:
- The name of the tutorial project.
- How to run or interact with the tutorial project, whatever that means (e.g. publish to maincloud and then `spacetime call`).
- Links to external dependencies (e.g. for client projects, the module which it runs against).
- A back-link to the tutorial that builds this project.
At the end of the tutorial that builds the `quickstart-chat` module in Rust, you might write:
You can find the full code for this module in [the SpacetimeDB module examples](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/quickstart-chat).
```
--------------------------------
### Install .NET 8 SDK and WASI Workload
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/modules/c-sharp/quickstart.md
Commands to check for and install the .NET 8 SDK and the required WASI experimental workload for SpacetimeDB module development.
```bash
dotnet --list-sdks
dotnet workload install wasi-experimental
```
--------------------------------
### Start SpacetimeDB Standalone Server
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/getting-started.md
Starts the SpacetimeDB standalone server locally. The server defaults to listening on port 3000, but this can be changed using the --listen-addr flag. SSL is not supported in this mode.
```bash
spacetime start
```
--------------------------------
### Running the Client Application
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/typescript/quickstart.md
These commands navigate to the client directory and start the development server using pnpm.
```sh
cd client
pnpm run dev
```
--------------------------------
### SpacetimeDB Client SDKs
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/index.md
Overview of available SpacetimeDB Client SDKs and their quickstart guides.
```MARKDOWN
- [Rust](/docs/sdks/rust) - [(Quickstart)](/docs/sdks/rust/quickstart)
- [C#](/docs/sdks/c-sharp) - [(Quickstart)](/docs/sdks/c-sharp/quickstart)
- [TypeScript](/docs/sdks/typescript) - [(Quickstart)](/docs/sdks/typescript/quickstart)
```
--------------------------------
### Install Rust Compiler
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/modules/rust/quickstart.md
Command to install the Rust compiler on macOS and Linux systems using a script from rustup.rs.
```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
```
--------------------------------
### Run the Client with dotnet command in bash
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/c-sharp/quickstart.md
This snippet shows how to run the client by executing the dotnet run command in the client directory. This command compiles and executes the C# client application.
```bash
dotnet run --project client
```
--------------------------------
### Run the Client with Main Function in C#
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/c-sharp/quickstart.md
This snippet adds a call to the Main function in Program.cs to run the client application. This is the entry point for the application.
```csharp
Main();
```
--------------------------------
### SQL Query Result Example
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/modules/rust/quickstart.md
This is an example of the output generated by the SQL query. It shows the 'sender', 'sent', and 'text' columns from the 'message' table, with a single row containing example data.
```sql
sender | sent | text
--------------------------------------------------------------------+----------------------------------+-----------------
0x93dda09db9a56d8fa6c024d843e805d8262191db3b4ba84c5efcd1ad451fed4e | 2025-04-08T15:47:46.935402+00:00 | "Hello, world!"
```
--------------------------------
### Run Development Server
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/typescript/quickstart.md
Command to start the development server for the client application. This is typically used to view changes in real-time during development.
```sh
cd client
pnpm run dev
```
--------------------------------
### Start Local SpacetimeDB Server
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/unity/part-2.md
Starts a local instance of SpacetimeDB. This is a prerequisite for publishing and interacting with modules.
```sh
spacetime start
```
--------------------------------
### Project Setup: Install SpacetimeDB SDK
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/typescript/index.md
Install the SpacetimeDB SDK package using npm in your client project directory. This command assumes you are in the root of your project and have a 'client' subdirectory.
```bash
cd client
npm install @clockworklabs/spacetimedb-sdk
```
--------------------------------
### SQL Query Result Example
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/modules/rust/quickstart.md
Shows the expected tabular output format for a SQL query executed against a SpacetimeDB database. This example displays columns for sender, sent timestamp, and text content.
```sql
sender | sent | text
--------------------------------------------------------------------+----------------------------------+-----------------
0x93dda09db9a56d8fa6c024d843e805d8262191db3b4ba84c5efcd1ad451fed4e | 2025-04-08T15:47:46.935402+00:00 | "Hello, world!"
```
--------------------------------
### Execute SQL Query
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/modules/rust/quickstart.md
Demonstrates how to run a SQL query against a SpacetimeDB database using the `spacetime sql` command. This example queries all data from the 'message' table in the 'quickstart-chat' database.
```bash
spacetime sql quickstart-chat "SELECT * FROM message"
```
--------------------------------
### Spacetime Start Command
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/cli-reference.md
Starts a local SpacetimeDB instance. Allows specifying the edition (e.g., standalone, cloud) to be used for startup. Additional arguments can be passed to the underlying spacetimedb process.
```bash
spacetime start [--edition ] [--help] []...
Start a local SpacetimeDB instance
Arguments:
The args to pass to `spacetimedb-{edition} start`
Options:
--edition The edition of SpacetimeDB to start up [possible values: standalone, cloud] [default: standalone]
--help Show this message and exit.
Run `spacetime start --help` to see all options.
```
--------------------------------
### Install SpacetimeDB Unity Package
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/c-sharp/index.md
Installs the SpacetimeDB Unity Package by providing its Git URL to the Unity Package Manager.
```bash
https://github.com/clockworklabs/com.clockworklabs.spacetimedbsdk.git
```
--------------------------------
### C# Main Function Call
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/c-sharp/quickstart.md
Adds the call to the Main function to start the client application.
```csharp
Main();
```
--------------------------------
### Call SpacetimeDB Reducer
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/modules/c-sharp/quickstart.md
Executes a reducer on the SpacetimeDB server. Arguments are passed in JSON format.
```bash
spacetime call quickstart-chat SendMessage "Hello, World!"
```
--------------------------------
### JOIN Example
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sql/index.md
An example demonstrating how to join multiple tables (Customers, Orders, Inventory) to retrieve specific information.
```SQL
-- Find all customers who ordered a particular product and when they ordered it
SELECT customer.first_name, customer.last_name, o.date
FROM Customers customer
JOIN Orders o ON customer.id = o.customer_id
JOIN Inventory product ON o.product_id = product.id
WHERE product.name = {product_name}
```
--------------------------------
### Query SpacetimeDB with SQL
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/modules/c-sharp/quickstart.md
Executes a SQL query against the SpacetimeDB database.
```bash
spacetime sql quickstart-chat "SELECT * FROM message"
```
--------------------------------
### Spacetime Publish Output Example
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/modules/c-sharp/index.md
Example output from the `spacetime publish` command, showing the created database name and its identity.
```text
Created new database with name: , identity:
```
--------------------------------
### View SpacetimeDB Logs
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/modules/c-sharp/quickstart.md
Retrieves logs from the SpacetimeDB server to verify reducer execution.
```bash
spacetime logs quickstart-chat
```
--------------------------------
### Manage SpacetimeDB Systemd Service
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/deploying/spacetimedb-standalone.md
Commands to enable the SpacetimeDB service to start on boot, start the service immediately, and check its current status.
```sh
sudo systemctl enable spacetimedb
sudo systemctl start spacetimedb
sudo systemctl status spacetimedb
```
--------------------------------
### Install SpacetimeDB CLI
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/llms.md
Installs the SpacetimeDB command-line interface tool for managing modules, databases, and local instances across different operating systems.
```bash
curl -sSf https://install.spacetimedb.com | sh
```
```powershell
iwr https://windows.spacetimedb.com -useb | iex
```
--------------------------------
### Create Project Directory
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/unity/part-1.md
Creates a new directory for the project and navigates into it. This is the initial step for setting up the project structure.
```bash
mkdir blackholio
cd blackholio
```
--------------------------------
### EBNF Grammar Specification
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/STYLE.md
Specifies how to write Extended Backus-Naur Form (EBNF) grammars for context-free languages within documentation. It advises starting with the topmost nonterminal and working downwards, excluding trivial rules. Examples should be provided in a separate code block.
```ebnf
statement = ident, "(", [ expr, { ",", expr } ], ")" ;
expr = literal | ident ;
ident = alpha, { alpha | digit } ;
literal = digit, { digit } ;
alpha = "a" | "b" | ... | "z" | "A" | "B" | ... | "Z" ;
digit = "0" | "1" | ... | "9" ;
```
--------------------------------
### Start SpacetimeDB Service
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/deploying/spacetimedb-standalone.md
This command starts the SpacetimeDB service after an upgrade or installation. It ensures that the service is running and accessible.
```sh
sudo systemctl start spacetimedb
```
--------------------------------
### TypeScript SpacetimeDB SDK Setup and Module Generation
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/llms.md
Guides users on setting up the SpacetimeDB client SDK in a TypeScript project and generating module-specific bindings. It covers installing the SDK via npm or yarn, using the `spacetime generate` command with language and output directory flags, and importing generated types and SDK components for client application development.
```bash
mkdir -p src/module_bindings
spacetime generate --lang typescript \
--out-dir src/module_bindings \
--project-path ../path/to/your/server_module
```
```typescript
// Import SDK core types
import { Identity, Status } from "@clockworklabs/spacetimedb-sdk";
// Import generated connection class, event contexts, and table types
import { DbConnection, EventContext, ReducerEventContext, Message, User } from "./module_bindings";
// Reducer functions are accessed via conn.reducers
```
--------------------------------
### Navigate to Project Directory
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/rust/quickstart.md
Changes the current directory to the 'quickstart-chat' folder, which is assumed to be created in a previous step.
```bash
cd quickstart-chat
```
--------------------------------
### C# ArrayList Usage Example
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/STYLE.md
Provides a C# example of using the ArrayList class to add elements and display its properties, including expected console output.
```csharp
using System;
using System.Collections;
public class SamplesArrayList {
public static void Main() {
// Creates and initializes a new ArrayList.
ArrayList myAL = new ArrayList();
myAL.Add("Hello");
myAL.Add("World");
myAL.Add("!");
// Displays the properties and values of the ArrayList.
Console.WriteLine( "myAL" );
Console.WriteLine( " Count: {0}", myAL.Count );
Console.WriteLine( " Capacity: {0}", myAL.Capacity );
Console.Write( " Values:" );
PrintValues( myAL );
}
public static void PrintValues( IEnumerable myList ) {
foreach ( Object obj in myList )
Console.Write( " {0}", obj );
Console.WriteLine();
}
}
/*
This code produces output similar to the following:
myAL
Count: 3
Capacity: 4
Values: Hello World !
*/
```
--------------------------------
### Initialize SpacetimeDB C# Module
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/modules/c-sharp/quickstart.md
Command to initialize a new SpacetimeDB module project with C# as the language.
```bash
mkdir quickstart-chat
cd quickstart-chat
spacetime init --lang csharp server
```
--------------------------------
### Add SpacetimeDB C# SDK Package
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/c-sharp/quickstart.md
Adds the `SpacetimeDB.ClientSDK` NuGet package to the C# project using the .NET CLI.
```bash
dotnet add package SpacetimeDB.ClientSDK
```
--------------------------------
### Rust Code Example with Meta-Variables
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/STYLE.md
Demonstrates how to use meta-variables in Rust code blocks, enclosed in curly braces and explained in accompanying text. This example shows querying a table by a specific column value.
```rust
ctx.db.{table}().{column}().find({value})
```
```rust
ctx.db.people().name().find("Billy")
```
--------------------------------
### Run SpacetimeDB Client
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/c-sharp/quickstart.md
Command to run the SpacetimeDB client application from the command line.
```bash
dotnet run --project client
```
--------------------------------
### C# ArrayList Declaration Example
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/STYLE.md
Demonstrates the declaration of the ArrayList class in C#, implementing the IList interface.
```csharp
public class ArrayList : ICloneable, System.Collections.IList
```
--------------------------------
### SpacetimeDB Client SDK Setup (C#)
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/llms.md
Provides instructions for setting up a C# client application to interact with SpacetimeDB. It covers adding the client SDK NuGet package for .NET projects and integrating the SDK via a Git URL for Unity projects.
```bash
dotnet new console -o my_csharp_client
cd my_csharp_client
dotnet add package SpacetimeDB.ClientSDK
```
```bash
https://github.com/clockworklabs/com.clockworklabs.spacetimedbsdk.unity
```
--------------------------------
### Unity Tutorial Structure
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/unity/index.md
Outlines the different parts of the Unity tutorial for building a multiplayer game with SpacetimeDB. It details the progression from basic setup to gameplay and advanced features.
```markdown
- Part 1 - Setup
- Part 2 - Connecting to SpacetimeDB
- Part 3 - Gameplay
- Part 4 - Moving and Colliding
```
--------------------------------
### SpacetimeDB Module Development Languages
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/index.md
Information on developing SpacetimeDB modules using C# and Rust, including links to quickstart guides for each language.
```markdown
- [Rust](/docs/modules/rust) - [(Quickstart)](/docs/modules/rust/quickstart)
- [C#](/docs/modules/c-sharp) - [(Quickstart)](/docs/modules/c-sharp/quickstart)
```
--------------------------------
### TypeScript Type for JSON Encoding
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/STYLE.md
An example of defining a TypeScript-style type to describe JSON encoding, as an alternative to EBNF when readers are familiar with the language.
```typescript
type User = {
id: number;
name: string;
email?: string;
};
```
--------------------------------
### SpacetimeDB Tutorial Next Steps and Extensions
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/STYLE.md
Provides guidance on directing users to the next steps in a tutorial series, linking to relevant SDK reference documentation, and suggesting potential project extensions. This includes ideas for improving user interfaces, refining data subscriptions, and adding new features like message styling, moderation, rooms, and direct messaging.
```English
If this tutorial is part of a series, link to the next entry:
You can use any of SpacetimDB's supported client languages to do this. Take a look at the quickstart guide for your client language of choice: [Rust](/docs/sdks/rust/quickstart), [C#](/docs/sdks/c-sharp/quickstart), or [TypeScript](/docs/sdks/typescript/quickstart). If you are planning to use SpacetimeDB with the Unity game engine, you can skip right to the [Unity Comprehensive Tutorial](/docs/unity/part-1).
If this tutorial is about a specific component, link to its reference page:
Check out the [Rust SDK Reference](/docs/sdks/rust) for a more comprehensive view of the SpacetimeDB Rust SDK.
If this tutorial is the end of a series, or ends with a reasonably complete app, throw in some ideas about how the reader could extend it:
Our basic terminal interface has some limitations. Incoming messages can appear while the user is typing, which is less than ideal. Additionally, the user's input gets mixed with the program's output, making messages the user sends appear twice. You might want to try improving the interface by using [Rustyline](https://crates.io/crates/rustyline), [Cursive](https://crates.io/crates/cursive), or even creating a full-fledged GUI.
Once your chat server runs for a while, you might want to limit the messages your client loads by refining your `Message` subscription query, only subscribing to messages sent within the last half-hour.
You could also add features like:
- Styling messages by interpreting HTML tags and printing appropriate [ANSI escapes](https://en.wikipedia.org/wiki/ANSI_escape_code).
- Adding a `moderator` flag to the `User` table, allowing moderators to manage users (e.g., time-out, ban).
- Adding rooms or channels that users can join or leave.
- Supporting direct messages or displaying user statuses next to their usernames.
```
--------------------------------
### Create C# Console Application
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/c-sharp/quickstart.md
Creates a new C# console application project named 'client' in the current directory using the .NET CLI.
```bash
dotnet new console -o client
```
--------------------------------
### SpacetimeDB Client-side SDK Languages
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/index.md
Details on client-side SDKs for interacting with SpacetimeDB databases, including support for Rust, C#, and TypeScript, with links to quickstart guides.
```markdown
- [Rust](/docs/sdks/rust) - [(Quickstart)](/docs/sdks/rust/quickstart)
- [C#](/docs/sdks/c-sharp) - [(Quickstart)](/docs/sdks/c-sharp/quickstart)
- [TypeScript](/docs/sdks/typescript) - [(Quickstart)](/docs/sdks/typescript/quickstart)
```
--------------------------------
### Clear and Create Main Rust File
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/rust/quickstart.md
Removes the default 'Hello world' content from client/src/main.rs and creates an empty file, preparing it for the client application code.
```bash
rm client/src/main.rs
touch client/src/main.rs
```
--------------------------------
### SQL Query Example with Meta-Variables
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/STYLE.md
Illustrates an SQL query using meta-variables that represent table and column names, and a value to search for. The meta-variables are explained in the surrounding text.
```sql
SELECT * FROM {table} WHERE {column} = {value}
```
--------------------------------
### Import SpacetimeDB Unity SDK
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/unity/part-1.md
Adds the SpacetimeDB Unity SDK package to your Unity project using the Package Manager. This SDK provides tools for integrating SpacetimeDB, including a network manager.
```bash
https://github.com/clockworklabs/com.clockworklabs.spacetimedbsdk.git
```
--------------------------------
### Project Setup: tsconfig.json Configuration
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/typescript/index.md
Configure your TypeScript project's tsconfig.json file to use the SpacetimeDB TypeScript client SDK. This example sets the target to 'es2015'.
```json
{
"compilerOptions": {
"target": "es2015"
}
}
```
--------------------------------
### SpacetimeDB Connect Reducer Stub (Rust)
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/STYLE.md
A placeholder for the 'connect' reducer function within a SpacetimeDB module. This serves as a starting point for implementing database logic in response to client connections.
```Rust
I don't actually need to fill this in.
```
--------------------------------
### SpacetimeDB Rust Client Project Setup
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/llms.md
Commands to set up a new Rust project for a SpacetimeDB client application. It includes creating a new cargo project and adding the `spacetimedb_sdk` dependency.
```bash
cargo new my_rust_client
cd my_rust_client
cargo add spacetimedb_sdk # Ensure version matches your SpacetimeDB installation
```
--------------------------------
### SpacetimeDB Lifecycle Reducers (Rust)
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/llms.md
Demonstrates the implementation of SpacetimeDB's special lifecycle reducers: `init`, `client_connected`, and `client_disconnected`. These reducers handle module initialization, new client connections, and client disconnections respectively, with examples showing logging and initial data setup.
```rust
use spacetimedb::{reducer, table, ReducerContext, Table, log};
#[table(name = settings)]
#[derive(Clone, Debug)]
pub struct Settings {
#[primary_key]
key: String,
value: String,
}
// Example init reducer: Insert default settings if the table is empty
#[reducer(init)]
pub fn initialize_database(ctx: &ReducerContext) {
log::info!(
"Database Initializing! Module Identity: {}, Timestamp: {}",
ctx.identity(),
ctx.timestamp
);
// Check if settings table is empty
if ctx.db.settings().count() == 0 {
log::info!("Settings table is empty, inserting default values...");
// Insert default settings
ctx.db.settings().insert(Settings {
key: "welcome_message".to_string(),
value: "Hello from SpacetimeDB!".to_string(),
});
ctx.db.settings().insert(Settings {
key: "default_score".to_string(),
value: "0".to_string(),
});
} else {
log::info!("Settings table already contains data.");
}
}
// Example client_connected reducer
#[reducer(client_connected)]
pub fn handle_connect(ctx: &ReducerContext) {
log::info!("Client connected: {}, Connection ID: {:?}", ctx.sender, ctx.connection_id);
// ... setup initial state for ctx.sender ...
}
// Example client_disconnected reducer
#[reducer(client_disconnected)]
pub fn handle_disconnect(ctx: &ReducerContext) {
log::info!("Client disconnected: {}, Connection ID: {:?}", ctx.sender, ctx.connection_id);
// ... cleanup state for ctx.sender ...
}
```
--------------------------------
### Compile and Run Chat Client
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/rust/quickstart.md
Steps to navigate to the client directory, compile the Rust code, and run the chat application. Shows expected output for connection and message sending.
```bash
cd client
cargo run
```
--------------------------------
### Accessing Database Tables via Db Property
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/c-sharp/index.md
The Db property of the DbConnection provides access to the subscribed view of the remote database's tables. It allows access to each table defined by the module. An example shows how to get a handle to the User table.
```csharp
class DbConnection
{
public RemoteTables Db;
/* other members */
}
```
```csharp
interface IRemoteDbContext
{
public DbView Db { get; }
}
// Example:
var conn = ConnectToDB();
// Get a handle to the User table
var tableHandle = conn.Db.User;
```
--------------------------------
### Handle User Input with InputLoop and ProcessCommands in C#
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/c-sharp/quickstart.md
The InputLoop function reads commands from standard input and enqueues them. The ProcessCommands function dequeues and processes these commands, calling Reducer.SendMessage or Reducer.SetName based on the command type. These functions are added to Program.cs.
```csharp
/// Read each line of standard input, and either set our name or send a message as appropriate.
void InputLoop()
{
while (true)
{
var input = Console.ReadLine();
if (input == null)
{
break;
}
if (input.StartsWith("/name "))
{
input_queue.Enqueue(("name", input[6..]));
continue;
}
else
{
input_queue.Enqueue(("message", input));
}
}
}
void ProcessCommands(RemoteReducers reducers)
{
// process input queue commands
while (input_queue.TryDequeue(out var command))
{
switch (command.Command)
{
case "message":
reducers.SendMessage(command.Args);
break;
case "name":
reducers.SetName(command.Args);
break;
}
}
}
```
--------------------------------
### Initialize SpacetimeDB Rust Module
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/modules/rust/quickstart.md
Command to initialize a new SpacetimeDB module project with Rust as the language.
```bash
spacetime init --lang rust server
```
--------------------------------
### Handle Reducer Failures in Spacetime
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/rust/quickstart.md
This section details how to handle reducer failures in Spacetime. It shows how to register callbacks using the `on_reducer` method to be invoked when a reducer succeeds or fails. Examples include `on_name_set` to notify users of rejected names and `on_message_sent` for failed message sending attempts.
```rust
/// Our `on_set_name` callback: print a warning if the reducer failed.
fn on_name_set(ctx: &ReducerEventContext, name: &String) {
if let Status::Failed(err) = &ctx.event.status {
eprintln!("Failed to change name to {:?}: {}", name, err);
}
}
/// Our `on_send_message` callback: print a warning if the reducer failed.
fn on_message_sent(ctx: &ReducerEventContext, text: &String) {
if let Status::Failed(err) = &ctx.event.status {
eprintln!("Failed to send message {:?}: {}", text, err);
}
}
```
--------------------------------
### Processing Updates in a Separate Thread in C#
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/c-sharp/quickstart.md
This code snippet demonstrates how to process database updates in a separate thread to avoid blocking the main thread. The ProcessThread function loops until a cancellation token is requested, calling the FrameTick function on the DbConnection to process updates and the ProcessCommands function to process commands. Finally, it disconnects from the database.
```csharp
/// Our separate thread from main, where we can call process updates and process commands without blocking the main thread.
void ProcessThread(DbConnection conn, CancellationToken ct)
{
try
{
// loop until cancellation token
while (!ct.IsCancellationRequested)
{
conn.FrameTick();
ProcessCommands(conn.Reducers);
Thread.Sleep(100);
}
}
finally
{
conn.Disconnect();
}
}
```
--------------------------------
### Project Setup with SpacetimeDB SDK
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sdks/rust/index.md
Instructions for setting up a new Rust project to use the SpacetimeDB Rust client SDK. This involves creating a new Cargo project and adding the SDK as a dependency.
```bash
cargo add spacetimedb_sdk
```
--------------------------------
### INSERT Examples
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sql/index.md
Provides examples for inserting single or multiple rows into the Inventory table.
```SQL
-- Inserting one row
INSERT INTO Inventory (item_id, item_name) VALUES (1, 'health1');
-- Inserting two rows
INSERT INTO Inventory (item_id, item_name) VALUES (1, 'health1'), (2, 'health2');
```
--------------------------------
### UPDATE Example
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sql/index.md
An example demonstrating how to update the item_name for rows matching a specific item_id in the Inventory table.
```SQL
-- Update the item_name for all rows with a specific item_id
UPDATE Inventory SET item_name = 'new name' WHERE item_id = 1;
```
--------------------------------
### Publish SpacetimeDB Module
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/modules/c-sharp/quickstart.md
Compiles and publishes a SpacetimeDB module to the database. It can take an optional name for the module.
```bash
spacetime publish --project-path server quickstart-chat
```
--------------------------------
### DELETE Examples
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/sql/index.md
Shows examples of deleting all rows or specific rows from the Inventory table using the DELETE statement.
```SQL
-- Delete all rows
DELETE FROM Inventory;
-- Delete all rows with a specific item_id
DELETE FROM Inventory WHERE item_id = 1;
```
--------------------------------
### Troubleshoot SpacetimeDB Service Startup and Permissions
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/deploying/spacetimedb-standalone.md
Offers commands to diagnose issues when the SpacetimeDB service fails to start. It includes checking logs, verifying file permissions for the Spacetime executable, and adding execute permissions if necessary.
```sh
sudo journalctl -u spacetimedb --no-pager | tail -20
```
```sh
sudo ls -lah /stdb/spacetime
```
```sh
sudo chmod +x /stdb/spacetime
```
--------------------------------
### Initialize C# SpacetimeDB Project
Source: https://github.com/clockworklabs/spacetime-docs/blob/master/docs/modules/c-sharp/index.md
Command to create a new SpacetimeDB project with C# language support. This sets up the necessary project structure and configuration files.
```bash
spacetime init --lang csharp my-project-directory
```