# Embedding

In Rust, SurrealDB can be run as an in-memory database, it can persist data using a file-based storage engine, or on a distributed cluster.

SurrealDB is designed to be run in many different ways and in many environments. Due to the [separation of the storage and API layers](/docs/learn/data-models/architecture.md), SurrealDB can be run in embedded mode, from within a number of different language environments. In Rust, SurrealDB can be run as an in-memory database, it can persist data using a file-based storage engine, or on a distributed cluster.

## Install the SDK

First, create a new project using `cargo new` and add the SurrealDB crate to your dependencies, enabling the key-value store you need:

```sh
# For an in memory database
cargo add surrealdb --features kv-mem

# For a RocksDB file
cargo add surrealdb --features kv-rocksdb
```

You will need to add the following additional dependencies:

```bash
cargo add serde --features derive
cargo add tokio --features macros,rt-multi-thread
```

<br />

## Connect to SurrealDB

Open `src/main.rs` and replace everything in there with the following code to try out some basic operations using the SurrealDB SDK with an embedded database. Look at [integrations to connect to a database](/docs/reference/rust.md).

```rust
use serde::{Deserialize, Serialize};
use surrealdb::types::RecordId;
use surrealdb::Surreal;

// For an in memory database
use surrealdb::engine::local::Mem;

// For a RocksDB file
// use surrealdb::engine::local::RocksDb;

#[derive(Debug, Serialize)]
struct Name<'a> {
    first: &'a str,
    last: &'a str,
}

#[derive(Debug, Serialize)]
struct Person<'a> {
    title: &'a str,
    name: Name<'a>,
    marketing: bool,
}

#[derive(Debug, Serialize)]
struct Responsibility {
    marketing: bool,
}

#[derive(Debug, Deserialize)]
struct Record {
    #[allow(dead_code)]
    id: RecordId,
}

#[tokio::main]
async fn main() -> surrealdb::Result<()> {
    // Create database connection in memory
    let db = Surreal::new::<Mem>(()).await?;
    
    // Create database connection using RocksDB
    // let db = Surreal::new::<RocksDb>("path/to/database-folder").await?;

    // Select a specific namespace / database
    db.use_ns("main").use_db("main").await?;

    // Create a new person with a random id
    let created: Option<Record> = db
        .create("person")
        .content(Person {
            title: "Founder & CEO",
            name: Name {
                first: "Tobie",
                last: "Morgan Hitchcock",
            },
            marketing: true,
        })
        .await?;
    dbg!(created);

    // Update a person record with a specific id
    let updated: Option<Record> = db
        .update(("person", "jaime"))
        .merge(Responsibility { marketing: true })
        .await?;
    dbg!(updated);

    // Select all people records
    let people: Vec<Record> = db.select("person").await?;
    dbg!(people);

    // Perform a custom advanced query
    let groups = db
        .query("SELECT marketing, count() FROM type::table($table) GROUP BY marketing")
        .bind(("table", "person"))
        .await?;
    dbg!(groups);

    Ok(())
}
```

Run your program from the command line with:

```sh
cargo run
```

<br />

## SDK methods

The Rust SDK comes with a number of built-in functions.

<table>
    <thead>
        <tr>
            <th scope="col">Function</th>
            <th scope="col">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td scope="row" data-label="Function"><a href="#init"><code>Surreal::init()</code></a></td>
            <td scope="row" data-label="Description">Initialises a static database engine</td>
        </tr>
        <tr>
            <td scope="row" data-label="Function"><a href="#connect"><code>db.connect(endpoint)</code></a></td>
            <td scope="row" data-label="Description">Connects to a specific database endpoint, saving the connection on the static client</td>
        </tr>
        <tr>
            <td scope="row" data-label="Function"><a href="#new"><code>{"Surreal::new::<T>(endpoint)"}</code></a></td>
            <td scope="row" data-label="Description">Connects to a local or remote database endpoint</td>
        </tr>
        <tr>
            <td scope="row" data-label="Function"><a href="#use-ns-db"><code>db.use_ns(namespace).use_db(database)</code></a></td>
            <td scope="row" data-label="Description">Switch to a specific namespace and database</td>
        </tr>
        <tr>
            <td scope="row" data-label="Function"><a href="#signup"><code>db.signup(credentials)</code></a></td>
            <td scope="row" data-label="Description">Signs up a user using a specific record access method</td>
        </tr>
        <tr>
            <td scope="row" data-label="Function"><a href="#signin"><code>db.signin(credentials)</code></a></td>
            <td scope="row" data-label="Description">Signs this connection in using a specific access method or system user</td>
        </tr>
        <tr>
            <td scope="row" data-label="Function"><a href="#invalidate"><code>db.invalidate()</code></a></td>
            <td scope="row" data-label="Description">Invalidates the authentication for the current connection</td>
        </tr>
        <tr>
            <td scope="row" data-label="Function"><a href="#authenticate"><code>db.authenticate(token)</code></a></td>
            <td scope="row" data-label="Description">Authenticates the current connection with a JSON Web Token</td>
        </tr>
        <tr>
            <td scope="row" data-label="Function"><a href="#set"><code>db.set(key, val)</code></a></td>
            <td scope="row" data-label="Description">Assigns a value as a parameter for this connection</td>
        </tr>
        <tr>
            <td scope="row" data-label="Function"><a href="#query"><code>db.query(sql)</code></a></td>
            <td scope="row" data-label="Description">Runs a set of SurrealQL statements against the database</td>
        </tr>
        <tr>
            <td scope="row" data-label="Function"><a href="#select"><code>db.select(resource)</code></a></td>
            <td scope="row" data-label="Description">Selects all records in a table, or a specific record</td>
        </tr>
        <tr>
            <td scope="row" data-label="Function"><a href="#create"><code>db.create(resource).content(data)</code></a></td>
            <td scope="row" data-label="Description">Creates a record in the database</td>
        </tr>
        <tr>
            <td scope="row" data-label="Function"><a href="#update-content"><code>db.update(resource).content(data)</code></a></td>
            <td scope="row" data-label="Description">Updates all records in a table, or a specific record</td>
        </tr>
        <tr>
            <td scope="row" data-label="Function"><a href="#update-merge"><code>db.update(resource).merge(data)</code></a></td>
            <td scope="row" data-label="Description">Modifies all records in a table, or a specific record</td>
        </tr>
        <tr>
            <td scope="row" data-label="Function"><a href="#update-patch"><code>db.update(resource).patch(data)</code></a></td>
            <td scope="row" data-label="Description">Applies JSON Patch changes to all records in a table, or a specific record</td>
        </tr>
        <tr>
            <td scope="row" data-label="Function"><a href="#delete"><code>db.delete(resource)</code></a></td>
            <td scope="row" data-label="Description">Deletes all records, or a specific record</td>
        </tr>
    </tbody>
</table>

<br />

## `.init()` {#init}

The DB static singleton ensures that a single database instance is available across very large or complicated applications. With the singleton, only one connection to the database is instantiated, and the database connection does not have to be shared across components or controllers.

```rust title="Method Syntax"
Surreal::init()
```

### Example usage
```rust
static DB: LazyLock<Surreal<Client>> = LazyLock::new(Surreal::init);

#[tokio::main]
async fn main() -> surrealdb::Result<()> {
    // Connect to the database
    DB.connect::<Wss>("cloud.surrealdb.com").await?;
    // Select a namespace + database
    DB.use_ns("main").use_db("main").await?;
    // Create or update a specific record
    let tobie: Option<Record> = DB
        .update(("person", "tobie"))
        .content(Person { name: "Tobie" })
        .await?;
    Ok(())
}
```

<br />

## `.connect()` {#connect}

Connects to a local or remote database endpoint.

```rust title="Method Syntax"
db.connect(endpoint)
```

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2">Argument</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Argument">
                <code>endpoint</code>
                <label label="required" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The database endpoint to connect to.
            </td>
        </tr>
    </tbody>
</table>

### Example usage
```rust
// Connect to a local endpoint
DB.connect::<Ws>("127.0.0.1:8000").await?;
// Connect to a remote endpoint
DB.connect::<Wss>("cloud.surrealdb.com").await?;
```

<br />

## `.new()` {#new}

Connects to a local or remote database endpoint.

```rust title="Method Syntax"
Surreal::new::<T>(endpoint)
```

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2">Arguments</th>
            <th colspan="2">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>endpoint</code>
                <label label="required" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The database endpoint to connect to.
            </td>
        </tr>
    </tbody>
</table>

### Example usage
```rust
let db = Surreal::new::<Ws>("127.0.0.1:8000").await?;
```

<br />

## `.use_ns()` and `.use_db()` {#use-ns-db}

Switch to a specific namespace and database.

```rust title="Method Syntax"
db.use_ns(ns).use_db(db)
```

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2">Arguments</th>
            <th colspan="2">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>ns</code>
                <label label="required" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                Switches to a specific namespace.
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>db</code>
                <label label="required" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                Switches to a specific database.
            </td>
        </tr>
    </tbody>
</table>

### Example usage
```rust
db.use_ns("main").use_db("main").await?;
```

<br />

## `.signup()` {#signup}

Signs up using a specific record access method.

```rust title="Method Syntax"
db.signup(credentials)
```

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2">Arguments</th>
            <th colspan="2">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>credentials</code>
                <label label="required" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                Variables used in a signup query.
            </td>
        </tr>
    </tbody>
</table>

### Example usage
```rust
use serde::Serialize;
use surrealdb::opt::auth::Scope;

#[derive(Serialize)]
struct Credentials<'a> {
    email: &'a str,
    pass: &'a str,
}

let jwt = db.signup(Scope {
    namespace: "main",
    database: "main",
    access: "user",
    params: Credentials {
        email: "info@surrealdb.com",
        pass: "123456",
    },
}).await?;

// ⚠️: It is important to note that the token should be handled securely and protected from unauthorized access.
let token = jwt.as_insecure_token();
```

<br />

## `.signin()` {#signin}

Signs in using a specific access method or system user.

```rust title="Method Syntax"
db.signin(credentials)
```

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2">Arguments</th>
            <th colspan="2">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>credentials</code>
                <label label="required" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                Variables used in a signin query.
            </td>
        </tr>
    </tbody>
</table>

### Example usage
```rust
use serde::Serialize;
use surrealdb::opt::auth::Scope;

#[derive(Serialize)]
struct Credentials<'a> {
    email: &'a str,
    pass: &'a str,
}

let jwt = db.signin(Scope {
    namespace: "main",
    database: "main",
    access: "user",
    params: Credentials {
        email: "info@surrealdb.com",
        pass: "123456",
    },
}).await?;

// ⚠️: It is important to note that the token should be handled securely and protected from unauthorized access.
let token = jwt.as_insecure_token();
```

<br />

## `.invalidate()` {#invalidate}

Invalidates the authentication for the current connection.

```rust title="Method Syntax"
db.invalidate(credentials)
```

### Example usage
```surql
db.invalidate().await?;
```

<br />

## `.authenticate()` {#authenticate}

Authenticates the current connection with a JWT token.

```rust title="Method Syntax"
db.authenticate(token)
```

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2">Arguments</th>
            <th colspan="2">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>token</code>
                <label label="required" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The JWT authentication token.
            </td>
        </tr>
    </tbody>
</table>

### Example usage
```rust
db.authenticate(jwt).await?;
```

<br />

## `.set()` {#set}

Assigns a value as a parameter for this connection.

```rust title="Method Syntax"
db.set(key, val)
```

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2">Arguments</th>
            <th colspan="2">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>key</code>
                <label label="required" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                Specifies the name of the variable.
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>val</code>
                <label label="required" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                Assigns the value to the variable name.
            </td>
        </tr>
    </tbody>
</table>

### Example usage
```rust
// Assign the variable on the connection
db.set("name", Name {
    first: "Tobie",
    last: "Morgan Hitchcock",
}).await?;
// Use the variable in a subsequent query
db.query("CREATE person SET name = $name").await?;
// Use the variable in a subsequent query
db.query("SELECT * FROM person WHERE name.first = $name.first").await?;
```

<br />

## `.query()` {#query}

Runs a set of SurrealQL statements against the database.

```rust title="Method Syntax"
db.query(sql).bind(vars)
```

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2">Arguments</th>
            <th colspan="2">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>sql</code>
                <label label="required" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                Specifies the SurrealQL statements.
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>vars</code>
               <label label="optional" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                Assigns variables which can be used in the query.
            </td>
        </tr>
    </tbody>
</table>

### Example usage
```rust
// Run some queries
let sql = "
    CREATE person;
    SELECT * FROM type::table($table);
";
let mut result = db
    .query(sql)
    .bind(("table", "person"))
    .await?;
// Get the first result from the first query
let created: Option<Person> = result.take(0)?;
// Get all of the results from the second query
let people: Vec<Person> = result.take(1)?;
```

<br />

## `.select()` {#select}

Selects all records in a table, or a specific record, from the database.

```rust title="Method Syntax"
db.select(resource)
```

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2">Arguments</th>
            <th colspan="2">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>resource</code>
                <label label="required" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The table name or a record ID to select.
            </td>
        </tr>
    </tbody>
</table>

### Example usage
```rust
// Select all records from a table
let people: Vec<Person> = db.select("person").await?;
// Select a specific record from a table
let person: Option<Person> = db.select(("person", "h5wxrf2ewk8xjxosxtyc")).await?;
```

### Translated query
This function will run the following query in the database:

```surql
SELECT * FROM $resource;
```

<br />

## `.create()` {#create}

Creates a record in the database.

```rust title="Method Syntax"
db.create(resource).content(data)
```

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2">Arguments</th>
            <th colspan="2">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>resource</code>
                <label label="required" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The table name or the specific record ID to create.
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>data</code>
               <label label="optional" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The document / record data to insert.
            </td>
        </tr>
    </tbody>
</table>

### Example usage
```rust
// Create a record with a random ID
let person: Option<Person> = db.create("person").await?;
// Create a record with a specific ID
let record: Record = db
    .create(("person", "tobie"))
    .content(Person {
        name: "Tobie",
        settings: {
            active: true,
            marketing: true,
       },
    }).await?;
```

### Translated query
This function will run the following query in the database:

```surql
CREATE $resource CONTENT $data;
```

<br />

## `.update().content()` {#update-content}

Updates all records in a table, or a specific record, in the database.

```rust title="Method Syntax"
db.update(resource).content(data)
```

> [!NOTE]
> This function replaces the current document / record data with the specified data.

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2">Arguments</th>
            <th colspan="2">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>resource</code>
                <label label="required" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The table name or the specific record ID to create.
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>data</code>
               <label label="optional" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The document / record data to insert.
            </td>
        </tr>
    </tbody>
</table>

### Example usage
```rust
// Update all records in a table
let people: Vec<Person> = db.update("person").await?;
// Update a record with a specific ID
let person: Option<Person> = db
    .update(("person", "tobie"))
    .content(Person {
        name: "Tobie",
        settings: {
            active: true,
            marketing: true,
        },
    }).await?;
```

### Translated query
This function will run the following query in the database:

```surql
UPDATE $resource CONTENT $data;
```

<br />

## `.update().merge()` {#update-merge}

Modifies all records in a table, or a specific record, in the database.

```rust title="Method Syntax"
db.update(resource).merge(data)
```

> [!NOTE]
> This function merges the current document / record data with the specified data.

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2">Arguments</th>
            <th colspan="2">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>resource</code>
                <label label="required" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The table name or the specific record ID to create.
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>data</code>
               <label label="optional" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The document / record data to insert.
            </td>
        </tr>
    </tbody>
</table>

### Example usage
```rust
// Update all records in a table
let people: Vec<Person> = db.update("person")
    .merge(Document {
        updated_at: Datetime::default(),
    })
    .await?;
// Update a record with a specific ID
let person: Option<Person> = db.update(("person", "tobie"))
    .merge(Document {
        updated_at: Datetime::default(),
        settings: Settings {
            active: true,
        },
    })
    .await?;
```

### Translated query
This function will run the following query in the database:

```surql
UPDATE $resource MERGE $data;
```

<br />

## `.update().patch()` {#update-patch}

Applies JSON Patch changes to all records, or a specific record, in the database.

```rust title="Method Syntax"
db.update(resource).patch(data)
```

> [!NOTE]
> This function patches the current document / record data with the specified JSON Patch data.

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2">Arguments</th>
            <th colspan="2">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>resource</code>
                <label label="required" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The table name or the specific record ID to modify.
            </td>
        </tr>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>data</code>
               <label label="optional" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The JSON Patch data with which to modify the records.
            </td>
        </tr>
    </tbody>
</table>

### Example usage
```rust
// Update all records in a table
let people: Vec<Person> = db.update("person")
    .patch(PatchOp::replace("/created_at", Datetime::default()))
    .await?;

// Update a record with a specific ID
let person: Option<Person> = db.update(("person", "tobie"))
    .patch(PatchOp::replace("/settings/active", false))
    .patch(PatchOp::add("/tags", &["developer", "engineer"]))
    .patch(PatchOp::remove("/temp"))
    .await?;
```

### Translated query
This function will run the following query in the database:

```surql
UPDATE $resource PATCH $data;
```

<br />

## `.delete()` {#delete}

Deletes all records in a table, or a specific record, from the database.

```rust title="Method Syntax"
db.delete(resource)
```

### Arguments
<table>
    <thead>
        <tr>
            <th colspan="2">Arguments</th>
            <th colspan="2">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td colspan="2" scope="row" data-label="Arguments">
                <code>resource</code>
                <label label="required" />
            </td>
            <td colspan="2" scope="row" data-label="Description">
                The table name or a record ID to select.
            </td>
        </tr>
    </tbody>
</table>

### Example usage
```rust
// Delete all records from a table
let people: Vec<Person> = db.delete("person").await?;
// Delete a specific record from a table
let person: Option<Person> = db.delete(("person", "h5wxrf2ewk8xjxosxtyc")).await?;
```

### Translated query
This function will run the following query in the database:

```surql
DELETE FROM $resource RETURN BEFORE;
```
