• Start

Methods

delete

The .delete() method for the SurrealDB Rust SDK deletes all or specific records from the database.

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

Method Syntax
db.delete(resource)

Argument

Description

resource

The table name or a record ID to select. Will also accept a tuple of record name and ID.

use surrealdb::engine::any::connect;
use surrealdb::opt::auth::Root;
use surrealdb::opt::Resource;
use surrealdb::types::{RecordId, SurrealValue};

#[derive(Debug, SurrealValue)]
struct Person {
    id: RecordId,
}

#[tokio::main]
async fn main() -> surrealdb::Result<()> {
    let db = connect("ws://localhost:8000").await?;
    db.signin(Root {
        username: "root".to_string(),
        password: "secret".to_string(),
    })
    .await?;
    db.use_ns("ns").use_db("db").await?;

    // Create three `person` records
    db.create(Resource::from(("person", "one"))).await?;
    db.create(Resource::from(("person", "two"))).await?;
    db.create(Resource::from(("person", "three"))).await?;

        let deleted_one: Option<Person> = db.delete(("person",
        "one")).await?;
    dbg!(deleted_one);
    let deleted_rest: Vec<Person> = db.delete("person").await?;
    dbg!(deleted_rest);
    Ok(())
}

For deletes targeting every record in a table, chain .range(...) so only record IDs inside the RecordIdKeyRange are removed.

use surrealdb::{
    engine::any::connect,
    opt::Resource,
    types::{ToSql, Value},
};

#[tokio::main]
async fn main() {
    let db = connect("memory").await.unwrap();
    db.use_ns("ns").use_db("db").await.unwrap();

    db.query("CREATE person:alucard, person:plato, person:vlad")
        .await
        .unwrap();

    let res = db
        .delete::<Value>(Resource::from("person"))
        .range("n"..="z")
        .await
        .unwrap()
        .to_sql();
    println!("{res:?}");
}

While SurrealQL's DELETE statement returns an empty array by default, this function translates into a query that adds a RETURN BEFORE clause to return the deleted items.

DELETE FROM $resource RETURN BEFORE;

Was this page helpful?