# Quickstart

> Embedded agdb quickstart: set up Rust app, create a DB, and run native object queries

The following is the quickstart guide for the agdb embedded/application database.

[Looking for server client guide instead?](/api-docs/rust)

<steps>

### Install Rust toolchain

From the [official source](https://www.rust-lang.org/tools/install).

### Create an application

First we initialize an application called `agdb_app` with cargo:

```bash
mkdir agdb_app
cd agdb_app
cargo init
```

### Add dependencies

```bash
cargo add agdb
```

### Create the database

In `main.rs` we create a memory mapped database:

```rsfilename="main.rs"
use agdb::{Db, DbError};

fn main() -> Result<(), DbError> {
    let db = Db::new("agdb_app.agdb")?;
    Ok(())
}
```

<note>

The namesake file "agdb_app.agdb" will be created in your working directory.
The .agdb extension is conventional.

</note>

### Run queries

We run our first query against the database inserting a node with alias "users":

```rs
use agdb::QueryBuilder;

db.exec_mut(QueryBuilder::insert()
                .nodes()
                .aliases("users")
                .query())?;
```

We then insert additional nodes representing some users and connect them with the "users" node:

```rs
use agdb::{DbId, DbType};

// We derive from agdb::DbType
// so we can use the type in the db.
#[derive(Debug, DbType)]
struct User {
    db_id: Option<DbId>, // The db_id member is optional but
                         // it allows inserting your user type
                         // directly into the database.
    username: String,
    age: u64,
}

let users = vec![User { db_id: None, username: "Alice".to_string(), age: 40 },
                 User { db_id: None, username: "Bob".to_string(), age: 30 },
                 User { db_id: None, username: "John".to_string(), age: 20 }];

let db_users = db.exec_mut(QueryBuilder::insert()
                                .nodes()
                                .values(&users) // We can pass users directly as
                                                // query parameter thanks to the
                                                // implementation of the agdb::DbType
                                                // trait via #[derive(DbType)].
                                .query())?;

db.exec_mut(
    QueryBuilder::insert()
        .edges()
        .from("users")
        .to(&db_users) // We can feed result of a previous
                       // query directly to the next one.
        .query(),
)?;
```

<tip>

We could also run all the queries as a single transaction with `transaction()`
/ `transaction_mut()` instead of exec variants that operate on a single query
each time.

</tip>

### Find a user in the database matching some conditions

```rs
// We combine search & select into a single query like so:
let users: Vec<User> = db
    .exec(
        QueryBuilder::select()
            .elements::<User>() // Select only relevant properties for the User struct.
            .search()
            .from("users") // Start the search from the "users" node.
            .where_()
            .key("age") // Examine "age" property.
            .less_than(40) // Include it in the search result if the value is less than 40.
            .query(),
    )?
    .try_into()?; // Convert the result into a list of User objects.

println!("{:?}", users);
// We can print the users thanks to #[derive(Debug)]. The result should be something like:
// [User { db_id: Some(DbId(4)), username: "John", age: 20 }, User { db_id: Some(DbId(3)), username: "Bob", age: 30 }]
```

### Run the program

```bash
cargo run
```

### Full program

```rsfilename="main.rs"
use agdb::{Db, DbError, DbId, DbType, QueryBuilder};

#[derive(Debug, DbType)]
struct User {
    db_id: Option<DbId>,
    username: String,
    age: u64,
}

fn main() -> Result<(), DbError> {
    let db = Db::new("agdb_app.agdb")?;

    db.exec_mut(QueryBuilder::insert().nodes().aliases("users").query())?;

    let users = vec![
        User { db_id: None, username: "Alice".to_string(), age: 40 },
        User { db_id: None, username: "Bob".to_string(), age: 30 },
        User { db_id: None, username: "John".to_string(), age: 20 },
    ];

    let db_users = db.exec_mut(QueryBuilder::insert().nodes().values(&users).query())?;

    db.exec_mut(
        QueryBuilder::insert()
            .edges()
            .from("users")
            .to(&db_users)
            .query(),
    )?;

    let users: Vec<User> = db
        .exec(
            QueryBuilder::select()
                .elements::<User>()
                .search()
                .from("users")
                .where_()
                .key("age")
                .less_than(40)
                .query(),
        )?
        .try_into()?;

    println!("{users:?}");

    Ok(())
}
```

The database is persisted in `agdb_app.agdb`, so running the program again inserts the users again. Delete the file to start fresh or use `DbMemory` for experiments.

For more complete programs see the [examples](/docs/examples).

</steps>
