# Concepts ## Graph *Related:* [Why graph?](https://agdb.agnesoft.com/blog/why-graph) Graph is a set of nodes (also vertices, points) that are connected to each other through edges (also arcs, links). In `agdb` the data is plotted on directed graphs and there are no restrictions on their structure. They can be cyclic (forming a cycle), acyclic (being open-ended), sparse (having only some connections between nodes), disjointed (thus forming multiple graphs), having self-referential edges (nodes being connected to themselves), having multiple edges to the same node (even itself) and/or in the same direction. Nodes and edges are `graph elements` and each can have key-value pairs associated with them usually referred to as `values`. Each graph element has a signed integer `id` (`db id`) - nodes having positive values while edges negative values. Note that upon removal of a graph element its `id` is freed and can be reused by subsequent inserts of new graph elements. **Terminology:** - Graph (set of nodes and edges) - Node (point on a graph) - Edge (connection between two nodes) - Graph elements (nodes & edges) - `db id` (graph element `id`, positive for nodes, negative for edges) - Values (key-value pairs associated with a node or an edge) ## Query *Related:* [Why object queries?](https://agdb.agnesoft.com/blog/object-queries), [Queries](https://agdb.agnesoft.com/docs/references/queries) Query is a request to retrieve or manipulate data in a database (both the graph structure and `values` associated with the nodes and edges). In `agdb` queries are not texts (like in SQL) but rather objects that contain details about what is being requested. These objects are typically constructed via a query builder, but it is also possible to create them like any other object. The builder steps resemble, and often indeed are, direct translations of a well known SQL equivalents (e.g. `QueryBuilder::select() == SELECT`, `QueryBuilder::insert() == INSERT INTO`). Queries are executed by the database directly. The `agdb` distinguishes between `immutable` (retrieving data) and `mutable` (manipulating data) queries. Each query execution produces either a result or an error. In `agdb` there is a single `result` object containing a numerical result (i.e. number of affected elements or values) and a list of database elements. Each element in a result consists of a database `id` and a list of `values` (associated key-value pairs). In case of a failure the database execution yields an error detailing what went wrong instead of a result. See dedicated [queries](https://agdb.agnesoft.com/docs/references/queries) documentation for details. **Terminology:** - Query (request to retrieve or manipulate data) - Immutable query (request to retrieve data) - Mutable query (request to manipulate data) - Result (result of a query) ## Transaction *Related*: [Queries](https://agdb.agnesoft.com/docs/references/queries) Transactions are a way to provide atomicity, isolation and data consistency in a database (three of [ACID](https://en.wikipedia.org/wiki/ACID){rel=""nofollow""} properties). In `agdb` every query is a transaction, but it is also possible to execute multiple queries as a single transaction. Just like `queries` transactions are immutable or mutable. The database methods take `&self`, so in multithreaded environment you share the database simply as `Arc` without any extra lock. Mutable transactions are serialized internally while immutable transactions run concurrently against the last committed snapshot and never block the writer. A mutable transaction is committed when its closure returns `Ok` and rolled back when the closure returns an error or any of its mutable queries fails. Furthermore, unlike traditional transactions implemented in other database systems the `agdb` transactions are immediately executed requiring a closure containing (minimum) amount of code and queries required for the transaction to be performed. This forces the client to optimize their transactions and reduce the time other writers wait, which is particularly important for mutable transactions as only one of them can run at a time. **Terminology:** - Transaction (set of queries to be executed atomically against a database wrapped in a closure) - Mutable transaction (set of mutable & immutable queries wrapped in a closure) - Immutable transaction (set of immutable queries wrapped in a closure) ## Storage *Related*: [Why single file?](https://agdb.agnesoft.com/blog/single-file) Every persistent database eventually stores its data somewhere on disk in one or more files. The `agdb` stores its data in a single file (that is being shadowed by another temporary write ahead log file). Its internal structure is very similar to that of a memory which makes it very easy to map between the two. The file format is fully platform-agnostic, and the file can be safely transferred to another machine and loaded there. The `agdb` provides four storage backends exposed as type aliases: | Alias | Storage | Use case | | ---------- | ------------------------- | ----------------------------------------------------------- | | `Db` | `FileStorageMemoryMapped` | Production default — memory-mapped file, fastest reads | | `DbFile` | `FileStorage` | Lower memory footprint, minimum file I/O buffering | | `DbMemory` | `MemoryStorage` | Tests, ephemeral data — no disk I/O | | `DbAny` | `AnyStorage` | Runtime-selectable backend (file, memory-mapped, or memory) | Each alias also has corresponding `*Transaction` and `*TransactionMut` variants for use inside explicit transaction closures. The `DbAny` variant lets you choose the backend at runtime: ```rs use agdb::DbAny; let db = DbAny::new_mapped("my.agdb")?; // memory-mapped (same as Db::new) let db = DbAny::new_file("my.agdb")?; // file-only (same as DbFile::new) let db = DbAny::new_memory("my.agdb")?; // in-memory (same as DbMemory::new) ``` The database durability is provided by the write-ahead-log (WAL) file which records reverse of every operation to be performed on the main file before it actually happens. In case of any catastrophic failure the main database file is repaired from the WAL on loading the database. The changes of a transaction are held in memory and written to the file at its commit: first the WAL, then the main file, then the WAL is cleared. A transaction whose changes grow past the overlay limit (64 MiB by default) writes them to the main file before the commit, keeping the WAL until the commit, so the memory a transaction takes stays bounded. Lower the limit on systems where memory is scarce. By default the database relies on the operating system to flush dirty pages to disk in the background (`SyncMode::None`). This is fast and sufficient for local filesystems. On network filesystems with client-side write caching (e.g. WekaFS with `writecache`) the OS may reorder or delay flushes, which can corrupt the WAL protocol. For these environments set `SyncMode::Commit`, which issues `fdatasync` on the WAL before the main file is written and on the main file before the WAL is cleared, ensuring the correct ordering of writes. The clearing of the WAL itself is not synced, so a crash right after a commit may roll that transaction back but always leaves a consistent database. `SyncMode::Strict` also syncs the clearing so that a committed transaction survives a crash, at the cost of one more sync per commit: ```rs use agdb::{Db, StorageConfig, SyncMode}; let db = Db::new("my.agdb")?; db.set_storage_config(StorageConfig { sync_mode: SyncMode::Commit, overlay_limit: 16 * 1024 * 1024, ..Default::default() }); ``` The syncs add latency per transaction, but their number does not grow with the size of the transaction. `StorageConfig` also has the `memory_limit` (`Option`, `None` or `0` for unlimited) bounding the memory a database may use: the memory and memory mapped databases fail the transactions that would grow them past it while the file database caches its reads in that much memory. Just like the memory the main database file will get fragmented over time. Sectors of the file used for the data that was later reallocated will remain unused (fragmented) until the database file is defragmented with `db.optimize_storage()`. It rebuilds the database into a new compact file (`{name}.rebuild`) and replaces the original with it once it is durable, so it needs the free disk space for the copy. The storage taken by individual elements and properties is generally as follows: - node: 32 bytes - edge: 32 bytes (ids are 32-bit) - key-value pair: 20 bytes (4 bytes key id + 16 bytes value) - label (key without a value): 4 bytes - value longer than 15 bytes: 16 bytes in the pair + the value itself stored separately - values of an element (unless it is a single label, which is stored inline): one allocation with an 8 byte header, whose capacity can exceed the space used The size of the graph elements (nodes & edges) is fixed. The keys are stored once and referenced by a 4 byte id so a key-value pair takes 20 bytes plus the value if it does not fit inline. This creates some inefficiency for small values (e.g. integers) but it also allows application of small value optimization where values up to 15 bytes in size (e.g. strings) do not allocate or take extra space. When a value is larger than 15 bytes it will be stored separately making it `20 + value length` bytes at least. The reason for values taking 16 bytes at minimum instead of 8 is that the value needs to store a type information for which 1 byte is required. 9 bytes is an awkward and very inefficient (as measured where 16 byte values were much faster) size even if it could save some file space. The next alignment is therefore 16 bytes which also allows the aforementioned small value optimization. **Terminology:** - File storage (underlying single data file) - Write ahead log (WAL, shadowing file storage to provide durability) - Sync mode (`None` = rely on OS flushing, `Commit` = explicit fsync per transaction, `Strict` = `Commit` plus fsync of the cleared WAL) - Overlay limit (bytes of a transaction held in memory before they are written ahead of its commit) ## Data types Supported types of both keys and values are: - `i64` - `u64` - `f64` - `String` - `Vec` - `Vec` - `Vec` - `Vec` - `Vec` - `Vec` (heterogeneous list) A value can also be `DbValue::None` (no value), which is the value of a key that is used as a label. It is an enum of limited number of supported types that are universal across all platforms and programming languages. They are serialized in file as follows: | Type | Layout | Size | | ------------- | ------------------------------------------------------------------------------- | -------- | | `i64` | little endian | 8 bytes | | `u64` | little endian | 8 bytes | | `f64` | little endian | 8 bytes | | `String` | size as `u64` little endian followed by UTF-8 encoded string as `u8` bytes | 8+ bytes | | `Vec` | size as `u64` little endian followed by individual `u8` bytes | 8+ bytes | | `Vec` | size as `u64` little endian followed by individual `i64` little endian elements | 8+ bytes | | `Vec` | size as `u64` little endian followed by individual `u64` little endian elements | 8+ bytes | | `Vec` | size as `u64` little endian followed by individual `f64` elements | 8+ bytes | | `Vec` | size as `u64` little endian followed by individual `String` elements | 8+ bytes | ## Cargo features The `agdb` crate has the following optional features: - `derive` (default): derive macros (`DbType`, `DbElement`, `DbValue`, ...) - `regex`: enables the `Regex` comparison in search conditions - `serde`: `serde` serialization of queries and results - `openapi`: `utoipa` OpenAPI schemas of the query types Enable them when adding the crate, e.g. `cargo add agdb --features regex`. # Quickstart The following is the quickstart guide for the agdb embedded/application database. [Looking for server client guide instead?](https://agdb.agnesoft.com/api-docs/rust) ::steps ### Install Rust toolchain From the [official source](https://www.rust-lang.org/tools/install){rel=""nofollow""}. ### 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: ```rs filename="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. ::: ### 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, // 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. ::: ### Find a user in the database matching some conditions ```rs // We combine search & select into a single query like so: let users: Vec = db .exec( QueryBuilder::select() .elements::() // 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 ```rs filename="main.rs" use agdb::{Db, DbError, DbId, DbType, QueryBuilder}; #[derive(Debug, DbType)] struct User { db_id: Option, 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 = db .exec( QueryBuilder::select() .elements::() .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](https://agdb.agnesoft.com/docs/examples). :: # Running the server The `agdb_server` can be run in multiple ways. The following table directs you to the correct documentation based on your use case. It differentiates between running the server as a single server or as a cluster of multiple replicated nodes (using Raft consensus protocol). The documentation is provided for running the server on bare metal, using docker or Kubernetes (K8s). Please refer to the [server](https://agdb.agnesoft.com/docs/references/server) documentation for general information. | Type / Target | Bare Metal | Docker | K8s | | ------------- | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | --------------------------------------------------------------------------- | | Server | [LINK](https://agdb.agnesoft.com/docs/guides/how-to-run-server/server-bare-metal) | [LINK](https://agdb.agnesoft.com/docs/guides/how-to-run-server/server-docker) | [LINK](https://agdb.agnesoft.com/docs/guides/how-to-run-server/server-k8s) | | Cluster | [LINK](https://agdb.agnesoft.com/docs/guides/how-to-run-server/cluster-bare-metal) | [LINK](https://agdb.agnesoft.com/docs/guides/how-to-run-server/cluster-docker) | [LINK](https://agdb.agnesoft.com/docs/guides/how-to-run-server/cluster-k8s) | # Bare metal The `agdb_server` can be run on bare metal by building the binary and running it on the target machine: ::steps ### Install prerequisites - Git: [official source](https://git-scm.com/){rel=""nofollow""} (skip if you already have it) - Rust: [official source](https://www.rust-lang.org/tools/install){rel=""nofollow""} - [OPTIONAL, REQUIRED FOR STUDIO] Node.js: [official source](https://nodejs.org/en/download/){rel=""nofollow""} and `pnpm` (`npm i -g pnpm`) - [OPTIONAL, UNIX ONLY, REQUIRED FOR TLS] CMake: [official source](https://cmake.org/download/){rel=""nofollow""} - [OPTIONAL, WINDOWS ONLY, REQUIRED FOR TLS] Microsoft Build Tools (includes CMake): [official source](https://learn.microsoft.com/en-us/cpp/build/building-on-the-command-line){rel=""nofollow""} ### Install `agdb_server` ```shell cargo install agdb_server --features "tls studio" # The `tls` feature is optional and can be omitted if TLS support is not needed. Requires CMake and on Windows also MSVC. # The `studio` feature is optional and can be omitted if you do not need or want server GUI. Requires `pnpm`. ``` :::note The studio sources are not part of the published crate, so `cargo install` cannot build the studio. To get the studio, build the server manually from the repository as described below, or use the [Docker image](https://agdb.agnesoft.com/docs/guides/how-to-run-server/server-docker). ::: You can also build the server manually. One advantage is that you can use a custom `pepper` value and bake it into the binary instead of using runtime configured value. The `pepper` file is located in sources as `agdb_server/pepper` and contains a random 16 byte value that is used internally to additionally "season" the encrypted passwords. When building for production you should change this value to a different one and keep the pepper file as secret in case you needed to rebuild the server or build a new version. It can also be changed via configuration during runtime. The steps for a manual build (use `bash` on Unix or `git bash` on Windows): ```bash git clone https://github.com/agnesoft/agdb.git cd agdb/ git checkout $(git describe --tags) # checkout the latest released version printf '%s' "1234567891234567" > agdb_server/pepper # exactly 16 bytes, no trailing newline; use a different value, it is a secret cargo build --release -p agdb_server --features "tls studio" # The `tls` feature is optional and can be omitted if TLS support is not needed. Requires CMake and on Windows also MSVC. # The `studio` feature is optional and can be omitted if you do not need or want server GUI. Requires `pnpm`. mv target/release/agdb_server "" # Windows: target/release/agdb_server.exe ``` :::warning Server with a different pepper value (e.g. default non-prod version) won't be able to decode passwords in the internal database. If you lose the pepper value of your server and need to rebuild it you should generate a new pepper and then you will need to create a new admin account (by changing the config value to a non-existent user) and using that account you can reset passwords of all your users via `/api/v1/admin/user/{username}/change_password` API (including the old admin account). ::: Alternatively you can use the default pepper value but specify in configuration the "pepper_path" from which the pepper would be loaded during runtime. This file and location should be treated as secret. All the caveats of manual build still apply including the recovery steps in case the pepper value is lost. ### Run the server ```bash agdb_server ``` The server upon starting will create few things in its working directory: - `agdb_server.yaml`: Configuration file. You can alter it as you wish or prepare one in advance. You would need to restart the server for the changes to take effect. - `agdb_server_data/`: Folder for storing the user data. It can be changed in the configuration file (requires restart of the server and possibly moving the internal database and data, if any, to the new location). - `agdb_server_data/agdb_server.agdb` (`agdb_server_data/.agdb_server.agdb`): Internal database of the server (uses `agdb` itself) + its write ahead file (the dotfile). and report where it listens at: ```bash 2024-01-26T17:47:30.956260Z INFO agdb_server: Listening at :::3000 ``` :::tip You can prepare the configuration file before starting the server. ::: [Please refer to the server reference for the configuration options.](https://agdb.agnesoft.com/docs/references/server) ### Test that the server is up with `curl` ```bash curl -v localhost:3000/api/v1/status # should return 200 OK ``` ### Create a database user It is recommended (but optional) to create a regular user rather than using the `admin` user (which is however still possible): ```bash # produce an admin API token, e.g. "bb2fc207-90d1-45dd-8110-3247c4753cd5" token=$(curl -X POST -H 'Content-Type: application/json' localhost:3000/api/v1/user/login -d '{"username":"admin","password":"admin"}') # using admin token to create a user curl -X POST -H "Authorization: Bearer ${token}" -H 'Content-Type: application/json' localhost:3000/api/v1/admin/user/my_db_user/add -d '{"password":"password123"}' # login as the new user and producing their token token=$(curl -X POST -H 'Content-Type: application/json' localhost:3000/api/v1/user/login -d '{"username":"my_db_user","password":"password123"}') ``` ### Interact with the database server You can either continue using `curl`, interactive OpenAPI GUI from any browser `localhost:3000/api/v1` (provided by `rapidoc`) or choose one of the [available API clients](https://agdb.agnesoft.com/api-docs/openapi). The raw OpenAPI specification can be downloaded from the server at `localhost:3000/api/v1/openapi.json` as well. If you built the server with the `studio` feature, you can also manage it from a browser at `localhost:3000/studio/`. See [How to use the studio?](https://agdb.agnesoft.com/docs/guides/how-to-use-studio). ### Shutdown the server The server can be shutdown with `CTRL+C` or programmatically posting to the shutdown endpoint as logged in server admin: ```bash # this will produce an admin API token, e.g. "bb2fc207-90d1-45dd-8110-3247c4753cd5" token=$(curl -X POST -H 'Content-Type: application/json' localhost:3000/api/v1/user/login -d '{"username":"admin","password":"admin"}') curl -X POST -H "Authorization: Bearer ${token}" localhost:3000/api/v1/admin/shutdown ``` :: # Docker The `agdb_server` can be run in Docker using official Docker image. Optionally you can [build the image](https://github.com/agnesoft/agdb/blob/main/agdb_server/containerfile){rel=""nofollow""} yourself. ::steps ### Install Docker - Windows: {rel=""nofollow""} - Linux: {rel=""nofollow""} ### Pull or build the agdb_server image The image is based on [Alpine Linux](https://alpinelinux.org/){rel=""nofollow""} using musl libc. The image is made available on Docker Hub or GitHub packages: | Vendor | Tag | Command | Description | | ---------- | ------ | ----------------------------------------- | ----------------------------------------------------------------------------------------- | | Docker Hub | latest | docker pull agnesoft/agdb\:latest | Equals latest released version | | Docker Hub | 0.x.x | docker pull agnesoft/agdb:0.x.x | Released version, e.g. 0.10.0 | | Docker Hub | dev | docker pull agnesoft/agdb\:dev | Equals latest development version on the main branch, refreshed with every commit to main | | GitHub | latest | docker pull ghcr.io/agnesoft/agdb\:latest | Equals latest released version | | GitHub | 0.x.x | docker pull ghcr.io/agnesoft/agdb:0.x.x | Released version, e.g. 0.10.0 | | GitHub | dev | docker pull ghcr.io/agnesoft/agdb\:dev | Equals latest development version on the main branch, refreshed with every commit to main | If you want to build the image yourself run the following in the root of the checked out `agdb` repository: ```bash docker build --pull -t agnesoft/agdb:dev -f agdb_server/containerfile . ``` ### Run the server ```bash docker run -v agdb_data:/agdb/agdb_server_data --name agdb -p 3000:3000 agnesoft/agdb:dev ``` This command runs the server using the default configuration (without TLS). It assigns a volume to the data directory for data persistence, gives the container a name (`agdb`) and publishes the container's exposed port (`3000`) to the host. You can publish to a different local port (e.g. `5000:3000` (host\:container)) where the container's port `3000` will be locally accessible on the port `5000`. ### Test that the server is up with `curl` ```bash curl -v localhost:3000/api/v1/status # should return 200 OK ``` ### Shutdown the server The server can be shutdown either by stopping the container or programmatically posting to the shutdown endpoint as logged in server admin: ```bash # this will produce an admin API token, e.g. "bb2fc207-90d1-45dd-8110-3247c4753cd5" token=$(curl -X POST -H 'Content-Type: application/json' localhost:3000/api/v1/user/login -d '{"username":"admin","password":"admin"}') curl -X POST -H "Authorization: Bearer ${token}" localhost:3000/api/v1/admin/shutdown ``` ### TLS Support In order to enable TLS support you need to provide following config values as per the [server documentation](https://agdb.agnesoft.com/docs/references/server): ```yaml tls_certificate: /agdb/cert.pem tls_key: /agdb/cert.key ``` If you are using self-signed certificate you should provide also the root CA via: ```yaml tls_root: /agdb/root_ca.pem ``` You can then mount the custom config and the certificates into the container as volume(s). Assuming the `agdb_server.yaml` and the certificates are in `/local/path` on your host machine: ```bash docker run -v agdb_data:/agdb/agdb_server_data -v /local/path:/agdb --name agdb -p 3000:3000 agnesoft/agdb:dev ``` When you run the container this way it will load the configuration from `/agdb/agdb_server.yaml` and if it specifies the paths to the files they would be loaded as well. :: # Kubernetes The `agdb_server` can be run in Kubernetes using official Docker image. Optionally you can [build the image](https://github.com/agnesoft/agdb/blob/main/agdb_server/containerfile){rel=""nofollow""} yourself and host it at the repository of your choosing. Please refer to the [server-docker](https://agdb.agnesoft.com/docs/guides/how-to-run-server/server-docker) guide for available images. ::note This guide is for running `agdb_server` as a single instance. This is only recommended when resiliency is not required and/or if speed is of the essence. Consider running [cluster](https://agdb.agnesoft.com/docs/guides/how-to-run-server/cluster-k8s) instead. :: ### Requirements - Kubernetes cluster (you can enable local K8s cluster in Docker Desktop) - kubectl ### Stateful set yaml You can find an example Kubernetes deployment at {rel=""nofollow""} The example breakdown: ::steps ### Service First we deploy a headless K8s service (`clusterIP: None`) that only allows communication inside the cluster. As we are running a database server it would typically serve other backends in the same cluster and not be accessible from the outside. If such access is needed consider using `LoadBalancer` type service or `Ingress` controller with an additional `ClusterIP` service. The port available in the cluster is `3000` under a name of `agdb`. Furthermore, we specify selector value `app: agdb` and also a label of the same value. ```yaml apiVersion: v1 kind: Service metadata: name: agdb labels: app: agdb spec: ports: - port: 3000 name: agdb clusterIP: None selector: app: agdb ``` ### Secrets Next document is the pepper secret `agdb-pepper`. ```yaml apiVersion: v1 kind: Secret metadata: name: agdb-pepper labels: app: agdb stringData: pepper: "1234567891234567" ``` Followed by the certificates. In production, you should create the certificates using kubectl command from secure files rather than embedding them into the manifest. However, for demonstration purposes the following example is provided. It uses self-signed certificate with the corresponding CA. It needs to be provided as `base64` value. You can use e.g. `cat cert.pem | base64` bash command to get the correct value (end of lines do not matter). :::warning The certificate must be issued (or used as an alternative name - SAN) for the DNS name of the server used in its configuration `address` field. E.g. `agdb.default.svc.cluster.local`. ::: ```yaml apiVersion: v1 kind: Secret metadata: name: agdb-certs labels: app: agdb data: cert.pem: ... key.pem: ... root_ca.pem: ... ``` ### ConfigMap The configuration named `agdb-config` via the `ConfigMap` is optional as the default configuration would work just as well. It might however be useful if you needed to change anything regarding the server later. For example disabling TLS if it is not needed etc. ```yaml --- apiVersion: v1 kind: ConfigMap metadata: name: agdb-config labels: app: agdb data: agdb_server.yaml: | bind: :::3000 address: https://agdb.default.svc.cluster.local:3000 basepath: "" static_roots: [] admin: admin log_level: INFO data_dir: /agdb/data pepper_path: /agdb/pepper/pepper tls_certificate: /agdb/certs/cert.pem tls_key: /agdb/certs/key.pem tls_root: /agdb/certs/root_ca.pem cluster_token: cluster cluster_heartbeat_timeout_ms: 1000 cluster_term_timeout_ms: 3000 cluster: [] ``` ### StatefulSet The main part of the deployment is the stateful set definition. While replica set could work to some extent the instances of `agdb_server` are not interchangeable and cannot be freely scaled horizontally. The stateful set type is therefore a better fit. It uses the selector and labels `app: agdb` in order to "link" the service and the underlying pod together. Kubernetes is using selectors rather than direct mapping when linking various things together such as services and pods. We specify 1 replica only (refer to the [agdb as K8s cluster](https://agdb.agnesoft.com/docs/guides/how-to-run-server/cluster-k8s) for an alternative). The container spec matches the port on the service by name `agdb` and exposes the container port `3000` (default). The security context specifies the user `1000` (default uid in the container) and disables root access as it is not needed and enhances security. Finally, we specify volumes and volume mounts to add the `secrets`, `configmap` and persistent volume claim (PVC) to the expected locations. The PVC is a way how data can survive restart or redeployment. By default, 1 GB of storage is specified which can be increased (but not decreased) in subsequent deployments. Certificates are provided for TLS support. ```yaml --- apiVersion: apps/v1 kind: StatefulSet metadata: name: agdb labels: app: agdb spec: serviceName: "agdb" replicas: 1 selector: matchLabels: app: agdb template: metadata: labels: app: agdb spec: containers: - name: agdb image: agnesoft/agdb:dev ports: - containerPort: 3000 name: agdb securityContext: runAsUser: 1000 runAsGroup: 1000 allowPrivilegeEscalation: false volumeMounts: - name: agdb-data mountPath: /agdb/data - name: config mountPath: /agdb - name: pepper mountPath: /agdb/pepper - name: certs mountPath: /agdb/certs volumes: - name: config configMap: name: agdb-config defaultMode: 511 - name: pepper secret: secretName: agdb-pepper - name: certs secret: secretName: agdb-certs volumeClaimTemplates: - metadata: name: agdb-data labels: app: agdb spec: accessModes: ["ReadWriteOnce"] resources: requests: storage: 1Gi ``` ### Test that the server is up with `curl` The following command must be run from within the cluster unless the server was exposed via `LoadBalancer` or `Ingress`. The `.default.` bit is the name of the namespace where everything was deployed. ```bash curl -v https://agdb.default.svc.cluster.local:3000/api/v1/status # should return 200 OK ``` ### Additional considerations - You could use the `localhost:3000/api/v1/status` as a startup/readiness/health probe. - Standard shutdown procedure via the endpoint will not work as K8s will simply restart the server. - Consider running the [cluster](https://agdb.agnesoft.com/docs/guides/how-to-run-server/cluster-k8s) rather than just a single node. - You should be able to adapt the above to other platforms such as AWS EKS. - If you are using `agdb` only inside the K8s cluster with no visibility outside of it you may want to disable TLS. - If you are exposing `agdb` outside the K8s cluster use real production certificate. In that case leave the `tls_root` configuration option empty. :: # Bare metal (cluster) The `agdb_server` can be run as a cluster on bare metal. First you should build the server as described in the [server - bare metal](https://agdb.agnesoft.com/docs/guides/how-to-run-server/server-bare-metal) guide. In the following steps we will run a cluster of 3 nodes on a local machine however it should work essentially the same even when each server was run on its own machine: ::steps ### Prepare cluster configuration First we create the configuration files for our nodes. Notice that the only difference is the port in the address option. As described in the main [server](https://agdb.agnesoft.com/docs/references/server) documentation the address field determines the index of the local node (position in the cluster list). The list of nodes is then the same and having the same order for each instance as it provides the cluster "hash" for establishing trust in the cluster (in addition to the `cluster_token`): ```yaml #node0: ~/agdb_cluster/node0/agdb_server.yaml bind: :::3000 address: http://localhost:3000 basepath: "" static_roots: [] admin: admin log_level: INFO data_dir: agdb_server_data pepper_path: "" tls_certificate: "" tls_key: "" tls_root: "" cluster_token: cluster cluster_heartbeat_timeout_ms: 1000 cluster_term_timeout_ms: 3000 cluster: [http://localhost:3000, http://localhost:3001, http://localhost:3002] #node1: ~/agdb_cluster/node1/agdb_server.yaml bind: :::3001 address: http://localhost:3001 basepath: "" static_roots: [] admin: admin log_level: INFO data_dir: agdb_server_data pepper_path: "" tls_certificate: "" tls_key: "" tls_root: "" cluster_token: cluster cluster_heartbeat_timeout_ms: 1000 cluster_term_timeout_ms: 3000 cluster: [http://localhost:3000, http://localhost:3001, http://localhost:3002] #node2: ~/agdb_cluster/node2/agdb_server.yaml bind: :::3002 address: http://localhost:3002 basepath: "" static_roots: [] admin: admin log_level: INFO data_dir: agdb_server_data pepper_path: "" tls_certificate: "" tls_key: "" tls_root: "" cluster_token: cluster cluster_heartbeat_timeout_ms: 1000 cluster_term_timeout_ms: 3000 cluster: [http://localhost:3000, http://localhost:3001, http://localhost:3002] ``` ### Run the server Next we run all 3 nodes as background processes in their respective directories with the prepared config files. It is recommended to run each in its own shell so you can observe the logs otherwise they would be all writing to the same shell if run as background processes (i.e. `agdb_server &`). If you decide to run all of them in the same shell each log messages clearly indicates to which node it belongs using the node's index (e.g. `[0]`, `[1]` etc.) ```bash cd ~/agdb_cluster/node0/ #run each node in its respective directory agdb_server ``` ### Test that the cluster is up with `curl` The following commands will hit each node and return the list of nodes, their status and which one is the leader. If the servers are connected and operating normally the returned list should be the same from each node. ```bash curl -v localhost:3000/api/v1/cluster/status curl -v localhost:3001/api/v1/cluster/status curl -v localhost:3002/api/v1/cluster/status ``` ### Shutdown the servers The cluster must be shutdown one by one using the same mechanism as with single server including the `CTRL+C`. Using curl: ```bash # this will produce an admin API token, e.g. "bb2fc207-90d1-45dd-8110-3247c4753cd5" token=$(curl -X POST -H 'Content-Type: application/json' localhost:3000/api/v1/user/login -d '{"username":"admin","password":"admin"}') curl -X POST -H "Authorization: Bearer ${token}" localhost:3000/api/v1/admin/shutdown token=$(curl -X POST -H 'Content-Type: application/json' localhost:3001/api/v1/user/login -d '{"username":"admin","password":"admin"}') curl -X POST -H "Authorization: Bearer ${token}" localhost:3001/api/v1/admin/shutdown token=$(curl -X POST -H 'Content-Type: application/json' localhost:3002/api/v1/user/login -d '{"username":"admin","password":"admin"}') curl -X POST -H "Authorization: Bearer ${token}" localhost:3002/api/v1/admin/shutdown ``` While it is technically possible to use cluster login and avoid logins to each node separately it might be fragile and not work well in situations where the cluster is in bad shape with nodes not being available etc. Local login and shutdown are guaranteed to work regardless of the overall cluster status. :: # Docker (cluster) The `agdb_server` can be run as a cluster in docker. Optionally you can [build the image](https://github.com/agnesoft/agdb/blob/main/agdb_server/containerfile){rel=""nofollow""} yourself. ::steps ### Install docker - Windows: {rel=""nofollow""} - Linux: {rel=""nofollow""} ### Pull or build the agdb_server image The image is based on [Alpine Linux](https://alpinelinux.org/){rel=""nofollow""} using musl libc. The image is made available on Docker Hub or GitHub packages: | Vendor | Tag | Command | Description | | ---------- | ------ | ----------------------------------------- | ----------------------------------------------------------------------------------------- | | Docker Hub | latest | docker pull agnesoft/agdb\:latest | Equals latest released version | | Docker Hub | 0.x.x | docker pull agnesoft/agdb:0.x.x | Released version, e.g. 0.10.0 | | Docker Hub | dev | docker pull agnesoft/agdb\:dev | Equals latest development version on the main branch, refreshed with every commit to main | | GitHub | latest | docker pull ghcr.io/agnesoft/agdb\:latest | Equals latest released version | | GitHub | 0.x.x | docker pull ghcr.io/agnesoft/agdb:0.x.x | Released version, e.g. 0.10.0 | | GitHub | dev | docker pull ghcr.io/agnesoft/agdb\:dev | Equals latest development version on the main branch, refreshed with every commit to main | If you want to build the image yourself run the following in the root of the checked out `agdb` repository: ```bash docker build --pull -t agnesoft/agdb:dev -f agdb_server/containerfile . ``` ### Run the cluster You will need the `compose.yaml` file from the sources at: {rel=""nofollow""} ```bash # the -f path is where the file resides in the sources, you can change it to the actual location of the compose.yaml file docker compose -f agdb_server/compose.yaml up --wait ``` This command runs the 3 nodes as a docker cluster using docker compose that contains valid cluster configuration. The volumes are provided for each node so that the data is persisted. It exposes the nodes at the ports `3000`, `3001` and `3002`. By default, it is using TLS self-signed certificates. You can either remove the certificates and related configuration from the `compose.yaml` or provide your own certificates. The `curl` examples below use `-k` to accept the self-signed certificate. Refer to the [server configuration](https://agdb.agnesoft.com/docs/references/server) for more details. ### Test that the cluster is up with `curl` The following commands will hit each node and return the list of nodes, their status and which one is the leader. If the servers are connected and operating normally the returned list should be the same from each node. ```bash curl -kv https://localhost:3000/api/v1/cluster/status curl -kv https://localhost:3001/api/v1/cluster/status curl -kv https://localhost:3002/api/v1/cluster/status ``` ### Shutdown the cluster The cluster can be shutdown either by stopping the containers or programmatically posting to the shutdown endpoints as logged in server admin: ```bash # this will produce an admin API token, e.g. "bb2fc207-90d1-45dd-8110-3247c4753cd5" token=$(curl -k -X POST -H 'Content-Type: application/json' https://localhost:3000/api/v1/user/login -d '{"username":"admin","password":"admin"}') curl -k -X POST -H "Authorization: Bearer ${token}" https://localhost:3000/api/v1/admin/shutdown token=$(curl -k -X POST -H 'Content-Type: application/json' https://localhost:3001/api/v1/user/login -d '{"username":"admin","password":"admin"}') curl -k -X POST -H "Authorization: Bearer ${token}" https://localhost:3001/api/v1/admin/shutdown token=$(curl -k -X POST -H 'Content-Type: application/json' https://localhost:3002/api/v1/user/login -d '{"username":"admin","password":"admin"}') curl -k -X POST -H "Authorization: Bearer ${token}" https://localhost:3002/api/v1/admin/shutdown ``` While it is technically possible to use cluster login and avoid logins to each node separately it might be fragile and not work well in situations where the cluster is in bad shape with nodes not being available etc. Local login and shutdown are guaranteed to work regardless of the overall cluster status. :: # Kubernetes (cluster) The `agdb_server` can be run in Kubernetes using official Docker image. Optionally you can [build the image](https://github.com/agnesoft/agdb/blob/main/agdb_server/containerfile){rel=""nofollow""} yourself and host it at the place of your choosing. Please refer to the [server-docker](https://agdb.agnesoft.com/docs/guides/how-to-run-server/server-docker) guide for available images. ### Requirements - Kubernetes cluster (you can enable local K8s cluster in Docker Desktop) - kubectl ### Stateful set yaml You can find an example Kubernetes deployment at {rel=""nofollow""} The example breakdown: ::steps ### Service First we deploy a headless K8s service (`clusterIP: None`) that only allows communication inside the cluster. As we are running a database server it would typically serve other backends in the same cluster and not be accessible from the outside. If such access is needed consider using `LoadBalancer` type service or `Ingress` controller with an additional `ClusterIP` service. The port available in the cluster is `3000` under a name of `agdb`. Furthermore we specify selector value `app: agdb` and also a label of the same value. ```yaml apiVersion: v1 kind: Service metadata: name: agdb labels: app: agdb spec: ports: - port: 3000 name: agdb clusterIP: None selector: app: agdb ``` :::warning When accessing the database cluster through the service name each request will be sent to random node (the sessions are not sticky) that may lead to inconsistent view into the cluster's data. Consider specifying a pod to connect to. Instead of `http://agdb.default.svc.cluster.local:3000` use for example `http://agdb-0.agdb.default.svc.cluster.local:3000`. ::: ### Secrets Next document is the pepper secret `agdb-pepper`. ```yaml apiVersion: v1 kind: Secret metadata: name: agdb-pepper labels: app: agdb stringData: pepper: "1234567891234567" ``` Followed by the certificates. In production, you should create the certificates using kubectl command from secure files rather than embedding them into the manifest. However, for demonstration purposes the following example is provided. It uses self-signed certificate with the corresponding CA. It needs to be provided as `base64` value. You can use e.g. `cat cert.pem | base64` bash command to get the correct value (end of lines do not matter). :::tip The certificate must be issued (or used as an alternative name - SAN) for the DNS names of the servers used in their configuration `address` field. E.g. `agdb-0.agdb.default.svc.cluster.local`, `agdb-1.agdb.default.svc.cluster.local`, `agdb-2.agdb.default.svc.cluster.local`. ::: ```yaml apiVersion: v1 kind: Secret metadata: name: agdb-certs labels: app: agdb data: cert.pem: ... key.pem: ... root_ca.pem: ... ``` ### ConfigMap The configuration named `agdb-config` via the `ConfigMap` is required as we need specific configuration for each node. Additionally, we specify a custom `start.sh` script that dynamically assigns the deployment index as a cluster index on startup. We are using the same certificate in all servers, and it must be valid for all the names it is used for, e.g. `agdb-0.default.svc.cluster.local`, `agdb-1.default.svc.cluster.local`, `agdb-2.default.svc.cluster.local`. ```yaml --- apiVersion: v1 kind: ConfigMap metadata: name: agdb-config labels: app: agdb data: start.sh: | cp /agdb/config/agdb_server.yaml /agdb/agdb_server.yaml sed -i "s/{id}/$AGDB_REPLICA_INDEX/g" /agdb/agdb_server.yaml /usr/local/bin/agdb_server agdb_server.yaml: | bind: :::3000 address: https://agdb-{id}.agdb.default.svc.cluster.local:3000 basepath: "" static_roots: [] admin: admin log_level: INFO data_dir: /agdb/data pepper_path: /agdb/pepper/pepper tls_certificate: /agdb/certs/cert.pem tls_key: /agdb/certs/key.pem tls_root: /agdb/certs/root_ca.pem cluster_token: cluster cluster_heartbeat_timeout_ms: 1000 cluster_term_timeout_ms: 3000 cluster: [https://agdb-0.agdb.default.svc.cluster.local:3000, https://agdb-1.agdb.default.svc.cluster.local:3000, https://agdb-2.agdb.default.svc.cluster.local:3000] ``` ### StatefulSet The main part of the deployment is the stateful set definition. It uses the selector and labels `app: agdb` in order to "link" the service and the underlying pods together. Kubernetes is using selectors rather than direct mapping when linking various things together such as services and pods. We specify 3 replicas as we want to run 3 node cluster. The container spec matches the port on the service by name `agdb` and exposes the container port `3000` (default). The security context specifies the user `1000` (default uid in the container) and disables root access as it is not needed and enhances security. Finally, we specify volumes and volume mounts to add the `secrets`, `configmap` and persistent volume claim (PVC) to the expected locations. The PVC is a way how data can survive restart or redeployment. By default, 1 GB of storage is specified which can be increased (but not decreased) in subsequent deployments. The custom command running the `start.sh` from the configmap and the environment variable `AGDB_REPLICA_INDEX` make sure the correct config is assigned to each node on startup. Certificates are provided for TLS support. ```yaml --- apiVersion: apps/v1 kind: StatefulSet metadata: name: agdb labels: app: agdb spec: serviceName: "agdb" replicas: 3 selector: matchLabels: app: agdb template: metadata: labels: app: agdb spec: containers: - name: agdb image: agnesoft/agdb:dev command: ["sh", "/agdb/config/start.sh"] ports: - containerPort: 3000 name: agdb securityContext: runAsUser: 1000 runAsGroup: 1000 allowPrivilegeEscalation: false env: - name: AGDB_REPLICA_INDEX valueFrom: fieldRef: fieldPath: metadata.labels['apps.kubernetes.io/pod-index'] volumeMounts: - name: agdb-data mountPath: /agdb/data - name: config mountPath: /agdb/config - name: pepper mountPath: /agdb/pepper - name: certs mountPath: /agdb/certs volumes: - name: config configMap: name: agdb-config defaultMode: 511 - name: pepper secret: secretName: agdb-pepper - name: certs secret: secretName: agdb-certs volumeClaimTemplates: - metadata: name: agdb-data labels: app: agdb spec: accessModes: ["ReadWriteOnce"] resources: requests: storage: 1Gi ``` ### Test that the server is up with `curl` The following command must be run from within the cluster unless the server was exposed via `LoadBalancer` or `Ingress`. The `.default.` bit is the name of the namespace where everything was deployed. ```bash curl -v https://agdb-0.agdb.default.svc.cluster.local:3000/api/v1/status # should return 200 OK curl -v https://agdb-1.agdb.default.svc.cluster.local:3000/api/v1/status # should return 200 OK curl -v https://agdb-2.agdb.default.svc.cluster.local:3000/api/v1/status # should return 200 OK ``` ### Additional considerations - You could use the `localhost:3000/api/v1/status` as a startup/readiness/health probe. - Standard shutdown procedure via the endpoint will not work as K8s will simply restart the servers. - You should be able to adapt the above to other platforms such as AWS EKS. - Always connect to a particular node (e.g. `agdb-0`) rather than the service address since the latter will route the request to a random node. - If you are using `agdb` only inside the K8s cluster with no visibility outside of it you may want to disable TLS. - If you are exposing `agdb` outside the K8s cluster use real production certificate. In that case leave the `tls_root` configuration option empty. :: # Using the studio The agdb studio is the web GUI of the [`agdb_server`](https://agdb.agnesoft.com/docs/references/server). In a browser you can: - create, share, back up and manage databases, - build and run queries without writing code, - see the results as a 3D graph, a table, a chart or JSON, and edit the data in place, - collect queries into dashboards that you share with other users, - and, as the server admin, manage users and watch the server and the cluster. ## Open the studio The studio is built into the server binary when the server is built with the `studio` feature. It is not part of the default build. The official [Docker image](https://agdb.agnesoft.com/docs/guides/how-to-run-server/server-docker) includes it. To build it yourself, build the server from a checkout of the [agdb repository](https://github.com/agnesoft/agdb){rel=""nofollow""}, which has the studio sources: ```bash cargo build --release -p agdb_server --features "tls studio" ``` The build needs Node.js and `pnpm`. See [How to run the server?](https://agdb.agnesoft.com/docs/guides/how-to-run-server) for the details. When the server runs, open the `/studio/` path of its address in a browser, e.g. `http://localhost:3000/studio/`. The studio sends its requests to the server's configured `address` and `basepath` (see the [server configuration](https://agdb.agnesoft.com/docs/references/server#configuration)), not to the address in your browser. When you reach the server from another machine or through a reverse proxy, set `address` to the URL the browser uses, for example `address: "https://example.com"` with `basepath: "/agdb"` serves the studio at `https://example.com/agdb/studio/`. In a cluster, `address` also identifies the node to the other nodes, so each node keeps its own reachable address; connect the studio to a node directly or enter the node's URL as **Server URL** when logging in. ::note Every page of the studio has its own address, so you can bookmark it or send it to someone. Opening it when you are not logged in takes you to the login first and then back to the page. :: ## Log in The login page asks for: - **Server URL**: prefilled with the server that serves the studio. A cluster node's address also works. - **Username** and **Password**: the server admin is created when the server first starts (`admin` / `admin` by default, change the password after the first login). The admin creates other users on the [admin pages](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/admin). - **Log in on all nodes in the cluster**: logs you in on every node of a cluster at once, so you can switch between them later. A login lasts for `token_expiry_seconds` of the [server configuration](https://agdb.agnesoft.com/docs/references/server#configuration) (1 hour by default). When it ends, the studio shows **Session ended** and returns you to the page you were on after you log in again. ## Your first graph ::steps ### Add a database On the **Databases** page type a **Name**, choose the **Type** **Mapped** and click **Add**. (A **Memory** database is lost when the server stops, unless it has a backup.) ### Open it Click the database's row. The query page opens. ### Insert some data Select the **exec_mut** tab, click into the empty query row and paste (Ctrl+V) these lines: ```rust QueryBuilder::insert().nodes().aliases(["alice", "bob", "carol"]).query() QueryBuilder::insert().edges().from("alice").to(["bob", "carol"]).query() ``` Each line becomes its own query row. Click **Run mutation** (or press Ctrl+Enter). ### Look at it Select the **exec** tab and add a query by typing the steps `search`, `from` (with the argument `alice`) and `query`, picking each one from the suggestions. Run it. The three nodes and two edges are shown as a graph. Click a node to see and edit its values. ### Keep it Click **Add to dashboard** at the top of the page, choose **+ New dashboard** and give it a name. The query is now a widget on that dashboard under **Dashboards**. :: ## Guides | Page | What it covers | | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | | [Databases](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/databases) | Adding databases, the database actions, sharing databases with other users | | [Queries](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/queries) | The query builder, running queries, copying them as code, query links | | [Results and charts](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/results) | The table, JSON, summary and chart views of query results | | [Graph](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/graph) | The graph view, editing elements, colours and sizes | | [Dashboards](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/dashboards) | Creating, editing and sharing dashboards and their widgets | | [Admin](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/admin) | Server status, users, and all databases and dashboards of the server | | [Account and cluster](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/account-and-cluster) | Sessions, password, theme, notifications and switching between cluster nodes | | [Export and print](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/export-and-print) | CSV, JSON, Rust code, printing and PDF | The addresses of the pages, the keyboard shortcuts and the limits of the studio are listed in the [studio reference](https://agdb.agnesoft.com/docs/references/studio). # Databases The **Databases** page (`/studio/db`) lists every database you own or that is shared with you. ## Add a database The **Add Database** form at the top takes a **Name** and a **Type**: | Type | Meaning | | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | **Memory** | Memory only, basically a cache. The data is lost when the server stops, unless it has a backup: then it starts from the backup. The default. | | **Mapped** | Memory mapped file: reads from memory, changes are written to the disk. | | **File** | File only: reads and writes go to the disk, no memory caching. Uses the least memory. | See [storage](https://agdb.agnesoft.com/docs/guides/concepts#storage) for the details of each type. A new database is always owned by the user who adds it. You can change the type later with **Convert**. The refresh button next to the form reloads the list. ## The database table | Column | Meaning | | ---------- | ----------------------------------------------- | | **Role** | Your role on the database: admin, write or read | | **Owner** | The user who owns the database | | **Name** | The name of the database | | **Type** | memory, file or mapped | | **Size** | Size of the database in bytes | | **Backup** | Date and time of the last backup, or N/A | Click a column header to sort by it: ascending, descending, then back to unsorted. Click a row (or press Enter on it) to open the [query page](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/queries) of that database. The chevron at the end of the row opens the [users of the database](https://agdb.agnesoft.com/#share-a-database). The **Export** menu above the table downloads the rows as **CSV** or **JSON**, or prints them (see [Export and print](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/export-and-print)). ## Database actions The actions menu of a row shows only the actions your role allows. The ones that delete or overwrite data, including **Backup**, are at the bottom, below a line. Most of them ask you to confirm first. | Action | Who can use it | What it does | | ----------------------------------------------------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | **Audit** | any role | Shows the audit log of the database: when, who and which query changed it. | | **Backup** | admin role | Backs up the database. An existing backup is replaced. | | **Clear** → **All**, **Db only**, **Audit only**, **Backup only** | admin role | Empties the database, its audit log, its backup, or all of them. | | **Convert** → **Memory**, **File**, **Mapped** | admin role | Changes the type of the database. | | **Copy** | any role | Copies the database under a new **Name**. The copy is yours. | | **Optimize** | write or admin role | Packs the database file, reclaiming unused space. | | **Rename** | owner | Gives the database a new **Name**. | | **Rollback** | admin role | Swaps the database with its backup: the backup becomes the database and the database becomes the backup (Memory databases keep the backup). | | **Restore** | admin role | Replaces the database with its backup and keeps the backup. | | **Remove** | owner | Disconnects the database from the server. The files stay on the disk. | | **Delete** | owner | Deletes the database and its files permanently. You have to type the database name to confirm. | ::warning **Delete** cannot be undone. Use **Remove** if you only want the database out of the list. :: ## Share a database Open the users panel with the chevron at the end of the row. It lists the users of the database grouped by role, with a **Filter users...** box. Large groups show the first 10 users and a **+N more** link. | Role | The user can | | -------------- | ----------------------------------------------------------------------------------- | | **Admin** | read, change, back up, convert and clear the database, and add and remove its users | | **Read/Write** | read and change the data, optimize the database | | **Read Only** | read the data, see the audit log, copy the database | Users with the admin role can: - add a user with the **+** button: a **Username** and a **Role**, - change a user's role by clicking the username, - remove a user with the remove button next to the name. The owner always has the admin role and cannot be changed or removed. A shared database shows up on the other user's **Databases** page with their role in the **Role** column. The server admin sees and manages every database of the server on the [admin pages](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/admin#databases). # Queries The query page (`/studio/query//`) opens when you click a database on the **Databases** page. Its heading names the database. The query builder is at the top and the [results](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/results) below it. The builder writes the same queries as the [`QueryBuilder`](https://agdb.agnesoft.com/docs/references/queries) of the agdb libraries, one step at a time, so you do not need to know the syntax up front. ## Tabs The builder has three tabs. Each has its own queries and its own undo history. | Tab | Use it for | | ------------ | -------------------------------------------------------------------------------------------------------------------------------- | | **exec** | Queries that read the database (`select`, `search`). | | **exec_mut** | Queries that change the database (`insert`, `remove`). The rows are orange and the button reads **Run mutation**. | | **context** | Queries that load extra elements around the results, e.g. the neighbourhood of the nodes you found. They show only in the graph. | Running runs only the tab you are on. ## Build a query Each row of a tab is one query, a chain of steps such as `select` → `ids` → `query`. 1. Click into the row and start typing. A list shows the steps that can come next, filtered by what you typed. Pick one with the arrow keys and Enter, or click it. 2. A step that takes arguments opens an editor below it. Each argument has a type and a value. Close the editor with Esc or Enter. The step then shows a short summary such as `(s, foo), (u, 3)`; click it to change the arguments again. 3. Go on with the next step. The closing `query` step is optional. The type of an argument is picked from a short label: | Label | Type | Label | Type | | ----- | -------- | ----------------------------- | ---------------------------------------------- | | `s` | string | `s[]` `u[]` `i[]` `b[]` `f[]` | lists of these, comma separated (`1, 2, 3`) | | `u` | unsigned | `↑` `↓` | ascending and descending order (in `order_by`) | | `i` | signed | | | | `b` | boolean | | | | `f` | float | | | Ids can be numbers or aliases. Arguments that repeat, like the key-value pairs of `values`, have **+** and **−** buttons to add and remove entries (**−** when there is more than one). To fix a step, hover it and click its ×, or focus it and press Delete. Backspace in an empty input removes the step before it. When a step no longer fits the chain, it gets a red outline and the query cannot run until it is fixed. ::tip You can also paste queries written in Rust. Copy `QueryBuilder::…` code (one query per line, a `vec![…]` of queries, or a whole `db.exec(…)` call) and press Ctrl+V in a row. Each query becomes its own row. :: ## Several queries Click **+** at the end of the last row to add another query. All the queries of a tab are sent together and run in **one transaction**. Empty rows are skipped. The controls of each row (the grip handle and the result index only when the tab has more than one row): | Control | What it does | | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | grip handle | Drag to reorder the rows, or focus it and use the up and down arrows. | | result index | The row's index in the results (from 0; blank for empty rows). Click to select the row. Ctrl+click adds rows to the selection, Shift+click selects a range. | | colour swatch | Colour of this query's elements in the [graph](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/graph). Not on the context tab or on empty rows. | | eraser | Clears the steps of the row. | | copy / paste | Copies the query as Rust code, or pastes a copied query into an empty row or below a filled one. | | trash | Removes the row, or all selected rows. | With rows selected, Ctrl+C copies them, Delete removes them and Esc clears the selection. Next to the rows, when the tab has more than one row: - **Show queries** / **Hide queries** folds the rows into a one-line summary. - The copy button copies all queries of the tab as Rust code, one per line (with at least two queries). - The eraser button removes all queries of the tab, after you confirm (**Clear all queries**). **Undo** and **Redo** at the right of the tabs (Ctrl+Z, Ctrl+Shift+Z or Ctrl+Y, except in a field that has text) step through your edits. ## Run a query Click **Run query** (**Run mutation** on the exec_mut tab) or press Ctrl+Enter. While it runs, the button turns into **Stop query**. If the query fails, the error is shown above the results. ::warning Stopping a mutation only stops waiting for its answer. The changes have already been sent to the server and may still be made. :: ## Query links The queries of all tabs are kept in the address of the page, e.g. `/studio/query/alice/shop?exec=select().ids(1)`. Copy the address from the browser to bookmark a query or send it to someone with access to the database. The link opens the same queries, but does not run them. Before running mutations that came from a link, the studio shows their code and asks **Run queries from a link?**, so a link cannot change your data without you seeing it first. The address holds up to about 6,000 characters. When all the queries together are longer, the address no longer holds any of them and the studio warns **Queries too long for the link**; use **Export query** → **Query (JSON)** or the Rust code to keep them instead. A link longer than that does not open (**Link too long**). Queries in a link that cannot be read are skipped with the warning **Some queries were not opened**; if one of them is a mutation, none of the mutations are opened. ::note The query page keeps nothing else. The results, colours, chart settings and pinned details are gone when you leave the page or reload it. To keep a query with its view, [add it to a dashboard](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/dashboards#add-a-query-from-the-query-page). :: ## Export the query **Export query** on the page heading downloads the queries of all tabs as **Query (JSON)** or **Rust code** (a `.rs` file with a function per tab that returns its `QueryBuilder` queries). See [Export and print](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/export-and-print). # Results and charts The results of the last run are shown below the [query builder](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/queries). The same results view is used in [dashboard widgets](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/dashboards). ## The toolbar The toolbar sums up the last run, one chip per query, e.g. `#1 · result: 5 · 3 nodes · 2 edges · 1 other` (the `#1` only for a batch of several queries), and the time of the run. More chips appear when they apply: - `unique: N`: some queries of the batch returned the same elements. The graph and the table show each element once. - `context: N`: elements loaded by the **context** tab (see [Context and expanded elements](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/graph#context-and-expanded-elements)). - `expanded: N`: elements loaded with **Expand neighbours** in the graph. On the right are the **Export** menu, the **Style** button for the colours and sizes of the [graph](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/graph#style) (not in the chart view) and the views: **Summary** when the result is a single number, **Graph**, **Table**, **Chart** and **JSON**. The studio picks a view that fits the results: - **Summary** when there are no elements, e.g. for `node_count` or a mutation (shows **Node count**, **Edge count**, **Affected** or **Result**). - **Table** for metadata such as `keys`, `key_count`, `edge_count`, `aliases` or `indexes`. - **Graph** otherwise. A view you choose yourself stays until the results change their shape. ## Table One row per element with the columns `id`, `alias` (when any node has one), `result` (for a batch: which of its queries returned the element), `from` and `to` (when there are edges), and one column per property key. The row of the database itself (id 0) reads `(database)`. The table shows 100 rows per page with **Previous** and **Next**. Right-click a row, or use its ⋮ button, for the same actions as in the [graph](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/graph#element-actions): view and edit values, pin, expand neighbours, delete. ## JSON The raw results as the database returned them, with a **Copy** button. Unlike the table, it keeps elements returned by more than one query. Long results are cut at 50,000 characters; **Show all** shows the rest. ## Chart The chart view draws the results as a **Bar**, **Line**, **Donut** or **Stat** chart. Every chart measures groups of elements: | Setting | Choices | | --------- | -------------------------------------------------------------------------------------------------- | | **Show** | **Count** of elements, or **Sum** / **Average** / **Min** / **Max** of a numeric property (**of**) | | **by** | a property (one group per value), or **Query of the batch** (one group per query) | | **Lines** | line charts of a batch only: **One**, or **One per query** | - **Bar**: one bar per group; grouped by a property the largest come first, grouped by query they keep the order of the batch. At most 12 bars including a grey **Other** that adds up the rest. - **Line**: the groups along the x axis, ordered as numbers or dates when all the values are numbers or dates, otherwise as text. Not available when grouping by query, because a line needs ordered values. - **Donut**: parts of a total, so only **Count** and **Sum**. At most 5 slices including **Other**. - **Stat**: the measure of all elements as one number. The first time you open the chart it suggests one: a count by the first text property that has 2 to 12 different values shared by several elements, or else a bar per query for a batch and a stat tile for a single query. Hover a bar, point or slice, or focus the chart and use the arrow keys, to see its exact value. ::tip Charts read the values from the results. Use `select().search()…` rather than a bare `search()`, which returns only ids. :: ### Chart style **Style** in the chart settings opens the **Chart style** dialog: - **Title**: replaces the generated title, e.g. "Count by category". Leave it empty to get the generated one back. - **Colour**: one colour for every bar, or for a single line. Bars of queries that have a colour in the query builder keep it. - **Bars** / **Slices** / **Lines**: a colour and a new name for each one. - **Reset**: back to the generated title, the default colours and the names from the data. Colours and names belong to the values they were picked for, so choosing another **by** drops them. Changing the chart type keeps them. ## Export **Export** downloads the results as **Table (CSV)**, **Chart data (CSV)** (chart view only) or **JSON**, or prints the current view with **Print…**. See [Export and print](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/export-and-print). # Graph The **Graph** view draws the nodes and edges of the results in 3D. Edges have arrows, get lighter towards their target (up to 2,000 edges), and parallel edges are curved. The graph zooms to fit when new results arrive. ## Move around - Drag to rotate, scroll or pinch to zoom, or use the **+**, **−** and **Fit** buttons. - Hover a node to highlight it, its edges and its neighbours. The tooltip shows its id, alias and up to 5 values. Values marked `query` come from the query and are not stored on the element. - Click a node or an edge to open its [details](https://agdb.agnesoft.com/#view-and-edit-values). The selected node has a halo around it. - Click the background to close the menu, the details (unless they have unsaved edits) and add edge mode. ## Element actions Right-click a node or an edge (or use the ⋮ button of a row in the table) for its menu: | Action | What it does | | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | **View details** | Opens the details panel. | | **Edit values** | Opens the details panel ready to edit. | | **Pin details** / **Unpin details** | Keeps a card with the element's values next to it in the graph. Shift+click does the same. | | **Expand neighbours** | Nodes only. Loads its edges and the nodes at their other ends, in both directions. | | **Add edge from here** | Nodes only. Click the target node in the graph and confirm to create the edge (Esc cancels). Its details then open for editing. | | **Colour by distance from here** | Nodes only. Colours the other nodes by how many hops away they are. | | **Delete** | Deletes the element after you confirm. Deleting a node deletes its edges too. | | **Colour** | Gives this one element its own colour. | ::warning These actions change the database right away, also in dashboard widgets. :: ## View and edit values The details panel lists the values of the element in a **Key** / **Value** / **Type** table. For an edge it also shows where it goes from and to. - Click a value (or press Enter on it) to edit it in place. Enter saves, Esc cancels. - × removes a value, **+ Add value** adds one. - The pencil button edits all values in one form with **Save** and **Cancel**. - **From the query** lists the values the query returned that are not stored on the element. They cannot be edited. After a change, when the last run was on the **exec** tab, the studio runs the **exec** and **context** queries again to refresh the graph and keeps the expanded elements. After an **exec_mut** run the results are updated in place; mutations are never run again. ## Pinned cards A pinned card floats next to its element, joined to it by a line. Drag its header to move it, double-click it to open the details, and use its unpin button to remove it. ## Style **Style** in the toolbar colours and sizes the nodes and edges. The colours come from a palette of 7 that works in both the light and the dark theme. Once anything is coloured, the remaining elements turn grey. The rules apply in this order, so a later section overrides an earlier one: 1. **By query**: one colour per query of the batch. With several queries, **Give each query its own colour** colours them all at once. The swatch of a query row in the builder sets the same colour. 2. **By property**: pick a **Property…** and which values to colour: **a colour per value** (the first 7 values), **a gradient** (numeric properties), **any value**, or one value. For **any value** and one value pick a colour, then click **Add**. The first matching rule wins; ↑ moves a rule up. Gradients are **Teal**, **Purple**, **Rose** or **Several colours**. 3. **Single elements**: elements you coloured one by one from the right-click menu. **Colour by distance from the search start** appears when the last query searched from a node. It colours by hops along the shown edges, in either direction; 6 hops and more share the last colour. **Clear all colours** removes every colour, including the query and single element colours; the sizes stay. **Sizes** (graph view only): - **Nodes**: **same size**, **connections**, **incoming connections**, **outgoing connections**, or a numeric property. - **Edges**: **same size** or a numeric property. - Property sizes use a **linear** or **log** scale. Connections count the edges shown in the graph. The legend in the corner of the graph lists the colours (**Set by hand**, **By property**, **By query**) with the number of elements of each, the gradient ranges and the sizes. **Edit style** opens the Style panel. ## Context and expanded elements Besides the results of the last **exec** or **exec_mut** run, the graph also shows: - **context** elements: the results of the queries on the **context** tab. Run that tab on its own. Use it to load what is around your results without adding it to them. - **expanded** elements: loaded with **Expand neighbours**, or edges you added. A new run of **exec** or **exec_mut** clears them. Both are drawn in their own context colour and counted in the `context` and `expanded` chips. They show only in the graph and in the JSON export, not in the table, the chart or the CSV. ## Limits - The graph draws at most 2,000 nodes. Use the table to see all of them, or narrow the query. - There is no search or filter in the graph itself; change the query instead. # Dashboards A dashboard is a grid of widgets. Each widget runs a query on a database and shows its results, the same way as the [query page](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/results). Dashboards are stored on the server, so they follow you to any browser, and you can share them with other users. ## The dashboard list **Dashboards** in the top bar (`/studio/dashboards`) lists: - **My dashboards**: the dashboards you own. - **Shared with me**: dashboards other users gave you a role on. - **Public**: public dashboards of other users that you have no role on. Each row shows the name and when it was last updated. Other users' dashboards show as `owner/name` with your role and a **Public** badge; on your own, the globe button shows whether it is public. Its buttons: | Button | Who | What it does | | ---------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------- | | star | any user | Opens this dashboard at the start of the studio, instead of the database list. One per user. | | globe | owner | Makes the dashboard public (every user can view it) or private again. | | users | any role | Opens the [users of the dashboard](https://agdb.agnesoft.com/#share-a-dashboard). | | **Rename** | owner | Gives it a new name. | | **Delete** | owner | Deletes it, also for the users it is shared with. The databases it shows are not changed. | | **Leave** | users with a role | Gives up your role on the dashboard. Its owner or an admin can share it again. A public dashboard stays under **Public**. | ### Create a dashboard - **New dashboard** asks for a name: 1 to 64 letters, digits, `_`, `-` or `.`, not starting with `.`. - **Import** creates a dashboard from a file saved with **Export** → **Dashboard file**. - **Add to dashboard** on the query page creates one from a query (see [below](https://agdb.agnesoft.com/#add-a-query-from-the-query-page)). ::note Widgets point to their databases by `owner/db`. An imported dashboard works only where databases with the same owners and names exist and you have access to them. :: ## Add a query from the query page Build a query on the **exec** tab, then click **Add to dashboard** at the top of the query page. Choose a **Dashboard** you can edit, or **+ New dashboard** with a name, and a **Widget title**. The widget gets the **exec** and **context** queries together with the colours, sizes, view, chart and pinned details you set up, and is added to the end of the dashboard. ## The dashboard page Widgets run when the dashboard opens. **Refresh** reruns all of them; each widget also has its own refresh button. **Add widget** opens the widget editor. Every change you make to the dashboard is **saved right away**; there is no Save button. **Saving…** shows while it saves. If saving fails, **Changes not saved** with **Retry** keeps your edits until it works, and the studio warns you before you leave the page. ### Widgets The header of a widget shows its title and database, the results toolbar (summary, **Export**, **Style** and the view icons **Summary** (for single numbers), **Graph**, **Table**, **Chart**, **JSON**) and its buttons: - refresh, - **Open in query editor**: opens the widget's queries on the query page, - **Maximize** / **Restore**: shows the widget over the whole page, - **Widget options** (…), for editors only: **Edit widget…**, **Size**, **Move earlier**, **Move later**, **Remove**. The view, chart, colours, sizes and pins you change in a widget apply only until you reload. The **Unsaved view** label then offers **Save** to keep them in the dashboard (editors only), or **Reset** to go back. **Remove** does not ask first: **Undo** next to the title brings the widget back for 8 seconds. ### Layout The dashboard is a grid 4 columns wide. A widget is 1 to 4 columns wide and 1 to 3 rows high, new ones are 2 × 1. Set the size with **Size** in the widget options (hover the grid to preview the size, click to set it), and the order with **Move earlier** and **Move later**. Widgets cannot be dragged. From 900 to 1199 px wide the grid has 2 columns, and below 900 px 1 column. ### The widget editor **Edit widget…** or **Add widget** opens the editor: - **Title** of the widget. - **Database** the widget queries. - **Auto refresh**: **Off**, **10 s**, **30 s**, **1 min**, **5 min**, **15 min** or **1 h** (an imported dashboard may also hold other intervals up to 1 day). It pauses while the browser tab is hidden, and stops after a failed run until a refresh works again. - The [query builder](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/queries) with the **exec** and **context** tabs, and a preview of the results that updates as you edit. **Save** stores the widget with its queries, colours, sizes, view, chart and pinned details. **Cancel** (or Esc) asks before it throws away unsaved changes. ## Share a dashboard The users button of a dashboard opens its users, grouped by role: | Role | The user can | | -------------- | ---------------------------------------------------------------------------- | | owner | everything, including rename, delete and making it public | | **Admin** | edit the widgets and the layout, add and remove users and change their roles | | **Read/Write** | edit the widgets and the layout | | **Read Only** | view and refresh. The dashboard shows a **Read only** badge. | Users with the admin role add users with the **+** button (a **Username** and a **Role**), change a role by clicking the username, and remove users with the remove button. Every user can view a **public** dashboard with read only access. ::warning Widgets run their queries with the **viewer's own** access to the databases. Sharing a dashboard does not share its databases: share them too, or the widget shows **Database not found**. :: ## Limits - A dashboard (its widgets and layout, not the results) is up to 256 KB. - Names cannot contain `/` and are unique per owner. - A dashboard saved by a newer studio cannot be opened by an older one; update the server (and with it the studio). - Widget queries should read data. The element actions of the graph and the table still work in widgets and change the database. # Admin The server admin has a second set of pages. Switch to them with **Admin View** in the account menu, and back with **User View**. In the admin view the logo has a red **admin** badge and the top bar shows **Status**, **Databases**, **Dashboards** and **Users**. Other users who open an admin page are sent back to the start with **Admins only**. ## Status **Server Status** (`/studio/admin`, **Status** in the top bar) shows the server at a glance: the number of **Databases**, **Users** and **Logged In** users, **Memory**, **Data Size** and **Uptime**. It refreshes every 15 seconds. **Log Level** can be changed right there (off, error, warn, info, debug; trace acts as debug). The change takes effect at once, without a restart, on the node you are connected to only, and is not written to the [configuration file](https://agdb.agnesoft.com/docs/references/server#configuration). **Cluster Nodes** lists the nodes of a cluster with their **Address**, **Status**, the **Leader** (crown), the **Executed Index** of the Raft log and whether a node is resyncing (**Resync**). ## Users **Users** (`/studio/admin/users`) lists every user of the server, admins first (crown), with their number of **Sessions**. - **Add User**: a **Username** (at least 3 characters) and a **Password** (at least 8 characters). - **Log out all**: logs out every user except the server admin, optionally on all nodes of the cluster. The actions of a user: | Action | What it does | | ------------------- | ---------------------------------------------------------------------------------------- | | **Sessions** | Lists the user's sessions; each can be logged out. | | **Change Password** | Sets a new password for the user. | | **Log out** | Logs out all or one of the user's sessions, optionally on all nodes of the cluster. | | **Delete** | Deletes the user together with their databases and dashboards. Not offered for yourself. | The table can be exported like the database table (see [Export and print](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/export-and-print)). ## Databases **Databases** (`/studio/admin/db`) is the [database page](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/databases) for every database of the server, with every action and the users of every database available. **Copy** and **Rename** also take an **Owner**, so you can move or copy a database to another user. A database added with the form belongs to you; copy or rename it to give it to another user. Opening a database from here opens the admin query page, which runs queries with admin access. It has no **Add to dashboard** button. ## Dashboards **Dashboards** (`/studio/admin/dashboards`) lists all dashboards of all users in one table. The admin can do with every dashboard what its owner can. **New dashboard** and **Import** also ask for the **Owner (username)**. An opened dashboard shows an **Admin access** badge: its widgets run with admin access to every database, so they may show data that the owner of the dashboard cannot see. # Account and cluster ## Account menu Your username at the top right opens the account menu: - **Admin View** / **User View**: for the server admin, switches to the [admin pages](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/admin) and back. - **Sessions**: opens **Active Sessions**, your logins in this and other browsers and devices, with when they were created and when they expire. Log out any of them with its button. - **Change password**: your **Current password** and a **New password** of at least 8 characters, twice. - **Theme**: **System** (follows your operating system), **Light** or **Dark**. The choice is kept in the browser. - **Log out**: when you have more than one session, choose **Current session**, **All sessions**, **Other sessions** or a single one. **Log out on all nodes in the cluster** is ticked by default. ## Sessions A login lasts for the server's `token_expiry_seconds` (1 hour by default). The studio checks it every minute. When it ends, all open dialogs close, the login page says **Session ended**, and after you log in again as the same user you are back on the page you were on. The login is shared by all tabs of the browser: logging out in one tab logs out the others. ## Notifications Messages appear at the bottom right of the page. Errors stay until you close them, other messages go away after a few seconds. The bell button in the same corner opens the last 50 of them, with a button to clear them all (it asks first). If the server stops answering, the studio says **Can't reach the server** and keeps retrying for a while when the page loads. If it still cannot connect, start the server and reload the page. ## Cluster The top bar shows **Connected to:** and the server you are on (hidden while a cluster has no leader). When the server runs as a [cluster](https://agdb.agnesoft.com/docs/guides/how-to-run-server), a crown shows when you are on the leader, and a coloured dot shows the health of the cluster: | Colour | Meaning | | ------ | --------------------------------------------------------------------------- | | green | All nodes are up and there is a leader. | | amber | A node is down, or there is no leader (election running). | | red | All nodes are down, there are no nodes, or the status could not be fetched. | | grey | The status is not loaded yet. | When something is wrong, the text **Cluster degraded**, **Cluster unhealthy** or **Cluster unknown** is shown as well. Hover or click it to see the nodes: whether each one is online, and whether you are logged in there. Click an online node to switch the studio to it (until you reload the page). If you are not logged in on that node, the studio logs you out of the current node in this browser (in all tabs) and opens the login page with the new node's address filled in. Log in with **Log in on all nodes in the cluster** to switch freely. # Export and print You can download data from the studio as CSV or JSON files, or print it. To save a PDF, print and choose "Save as PDF" as the printer. Prints always use the light theme, even when the studio is shown in dark mode. Use the studio's **Print…** items rather than the browser's own print command: they draw graphs and charts at the size of the page, and they print the widgets of a dashboard that are scrolled out of view. | Where | What you can export | | -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Export** on query results (query page and dashboard widgets) | **Table (CSV)**: the elements and their values, one column per key, as in the table view (lists as JSON arrays). **Chart data (CSV)**: the values the chart shows (chart view only). **JSON**: the raw query results, with the context and expanded elements shown with them, if any. **Print…**: the current view, including the graph. | | **Export query** on the query page heading | **Query (JSON)**: each tab's queries as text chains, the same format as query links. **Rust code**: a `.rs` file with a function per tab that returns its queries as `QueryBuilder` code. | | **Export** on a dashboard | **Dashboard file**: the dashboard layout and widgets, which you can import again with **Import** on the dashboard list. **All data (JSON)**: the results of every widget that has run. **Print…**: the whole dashboard. | | **Export** above the database and user tables | **CSV**, **JSON** and **Print…** of the rows, in the order they are currently sorted. | File names start with the database (`owner-db-…`) or the dashboard (`owner-name-dashboard-…`) they come from and end with the date and time, e.g. `alice-shop-results-2026-11-28T1530.csv` or `databases-2026-11-28T1530.json`. CSV files are UTF-8 and open correctly in Excel and LibreOffice. Text values that start with `=`, `+`, `-`, `@`, a tab or a carriage return get a leading `'`, so that spreadsheets do not run them as formulas. # Troubleshooting For the meaning of the server status codes and the database and client errors see the [error codes](https://agdb.agnesoft.com/docs/references/error-codes) reference. ## Getting cross-origin (CORS) errors when connecting to the `agdb_server` CORS error can happen even locally when running the server and connecting to it using raw IP address (e.g. `127.0.0.1`). Try connecting to the server using `localhost` (the default `address` is `http://localhost:3000`, the default `bind` is `:::3000`) or another DNS name instead. ## Database fails to open or appears corrupted When a database is opened the WAL (write-ahead log) file is replayed to repair any incomplete transactions from a previous crash. If the main database file (e.g. `my_db.agdb`) or its WAL (the same name with a leading dot, e.g. `.my_db.agdb`) are missing or truncated (e.g. disk full during a write), the database may fail to load. **Steps to try:** 1. Make sure the `my_db.agdb` file is present and not zero-length. The WAL `.my_db.agdb` can be empty or hold stale records of earlier commits, both are normal. 2. If only the WAL is missing the database will still load, but you may have lost the last uncommitted transaction. 3. Restore from a backup if available: use `/api/v1/db/{owner}/{db}/restore` (server) or copy the backup file manually (embedded). 4. If you run on a network filesystem (e.g. WekaFS), consider enabling `SyncMode::Commit` or `SyncMode::Strict` (embedded) or `sync_mode: commit` / `sync_mode: strict` (server) to avoid future reorder-related corruption. See the [storage](https://agdb.agnesoft.com/docs/guides/concepts#storage) section. ## Authentication token expired or 401 errors Login tokens expire after `token_expiry_seconds` (default: 3600 = 1 hour). If you receive repeated `401 Unauthorized` responses: 1. Re-login to obtain a fresh token. 2. For long-running automation, schedule a periodic re-login before the token expires. 3. When using a cluster, prefer `cluster_user_login` — it creates the same session token on every node so you can talk to any node without separate logins. ## Cluster leader not elected / nodes cannot find each other If the cluster is stuck without a leader: 1. Verify the `cluster` array is **identical** in every node's config, including order. 2. Verify each node's `address` appears exactly once in that array. 3. Verify `cluster_token` is the same on all nodes. 4. If using TLS, make sure the certificate's SANs (Subject Alternative Names) cover the hostnames used in `cluster` and `address`. 5. Check that the `cluster_term_timeout_ms` is not too short for your network latency — increase it on high-latency links. 6. Use `/api/v1/cluster/status` on each node to see who it thinks the leader is and the peers as that leader last reported them. A node that has not heard from a leader recently reports only itself. ## Query returns unexpected results 1. **Using verbose comparison without import** — conditions like `.value(LessThan(40.into()))` compile but always match everything. Prefer the shorthand `.key("age").less_than(40)` which avoids this class of error entirely. If you must use the enum form, fully qualify it: `.value(Comparison::LessThan(40.into()))`. 2. **Wrong exec variant** — `db.exec()` (or `db_exec` on the client) only accepts immutable queries (`select`, `search`). Passing a mutable query returns a `403` error ("permission denied: mutable queries not allowed, use exec_mut endpoint") on the server or a compile error in embedded Rust. 3. **Forgetting `.query()`** — every builder chain must end with `.query()` (and `.into()` for batch execution on the server). A missing `.query()` is a compile-time error in Rust but easy to miss in dynamic-language clients. 4. **Index not created** — `search().index("key").value(v)` requires the index to exist. If no index is present the query returns an error, not an empty result. Create it first with `insert().index("key")`. ## Server refuses to start with "Cluster does not contain local node: :url[( [...] )"] The local `address` followed by the `basepath` (the `` in the message) must match one of the entries in the `cluster` array **exactly** (including scheme and port). For example, `http://localhost:3000` does not match `http://127.0.0.1:3000`. # Running in production This guide collects what an operator of `agdb_server` should set up beyond the defaults. It does not repeat the configuration reference, please see the [server reference](https://agdb.agnesoft.com/docs/references/server) for every option and the [How to run the server?](https://agdb.agnesoft.com/docs/guides/how-to-run-server) guides for the deployment methods (bare metal, Docker, Kubernetes, single node or cluster). ## TLS The server serves TLS (via `rustls`) when both `tls_certificate` and `tls_key` are set in `agdb_server.yaml`. If either is empty the server listens on plain HTTP without any warning, so check the startup log for the `TLS enabled` line. ```yaml # agdb_server.yaml address: https://db.example.com:3000 tls_certificate: /etc/agdb/cert.pem tls_key: /etc/agdb/cert.key.pem tls_root: "" # only for a private CA, see below ``` - The `tls` cargo feature must be compiled in: `cargo install agdb_server --features tls` (requires CMake, see [bare metal](https://agdb.agnesoft.com/docs/guides/how-to-run-server/server-bare-metal)). Without it the `tls_*` settings have no effect. The Docker image is built with all features. - The certificate and key are read once on start. Restart the server to use a renewed certificate. - `tls_root` is the root CA file the server trusts when it connects to the other nodes of a cluster. It is needed only if the nodes use certificates from a private CA or self-signed ones. The certificate must be valid for the names used in `address` and `cluster`. - Rust clients need the `tls` feature of `agdb_api` to connect to an `https://` address: `cargo add agdb_api --features tls` (see the [Rust client](https://agdb.agnesoft.com/api-docs/rust)). If a reverse proxy terminates TLS for you (see below) the server itself can stay on plain HTTP on a private network, but `address` must still be the public `https://` address clients use. ## Password pepper Passwords are stored as PBKDF2 hashes that include a 16 byte secret, the pepper. By default the server uses the pepper built into the binary (`agdb_server/pepper` in the sources), which is public. In production use your own, either baked in when [building the server](https://agdb.agnesoft.com/docs/guides/how-to-run-server/server-bare-metal) or loaded at runtime: ```yaml pepper_path: /run/secrets/agdb_pepper # a file with exactly 16 bytes ``` Surrounding whitespace in the file (such as a trailing newline) is trimmed and the server refuses to start if the file is unreadable or the value is not 16 bytes long. ::warning The pepper is part of every stored password hash. A server with a different pepper cannot verify any existing password, so store it as a secret, back it up, and never change it on a server that has users. All nodes of a cluster must use the same pepper. If it is lost, follow the recovery steps in the [bare metal guide](https://agdb.agnesoft.com/docs/guides/how-to-run-server/server-bare-metal): start with a new pepper and a new `admin` name, then reset the passwords with `/api/v1/admin/user/{username}/change_password`. :: ## Admin account On the first start the server creates the user named by `admin` (default `admin`) with a password equal to its name. Change it before exposing the server: ```bash token=$(curl -s -X POST -H 'Content-Type: application/json' localhost:3000/api/v1/user/login -d '{"username":"admin","password":"admin"}') curl -X PUT -H "Authorization: Bearer ${token}" -H 'Content-Type: application/json' \ localhost:3000/api/v1/user/change_password -d '{"password":"admin","new_password":"a-long-random-password"}' ``` New passwords must be at least 8 characters. Pick the `admin` name before the first start. On every start the server makes the user named by `admin` the admin, creating it with the password equal to its name if it does not exist, so changing the field later hands the admin role to that user (with a weak password if it is new) rather than renaming the existing admin (see [Configuration](https://agdb.agnesoft.com/docs/references/server#configuration)). Use a regular user for day to day work and keep the admin for operations (see [Admin](https://agdb.agnesoft.com/docs/references/server#admin)). ## Reverse proxy To serve the server under a path of a proxy set `basepath` and `address`. The `address` holds only the scheme and host (a path in it is ignored with a warning) and the server serves all its routes, including `/studio/` when built with the `studio` feature, under `basepath`. The proxy must therefore forward the full path without stripping the prefix. ```yaml bind: 127.0.0.1:3000 address: https://db.example.com basepath: /agdb request_body_limit: 10485760 # bytes, default 10 MiB ``` The `request_body_limit` caps the size of any request. Raise it if you send large query batches and set the proxy limit to at least the same value. In a cluster `request_body_limit` must be at least `cluster_max_append_size` plus 64 KiB (otherwise the node refuses to start) and any proxy between the nodes must accept the same size. The snapshot a lagging node fetches from the leader is one long streamed response of `GET {basepath}/api/v1/cluster/snapshot/{id}`. The server sends it with `X-Accel-Buffering: no`, which nginx honours by default and passes the stream through unbuffered. Do not override that with `proxy_ignore_headers` or turn buffering on for this route. A minimal nginx example (adapt it, it is not a complete hardened configuration): ```nginx location /agdb/ { # no URI part in proxy_pass: the path is forwarded unchanged proxy_pass http://127.0.0.1:3000; proxy_set_header Host $host; client_max_body_size 10m; # at least request_body_limit } ``` ## Durability and memory Three settings control how the databases are written and how much memory they take. Their meaning and trade-offs are explained in [Sync Mode](https://agdb.agnesoft.com/docs/references/server#sync-mode), [Overlay Limit](https://agdb.agnesoft.com/docs/references/server#overlay-limit) and the [storage concepts](https://agdb.agnesoft.com/docs/guides/concepts#storage): ```yaml sync_mode: none # none (default), commit or strict overlay_limit: 67108864 # bytes of a transaction kept in memory before commit memory_limit: 0 # bytes per user database, 0 = unlimited ``` `sync_mode` and `overlay_limit` apply to the server database, the cluster log and the user databases. `memory_limit` applies only to user databases. The values in use are logged on start (`sync_mode`, `overlay_limit`). ## Backups and restore Back up on two levels. **Per database** with the backup API. The database admin (or the server admin via `/api/v1/admin/db/...`) creates, restores or rolls back a backup: ```bash curl -X POST -H "Authorization: Bearer ${token}" localhost:3000/api/v1/db/alice/my_db/backup curl -X POST -H "Authorization: Bearer ${token}" localhost:3000/api/v1/db/alice/my_db/restore ``` - `backup` keeps one backup per database and overwrites the previous one. - `restore` replaces the database with the backup and keeps the backup, so it can be repeated. - `rollback` swaps the database and the backup, so calling it twice toggles between the two states (for `mapped` and `file` databases; for `memory` databases it behaves like `restore`). - The audit log is backed up and restored together with the database. For several generations of backups use `copy` and `rename` as described in [Backups](https://agdb.agnesoft.com/docs/references/server#backups). **Per server** by copying `data_dir` (default `agdb_server_data`): | Path | Content | | --------------------------------------- | ------------------------------------------------- | | `agdb_server.agdb`, `.agdb_server.agdb` | server database (users, sessions) and its WAL | | `agdb_server.log` | cluster log (a database file) | | `.agcluster/staging` | snapshots prepared for other nodes (cluster) | | `{owner}/{db}` | user databases (and their dot-prefixed WAL files) | | `{owner}/backups/{db}.bak` | the backups made by the backup API | | `{owner}/backups/{db}.audit` | the audit log of the backup | | `{owner}/audit/{db}/YYYY-MM-DD.log` | audit log, one file per UTC day | Shut the server down (`/api/v1/admin/shutdown` or `CTRL+C`) before taking a file level copy and keep the [pepper](https://agdb.agnesoft.com/#password-pepper) and the configuration with it. Test the restore on a spare machine. ### Audit log retention Every mutable query is recorded in the audit log, which grows with each write. Trim it regularly, e.g. from a scheduled job. The call keeps today and the given number of UTC days before it, in both the live log and the backup: ```bash curl -X POST -H "Authorization: Bearer ${token}" "localhost:3000/api/v1/db/alice/my_db/audit/trim?keep_days=90" ``` The server admin can use `/api/v1/admin/db/{owner}/{db}/audit/trim` for any database. See [Audit](https://agdb.agnesoft.com/docs/references/server#audit) for the details. ## Monitoring | Endpoint | Use | | ---------------------------------- | ------------------------------------------------------------------------------------------------------- | | `GET /api/v1/status` | liveness / readiness probe, no token, `200 OK` when the node is up, always answered locally | | `GET /api/v1/admin/status` | admin only: `uptime`, `dbs`, `users`, `logged_in_users`, `size` (data directory), `memory`, `log_level` | | `GET /api/v1/cluster/status` | no token: per node `address`, `status`, `leader`, `executed_index`, `resync` | | `POST /api/v1/admin/set_log_level` | admin only: `?new_level=` one of `off`, `error`, `warn`, `info`, `debug`, `trace` | - `memory` is the memory of the server process (reported as 0 on platforms other than Linux and Windows). - Without a cluster `cluster/status` returns just the node itself as the leader. In a cluster it shows the nodes as the leader last reported them, so a node that has not heard from a leader recently reports only itself. A node with `resync: true` is catching up with the leader. Alert on a missing leader and on `executed_index` falling behind. - The server logs to the standard output. Set the level with `log_level` in the configuration, or change it at runtime with `set_log_level`. The runtime change applies to the one node that received it and is not written to the configuration, so it is lost on restart. - At the `debug` and `trace` levels the request and response bodies are logged, and at every level except `off` the body of a `5xx` response, truncated to `log_body_limit` bytes (default 10240, `0` disables the body logging). Bodies can contain sensitive data, so use these levels only temporarily. Below `debug` the polled status endpoints are not logged. ## Sessions and token expiry A login creates a session token valid for `token_expiry_seconds` from the login (60 to 86400, default 3600). The expiry is not extended by using the token, clients log in again on `401`. Expired tokens are removed on start and periodically. Users can log out the current, all or other sessions, the admin can force a logout of a user or of all non-admin users, see [Users](https://agdb.agnesoft.com/docs/references/server#users) and [Admin](https://agdb.agnesoft.com/docs/references/server#admin). Use `/api/v1/cluster/user/login` to get one token valid on every node of a cluster. ## Upgrading - Configuration changes require a restart. The server refuses to start with an invalid value or an unknown key, so check the log after a restart. - Take a backup first (see above), especially for a cluster topology change, whose steps are in the [Cluster](https://agdb.agnesoft.com/docs/references/server#cluster) section. - The nodes of a cluster refuse messages of a cluster with a different agdb database version, `cluster` list or `cluster_max_log_entries`, so keep every node on the same release and these settings identical on all nodes. - When upgrading from a version with the previous cluster implementation, the new version does not replay the old cluster log and removes it on start. Let all nodes catch up with the leader and stop them all before the upgrade so that they start with the same data. - Audit logs in the older single-file format are converted automatically. Call `audit/trim` only after all nodes run a version that supports it. - For a node that is down for long (e.g. during an upgrade) and fell behind the leader, see [Failures and repair](https://agdb.agnesoft.com/docs/references/server#failures-and-repair): it receives a full snapshot from the leader. ## Production checklist - TLS enabled on the server or a TLS terminating proxy in front, `address` set to the public URL - Server built with the `tls` feature if the server terminates TLS - Own pepper (`pepper_path` or built in), backed up and identical on all nodes - `admin` password changed, regular users for applications - `cluster_token` changed from the default `cluster` in a cluster, and treated as a secret - `request_body_limit` and the proxy body limits consistent (cluster: at least `cluster_max_append_size` + 64 KiB) - `sync_mode` chosen for your storage (see [Sync Mode](https://agdb.agnesoft.com/docs/references/server#sync-mode)) - Regular database backups and audit trimming scheduled, a restore tested - `/api/v1/status` wired to the health checks, `cluster/status` and `admin/status` monitored - `log_level` at `info` in normal operation (not `debug` or `trace`) - `token_expiry_seconds` set to what your clients need and no more For common problems see [Troubleshooting](https://agdb.agnesoft.com/docs/guides/troubleshooting). # Data modelling This guide is a bridge between the [concepts](https://agdb.agnesoft.com/docs/guides/concepts) (what a graph in `agdb` is) and the worked examples such as [Efficient agdb](https://agdb.agnesoft.com/docs/references/efficient-agdb) (a whole application built step by step). It answers a single question: given my application data, what should the graph look like? ## Building blocks - **Nodes are entities.** A user, a post, a database, an invoice. - **Edges are relationships.** They are directed (`from` -> `to`) and, like nodes, can carry values. A `role`, a `created` timestamp or a `liked` flag on an edge is often all the "join table" you need. - **Values are key-value properties** of nodes and edges, e.g. `("username", "alice")`. - **Labels are keys without a value** (`DbValue::None`). They tag an element cheaply (4 bytes) and can be matched with `keys("admin")`. - **Aliases are names for nodes.** A node with an alias can be used in place of its id in any query. ```rs // Aliased roots, a user node with a label and a value. db.exec_mut( QueryBuilder::insert() .nodes() .aliases(["users", "posts"]) .query(), )?; let alice = db.exec_mut( QueryBuilder::insert() .nodes() .values([[("username", "alice").into(), ("admin", DbValue::None).into()]]) .query(), )?; // The edge from the root is the "row belongs to table" relationship. db.exec_mut( QueryBuilder::insert() .edges() .from("users") .to(&alice) .query(), )?; ``` ## Roots and edges instead of tables There are no tables in `agdb`. The role of a table is played by a **root node with an alias** (`users`, `posts`) and the rows are the nodes hanging off it. Which nodes belong to the "table" is expressed by edges rather than by a schema, so one node can belong to several collections at once (e.g. `alice` can be reachable from `users`, from `admins` and from the team she is in) without duplicating anything. The aliased root is also the entry point of every search: you start there and walk towards the data. | Relational | `agdb` | | ------------------------- | ---------------------------------------------------------------------------------------- | | table | root node with an alias + child nodes connected from it | | row | node with values | | column | key of a value (rows need not all have the same keys) | | foreign key (one-to-many) | an edge from the parent to the child | | join table (many-to-many) | edges between the two nodes, with values on the edge (`role`, `since`) | | `UNIQUE` / index | `insert().index("key")` plus a check inside a mutable transaction | | `WHERE` | search conditions (`where_()`) or an index lookup | | `JOIN` | following edges in a search (see [Joins](https://agdb.agnesoft.com/docs/examples/joins)) | For the reasoning behind this see [Why not SQL?](https://agdb.agnesoft.com/blog/why-not-sql) and [Why object queries?](https://agdb.agnesoft.com/blog/object-queries). ### One-to-many The edge from the parent is the relationship. A post authored by a user is simply an edge `user -> post`; "all posts of alice" is a search from alice. ```rs db.exec_mut( QueryBuilder::insert() .edges() .from(&alice) .to(&post) .query(), )?; let posts = db.exec( QueryBuilder::select() .values(["title"]) .search() .from(alice.elements[0].id) .where_() .neighbor() .query(), )?; ``` ### Many-to-many with values on the edge No join table is needed. The edge between the two nodes is the row of the join table and it holds the attributes of the relationship. This is taken from the [Joins](https://agdb.agnesoft.com/docs/examples/joins) example, where `user` is the alias of a user node and `dbs` the result of inserting two database nodes: ```rs db.exec_mut( QueryBuilder::insert() .edges() .from("user") .to(dbs) .values([[("role", "admin").into()], [("role", "read").into()]]) .query(), )?; ``` Use `values_uniform` when every edge gets the same values (e.g. `("liked", 1)`). Reading the data back is a graph search, not a join: see the [Joins](https://agdb.agnesoft.com/docs/examples/joins) example for both the single-pass depth-first approach and the transaction based one. ## Index or graph search? There are two ways to find an element and the model should be chosen with that in mind. **Graph search** starts at an alias and follows edges while checking conditions. Its cost depends on how much of the graph it has to visit, so a good model *narrows the search by structure*: `users -> alice -> posts` visits only alice's posts. Limit the traversal with conditions: ```rs // The users root and its direct children, without walking through archived nodes. QueryBuilder::select() .values(["username"]) .search() .from("users") .where_() .distance_less_than_or_equal(2) .and() .not_beyond() .keys("archived") .query(); ``` - `distance_*` conditions bound how far the search goes (1 = first edge, 2 = the node behind it). - `beyond()` / `not_beyond()` decide whether the search continues through the elements that match (see [Queries](https://agdb.agnesoft.com/docs/references/queries)). - When you only want one item use `depth_first()` with `limit(1)`; the default breadth first search is better suited for "closest first" results. **Index lookup** finds elements by the value of a key regardless of where they are. It pays off when the data is uniform and cannot be split sensibly by structure, typically a lookup by `username`, `email` or session `token` among many thousands of siblings. ```rs db.exec_mut(QueryBuilder::insert().index("username").query())?; let user = db.exec( QueryBuilder::select() .values(["username"]) .search() .index("username") .value("alice") .query(), )?; ``` An index can be created at any time, existing elements are indexed too. Keep in mind that: - an index is on a **key** and covers every element having it (nodes and edges alike), so pick keys that are specific to one kind of entity; - the index is not a constraint. A `UNIQUE` equivalent is a search inside a mutable transaction that rejects the insert if the value exists, as done in [Efficient agdb](https://agdb.agnesoft.com/docs/references/efficient-agdb) and the [Indexes](https://agdb.agnesoft.com/docs/examples/indexes) example; - index searches skip the traversal, so the traversal conditions (`distance`, `neighbor`, `beyond`, `not_beyond`) are not available in them. A rule of thumb: model the relationships that you traverse (owner, parent, membership) as edges and index the keys you look up *from the outside* (login names, tokens, external ids). ## Typed data Hand-writing key-value pairs gets tedious. Derive `DbType` on your structs to insert and select them directly; the derive macros are described in the [derive macros reference](https://agdb.agnesoft.com/docs/references/derive-macros) and the [User types](https://agdb.agnesoft.com/docs/examples/user-types) example. ```rs #[derive(Debug, DbType)] struct User { username: String, password: String, } let user = User { username: "alice".into(), password: "secret".into() }; let id = db.exec_mut(QueryBuilder::insert().element(&user).query())?.elements[0].id; let user: User = db .exec( QueryBuilder::select() .values(User::db_keys()) .ids(id) .query(), )? .try_into()?; ``` `DbType` only maps fields to keys, so two structs with the same fields are indistinguishable in the graph. When several such types hang off the same node derive `DbElement` instead: it additionally stores the type name with each element (the `db_element_id` value) and lets you select only the elements of one type with `select().elements::()` or filter them with `where_().element::()`. Only use it where types really overlap, because it stores one more value per element. ## Evolving the model The model is not fixed up front. Properties can be added to existing elements, new edges and roots introduced and indexes created later, all with ordinary queries run in a transaction. Typical changes are caching a computed value on a node (a `likes` counter instead of counting edges every time) or introducing an intermediate node. See [Schema updates](https://agdb.agnesoft.com/docs/references/efficient-agdb#schema-updates) for a walk-through and the [Schema migration](https://agdb.agnesoft.com/docs/examples/schema-migration) example for converting stored values between two versions of a type. ## Common pitfalls - **Everything under one root.** An alias with millions of direct children is fine for index lookups but a search from it that has to scan the children is not. If you traverse from a root, split it by something meaningful (per user, per tenant, per year) so searches start closer to the data. - **Large blobs.** Values over 15 bytes are stored out of line and every key-value pair costs at least 20 bytes (see [storage](https://agdb.agnesoft.com/docs/guides/concepts#storage)). Keep big files outside of the database and store a reference (path, URL, object key) instead. - **Reused ids.** A removed element frees its `db id` and a later insert may receive the same one. Never keep a bare id as a long-lived external reference to something that can be deleted; use a value of your own (a uuid, a username) with an index. See [concepts](https://agdb.agnesoft.com/docs/guides/concepts#graph). - **Long mutable transactions.** Only one mutable transaction runs at a time. Do the minimum inside it (check, insert, connect) and prepare the data beforehand. Keep reads that do not need to be atomic with the write outside the closure. - **Searching without bounds.** A search without conditions walks the whole reachable graph. Add `distance`, `limit` or a `not_beyond` condition, or start from a node closer to the data. # Guides The following guides walk you through using `agdb` step by step: - [Concepts](https://agdb.agnesoft.com/docs/guides/concepts) - graph, queries, transactions, storage and data types. - [Quickstart](https://agdb.agnesoft.com/docs/guides/quickstart) - embedded database in a Rust application. - [Data modelling](https://agdb.agnesoft.com/docs/guides/data-modelling) - designing your data as a graph of nodes, edges, aliases and indexes, coming from SQL. - [Quickstart - Rust client](https://agdb.agnesoft.com/api-docs/rust) - talking to the `agdb_server` from Rust. See also the [TypeScript](https://agdb.agnesoft.com/api-docs/typescript), [PHP](https://agdb.agnesoft.com/api-docs/php) and [Python](https://agdb.agnesoft.com/api-docs/python) clients. - [How to run a server?](https://agdb.agnesoft.com/docs/guides/how-to-run-server) - single server or cluster on bare metal, Docker or Kubernetes. - [Running in production](https://agdb.agnesoft.com/docs/guides/running-in-production) - TLS, reverse proxy, backups, monitoring and upgrades of the `agdb_server`. - [How to use the studio?](https://agdb.agnesoft.com/docs/guides/how-to-use-studio) - [Databases](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/databases) - [Queries](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/queries) - [Results and charts](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/results) - [Graph](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/graph) - [Dashboards](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/dashboards) - [Admin](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/admin) - [Account and cluster](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/account-and-cluster) - [Export and print](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/export-and-print) - [Troubleshooting](https://agdb.agnesoft.com/docs/guides/troubleshooting) - common problems and how to fix them. # Examples overview The examples are small runnable programs that live in the `agdb` repository. Each page below explains what the example demonstrates, how to run it and walks through its key parts. For guided step-by-step tutorials see the [guides](https://agdb.agnesoft.com/docs/guides). ## Embedded database (Rust) These examples use `agdb` directly as an embedded database. Run them from the repository root. | Example | What it shows | Run | | ---------------------------------------------------------------------------- | --------------------------------------------------------------- | ---------------------------------------------- | | [App db](https://agdb.agnesoft.com/docs/examples/app-db) | Schemaless key-value nodes, edges and a search | `cargo run -p agdb --example app_db` | | [Indexes](https://agdb.agnesoft.com/docs/examples/indexes) | Looking up elements by an indexed key instead of a graph search | `cargo run -p agdb --example indexes` | | [Joins](https://agdb.agnesoft.com/docs/examples/joins) | Combining data from nodes and edges in one result | `cargo run -p agdb --example joins` | | [Schema migration](https://agdb.agnesoft.com/docs/examples/schema-migration) | Changing the shape of stored data inside a transaction | `cargo run -p agdb --example schema_migration` | | [User types](https://agdb.agnesoft.com/docs/examples/user-types) | Deriving `DbType`, `DbValue` and `DbElement` for your own types | `cargo run -p agdb --example user_types` | | [Agent memory](https://agdb.agnesoft.com/docs/examples/agent-memory) | Long-term memory of an AI agent: recall, provenance, forgetting | `cargo run -p agdb --example agent_memory` | ## Server clients These examples talk to a running `agdb_server` using one of the [API clients](https://agdb.agnesoft.com/api-docs/openapi). | Example | What it shows | Run | | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------- | | [Server client - Rust](https://agdb.agnesoft.com/docs/examples/server-client-rust) | Users, databases and query batches with `agdb_api` | `cargo run -p agdb_api --example server_client` | | [Server client - TypeScript](https://agdb.agnesoft.com/docs/examples/server-client-typescript) | The same flow with `@agnesoft/agdb_api` | `pnpm run examples --filter @agnesoft/agdb_api` | | [Server client - PHP](https://agdb.agnesoft.com/docs/examples/server-client-php) | The same flow with `agnesoft/agdb_api` in one batch | `pnpm run examples --filter agdb_api_php` | | [Server client - Python](https://agdb.agnesoft.com/docs/examples/server-client-python) | The same flow with the Python `agdb_api` in one batch | `pnpm run examples --filter agdb_api_python` | # App db ## What it shows The example creates an in-memory database (`DbMemory`) with a root node aliased `users`, inserts users as plain key-value nodes without any schema and links them to the root with edges. It then finds a user with a depth-first search filtered by `username` - the graph equivalent of `SELECT * FROM users WHERE username = "user1"` - and prints the id and the key-value pairs of the found element from the raw `QueryResult`. ## Run it ```bash cargo run -p agdb --example app_db ``` ## Inserting schemaless data Each node gets its own list of key-value pairs. There is no schema, so the second user can simply omit the `age`. The result of the insert is passed directly to the next query to connect the new nodes to the `users` root: ```rs // Inserts the raw data by providing list of keys and values // for each node. Notice we can easily create sparse data // omitting certain fields as there is no schema to enforce. let users = db.exec_mut( QueryBuilder::insert() .nodes() .values([ vec![ ("username", "user1").into(), ("password", "password123").into(), ("age", 20).into(), ], vec![ ("username", "user2").into(), ("password", "password456").into(), ], ]) .query(), )?; // Link the users with the "users" node. Note that we are referring to // the users node with an alias "users" we have given it and to // the new user nodes by supplying the result of the previous query directly. // One could also use the `QueryResult::ids()` method to extract the ids. db.exec_mut( QueryBuilder::insert() .edges() .from("users") .to(users) .query(), )?; ``` ## Searching and reading the result The search starts at `users` and returns only elements whose `username` is `user1`. The result always has the same shape: a numeric `result` and a list of `elements`, each with an `id` and its key-value pairs. Nodes have positive ids and edges negative ids: ```rs let user_result = db.exec( QueryBuilder::select() .search() .depth_first() .from("users") .where_() .key("username") .value("user1") .query(), )?; if user_result.result == 1 { println!("User: {:?}", user_result.elements[0].id); for key_value in user_result.elements[0].values.iter() { println!(" {}: {}", key_value.key, key_value.value); } } ``` ## Learn more - [Concepts](https://agdb.agnesoft.com/docs/guides/concepts) - graph, ids and data types. - [Queries reference](https://agdb.agnesoft.com/docs/references/queries) - [insert](https://agdb.agnesoft.com/docs/references/queries#insert), [search](https://agdb.agnesoft.com/docs/references/queries#search) and [conditions](https://agdb.agnesoft.com/docs/references/queries#conditions). - [User types](https://agdb.agnesoft.com/docs/examples/user-types) - the same data with Rust structs instead of raw key-values. # Indexes ## What it shows The example creates indexes on the `username` and `token` keys, inserts 100 users as typed `User` structs linked to a `users` root and then finds one user by looking up its `username` in the index instead of searching the graph. The result is converted straight back into a `User`. ## Run it ```bash cargo run -p agdb --example indexes ``` ## Creating indexes An index is created for a key. It can be created before or after the data is inserted - an index created later indexes all existing values of that key as well: ```rs // Create two indexes, one for username and one for token. They can just as well // be created later and will index all existing data as well. db.exec_mut(QueryBuilder::insert().index("username").query())?; db.exec_mut(QueryBuilder::insert().index("token").query())?; ``` ## Looking up by index The index search finds the element with the given value directly. This is useful when the data is too uniform to be split up on the graph - for example users looked up by their username or logged-in users looked up by a token: ```rs let user: User = db .exec( QueryBuilder::select() .values(User::db_keys()) .search() .index("username") .value("user50") .query(), )? .try_into()?; println!("{user:?}"); ``` ## Learn more - [Insert index](https://agdb.agnesoft.com/docs/references/queries#insert-index) and [remove index](https://agdb.agnesoft.com/docs/references/queries#remove-index) in the queries reference. - [Search](https://agdb.agnesoft.com/docs/references/queries#search) - index search versus graph search. - [Efficient agdb](https://agdb.agnesoft.com/docs/references/efficient-agdb) - when to model data on the graph and when to use an index. # Joins ## What it shows `agdb` has no join operator because the relations are stored directly as edges. The example models a user who has access to several databases, with the database `name` stored on the nodes and the user's `role` stored on the edges, and shows two ways to read both into one list of `UserDb { name, role }`. ## Run it ```bash cargo run -p agdb --example joins ``` ## Single search A depth-first search from the user returns edges and nodes in order: each edge (with `role`) is followed by the node it points to (with `name`). The sign of the id tells them apart - edges have negative ids: ```rs let mut user_dbs: Vec = vec![]; db.exec( QueryBuilder::select() .search() .depth_first() .from("user") .where_() .keys("role") .or() .keys("name") .query(), )? .elements .into_iter() .for_each(|e| { if e.id.0 < 0 { // handle the edge user_dbs.push(UserDb { role: e.values[0].value.to_string(), name: String::new(), }); } else { // handle the node user_dbs.last_mut().unwrap().name = e.values[0].value.to_string(); } }); ``` ## Multiple queries in a transaction When the data is sparse, or you need more control, run several queries inside one read transaction. All of them see the same consistent state of the database: ```rs let user_dbs = db.transaction(|t| -> Result, DbError> { let db_names = t.exec( QueryBuilder::select() .search() .from("user") .where_() .neighbor() .and() .keys("name") .query(), )?; let mut dbs = vec![]; for db_name in db_names.elements { let role = t.exec( QueryBuilder::select() .search() .to(db_name.id) .limit(1) .where_() .keys("role") .query(), )?; dbs.push(UserDb { name: db_name.values[0].value.to_string(), role: role.elements[0].values[0].value.to_string(), }); } Ok(dbs) })?; ``` ## Learn more - [Transactions](https://agdb.agnesoft.com/docs/references/queries#transactions) in the queries reference. - [Conditions](https://agdb.agnesoft.com/docs/references/queries#conditions) - `keys`, `neighbor`, `and`/`or` and more. - [Search](https://agdb.agnesoft.com/docs/references/queries#search) - search directions, `limit` and ordering. # Schema migration ## What it shows The example stores 100 users with an old schema (`name`, `status` as a string and `age`) and migrates them to a new one (`db_id`, `name` and `status` as an enum stored as a number). The whole migration runs in one mutable transaction, so it either fully succeeds or leaves the data untouched. ## Run it ```bash cargo run -p agdb --example schema_migration ``` ## Converting values in both directions The trick of the migration is in the conversions of the new `UserStatus` enum. Reading accepts both the old string values and the new numbers, while writing always stores numbers: ```rs impl TryFrom for UserStatus { type Error = DbError; fn try_from(value: DbValue) -> Result { match value.to_string().as_str() { "active" | "0" => Ok(Self::Active), "inactive" | "1" => Ok(Self::Inactive), "banned" | "2" => Ok(Self::Banned), _ => Err(DbError::db( agdb::DbErrorType::TypeError, "Invalid user status", )), } } } impl From for DbValue { fn from(value: UserStatus) -> Self { match value { UserStatus::Active => 0_u64.into(), UserStatus::Inactive => 1_u64.into(), UserStatus::Banned => 2_u64.into(), } } } ``` ## The migration Inside the transaction the obsolete `age` property is removed from all users, the users are loaded with the new schema (the conversion above accepts the old strings) and inserted back, which overwrites the `status` values with numbers: ```rs db.transaction_mut(|t| { // First remove the "age" property from all the users. t.exec_mut( QueryBuilder::remove() .values("age") .ids(QueryBuilder::search().from("users").query()) .query(), )?; let users: Vec = t .exec( QueryBuilder::select() .search() .from("users") .where_() .neighbor() .query(), )? .try_into()?; t.exec_mut(QueryBuilder::insert().elements(&users).query()) // NOTE: When migrating huge amount of data it would be better to do it in batches using // the `limit` and `offset` values in the search query. })?; ``` ## Learn more - [Transactions](https://agdb.agnesoft.com/docs/references/queries#transactions) in the queries reference. - [Remove values](https://agdb.agnesoft.com/docs/references/queries#remove-values) and [insert values](https://agdb.agnesoft.com/docs/references/queries#insert-values). - [DbType](https://agdb.agnesoft.com/docs/references/queries#dbtype) - how user types map to stored values. # User types ## What it shows The example shows the derive macros that let you use your own Rust types directly in queries: - `DbValue` + `DbSerialize` store an enum or a struct as a single value. - `DbTypeMarker` allows a type to be used in a `Vec` of values. - `DbType` maps a struct to the key-value pairs of a database element, with the `rename`, `skip` and `flatten` field attributes and optional fields. - `DbElement` additionally stores the type of the struct so that two types with the same fields can be told apart. ## Run it ```bash cargo run -p agdb --example user_types ``` The derive macros are part of the default `derive` feature of the `agdb` crate. ## Defining the types ```rs #[derive(Debug, Clone, DbSerialize, DbValue)] enum UserStatus { Active, Inactive, Banned, } // The empty trait `DbTypeMarker` (deriveable via // `agdb::DbTypeMarker`) is used to allow the user // types (structs & enums) to be used in vectorized // variants of the user types. #[derive(Debug, Clone, DbTypeMarker, DbSerialize, DbValue)] struct Property { name: String, value: String, } #[derive(Debug, DbType)] struct SubProperty { id: i32, } #[derive(Debug, DbType)] struct User { username: String, password: String, #[agdb(rename = "name")] display_name: Option, status: UserStatus, extra: Vec, #[agdb(skip)] _skipped: (), #[agdb(flatten)] sub: SubProperty, } ``` ## Telling overlapping types apart Types derived with `DbElement` store their type with each element, so a search can return only the elements of one type even when several types with the same fields are reachable from the same node - no extra conditions needed: ```rs let type1: T1 = db .exec( QueryBuilder::select() .element::() .search() .from("types") .query(), )? .try_into()?; let type2: T2 = db .exec( QueryBuilder::select() .element::() .search() .from("types") .query(), )? .try_into()?; ``` ## Learn more - [DbType](https://agdb.agnesoft.com/docs/references/queries#dbtype) in the queries reference. - [Data types](https://agdb.agnesoft.com/docs/guides/concepts#data-types) - which Rust types map to which database values. - [Quickstart](https://agdb.agnesoft.com/docs/guides/quickstart) - a step-by-step guide using user types. # Agent memory ## What it shows The example stores the long-term memory of an AI agent as a graph: a conversation with its messages, the entities the messages mention and the facts linking the entities. It then recalls the facts reachable from an entity as context for the next prompt, finds the messages mentioning an entity and forgets the conversation while keeping what was learned from it. See [agdb in the AI era](https://agdb.agnesoft.com/blog/ai-era) for the background. ## Run it ```bash cargo run -p agdb --example agent_memory ``` It prints the recalled facts, the messages mentioning `agdb` and the number of nodes left after forgetting the conversation: ```text agdb_server is built on agdb agdb is written in Rust [Message { db_id: Some(DbId(5)), role: "assistant", text: "Noted, and agdb is written in Rust." }, Message { db_id: Some(DbId(4)), role: "user", text: "agdb_server is built on agdb." }] Nodes after forgetting: 5 ``` ## The model Messages and entities are typed structs. The text of a message is only ever a value - it is never parsed as a query so it cannot inject anything into it: ```rs #[derive(Debug, DbType)] struct Message { db_id: Option, role: String, text: String, } #[derive(Debug, DbType)] struct Entity { db_id: Option, kind: String, name: String, } ``` The entities are indexed by `name` so that a name appearing in a new message can be looked up directly. The messages point to the entities they mention and the facts are edges between the entities: ```rs // Which message mentions which entity. t.exec_mut( QueryBuilder::insert() .edges() .from([message1, message1, message2, message2]) .to([server, database, database, rust]) .query(), )?; // The facts are edges between the entities. t.exec_mut( QueryBuilder::insert() .edges() .from([server, database]) .to([database, rust]) .values([ [("relation", "is built on").into()], [("relation", "is written in").into()], ]) .query(), )?; ``` ## Recall Starting at the entity, the search follows only the outgoing edges, so it traverses the facts and not the messages (they point to the entities, not the other way round). The distance condition selects the edges up to two hops away and also stops the search there: ```rs let facts = t.exec( QueryBuilder::select() .values("relation") .search() .from(*start) .where_() .edge() .and() .distance_less_than(4) .query(), )?; ``` Each returned edge has its `from` and `to` ids, so the names of both entities are selected to turn the fact into a line of text for the prompt. This recalls only the chain of facts starting at the entity, along the outgoing edges (`recall("Rust")` finds nothing). The facts pointing to the entity need a second search with `.to(entity)` filtered by `.keys("relation")` and bounded by a distance condition, as the incoming edges include the ones from the messages. ## Provenance The messages mentioning an entity are among its direct neighbours along the incoming edges (`to`). The `neighbor()` condition (distance 2) stops the search at them - without it the search would continue past them, e.g. to the messages mentioning `agdb_server`, which has a fact about `agdb`. The neighbours are the messages, the `entities` root and the entities with facts about this one; the `role` key keeps only the messages: ```rs let sources: Vec = db .exec( QueryBuilder::select() .elements::() .search() .to(database) .where_() .neighbor() .and() .keys("role") .query(), )? .try_into()?; ``` This is provenance per entity. To trace each fact to the message it was learned from, store the id of that message as a value on the fact edge (e.g. `("source", message_id)`). ## Forgetting Removing the conversation node and its messages (the nodes at distance 0 and 2) also removes their edges. The entities and the facts between them stay: ```rs let conversation = t.exec( QueryBuilder::search() .from(alias) .where_() .node() .and() .distance_less_than(3) .query(), )?; t.exec_mut(QueryBuilder::remove().ids(conversation).query())?; ``` ## Learn more - [Search](https://agdb.agnesoft.com/docs/references/queries#search) and its [conditions](https://agdb.agnesoft.com/docs/references/queries#conditions) in the queries reference. - [Transactions](https://agdb.agnesoft.com/docs/references/queries#transactions) - the memory is written and recalled in transactions. - [Indexes](https://agdb.agnesoft.com/docs/examples/indexes) - looking up elements by an indexed key. # 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: ```bash cargo run -p agdb_server ``` and in another one run the example: ```bash 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 ```rs 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`: ```rs #[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: ```rs 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](https://agdb.agnesoft.com/api-docs/rust) - installing and using `agdb_api`. - [Server reference](https://agdb.agnesoft.com/docs/references/server) - configuration, users, databases and the REST API. - [How to run a server?](https://agdb.agnesoft.com/docs/guides/how-to-run-server) # Server client - TypeScript ## What it shows The TypeScript version of the [Rust server client](https://agdb.agnesoft.com/docs/examples/server-client-rust) example using the `@agnesoft/agdb_api` package: it logs in as the admin, creates a user and a database and runs two batches of queries. Plain JavaScript objects are inserted as node values and the result of the first batch is passed directly to the second one. ## Run it From the repository root: ```bash pnpm run examples --filter @agnesoft/agdb_api ``` The script compiles the example, builds the `agdb_server` and runs the example against a freshly started server, so you do not need to start one yourself. The port 3000 must be free (stop any `agdb_server` you started yourself). ## Users and databases The TypeScript client takes named arguments as objects: ```ts const client = AgdbApi.new(new FetchClient(), "localhost:3000"); // Log in as admin and create a new user. await client.user_login({ username: "admin", password: "admin" }); await client.admin_user_add({ username: "client", password: "password111", }); // Switch to the new user and create a database. await client.user_login({ username: "client", password: "password111" }); await client.db_add({ owner: "client", db: "db", db_type: "memory" }); ``` ## Running queries ```ts const users = [ { username: "user1", password: "password123" }, { username: "user2", password: "password456" }, ]; // Insert a root "users" alias and the user nodes. let queries = [ QueryBuilder.insert().nodes().aliases(["users"]).query(), QueryBuilder.insert().nodes().values(users).query(), ]; let results = ( await client.db_exec_mut({ owner: "client", db: "db", queries }) )[1]; // Link users to root and search for one by username. queries = [ QueryBuilder.insert().edges().from("users").to(results[1]).query(), QueryBuilder.select() .search() .depth_first() .from("users") .where() .key("username") .value("user1") .query(), ]; results = (await client.db_exec_mut({ owner: "client", db: "db", queries }))[1]; console.log(`User: ${results[1].elements[0].id}`); for (const { key, value } of results[1].elements[0].values) { console.log(` ${JSON.stringify(key)}: ${JSON.stringify(value)}`); } ``` Note that `where_()` from Rust is `where()` in TypeScript. ## Learn more - [TypeScript client](https://agdb.agnesoft.com/api-docs/typescript) - installing and using `@agnesoft/agdb_api` in your project. - [Server reference](https://agdb.agnesoft.com/docs/references/server) # Server client - PHP ## What it shows The PHP version of the server client example using the `agnesoft/agdb_api` package. It checks the server status, logs in as the admin, creates a user and a memory mapped database and runs all queries in a single batch, linking the inserted nodes with references to the results of earlier queries in the same batch (`:0`, `:1`). ## Run it From the repository root: ```bash pnpm run examples --filter agdb_api_php ``` The script installs the Composer dependencies, builds the `agdb_server` and runs the example against a freshly started server. The port 3000 must be free (stop any `agdb_server` you started yourself). To use the client in your own project, add it with Composer: ```bash composer require agnesoft/agdb_api:dev-main ``` See the [PHP client](https://agdb.agnesoft.com/api-docs/php) page for details. ## Users and databases ```php require "vendor/autoload.php"; use Agnesoft\AgdbApi\AgdbApi; use Agnesoft\AgdbApi\CurlClient; use Agnesoft\AgdbApi\DbKind; use Agnesoft\AgdbApi\QueryBuilder; // Create the client using the native cURL transport. $client = AgdbApi::new(new CurlClient(), "localhost:3000"); // Runs the status query against the database // and throws if the server is not accessible. $client->status(); // Login as server admin. $client->user_login("admin", "admin"); // Create user "php_user1". $client->admin_user_add("php_user1", "php_user1"); // Login as "php_user1". $client->user_login("php_user1", "php_user1"); // Creates memory mapped database "db1" for user "php_user1". $client->db_add("php_user1", "db1", DbKind::Mapped); ``` ## One batch with result references Within a batch a query can refer to the result of an earlier query by its index prefixed with a colon. The edges are inserted from the result of query `:0` (the `users` root) to the result of query `:1` (the user nodes): ```php $queries = [ // :0: Inserts a root node aliased "users". QueryBuilder::insert() ->nodes() ->aliases(["users"]) ->query(), // :1: Inserts more nodes with some data. QueryBuilder::insert() ->nodes() ->values([ [ "username" => "user1", "password" => "password123", ], [ "username" => "user2", "password" => "password456", ], ]) ->query(), // :2: Connect the root to the inserted nodes with edges referencing both from previous queries. QueryBuilder::insert()->edges()->from(":0")->to(":1")->query(), // :3: Find a node starting at the "users" node with specific username. QueryBuilder::select() ->search() ->from("users") ->where() ->key("username") ->value("user1") ->query(), ]; // Execute the queries. $result = $client->db_exec_mut("php_user1", "db1", $queries); // Print the result of the last query. print_r($result[1][3]); ``` The client returns the HTTP status and the list of results, one per query, so `$result[1][3]` is the result of the search. ## Learn more - [PHP client](https://agdb.agnesoft.com/api-docs/php) - installing and using `agnesoft/agdb_api`. - [Server reference](https://agdb.agnesoft.com/docs/references/server) # Server client - Python ## What it shows The Python version of the server client example using the `agdb_api` Python package. It checks the server status, logs in as the admin, creates a user and a memory mapped database and runs all queries in a single batch, linking the inserted nodes with references to the results of earlier queries in the same batch (`:0`, `:1`). ## Run it From the repository root (requires [uv](https://docs.astral.sh/uv/){rel=""nofollow""}): ```bash pnpm run examples --filter agdb_api_python ``` The script builds the `agdb_server` and runs the example against a freshly started server. The port 3000 must be free (stop any `agdb_server` you started yourself). Against another server set the `AGDB_SERVER_ADDRESS` environment variable (default `localhost:3000`). To use the client in your own project, install it from the repository: ```bash pip install "git+https://github.com/agnesoft/agdb#subdirectory=agdb_api/python" ``` See the [Python client](https://agdb.agnesoft.com/api-docs/python) page for details. ## Users and databases ```python import os from agdb_api import AgdbApi, DbKind, QueryBuilder, UrllibClient # Create the client using the `urllib` transport of the standard library. client = AgdbApi.new( UrllibClient(), os.environ.get("AGDB_SERVER_ADDRESS", "localhost:3000") ) # Runs the status query against the server and raises if it is not # accessible. client.status() # Login as server admin. client.user_login("admin", "admin") # Create user "py_user1". client.admin_user_add("py_user1", "py_user1") # Login as "py_user1". client.user_login("py_user1", "py_user1") # Creates memory mapped database "db1" for user "py_user1". client.db_add("py_user1", "db1", DbKind.Mapped) ``` ## One batch with result references Within a batch a query can refer to the result of an earlier query by its index prefixed with a colon. The edges are inserted from the result of query `:0` (the `users` root) to the result of query `:1` (the user nodes): ```python queries = [ # :0: Inserts a root node aliased "users". QueryBuilder.insert().nodes().aliases(["users"]).query(), # :1: Inserts more nodes with some data. QueryBuilder.insert() .nodes() .values( [ {"username": "user1", "password": "password123"}, {"username": "user2", "password": "password456"}, ] ) .query(), # :2: Connect the root to the inserted nodes with edges referencing # both from previous queries. QueryBuilder.insert().edges().from_(":0").to(":1").query(), # :3: Find a node starting at the "users" node with specific username. QueryBuilder.select() .search() .from_("users") .where() .key("username") .value("user1") .query(), ] # Execute the queries. _, results = client.db_exec_mut("py_user1", "db1", queries) # Print the result of the last query. user = results[3].elements[0] print(f"User (id: {user.id})") for kv in user.values: print(f"{kv.key.to_json()}: {kv.value.to_json()}") ``` The client returns the HTTP status and the list of results, one per query, so `results[3]` is the result of the search. Names that are Python keywords get a trailing underscore (`from_`). ## Learn more - [Python client](https://agdb.agnesoft.com/api-docs/python) - installing and using the `agdb_api` Python package. - [Server reference](https://agdb.agnesoft.com/docs/references/server) # References overview In this section you will find complete references of all aspects of `agdb`: - [Queries](https://agdb.agnesoft.com/docs/references/queries) - every query, its builder, result and the database API. - [Derive macros](https://agdb.agnesoft.com/docs/references/derive-macros) - `DbType`, `DbElement`, `DbValue`, `DbSerialize`, `DbTypeMarker` and their attributes. - [Server](https://agdb.agnesoft.com/docs/references/server) - configuration, REST API, authentication and clustering of the `agdb_server`. - [Error codes](https://agdb.agnesoft.com/docs/references/error-codes) - server status codes and the errors of the database and the API clients. - [Studio](https://agdb.agnesoft.com/docs/references/studio) - serving the studio, its pages and URLs, keyboard shortcuts and limits. - [Cloud](https://agdb.agnesoft.com/docs/references/cloud) - self-hosted and managed cloud deployment options. - [Efficient agdb](https://agdb.agnesoft.com/docs/references/efficient-agdb) - designing a database and its queries for a realistic workload. - [Performance](https://agdb.agnesoft.com/docs/references/performance) - benchmarks and the principles behind `agdb` performance. # Queries All interactions with the `agdb` are realized through queries. There are two kinds of queries: - Immutable queries - Mutable queries Immutable queries read the data from the database through `select` and `search` queries. Mutable queries write to or delete from the database through `insert` and `remove` queries. Both kinds are executed through a shared reference to the database: ::note Mutable queries are serialized internally so only one of them runs at a time. Immutable queries run concurrently with each other and with the writer against the last committed snapshot. Share the database between threads as `Arc`, no additional lock is needed. :: The queries are executed against the database by calling the corresponding method on the database object: ```rs impl Db { // immutable queries only pub fn exec(&self, query: T) -> Result // mutable queries only pub fn exec_mut(&self, query: T) -> Result } ``` If a mutable query fails none of its changes are applied (the database is rolled back to the state before the query). Alternatively you can run a series of queries as a [transaction](https://agdb.agnesoft.com/#transactions). All queries return `Result`. The [`QueryResult`](https://agdb.agnesoft.com/#queryresult) is the universal data structure holding results of all queries in a uniform structure. The [`DbError`](https://agdb.agnesoft.com/#dberror) is the singular error type holding information of any failure or problem encountered when running the query. ## Types ### DbType The `DbType` trait is an interface that can be implemented for user defined types so that they can be seamlessly used with the database: ```rs pub trait DbType: Sized { type ValueType; fn db_id(&self) -> Option; fn db_keys() -> Vec; fn from_db_element(element: &DbElement) -> Result; fn to_db_values(&self) -> Vec; fn db_element_id() -> Option { None } } ``` Typically, you would derive this trait with `agdb::DbType` procedural macro that uses the field names as keys (of type `String`) and losslessly converts the values when reading/writing from/to the database from supported types (e.g. field type `i32` will become `i64` in the database). You can also use an alternative derive `agdb::DbElement` that acts like `agdb::DbType` but additionally implements the `db_element_id()` to return the type's name. It is then automatically used as additional property when using it with the `QueryBuilder`. When inserting type that derived `DbElement` an additional property `db_element_id` will be inserted for the given db element. Conversely, when select & searching elements the automatic condition matching the `db_element_id` with the type name is also inserted into the search. It is recommended but optional to have `db_id` field of type `DbId` or `Option>` (e.g. `Option` or `Option`) in your user defined types which will further allow you to directly update your values with query shorthands. However, it is optional, and all other features will still work including conversion from `QueryResult` or passing your types to `values()` in the builders or type matching when deriving from `DbElement`. The `agdb::DbType` macro also supports `Option`al types. When a value is `None` it will be omitted when saving the object to the database. Note that `db_keys()` returns an empty list for a struct with an `Option` field (other than `db_id`) as not all keys are guaranteed to be stored, so selecting with it (e.g. `select().values(User::db_keys())`, `elements::()`) selects all values of the element. Example: ```rs #[derive(DbType)] struct User { db_id: Option, name: String, } let user = User { db_id: None, name: "Bob".to_string() }; db.exec_mut(QueryBuilder::insert().nodes().values(user).query())?; let mut user: User = db.exec(QueryBuilder::select().values(User::db_keys()).ids(1).query())?.try_into()?; // User { db_id: Some(DbId(1)), name: "Bob" } user.name = "Alice".to_string(); db.exec_mut(QueryBuilder::insert().element(&user).query())?; //updates the user element with new name ``` The `#[derive(DbValue)]` and `#[derive(DbSerialize)]` macros support generic types (the generic parameters are carried over to the implementation) while `#[derive(DbType)]` and `#[derive(DbElement)]` support only non-generic structs. There is also a blanket `impl DbType for &T` so references work wherever `DbType` is expected (e.g. passing `&user` to `.values()`). You can optionally use `#[agdb(flatten)]` to flatten nested structs, `#[agdb(rename = "new_name")]` to disambiguate the duplicate keys (useful when flattening) or `#[agdb(skip)]` to omit a field (requires the field's type to implement `Default` unless it is an `Option`, which reads back as `None`). All the macros and attributes are described in the [derive macros](https://agdb.agnesoft.com/docs/references/derive-macros) reference. In some cases you may want to implement the `DbType` trait yourself if you want to do some additional transformation besides the supported ones by the derive macro. Additionally, you can use these supporting derive macros: ```rs #[derive(DbTypeMarker)] // allows using vectorized custom types, e.g. Vec in fields of user defined types. // It is a blank marker trait: `Vec` is convertible to `DbValue` only if // `T: Into + DbTypeMarker`. #[derive(DbValue)] // derives an implementation converting a user defined type // to DbValue for easy nesting of user defined types. // NOTE: it additionally requires agdb::AgdbSerialize trait to be implemented #[derive(DbSerialize)] // derives implementation of agdb::AgdbSerialize trait (includes both serialize and deserialize) for user defined types ``` Types not directly used in the database but for which the conversions are supported: - u32 <=> u64 - i32 <=> i64 - f32 <=> f64 - Vec :i32[ <=> Vec :i64] - Vec :u32[ <=> Vec :u64] - Vec :f32[ <=> Vec :f64] - \&str => String (only one way conversion to `String`) - Vec<\&str> => Vec :string[ (only one way conversion to `Vec`)] - bool (\*) \* The boolean type is not a native type in the `agdb`, but you can still use it in your types in any language. The `bool` type will be converted to `u64` (0 == false, 1 == true). The `Vec` type will be converted to `Vec` (`VecU64`, 0 == false, 1 == true). The conversion back to `bool` is possible from wider range of values - the same rules apply for vectorized version which however cannot be converted to from single values: - u64 / i64: any non-zero value will be `true` - f64: any value except `0.0` will be `true` - string: only `"true"` or `"1"` will be `true` ### QueryResult The `QueryResult` is the universal result type for all successful queries. It can be converted to user defined types that implement [`DbType`](https://agdb.agnesoft.com/#dbtype) with `try_into()`. It looks like this: ```rs pub struct QueryResult { pub result: u64, pub elements: Vec, } ``` The `result` field holds numerical result of the query. It typically returns the number of database items affected. For example when selecting from the database it will hold the number of elements returned. When removing from the database it will hold the number of elements deleted from the database. The `QueryResult` also provides a convenience method `ids()` that extracts the `DbId` of every element in the result — useful for chaining query results: ```rs let nodes = db.exec_mut(QueryBuilder::insert().nodes().count(3).query())?; db.exec_mut(QueryBuilder::insert().edges().from("root").to(nodes.ids()).query())?; ``` The `elements` field hold the [database elements](https://agdb.agnesoft.com/docs/guides/concepts#graph) returned. Each element looks like: ```rs pub struct DbElement { pub id: DbId, pub from: DbId, // edge: origin node id; node: first outgoing edge id (0 if none) pub to: DbId, // edge: destination node id; node: first incoming edge id (0 if none) pub values: Vec, } ``` The `id` (i.e. `pub struct DbId(i64)`) is a numerical identifier of a database element. Positive number means the element is a `node` while negative number means the element is an `edge`. The value `0` is a special value signifying no valid element and is used when certain queries return data not related to any particular element, e.g. aliases. For **edge** elements, `from` and `to` are the origin and destination node ids respectively. For **node** elements, `from` holds the id of the first outgoing edge and `to` holds the id of the first incoming edge (`DbId(0)` if there are none). This allows traversal of the edge list from a node result without an additional query. The values are `key-value` pairs (properties) associated with the given element: ```rs pub struct DbKeyValue { pub key: DbValue, pub value: DbValue, } ``` Where `DbValue` is: ```rs pub enum DbValue { Bytes(Vec), I64(i64), U64(u64), F64(DbF64), String(String), VecI64(Vec), VecU64(Vec), VecF64(Vec), VecString(Vec), VecDbValue(Vec), // heterogeneous list None, // no value, the value of a key that is a label } ``` Note the `DbF64` type (i.e. `pub struct DbF64(f64)`) which is a convenient wrapper of `f64` to provide opinionated implementation of some of the operations that are not floating type friendly like comparisons. In `agdb` the float type is using [`total_cmp` standard library function](https://doc.rust-lang.org/std/primitive.f64.html#method.total_cmp){rel=""nofollow""}. Please see its documentation for important details about possible limits or issues on certain platforms. The enum variants can be conveniently accessed through methods named after each variant: ```rs fn bytes(&self) -> Result<&Vec, DbError>; fn to_bool(&self) -> Result; fn to_f64(&self) -> Result; fn to_i64(&self) -> Result; fn to_u64(&self) -> Result; fn to_string(&self) -> String; fn string(&self) -> Result<&String, DbError>; fn vec_f64(&self) -> Result<&Vec, DbError>; fn vec_i64(&self) -> Result<&Vec, DbError>; fn vec_u64(&self) -> Result<&Vec, DbError>; fn vec_string(&self) -> Result<&Vec, DbError>; fn vec_db_value(&self) -> Result<&Vec, DbError>; fn vec_bool(&self) -> Result, DbError>; ``` The numerical variants (`I64`, `U64`, `DbF64`) will attempt loss-less conversions where possible (e.g. `to_f64()` accepts only integers exactly representable as `f64`: `i64` in `-(2^53)..=2^53` and `u64` in `0..=2^53`). To avoid copies all other variants return `&` where conversions are not possible even if they could be done in theory. The special case is `to_string()` provided by the `Display` trait. It converts any values into string (it also copies the `String` variant) and performs possibly lossy conversion from `Bytes` to UTF-8 string. For `bool` conversion details refer to [DbType](https://agdb.agnesoft.com/#dbtype) section. Two conversions into `DbValue` are deliberately lenient: a `PathBuf` that is not valid UTF-8 is stored as `String` with the invalid sequences replaced by `U+FFFD` (it does not round trip) and a vector of values is stored as the vector variant of the type of its first element if all other elements convert to it (e.g. `[I64(1), U64(2)]` becomes `VecI64` but `[U64(2), I64(1)]` becomes `VecU64`), which may surprise users of other languages, otherwise it stays a `VecDbValue`. Additionally, several standard library types implement `Into` and `TryFrom` for convenient conversion — they are stored as their string or byte representation: - `PathBuf` (stored as `String`) - `SystemTime` (stored as `Bytes` — its serialized form) - `SocketAddr` (stored as `String`) - `IpAddr` (stored as `String`) `Vec` where `T: Into + DbTypeMarker` (implemented e.g. for the types above and for your types deriving `DbTypeMarker`) is automatically converted to the matching typed vector (`VecI64`, `VecU64`, `VecF64`, `VecString`) if all its elements convert to the type of the first one, otherwise to `VecDbValue`, allowing heterogeneous lists of any supported type. ### DbError Failure when running a query is reported through a `DbError` which carries a `category` (what subsystem failed), a `ty` (what kind of failure), a human-readable `description`, an optional `cause` chain, and the source location where the error originated. All the error types are listed in the [error codes](https://agdb.agnesoft.com/docs/references/error-codes#embedded-errors) reference. ```rs pub struct DbError { pub description: String, pub category: DbErrorCategory, // Collections, Db, Graph, Query, Serialization, Storage pub ty: DbErrorType, // DbCreate, InvalidIndex, NotAllowed, NotEnoughData, // NotFound, OutOfBounds, Poisoned, TypeError pub cause: Option>, pub source_location: Location<'static>, } ``` Most commonly you will encounter **query** errors (`NotFound` for missing ids/aliases, `TypeError` for value mismatches) or **data** errors. Convenience constructors like `DbError::query(ty, description)` or `DbError::db(ty, description)` create errors in the most common categories. It is up to the client code to handle the errors. ### QueryId, QueryIds Most queries operate over a set of database `ids`. The `QueryIds` type is actually an enum: ```rs pub enum QueryIds { Ids(Vec), Search(SearchQuery), } ``` It represents either a set of actual `ids` or a `search` query that will be executed as the larger query and its results fed as `ids` to the larger query. The `QueryId` is defined as another enum: ```rs pub enum QueryId { Id(DbId), Alias(String), } ``` This is because you can refer to the database elements via their numerical identifier or by the `string` alias (name). The `DbId` is then just a wrapper type: `pub struct DbId(pub i64)`. Both `QueryIds` and `QueryId` can be constructed from large number of different types like raw `i64`, `&str`, `String` or vectors of those etc. ### QueryValues The `QueryValues` is an enum type that makes a distinction between singular and multiple values like so: ```rs pub enum QueryValues { Single(Vec), Multi(Vec>), } ``` This is especially important because it can change the meaning of a query making use of this type. For example when inserting elements into the database and supplying `QueryValues::Single` all the elements will have the copy of the single set of properties associated with them. Conversely, `QueryValues::Multi` will initialize each element with a different provided set of properties but the number of inserted elements and the number of property sets must then match (it would be a query logic error if they did not match and the query would fail with such an error). ## Mutable queries Mutable queries are the way to modify the data in the database. Remember there can only be a mutable query running against the database at any one time (other mutable queries wait for it) while immutable queries keep running concurrently against the last committed snapshot. There are two types of mutable queries: - insert - remove The `insert` queries are used for both insert and updating data while `remove` queries are used to delete data from the database. ## Immutable queries Immutable queries read the data from the database and there can be an unlimited number of concurrent queries running against the database at the same time, including while a mutable query is running (they see the last committed state). There are two types of immutable queries: - select - search The `select` queries are used to read the data from the database using known `id`s of elements. The `search` queries are used to find the `id`s and the result of search queries is thus often combined with the `select` queries. ## Transactions You can run a series of queries as a transaction invoking corresponding methods on the database object: ```rs impl Db { // immutable transaction pub fn transaction>(&self, f: impl FnOnce(&Transaction) -> Result) -> Result // mutable transaction pub fn transaction_mut>(&self, f: impl FnOnce(&mut TransactionMut) -> Result) -> Result } ``` The transaction methods take a closure that itself takes a transaction object as an argument. This is to prevent long-lived transactions and force them to be as concise as possible. The transaction objects implement the same execution methods as the `Db` itself (`exec` / `exec_mut`). It is not possible to nest transactions, but you can run immutable queries within a mutable transaction `TransactionMut`. Note that you cannot manually abort, rollback or commit the transaction. These are handled by the database itself based on the result of the closure. If it's `Ok` the transaction will be committed (in case of the `mutable` queries as there is nothing to commit for `immutable` queries). If the result is `Err` the transaction will be rolled back. A mutable transaction is also rolled back when any of its mutable queries fails, even if the closure handles that error and returns `Ok`. An immutable transaction reads a consistent snapshot of the last commit and does not block the writer. To write after reading run a short mutable transaction that only writes and resolves its targets again (by alias, index or search condition) as the ids read earlier are not stable across commits. In both cases the result will be returned and the signature of the transaction methods allows for custom mapping of the default `Result` to an arbitrary `` result-error pair. Worth noting is that regular `exec / exec_mut` methods on the `Db` object are actually implemented as transactions. ## Database methods Besides running queries the `Db` object provides a few methods for managing the database itself. All take `&self`: - `backup(filename)` - flushes and copies the database to `filename` (waits for the running write transaction, reads keep running) - `copy(filename)` - copies the database to `filename` and returns it as a new `Db` with the same storage config - `rename(filename)` - renames the database (and its files for file based storage) - `restore(filename)` - atomically replaces the content of the database with the database at `filename`. A missing `filename` creates an empty database, so the content is replaced with nothing. Reads that started before the call still see the old data - `optimize_storage()` - defragments the storage file - `size()` - size of the database in bytes - `sync()` - flushes the buffered data to durable storage - `sync_mode()` / `set_sync_mode(mode)` - gets / sets the [`SyncMode`](https://agdb.agnesoft.com/docs/guides/concepts#storage) - `storage_config()` / `set_storage_config(config)` - gets / sets the `StorageConfig` (sync mode, overlay limit, memory limit) - `filename()` - the name the database was created with None of these methods may be called from within a transaction (they wait for or exclude the running write transaction). ## Insert There are 5 distinct insert queries: - insert aliases - insert edges - insert nodes - insert index - insert values ### Insert aliases | **Struct** | **Result** | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | ```rs pub struct InsertAliasesQuery { pub ids: QueryIds, pub aliases: Vec, } ``` | ```rs pub struct QueryResult { pub result: u64, // number of inserted/updated aliases pub elements: Vec, // empty } ``` | | **Builder** | | | ```rs QueryBuilder::insert().aliases("a").ids(1).query(); QueryBuilder::insert().aliases("a").ids("b").query(); // alias "b" is replaced with "a" QueryBuilder::insert().aliases(["a", "b"]).ids([1, 2]).query(); QueryBuilder::insert().aliases(["a"]).ids(QueryBuilder::search().from("root").where_().node().query()).query(); // aliases from search results ``` | | Inserts or updates aliases of existing nodes (and only nodes, edges cannot have aliases) through this query. It takes `ids` [`QueryIds`](https://agdb.agnesoft.com/#queryid-queryids) and list of `aliases` as arguments. The number of aliases must match the `ids` (even if they are a search query). Empty alias (`""`) are not allowed. Note that this query is also used for updating existing aliases. By inserting a different alias of an `id` that already has one that alias will be overwritten with the new one. ### Insert edges | **Struct** | **Result** | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ```rs pub struct InsertEdgesQuery { pub from: QueryIds, pub to: QueryIds, pub ids: QueryIds, pub values: QueryValues, pub each: bool, } ``` | ```rs pub struct QueryResult { pub result: u64, // number of inserted edges pub elements: Vec, // list of inserted edges (only ids) } ``` | | **Builder** | | | ```rs QueryBuilder::insert().edges().from(1).to(2).query(); QueryBuilder::insert().edges().from("a").to("b").query(); QueryBuilder::insert().edges().from("a").to([1, 2]).query(); QueryBuilder::insert().edges().from([1, 2]).to([2, 3]).query(); QueryBuilder::insert().edges().from([1, 2]).to([2, 3]).each().query(); QueryBuilder::insert().edges().from("a").to([1, 2]).values([[("k", 1).into()], [("k", 2).into()]]).query(); QueryBuilder::insert().edges().from("a").to([1, 2]).values_uniform([("k", "v").into(), (1, 10).into()]).query(); QueryBuilder::insert().edges().from(QueryBuilder::search().from("a").where_().node().query()).to(QueryBuilder::search().from("b").where_().node().query()).query(); QueryBuilder::insert().edges().from(QueryBuilder::search().from("a").where_().node().query()).to(QueryBuilder::search().from("b").where_().node().query()).values([[("k", 1).into()], [("k", 2).into()]]).query(); QueryBuilder::insert().edges().from(QueryBuilder::search().from("a").where_().node().query()).to(QueryBuilder::search().from("b").where_().node().query()).values_uniform([("k", "v").into(), (1, 10).into()]).query(); QueryBuilder::insert().edges().ids(-3).from(1).to(2).query(); QueryBuilder::insert().edges().ids([-3, -4]).from(1).to(2).query(); QueryBuilder::insert().edges().ids(QueryBuilder::search().from(1).where_().edge().query()).from(1).to(2).query(); ``` | | The `from` and `to` represents list of origins and destinations of the edges to be inserted. As per [`QueryIds`](https://agdb.agnesoft.com/#queryid-queryids) it can be a list, single value, search query or even a result of another query (e.g. [insert nodes](https://agdb.agnesoft.com/#insert-nodes)) through the call of convenient `QueryResult::ids()` method. All `ids` must be `node`s and all must exist in the database otherwise data error will occur. If `from` or `to` resolves to no nodes (an empty list or a search that found nothing) the query succeeds and inserts nothing, which allows "search and insert if found" without a transaction. If the `values` is [`QueryValues::Single`](https://agdb.agnesoft.com/#queryvalues) all edges will be associated with the copy of the same properties. If `values` is [`QueryValues::Multi`](https://agdb.agnesoft.com/#queryvalues) then the number of edges being inserted must match the provided values otherwise a logic error will occur. By default, the `from` and `to` are expected to be of equal length specifying at each index the pair of nodes to connect with an edge. If all-to-all is desired set the `each` flag to `true`. The rule about the `values` [`QueryValues::Multi`](https://agdb.agnesoft.com/#queryvalues) still applies though so there must be enough values for all nodes resulting from the combination. The values can be inferred from user defined types if they implement `DbType` trait (`#derive(agdb::DbType)`). Both singular and vectorized versions are supported. Optionally one can specify `ids` that facilitates insert-or-update semantics. The field can be a search sub-query. If the resulting list in `ids` is empty the query will insert edges as normal. If the list is not empty all `ids` must exist and refer to existing edges and the query will perform update of values instead. Note: the specified from/to (origin/destination) for the updated edges is not checked against those supplied via `ids`. ### Insert index | **Struct** | **Result** | | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- | | ```rs pub struct InsertIndexQuery(pub DbValue); ``` | ```rs pub struct QueryResult { pub result: u64, // number of indexed values pub elements: Vec, // empty } ``` | | **Builder** | | | ```rs QueryBuilder::insert().index("key").query(); ``` | | Creates an index for a key. The index is valid for the entire database including any and all existing values in the database. The purpose of the index is to provide faster lookup for data that is not modelled on the graph itself. Example can be looking up users by their username or token. ### Insert nodes | **Struct** | **Result** | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ```rs pub struct InsertNodesQuery { pub count: u64, pub values: QueryValues, pub aliases: Vec, pub ids: QueryIds, } ``` | ```rs pub struct QueryResult { pub result: u64, // number of inserted nodes pub elements: Vec, // list of inserted nodes (only ids) } ``` | | **Builder** | | | ```rs QueryBuilder::insert().nodes().count(2).query(); QueryBuilder::insert().nodes().count(2).values_uniform([("k", "v").into(), (1, 10).into()]).query(); QueryBuilder::insert().nodes().aliases(["a", "b"]).query(); QueryBuilder::insert().nodes().aliases(["a", "b"]).values([[("k", 1).into()], [("k", 2).into()]]).query(); QueryBuilder::insert().nodes().aliases(["a", "b"]).values_uniform([("k", "v").into(), (1, 10).into()]).query(); QueryBuilder::insert().nodes().values([[("k", 1).into()], [("k", 2).into()]]).query(); QueryBuilder::insert().nodes().ids(1).count(1).query(); QueryBuilder::insert().nodes().ids([1, 2]).count(1).query(); QueryBuilder::insert().nodes().ids("a").count(1).query(); QueryBuilder::insert().nodes().ids("a").aliases("a").query(), QueryBuilder::insert().nodes().ids(["a", "b"]).count(1).query(); QueryBuilder::insert().nodes().ids([1, 2]).values([[("k", "v").into()], [(1, 10).into()]]).query(), QueryBuilder::insert().nodes().ids([1, 2]).values_uniform([("k", "v").into(), (1, 10).into()]).query(), QueryBuilder::insert().nodes().ids(QueryBuilder::search().from(1).query()).count(1).query(); ``` | | The `count` is the number of nodes to be inserted into the database. It can be omitted (left `0`) if either `values` or `aliases` (or both) are provided. If the `values` is [`QueryValues::Single`](https://agdb.agnesoft.com/#queryvalues) you must provide either `count` or `aliases`. It is not an error if the count is set to `0`, but the query will be a no-op and return empty result. If both `values` [`QueryValues::Multi`](https://agdb.agnesoft.com/#queryvalues) and `aliases` are provided their lengths must be compatible (aliases <= values), otherwise it will result in a logic error. Empty aliases (`""`) are not allowed. The values can be inferred from user defined types if they implement `DbType` trait (`#derive(agdb::DbType)`). Both singular and vectorized versions are supported. Optionally one can specify `ids` that facilitates insert-or-update semantics. The field can be a search sub-query. If the resulting list in `ids` is empty the query will insert nodes as normal. If the list is not empty all `ids` must exist and must refer to nodes and the query will perform update instead - both aliases (replacing existing ones if applicable) and values. If an alias already exists in the database its values will be amended (inserted or replaced) with the provided values. ### Insert values | **Struct** | **Result** | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | ```rs pub struct InsertValuesQuery { pub ids: QueryIds, pub values: QueryValues, } ``` | ```rs pub struct QueryResult { pub result: u64, // number of inserted key-value pairs pub elements: Vec, // list of new elements } ``` | | **Builder** | | | ```rs QueryBuilder::insert().element(&T { ... }).query(); //Where T: DbType (i.e. #derive(agdb::DbType)) QueryBuilder::insert().elements(&vec![T {...}, T {...}]).query(); //Where T: DbType (i.e. #derive(agdb::DbType)) QueryBuilder::insert().values([vec![("k", "v").into(), (1, 10).into()], vec![("k", 2).into()]]).ids([1, 2]).query(); QueryBuilder::insert().values([vec![("k", "v").into(), (1, 10).into()], vec![("k", 2).into()]]).ids(QueryBuilder::search().from("a").query()).query(); QueryBuilder::insert().values([vec![("k", "v").into(), (1, 10).into()], vec![("k", 2).into()]]).search().from("a").query(); //Equivalent to the previous query QueryBuilder::insert().values_uniform([("k", "v").into(), (1, 10).into()]).ids([1, 2]).query(); QueryBuilder::insert().values_uniform([("k", "v").into(), (1, 10).into()]).ids(QueryBuilder::search().from("a").query()).query(); QueryBuilder::insert().values_uniform([("k", "v").into(), (1, 10).into()]).search().from("a").query(); //Equivalent to the previous query ``` | | Inserts or updates key-value pairs (properties) of existing elements or insert new elements (nodes). You need to specify the `ids` [`QueryIds`](https://agdb.agnesoft.com/#queryid-queryids) and the list of `values`. The `values` can be either [`QueryValues::Single`](https://agdb.agnesoft.com/#queryvalues) that will insert the single set of properties to all elements identified by `ids` or [`QueryValues::Multi`](https://agdb.agnesoft.com/#queryvalues) that will insert to each `id` its own set of properties, but their number must match the number of `ids`. If the user defined type contains `db_id` field of type `Option>` you can use the shorthand `insert().element() / .insert().elements()` that will infer the values and `ids` from your types. The `values()` will be inferred from user defined types if they implement `DbType` trait (`#derive(agdb::DbType)`). Both singular and vectorized versions are supported. - If an `id` is non-0 or an existing alias that element will be updated in the database with provided values. - If an `id` is `0` or a non-existent alias new element (node) will be inserted into the database with that alias. Note: that this query is insert-or-update for both nodes and existing values. By inserting the same `key` its old value will be overwritten with the new one. ### Value amendments Instead of replacing a value outright you can modify it in place with amendment operations. Amendments are available on both `insert` and `remove` builders: ```rs // Amend-add: add to numeric values (saturating), append to strings/vectors QueryBuilder::insert().amend([vec![("score", 10).into()]]).ids(1).query(); QueryBuilder::insert().amend_uniform([("score", 10).into()]).ids([1, 2]).query(); // Amend-remove: subtract from numeric values, remove every occurrence from strings and the first occurrence from vectors QueryBuilder::remove().amend([vec![("tags", "old").into()]]).ids(1).query(); QueryBuilder::remove().amend_uniform([("tags", "old").into()]).ids([1, 2]).query(); // Bitwise operations on integer/byte values QueryBuilder::insert().amend_or([vec![("flags", 0x04_u64).into()]]).ids(1).query(); QueryBuilder::insert().amend_and([vec![("mask", 0xFF_u64).into()]]).ids(1).query(); QueryBuilder::insert().amend_xor([vec![("toggle", 0x01_u64).into()]]).ids(1).query(); // Uniform variants: amend_or_uniform, amend_and_uniform, amend_xor_uniform // The same bitwise operations exist on the remove builder (e.g. remove().amend_or(), remove().amend_or_uniform()) QueryBuilder::remove().amend_or([vec![("flags", 0x04_u64).into()]]).ids(1).query(); ``` The query is the same `InsertValuesQuery` with its `amend` field set (`Amend::Add`, `Amend::Remove`, `Amend::AddBitwise(BitwiseOp)` or `Amend::RemoveBitwise(BitwiseOp)`; the default `Amend::None` overwrites). The `insert()` builders use the "add" context, the `remove()` builders the "remove" context. They differ for the values that are not integers or bytes (the bitwise operation falls back to the plain add or remove semantics) and for a key that does not exist on the element: the add context inserts the value as is, while the remove context does nothing. Amendment behavior depends on the value type: | Type | `insert().amend()` | `remove().amend()` | Bitwise (`amend_or` / `amend_and` / `amend_xor`) | | ------------ | -------------------------------------------- | -------------------------------------- | ------------------------------------------------ | | `I64`, `U64` | Saturating addition | Saturating subtraction | Bitwise OR / AND / XOR applied directly | | `F64` | Floating-point addition | Floating-point subtraction | Falls back to add/remove semantics | | `String` | Concatenation | Remove all occurrences of substring | Falls back to add/remove semantics | | `Bytes` | Byte vector extension | Not supported (returns error) | Byte-level OR / AND / XOR | | `Vec*` | Extend with elements (or push single scalar) | Remove first matching element per item | Falls back to add/remove semantics | Types must be compatible — amending an `I64` with a `String` will return an error. ## Remove There are 4 distinct remove queries: - remove aliases - remove (elements) - remove index - remove values ### Remove aliases | **Struct** | **Result** | | ---------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | | ```rs pub struct RemoveAliasesQuery(pub Vec); ``` | ```rs pub struct QueryResult { pub result: u64, // number of removed aliases pub elements: Vec, // empty } ``` | | **Builder** | | | ```rs QueryBuilder::remove().aliases("a").query(); QueryBuilder::remove().aliases(["a", "b"]).query(); ``` | | The aliases listed will be removed from the database if they exist. It is NOT an error if the aliases do not exist in the database. ### Remove elements | **Struct** | **Result** | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ```rs pub struct RemoveQuery(pub QueryIds); ``` | ```rs pub struct QueryResult { pub result: u64, // number of removed ids // (does not include removed edges // unless listed in query ids) pub elements: Vec, // empty } ``` | | **Builder** | | | ```rs QueryBuilder::remove().ids(1).query(); QueryBuilder::remove().ids("a").query(); QueryBuilder::remove().ids([1, 2]).query(); QueryBuilder::remove().ids(["a", "b"]).query(); QueryBuilder::remove().ids(QueryBuilder::search().from("a").query()).query(); QueryBuilder::remove().search().from("a").query(); //Equivalent to the previous query ``` | | The elements identified by [`QueryIds`](https://agdb.agnesoft.com/#queryid-queryids) will be removed from the database if they exist. It is NOT an error if the elements to be removed do not exist in the database. All associated properties (key-value pairs) are also removed from all elements. Removing nodes will also remove all their edges (incoming and outgoing) and their properties. ### Remove index | **Struct** | **Result** | | ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ```rs pub struct RemoveIndexQuery(pub DbValue); ``` | ```rs pub struct QueryResult { pub result: u64, // number of values removed // from the index pub elements: Vec, // empty } ``` | | **Builder** | | | ```rs QueryBuilder::remove().index("key").query(); ``` | | Removes an index from the database. It is NOT an error if the index does not exist in the database. ### Remove values | **Struct** | **Result** | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ```rs pub struct RemoveValuesQuery(pub SelectValuesQuery); ``` | ```rs pub struct QueryResult { pub result: u64, // number of actually removed // key-value pairs pub elements: Vec, // empty } ``` | | **Builder** | | | ```rs QueryBuilder::remove().values(["k1", "k2"]).ids([1, 2]).query(); QueryBuilder::remove().values(["k1", "k2"]).ids(QueryBuilder::search().from("a").query()).query(); QueryBuilder::remove().values(["k1", "k2"]).search().from("a").query(); //Equivalent to the previous query ``` | | NOTE: See [`SelectValuesQuery`](https://agdb.agnesoft.com/#select-values) for more details. The properties (key-value pairs) identified by `keys` and associated with `ids` [`QueryIds`](https://agdb.agnesoft.com/#queryid-queryids) will be removed from the database if they exist. It is an error if any of the `ids` do not exist in the database, but it is NOT an error if any of the keys does not exist or is not associated as property to any of the `ids`. ## Select There are following select queries: - select aliases - select all aliases - select all edge count - select edge count - select (elements) - select indexes - select keys - select key count - select values ### Select aliases | **Struct** | **Result** | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ```rs pub struct SelectAliasesQuery(pub QueryIds); ``` | ```rs pub struct QueryResult { pub result: u64, // number of returned elements pub elements: Vec, // list of elements each with // a single property // (`String("alias")`: `String`) } ``` | | **Builder** | | | ```rs QueryBuilder::select().aliases().ids([1, 2]).query(); QueryBuilder::select().aliases().ids(QueryBuilder::search().from(1).query()).query(); QueryBuilder::select().aliases().search().from(1).query(); //Equivalent to the previous query ``` | | Selects aliases of the `ids` [`QueryIds`](https://agdb.agnesoft.com/#queryid-queryids) or a search. If any of the `ids` does not have an alias running the query will return an error. ### Select all aliases | **Struct** | **Result** | | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ```rs pub struct SelectAllAliasesQuery {} ``` | ```rs pub struct QueryResult { pub result: u64, // number of elements with aliases pub elements: Vec, // list of elements with an // alias each with a single // property (`String("alias"): String`) } ``` | | **Builder** | | | ```rs QueryBuilder::select().aliases().query(); ``` | | Selects all aliases in the database. ### Select all edge count | **Struct** | **Result** | | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | ```rs pub struct SelectAllEdgeCountQuery {} ``` | ```rs pub struct QueryResult { pub result: u64, // Count of edges in the database pub elements: Vec, // empty list of elements } ``` | | **Builder** | | | ```rs QueryBuilder::select().edge_count().query(); ``` | | Selects number (count) of edges in the database. Unlike the edge count of the elements each edge is counted once, including the self-referential ones. ### Select edge count | **Struct** | **Result** | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ```rs pub struct SelectEdgeCountQuery { pub ids: QueryIds, pub from: bool, pub to: bool } ``` | ```rs pub struct QueryResult { pub result: u64, // Sum of all edge_counts in all selected elements pub elements: Vec, // list of elements with an // edge count each with a single // property (`String("edge_count")`: `u64`) } ``` | | **Builder** | | | ```rs QueryBuilder::select().edge_count().ids([1, 2]).query(); QueryBuilder::select().edge_count_from().ids([1, 2]).query(); QueryBuilder::select().edge_count_to().ids([1, 2]).query(); QueryBuilder::select().edge_count().ids(QueryBuilder::search().from("a").query()).query(); QueryBuilder::select().edge_count().search().from("a").query(); // Equivalent to the previous query ``` | | Selects count of edges of nodes (`ids`). The `edge_count` variant counts all edges (outgoing & incoming). The `edge_count_from` counts only outgoing edges. The `edge_count_to` counts only incoming edges. NOTE: Self-referential edges (going from the same node to the same node) will be counted twice in the first variant (`edge_count`) as the query counts outgoing/incoming edges rather than unique database elements. As a result the `edge_count` result may be higher than the actual number of physical edges in such a case. ### Select indexes | **Struct** | **Result** | | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ```rs pub struct SelectIndexesQuery {} ``` | ```rs pub struct QueryResult { pub result: u64, // number of indexes in the database pub elements: Vec, // single element with id 0 and list of // properties representing each index // (`DbValue`: `u64`) where the key is // the indexed key and the value is number // of indexed values in the index. } ``` | | **Builder** | | | ```rs QueryBuilder::select().indexes().query(); ``` | | Selects all indexes in the database. ### Select keys | **Struct** | **Result** | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ```rs pub struct SelectKeysQuery(pub QueryIds); ``` | ```rs pub struct QueryResult { pub result: u64, // number of returned elements pub elements: Vec, // list of elements with only keys // values will be `None` } ``` | | **Builder** | | | ```rs QueryBuilder::select().keys().ids("a").query(); QueryBuilder::select().keys().ids([1, 2]).query(); QueryBuilder::select().keys().ids(QueryBuilder::search().from(1).query()).query(); QueryBuilder::select().keys().search().from(1).query(); // Equivalent to the previous query ``` | | Selects elements identified by `ids` [`QueryIds`](https://agdb.agnesoft.com/#queryid-queryids) or search query with only keys returned. If any of the `ids` does not exist in the database running the query will return an error. This query is most commonly used for establishing what data is available in on the graph elements (e.g. when transforming the data into a table this query could be used to populate the column names). ### Select key count | **Struct** | **Result** | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ```rs pub struct SelectKeyCountQuery(pub QueryIds); ``` | ```rs pub struct QueryResult { pub result: u64, // sum value of all key_counts from all selected elements pub elements: Vec, // list of elements each with a // single property // (`String("key_count")`: `u64`) } ``` | | **Builder** | | | ```rs QueryBuilder::select().key_count().ids("a").query(); QueryBuilder::select().key_count().ids([1, 2]).query(); QueryBuilder::select().key_count().ids(QueryBuilder::search().from(1).query()).query(); QueryBuilder::select().key_count().search().from(1).query(); // Equivalent to the previous query ``` | | Selects elements identified by `ids` [`QueryIds`](https://agdb.agnesoft.com/#queryid-queryids) or search query with only key count returned. If any of the `ids` does not exist in the database running the query will return an error. This query is most commonly used for establishing how many properties there are associated with the graph elements. ### Select node count | **Struct** | **Result** | | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | ```rs pub struct SelectNodeCountQuery {} ``` | ```rs pub struct QueryResult { pub result: u64, // Count of nodes in the database pub elements: Vec, // empty list of elements } ``` | | **Builder** | | | ```rs QueryBuilder::select().node_count().query(); ``` | | Selects number (count) of nodes in the database. ### Select values | **Struct** | **Result** | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ```rs pub struct SelectValuesQuery { pub keys: Vec, pub ids: QueryIds, } ``` | ```rs pub struct QueryResult { pub result: u64, // number of returned elements pub elements: Vec, // list of elements with only // selected properties } ``` | | **Builder** | | | ```rs QueryBuilder::select().ids("a").query(); QueryBuilder::select().ids([1, 2]).query(); QueryBuilder::select().ids(QueryBuilder::search().from(1).query()).query(); QueryBuilder::select().search().from(1).query(); // Equivalent to the previous query QueryBuilder::select().values(["k", "k2"]).ids("a").query(); QueryBuilder::select().values(["k", "k2"]).ids([1, 2]).query(); QueryBuilder::select().values(["k", "k2"]).ids(QueryBuilder::search().from(1).query()).query(); QueryBuilder::select().values(["k", "k2"]).search().from(1).query(); // Equivalent to the previous query QueryBuilder::select().element::().search().from("a").query(); //selects a single element (limit is set to 1); T: DbType QueryBuilder::select().elements::().ids(1).query(); QueryBuilder::select().elements::().ids(QueryBuilder::search().from("a").query()).query(); QueryBuilder::select().elements::().search().from("a").query(); // Equivalent to the previous query ``` | | Selects elements identified by `ids` [`QueryIds`](https://agdb.agnesoft.com/#queryid-queryids) or search query with only selected properties (identified by the list of keys). If any of the `ids` does not exist in the database or (when a list of keys is given) does not have all the keys associated with it then running the query will return an error. A missing key is an error only for explicitly listed `ids`; when the elements come from a search they are returned with whichever of the keys they have. The search query is most commonly used to find, filter or otherwise limit what elements to select. You can limit what properties will be returned. If the list of properties to select is empty all properties will be returned. If you plan to convert the result into your user defined type(s) you should use either `elements::()` variant or supply the list of keys to `values()` with `T::db_keys()` provided through the `DbType` trait (`#[derive(agdb::DbType)]` or `#[derive(agdb::DbElement)]`) as argument to `values()`. If `T` derives from `DbElement` or otherwise implements `DbType::db_element_id()` the "select().search()" query will have automatic condition added, i.e. as if written by hand `key("db_element_id").value("T")` to simplify working with types, especially if they are overlapping. You can also often omit conditions altogether in some cases. ## Search | **Struct** | **Result** | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ```rs pub struct SearchQuery { pub algorithm: SearchQueryAlgorithm, pub origin: QueryId, pub destination: QueryId, pub limit: u64, pub offset: u64, pub order_by: Vec, pub conditions: Vec, pub reverse: bool, // reverse path search (follows incoming edges) } ``` | ```rs pub struct QueryResult { pub result: u64, // number of elements found pub elements: Vec, // list of elements found (only ids) } ``` | | ```rs pub enum SearchQueryAlgorithm { BreadthFirst, DepthFirst, Index, Elements } pub enum DbKeyOrder { Asc(DbValue), Desc(DbValue), } ``` | | | **Builder** | | | ```rs QueryBuilder::search().from("a").query(); QueryBuilder::search().to(1).query(); //reverse search QueryBuilder::search().from("a").to("b").query(); //path search using A* algorithm QueryBuilder::search().to("b").from("a").query(); //reverse path search (follows incoming edges, can be faster when destination has fewer incoming edges) QueryBuilder::search().breadth_first().from("a").query(); //breadth first is the default and can be omitted QueryBuilder::search().depth_first().from("a").query(); QueryBuilder::search().elements().query(); QueryBuilder::search().index("age").value(20).query(); //index search //limit, offset, order_by and conditions can be applied to all search variants including index search QueryBuilder::search().from(1).order_by([DbKeyOrder::Desc("age".into()), DbKeyOrder::Asc("name".into())]).query() QueryBuilder::search().index("age").value(20).limit(10).query(); //index search with limit QueryBuilder::search().index("name").value("alice").where_().node().query(); //index search with conditions QueryBuilder::search().from(1).offset(10).query(); QueryBuilder::search().from(1).limit(5).query(); QueryBuilder::search().from(1).order_by([DbKeyOrder::Desc("k".into())]).offset(10).query(); QueryBuilder::search().from(1).order_by([DbKeyOrder::Desc("k".into())]).limit(5).query(); QueryBuilder::search().from(1).order_by([DbKeyOrder::Desc("k".into())]).offset(10).limit(5).query(); QueryBuilder::search().from(1).offset(10).limit(5).query(); ``` | | There is only a single search query that provides the ability to search the graph or indexes. When searching the graph it examines connected elements and their properties. While it is possible to construct the search queries manually, specifying them that way can be excessively difficult and therefore **using the builder pattern is recommended**. The default search algorithm is `breadth first` however you can choose to use `depth first`. For path search the `A*` algorithm is used. For searching an index the algorithm is `index`. For searching disregarding the graph structure and indexes (full search) the algorithm is `elements`. Elements will never be examined twice during any search regardless of any cycles in the graph. Very often you would want the values / elements to be returned from the search query. To accomplish it you need to nest the search query in the select query with either `.search()` builder element or `ids()` step that takes a `SearchQuery` as argument. That fetches the data as the search query only traverses the graph. E.g. `QueryBuilder::select().search().from("alias").query()`. Refer to the [Select Values](https://agdb.agnesoft.com/#select-values) query for details. Index searches skip the graph traversal and their `where_()` is the restricted `WhereFilter` builder: it offers the element conditions (`node`, `edge`, `ids`, `key`, `keys`, `element`, `edge_count*`) but not the traversal conditions (`distance`, `neighbor`, `beyond`, `not_beyond`). The first condition must be a key-value equality (`index("key").value(v)`), any other comparison is rejected with an error, and the index is looked up by the value and by the other stored types that the equality converts to the type of the operand (e.g. a stored `u64` 5 for the `i64` 5, at most one extra lookup per such type) so the result is the same as for a scan with the same condition (see the conditions below). They still support `limit`, `offset`, `order_by`, and `where_()` conditions — these are applied to the index results in the same way as for graph searches. The graph search query is made up of the `origin` and `destination` of the search and the algorithm. Specifying only `origin` (from) will result in a search along `from->to` edges. Specifying only `destination` (to) will result in the reverse search along the `to<-from` edges. When both `origin` and `destination` are specified the search algorithm becomes a path search and the algorithm used will be `A*`. Optionally you can specify a `limit` (0 = unlimited) and `offset` (0 = no offset) to the returned list of graph element `ids`. If specified (!= 0) the `origin` and the `destination` must exist in the database, otherwise an error will be returned. The elements can be optionally ordered with `order_by` list of keys allowing ascending/descending ordering based on multiple properties. When searching `elements` the database is being scanned in linearly one element (node & edge) at a time which can be very slow. Consider using `limit` in this case. However, this search can be useful in exploration, when the database structure is not known, when searching for abandoned/lost elements and other edge cases not covered by regular search algorithms. The default order of returned elements is from the lowest internal db `id` to the highest which does not necessarily indicate age of the elements as the `ids` can be reused when elements are deleted. Finally, the list of `conditions` that each examined graph element must satisfy to be included in the result (and subjected to the `limit` and `offset`). **NOTE:** When both `origin` and `destination` are specified, and the algorithm is switched to the `A*` the `limit` and `offset` are applied differently. In regular (open-ended) search the search will end when the `limit` is reached but with the path search (A\*) the `destination` must be reached first before they are applied. ### Breadth First The `breadth first` algorithm (the default one) examines every element on each level before moving to the next level. For instance starting at a node this algorithm will first examine all the edges in the selected direction (from/to) before examining the adjacent nodes reachable through those edges. The order of the elements is **from newest to oldest** where newest means most recently connected. Similarly, the next level is also examined in the same order. Example: Given a graph of 6 nodes connected together with 4 edges like so (NOTE: `ids` are for illustration only and does NOT indicate newer/older element): | Level 0 | Level 1 | Level 2 | Level 3 | Level 4 | | -------- | -------- | -------- | -------- | -------- | | Node (a) | Edge (b) | Node (d) | Edge (f) | Node (h) | | | Edge (c) | Node (e) | Edge (g) | Node (j) | The `breadth first` algorithm will first visit node (a) at level 0. Then it will visit all edges at level 1 starting with the newest edge (c) followed by the older edge (b). Then it will move on to the level 2 once more examining the newest node first (g) followed by (f). Lastly it will move on to level 4 examining nodes (j) and (h). The "newest" means most recently connected and does not necessarily mean it will have higher `id` because `ids` can be reused from deleted elements. ### Depth First The `depth first` algorithm follows every element to the next level first. When it cannot continue on to a next level it will step back to the previous level trying another direction if possible. When exhausted or not available it will backtrack again to the previous level and continue from there. The order of the elements is **from newest to oldest** where newest means most recently connected. Example: Given a graph of 6 nodes connected together with 4 edges like so (NOTE: `ids` are for illustration only and does NOT indicate newer/older element): | Level 0 | Level 1 | Level 2 | Level 3 | Level 4 | | -------- | -------- | -------- | -------- | -------- | | Node (a) | Edge (b) | Node (d) | | | | | Edge (c) | Node (e) | Edge (f) | Node (h) | | | | | Edge (g) | Node (j) | The `depth first` algorithm will first visit node (a) at level 0. Then it will visit the most recent edge (c) on level 1. Then it will follow it to its connected node (e) at level 2, then edge (g) at level 3 and finally node (j) at level 4. Since it cannot continue it will step back to level 3 and examine the edge (f) and follow it to node (h) at level 4. After that it will step back to level 3 and see nothing available so it will backtrack further to level 1 to examine edge (b) and follow it to node (d). That will conclude the search. NOTE: when a graph contains multiple edges leading to the same elements the extra edges will appear seemingly "out of order" in the search result (i.e. at the end). This is because no element can be visited twice yet the DFS algorithm will eventually backtrack and attempt to go in their direction possibly including them in the result. Typically, you might want to filter out all edges with `.where_().node()` condition. ### Paths Path search (`from().to()`) uses A\* algorithm. Every element (node or edge) has a cost of `1` by default. If it passes all the conditions (the `SearchControl` value `true`) the cost will remain `1` and would be included in the result (if the path it is on would be selected). If it fails any of the conditions (the `SearchControl` value `false`) its cost will be `2`. This means that the algorithm will prefer paths where elements match the conditions rather than the absolutely shortest path (that can be achieved with no conditions). If the search is not to continue beyond certain element (through `beyond()`, `not_beyond()` or `distance()` conditions) its cost will be `0` and the paths it is on will no longer be considered for that search. ### Conditions | **Struct** | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ```rs pub struct QueryCondition { pub logic: QueryConditionLogic, pub modifier: QueryConditionModifier, pub data: QueryConditionData, } pub enum QueryConditionLogic { And, Or, } pub enum QueryConditionModifier { None, Beyond, Not, NotBeyond, } pub enum QueryConditionData { Distance(CountComparison), Edge, EdgeCount(CountComparison), EdgeCountFrom(CountComparison), EdgeCountTo(CountComparison), Ids(Vec), KeyValue(KeyValueComparison), Keys(Vec), Node, Where(Vec), } pub enum CountComparison { Equal(u64), GreaterThan(u64), GreaterThanOrEqual(u64), LessThan(u64), LessThanOrEqual(u64), NotEqual(u64), } pub enum Comparison { Equal(DbValue), GreaterThan(DbValue), GreaterThanOrEqual(DbValue), LessThan(DbValue), LessThanOrEqual(DbValue), NotEqual(DbValue), Contains(DbValue), StartsWith(DbValue), EndsWith(DbValue), Any(DbValue), // matches if the element's value equals (or contains) any of the listed values Regex(DbValue), // `DbValue::String` pattern, matches if the element's value matches the regex (requires `regex` feature) } pub struct KeyValueComparison { pub key: DbValue, pub value: Comparison, } ``` | | **Builder** | | ```rs //the where_() can be applied to any of the basic search queries after order_by/offset/limit //not() and not_beyond() can be applied to all conditions including nested where_() QueryBuilder::search().from(1).where_().distance_less_than(3).query(); QueryBuilder::search().from(1).where_().edge().query(); QueryBuilder::search().from(1).where_().edge_count_greater_than(2).query(); QueryBuilder::search().from(1).where_().edge_count_from(1).query(); QueryBuilder::search().from(1).where_().edge_count_to_not_equal(1).query(); QueryBuilder::search().from(1).where_().node().query(); QueryBuilder::search().from(1).where_().key("k").value(1).query(); QueryBuilder::search().from(1).where_().keys(["k1", "k2"]).query(); QueryBuilder::search().from(1).where_().not().keys(["k1", "k2"]).query(); QueryBuilder::search().from(1).where_().element::().query(); //T: DbType, matches the "db_element_id" or all of T::db_keys() QueryBuilder::search().from(1).where_().ids([1, 2]).query(); QueryBuilder::search().from(1).where_().beyond().keys(["k"]).query(); QueryBuilder::search().from(1).where_().not().ids([1, 2]).query(); QueryBuilder::search().from(1).where_().not_beyond().ids("a").query(); QueryBuilder::search().from(1).where_().neighbor().query(); //shorthand for distance(CountComparison::Equal(2)) QueryBuilder::search().from(1).where_().key("name").regex("^A.*").query(); //regex match QueryBuilder::search().from(1).where_().key("age").greater_than(18).query(); //shorthand for value(Comparison::GreaterThan(...)) QueryBuilder::search().from(1).where_().key("age").less_than(65).query(); QueryBuilder::search().from(1).where_().key("name").contains("alice").query(); //substring/element match QueryBuilder::search().from(1).where_().key("role").any(["admin", "mod"]).query(); //matches any of the list QueryBuilder::search().from(1).where_().distance_less_than(3).query(); //shorthand for distance(CountComparison::LessThan(3)) QueryBuilder::search().from(1).where_().edge_count_from_greater_than(0).query(); //shorthand for edge_count_from(CountComparison::GreaterThan(0)) QueryBuilder::search().from(1).where_().node().or().edge().query(); QueryBuilder::search().from(1).where_().node().and().distance_greater_than_or_equal(3).query(); QueryBuilder::search().from(1).where_().node().or().where_().edge().and().key("k").value(1).end_where().query(); QueryBuilder::search().from(1).where_().node().or().where_().edge().and().key("k").contains(1).end_where().query(); QueryBuilder::search().from(1).where_().node().or().where_().edge().and().key("k").contains(vec![1, 2]).end_where().query(); ``` | The currently supported conditions are: - Where (opens nested list of conditions) - Edge (if the element is an `edge`) - Node (if the element is a `node`) - Distance (if the current distance of the search satisfies the numerical comparison, each graph element away from the start increases the distance, including edges, i.e. second node from start is at distance `2`) - EdgeCount (if the element is a node and total number of edges (in and out) satisfies the numerical comparison - self-referential edges are counted twice) - EdgeCountFrom (if the element is a node and total number of outgoing edges satisfies the numerical comparison) - EdgeCountTo (if the element is a node and total number of incoming edges satisfies the numerical comparison) - Ids (if the element `id` is in the list) - KeyValue (if the element's property has the `key` and its value satisfies `value` comparison) - Keys (if the element has all the `keys` regardless of their values) - EndWhere (closes nested list of conditions) The builder also provides convenience methods: - `neighbor()` — shorthand for `.distance(CountComparison::Equal(2))`, i.e. immediate neighbors of the origin node - Distance shorthands: `distance_greater_than(v)`, `distance_greater_than_or_equal(v)`, `distance_less_than(v)`, `distance_less_than_or_equal(v)`, `distance_not_equal(v)` — avoid manually constructing `CountComparison` - Value comparison shorthands on `.key("k")` — avoid manually constructing `Comparison`: - `.greater_than(v)`, `.greater_than_or_equal(v)`, `.less_than(v)`, `.less_than_or_equal(v)`, `.not_equal(v)` - `.contains(v)` — substring match for strings, element match for vectors - `.starts_with(v)`, `.ends_with(v)` — string prefix/suffix match - `.any(v)` — matches if the value equals any element in the provided list - `.regex("pattern")` — regex match on a key's value (requires the `regex` [cargo feature](https://agdb.agnesoft.com/docs/guides/concepts#cargo-features), without it the comparison never matches) - Edge count shorthands: `edge_count_from_greater_than(v)`, `edge_count_to_less_than(v)`, etc. — full set of `_greater_than`, `_less_than`, `_not_equal` variants for `edge_count`, `edge_count_from`, and `edge_count_to` All conditions can be further modified as follows: - Beyond (controls traversal only: continues the search only beyond this element if the condition passes, does not affect element selection) - Not (reverses the condition selection result) - NotBeyond (controls traversal only: stops the search beyond this element if the condition passes, does not affect element selection) The conditions can be changed with logic operators: - And (logical `and`) - Or (logical `or`) NOTE: The use of `where_` with an underscore as the method name is necessary to avoid conflict with the Rust keyword. The conditions are applied one at a time to each visited element and chained using logic operators `AND` and `OR`. There is no operator precedence (`AND` does not bind tighter than `OR`): the conditions on one level are combined strictly from left to right, e.g. `a OR b AND c` is `(a OR b) AND c`. They can be nested using `where_` and `end_where` (in place of brackets). The condition evaluator supports short-circuiting not evaluating conditions further if the logical outcome cannot change. The type of the operand of a comparison (the value in the query) decides the type of the comparison: the stored value is converted to the type of the operand using the lossless conversions of `DbValue` and then compared within that type (e.g. `Comparison::Equal(1_i64)` matches a stored `u64` 1 but `Comparison::LessThan(1_u64)` does not match a stored `i64` -1 as it cannot be converted). If the stored value cannot be converted the comparison is `false` (including `<`, `<=`, `>`, `>=`, `contains`, `starts_with`, `ends_with` and `any`) except for `Comparison::NotEqual` which is always the exact negation of `Comparison::Equal` and so is `true`. Values of the same type as the operand are compared directly. Keys are never converted. The conversions are (stored type in the rows, operand type in the columns, `-` = cannot be converted): | stored (rows) / operand (columns) | `i64` | `u64` | `f64` | `string`, `bytes`, `vec` | `vec` | `vec` | `vec` | | --------------------------------- | ---------------- | --------- | ---------------- | -------------------------------- | -------------------- | ------------- | -------------------- | | `i64` | as is | if `>= 0` | if `|v| <= 2^53` | - | - | - | - | | `u64` | if `<= i64::MAX` | as is | if `<= 2^53` | - | - | - | - | | `f64` | - | - | as is | - | - | - | - | | `string`, `bytes`, `vec` | - | - | - | as is (same type only) | - | - | - | | `vec` | - | - | - | - | as is | if all `>= 0` | if all `|v| <= 2^53` | | `vec` | - | - | - | - | if all `<= i64::MAX` | as is | if all `<= 2^53` | | `vec` | - | - | - | - | - | - | as is | | `vec` | - | - | - | - | - | - | - | | none | - | - | - | - | - | - | - | For `contains`, `starts_with`, `ends_with` and `any` the stored vector (or the stored scalar for `any`) is converted the same way, e.g. `Comparison::Contains(2_i64)` matches a stored `vec` `[1, 2]`. The elements of a stored `vec` are compared one by one with the same rules. `Comparison::Equal(None)` matches only the values without a value (labels). A vector made from a mix of numbers (e.g. `[1_i64, 2_u64]`) gets the type of its first element when it is built (it is `vec` here) and so that is also the type the stored values are converted to; a mix that cannot be made into one type stays `vec`. Similarly, `Comparison::StartsWith` and `Comparison::EndsWith` are provided with the same semantics as `Comparison::Contains` matching only from the beginning or end respectively (both single value and vectorized and vice versa). The condition `Distance` and the condition modifiers `Beyond` and `NotBeyond` are particularly important because they can directly influence the search. The former (`Distance`) can limit the depth of the search and can help with constructing more elaborate queries (or sequence thereof) extracting only fine-grained elements (e.g. nodes whose edges have particular properties or are connected to other nodes with some properties). The latter (`Beyond` and `NotBeyond`) can limit search to only certain areas of an otherwise larger graph, but they only control traversal (whether the search continues or stops at an element) and do not select or reject elements on their own. All visited elements are selected by default with `(not)_beyond` conditions. To control selection of elements, combine them with additional conditions. Their most basic usage would be with condition `ids` to flat out stop the search at certain elements or continue only beyond certain elements. ### Truth tables The following information should help with reasoning about the query conditions. Most of it should be intuitive, but there are some aspects that might not be obvious especially when combining logic operators and condition modifiers. The search is using the following `enum` when evaluating conditions: ```rs pub enum SearchControl { Continue(bool), Finish(bool), Stop(bool), } ``` The type controls the search and the boolean value controls if the given element should be included in the search result. The `Stop` will prevent the search expanding beyond current element (stopping the search in that direction). `Finish` will immediately exit the search returning accumulated elements (`ids`) and is only used internally with `offset` and `limit` (NOTE: path search and `order_by` still require complete search regardless of `limit`). Each condition contributes to the final control result as follows with the starting/default value being always `Continue(true)`: #### And | Left | Right | Result | | -------------- | --------------- | ----------------------- | | Continue(left) | Continue(right) | Continue(left && right) | | Continue(left) | Stop(right) | Stop(left && right) | | Continue(left) | Finish(right) | Finish(left && right) | | Stop(left) | Stop(right) | Stop(left && right) | | Stop(left) | Finish(right) | Finish(left && right) | | Finish(left) | Finish(right) | Finish(left && right) | #### Or | Left | Right | Result | | -------------- | --------------- | ------------------------- | | Continue(left) | Continue(right) | Continue(left \|\| right) | | Continue(left) | Stop(right) | Continue(left \|\| right) | | Continue(left) | Finish(right) | Continue(left \|\| right) | | Stop(left) | Stop(right) | Stop(left \|\| right) | | Stop(left) | Finish(right) | Stop(left \|\| right) | | Finish(left) | Finish(right) | Finish(left \|\| right) | #### Modifiers Modifiers will change the result of a condition based on the control value (the boolean) as follows: | Modifier | TRUE | FALSE | | --------- | ------------------- | ---------------- | | None | - | - | | Beyond | `&& Continue(true)` | `Stop(true)` | | Not | `!` | `!` | | NotBeyond | `&& Stop(true)` | `Continue(true)` | #### Results Most conditions result in `Continue(bool)` except for `distance()` and nested `where()` which can also result in `Stop(bool)`: | Condition | Continue | Stop | | ----------- | -------- | ---- | | Where | YES | YES | | Edge | YES | NO | | Node | YES | NO | | Distance | YES | YES | | EdgeCount\* | YES | NO | | Ids | YES | NO | | Key(Value) | YES | NO | | Keys | YES | NO | --- For further examples and use cases see the [efficient agdb](https://agdb.agnesoft.com/docs/references/efficient-agdb). # Server The `agdb_server` is the OpenAPI REST server that provides remote `agdb` database management. Running the server is trivial as there are no dependencies, no complicated configuration etc. It can be run on any platform supported by Rust. Please follow the guide: [How to run the server?](https://agdb.agnesoft.com/docs/guides/how-to-run-server) The server is based on [`axum`](https://github.com/tokio-rs/axum){rel=""nofollow""} and uses OpenAPI to specify its API (via [`utoipa`](https://github.com/juhaku/utoipa){rel=""nofollow""}) and [`rapidoc`](https://rapidocweb.com/){rel=""nofollow""} for the OpenAPI GUI. To interact with the server you can use the rapidoc GUI, `curl` or any of the [available API clients](https://agdb.agnesoft.com/api-docs/openapi). Internally it uses the `agdb` database: GUI accessible at (run in a browser when the server is running): ```bash http://localhost:3000/api/v1 ``` ## Configuration The server will create default configuration when run and always reads it from the working directory if it exists: ```yaml # agdb_server.yaml bind: ":::3000" # address to listen at (bind to) address: "http://localhost:3000" # address the incoming connections will come from basepath: "" # base path to append to the address in case the server is to be run behind a reverse proxy static_roots: [] # list of static folders to serve in format : (e.g. /static:/home/user/www) admin: admin # the admin user that will be created automatically for the server, the password will be the same as name (admin by default, recommended to change after startup) token_expiry_seconds: 3600 # for how long are login tokens valid for, min: 60 = 1 minute, max: 86400 = 1 day, default: 3600 = 1 hour data_dir: agdb_server_data # directory to store user data log_level: info # Options are: off, error, warn, info, debug, trace log_body_limit: 10240 # maximum length of the body of the request that will be logged in bytes, default is 10KB request_body_limit: 10485760 # maximum length of the body of the request that will be accepted in bytes, default is 10MB pepper_path: "" # Optional path to a runtime secret file containing 16 bytes "pepper" value for additionally "seasoning" (hashing) passwords. If empty a built-in pepper value is used - see "How to run the server?" guide for details tls_certificate: "" # path to the TLS certificate file tls_key: "" # path to the TLS key file tls_root: "" # path to the TLS root CA file cluster_token: cluster # token used between members of the cluster for authentication, treat this value as secret cluster_heartbeat_timeout_ms: 1000 # number of milliseconds since last message sent to a node in the cluster before the leader sends a heartbeat message cluster_term_timeout_ms: 3000 # number of milliseconds without receiving a message from the leader after which the nodes will consider leader to be off and begin a new term cluster_election_factor_ms: 1000 # number of milliseconds delay for starting election in each node, this time will be multiplied by the index of the node (e.g. node 0 * cluster_election_factor_ms == starts election immediately) cluster: [] # list of "address" fields of all nodes in the cluster including local node - the order and values must be the same in all members of the cluster cluster_max_log_entries: 1000 # number of applied Raft log entries kept before pruning older ones, must be the same on all nodes cluster_max_chunk_size: 4194304 # maximum size in bytes of each chunk of a snapshot streamed to a node cluster_max_append_size: 4194304 # maximum size in bytes of the log entries in one request to a node cluster_max_parallel_logs: 64 # maximum number of committed log entries executing at once, entries that touch the same user, database or dashboard always run one after another; 0 means the default cluster_rpc_timeout_ms: 2000 # number of milliseconds a node waits for the reply of another node cluster_min_throughput: 32768 # minimum bytes per second assumed of a link to another node, an append is given the time its size needs at this rate on top of cluster_rpc_timeout_ms cluster_hold_timeout_ms: 300000 # number of milliseconds the leader keeps the log entries and a prepared snapshot for a node it does not hear from, e.g. one restarting cluster_max_log_bytes: 1073741824 # maximum size in bytes of the Raft log cluster_max_pending_bytes: 67108864 # maximum size in bytes of the committed log entries waiting to be executed, writes beyond it fail with 503 until the nodes catch up sync_mode: none # controls fsync behavior: "none" (default), "commit" or "strict" overlay_limit: 67108864 # bytes of a transaction held in memory before they are written to the database file ahead of its commit memory_limit: 0 # maximum size in bytes of the memory used by each user database, 0 = unlimited (not applied to the server database) ``` You can prepare it in advance in a file `agdb_server.yaml`. The `admin` field names the server admin: on every start the server makes that user the admin, creating it with the password equal to its name if it does not exist yet, so change the `admin` field only to hand the admin role to another user. The other settings can be changed later too. All config changes require server restart to take effect. The server refuses to start when the file cannot be parsed or contains an invalid value, for example an unknown key, an invalid `log_level` or `sync_mode`, a `token_expiry_seconds` outside of 60-86400, or a `cluster_max_log_entries` of 0. A `cluster_max_chunk_size`, `cluster_max_append_size` or `cluster_max_parallel_logs` of 0 falls back to its default. The `basepath` is normalised to start with `/` and not to end with it (`api/` becomes `/api`) and a path in `address` is ignored (with a warning) - use `basepath` for it. ### Sync Mode The `sync_mode` setting controls whether the server issues explicit `fdatasync` calls at transaction commit boundaries. It applies uniformly to the server database, cluster log, and all user databases. | Value | Behavior | | -------- | --------------------------------------------------------------------------- | | `none` | Rely on the operating system to flush dirty pages in the background. | | `commit` | Issue `fdatasync` on every transaction commit ensuring write ordering. | | `strict` | Like `commit` and also sync the cleared WAL so the commit survives a crash. | **Default: `none`** — on local filesystems (ext4, xfs, ZFS, etc.) the OS page cache provides sufficient write ordering guarantees for the WAL protocol. The kernel flushes dirty pages in program order and the filesystem journal protects metadata. The probability of a reorder causing data loss on local disk is negligible in practice. **When to enable `commit`:** - **Network filesystems with client-side write caching** (e.g. WekaFS mounted with `writecache`, CephFS with client buffering). These filesystems may reorder or delay flushes across files. Without explicit fsync the WAL can be cleared on disk before the main data file is flushed, which would cause an already-committed transaction to roll back on restart. - **Any storage layer where write ordering between two open file descriptors is not guaranteed** by the OS (FUSE-based mounts, certain cloud block storage with write-back caching). With `commit` a crash right after a commit may roll that transaction back (the database stays consistent). Use `strict` when an acknowledged commit must survive a crash of the node, at the cost of one more sync per commit. **When `none` is safe:** - Local physical disks with a POSIX filesystem — the OS provides ordering. - Cluster deployments on local disk — Raft replication provides node-level durability through quorum acknowledgement. Even in the theoretical local-disk reorder scenario, other nodes hold the committed entry. - Any environment where a small window of potential data loss on power failure is acceptable (similar to SQLite's `PRAGMA synchronous=NORMAL`). The `commit` mode adds latency proportional to the storage backend's fsync speed (typically sub-millisecond on local NVMe, 1-5ms on spinning disk, 5-50ms on network filesystems). Enable it only when the underlying storage requires it. ### Overlay Limit The `overlay_limit` setting bounds the bytes of a transaction held in memory until its commit. A transaction that grows past it writes its changes to the database file before the commit and keeps the WAL until then, which costs one extra WAL sync unless `sync_mode` is `none`. It applies to the server database, cluster log, and all user databases. Lower it on nodes with little memory. The server is built with a default `pepper` (can be changed as [part of the build](https://agdb.agnesoft.com/docs/guides/how-to-run-server/server-bare-metal) ) that is used if `pepper_path` is not specified. If unique it makes sure the two different `agdb_server` instances do not produce the same password hashes and enhances the security. The `pepper` value is to be considered a secret. The TLS is turned on by specifying the `tls_certificate` and `tls_key` and internally uses [`rustls`](https://github.com/rustls/rustls){rel=""nofollow""}. The `tls_root` is optional (can be empty) and needs to be specified only if you are using self-signed certificates. The certificate use in `tls_certificate` must be issued for the name (or one of alternative names) used in the `address` and `cluster` fields. For self-signed certificate and root CA (usable in docker compose or K8s deployments) you can use the following: ```bash cargo install rustls-cert-gen rustls-cert-gen \ --common-name=agdb \ --ca-file-name=root_ca \ --cert-file-name=cert \ --country-name=CZ \ --organization-name=Agnesoft \ --san=localhost \ --san=agdb0 \ --san=agdb1 \ --san=agdb2 \ --output=. ``` ## Users The server has a single admin account (`admin` by default, configurable with password being the name) that can perform any regular user action + all admin actions such as creating users. You can use this account for using the database locally, but it would be advisable to use it only for maintaining the server and to create a regular user for use with the databases: ```bash # produce an admin API token, e.g. "bb2fc207-90d1-45dd-8110-3247c4753cd5" token=$(curl -X POST -H 'Content-Type: application/json' localhost:3000/api/v1/user/login -d '{"username":"admin","password":"admin"}') # using admin token to create a user curl -X POST -H "Authorization: Bearer ${token}" -H 'Content-Type: application/json' localhost:3000/api/v1/admin/user/my_db_user/add -d '{"password":"password123"}' # login as the new user and producing their token token=$(curl -X POST -H 'Content-Type: application/json' localhost:3000/api/v1/user/login -d '{"username":"my_db_user","password":"password123"}') ``` Users are allowed to change their password and to create and manipulate databases. A user name must have at least 3 characters (otherwise the server answers 462) and a password at least 8 characters (otherwise 461). Login tokens are now session based. Each successful login creates a new API token bound to a specific session rather than reusing one shared token per user. The current active sessions can be inspected via `/api/v1/user/status` which returns a `UserStatus` containing the list of `UserSession` objects: ```rs pub struct UserStatus { pub username: String, // username pub login: bool, // whether the user is currently logged in pub admin: bool, pub sessions: Vec, } pub struct UserSession { pub session: String, // the session token string pub agent: String, // client that created the session pub created: u64, // session creation time (unix timestamp, seconds) pub expires_at: u64, // token expiry (unix timestamp, seconds since epoch) } ``` Available user APIs: | Action | Description | | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | /api/v1/user/change_password | changes the current user's password | | /api/v1/user/login | logs in the user returning a new API token for a new session | | /api/v1/user/logout | logs out the current session by default, all sessions with `?session=all`, all other sessions with `?session=others`, or a specific session by id | | /api/v1/user/status | returns current user's username, whether it is a server admin, and the list of current login sessions | | /api/v1/cluster/user/login | logs in the user cluster wide and creates the same new session token on all nodes in the cluster | | /api/v1/cluster/user/logout | same logout options as `/api/v1/user/logout`, but applied cluster wide | Examples: ```bash # logout only the current session curl -X POST -H "Authorization: Bearer ${token}" localhost:3000/api/v1/user/logout # logout all sessions of the current user curl -X POST -H "Authorization: Bearer ${token}" "localhost:3000/api/v1/user/logout?session=all" # logout all other sessions but keep the current one curl -X POST -H "Authorization: Bearer ${token}" "localhost:3000/api/v1/user/logout?session=others" ``` ## Dashboards Users can store named dashboards (used by agdb Studio). The server keeps the dashboard `config` as an opaque JSON string of up to 256 KB and does not interpret it. Names may contain letters, digits, `_`, `-` and `.` (1-64 characters, not starting with `.`). Dashboards are deleted together with their owner. Dashboards are shared like databases: the owner has the `admin` role and can add other users as `admin` (manage users), `write` (change the config) or `read`. Only the owner can rename, remove or publish a dashboard. A public dashboard can be viewed (read only) by every logged-in user; to everyone else a dashboard they have no role on does not exist (404). Widgets in agdb Studio run their queries with each viewer's own database access, except in the Studio admin view, where a server admin sees every dashboard and its widgets run with admin access (marked "Admin access"). | Action | Description | | ------------------------------------------------------------- | --------------------------------------------------------------------- | | /api/v1/dashboard/list | dashboards the user has a role on and public ones | | /api/v1/dashboard/{owner}/{name} | returns the dashboard with its config and the user's role | | /api/v1/dashboard/{owner}/{name}/add | creates a new own dashboard (409 if it already exists) | | /api/v1/dashboard/{owner}/{name}/save | replaces the dashboard config (write role) | | /api/v1/dashboard/{owner}/{name}/rename?new_name=... | renames the dashboard (owner only, 409 if the new name is taken) | | /api/v1/dashboard/{owner}/{name}/remove | removes the dashboard (owner only) | | /api/v1/dashboard/{owner}/{name}/public?public=true\|false | makes the dashboard public or private (owner only) | | /api/v1/dashboard/{owner}/{name}/user/list | lists the dashboard users and their roles | | /api/v1/dashboard/{owner}/{name}/user/{username}/add?db_role= | adds a user or changes their role (admin role) | | /api/v1/dashboard/{owner}/{name}/user/{username}/remove | removes a user (admin role, or the user leaving) | | /api/v1/user/home_dashboard | gets (GET), sets (PUT ?owner=\&name=) or clears (DELETE) the home one | Server admins manage every dashboard through the same routes under `/api/v1/admin/dashboard/...` (`list`, `{owner}/{name}`, `add`, `save`, `rename`, `remove`, `public` and `user/...`). Example: ```bash curl -X POST -H "Authorization: Bearer ${token}" -H "Content-Type: application/json" -d '{"config":"{}"}' localhost:3000/api/v1/dashboard/my_user/ops/add ``` ## Databases Any user can create, remove and manipulate their own databases. To create a database: ```bash curl -X POST -H "Authorization: Bearer ${token}" localhost:3000/api/v1/db/my_db_owner/my_db/add?db_type=mapped ``` Note that a user can only create databases under their own name. A database name is a file name in the owner's folder: it must not be empty, start with `.`, contain `/`, `\`, `:` or NUL, or be `audit` or `backups` (any case), otherwise the server answers 467. The same applies to the new name of a copy or rename. User names follow the same file name rules except that `audit` and `backups` are allowed, and must not be `agdb_server.agdb`, `agdb_server.log` or `agdb_server.journal`, otherwise the server answers 400. The `db_type` can be one of: ```yaml memory # memory only database, basically a cache mapped # memory mapped database, using memory for reading but persisting changes to the disk file # file based database only, no memory caching, reading/writing from/to disk ``` It is possible to add an existing database to the server. Move the db file to the server data folder and run `/api/v1/db/{owner}/{db}/add` API as if you were creating a new database with the db's name. If the file exists it will be added rather than created. Similarly, you can remove database (instead of deleting it) from the server with `/api/v1/db/{owner}/{db}/remove` API that will disassociate the db from the server which you can then move and use elsewhere. Listing databases (`/api/v1/db/list`) returns `ServerDatabase` objects that include a `created` field (unix timestamp in seconds) indicating when the database was first added to the server. ### Database Users Each database is scoped to one user (owner) who can exercise full control over it. The owner can add more users (they must exist on the server) to the database including admin level users with one of three roles: ```yaml read # can only run immutable exec queries write # can run mutable and immutable exec queries admin # same as write but can also admin the database ``` The admin users can do some (but not all) actions that the owner can: ### Database Actions The databases of the current user (owned and others') are listed by `/api/v1/db/list`. The ownership of a database can only be transferred by the server admin with `/api/v1/admin/db/{owner}/{db}/rename?new_owner=...&new_db=...`; the same parameters apply to `/api/v1/admin/db/{owner}/{db}/copy`. | Action | Permission | Description | | ---------------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------ | | /api/v1/db/{owner}/{db}/add | owner | adds (from existing files) or creates a database (memory, memory mapped, file only) | | /api/v1/db/{owner}/{db}/audit | read | returns the log of all mutable queries that ran against the database (with user who ran them) | | /api/v1/db/{owner}/{db}/audit/trim | admin | removes the audit (live and backup) older than today and `?keep_days=` days before it | | /api/v1/db/{owner}/{db}/backup | admin | creates an automatic backup snapshot of the database (see backup docs below) | | /api/v1/db/{owner}/{db}/clear | admin | clears database resources; `?resource=all|db|audit|backup` query parameter, no body | | /api/v1/db/{owner}/{db}/convert | admin | converts db between memory/mapped/file | | /api/v1/db/{owner}/{db}/copy | read | creates a copy of the database under the current user (`?new_db=`) | | /api/v1/db/{owner}/{db}/delete | owner | deletes the database including files on disk | | /api/v1/db/{owner}/{db}/exec | read | executes queries against the database (does not allow mutable queries) | | /api/v1/db/{owner}/{db}/exec_mut | write | executes queries against the database (allows both mutable and immutable queries) | | /api/v1/db/{owner}/{db}/optimize | write | optimizes the underlying file storage packing the data reclaiming unused regions (defragmenting) | | /api/v1/db/{owner}/{db}/remove | owner | removes the database from the server but keeps the files on disk (main, WAL, backup, audit) | | /api/v1/db/{owner}/{db}/rename | owner | renames the database (`?new_db=`), see the note above on transferring the ownership | | /api/v1/db/{owner}/{db}/restore | admin | restores the database from the automatic backup while keeping the backup unchanged | | /api/v1/db/{owner}/{db}/rollback | admin | swaps the current database with the backup (a `memory` database is restored from it instead) | | /api/v1/db/{owner}/{db}/user/{username}/add | admin | adds a user to the database or changes their role (`PUT`, `?db_role=read|write|admin`) | | /api/v1/db/{owner}/{db}/user/list | read | list users of the database with their roles | | /api/v1/db/{owner}/{db}/user/{username}/remove | admin | removes a user from the database (`DELETE`) | ### Backups Each database can be backed up. The backup API `/api/v1/db/{owner}/{db}/backup` has no parameters and will always back up the database under the same name to the "backups" subfolder in the owner's data. The database can be restored with `/api/v1/db/{owner}/{db}/restore`. This replaces the current database contents with the backup while leaving the backup intact, so repeating `restore` will reapply the same snapshot. If you want the old swap-style behavior, use `/api/v1/db/{owner}/{db}/rollback`. This swaps the current database with the backup, so running `rollback` twice toggles between the two states. For `memory` databases `rollback` behaves like `restore` and keeps the backup. The backup and restore flow also keeps the audit log snapshot aligned with the database backup. If you need more granular backup or multiple backups you can devise your own scheme using the `/api/v1/db/{owner}/{db}/copy`, `/api/v1/db/{owner}/{db}/rename` and possibly `/api/v1/db/{owner}/{db}/remove` or `/api/v1/db/{owner}/{db}/delete` APIs. ### Audit Every mutable query is recorded in the database's audit log with the user who ran it and a timestamp (unix seconds). The log is stored as JSON lines in one file per UTC day under `{data_dir}/{owner}/audit/{db}/YYYY-MM-DD.log` and its backup counterpart under `{data_dir}/{owner}/backups/{db}.audit/`. Audit logs of the older format (a single JSON array in `audit/{db}.log` / `backups/{db}.log`) are converted when the server starts, the database is added, restored or rolled back, or a cluster node resyncs it. A file that cannot be fully read (e.g. cut short by a crash) has the entries before the unreadable part converted and is kept as `legacy.corrupt` in the database's audit directory. The log grows with every write. Use `/api/v1/db/{owner}/{db}/audit/trim?keep_days={n}` (or `/api/v1/admin/db/{owner}/{db}/audit/trim` as the server admin) to keep only today and the `n` UTC days before it in both the live and the backup log, e.g. as part of a retention job. Only whole day files are removed, so the audit always covers at least the last `n` × 24 hours. The server that receives the request resolves the first day to keep with its own clock, so every node in a cluster removes the same days. The trim is replicated in a cluster; call it only after all nodes run a version that supports it. ### Queries All queries are executed using the single `/api/v1/db/{owner}/{db}/exec` (read only queries) and `/api/v1/db/{owner}/{db}/exec_mut` (for queries that also write to the database) endpoint and are exactly the same as in the embedded/application database (see [Queries documentation](https://agdb.agnesoft.com/docs/references/queries)). However, depending on the user's role the server may reject executing the queries (i.e. mutable queries executed by the user with `read` role in the database). The endpoints accept a list of queries and the entire list is run as a transaction meaning either all queries succeed or none of them do. The endpoint will return list of results, one per executed query. The request and the reply are JSON by default; the content type `application/vnd.agdb.api.v1` selects agdb's binary serialization instead. It is possible to reference queries from each other in the list and the server will inject results of the referenced queries to the next one. This is slight extension to the vanilla `agdb` queries. It is best illustrated by an example: ```rs let queries = &vec![ QueryBuilder::insert().nodes().count(1).query().into(), // :0 QueryBuilder::insert().nodes().count(1).query().into(), // :1 QueryBuilder::insert().edges().from(":0").to(":1").query().into(), // :2 QueryBuilder::search().from(":0").to(":1").query().into(), //:3 ]; ``` In places where the `alias` can be used (an `ids` identifier) you can use an index prefixed by `:` to inject result of the previous query in the list. In the example we are inserting two separate nodes and then creating an edge between them and finally searching from one node to the other. An index to the results can be used in most places including conditions. What is currently not possible is to inject data (i.e. key-value properties) from results to subsequent queries. **Transactions** While the server serves each request asynchronously and can serve any number of clients at the same time the queries and individual databases must still follow the basic principles of the `agdb` that are the same as in the embedded variant: - mutable transactions run one at a time - any number of immutable transactions run concurrently with each other and with the writer, against the last committed state The `agdb` performs well even under heavily contested read/write load. See `agdb_benchmark` and [performance documentation](https://agdb.agnesoft.com/docs/references/performance). ## Admin Each `agdb_server` has exactly one admin account (`admin` by default) that acts as a regular user but additionally is allowed to execute APIs under `/admin/`. These mostly copies the APIs for regular users but some of the restrictions are not enforced (i.e. ownership or db role). Furthermore, the admin has access to the following exclusive APIs: | Action | Description | | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | /api/v1/admin/db/\* | provides same endpoints as for regular users but without owner/role restrictions | | /api/v1/admin/backup | backs up the node it is sent to into `_bak`, see [Server backup](https://agdb.agnesoft.com/#server-backup) | | /api/v1/admin/optimize | retries the pending file operations of the node it is sent to and optimizes the storage of its server database and cluster log, reporting their sizes before and after | | /api/v1/admin/shutdown | gracefully shuts down the server | | /api/v1/admin/status | lists extended statistics of the server — uptime, # dbs, # users, # logged users, server data size, process memory usage, log level | | /api/v1/admin/set_log_level | sets log level (`?new_level=`), one of `trace`, `debug`, `info`, `warn`, `error`, `off` | | /api/v1/admin/user/{username}/add | adds new user to the server | | /api/v1/admin/user/{username}/change_password | changes password of a user | | /api/v1/admin/user/{username}/logout | force logout of all sessions of a user by default, or a specific session with `?session=` | | /api/v1/admin/user/logout_all | force logout of all non-admin users | | /api/v1/admin/user/{username}/delete | deletes user and all their data (databases) from the server | | /api/v1/admin/user/list | lists the all users on the server | | /api/v1/cluster/admin/user/{username}/logout | same admin logout options as above, but applied on all nodes in the cluster | | /api/v1/cluster/admin/user/logout_all | force logout of all non-admin users from all nodes in the cluster | ### Server backup `POST /api/v1/admin/backup` takes a backup of the node it is sent to for disaster recovery. It copies the user databases, the server database and the cluster log into `_stage` next to the data directory, then switches it to `_bak`, keeping one backup. The node pauses application of writes during the copy so the catalog and database files agree. It can still serve reads. The response reports the backup's `size`, `time` in Unix seconds, and any `unavailable` databases whose files were copied as-is. The endpoint returns 503 while another backup or a snapshot install is running. The node keeps the cluster log entries needed for recovery while the backup runs. ::warning The data dir must be a subdirectory of the persistent volume, never its mount point, so that `_stage`, `_bak` and `_old` are on the same file system and persist. The backup is on the same volume as the data, copy `_bak` elsewhere to keep it safe or to keep older backups. :: The server has no built-in schedule, call the endpoint on your own schedule (e.g. a Kubernetes CronJob). To restore, stop the node and swap `` with `_bak`. To restore a whole cluster, restore one node and start the other nodes with empty data dirs so they receive a snapshot from it; do not restore several nodes from their own backups. ## Shutdown The server can be gracefully shutdown with `CTRL+C` or programmatically by using the `/api/v1/admin/shutdown` endpoint which requires admin token, e.g. ```bash token=$(curl -X POST -H 'Content-Type: application/json' localhost:3000/api/v1/user/login -d '{"username":"admin","password":"admin"}') #will produce a token, e.g. "bb2fc207-90d1-45dd-8110-3247c4753cd5" curl -X POST -H "Authorization: Bearer ${token}" localhost:3000/api/v1/admin/shutdown ``` ## Cluster You can and in most cases should run the server in a cluster for resiliency and durability of the data. The exception would be if you require speed at the cost of resiliency and durability and the `agdb` is used more as a cache rather than main database. The `agdb_server` is using custom implementation of a [Raft consensus algorithm](https://en.wikipedia.org/wiki/Raft_\(algorithm\)){rel=""nofollow""}. The benefits of the algorithm are durability, data consistency and speed as the actions do not need to be persisted to all nodes (only majority) before acknowledging the client. The custom implementation in `agdb` additionally offers the following features and guarantees atop of Raft: - Write action acknowledgement happens only when the respective action was executed fully (not just that the action was received by the majority as is the standard implementation). - Clients can request write operations through any member of the cluster (not only the leader) and the node will forward it to the current leader and act as a proxy. - When forwarding the action the node will only acknowledge the client when both of the following becomes true: - The leader committed the operation meaning the majority of the nodes persisted the action. - The node through which the action was performed executed the action itself and in full. - Even when there is no leader elected such as when the cluster is being (re)deployed the read operations are always available This means that you can freely choose a node and perform any action through it and observe consistent results at the minor performance penalty due to the forwarding (unless you picked the leader node). It might be useful in situations where reads are more frequent as they would be more spread out across the cluster. This however does NOT prevent inconsistencies in situations where every request is sent to a different node (e.g. when accessing the cluster through single service in Kubernetes). The `agdb` does not offer consistency across all nodes at all times - only leader + local node (if different) + number of other (unspecified) nodes required to reach majority. ::note The pepper value (used for additionally hashing the passwords, see the [configuration](https://agdb.agnesoft.com/#configuration) section) also needs to be the same across the cluster as when sending actions to do with passwords only the hashed values are sent between nodes rather than raw passwords for security reasons. :: The nodes use `cluster_token` from the config (see above) and calculated cluster `hash` to authenticate to each other. The hash is the calculated value based on the `cluster` array in the config listing all the nodes (`address` values) in the cluster, the `cluster_max_log_entries` and the version of the database format. It is required for the `cluster` array to be the same in the config files of all nodes. Additionally, when the `cluster` is not empty the local `address` value must match one of the addresses. The index of such address is the index of the node in the cluster. Example: ```yaml #node0 agdb_server.yaml address: http://localhost:3000 cluster: ["http://localhost:3000", "http://localhost:3001", "http://localhost:3002"] #node1 agdb_server.yaml address: http://localhost:3001 cluster: ["http://localhost:3000", "http://localhost:3001", "http://localhost:3002"] #node2 agdb_server.yaml address: http://localhost:3002 cluster: ["http://localhost:3000", "http://localhost:3001", "http://localhost:3002"] ``` ::note You should run a cluster of at least 2 nodes. Recommended number is 3 or any odd number. The even number of nodes will still work but the benefits of the consensus algorithm will be somewhat diminished due to the majority rule. Majority of 2 is 2 nodes, of 3 nodes is 2 nodes, of 4 nodes is 3 nodes, of 5 nodes is also 3 nodes etc. :: The node0 will have the index `0`, the node1 will have the index `1` and node2 will have the index `2` as their respective addresses (`address` field) match these indexes in the `cluster` array which itself is the same in all configs and thus produces the same cluster hash. This mechanism helps protect the cluster during topology change. However, if you need to change number of nodes in the cluster, you risk the [split brain issue](https://en.wikipedia.org/wiki/Split-brain_\(computing\)){rel=""nofollow""}. For instance if you changed the number of nodes from 3 to 5 on node0 then the node1 and node2 would still see the old topology of 3 nodes, elect either as leader and continued as normal. Whereas the node0 with the 2 new nodes could do the same (as majority in cluster of 5 is 3 nodes). If you must for any reason change the topology: - Perform backup of all nodes - Prevent new nodes from starting (do NOT start new nodes under any circumstances yet) - Update the configuration of the OLD (existing) nodes with the new nodes one by one - Wait for the cluster leader to be established (this is only possible if the majority rules allow it: going from 3 to 5 is fine, going from 3 to 7 is not) - Bring the new nodes up and let them synchronize with the leader ::warning Make topology changes only when absolutely necessary and exercise great care when doing it. :: The nodes send the log entries to each other as requests of at most `cluster_max_append_size` plus 64 KiB. The `request_body_limit` of every node must be at least that, otherwise the node does not start, and so must the body limit of any proxy between the nodes. A node fetches a snapshot from the leader as one streamed response of `GET {basepath}/api/v1/cluster/snapshot/{id}?offset=N`, which a proxy between the nodes must allow too. ### Failures and repair The cluster keeps its log in `{data_dir}/agdb_server.log` and prepares the snapshots for other nodes in `{data_dir}/.agcluster/staging`. A node that falls behind receives the missing log entries from the leader. A node behind the log the leader still keeps, e.g. one that was down for long, receives a full snapshot of the server and of all databases instead, fetched from the leader as one stream that is given up only when no data arrives within `cluster_rpc_timeout_ms` and resumed where it stopped. An action that fails for its own reason, e.g. an invalid query, fails the same way on every node and the error is its result. An action that fails on a node for any other reason, e.g. a disk error, does not change the result: that node waits with the later actions touching the same database, user or dashboard and the leader sends it a copy of just that database or record. Every node also compares the results of the recent actions with the leader and takes a copy of the data an action changed whenever the results differ. Every change of the files of a database waits for the queries already running on it, and the queries started meanwhile wait for the change. The node records each change in its journal `{data_dir}/agdb_server.journal` before it touches the files and prepares the new files in `{data_dir}/.staging`. A change that fails is undone or finished from the journal at once, on the next start or by `/api/v1/admin/optimize`. A database stays on the server when a change of its files fails. A database whose files cannot be opened, e.g. on start or after a failed change, or with a change still pending in the journal, answers 503 `db unavailable` with the error and an action writing it fails like on a disk error. The node opens it again on its next restore, rollback or conversion and on `/api/v1/admin/optimize`, and the leader before it sends a copy of it to another node. If it still cannot be opened, the leader sends its files as they are and the other node keeps the database unavailable too until it can be opened. A node installing a full snapshot prepares it in full first and keeps serving its old data until it switches to it. A failed action is never retried. If the leader itself fails to run an action, it gives up on it at once and records that in its log: the action fails with 471, the data it touched is kept as it is on the leader and the other nodes get a copy of it. If that leader is lost before the other nodes copied the data, the copy of the next leader is kept instead, so after a leader change an action that failed with 471 may still have taken effect. The leader stays the leader unless it cannot read its own log, then another node takes over. If the leader cannot even mark the data it touched, the action fails with 520 as it may still take effect when the node replays its log. An action that does not finish within 50 s, or whose leader loses the leadership or stops before it is committed, or whose forward from another node fails after it may have reached the leader, fails with 520, it may or may not be executed. An action that was committed but whose result was lost on the node, e.g. as the node received the data in a snapshot instead or stopped before applying it, fails with 521 with its index in the message: it is final and the data shows its outcome once applied. An action that fails with 503 was not executed and can be retried. The cluster never waits for a broken database indefinitely. ::note Upgrading from a version with the previous cluster implementation: the new version does not replay the old cluster log and removes it on start. Let all nodes catch up with the leader and stop them before the upgrade so that they all start with the same data. :: ## Misc Following are the special or miscellaneous endpoints: | Endpoint | Description | | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | /api/v1 | serves rapidoc OpenAPI GUI (use this in the browser) | | /api/v1/openapi.json | returns the server's OpenAPI specification as json | | /api/v1/status | returns 200 OK if the server is ready (up) | | /api/v1/cluster/status | returns the list of cluster nodes as the leader last reported them to the current node (reachable, leader, executed index, resync); without a recent word from the leader only the current node is known | | /studio/ | serves agdb Studio (only when the server is built with the `studio` feature) | # Studio The agdb studio is the web GUI of the [`agdb_server`](https://agdb.agnesoft.com/docs/references/server), written in Vue and built into the server binary. For how to use it, see the guide: [How to use the studio?](https://agdb.agnesoft.com/docs/guides/how-to-use-studio) ## Serving - The studio is part of the server only when it is built with the `studio` cargo feature, e.g. `cargo build --release -p agdb_server --features "tls studio"` in a checkout of the agdb repository. The feature is off by default and the build needs Node.js and `pnpm`. The official Docker image includes the studio. If `agdb_studio/app/dist` already exists, the build embeds it as it is; delete it to build the studio again. - The server serves it at `
/studio/`. When the server starts, it points the studio's requests to its configured `address` and `basepath`, so `address` must be the URL the browser reaches the server at (e.g. the public URL of a reverse proxy). In a cluster, `address` also identifies the node to the other nodes, so each node keeps its own reachable address; connect the studio to a node directly or enter the node's URL as **Server URL** when logging in. - Every address under `/studio/` opens the studio, so links to its pages work directly. - A login lasts for `token_expiry_seconds` of the [server configuration](https://agdb.agnesoft.com/docs/references/server#configuration). - Dashboards and the home dashboard are stored on the server (see [Dashboards](https://agdb.agnesoft.com/docs/references/server#dashboards) in the server reference). The browser keeps the login token and the theme, and for each tab the page to return to after login. The chosen cluster node is not kept: a reload returns to the server that serves the studio. Queries are kept in the page address. ## Pages All addresses are under `/studio`. Every page except the login needs a login; the admin pages need the server admin. | Address | Page | Who | | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ------ | | `/login` | Log in | anyone | | `/` | Your home dashboard, or the databases when you have none | user | | `/db` | [Databases](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/databases) | user | | `/query//` | [Query](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/queries), with the queries in `?exec=`, `?exec_mut=` and `?context=` | user | | `/dashboards` | [Dashboards](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/dashboards) | user | | `/dashboards//` | A dashboard | user | | `/admin` | [Server status](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/admin#status) | admin | | `/admin/users` | [Users](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/admin#users) | admin | | `/admin/db` | [All databases](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/admin#databases) | admin | | `/admin/query//` | Query with admin access | admin | | `/admin/dashboards` | [All dashboards](https://agdb.agnesoft.com/docs/guides/how-to-use-studio/admin#dashboards) | admin | | `/admin/dashboards//` | A dashboard with admin access | admin | The login page also takes `?server=` to fill in the **Server URL**. ## Keyboard shortcuts | Where | Keys | Action | | ---------------------- | -------------------------------------- | ------------------------------------------------------------------------- | | Query builder | Ctrl/Cmd+Enter | Run the queries of the tab | | Query builder | Ctrl/Cmd+Z | Undo (not in a field that has text) | | Query builder | Ctrl/Cmd+Shift+Z, Ctrl+Y | Redo | | Query builder tabs | ← / → | Switch tab | | Step input | ↑ / ↓, Enter, Esc | Move through the suggestions, pick one, close the list and clear the text | | Step input | Backspace (empty input) | Remove the previous step | | Query row | Ctrl+V | Paste `QueryBuilder` code | | Focused step | Enter / Space | Edit the arguments | | Focused step | Delete / Backspace | Remove the step | | Argument editor | Esc, Enter in a value | Close the editor | | Row grip handle | ↑ / ↓ | Move the row | | Row number | Shift+↑ / ↓, Shift+click, Ctrl+click | Select rows | | Selected rows | Ctrl+C / Delete / Esc | Copy / remove / clear the selection | | Graph | Shift+click | Pin or unpin the element's details | | Graph | Esc | Close the menu, the views menu, the Style panel, then add edge mode | | Chart | Arrow keys, Home / End (chart focused) | Show the values one by one | | Value editor | Enter / Esc | Save / cancel | | Database table | Enter / Space on a row | Open the database | | Menus | ↑ / ↓, Home / End, → / ←, Enter | Move, open and close submenus, choose | | Dialogs, menus, panels | Esc | Close | ## Limits | What | Limit | | --------------------------- | ---------------------------------------------------------- | | Queries in the page address | about 6,000 characters | | Undo history | 100 steps per tab | | Nodes drawn in the graph | 2,000 | | Table page | 100 rows | | JSON view | 50,000 characters before **Show all** | | Chart | 12 bars, 5 donut slices, 5 lines, each including "Other" | | Dashboard size | 256 KB of widgets and layout | | Dashboard name | 1–64 letters, digits, `_`, `-`, `.`; not starting with `.` | | Widget size | 1–4 columns wide, 1–3 rows high | | Widget auto refresh | choices from 10 seconds to 1 hour | | Notification history | 50 | ## Accessibility and layout - Everything can be used with the keyboard. **Skip to content** is the first stop on every page, and menus, tables and dialogs follow the usual keyboard patterns. - Key pages are checked automatically with axe against WCAG 2.1 AA in both the light and the dark theme. Colours come with a text or a shape, e.g. the cluster status is spelled out when it is not healthy. - Animations are turned off when the operating system asks for reduced motion. - Prints always use the light theme. - Below 900 px wide the navigation moves into a menu button, tables scroll sideways, and dashboards use 1 column (2 columns from 900 to 1199 px). # Cloud There are two ways to run `agdb` in the cloud: host the `agdb_server` yourself on any cloud provider, or use the managed offering. ## Self-hosted The `agdb_server` is a single binary (also published as a Docker image) so it runs anywhere a container or a Linux/Windows VM runs. Pick the guide that matches your target: | Target | Single server | Cluster | | -------------------------------------------- | ------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- | | VM / bare metal | [Server - bare metal](https://agdb.agnesoft.com/docs/guides/how-to-run-server/server-bare-metal) | [Cluster - bare metal](https://agdb.agnesoft.com/docs/guides/how-to-run-server/cluster-bare-metal) | | Container service (ECS, Cloud Run, ACI, ...) | [Server - Docker](https://agdb.agnesoft.com/docs/guides/how-to-run-server/server-docker) | [Cluster - Docker](https://agdb.agnesoft.com/docs/guides/how-to-run-server/cluster-docker) | | Managed Kubernetes (EKS, GKE, AKS, ...) | [Server - Kubernetes](https://agdb.agnesoft.com/docs/guides/how-to-run-server/server-k8s) | [Cluster - Kubernetes](https://agdb.agnesoft.com/docs/guides/how-to-run-server/cluster-k8s) | Things to check when deploying to the cloud: - **Storage**: use block storage (e.g. a persistent volume) for the data directory. Network or FUSE-based filesystems may reorder writes; see the `sync_mode` option in the [server reference](https://agdb.agnesoft.com/docs/references/server). - **TLS**: terminate TLS at the server (`tls_certificate` / `tls_key`) or at a load balancer in front of it. - **Cluster**: every node needs a stable address that the other nodes can reach, which is why the Kubernetes guides use a StatefulSet. All configuration options are described in the [server reference](https://agdb.agnesoft.com/docs/references/server). ## Managed cloud A managed `agdb` cloud is offered as part of the [enterprise](https://agdb.agnesoft.com/enterprise/cloud) services. # Efficient agdb In this document we will explore more realistic use of the `agdb`. It should help you understand how to make the best use of the `graph` data schema and how to build complex queries. The premise that we will be working on is building a database for a social network. The users of the network can create posts and share them with other users to comment and like. You can see the complete code under [tests/efficient_agdb/mod.rs](https://github.com/agnesoft/agdb/blob/main/agdb/tests/efficient_agdb/mod.rs){rel=""nofollow""}. ## The setup ```rs fn create_db() -> Result, DbError> { let db = Arc::new(Db::new("social.agdb")?); db.transaction_mut(|t| -> Result<(), DbError> { t.exec_mut( QueryBuilder::insert() .nodes() .aliases(["root", "users", "posts"]) .query(), )?; t.exec_mut( QueryBuilder::insert() .edges() .from("root") .to(["users", "posts"]) .query(), )?; Ok(()) })?; Ok(db) } ``` We are setting up the database for the multithreaded use with the `Arc` (the database methods take `&self` so no additional lock is needed) in order to leverage unlimited read parallelism - writes are serialized internally while reads run concurrently against the last committed state. We create nodes for `users` and one for `posts` and create a `root` node and connect the other two to it. The `agdb` does allow disjointed graphs, but it is not easy to navigate an unknown database (e.g. when opening the database file in a data editor/explorer without knowing its content). A useful convention is thus to specify a root node. If it is a first node (that would always end up with the `id` == `1`) or has an alias (i.e. `root`) the entry-point is known. We can then connect other nodes to it or insert their aliases (or `ids`) as properties to the `root` node. There is no preferred or hard-coded method to do this which is intentional. You may also choose not to do it at all if you do not have a need for data discovery. ### Users The users of our social network will be nodes connected to the `users` node. The information we want to store about our users are: - username - e-mail - password Let's first define the `User` struct to hold this information: ```rs #[derive(DbType)] struct User { username: String, email: String, password: String, } ``` We derive from `agdb::DbType` so we can use the `User` type directly in our queries. A query creating the user would therefore look like this: ```rs fn register_user(db: &Db, user: &User) -> Result { db.transaction_mut(|t| -> Result { if t.exec( QueryBuilder::search() .from("users") .where_() .key("username") .value(&user.username) .query(), )? .result != 0 { return Err(DbError::db( DbErrorType::NotAllowed, format!("User {} already exists.", user.username), )); } let user = t .exec_mut( QueryBuilder::insert() .element(user) .query(), )? .elements[0] .id; t.exec_mut( QueryBuilder::insert() .edges() .from("users") .to(user) .query(), )?; Ok(user) }) } ``` First we check if the user exists and return error if the username is taken. We then use a transaction to create a user node and edge from `users` node. The reason why this is done in two steps (queries) is to keep the queries simpler and because we want to get back the result of the node insertion - the user `id`. If we fed the insert nodes query to the insert edges query the `id` would be lost. ### Posts The users should be able to create posts. The data we want to store about the posts are: - title - body - author Once again let's define the `Post` type. The specially treated `db_id` field will become useful later on: ```rs #[derive(DbType)] struct Post { db_id: Option, title: String, body: String, } ``` The first two will become properties while the `author` will be represented as an edge. To create a post: ```rs fn create_post(db: &Db, user: DbId, post: &Post) -> Result { db.transaction_mut(|t| -> Result { let post = t .exec_mut( QueryBuilder::insert() .element(post) .query(), )? .elements[0] .id; t.exec_mut( QueryBuilder::insert() .edges() .from([QueryId::from("posts"), user.into()]) .to(post) .values([vec![], vec![("authored", 1_u64).into()]]) .query(), )?; Ok(post) }) } ``` Beside connecting the node to two others we are also adding a property `authored` to the edge coming from the `user`. This is to distinguish it from other possible edges coming from the user - comments and likes. ### Comments The comments are created by the users and are either top level comments on a post or replies to other comments. Information we want to store about the comments are: - body - author - parent (post OR comment) We define the comment type: ```rs #[derive(DbType)] struct Comment { body: String, } ``` To create a comment: ```rs fn create_comment( db: &Db, user: DbId, parent: DbId, comment: &Comment, ) -> Result { db.transaction_mut(|t| -> Result { let comment = t .exec_mut( QueryBuilder::insert() .element(comment) .query(), )? .elements[0] .id; t.exec_mut( QueryBuilder::insert() .edges() .from([parent, user]) .to(comment) .values([vec![], vec![("commented", 1_u64).into()]]) .query(), )?; Ok(comment) }) } ``` The `parent` parameter can be either a post `id` or a comment `id`. The edges from the user have now a property `commented` to distinguish them from `authored` edges. ### Likes Likes can be best modelled as connections from users to posts and comments: ```rs fn like(db: &Db, user: DbId, id: DbId) -> Result<(), DbError> { db.exec_mut( QueryBuilder::insert() .edges() .from(user) .to(id) .values_uniform([("liked", 1).into()]) .query(), )?; Ok(()) } ``` The query is fairly self-explanatory. The edge has the `liked` property that distinguishes it from the other edges from a user (i.e. `authored` and `commented`). Since users can decide that they no longer like a post or comment we need to have the ability to remove it: ```rs fn remove_like(db: &Db, user: DbId, id: DbId) -> Result<(), DbError> { db.transaction_mut(|t| -> Result<(), DbError> { t.exec_mut( QueryBuilder::remove() .search() .from(user) .to(id) .where_() .keys("liked") .query(), )?; Ok(()) }) } ``` This query removes elements returned by the search. The search is the "path search" starting (`from`) the user and looking for the `id` (`to`). It selects only the element with the `liked` property which would be the edge we are looking for. The query is simple because it takes advantage of several facts: - if the `id` exists the path to it will contain 3 elements: starting node, an edge and the `id` node - elements not selected for the result by the condition are penalized in the path search eliminating the candidate path through the `authored` node - `limit(1)` is not useful here because path search applies the limit after it found the best path which would be as described - containing just one suitable element anyway Still if we were unsure the `id` exists or if we wanted to limit the search area as much as possible we could create a chain of conditions to only restrict the search to a particular distance and prevent the other edges to be followed: ```rs .where_() .keys("liked") .and() .beyond() .keys("liked") ``` This condition ensures that traversal only follows edges that have the `liked` property. The search stops at the first node reached after traversing the last such `liked` edge, which may be the destination node. Additionally, it will not continue from a node unless there is an adjacent edge with the `liked` property. ## Selects & Searches Now that we have the data in our database and means to add (or remove) more it is time to create the select and search queries. Recall that the search queries find the `ids` of the database (graph) elements. To read properties the properties you would need to combine it with a `select` query. ### Login First the user login which means searching the database for a particular username and matching its password: ```rs fn login(db: &Db, username: &str, password: &str) -> Result { let result = db .exec( QueryBuilder::select() .values("password") .search() .depth_first() .from("users") .limit(1) .where_() .neighbor() .and() .key("username") .value(username) .query(), )? .elements; let user = result.first().ok_or(DbError::db( DbErrorType::NotFound, format!("Username '{username}' not found"), ))?; let pswd = user.values[0].value.to_string(); if password != pswd { return Err(DbError::db( DbErrorType::NotAllowed, "Password is incorrect", )); } Ok(user.id) } ``` First we retrieve the password if the user exists: 1. Start the search at the `users` node using depth first algorithm. The depth first is better here because it allows us to examine users in sequence rather than first examining all the edges from the `users` node and only then all the users. 2. Limit the search to just a single element (`limit(1)`) as we want just one user, and we want to stop once it is found. 3. Limit the distance of the search to elements at distance 2 (distance 0 = starting node, distance 1 == edges from users, distance 2 == user nodes). 4. Check `username` property for a match against the passed in username. Upon success, we attempt to get the first element in the result returning "user not found" if it is not there. Finally, we get the value of the password (we have selected single property so we know it is there) from the result and check if the password matches. You may be wondering why we do not check the password in the query directly. The reason is that we have no way of stopping the further search if only the `username` matched but not the `password`. The search would then needlessly continue over all users. Therefore, we only retrieve the password and match it in the code. Since it would be salted and hashed anyway it would not be possible to do it with a database query in the first place. ### User content Showing users their content or content they liked can be done with a following query first retrieving the `ids` of the posts: ```rs fn user_posts_ids(db: &Db, user: DbId) -> Result, DbError> { Ok(db .exec( QueryBuilder::search() .from(user) .where_() .neighbor() .and() .beyond() .keys("authored") .query(), )? .ids()) } ``` This time we search from the logged in `user` node identified by its `id` (i.e. returned from the `login()` function). We know the posts are at distance 2 from there (beyond just a single edge) so the first condition is `distance(Equal(2))` (neighbor) to select the elements we want. We narrow down the search further with `beyond()` and a condition that limits where we want the search to go. That is the purpose of the `keys("authored")` so only elements with `authored` key are followed. Note that `beyond()` only controls traversal and does not select elements on its own - the `neighbor()` condition handles the selection. The same outcome can be reached with number of other conditions as well. For example using `keys("title")` condition. However, it would also examine all the comments and likes (you may remember similar discussion in the method to [remove likes](https://agdb.agnesoft.com/#likes)). Another option could be using `not_beyond()` with `where_().keys("commented").or().keys("liked")` - explicitly stopping at edges with those properties (`commented` and `liked`). The `keys()` condition is "all or nothing" so it needs to be `or`ed and specified twice in this case. Similarly to `user_posts` we can fetch the user comments and liked posts with slight modification of the condition: - user comments: `.keys("commented")` - liked posts: `keys("title")` and `.keys("liked")` Notice as well that the function returns the `ids` of the elements we were interested in which gives us flexibility in what we want to retrieve about the posts. In order to retrieve say titles of the posts we would need to feed it to a select query: ```rs fn post_titles(db: &Db, ids: Vec) -> Result, DbError> { Ok(db .exec( QueryBuilder::select() .values("title") .ids(ids) .query(), )? .elements .into_iter() .map(|post| post.values[0].value.to_string()) .collect()) } ``` Here we take advantage of the fact that we have selected a single property so that every element in the result is guaranteed to have it. ### Posts Selecting all posts is a fairly straightforward query, but we would rarely need all of them at once. A common need for large collections of data is "paging". That means returning only a chunk of data at a time. Similarly to SQL we can use both `offset` and `limit` to achieve this: ```rs fn posts(db: &Db, offset: u64, limit: u64) -> Result, DbError> { db .exec( QueryBuilder::select() .elements::() .search() .from("posts") .offset(offset) .limit(limit) .where_() .neighbor() .query(), )? .try_into() } ``` By running the function repeatedly and incrementing the `offset` by the `limit` we would iterate over all posts in `limit` steps (usually called "pages"). Notice the `distance` condition which is all we need to limit the search to just posts. There is something missing though as we would want to also order the posts by the number of likes they have. That would be possible with the current schema but not very easily. We will revisit this a later when we will discuss the schema updates. ### Comments Now that we have the posts we will want to fetch the comments on them. Our schema says that the only outgoing edges from posts are the comments so getting the comments can be done like this: ```rs fn comments(db: &Db, id: DbId) -> Result, DbError> { db .exec( QueryBuilder::select() .elements::() .search() .depth_first() .from(id) .where_() .node() .and() .distance_greater_than(1) .query(), )? .try_into() } ``` Using the `depth_first` algorithm will help in organizing the comments in their natural tree structure in the result. The comments are nodes so `.node()` is the first condition. We are starting at the post, but we are not interested in selecting that hence the condition `.distance_greater_than(1)`. Since we are selecting the `body` property we can assume it when extracting it to a vector of comments. There is another flaw here however, do you see it? We currently do not have a way to tell which comment is a top level comment to correctly present the comments to the user other than in a flat list. This is another case for a schema update to satisfy this requirement. ## Schema updates Possibly the most common problem with any database is that it contains the information we want in some form, but it does not allow us using it in the way we would like. Perhaps we want to join the information together or get it in a different format than in which it is stored. Or the information is not there, and we need to start capturing it. These issues are not unique to `agdb` or to databases in general for that matter. They are ubiquitous in all software as requirements and our understanding of the problem domains change over time. The ability to change is what matters the most. Let's see how `agdb` tackles it. In our case we have already identified two such issues with our database so far: - ordering posts based on likes - determining level of comments We can perhaps already come up with more such as getting the authors of posts or comments, missing timestamp information etc. There are certainly more but for now let's focus on the two highlighted ones: ### Likes Let's start with the likes. The query to make use of the `liked` edges would not be terribly difficult (counting the `liked` edges incoming to a post or comment) but it certainly does not seem that easy or fast. Especially as we would be doing it over and over. Instead, we could simply introduce a counter property called `likes` and essentially cache the information on the posts (or comments) themselves. That would simplify and speed up things: ```rs fn add_likes_to_posts(db: &Db) -> Result<(), DbError> { db.transaction_mut(|t| -> Result<(), DbError> { let posts = t.exec( QueryBuilder::search() .from("posts") .where_() .neighbor() .query(), )?; let mut likes = Vec::>::new(); for post in posts.ids() { let post_likes = t .exec( QueryBuilder::search() .to(post) .where_() .distance(1) .and() .keys("liked") .query(), )? .result; likes.push(vec![("likes", post_likes).into()]); } t.exec_mut(QueryBuilder::insert().values(likes).ids(posts).query())?; Ok(()) }) } ``` We are doing a mutable transaction to prevent any new posts, likes or other modifications to interfere while we do this. First we get the `ids` of all the posts. Then we count the `liked` edges of each post (exactly what we would be doing if we did not want to change the schema) and finally we insert a new `likes` property with that count back to the posts. Furthermore, we should update our definition of `Post`: ```rs #[derive(DbType)] struct PostLiked { db_id: Option, title: String, body: String, likes: i64, } ``` This allows us to select and order posts based on likes: ```rs fn liked_posts(db: &Db, offset: u64, limit: u64) -> Result, DbError> { db .exec( QueryBuilder::select() .elements::() .search() .from("posts") .order_by([DbKeyOrder::Desc("likes".into())]) .offset(offset) .limit(limit) .where_() .neighbor() .query(), )? .try_into() } ``` However, this change is not "free" in that caching any information means it now exists in two places and those places must be synchronized (the famous cache invalidation problem). Fortunately this instance is not as hard. We simply make sure that whenever we add or remove `likes` we also update the counter on the post or comment. Since when we do those operations we also have the post/comment `id` doing that would be trivial. ### Comments Another issue we found was that comments do not track their level, and we cannot present them hierarchically. To make things simpler let's add only a simple distinction between top level comments and replies disregarding any further nesting. To do that we would simply mark the top level comments with a new property: ```rs fn mark_top_level_comments(db: &Db) -> Result<(), DbError> { db.exec_mut( QueryBuilder::insert() .values_uniform([("level", 1).into()]) .search() .from("posts") .where_() .distance(4) .query(), )?; Ok(()) } ``` Although this task might have seemed daunting it could be done with a simple query that once more takes advantage of the graph schema. We know that the only outgoing edges from the posts are the comments and that they are hierarchical (replies are attached to the comments they reply to). Therefore, when searching from the `posts` node at distance `4` we will find only the top level comments. We then uniformly apply a property `level=1` to them. Such a property could then be used by the client code to determine how the data is displayed to the users. ## Summary In this guide we have gone through a realistic example of an inception of a database setting it up from scratch, designing search queries and leveraging the graph schema. We have used the ability to limit the search area based on our data and the graph schema multiple times. Instead of searching possibly millions of records and filtering them out to get what we want we could search & select just the relevant fraction of the data set. That is the main advantage of the graph databases. If a user authored just 3 posts the query would do exactly the same work if there were 30 posts total in the database as if there were 3 billion. We have also discovered issues with the schema and were able to seamlessly fix them. It demonstrated yet another important aspect of graph databases which is fearless schema updates. Modelling data on a graph feels natural and changing it to fit new or changing requirements is just as natural. Lastly we have seen that the queries can be simple, readable, statically checked and completely native while still providing complex functionality such as filtering through conditions, paging, ordering etc. Moreover, while the features of object queries won't make them always logically correct they eliminate entire categories of issues like syntax errors, type errors, security issues like SQL injection, and even certain logic errors etc. For the comprehensive overview of all queries see the [query reference](https://agdb.agnesoft.com/docs/references/queries). For the code used in this document see [the code in the tests](https://github.com/agnesoft/agdb/blob/main/agdb/tests/efficient_agdb/mod.rs){rel=""nofollow""}. # Performance Database performance is one of the key metrics when judging the suitability of the solution for a given use case. Individual metrics such as how many inserts or selects can a database handle in a tight loop are not very interesting or indicative of real performance. In this document we will therefore examine the performance of `agdb` in more realistic use cases via `agdb_benchmark` that simulate real world usage. The `agdb` is designed with the following principles: - ACID database - O(1) complexity for direct access - O(n) complexity for search - Unlimited read concurrency: snapshot readers that do not wait for the writer except briefly while it publishes a small commit - Serial writes: one exclusive writer at a time The database is ACID compliant, operations must be transactional = `atomic` (A) meaning they are "all or nothing" operations, `consistent` (C) so that the queries will only produce valid state of the data, `isolated` (I) meaning the transactions do not affect each other when in flight and `durable` (D) meaning the database is resistant to system failure and will preserve integrity of the data. Direct access read/write operations have constant complexity of O(1) while search operations are O(n) but the `n` can be limited to a subgraph greatly reducing the time the operation takes. Let's see if the `agdb` lives up to these principles. ## Concurrency model Reads (`exec()` and `transaction()`) run on a consistent snapshot of the last commit. They never block the writer and wait for it only briefly while it publishes a small commit (up to 1 MiB that it writes in place when no reader holds the snapshot). A custom storage that does not provide snapshots is read under the database lock and readers then wait for the whole write. Writes (`exec_mut()` and `transaction_mut()`) are serial: `transaction_mut()` holds the exclusive writer lock for the whole closure, so the result of a write never depends on the timing of another writer. To write from many threads without holding the writer lock longer than necessary read and compute in `transaction()` and then run a short `transaction_mut()` that only writes. The write must resolve its targets again (by alias, index or a search condition) or check them. The ids read from a snapshot are not stable across commits as the ids of removed elements are reused, so an id found by the read may belong to a different element (or to none) when the write runs. The same applies to the values: if a value read in `transaction()` decides what gets written, read it again in the `transaction_mut()`, otherwise a write committed in between is silently overwritten. ## The benchmark The `agdb_benchmark` project is building upon the [Efficient agdb](https://agdb.agnesoft.com/docs/references/efficient-agdb) simulating the traffic in a "social network" database. It simulates concurrent read & write operations on the same database: - Posters: Writes social media posts - Commenters: Writes comments to the existing posts - Post readers: Reads existing posts - Comment readers: Read existing comments It is highly configurable through the `agdb_benchmark.yaml` (or custom file passed as an argument, produced on first run) with the following settings: - Running using embedded database or against a server - How many of each category of users (post writers, comment writers, post readers, comment readers) - How many operations should each user perform - How large each operation should be [readers only] (e.g. how many posts to read) - Contents of each operation [writes only] (e.g. post title, post body) - Delay between each operation For writers the configured content is additionally augmented by the user `id` to produce unique content. The delays are further shifted by the user `id` to prevent unrealistic resource contention by everyone in a single millisecond. The read operations are repeated if no result is yielded effectively "waiting" for the readers to input data first. The benchmark uses tokio tasks spawning everything together. It measures each database operation (transaction as some operations are multiple queries) for minimum, average, maximum and total elapsed time. Additionally, it shows total database size after all operations finished and furthermore after running the optimization algorithm compacting (defragmenting) the data. ### Default settings - Insert user nodes (for post & comment writers) - 10 post writers (100 posts each, 100ms delay, non-small title (>15 bytes) & body (>15 bytes)) - 10 comment writers (100 comments each, 100ms delay, non-small body (>15 bytes)) - 100 post readers (100 reads each, 10 posts per read, 100ms delay) - 100 comment readers (100 reads each, 10 comments per read, 100ms delay). ### Measured operations - Insert user nodes: a node aliased `"users"` with individual users connected to it with a blank edge. Each user has properties `"name"` and `"email"` (values small values `<15 bytes`). - Write posts: a post node connected with a blank edge to the single node aliased `"posts"` and with an edge (property `"authored": 1`) to the respective user node. The properties are `"title"` and `"body"` from config (values are large `>15 bytes`). - Write comments: a comment node connected with a blank edge to the latest post (found via search from `"posts"` node) and with an edge (property `"commented": 1`) to the respective user node. The properties are only `"body"` from config (value is large `>15 bytes`). - Read posts: reads configured amount (e.g. 10 by default) of recent posts on each iteration (found via search from `"posts"` node). - Read comments: reads configured amount (e.g. 10 by default) of recent comments on the latest post (found via search from `"posts"` node). - Database size: after all operations finished & after optimization algorithm is run. ### Run command ```bash cargo run --release -p agdb_benchmark ``` ## Results The following benchmarks were run on: - CPU: Intel Core i7-7700 4 cores (8 logical cores) @ 3,6 GHz - RAM: Crucial Ballistix Sport LT 16GB (2x8GB) DDR4 @ 2400 MHz - DISK: HyperX Savage - 240GB (KINGSTON SHSS37A240G, 4 cores, 8 channels Phison S10, 560 MB/s read, 530 MB/s write, SATA III (6 Gb/s)) - OS: Windows 10 22H2 (19045.3448), Debian: Version 12 (bookworm) [running in Hyper-V/WSL2] When running on a different machine your results will vary, but the relative comparisons should still hold. ### Memory mapped (default) The benchmark run with [default settings](https://agdb.agnesoft.com/#default-settings) using memory mapped file persistent storage (database size is limited to available RAM): **Windows** | Description | Threads | Iters | Per iter | Count | Min | Avg | Max | Total | | -------------- | -------- | ------ | -------- | ------ | ----- | ------ | ------ | ----- | | Creating users | 1 | 1 | 20 | 20 | - | 1 ms | - | 30 ms | | Write posts | 10 | 100 | 1 | 1 000 | 1 ms | 25 ms | 3 s | 8 s | | Write comments | 10 | 100 | 1 | 1 000 | 1 ms | 29 ms | 3 s | 8 s | | Read posts | 100 | 100 | 10 | 10 000 | 14 μs | 387 μs | 282 ms | 9 s | | Read comments | 100 | 100 | 10 | 10 000 | 9 μs | 295 μs | 21 ms | 9 s | | Database size | 1 627 kB | 785 kB | | | | | | | **Debian (Hyper-V/WSL2)** | Description | Threads | Iters | Per iter | Count | Min | Avg | Max | Total | | -------------- | -------- | ------ | -------- | ------ | ------ | ------ | ------ | ----- | | Creating users | 1 | 1 | 20 | 20 | - | 316 μs | - | 6 ms | | Write posts | 10 | 100 | 1 | 1 000 | 390 μs | 1 ms | 141 ms | 2 s | | Write comments | 10 | 100 | 1 | 1 000 | 397 μs | 1 ms | 286 ms | 1 s | | Read posts | 100 | 100 | 10 | 10 000 | 12 μs | 716 μs | 287 ms | 5 s | | Read comments | 100 | 100 | 10 | 10 000 | 6 μs | 445 μs | 286 ms | 5 s | | Database size | 1 627 kB | 785 kB | | | | | | | --- The data shows that the average write operation without contention is very fast (Creating users). Concurrent writes that also contest the database with read operations increase the latency by an order of magnitude. The read operations that can be as fast as <10μs can slow down with contention up to two orders of magnitude particularly due to frequent reads. ### File only The benchmark run with [default settings](https://agdb.agnesoft.com/#default-settings) using file persistent storage only (no memory use but unlimited database size): **Windows** | Description | Threads | Iters | Per iter | Count | Min | Avg | Max | Total | | -------------- | -------- | ------ | -------- | ------ | ------ | ------ | ------ | ----- | | Creating users | 1 | 1 | 20 | 20 | - | 1 ms | - | 38 ms | | Write posts | 10 | 100 | 1 | 1 000 | 1 ms | 650 ms | 96 s | 306 s | | Write comments | 10 | 100 | 1 | 1 000 | 1 ms | 1 s | 149 s | 306 s | | Read posts | 100 | 100 | 10 | 10 000 | 604 μs | 23 ms | 758 ms | 305 s | | Read comments | 100 | 100 | 10 | 10 000 | 390 μs | 28 ms | 775 ms | 304 s | | Database size | 1 627 kB | 785 kB | | | | | | | **Debian (Hyper-V/WSL2)** | Description | Threads | Iters | Per iter | Count | Min | Avg | Max | Total | | -------------- | -------- | ------ | -------- | ------ | ------ | ------ | ------ | ----- | | Creating users | 1 | 1 | 20 | 20 | - | 340 μs | - | 6 ms | | Write posts | 10 | 100 | 1 | 1 000 | 459 μs | 9 ms | 304 ms | 67 s | | Write comments | 10 | 100 | 1 | 1 000 | 431 μs | 15 ms | 99 ms | 65 s | | Read posts | 100 | 100 | 10 | 10 000 | 384 μs | 23 ms | 351 ms | 68 s | | Read comments | 100 | 100 | 10 | 10 000 | 61 μs | 24 ms | 213 ms | 68 s | | Database size | 1 627 kB | 785 kB | | | | | | | Running purely off a file significantly decreases performance. While the minimum write times remain expectedly the same as with memory mapped option (that uses the same underlying persistent file storage for writes) the average and particularly maximum times increased dramatically. This indicates that for data sets too large to fit to RAM running purely off a file is not a viable option either due to prohibitively bad performance. Therefore, a different strategy would be required (in-memory caching, splitting the data set over multiple databases etc.). The file based database might be suitable for write heavy use cases with huge amounts of data such as log store where operations can be serialized to limit the contention and reads/searches are relatively infrequent and do not collide with writes often. ### In memory (cache only) The benchmark run with [default settings](https://agdb.agnesoft.com/#default-settings) using in-memory cache only (no persistence): **Windows** | Description | Threads | Iters | Per iter | Count | Min | Avg | Max | Total | | -------------- | -------- | ------ | -------- | ------ | ----- | ------ | ------ | ------ | | Creating users | 1 | 1 | 20 | 20 | - | 9 μs | - | 189 μs | | Write posts | 10 | 100 | 1 | 1 000 | 11 μs | 5 ms | 442 ms | 3 s | | Write comments | 10 | 100 | 1 | 1 000 | 10 μs | 10 ms | 440 ms | 3 s | | Read posts | 100 | 100 | 10 | 10 000 | 14 μs | 300 μs | 7 ms | 6 s | | Read comments | 100 | 100 | 10 | 10 000 | 13 μs | 319 μs | 7 ms | 6 s | | Database size | 1 627 kB | 785 kB | | | | | | | **Debian (Hyper-V/WSL2)** | Description | Threads | Iters | Per iter | Count | Min | Avg | Max | Total | | -------------- | -------- | ------ | -------- | ------ | ---- | ------ | ---- | ------ | | Creating users | 1 | 1 | 20 | 20 | - | 6 μs | - | 125 μs | | Write posts | 10 | 100 | 1 | 1 000 | 6 μs | 503 μs | 7 ms | 2 s | | Write comments | 10 | 100 | 1 | 1 000 | 4 μs | 374 μs | 1 ms | 1 s | | Read posts | 100 | 100 | 10 | 10 000 | 9 μs | 729 μs | 8 ms | 5 s | | Read comments | 100 | 100 | 10 | 10 000 | 6 μs | 741 μs | 5 ms | 5 s | | Database size | 1 627 kB | 785 kB | | | | | | | Unsurprisingly by far the fastest option. Operating purely off RAM offers unmatched performance but without any persistence such a database can be of limited use. Still for caching purposes this solution is very viable offering sub-millisecond performance for all operations (read & write) with minimal impact of contention even in highly contested cases such as the one being benchmarked. ### In Memory (10x) Increasing the number of writers and readers 10x: | Description | Threads | Iters | Per iter | Count | Min | Avg | Max | Total | | -------------- | ------- | -------- | -------- | ------- | ----- | ------ | ------ | ----- | | Creating users | 1 | 1 | 200 | 200 | - | 9 μs | - | 1 ms | | Write posts | 100 | 100 | 1 | 10 000 | 10 μs | 152 ms | 34 s | 497 s | | Write comments | 100 | 100 | 1 | 10 000 | 9 μs | 154 ms | 64 s | 496 s | | Read posts | 1 000 | 100 | 10 | 100 000 | 21 μs | 3 ms | 235 ms | 497 s | | Read comments | 1 000 | 100 | 10 | 100 000 | 12 μs | 4 ms | 344 ms | 497 s | | Database size | 12 MB | 6 528 kB | | | | | | | ## Flamegraph The following is the ["flamegraph"](https://github.com/flamegraph-rs/flamegraph){rel=""nofollow""} illustrating what the benchmark is spending most time on. The obvious answer (as predicted) is the async orchestration through tokio followed by the database running queries. Digging down the callgraph there is no immediate performance bottleneck (such as memory allocation) that could be significantly optimized. The database functionality seems to be evenly distributed matching the expectations given what is being run: ![Flamegraph](https://agdb.agnesoft.com/images/flamegraph.svg) ## Conclusion The used benchmark simulates highly contested database environment where dozens of writers and hundreds of readers are using the database at the same time. Tweaking the values (e.g. increasing/decreasing) the writers/readers had no significant effect on overall results meaning that the database can scale, and the principles hold under all circumstances. Running the benchmark in 2 OSs with 3 different storage backends showed that results will vary depending primarily on use (or not) of RAM for caching and on the level of data contention. The contention slowdown however is by no means linear is largely down to the scheduling of tasks (tasks not actually being executed and waiting their turn) - more powerful hardware would improve the results significantly (vertical scalability). As demonstrated `agdb` can handle even an extreme load such as the one in the benchmark. The flamegraph has also shown that the database itself is well optimized and there are no obvious/easy wins with most of the time being taken by orchestration (Tokio runtime) as expected. When using `agdb` your bottlenecks will likely lay elsewhere and not in the database itself. Some advice: - Always measure your use case but do not rely on micro-benchmarks, use realistic workloads. See `Creating users` line in each table which is equivalent to an isolated micro-benchmark and compare it with the rest of the table that demonstrates realistic load with contention. - Correct storage backend matters. While the default is usually the best choice offering persistence and speed it comes with certain caveats: - Do not use memory mapped database if you store terabytes of data or your data set is likely to exceed your available RAM size. - Do not use memory mapped database if your use case is write-heavy with infrequent reads. The memory mapping aids only in reading and slows down the writes a little bit. - Do not use in-memory cache if you need persistence even though it is the fastest. # Derive macros The `agdb` crate provides derive macros that let you use your own structs and enums directly in queries. They are provided by the `agdb_derive` crate that is re-exported by `agdb` under the `derive` cargo feature, which is enabled by default: ```rs use agdb::DbElement; use agdb::DbSerialize; use agdb::DbType; use agdb::DbTypeMarker; use agdb::DbValue; ``` If you disable default features you can bring the macros back with `features = ["derive"]`. For a runnable walk-through see the [user types example](https://agdb.agnesoft.com/docs/examples/user-types). The `DbType` trait itself is described in the [queries reference](https://agdb.agnesoft.com/docs/references/queries#dbtype). | Macro | Applies to | Implements | | -------------- | ----------------- | --------------------------------------------------------------------- | | `DbType` | structs | `DbType`, `TryFrom<&DbElement>`, `TryFrom` | | `DbElement` | structs | same as `DbType` plus `DbType::db_element_id()` | | `DbValue` | structs and enums | `From`, `From<&T>` for `DbValue` and `TryFrom` (as bytes) | | `DbSerialize` | structs and enums | `AgdbSerialize` (serialization to and from bytes) | | `DbTypeMarker` | any type | the empty marker trait `DbTypeMarker` | ## DbType `#[derive(DbType)]` maps a struct with named fields to the key-value pairs of a single database element. Each field name becomes a key (a `String`) and the field value is converted to a `DbValue` (e.g. `i32` is stored as `i64`). See [data types](https://agdb.agnesoft.com/docs/guides/concepts#data-types) for the supported conversions. ```rs #[derive(DbType)] struct User { db_id: Option, name: String, age: u64, } ``` The derive generates: - `DbType::to_db_values()` - the key-value pairs to be stored. - `DbType::from_db_element()` - the reverse conversion from a `DbElement`. - `DbType::db_keys()` - the list of keys of the type (see below). - `DbType::db_id()` - the id of the element if the type has a `db_id` field, otherwise `None`. - `TryFrom<&DbElement>` and `TryFrom` for the type. The latter converts the first element of the result. ### Requirements and limitations - Only structs with named fields are supported. Using the derive on an enum is a compile error. - Generic structs are not supported. (`DbValue`, `DbSerialize` and `DbTypeMarker` are covered separately below.) - Every field type must convert to and from `DbValue`. That is the native types, the conversions listed in the [queries reference](https://agdb.agnesoft.com/docs/references/queries#dbtype), or your own types with `From for DbValue` and `TryFrom for T` implemented by hand or via [`DbValue`](https://agdb.agnesoft.com/#dbvalue). Nested structs can alternatively be merged into the parent with [`#[agdb(flatten)]`](https://agdb.agnesoft.com/#agdbflatten). - Every stored field must implement `Clone`, because the values are cloned when converted. - `Vec` fields of your own types require `T: DbTypeMarker`, see [`DbTypeMarker`](https://agdb.agnesoft.com/#dbtypemarker). - When reading, a missing key is a `NotFound` error and a value that cannot be converted is a `TypeError`. ### The `db_id` field A field named `db_id` is special. It is never stored as a property. It is set from the id of the element when reading and used as the id when the type is passed to `insert().element()` / `insert().elements()`. Its type is either `Option` where `T: Into` (e.g. `Option` or `Option`) or a plain `DbId`. The field is optional - without it all other features still work, you just cannot use the shorthand updates. ### Optional fields A field of type `Option` is not stored when it is `None` and is read as `None` when its key is missing. Because not all keys are guaranteed to exist, `db_keys()` returns an empty list for a type with any `Option` field (other than `db_id`). Selecting with it - `select().values(T::db_keys())` or `select().elements::()` - then selects all values of the element. ::warning Only the struct's own fields are checked. If a [flattened](https://agdb.agnesoft.com/#agdbflatten) type has an `Option` field, the parent's `db_keys()` silently leave out all the keys of the nested type, so `select().elements::()` does not select them and they read back as missing (`None`, or an error for non-optional fields). Avoid `Option` fields in flattened types, or select all values (`select().ids(..)`) for such a type. :: ### Using the type in queries ```rs let users = vec![ User { db_id: None, name: "Bob".to_string(), age: 30 }, User { db_id: None, name: "Alice".to_string(), age: 25 }, ]; // insert new nodes with the values taken from the structs let result = db.exec_mut(QueryBuilder::insert().nodes().values(&users).query())?; // select the elements as users let users: Vec = db .exec(QueryBuilder::select().elements::().ids(result).query())? .try_into()?; // update elements that have the db_id set db.exec_mut(QueryBuilder::insert().elements(&users).query())?; // a single element db.exec_mut(QueryBuilder::insert().element(&users[0]).query())?; ``` - `values(&T)` / `values(&Vec)` supply the values for inserts. A blanket `impl DbType for &T` makes references work too. - `insert().element(&t)` / `elements(&ts)` infer both ids (from `db_id`) and values. Elements without `db_id` are inserted as new nodes, otherwise they are updated. - `select().elements::()` selects the keys of `T` (all values if `db_keys()` is empty) and `select().element::()` selects a single element (see [select values](https://agdb.agnesoft.com/docs/references/queries#select-values)). - `try_into()` converts a `QueryResult` to `T` (the first element) or to `Vec` (all elements). - `search().where_().element::()` adds a condition matching the keys of `T` (or the `db_element_id` of [`DbElement`](https://agdb.agnesoft.com/#dbelement)). For a `DbType` with an `Option` field the key list is empty and the condition matches every element. ### `#[agdb(skip)]` ```rs #[derive(DbType)] struct Item { name: String, #[agdb(skip)] cache: Vec, } ``` The field is neither stored nor selected. When reading, it is filled with `Default::default()` (or `None` for an `Option`), so its type must implement `Default`. ### `#[agdb(rename = "...")]` ```rs #[derive(DbType)] struct Category { #[agdb(rename = "category_name")] name: String, } ``` Uses the given string as the key instead of the field name. Useful to keep database keys stable independent of the Rust names and to disambiguate keys when flattening. ### `#[agdb(flatten)]` ```rs #[derive(DbType)] struct Address { city: String, } #[derive(DbType)] struct Person { name: String, #[agdb(flatten)] address: Address, } ``` The fields of the nested struct are stored directly on the element (`name`, `city`) instead of the nested value being converted to a single `DbValue`. The nested type must itself implement `DbType`, and it works transitively. If nested structs have the same key the last one written wins - use `rename` to disambiguate. A flattened `Option` is `None` when reading if the nested type cannot be read from the element. If the nested type derives `DbElement`, its `db_element_id` is ignored and the parent's is used. ::note The attributes are written as `#[agdb(...)]`. Only `skip`, `rename` and `flatten` exist. They can be given on named fields of `DbType` and `DbElement` structs. Give a field at most one option: only the first `#[agdb(...)]` attribute of a field is read, the options are not meant to be combined (a skipped field has no key and a flattened field uses the keys of the nested type) and an option written after `rename = "..."` in the same attribute is not recognised. Unknown options are ignored. :: ## DbElement `#[derive(DbElement)]` does everything `DbType` does and additionally implements `DbType::db_element_id()` returning the name of the type. When such a type is stored, an extra property `db_element_id` with the type name is added to the element. It is not part of `db_keys()`. This allows telling apart types with the same fields. When used with the `QueryBuilder`, `select().element::().search()` (and `elements::()`) automatically adds the condition `key("db_element_id").value("T")` to the search, so only elements of that type are returned even when several types are reachable from the same node. ```rs #[derive(DbElement)] struct Dog { name: String, } #[derive(DbElement)] struct Cat { name: String, } db.exec_mut(QueryBuilder::insert().nodes().aliases("pets").query())?; let dog = db.exec_mut(QueryBuilder::insert().element(Dog { name: "Rex".into() }).query())?; let cat = db.exec_mut(QueryBuilder::insert().element(Cat { name: "Tom".into() }).query())?; db.exec_mut( QueryBuilder::insert() .edges() .from("pets") .to([dog.elements[0].id, cat.elements[0].id]) .query(), )?; // no extra conditions needed, only the Dog is returned let dog: Dog = db .exec(QueryBuilder::select().element::().search().from("pets").query())? .try_into()?; ``` The name is the type name only (no module path), so two types with the same name in different modules are not distinguished. The requirements, attributes and limitations are the same as for [`DbType`](https://agdb.agnesoft.com/#dbtype). ## DbValue `#[derive(DbValue)]` lets a struct or an enum be used as a field of a `DbType` struct (or anywhere `Into` is expected) without writing the conversions by hand. The value is stored as `DbValue::Bytes` using [`AgdbSerialize`](https://agdb.agnesoft.com/#dbserialize). It implements `From` and `From<&T>` for `DbValue` and `TryFrom` for `T` (returning `DbError` when the value is not bytes or the bytes are invalid). ```rs #[derive(Clone, DbSerialize, DbValue)] enum Status { Active, Inactive, } ``` ### Requirements and limitations - The type must implement `AgdbSerialize`, which you get with `#[derive(DbSerialize)]`. - Structs and enums are supported, including generic ones. The generic parameters and the `where` clause are carried over to the implementations without adding bounds, so bound the parameters yourself so that the type implements `AgdbSerialize` (e.g. `struct Foo`). - To use the type as a field of a `DbType` struct it must also implement `Clone`. - The value is opaque binary data. It cannot be searched or compared by its content, only by the whole value. If you need to query the fields, use `DbType` (with `flatten`) instead. - To use it in `Vec` fields also derive [`DbTypeMarker`](https://agdb.agnesoft.com/#dbtypemarker). ## DbSerialize `#[derive(DbSerialize)]` implements `AgdbSerialize` - the platform agnostic binary serialization used by `agdb` itself. Use it to serialize your own structures when you do not want or cannot use `serde`. It is also what `DbValue` builds on. ```rs #[derive(DbSerialize)] struct Property { name: String, value: String, } ``` - Supported are structs with named fields, tuple structs and enums (unit, tuple and struct variants). An enum is serialized as its variant index followed by the fields of the variant, so reordering or inserting variants changes the stored format. - All fields must implement `AgdbSerialize`. It is implemented for `i64`, `u64`, `f64`, `usize`, `bool`, `String`, `Vec`, `Option`, pairs `(A, B)`, `PathBuf`, `SystemTime`, `SocketAddr` and `IpAddr` and for other types deriving `DbSerialize`. Other integer widths such as `i32` need to be wrapped or converted. - Generic types are supported and each type parameter gets an `AgdbSerialize` bound. ## DbTypeMarker `#[derive(DbTypeMarker)]` implements the empty marker trait `DbTypeMarker`. The marker is needed because `Vec` converts to `DbValue` only when `T: Into + DbTypeMarker`, which avoids conflicts with the blanket implementations for native types. Derive it on the types you want to use in `Vec` fields. ```rs #[derive(Clone, DbTypeMarker, DbSerialize, DbValue)] struct Property { name: String, value: String, } #[derive(DbType)] struct Node { name: String, properties: Vec, } ``` A single value of the type does not need the marker. The derive does not take generic parameters into account, so for generic types implement the trait by hand: `impl agdb::DbTypeMarker for MyType {}`. ## Putting it together ```rs #[derive(Clone, DbTypeMarker, DbSerialize, DbValue)] struct Property { name: String, value: String, } #[derive(DbType)] struct Extra { id: i32, } #[derive(DbType)] struct User { db_id: Option, username: String, #[agdb(rename = "name")] display_name: Option, properties: Vec, #[agdb(skip)] session: (), #[agdb(flatten)] extra: Extra, } ``` See the [user types example](https://agdb.agnesoft.com/docs/examples/user-types) for the complete runnable program and [queries reference](https://agdb.agnesoft.com/docs/references/queries#dbtype) for the `DbType` trait and the type conversions. # Error codes This page lists the errors you can meet when working with `agdb`: the HTTP status codes of the [server](https://agdb.agnesoft.com/docs/references/server), the `DbError` of the embedded database and the error types of the API clients. For symptoms and fixes of common problems see also the [troubleshooting](https://agdb.agnesoft.com/docs/guides/troubleshooting) guide. ## Server A failed request returns a status code and the error description as the plain text body of the response. The OpenAPI specification (see [API docs](https://agdb.agnesoft.com/api-docs/openapi)) lists the codes of each endpoint. ### Custom codes (46x - 47x, 52x) The server uses codes in the 4xx and 5xx ranges that are not defined by HTTP to tell apart the errors of `agdb` itself. | Code | Body | Meaning | Typical cause | What to do | | ---- | -------------------------------- | ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | | 461 | `password too short (<8)` | The password is shorter than 8 | Creating a user or changing one's own password | Use a password of at least 8 characters | | 462 | `name too short (<3)` | The user name is shorter than 3 | Creating a user | Use a user name of at least 3 characters | | 463 | `user exists` | The user already exists | Creating a user with a taken name | Choose another name | | 465 | `db already exists` | The database already exists | Adding, copying or renaming a database to a name that is taken | Choose another name or delete the existing database | | 467 | usually `db invalid:
` | The database name or file is not valid | The name is empty, starts with `.`, contains `/`, `\`, `:` or NUL, or is `audit` or `backups`; also a database file that cannot be opened or created | Fix the name (also of the new name of a copy or rename), check the file | | 470 | the description of the `DbError` | A query failed in the database | An invalid query, e.g. a missing id or alias, a type mismatch or an invalid reference to a result of an earlier query (`:0`) in a batch | Fix the query, see [Embedded errors](https://agdb.agnesoft.com/#embedded-errors) | | 471 | `storage error:
` | The storage of the node failed | A file system or database file error, an invalid snapshot, or an action the cluster leader gave up on after a fault (see [Cluster](https://agdb.agnesoft.com/#cluster)) | Check the disk and the server log; in a cluster check the data afterward | | 520 | `` | The outcome of the request is unknown | The leader lost the leadership, the node stopped, a forward failed after it may have reached the leader or the request took more than 50 s (see [Cluster](https://agdb.agnesoft.com/#cluster)) | Check the state before repeating a request that is not safe to repeat | | 521 | `` | The request committed, its result is lost | The node stopped or resynced before it applied the request, the message has its log index (see [Cluster](https://agdb.agnesoft.com/#cluster)) | The request is final, the data shows its outcome once applied | The password check counts the length of the value in bytes. It runs when a user is created and when users change their own password (not on the admin password change). User names are checked only when a user is created. ### Standard codes | Code | Meaning | Typical cause | What to do | | ---- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | | 400 | Bad request | An invalid user name (`invalid user name '': ...`) or dashboard name (`invalid dashboard name '': use 1-... characters [A-Za-z0-9_.-], not starting with '.'`), malformed JSON or an undecodable binary (`application/vnd.agdb.api.v1`) body, an invalid `log_level` | Fix the request | | 401 | Unauthorized | A missing, unknown or expired token (the response has no body), wrong user name or password on login (`unauthorized`), a token of a user that is not the server admin on `/api/v1/admin/*`, a wrong `cluster_token` on the cluster endpoints | Log in again, see [troubleshooting](https://agdb.agnesoft.com/docs/guides/troubleshooting) | | 403 | Forbidden | The user lacks the required role or the operation is not allowed, e.g. a wrong current password when changing it (`invalid credentials`) or adding a database or dashboard to another user | Use a user with the role needed, see [Permission denied](https://agdb.agnesoft.com/#permission-denied) | | 404 | Not found | A missing user (`user not found: `), database (`db not found: /`), dashboard (`dashboard not found: `), backup (`backup not found`), session or token. A dashboard the user has no role on is reported as not found as well | Check the names and the owner | | 409 | Conflict | A dashboard to add or rename to already exists (`dashboard already exists: `) | Choose another name | | 413 | Payload too large | The request body is larger than `request_body_limit`, a dashboard config is larger than the maximum (`dashboard config too large (>N bytes)`) or a request is larger than a cluster append (`the request is larger than a cluster append`) | Send less data or raise `request_body_limit` / `cluster_max_append_size` | | 415 | Unsupported media type | A JSON body sent without `Content-Type: application/json`, e.g. curl without `-H 'Content-Type: application/json'` | Set the header | | 422 | Unprocessable entity | JSON that does not match the expected fields | Fix the body, see the [OpenAPI](https://agdb.agnesoft.com/api-docs/openapi) specification | | 500 | Internal server error | An unexpected failure of the server that is not a storage error, e.g. a failed internal channel or a database error that is not a query error | Check the server log | | 503 | Service unavailable | The cluster cannot execute the request right now, see [Cluster](https://agdb.agnesoft.com/#cluster) | Retry later | ### Permission denied A `403` caused by a role carries the body `permission denied: `. The reasons used by the server are `admin only` (the database or dashboard admin role is needed, e.g. for backup, restore, rollback, clear, convert, audit trim and managing users; a non-admin token on `/api/v1/admin/*` gets `401`), `owner only`, `write rights required`, `dashboard users only`, `cannot change role of db owner`, `cannot change role of dashboard owner`, `cannot remove owner`, `cannot add dashboard to another user` and `mutable queries not allowed, use exec_mut endpoint` (a mutable query sent to `exec`). The roles are described in the [server](https://agdb.agnesoft.com/docs/references/server) reference. ### Cluster In a [cluster](https://agdb.agnesoft.com/docs/references/server) a write goes through the leader and a node that is not the leader forwards it. A `503` was not executed and is safe to retry, its body tells the reason: | Body | Reason | | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | | `cluster is not ready yet` | The node has not joined the cluster yet | | `this node is not the leader, the leader is node ` / `the cluster has no leader` | No leader known (election in progress) or the leadership moved | | `the leader has not heard from a majority of the cluster` | Too many nodes are unreachable | | `the cluster is busy` | The log entries not yet executed exceed `cluster_max_pending_bytes` | | `the cluster node is shutting down` | The node is stopping | | `forward to leader failed to connect:
` | The node could not connect to the leader (retried before failing) | | `the password hash did not complete:
` | Hashing a password on login or a password change failed | | `db unavailable: /: ` | The files of the database could not be opened or a file operation on them is pending; `/admin/optimize` retries it | | `another backup or a snapshot install is running on this node` / `the cluster node is unavailable for backup` | `/admin/backup` could not start | A `520` may or may not have been executed: | Body | Reason | | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | | `the leadership was lost, the request may or may not have been executed` | The leader changed while the request was running | | `the cluster node is shutting down, the request may or may not have been executed` | The node stopped while the request was running | | `the request did not finish in time, it may or may not have been executed` | The request took more than 50 seconds | | `forward to leader failed:
` | The forward failed after it may have reached the leader | | `the action faulted and its resources could not be stamped, it may still take effect when replayed` | The leader failed to mark the data of an action that faulted | A `521` (`the request was committed at index , its result is lost on this node`) was executed: the request is final and the data shows its outcome once the node applied it. Check the state (e.g. with a query) before repeating a `520` request that is not safe to repeat. An action the leader itself failed to run is not retried: it fails with `471` (`storage error: the action faulted, its resources are accepted as they are`) and the data it touched is kept as it is on the leader. See the cluster section of the [server](https://agdb.agnesoft.com/docs/references/server) reference for details. ## Embedded errors The embedded database reports every failure as a `DbError` with a `category` (`Collections`, `Db`, `Graph`, `Query`, `Serialization`, `Storage`), a `ty` of `DbErrorType`, a `description`, an optional `cause` and the source location. The error is printed as `[:] (at )` followed by the cause chain. More in the [queries](https://agdb.agnesoft.com/docs/references/queries#dberror) reference. | `DbErrorType` | Meaning | | --------------- | --------------------------------------------------------- | | `DbCreate` | Failed to create a new database file or structure | | `InvalidIndex` | An internal index was invalid or corrupted | | `NotAllowed` | The requested operation is not permitted | | `NotEnoughData` | Not enough data was available to complete deserialization | | `NotFound` | The requested element, alias or key was not found | | `OutOfBounds` | An index was outside the valid range | | `Poisoned` | A lock was poisoned by a panicked thread | | `TypeError` | A type conversion or mismatch error | Create your own error with one of the constructors named after the category (`collections`, `db`, `graph`, `query`, `serialization`, `storage`) and add a cause with `caused_by`: ```rs use agdb::DbError; use agdb::DbErrorType; let error = DbError::db(DbErrorType::NotAllowed, "name must not be empty"); let wrapped = DbError::query(DbErrorType::NotFound, "user").caused_by(error); ``` The closure of a transaction may return any error type `E` that implements `From`, so errors of queries convert with `?` and you can add your own: ```rs use agdb::Db; use agdb::DbError; use agdb::DbId; use agdb::QueryBuilder; enum MyError { Db(DbError), Invalid, } impl From for MyError { fn from(error: DbError) -> Self { MyError::Db(error) } } fn add_node(db: &Db, valid: bool) -> Result { db.transaction_mut(|t| { let result = t.exec_mut(QueryBuilder::insert().nodes().count(1).query())?; if !valid { return Err(MyError::Invalid); // the transaction is rolled back } Ok(result.elements[0].id) }) } ``` On the server a `DbError` of a query is returned as `470` and one that originates in the storage (or a poisoned lock) as `471`. ## Clients All API clients report a failed request with an error carrying the HTTP `status` and the `description` (the body of the response). The error is printed as `: ` (in TypeScript with `e.to_string()`). A request that did not get a response (e.g. the connection failed) is reported with the status `500` and the description of the transport error. | Client | Error type | Status and description | Transport failure | | ---------- | -------------------------------------------------------- | -------------------------------------------------- | ----------------------------------------------------------------------------- | | Rust | `agdb_api::AgdbApiError` (a struct, `std::error::Error`) | `status: u16`, `description: String` | Status `500` when `reqwest` reports no status, the description is its message | | TypeScript | `AgdbApiError` (a class) | `status: number`, `description: string` | Thrown by `fetch_client` with status `500` and the message | | PHP | `AgdbApiError` (extends `\Exception`) | `public int $status`, `public string $description` | Thrown by `CurlClient` with status `500` and the cURL error | | Python | `AgdbApiError` (extends `Exception`) | `status: int`, `description: str` | Raised by `UrllibClient` with status `500` and the message | The Rust client uses the status `0` for errors that do not originate from an HTTP response: a failure to parse JSON, a `DbError` (converted with `From`) or a response of unexpected size. ```rs match client.user_login("alice", "password").await { Ok(_) => {} Err(e) if e.status == 401 => println!("wrong credentials: {e}"), Err(e) => println!("failed: {e}"), } ``` ```ts try { await client.user_login({ username: "alice", password: "password" }); } catch (e) { if (e instanceof AgdbApiError && e.status === 401) { console.log(e.to_string()); } } ``` ```php try { $client->user_login("alice", "password"); } catch (AgdbApiError $e) { echo $e->status . ": " . $e->description; } ``` ```python try: client.user_login("alice", "password") except AgdbApiError as e: print(e.status, e.description) ``` # OpenAPI The [agdb server](https://agdb.agnesoft.com/docs/references/server) can be accessed using OpenAPI (REST) via any HTTP client. In addition to the API specification `agdb` offers convenience clients for Rust, TypeScript/JavaScript, PHP and Python that use the same API: :language-icons :open-api-code-block # Rust The rust agdb API client is **async only** and can be used with any HTTP client that would implement the `agdb_api::HttpClient` trait. The default implementation uses [reqwest](https://crates.io/crates/reqwest){rel=""nofollow""}. The following is the quickstart guide for the agdb client in Rust (connecting to the server). It assumes an `agdb_server` is running locally. Please refer to the [server guide](https://agdb.agnesoft.com/docs/guides/how-to-run-server) to learn how to run the server. Looking for... [how to run a server?](https://agdb.agnesoft.com/docs/guides/how-to-run-server) | [another language?](https://agdb.agnesoft.com/api-docs/openapi) | [embedded db guide?](https://agdb.agnesoft.com/docs/guides/quickstart) ## Usage ::steps ### Install Rust Please install the Rust toolchain from the [official source](https://www.rust-lang.org/tools/install){rel=""nofollow""}. ### Create an application First we initialize an application called `agdb_client` with cargo: ```bash cargo init agdb_client ``` ### Add dependencies ```bash cargo add agdb --features serde,openapi cargo add agdb_api cargo add tokio --features full cargo add anyhow ``` ### Create the client The client should point to a running `agdb_server`: ```rs use agdb_api::AgdbApi; use agdb_api::ReqwestClient; #[tokio::main] async fn main() -> anyhow::Result<()> { let mut client = AgdbApi::new(ReqwestClient::new(), "localhost:3000"); Ok(()) } ``` :::note To connect to a server running with TLS (an `https://` address) enable the `tls` feature of the client: `cargo add agdb_api --features tls`. ::: ### Create a database user First we need to log in as default admin user and create our database user and then login as them: ```rs client.user_login("admin", "admin").await?; // The authentication login is stored in // the client for subsequent API calls. // Default admin credentials are "admin/admin". client.admin_user_add("my_user", "password123").await?; client.user_login("my_user", "password123").await?; // Login as our newly created user. ``` ### Create a database ```rs use agdb_api::DbKind; client.db_add("my_user", "my_db", DbKind::Mapped).await?; // Memory mapped database called "my_db" // will be created under our "my_user". ``` ### Run our first queries To run queries against the database we call `db_exec` (for read only queries) and `db_exec_mut` (for queries that also write to the database). In this case we will insert node "users" and 3 user nodes and connect them together. :::tip Note that we can feed the result of a previous query directly to the next one referencing it with an index into the (previous) results starting with colon followed by the index, e.g. `:0`, `:1`. ::: ```rs use agdb::{DbId, DbType, QueryBuilder, QueryType}; // We derive from agdb::DbType // so we can use the type in the db. #[derive(Debug, DbType)] struct User { db_id: Option, // The db_id member is optional but // it allows querying your user type // from 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 }]; // We can pass users directly as // query parameter thanks to the // implementation of the agdb::DbType // trait via #[derive(DbType)]. let queries: Vec = vec![QueryBuilder::insert().nodes().aliases("users").query().into(), QueryBuilder::insert().nodes().values(&users).query().into(), QueryBuilder::insert().edges().from("users").to(":1").query().into(), ]; client.db_exec_mut("my_user", "my_db", &queries).await?; ``` ## Run more queries Run another query searching & selecting the users and converting them back to the native local object and printing the result: ```rs let queries = vec![QueryBuilder::select() .elements::() // 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() .into()]; // Runs the query against the db, grabs the first result and converts it to the collection of users. let users: Vec = client.db_exec("my_user", "my_db", &queries).await?.1[0].clone().try_into()?; println!("{:?}", users); ``` ### Run the program ```bash cargo run ``` ### Full program {rel=""nofollow""} :: # PHP The PHP agdb API client is generated from the Rust client (`agdb_api`) by the repository's `agci generate` tool and its query builder from the Rust one (`agdb`), so both have the same methods. It requires PHP 8.1 or later with the `curl` and `json` extensions and sends the requests with native cURL (`CurlClient`). The following is the quickstart guide for the agdb client in PHP (connecting to the server). It assumes an `agdb_server` is running locally. Please refer to the [server guide](https://agdb.agnesoft.com/docs/guides/how-to-run-server) to learn how to run the server. Looking for... [how to run a server?](https://agdb.agnesoft.com/docs/guides/how-to-run-server) | [another language?](https://agdb.agnesoft.com/api-docs/openapi) | [embedded db guide?](https://agdb.agnesoft.com/docs/guides/quickstart) ## Usage The following is the from-scratch guide to use `agnesoft/agdb_api` PHP package. ::steps ### Install PHP {rel=""nofollow""} ### Install Composer {rel=""nofollow""} ### Create your project Create your project's folder (e.g. `my_agdb`) and initialize the package: ```bash mkdir my_agdb cd my_agdb composer init # follow the steps & prompts ``` ### Add `agnesoft/agdb_api` as a dependency ```bash composer require agnesoft/agdb_api:dev-main ``` This adds `"agnesoft/agdb_api": "dev-main"` to your `composer.json`. :::tip Consider using other dev packages such as `phpunit/phpunit` and `phpstan/phpstan`. ::: ### Create your main script E.g. `src/index.php` and create a client to connect to the server: ```php status(); ``` :::note Each method takes the parameters of the Rust client (same names and order). A method with a response body returns the status with the body (`[$status, $body]`), the others return just the status. The logins keep the token in the client and return only the status. A response outside the 2xx range throws an `AgdbApiError` holding the status and the response body, and a transport failure (e.g. the server is unreachable) throws it with status 500. ::: ### Create a database user To create a database user we use the default admin user: ```php // Login as server admin. $client->user_login("admin", "admin"); // Create user "php_user1". $client->admin_user_add("php_user1", "php_user1"); // Login as "php_user1", the token replaces the admin one. $client->user_login("php_user1", "php_user1"); ``` ### Create a database To create a database we associate it with a user and give it a name and kind (one of `DbKind::Mapped`, `DbKind::Memory`, `DbKind::File`): ```php // Creates memory mapped database "db1" for user "php_user1". $client->db_add("php_user1", "db1", DbKind::Mapped); ``` ### Execute queries To execute queries against the database we call `db_exec` (read only queries) and `db_exec_mut` (for queries that also write to the database) with the user and their database. :::note Notice we are feeding results of the previous query to the next one with special alias `":0"` and `":1"` referencing first and second result respectively. ::: ```php // Prepare the queries to be executed on the remote database. $queries = [ // :0: Inserts a root node aliased "users". QueryBuilder::insert() ->nodes() ->aliases(["users"]) ->query(), // :1: Inserts more nodes with some data. QueryBuilder::insert() ->nodes() ->values([ [ "username" => "user1", "password" => "password123", ], [ "username" => "user2", "password" => "password456", ], ]) ->query(), // :2: Connect the root to the inserted nodes with edges referencing both from previous queries. QueryBuilder::insert()->edges()->from(":0")->to(":1")->query(), // :3: Find a node starting at the "users" node with specific username. QueryBuilder::select() ->search() ->from("users") ->where() ->key("username") ->value("user1") ->query(), ]; // Execute queries. Since it includes mutable queries (inserts) // we need to call db_exec_mut() rather than read-only db_exec(). [, $results] = $client->db_exec_mut("php_user1", "db1", $queries); ``` ### Print the result The result is a pair of the status code and the list of results (one per query), so the result of the final query is `$result[1][3]`: ```php // Print the result of the last query. print_r($results[3]); // Agnesoft\AgdbApi\QueryResult Object // ( // [result] => 1 // [elements] => Array // ( // [0] => Agnesoft\AgdbApi\DbElement Object // ( // [id] => 2 // [from] => 0 // [to] => -1 // [values] => Array // ( // [0] => Agnesoft\AgdbApi\DbKeyValue Object // ( // [key] => Agnesoft\AgdbApi\DbValue_String Object // ( // [value] => username // ) // // [value] => Agnesoft\AgdbApi\DbValue_String Object // ( // [value] => user1 // ) // // ) // // [1] => Agnesoft\AgdbApi\DbKeyValue Object // ( // [key] => Agnesoft\AgdbApi\DbValue_String Object // ( // [value] => password // ) // // [value] => Agnesoft\AgdbApi\DbValue_String Object // ( // [value] => password123 // ) // // ) // // ) // // ) // // ) // // ) ``` ### Run the program :::warning Make sure the agdb_server is running at `localhost:3000`. ::: :::tip To run the example of this repository against a fresh server, call `pnpm run examples --filter agdb_api_php` from the root. ::: ```bash php src/index.php ``` ### Full program {rel=""nofollow""} :: # Typescript / Javascript The typescript agdb API client is generated from the Rust client (`agdb_api`) and its query builder from the Rust one (`agdb`), so both have the same methods. It sends the requests with the native `fetch`. The following is the quickstart guide for the agdb client in Javascript/Typescript (connecting to the server). It assumes an `agdb_server` is running locally. Please refer to the [server guide](https://agdb.agnesoft.com/docs/guides/how-to-run-server) to learn how to run the server. Looking for... [how to run a server?](https://agdb.agnesoft.com/docs/guides/how-to-run-server) | [another language?](https://agdb.agnesoft.com/api-docs/openapi) | [embedded db guide?](https://agdb.agnesoft.com/docs/guides/quickstart) ## Usage The following is the from-scratch guide to use `@agnesoft/agdb_api` typescript/javascript package. The package is ESM only, so the project has to be an ES module. ::steps ### Install NodeJS {rel=""nofollow""} ### Create your project Let's create a directory (e.g. `my_agdb`) and initialize the package: ```bash mkdir my_agdb cd my_agdb npm init # follow the steps & prompts npm pkg set type=module # the package is ESM only ``` ### Add `typescript` ```bash npm install typescript --save-dev ``` and create its configuration file `tsconfig.json`: ```json { "compilerOptions": { "module": "NodeNext", "sourceMap": true, "lib": ["ES2015", "DOM"], "moduleResolution": "nodenext", "allowJs": true, "esModuleInterop": true } } ``` :::tip Consider using other dev packages such as `prettier` and `eslint` (and `@typescript-eslint/parser`) ::: ### Add `@agnesoft/agdb_api` as a dependency. ```bash npm install @agnesoft/agdb_api ``` ### Create a client In your main script `index.ts` create a client connecting to the server: ```ts import { AgdbApi, Comparison, FetchClient, QueryBuilder, } from "@agnesoft/agdb_api"; async function main() { // Creates a client connecting to the remote server. const client = AgdbApi.new(new FetchClient(), "localhost:3000"); } ``` The code of the following steps goes inside the `main` function. :::note Each method takes its parameters as one object, named as in the Rust client, and resolves to the status code, with the response body if there is one (`[status, body]`). A response that is not a success rejects with an `AgdbApiError` holding the status and the description. ::: ### Create a database user To create a database user we use the default admin user: ```ts await client.user_login({ username: "admin", password: "admin" }); await client.admin_user_add({ username: "user1", password: "password123" }); await client.user_login({ username: "user1", password: "password123" }); ``` ### Create a database ```ts await client.db_add({ owner: "user1", db: "db1", db_type: "mapped" }); //memory mapped type, other options are "memory" and "file" ``` ### Execute queries To execute queries against the database we call `db_exec` (read only queries) and `db_exec_mut` (for queries that also write to the database) with the user and their database. :::note Notice we are feeding results of the previous query to the next one with special alias `":0"` and `":1"` referencing first and second result respectively. ::: ```ts // Prepare the queries to be executed on the remote database. const queries = [ // :0: Inserts a root node aliased "users" QueryBuilder.insert().nodes().aliases(["users"]).query(), // :1: Inserts more nodes with some data QueryBuilder.insert() .nodes() .values([ [ ["username", "user1"], ["password", "password123"], ], [ ["username", "user2"], ["password", "password456"], ], ]) .query(), // :2: Connect the root to the inserted nodes with edges referencing both from previous queries QueryBuilder.insert().edges().from(":0").to(":1").query(), // :3: Find a node starting at the "users" node (could also be ":0" in this instance) with specific username QueryBuilder.select() .search() .from("users") .where() .key("username") .value(Comparison.Equal("user1")) .query(), ]; // Execute queries. const results = ( await client.db_exec_mut({ owner: "user1", db: "db1", queries }) )[1]; ``` ### Print the result of the final query to the console: ```ts console.log(`User (id: ${results[3].elements[0].id})`); for (const { key, value } of results[3].elements[0].values) { console.log(`${JSON.stringify(key)}: ${JSON.stringify(value)}`); } ``` ### Call the main function Finally call the `main` function at the end of `index.ts`: ```ts main(); ``` ### Run the program :::warning Make sure the agdb_server is running at `localhost:3000`. ::: :::tip To run the example of this repository against a fresh server, call `pnpm run examples --filter @agnesoft/agdb_api` from the root. ::: ```bash npx tsc && node index.js ``` ### Full program {rel=""nofollow""} :: # Python The python agdb API client is generated from the Rust client (`agdb_api`) and its query builder from the Rust one (`agdb`), so both have the same methods. It requires Python 3.11 or later, has no dependencies and sends the requests with `urllib` of the standard library. The following is the quickstart guide for the agdb client in Python (connecting to the server). It assumes an `agdb_server` is running locally. Please refer to the [server guide](https://agdb.agnesoft.com/docs/guides/how-to-run-server) to learn how to run the server. Looking for... [how to run a server?](https://agdb.agnesoft.com/docs/guides/how-to-run-server) | [another language?](https://agdb.agnesoft.com/api-docs/openapi) | [embedded db guide?](https://agdb.agnesoft.com/docs/guides/quickstart) ## Usage The following is the from-scratch guide to use `agdb_api` python package. ::steps ### Install Python {rel=""nofollow""} ### Create your project Let's create a directory (e.g. `my_agdb`) with a virtual environment: ```bash mkdir my_agdb cd my_agdb python -m venv .venv source .venv/bin/activate ``` ### Add `agdb_api` as a dependency. ```bash pip install "git+https://github.com/agnesoft/agdb#subdirectory=agdb_api/python" ``` :::tip The package is fully typed, consider checking your code with `mypy` and formatting it with `ruff`. ::: ### Create a client In your main script (e.g. `main.py`) create a client connecting to the server: ```python from agdb_api import AgdbApi, DbKind, QueryBuilder, UrllibClient def main() -> None: # Creates a client connecting to the remote server. client = AgdbApi.new(UrllibClient(), "localhost:3000") ``` :::note Each method takes the parameters of the Rust client, by their names, and returns the status code, with the response body if there is one (`(status, body)`). A response that is not a success raises an `AgdbApiError` holding the status and the description. The names that are Python keywords get a trailing `_`, e.g. `from_`. ::: ### Create a database user To create a database user we use the default admin user: ```python client.user_login("admin", "admin") client.admin_user_add("user1", "password123") client.user_login("user1", "password123") ``` ### Create a database ```python client.db_add("user1", "db1", DbKind.Mapped) # memory mapped type, other options are DbKind.Memory and DbKind.File ``` ### Execute queries To execute queries against the database we call `db_exec` (read only queries) and `db_exec_mut` (for queries that also write to the database) with the user and their database. :::note Notice we are feeding results of the previous query to the next one with special alias `":0"` and `":1"` referencing first and second result respectively. ::: ```python # Prepare the queries to be executed on the remote database. queries = [ # :0: Inserts a root node aliased "users" QueryBuilder.insert().nodes().aliases(["users"]).query(), # :1: Inserts more nodes with some data QueryBuilder.insert() .nodes() .values( [ {"username": "user1", "password": "password123"}, {"username": "user2", "password": "password456"}, ] ) .query(), # :2: Connect the root to the inserted nodes with edges referencing both from previous queries QueryBuilder.insert().edges().from_(":0").to(":1").query(), # :3: Find a node starting at the "users" node (could also be ":0" in this instance) with specific username QueryBuilder.select() .search() .from_("users") .where() .key("username") .value("user1") .query(), ] # Execute queries. _, results = client.db_exec_mut("user1", "db1", queries) ``` ### Print the result of the final query to the console: ```python user = results[3].elements[0] print(f"User (id: {user.id})") for kv in user.values: print(f"{kv.key.to_json()}: {kv.value.to_json()}") ``` ### Run the program :::warning Make sure the agdb_server is running at `localhost:3000`. ::: :::tip To run the example of this repository against a fresh server, call `pnpm run examples --filter agdb_api_python` from the root. ::: ```bash python main.py ``` ### Full program {rel=""nofollow""} :: # Distance The `distance` is a unique property of graphs and perhaps their most important feature. In this post we will examine what distance actually is and how it is useful when working and thinking about data on a graph. First let's consider the following simplest graph: ![distance - simple](https://agdb.agnesoft.com/images/distance_simple.png) We have two nodes - "projects" and "project A" - connected with an edge. We search from "projects" and therefore the "projects" node is at distance 0. The adjacent edge is at distance 1 and finally the "project A" is at distance 2. The distance is also relative to the direction of the search. Consider a reverse search of the above graph: ![distance - simple - reversed](https://agdb.agnesoft.com/images/distance_simple_reversed.png) Here the origin node is "project A" and therefore it is at distance 0. The edge is once again at distance 1 and the "projects" node is at distance 2. ::tip The distance is only relevant when we are searching the graph and is always measured from the point of origin of our search regardless of the search direction. :: ## Distance of 2 When searching graphs perhaps the most significant distance is distance of 2. Why? Because at distance 2 there will always be all the neighboring nodes. Typically you would have a `root` node (such as "projects") being connected to individual nodes having relation to the root (individual projects). That we be akin to a "table" in a relational database. For instance: ![distance of 2](https://agdb.agnesoft.com/images/distance_2.png) In `agdb` the query to find all projects would look like this (using `Rust` as the query language): ```rust QueryBuilder::search() .from("projects") .where_() .neighbor() .query(); ``` Searching from the node "projects" and only returning elements at distance 2. The distance here serves two purposes. One is that it tells the algorithm what to return (elements at distance 2) and even more importantly it tells it when to stop searching. Since we are asking only for elements at the distance 2 it knows that it does not need to consider anything beyond that distance and can safely ignore it! ::tip At distance 2 there will always be all the adjacent (neighboring) nodes to the origin of search. :: ## Limit the search In the previous section we have covered the basics of distance and hinted to its power, so let's explore it properly. Expanding our graph with outputs of our projects: ![distance - outputs](https://agdb.agnesoft.com/images/distance_outputs.png) The original query searching for elements at distance 2 remains unaffected. It would still stop searching at distance 2 regardless if there are now further elements beyond that distance. It therefore does not matter how large and complicated the graph is because with `distance` we can ignore it all and focus the search to only the relevant `subgraph` that we are interested in. Even if the graph had a billion nodes, the above query confined to this subgraph would have to do the same number of operations and would be as performant as if there were only 3 nodes on the graph. Another way the `distance` limits the required work when searching the graph is that even if the element is reached via the distance constrained, e.g. node "projects" at distance 0 and all the connected edges, because it cannot be included in the final result (we asked for distance 2) the algorithm will not be examining its properties at all regardless of additional constraints. For instance searching for a particular project: ```rust QueryBuilder::search() .from("projects") .where_() .neighbor() .and() .key("name") .value("B") .query(); ``` The search algorithm will only look at the "name" properties of the elements at distance 2 rather than all elements in encountered. The query would have the same result without the `distance` condition but would be less efficient as the algorithm would need to do more work (examine properties of all elements and not stopping at distance 2). It is generally a good idea to lead the conditions with the distance constraints if possible for this very reason. Even more efficient version would be to switch to depth-first-search algorithm and limit the search to a single returned element: ```rust QueryBuilder::search() .depth_first() // use depth-first algorithm which is more efficient when searching for a single element .from("projects") .limit(1) // return maximum 1 element .where_() .neighbor() .and() .key("name") .value("B") .query(); ``` Now the algorithm will do least amount of work necessary to find what we are looking for. ## No more joins One of the most ubiquitous actions done in relational databases is joining the data from multiple tables. If we were to model the graph in a relational database we would likely end up with two tables - one for "projects" and one for "outcomes". We would additionally need a link (relation) between them that would most likely be accomplished with a foreign key column in "projects" referencing rows in the "outputs" table. In the query we would then use a join to extract data from both tables. On a graph this is much simpler because the relations are directly represented and joins are not necessary. Once more we can utilize the distance to get the outputs: ```rust QueryBuilder::search() .from("projects") .where_() .distance(4) .query(); ``` Since we know the structure of our graph we also know that the outputs are at distance 4 and can leverage that information to easily extract all outputs. But what if we wanted only outputs of a particular project? Then we would additionally use the `beyond` condition like so: ```rust QueryBuilder::search() .from("projects") .where_() .distance(4) .and() .beyond() .where_() .distance_not_equal(2) .or() .key("name") .value("B") .query(); ``` That would result in a following search: ![distance - outputs](https://agdb.agnesoft.com/images/distance_outputs_search.png) Yellow elements would be visited, red is where the algorithm would stop and not continue further and green ones are the elements found and to be included in the final result of the query. Let's break it down: - search starts at the node "projects" (distance 0) - we want only elements at distance 4 (the outputs): `.distance(4)` - additionally we want to limit the search to continue only `beyond` certain elements: `.and().beyond().where_()` (NOTE: the nested `.where_()` is like opening a bracket so we specify multiple conditions for our beyond segment) - the beyond conditions then are: - continue only if the distance is NOT 2 (`.distance_not_equal(2)`) - OR - if the element has property "name" with the value "B" The `beyond` condition might seem alien but when you look at the picture of the search it should become clear. We are simply telling the algorithm to search normally and not consider anything at distance 2 or beyond unless the `or` condition is satisfied, in this case property "name" equals value "B". Because only one element in our graph satisfies such condition ("project B") the algorithm will continue beyond it (and stop at distance 2 otherwise) and eventually reach the distance 4 and return all elements it finds there. This potentially greatly limits the scope of work needed. The detailed steps taken by the algorithm and how it evaluates each element: ::steps ### Distance 0: ```text - Distance is less than 4 meaning the first condition evaluates `false` (nothing is selected but search will continue). - Second condition has modifier "beyond" meaning it only controls traversal (whether the search continues or stops), not element selection. - Distance is not 2 so the beyond condition evaluates to `true` and due to the short circuit of the `or` condition we will not reach the `key` condition at all. The beyond condition lets the search continue. ``` ### Distance 1: ```text - Same evaluation as at distance 0. ``` ### Distance 2: ```text - Distance is still less than 4 and the first condition evaluates `false` (nothing is selected). - The beyond qualified condition for distance now evaluates to `false` as we are at distance 2. - The `or` however will examine key `name` of all elements at this distance and thus will evaluate to `true` only if the value is `B` and continue the search only beyond that element stopping at all others. ``` ### Distance 3: ```text - Same evaluation as 0 and 1. - This level is however reached only via elements that passed the previous beyond condition. ``` ### Distance 4: ```text - Distance is now 4 and the first condition evaluates `true` and elements will be selected for the result. - Algorithm is now stopped as nothing further away can satisfy the first condition and evaluation of the beyond conditions is therefore not relevant. ``` :: For general reference of the conditions and their evaluation see [truth tables in queries documentation](https://agdb.agnesoft.com/docs/references/queries#truth-tables). ::tip The algorithms will never visit same element twice and are immune to cycles. Similarly each element will appear in the result only once at the position of the first encounter. :: ## Conclusion As we have seen the `distance` is the powerful property of graphs and is one of the key advantages of modelling data on graphs as opposed to tables. They help us limit the scope of our search and can easily confine the search to small subgraph(s) even if the entire graph consists of billions of elements. Furthermore, you can easily extract related data without the need for joins and the algorithm will only examine the properties of the elements that are relevant to the search. # Why graph? The database area is dominated by relational database systems (tables) and text queries since the 1970s. However, the issues with the relational database systems are numerous, and they even gave rise the regular SW profession - database engineer. This is because contrary to their name they are very awkward at representing actual relations between data which is always demanded by the real world applications. They typically use foreign keys and/or proxy tables to represent them. Additionally, the tables naturally enforce fixed immutable data schema upon the data they store. To change the schema one needs to create a new database with the changed schema and copy the data over (this is called database migration). Such operation is very costly and most database systems fair poorly when there are foreign keys involved (requiring them to be disabled for the migration to happen). As it turns out nowadays no database schema is truly immutable. New and changed requirements happen so often that the database schemas usually need updating (migrating) nearly every time there is an update to the systems using it. There is no solution to this "schema" issue because it is the inherent feature of representing data in tabular form. It can be only mitigated to some degree but your mileage will vary greatly when using these techniques many of which are considered antipatterns. Things like indexes, indirection (storing data with varied length), storing blob data, data with internal format unknown to the database itself (e.g. JSON) are all the ways to prevent the need for database migration at the cost of efficiency. While there are good reasons for representing data in tabular form (lookup speed and space efficiency) the costs of very often far exceed the benefits. Plus as it turns out it is not even that efficient! The tables are represented as fixed size records (rows) one after another (this is what makes the schema immutable). This representation is the most efficient when we are reading entire rows at the time (all columns) which is very rarely the case. Most often we want only some of the columns which means we are discarding some (or most) of the row when reading it. This is the same problem the CPU itself has when using memory. It reads is using cache lines. If we happen to read only some of the line the rest is wasted and another line needs to be fetched for the next item(s) (this is called a `cache miss`). This is why contiguous collections (like a `vector`) are almost always the most efficient because they minimize the cache misses. Chandler Carruth had numerous talks at CPPCon on this subject demonstrating that by far the biggest performance impact on software are the cache misses (over 50 % and up to 80 % !!!) with everything else being dwarfed in comparison. Beside trying to optimize the tables the most prominent "solution" are the NoSQL databases. They typically use a different way to store data, often in a "schema-less" to cater to the above use cases - easing database migrations (or eliminating them) and providing more efficient data lookup. They typically choose some combination of key-value representation, document representation or a graph representation to scaffold the data instead of tables. They often trade in ACID properties, use write only - never delete "big tables" and other techniques. Of NoSQL databases the graph databases stand out in particular because by definition they actually store the relations between the data in the database. How the values are then "attached" to the graph vary but the graph itself serves as an "index" as well as a "map" to be efficiently searched and reason about. The sparse graph (not all nodes are connected to all others) representation is then actually the most flexible and accurate way to store and represent the sparse data (as mentioned, nearly all real world data is sparse). There are two key properties of representing data as a graph that directly relates to the aforementioned issues of schema and data searching. Firstly the graph itself is the schema that can change freely as needed at any time without any restrictions eliminating the schema issue entirely. You do not need to be clairvoyant and agonize over the right database schema. You can do what works now and change your mind later without any issues. Secondly the graph allows accurately representing any actual relations between the data allowing the most efficient native traversal and lookup of data (vaguely resembling traditional indexing) making the lookup constantly efficient regardless of the data set size. Where table performance will deteriorate as it grows the graph will stay constantly efficient if you can traverse only the subset of the nodes via their relations even if the graph itself contained billions of nodes. This is in a nutshell why the graph database is the best choice for most problem domains and data sets out there and why `agdb` is the graph database. ## Costs Everything has the cost and graph databases are no exception. Some operations and some data representations may be costlier in them as opposed to table based databases. For example if you had immutable schema that never updates then table based database might a better fit as the representation in form of tables is more storage efficient. Or if you always read the whole table or whole rows then once again the table based databases might be more performant. Typically, though these are uncommon edge cases unlikely to be found in the real world applications. The data is almost always sparse and diverse in nature, the schema is never truly stable etc. On the other hand most use cases benefit greatly from graph based representation and thus such a database is well worth it despite some (often more theoretical) costs. ## Why not an existing graph database? The following is the list of requirements for an ideal graph database: - Free license - Faster than table based databases in most common use cases - No new language for querying - No text based queries - Rust and/or C++ driver - Resource efficient (storage & memory) Surprisingly there is no database that would fit the bill. Even the most popular graph databases such as `Neo4J` or `OrientDB` fall short on several of these requirements. They do have their own text based language (e.g. Cypher for Neo4J). They lack the drivers for C++/Rust. They are not particularly efficient (being mostly written in Java). Even the recent addition built in Rust - `SurrealDb` - is using text based SQL queries. Quite incomprehensibly its driver support for Rust itself is not very mature so far and was added only later despite the system being written in Rust. Something which is oddly common in the database world, e.g. `RethinkDb`, itself a document database, written mostly in C++, has no C++ support but does officially support for example Ruby. Atop of these issues they often do not leverage the graph structure very well (except for Neo4J which does great job at this) still leaning heavily towards tables. # Object queries The most ubiquitous database query language is SQL which is text based language created in the 1970s. Its biggest advantage is that being text based it can be used from any language to communicate with the database. However, just like relational (table) bases databases from the same era it has some major flaws: - It needs to be parsed and interpreted by the database during runtime leading to common syntax errors that are hard or impossible to statically check. - Being a separate programming language from the client coding language increases cognitive load on the programmer. - It opens up the database to attacks from SQL-injection where the attacker is trying to force the interpreter to treat the user input (e.g. table or column names) as SQL code itself issuing malicious commands such as stealing or damaging the data. - Being "Turing-complete" and complex language on itself means it can lead (and often leads) to incredibly complex and unmaintainable queries. The last point is particularly troublesome because it partially stems from the `schema` issue discussed in the previous points. One common way to avoid changing the schema is to transform the data via queries. This is not only less efficient than representing the data in the correct form directly but also increases the complexity of queries significantly. The solutions include heavily sanitizing the user inputs in an attempt to prevent SQL injection attacks, wrapping the constructing of SQL in a builder-pattern to prevent syntax errors and easing the cognitive load by letting programmers create their queries in their main coding language. The complexity is often being reduced by the use of stored SQL procedures (pre-created queries). However, all of these options can only mitigate the issues SQL has. Using native objects representing the queries eliminate all of SQL issues sacrificing the portability between languages. However, that can be relatively easily be made up via already very mature (de)serialization of native objects available in most languages. Using builder pattern to construct these objects further improve their correctness and readability. Native objects carry no additional cognitive load on the programmer and can be easily used just like any other code. # Single file All operating systems have fairly low limit on number of open file descriptors for a program and for all programs in total making this system resource one of the rarest. Furthermore, operating over multiple files does not seem to bring in any substantial benefits for the database while it complicates its implementation significantly. The graph database typically needs to have access to the full graph at all times unlike say key-value stores or document databases. Splitting the data into multiple files would therefore be actually detrimental. Lastly overall storage taken by the multiple files would not actually change as the amount of data would be the same. Conversely, using just a single file (with a second temporary write ahead log file) makes everything simpler and easier. You can for example easily transfer the data to a different machine - it is just one file. The database can also operate on the file directly if memory mapping was turned off to save RAM at the cost of performance. The program would not need to juggle multiple files consuming valuable system resources. The one file is the database and the data. # Sharding, replication and performance at scale Most databases tackle the issue of (poor) performance at scale by scaling up using replication/sharding strategies. While these techniques are definitely useful, and they are planned for `agdb` they should be avoided as much as possible. The increase in complexity when using replication and/or sharding is dramatic, and it has adverse performance impact meaning it is only worth it if there is no other choice. The `agdb` is designed so that it performs well regardless of the data set size. Direct access operations are O(1) and there is no limit on concurrency. Write operations are O(1) amortized however they are exclusive - there can be only one write operation running on the database at any given time preventing any other read or write operations at the same time. You will still get O(n) complexity when searching the (sub)graph as reading 1000 connected nodes will take 1000 O(1) operations = O(n) same as reading 1000 rows in a table. However, if the data does not indiscriminately connect everything to everything one can have as large data set as the hardware can fit without performance issues. The key is querying only subset of the graph (subgraph) since your query will have performance based on that subgraph and not all the data stored in the database. The point here is that scaling has significant cost regardless of technology or clever tricks. Only when the database starts exceeding limits of a single machine they shall be considered because adding data replication/backup will mean huge performance hit. To mitigate it to some extent caching can be used, but it can never be as performant as local database. The features "at scale" are definitely coming you should avoid using them as much as possible even if available. [For real world performance see dedicated documentation.](https://agdb.agnesoft.com/docs/references/performance) # Why not SQL? SQL, or Structured Query Language, is a programming language that has dominated the database space for decades. Initially created 50 years ago in 1974 just two years after C. Despite its undeniable success its age means it has many less-than-ideal properties particularly unsuitable for a modern database(s) like the `agdb`. ## Yet another programming language SQL is a Turing complete programming language which has grown to be vast, complex and complicated. When a programmer needs to access or manipulate a database using SQL they need to learn entire additional language in addition to the one in which they are writing their program. This cognitive (over)load is very often being solved by abstracting the "raw" SQL behind an ORM (Object-relational mapping) to seemingly use the database directly from the main programming language. The keyword here is seemingly because under the hood any ORM will simply translate to a "raw" SQL that quite often might not be as performant as when written by hand. ::tip ORM often violates the famous zero-cost abstraction rule favorite in languages like C++ or Rust that states "the abstraction is as performant as if written by hand". :: The textual nature of SQL means that it can be used from any programming language with ease, but that is of little importance for an individual programmer writing it in their program. While they enjoy the benefits of their IDE and language server for their primary languages, there is not much that can be done about the embedded SQL statements in their code. Until they are run against a database it cannot even be known if even the basic syntax is correct (certain plugins do offer limited SQL support for syntax etc. but the ultimate truth is the particular implementation of the given database). This unpleasant experience is worsened further with advent of new programming tooling like Copilot where the main language support is better than ever while SQL support lags behind as it is nearly impossible to improve the experience in that area. ## Interpreting an injection SQL injection is one of the most prevalent attacks using SQL programming languages. This is made possible by two major properties: 1. SQL is a textual language. 2. SQL is a runtime-interpreted language. There is a long Wikipedia page on [this attack](https://en.wikipedia.org/wiki/SQL_injection){rel=""nofollow""} citing serious recent cases of data breaches due to it. This problem cannot be definitively solved because it stems from the fundamental properties of the language. As long as it must take user input and is effectively interpreted only during runtime this type of attack can and will happen. Various mitigation strategies while effective (e.g. stored procedures, database permissions) also increases complexity and cost of using the language. Probably the closest thing to eliminate SQL injection attacks entirely is use of server-side stored procedures. Essentially a type of remotely executed pre-defined function. However, the procedure itself must take precautions and to sanitize the inputs. Making changes to remote procedures is also much more difficult than simply changing the SQL statement in your code. Not to mention that even when the client code is perfectly fine and sanitized the SQL interpreted on the database side does not necessarily have to be (although it typically will be). ## Complexity and performance As mentioned the SQL is a regular programming language and as such it allows writing literally anything in it. Back in the 70s and decades after this property was very valuable because client machines (unlike database servers) were not particularly performant. Letting the server do the heavy lifting and massaging the data into the correct output made sense and often was the only viable approach. Unfortunately it can also lead to quite complex queries. Have you ever seen 10 000 line long SQL query? Yes, singular. And yes, 4 zeroes. Making changes to such a query will take many days spent on understanding it and figuring out how to change it. Nowadays, client machines are so powerful that doing any extra work on any server is generally undesirable. The situation is pretty much completely reversed. Particularly embedding application/business logic in database queries can lead to hard to change and hard to maintain code because SQL is not the primary language of any application and is often not even very suitable for it in the first place (it is a domain specific language for interfacing with the databases). Performance of SQL can never match compiled or even JIT compiled languages. Being interpreted means it must be parsed (in itself very non-trivial task that can lead to SQL injections mentioned above) and then translated into internal database structures and commands to be executed. And once more mitigation steps exist (like stored procedures again) but they are simply a patch over a fundamental property of the language. ## An alternative Despite all of its shortcomings the SQL is still the dominant database language and the `agdb` will have to support it at some point to certain degree as well. Somewhat frustratingly there is no good off the shelf alternative. Many no-SQL databases went on and created their own textual interpreted language immediately suffering from the very same issues described above but without any of the 50 years of hardening SQL has had. And the only benefit of being usable from "any" programming language is usually immediately thrown away by the creation of an ORM for each language. So what is the alternative? [Object based queries](https://agdb.agnesoft.com/blog/object-queries). Having a binary compiled format eliminates most of the above problems. A binary query cannot morph into another because of some user input. The code, including the queries, is written entirely and only in the language of choice. The performance is unmatched on both sides as the database does not need to interpret the text into its own structures and everything is as expected (or results in a query error if not). Language server and IDE can easily help like with any other code. There can never be a syntax error. It does not lend itself very easily to a thousand lines long data queries and basically forces the application to process the data in itself rather than on the database server (beyond basic operations like sorting or filtering). The cost of course is that the query system needs to be either written or generated for each language (initial cost) and that such a query system is not Turing complete programming language (which is perhaps more of a benefit). And that seems like a small price for everything else. Nearly everything has changed and after 50 years it is time for something better in the database space and to start treating SQL like we do the languages from the same era - replace them with better and safer alternatives. # agdb in the AI era Applications built around large language models need to remember things: what the user said, what the agent did, which facts it learned and where they came from. Most of that is not a list of documents but a web of relations: people, projects, decisions and the conversations connecting them. That is a graph, and it is where `agdb` fits naturally. ## Memory is a graph An agent's long-term memory has a few kinds of things in it: - conversations and their messages, - entities the messages mention (people, projects, technologies), - facts linking the entities ("agdb_server is built on agdb"), - the actions the agent took and what they touched. In `agdb` each of these is a node or an edge with key-value properties. There is no schema to migrate when the agent starts noticing a new kind of thing, you simply store it. Recalling context for the next prompt is then a traversal: start at the entity mentioned in the new message and follow its relations to what it is connected to. Thanks to `agdb`'s storage design a lookup or a traversal does not get slower as the database grows, its cost depends only on what it visits (see [Why graph?](https://agdb.agnesoft.com/blog/why-graph)). That matters when an agent recalls memory on every step of its loop. ```rs // The facts within two hops of an entity. Following the outgoing edges only // the facts are traversed and the distance condition also stops the search. let facts = t.exec( QueryBuilder::select() .values("relation") .search() .from(entity) .where_() .edge() .and() .distance_less_than(4) .query(), )?; ``` Knowledge can be traced back: the messages mentioning an entity are simply its neighbours pointing to it (and storing the source message on a fact edge traces each fact). Forgetting a conversation (e.g. when the user asks for it) removes its messages while keeping what was learned from them, or not, it is up to you. The complete runnable example is walked through in [Agent memory](https://agdb.agnesoft.com/docs/examples/agent-memory) (`cargo run -p agdb --example agent_memory`). ## Queries an LLM cannot inject into Text written by users, and text written by models, is untrusted. When it ends up concatenated into an SQL or Cypher string it can change what the query does. That is prompt injection meeting SQL injection. `agdb` has [no query language](https://agdb.agnesoft.com/blog/why-not-sql). Queries are typed objects built in your application's language and the user's or the model's text is only ever a value: ```rs let message = Message { db_id: None, role: "user".to_string(), text: untrusted_text, // stored as is, never parsed as a query }; db.exec_mut(QueryBuilder::insert().nodes().values([&message]).query())?; ``` There is nothing to escape and nothing to inject into. The same holds when the agent's tools are written by the model itself: an AI coding assistant writing `agdb` queries writes ordinary Rust, TypeScript, Python or PHP code with a typed query builder. A wrong query is most often a compile error (Rust) or a type-check error (TypeScript, or Python and PHP with a type checker such as mypy or PHPStan) rather than a query that silently does something else at runtime. ## One file per agent The embedded `agdb` is a library and the whole database is a [single file](https://agdb.agnesoft.com/blog/single-file). That makes some designs easy that are hard with a database server: - a separate memory file per agent, user or session, deleted when it is no longer needed, - local-first and on-device AI applications where the data never leaves the machine, - shipping a prepared knowledge graph as one file together with the application. When the agents need to share memory, the same queries run against [`agdb_server`](https://agdb.agnesoft.com/docs/references/server) with users, roles, backups and a replicated cluster, and the [studio](https://agdb.agnesoft.com/docs/guides/how-to-use-studio) lets you look at the agent's memory as a 3D graph. ## What agdb is not `agdb` is not a vector database. It can store embeddings as vector values (`Vec`) but it has no similarity search index. For semantic search over documents, use a vector database and let `agdb` hold the knowledge graph around it: the relationships, provenance and permissions. A vector search returns the ids of the closest chunks and `agdb` expands from them to everything connected. That is the idea behind GraphRAG and the two kinds of databases complement each other. ## Documentation for AI assistants The documentation of `agdb` is available to AI tools in plain markdown: - [llms.txt](https://agdb.agnesoft.com/llms.txt){rel=""nofollow""} lists every page with a short description, - [llms-full.txt](https://agdb.agnesoft.com/llms-full.txt){rel=""nofollow""} has the complete documentation in one file, - every page has its markdown version under `/raw`, e.g. [/raw/docs/guides/quickstart.md](https://agdb.agnesoft.com/raw/docs/guides/quickstart.md){rel=""nofollow""}. Point your coding assistant at them, or add `llms-full.txt` to its context, and it will write `agdb` queries with the real API rather than guessing it. # Blog Articles written about the `agdb` and related topics adding insights into technologies and thinking behind the database. ## Articles - [Distance](https://agdb.agnesoft.com/blog/distance) - [Why graph?](https://agdb.agnesoft.com/blog/why-graph) - [Object queries](https://agdb.agnesoft.com/blog/object-queries) - [Single file](https://agdb.agnesoft.com/blog/single-file) - [Replication, sharding and performance](https://agdb.agnesoft.com/blog/replication-sharding-performance) - [Why not SQL?](https://agdb.agnesoft.com/blog/why-not-sql) - [agdb in the AI era](https://agdb.agnesoft.com/blog/ai-era) # Technical Consultation We offer technical consultation for your project. Our experts will help you answer any of your questions, and we offer a free, 30 minute consultation to get you started. Drop us an e-mail to book a slot at: ## Enterprise & Commercial Support If you are interested in using `agdb` in your business please visit the dedicated [enterprise](https://agdb.agnesoft.com/enterprise) section for commercial options. ## General Questions - Search the [documentation](https://agdb.agnesoft.com/docs). - Send an e-mail with your questions to - Post a question in [r/agdb](https://www.reddit.com/r/agdb){rel=""nofollow""} subreddit. - Open a [discussion](https://github.com/agnesoft/agdb/discussions){rel=""nofollow""}. - Open an [issue](https://github.com/agnesoft/agdb/issues){rel=""nofollow""}. # Cloud The cloud solution is currently not publically available. Please contact us at . # Self-hosted If you are interested in self-hosting `agdb` we offer basic guides with server or cluster variants for the publically available target platforms: | Type / Target | Bare Metal | Docker | K8s | | ------------- | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | --------------------------------------------------------------------------- | | Server | [LINK](https://agdb.agnesoft.com/docs/guides/how-to-run-server/server-bare-metal) | [LINK](https://agdb.agnesoft.com/docs/guides/how-to-run-server/server-docker) | [LINK](https://agdb.agnesoft.com/docs/guides/how-to-run-server/server-k8s) | | Cluster | [LINK](https://agdb.agnesoft.com/docs/guides/how-to-run-server/cluster-bare-metal) | [LINK](https://agdb.agnesoft.com/docs/guides/how-to-run-server/cluster-docker) | [LINK](https://agdb.agnesoft.com/docs/guides/how-to-run-server/cluster-k8s) | If you require support setting up `agdb` in your environment please contact us at: # Support We offer following support channels: - [Technical Consultation](https://agdb.agnesoft.com/#technical-consultation) - Post a question in [r/agdb](https://www.reddit.com/r/agdb/){rel=""nofollow""} subreddit. - Open a [discussion](https://github.com/agnesoft/agdb/discussions){rel=""nofollow""}. - Open an [issue](https://github.com/agnesoft/agdb/issues){rel=""nofollow""}. For additional or dedicated support please contact us at: # Sponsors The sponsorship is available on GitHub at: {rel=""nofollow""} If you would like to become an official sponsor, get recognition on the homepage as well as in the repository please reach out to: # Enterprise The `agdb` is open-source software provided as-is under [Apache 2.0 license](https://agdb.agnesoft.com/license). You can obtain a commercial license that would grant you access to various services like a cloud hosted database, support for self-hosted solutions and direct general support. You can also consider [sponsoring](https://agdb.agnesoft.com/enterprise/sponsors) the development of `agdb` and get mentioned on the homepage and in the repository! - [Technical Consultation](https://agdb.agnesoft.com/enterprise/consultation) - [Self-hosted](https://agdb.agnesoft.com/enterprise/self-hosted) - [Cloud](https://agdb.agnesoft.com/enterprise/cloud) - [Support](https://agdb.agnesoft.com/enterprise/support) - [Sponsors](https://agdb.agnesoft.com/enterprise/sponsors)