Rust

Migration

Moves resources between services: sources (Appwrite, Supabase, NHost, Firebase, CSV, JSON) and destinations (Appwrite, CSV, JSON, a local backup), with the transfer, its cache and status counters.
Rust 28,402 lines (25,275 code)split
PartCodeCommentsBlankTotalFiles
Rust source25,2752,0061,12128,40248
Rust tests2202241

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-migration = { git = "https://github.com/appwrite/appwrite" }

Getting started#

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

A migration moves resources (users, databases, tables, rows, buckets, files, functions, messaging, sites) from one service into another. A Source exports them: Appwrite (through its API or straight from a project database), Supabase, NHost, Firebase, or a CSV or JSON file. A Destination imports them: Appwrite, a CSV or JSON file, or a local backup. A Transfer connects the two, keeps every resource it has seen in a Cache, and counts them by status. Sources and destinations are async, so the examples run them on a Tokio runtime. This guide covers the common tasks.

Stream a large JSON export

json_machine::Items reads a JSON array (or object) one item at a time, so an export of millions of rows never has to fit in memory. Each item comes with its key; the Ext decoder decodes it like json_decode, PassThru hands back its JSON text.

Rust
use php_std::Value;
use utopia_migration::json_machine::{Decoder, Items};

tokio::runtime::Runtime::new()?.block_on(async {
    let json = r#"[{"$id": "ada", "age": 36}, {"$id": "alan", "age": 41}]"#;
    let mut items = Items::from_bytes(json, Decoder::Ext { assoc: true });
    let mut ids = Vec::new();
    while let Some((_key, row)) = items.next().await? {
        if let Value::Array(row) = row {
            ids.push(row.get_str("$id").cloned());
        }
    }
    assert_eq!(ids, [Some(Value::from("ada")), Some(Value::from("alan"))]);

    // A truncated document yields what it has, then fails where it ends.
    let mut broken = Items::from_bytes("[1, 2", Decoder::PassThru);
    assert_eq!(broken.next().await?.map(|(_, v)| v), Some(Value::from("1")));
    assert_eq!(broken.next().await?.map(|(_, v)| v), Some(Value::from("2")));
    assert!(broken.next().await.is_err());
    Ok::<_, utopia_migration::Error>(())
})?;

Turn a JSON export into a CSV file

A JSON file of rows is a source for one table (<database>:<table>); a CSV destination writes the rows it imports to <directory>/<filename>.csv on a storage device. Run the transfer for the row resource type, then shut the destination down: that is when the file is moved onto the device.

Rust
use std::sync::Arc;
use utopia_migration::destinations::csv::{Csv, CsvOptions};
use utopia_migration::sources::json::Json;
use utopia_migration::{Destination, Transfer};
use utopia_storage::{Device, Local};

let dir = std::env::temp_dir().join(format!("utopia-migration-guide-{}", std::process::id()));
std::fs::create_dir_all(&dir)?;
std::fs::write(dir.join("people.json"), r#"[{"$id": "ada", "name": "Ada", "age": 36}, {"$id": "alan", "name": "Alan", "age": 41}]"#)?;

tokio::runtime::Runtime::new()?.block_on(async {
    let device: Arc<dyn Device> = Arc::new(Local::new(dir.to_str().unwrap_or_default()));
    let source = Json::new("people:people", dir.join("people.json").to_string_lossy(), device.clone());
    let destination =
        Csv::new(device, "people:people", "exports", "people", Vec::new(), CsvOptions::default()).await?;

    let mut transfer = Transfer::new(Box::new(source), Box::new(destination));
    transfer.run(&["row"], &mut |_rows| Ok(()), None, None).await?;
    transfer.destination_mut().shutdown().await?;
    Ok::<_, utopia_migration::Error>(())
})?;

let csv = std::fs::read_to_string(dir.join("exports/people.csv"))?;
assert_eq!(csv, "$id,$permissions,$createdAt,$updatedAt,name,age\nada,,,,Ada,36\nalan,,,,Alan,41\n");
std::fs::remove_dir_all(&dir)?;

Count what a transfer moved

Every resource the transfer sees is cached with its status. status_counters() totals them per resource type (types with nothing are left out), and report() lists them, filtered by a status when you give one. Rows are cached as a count per status rather than one by one.

Rust
use std::sync::Arc;
use utopia_migration::destinations::json::Json as JsonDestination;
use utopia_migration::sources::json::Json;
use utopia_migration::{Destination, Transfer};
use utopia_storage::{Device, Local};

let dir = std::env::temp_dir().join(format!("utopia-migration-counters-{}", std::process::id()));
std::fs::create_dir_all(&dir)?;
std::fs::write(dir.join("in.json"), r#"[{"$id": "a", "n": 1}, {"$id": "b", "n": 2}, {"$id": "c", "n": 3}]"#)?;

tokio::runtime::Runtime::new()?.block_on(async {
    let device: Arc<dyn Device> = Arc::new(Local::new(dir.to_str().unwrap_or_default()));
    let source = Json::new("db:numbers", dir.join("in.json").to_string_lossy(), device.clone());
    let destination = JsonDestination::new(device, "db:numbers", "out", "numbers", Vec::new()).await?;

    let mut transfer = Transfer::new(Box::new(source), Box::new(destination));
    transfer.run(&["row"], &mut |_rows| Ok(()), None, None).await?;
    transfer.destination_mut().shutdown().await?;

    let counters = transfer.status_counters();
    assert_eq!(counters["row"]["success"], 3);
    // Rows are cached as counts per status, so their report lines carry
    // the status as the id and the count as the status.
    let report = transfer.report("");
    assert_eq!((report[0].resource.as_str(), report[0].status.as_str()), ("row", "3"));
    assert_eq!(report[0].id, php_std::Value::from("success"));
    Ok::<_, utopia_migration::Error>(())
})?;
std::fs::remove_dir_all(&dir)?;

Decide what happens to resources that already exist

When the destination already has a database, table, column or index, OnDuplicate decides: Fail creates it anyway (so the create fails), Skip keeps the destination's, and Overwrite updates it only when the source changed it more recently. The Appwrite destination takes the mode in its options; resolve_schema_action is the decision itself.

Rust
use utopia_migration::{OnDuplicate, SchemaAction};

let source = Some("2025-03-01 10:00:00");
let dest = Some("2025-01-01 10:00:00");

assert_eq!(OnDuplicate::Overwrite.resolve_schema_action(true, source, dest), SchemaAction::Overwrite);
assert_eq!(OnDuplicate::Overwrite.resolve_schema_action(true, dest, source), SchemaAction::Skip);
assert_eq!(OnDuplicate::Skip.resolve_schema_action(true, source, dest), SchemaAction::Skip);
assert_eq!(OnDuplicate::Fail.resolve_schema_action(true, source, dest), SchemaAction::Create);
// Nothing there yet: every mode creates it.
assert_eq!(OnDuplicate::Skip.resolve_schema_action(false, None, None), SchemaAction::Create);
assert_eq!(OnDuplicate::from_value("overwrite"), Some(OnDuplicate::Overwrite));

Reference#

Moves resources between services: a Source exports them (Appwrite, Supabase, NHost, Firebase, a CSV or JSON file), a Destination imports them (Appwrite, a CSV or JSON file, a local backup), and a Transfer runs one into the other, recording every resource in a shared Cache and reporting per-status counters.

Modules#

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

cache3 items
The transfer's record of every resource it moved.
destination3 items
Where resources go.
destinations::appwrite::apiinternal
Users, teams, storage, functions, messaging, sites and rules, written through the Appwrite API.
destinations::appwrite3 items
An Appwrite project as the destination: databases are written straight to the project's databases, the rest through the Appwrite API or the platform database.
destinations::appwrite::projectinternal
Project settings, integrations, auth settings and project variables, written to the platform and project databases.
destinations::appwrite::schemainternal
Databases, tables, columns, indexes and rows, written to the project's databases.
destinations::csv2 items
Rows exported to a CSV file.
destinations::json2 items
Rows exported to a JSON file.
destinations::local1 items
A backup in a local directory.
destinations0 items
The destinations resources are imported into.
destinations::on_duplicate2 items
What a destination does with a resource it already has.
error4 items
The errors a migration fails with.
exception2 items
A failure tied to one resource, and a warning about one.
http5 items
HTTP calls as `Target::call()` makes them on cURL, on `utopia-client`.
json_machine3 items
A streaming JSON pull parser: the items of a top-level array (or the key/value pairs of a top-level object), decoded one at a time from a file read in 16 KiB chunks, so a large export never sits in memory whole.
resource13 items
What a transfer moves: `Resource`, its common state and its kinds.
resource::status7 items
Undocumented.
resource::types42 items
Undocumented.
resources::auth10 items
Users, teams, memberships, password hashes and project auth settings.
resources::backups1 items
Backup policies.
resources::database10 items
Databases, tables, columns, indexes and rows.
resources::database::column23 items
Undocumented.
resources::database::columns11 items
Builders of each column class with its constructor's defaults.
resources::domains1 items
Domain rules.
resources::functions3 items
Functions, their variables and deployments.
resources::integrations2 items
Platforms and API keys.
resources::messaging4 items
Messaging providers, topics, subscribers and messages.
resources0 items
The resource kinds, by area, and their array forms.
resources::settings6 items
Project settings: variables, protocols, labels, services, SMTP and webhooks.
resources::sites3 items
Sites, their variables and deployments.
resources::storage2 items
Buckets and files.
resources::templates1 items
Email templates.
sdk8 items
Undocumented.
sdk::query6 items
Queries as the API takes them: JSON strings.
sdk::spec0 items
Undocumented.
sdk::spec_types6 items
The shapes of the generated SDK tables (`super::spec`).
source7 items
Where resources come from.
sources::appwrite::api_reader1 items
Reading databases through the Appwrite API.
sources::appwrite5 items
The Appwrite source: its readers, and the builders that turn what they read into resources.
sources::appwrite::reader6 items
How the Appwrite source reads databases: through the API, or straight from the project's database.
sources::appwrite::sourceinternal
An Appwrite project as the source.
sources::csv2 items
Rows of one table from a CSV file, typed by the table's columns.
sources::firebase2 items
A Firebase project as the source: users from Identity Toolkit, documents from Firestore, files from Cloud Storage.
sources::json1 items
Rows from a JSON file: an array of objects, streamed.
sources0 items
The sources resources are exported from.
sources::nhost4 items
An NHost project as the source: users, the public schema's tables and rows, and storage files, read from its PostgreSQL database; file contents through its storage API.
sources::pginternal
Undocumented.
sources::supabase1 items
A Supabase project as the source: NHost's database export, with Supabase's users, buckets and objects; object contents through its storage API.
sources::supabase_mimes0 items
Undocumented.
target7 items
What sources and destinations share: errors, warnings, the cache, and HTTP calls to the service they read or write.
transfer10 items
The transfer: runs a source into a destination, and reports on it.
transfer::group27 items
Undocumented.

API#

What utopia_migration exports at its root.