Rust

Database

Document database: collections, attributes, indexes, documents, queries, permissions, relationships and tenancy over pluggable adapters (PostgreSQL, MariaDB, MySQL, SQLite, in-memory, Redis, Pool, Mirror).
Rust 55,702 lines (45,041 code)split
PartCodeCommentsBlankTotalFiles
Rust source45,0416,9313,73055,702109
Rust tests506144256213

Comments include doc comments. Rust tests are tests/ and #[cfg(test)] modules.

Install#

The crate lives in the Appwrite repository; depend on it from Git.

Cargo.toml
[dependencies]
utopia-database = { git = "https://github.com/appwrite/appwrite" }

Getting started#

Common tasks with Database, each a complete program you can copy and run.

A document database over SQL: collections with typed attributes and indexes, documents carrying their own permissions, queries that filter, order and page them, relationships between collections, tenancy and caching. It is the Rust port of utopia-php/database 7.4 and reads and writes the same schemas, rows and metadata, so a PHP service and a Rust service can work on one dataset. This guide covers the common tasks, then how the crate is built.

Parse the queries of a list request

A request names its queries as JSON strings. Query::parse reads one, with PHP's errors for the malformed ones; to_string writes it back.

Rust
use utopia_database::Query;
use utopia_database::query::Method;

let query = Query::parse(r#"{"method":"equal","attribute":"name","values":["Ada","Grace"]}"#)?;
assert_eq!(query.method(), &Method::Equal);
assert_eq!(query.attribute(), "name");
assert_eq!(query.values().len(), 2);
assert_eq!(query.to_string()?, r#"{"method":"equal","attribute":"name","values":["Ada","Grace"]}"#);

let error = Query::parse(r#"{"method":"near","values":[]}"#).unwrap_err();
assert_eq!(error.message(), "Invalid query method: near");

Give a document its permissions

Permissions are strings of a type and a role: read("any"), update("user:ada"). The helpers build them, and ID::unique() makes the ids PHP makes.

Rust
use utopia_database::helpers::{id, permission::Permission, role::Role};
use utopia_database::{Document, Value};

let mut profile = Document::default();
profile.set("$id", Value::from(id::unique()?.as_str()));
profile.set(
    "$permissions",
    Value::Array(
        [Permission::read(&Role::any()), Permission::update(&Role::user("ada", ""))]
            .into_iter()
            .map(|p| Value::from(p.as_str()))
            .collect(),
    ),
);
profile.set("name", Value::from("Ada"));

assert_eq!(profile.id().len(), 20);
assert_eq!(profile.read(), vec![r#"any"#.to_owned()]);
assert_eq!(profile.update(), vec![r#"user:ada"#.to_owned()]);

Store and find documents

Database sits on an adapter (PostgreSQL here) and a cache. It creates the schema, checks every document against its collection before writing it, and checks permissions against the roles of its Authorization.

Rust
use std::sync::Arc;

use utopia_cache::{Cache, Memory};
use utopia_database::adapter::postgres::Postgres;
use utopia_database::query::Method;
use utopia_database::{Authorization, Database, Document, Query, Value};

tokio::runtime::Runtime::new()?.block_on(async {
    let adapter = Postgres::connect("postgres://root:password@localhost:5432/root").await?;
    let db = Database::new(Arc::new(adapter), Arc::new(Cache::from_dyn(Arc::new(Memory::new()))), Vec::new());
    let authorization = Authorization::new();
    authorization.add_role("any");
    db.set_authorization(Arc::new(authorization));
    db.set_database("guide")?.set_namespace("app")?;
    db.create(None).await?;

    let permissions = ["read(\"any\")", "create(\"any\")"].map(String::from).to_vec();
    db.create_collection("people", Vec::new(), Vec::new(), Some(permissions), false).await?;
    db.create_attribute("people", "name", Database::VAR_STRING, 128, true, Value::Null, true, false, None, Default::default(), Vec::new())
        .await?;

    let mut ada = Document::default();
    ada.set("$id", Value::from("ada"));
    ada.set("name", Value::from("Ada"));
    db.create_document("people", ada).await?;

    let found = db
        .find("people", vec![Query::new(Method::Equal, "name", vec![Value::from("Ada")])], Database::PERMISSION_READ)
        .await?;
    assert_eq!(found[0].id(), "ada");
    Ok::<_, Box<dyn std::error::Error>>(())
})?;
Compiles in CI; needs a running service to execute.

Store documents in MongoDB

The Mongo adapter (feature mongo) keeps collections in one MongoDB database, the one its utopia_mongo::Client names. Attributes need no schema there, and with set_support_for_attributes(false) documents may carry any attribute (schemaless). Transactions need a replica set.

Rust
use std::sync::Arc;

use utopia_cache::{Cache, Memory};
use utopia_database::adapter::mongo::{Mongo, from_client};
use utopia_database::{Authorization, Database, Document, Value};
use utopia_mongo::{Client, Config};

tokio::runtime::Runtime::new()?.block_on(async {
    let client = Client::new(Config::new("guide", "localhost", 27017, "root", "password")).map_err(from_client)?;
    let adapter = Mongo::new(Arc::new(client)).await?;
    let db = Database::new(Arc::new(adapter), Arc::new(Cache::from_dyn(Arc::new(Memory::new()))), Vec::new());
    let authorization = Authorization::new();
    authorization.add_role("any");
    db.set_authorization(Arc::new(authorization));
    db.set_database("guide")?.set_namespace("app")?;
    db.create(None).await?;

    let permissions = ["read(\"any\")", "create(\"any\")"].map(String::from).to_vec();
    db.create_collection("notes", Vec::new(), Vec::new(), Some(permissions), false).await?;
    let mut note = Document::default();
    note.set("$id", Value::from("first"));
    let note = db.create_document("notes", note).await?;
    assert_eq!(note.sequence().map(utopia_database::value::to_text).unwrap_or_default().len(), 36);
    Ok::<_, Box<dyn std::error::Error>>(())
})?;
Compiles in CI; needs a running service to execute.

How the crate is built

  • Database (database/) is PHP's Database class split by area, one impl Database per file: the schema (settings and scopes, filters, cache keys, collections, attributes, indexes, metadata, transactions), documents (reads with the document cache, creates, updates, upserts, increments, deletes, finds, counts, sums, iteration) and relationships (one-to-one, one-to-many, many-to-one, many-to-many: their attributes, junction collections, population, writes, on-delete rules and relationship queries). A Database is a cheap clone: clones share the adapter, cache and settings, as PHP's references to one object do. Scoped settings (skip_relationships, silent, with_tenant, ...) take an async closure and restore the setting when it ends or is dropped.
  • Adapters (adapter/) implement the Adapter trait: the SQL of one engine, its limits and capabilities. Postgres speaks the wire protocol itself and renders statements as PHP's PDO does with emulated prepares, so the server sees the same SQL from both runtimes. Sqlite (feature sqlite) runs SQLite in process (rusqlite, bundled) and reproduces PDO-sqlite's prepares, bindings, fetches and errors; Memory (feature memory) keeps collections in PHP arrays, with PHP's array semantics, and journals for transactions. MariaDB (feature mariadb; with Flavor::MySQL and feature mysql, PHP's MySQL subclass) runs its statements over mysql_async's text protocol, rendered as PDO mysql renders them (mysqlnd's quoting, mysql_real_query with multi statements, the server status for inTransaction()). Mongo runs on utopia-mongo (the official driver) and sends the commands PHP's adapter sends: documents under PHP's internal keys (_uid, _id as a UUIDv7, _tenant, ...), queries as find filters, operators as aggregation pipeline updates; values cross as PHP's MongoDB extension converts them (UTCDateTime, ObjectId and Regex are Ext::Bson).
  • Filters (database/filters.rs) transform attribute values on the way to the adapter and back: the built-in json, datetime and the spatial, vector and object ones, plus any Filter registered globally (Database::add_filter) or for one database. Their signatures (the PHP closures' file:line) are part of document cache keys, so the keys match PHP's.
  • The cache (database/cache.rs) keeps documents and query results under PHP's keys, in a utopia_cache::Cache. A Redis cache with PHP's Json or igbinary codec shares its entries (per-projection hash fields and generation leases included) with PHP.
  • Values: attributes are PHP values (Value, php_std::types::Value extended with documents, queries and operators), so loose comparisons, key order and number formatting behave as in PHP.
  • Validators (validator/): structure, queries, indexes, permissions, roles, keys, dates, spatial and vector values, each with PHP's messages.

Query here is Utopia\Database\Query, the database's own query model. utopia-php/query, a separate SQL builder converted as the utopia-query crate, overlaps with it only in name: utopia-php/database 7.4 does not use it, and when the PHP library builds its SQL with it, the adapters here move onto utopia-query with it.

Status

The conversion is complete: every class, method and adapter of utopia-php/database 7.4, proven with bin/compat check database (the library's e2e suites and unit tests on every adapter, recorded as cases, with no differences). Appwrite's Rust services read and write through it.

Reference#

A document database: collections with typed attributes and indexes, documents with permissions, queries, relationships, tenancy and caching, over pluggable storage adapters.

Modules#

Each module groups one concept of the library. Internal ones hold items the crate re-exports at its root.

adapter::mariadb::ddlinternal
Databases, tables, columns, relationship columns and indexes, and the schema as the server reports it.
adapter::mariadb::documentsinternal
Documents: reads by id, creates, updates, upserts, deletes, sequence lookups and atomic increments, with their permission rows.
adapter::mariadb::findinternal
Finds, counts and sums: `WHERE` conditions for every query method (comparisons, `LIKE`, `REGEXP`, `MATCH ... AGAINST` full-text search, JSON arrays, spatial filters), cursor pagination and the document-level permission filter.
adapter::mariadb2 items
`MariaDB`: the MariaDB adapter, and with `Flavor::MySQL` (feature `mysql`) the MySQL adapter.
adapter::mariadb::operatorsinternal
Operators: atomic updates as SQL expressions over MariaDB's (and MySQL's) JSON functions, and their effect on a default value for documents an upsert creates.
adapter::mariadb::pdo10 items
The adapter writes SQL with named placeholders (`:_uid`) and binds values with a PDO parameter type. PDO (`ATTR_EMULATE_PREPARES`) substitutes the placeholders client side with quoted literals and sends the statement as text (`mysql_real_query`, multi statements allowed); with `ATTR_STRINGIFY_FETCHES` every fetched value is a string. `Pdo` reproduces that over `mysql_async`'s text protocol, so the server sees the same bytes and the adapter reads the same values:
adapter::mariadb::spatialinternal
Geometries: arrays to WKT, and the SRID-prefixed WKB MariaDB and MySQL return for spatial columns (or WKT) back to coordinate arrays.
adapter::mariadb::sqlinternal
The building blocks every statement uses: identifiers, table names, tenant conditions, column types, parameter types, and the mapping of driver errors onto the library's errors.
adapter::memory::documentsinternal
Documents: reads, creates, updates, deletes, sequences, increments, the permission indexes and the unique-index hash tables.
adapter::memory1 items
`Memory`: the in-memory adapter.
adapter::memory::operatorsinternal
Undocumented.
adapter::memory::queryinternal
Undocumented.
adapter::memory::schemainternal
Databases, collections, attributes, relationship fields and indexes.
adapter::memory::storeinternal
Undocumented.
adapter7 items
`Adapter`: the storage engine under a `crate::Database`.
adapter::mongo::bsoninternal
Undocumented.
adapter::mongo::castinginternal
Values to and from what MongoDB stores: dates as `UTCDateTime`, objects as embedded documents, integers as integers.
adapter::mongo::documentsinternal
Documents: reads, creates, updates (operators as aggregation pipelines), upserts, increments, deletes, finds, counts and sums.
adapter::mongo::filtersinternal
Queries as MongoDB filters, and the key mappings between documents and stored records.
adapter::mongo2 items
`Mongo`: the MongoDB adapter.
adapter::mongo::schemainternal
Databases, collections, attributes, relationships and indexes.
adapter::pool2 items
`Pool`: an adapter over a pool of adapters.
adapter::postgres::ddlinternal
Schemas, tables, columns, relationship columns and indexes.
adapter::postgres::documentsinternal
Documents: reads by id, creates, updates, upserts, deletes, sequence lookups and atomic increments, with their permission rows.
adapter::postgres::findinternal
Finds, counts and sums: `WHERE` conditions for every query method (comparisons, `LIKE`, POSIX regexes, full-text search, JSONB arrays and objects, PostGIS spatial filters), pgvector distance ordering, cursor pagination and the document-level permission filter.
adapter::postgres1 items
`Postgres`: the PostgreSQL adapter.
adapter::postgres::operatorsinternal
Operators: atomic updates as SQL expressions, and their effect on a default value for documents an upsert creates.
adapter::postgres::pdo13 items
The adapter writes SQL with named placeholders (`:_uid`) and binds values with a PDO parameter type. PDO (`ATTR_EMULATE_PREPARES`) substitutes the placeholders client side with quoted literals and sends the statement as plain text with `PQexec`; with `ATTR_STRINGIFY_FETCHES` every fetched value is a string. `Pdo` reproduces that, so the server sees the same text and the adapter reads the same values:
adapter::postgres::spatialinternal
Geometries: arrays to WKT for PostGIS, and the hex EWKB PostGIS returns (or WKT) back to coordinate arrays.
adapter::postgres::sqlinternal
The building blocks every statement uses: identifiers, table names, tenant conditions, column types, parameter types, statement execution with the statement timeout, and the mapping of driver errors onto the library's errors.
adapter::postgres::widthsinternal
Display widths of Unicode characters, as libpq computes them for the caret under an error position (`ucs_wcwidth` in PostgreSQL 18's `src/common/wchar.c`, over the tables PostgreSQL generates from Unicode).
adapter::postgres::wire6 items
The PostgreSQL frontend/backend protocol, as libpq's `PQexec` speaks it.
adapter::redis::documentsinternal
Documents of the `Redis` adapter: reads, writes, bulk writes, upserts, sequences, deletes and increments, journalled inside transactions.
adapter::redis3 items
`Redis`: documents stored in Redis.
adapter::redis::operatorsinternal
Operators of the `Redis` adapter: applied here to the stored value, as the SQL adapters apply them in SQL.
adapter::redis::queryinternal
Undocumented.
adapter::redis::schemainternal
Databases, collections, attributes, indexes and relationships of the `Redis` adapter: the meta hash of each collection and the scans that rewrite or drop its keys.
adapter::sqlite::ddlinternal
Tables, columns, relationship columns, indexes (FTS5 virtual tables for fulltext ones) and schema introspection.
adapter::sqlite::documentsinternal
Documents: reads by id, creates, updates, upserts, deletes, sequence lookups and atomic increments, with their permission rows.
adapter::sqlite::findinternal
Finds, counts and sums: `WHERE` conditions for every query method (comparisons, `LIKE` with explicit escapes, `REGEXP`, FTS5 searches, JSON array membership), cursor pagination and the document-level permission filter.
adapter::sqlite1 items
`Sqlite`: the SQLite adapter.
adapter::sqlite::operatorsinternal
Operators: atomic updates as SQL expressions (SQLite's JSON functions for arrays), and their effect on a default value for documents an upsert creates.
adapter::sqlite::pdo7 items
The adapter writes SQL with named placeholders (`:_uid`) and binds values with a PDO parameter type. The sqlite driver prepares the statement as it is (`sqlite3_prepare_v2`: SQLite reads `:name` placeholders itself, and text after the first statement is ignored) and binds each value when the statement executes, so `Pdo` does the same over `rusqlite`:
adapter::sqlite::sqlinternal
The building blocks every statement uses: identifiers, table names, tenant conditions, column types, parameter types, statement execution, the mapping of driver errors onto the library's errors, and geometry text.
adapter::sqlstate1 items
The descriptions PDO gives SQLSTATEs in its exception messages (`SQLSTATE[23000]: Integrity constraint violation: ...`), the same for every PDO driver.
change1 items
`Change`: a document before and after an upsert.
connection3 items
Whether an error means the connection to the database was lost.
database::attributesinternal
Attributes: create, update, rename, delete, and the checks they run.
database::cacheinternal
Document and query caching: keys, purges and the read-through `with_cache`.
database::collectionsinternal
Databases (schemas) and collections.
database::configinternal
Settings: listeners, statement transforms, scoped flags, namespace and database, cache, metadata, authorization, timeouts, validation, tenancy, document types, connection.
database::constsinternal
Undocumented.
database::documentsinternal
Documents: get, create, update, upsert, increase/decrease, delete, singly and in batches.
database::filtersinternal
Attribute filters (the global registry and the defaults), document encoding, decoding and casting, and the filter signatures cache keys carry.
database::findinternal
Finding documents: `find`, `find_one`, `count`, `sum`, `foreach`, `iterate`, and the query conversion and checks they run.
database::indexesinternal
Indexes: create, rename, delete.
database::metadatainternal
Persisting collection metadata with retries, and the cleanups that roll schema changes back when it fails.
database4 items
`Database`: collections, attributes, indexes, documents, finds, permissions, relationships, tenancy and caching over an `Adapter`.
database::planinternal
Attribute plans: the settings `decode()`, `casting()` and `encode()` read from each attribute of a collection, read once per collection document instead of once per document they process.
database::relationshipsinternal
Relationships: relationship attributes, populating related documents, writing and deleting through relationships, and queries on related attributes.
database::transactioninternal
Transactions.
datetime7 items
Dates as the database stores them: `Y-m-d H:i:s.v` in the default timezone (`FORMAT_DB`), and as the API shows them, with the offset (`FORMAT_TZ`).
document3 items
`Document`: an ordered set of attributes, with the system attributes (`$id`, `$sequence`, `$collection`, `$tenant`, `$createdAt`, `$updatedAt`, `$permissions`) every stored document has.
error3 items
The errors database operations fail with.
helpers::id4 items
Document identifiers: `unique` generates one, `custom` takes one given.
helpers0 items
Identifiers (`id`), roles (`role`) and permissions (`permission`).
helpers::permission2 items
`Permission`: an action granted to a `Role`, written `action("role")` (`read("any")`, `update("team:123/owner")`).
helpers::role2 items
`Role`: who a permission is granted to (`any`, `users`, `user:<id>`, `team:<id>/<dimension>`, ...).
mirror2 items
`Mirror`: a database whose writes are copied to a second one.
mirroring1 items
`Filter`: what a `crate::mirror::Mirror` runs around the writes it copies to its destination.
operator7 items
`Operator`: an atomic update of one attribute (increment, array append, string concat, ...), given as an attribute value of an update.
query::ctorinternal
Undocumented.
query::groupinternal
Undocumented.
query5 items
`Query`: one filter, order, selection or pagination step of a find.
query::valuesinternal
Undocumented.
validator::attribute4 items
`Attribute`: attribute definitions before they are created.
validator::authorization2 items
`Authorization`: the roles of the current request and whether a permission list grants an action to them.
validator::big_int4 items
Undocumented.
validator::byte_length1 items
`ByteLength`: strings of bounded byte length.
validator::datetime4 items
`Datetime`: date strings within a range, optionally in the future and at a precision.
validator::index2 items
`Index`: index definitions against a collection's attributes and the adapter's capabilities.
validator::index_dependency1 items
`IndexDependency`: whether an attribute can be deleted or renamed while indexes use it.
validator::indexed_queries1 items
`IndexedQueries`: query lists that also need indexes (full-text searches) and use at most one vector query.
validator::key1 items
`Key`: attribute, index and collection keys.
validator::label1 items
`Label`: user labels.
validator0 items
Validators: documents against their collection (`structure`), queries (`queries`, `query`), attribute and index definitions, keys, permissions and roles, and the `authorization` check of a permission list against the current roles.
validator::object1 items
`ObjectValidator`: values of object attributes.
validator::operator3 items
`Operator`: atomic update operators against the attributes they update.
validator::partial_structure1 items
`PartialStructure`: partial documents (the attributes of an update) against their collection.
validator::permissions2 items
`Permissions`: lists of permission strings.
validator::queries::document1 items
`Document`: the queries of a single-document read (selections only).
validator::queries::documents2 items
`Documents`: the queries of a document find.
validator::queries1 items
`Queries`: lists of queries, each checked by the `QueryValidator` of its kind; and the lists for one document (`document`) and for document finds (`documents`).
validator::query::base2 items
`QueryValidator`: the validator of one kind of query that `crate::validator::queries::Queries` dispatches to, by `MethodType`.
validator::query::cursor1 items
`Cursor`: `cursorAfter` and `cursorBefore` queries.
validator::query::filter2 items
`Filter`: filter queries (`equal`, `contains`, `between`, spatial, vector, logical, ...).
validator::query::limit1 items
`Limit`: `limit` queries.
validator::query0 items
Validators of one query by kind (`Validator\Query\*`): filters, cursors, limits, offsets, orders and selections.
validator::query::offset1 items
`Offset`: `offset` queries.
validator::query::order1 items
`Order`: `orderAsc`, `orderDesc` and `orderRandom` queries.
validator::query::select1 items
`Select`: `select` queries.
validator::roles3 items
`Roles`: lists of role strings.
validator::sequence1 items
`Sequence`: document sequence values (`$sequence` and `id` attributes).
validator::spatial1 items
`Spatial`: values of point, linestring and polygon attributes.
validator::structure2 items
`Structure`: documents against their collection's attributes; and the registry of attribute `formats`.
validator::structure::formats7 items
The registry of attribute formats: named validators an attribute's `format` selects, for one attribute type (an `email` format of `string` attributes, an `enum` of `string`, a `range` of `integer`).
validator::uid1 items
`Uid`: document identifiers.
validator::vector1 items
`Vector`: values of vector attributes.
value15 items
The values documents and queries carry.

API#

What utopia_database exports at its root.