Server client - Rust
What it shows
The example uses the async Rust client agdb_api to log in to an agdb_server as the admin, create a user, log in as that user, create a database and run two batches of queries: the first inserts a users root and user nodes, the second links them and searches for one user.
Run it
The example needs a running server on localhost:3000 with the default admin user. In one terminal start the server:
cargo run -p agdb_server
and in another one run the example:
cargo run -p agdb_api --example server_client
The example creates the user client, so a second run against the same server fails because the user already exists. Run it against a fresh server (delete its data_dir, agdb_server_data by default) or change the user name.
Users and databases
use agdb::DbType;
use agdb::QueryBuilder;
use agdb_api::DbKind as ApiDbType;
use agdb_api::ReqwestClient;
let mut client = agdb_api::AgdbApi::new(ReqwestClient::new(), "localhost:3000");
// Log in as admin and create a new user.
client.user_login("admin", "admin").await?;
client.admin_user_add("client", "password111").await?;
// Switch to the new user and create a database.
client.user_login("client", "password111").await?;
client.db_add("client", "db", ApiDbType::Memory).await?;
Running queries
Queries are built with the same QueryBuilder as in the embedded database and sent in batches. The user data is a plain struct deriving DbType:
#[derive(Debug, DbType)]
struct User {
username: String,
password: String,
}
A batch runs as a single transaction and returns one result per query, so the second batch can use the ids returned by the first one:
let users = vec![
User {
username: "user1".to_string(),
password: "password123".to_string(),
},
User {
username: "user2".to_string(),
password: "password456".to_string(),
},
];
// Insert a root "users" alias and the user nodes.
let queries = vec![
QueryBuilder::insert()
.nodes()
.aliases(["users"])
.query()
.into(),
QueryBuilder::insert().nodes().values(&users).query().into(),
];
let results = client.db_exec_mut("client", "db", &queries).await?.1;
// Link users to root and search for one by username.
let queries = vec![
QueryBuilder::insert()
.edges()
.from("users")
.to(results[1].ids())
.query()
.into(),
QueryBuilder::select()
.search()
.depth_first()
.from("users")
.where_()
.key("username")
.value("user1")
.query()
.into(),
];
let results = client.db_exec_mut("client", "db", &queries).await?.1;
println!("User: {:?}", results[1].elements[0].id);
for key_value in results[1].elements[0].values.iter() {
println!(" {}: {}", key_value.key, key_value.value);
}
Learn more
- Rust client - installing and using
agdb_api. - Server reference - configuration, users, databases and the REST API.
- How to run a server?