Module database

Module database 

Source
Expand description

§Firebase Realtime Database

This module ports core pieces of the Realtime Database from the Firebase JS SDK to Rust.

It wires the Database component into the FirebaseApp, provides an in-memory backend for quick tests, and can fall back to the REST API for basic reads and writes against an emulator or hosted backend.

Live streaming connections and the richer reference/query surface from the JS SDK are still pending.

It includes error handling, configuration options, and integration with Firebase apps.

Porting status: 30% [### ] (details)

§Features

  • Component registration and shared get_database resolution
  • Reference CRUD with auto-ID push and path navigation (parent/root)
  • Priority-aware writes plus server value helpers (server_timestamp increment)
  • Snapshot traversal (child, has_child, size, to_json) and value/child listeners
  • Dual backends (in-memory + REST) with unit test coverage

§Quick Start Example

use firebase_rs_sdk::app::*;
use firebase_rs_sdk::database::{*, query as compose_query};
use serde_json::json;

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Point to the Realtime Database emulator or a database URL.
    let options = FirebaseOptions {
        project_id: Some("demo-project".into()),
        database_url: Some("http://127.0.0.1:9000/?ns=demo".into()),
        ..Default::default()
    };
    let app = initialize_app(options, Some(FirebaseAppSettings::default())).await?;
    let database = get_database(Some(app)).await?;

    let messages = database.reference("/messages")?;
    messages.set(json!({ "greeting": "hello" })).await?;
    let value = messages.get().await?;
    assert_eq!(value, json!({ "greeting": "hello" }));

    let recent = compose_query(
        messages,
        vec![order_by_child("timestamp"), limit_to_last(10)],
    )?;
    let latest = recent.get().await?;
    println!("latest snapshot: {latest}");

    Ok(())
}

§References to the Firebase JS SDK

§WASM Notes

  • The module compiles on wasm targets when the wasm-web feature is enabled. Web builds attempt to establish a realtime WebSocket and transparently degrade to a long-poll fetch loop when sockets cannot open, reusing the same listener bookkeeping as native builds. OnDisconnect operations require an active WebSocket; on the long-poll fallback they are queued locally and executed when go_offline() runs, which does not fully replicate server-side disconnect handling.
  • Calling get_database(None) is not supported on wasm because the default app lookup is asynchronous. Pass an explicit FirebaseApp instance instead.
  • go_online/go_offline are currently stubs on wasm (and native) but provide the async surface needed for upcoming realtime work.

Modules§

error

Structs§

ChildEvent
DataSnapshot
Represents a data snapshot returned to listeners, analogous to the JS DataSnapshot type.
Database
DatabaseQuery
Represents a composable database query, analogous to the JS QueryImpl (packages/database/src/api/Reference_impl.ts).
DatabaseReference
ListenerRegistration
RAII-style listener registration; dropping the handle detaches the underlying listener.
OnDisconnect
Async handle for scheduling writes that run when the client disconnects.
QueryConstraint
Represents a single constraint produced by helpers such as order_by_child() (packages/database/src/api/Reference_impl.ts).
TransactionResult
Result returned by run_transaction, mirroring the JS SDK contract.

Enums§

ChildEventType

Functions§

end_at
Mirrors the JS endAt() constraint (Reference_impl.ts).
end_at_with_key
Mirrors the JS endAt(value, name) overload (Reference_impl.ts).
end_before
Mirrors the JS endBefore() constraint (Reference_impl.ts).
end_before_with_key
Mirrors the JS endBefore(value, name) overload (Reference_impl.ts).
equal_to
Mirrors the JS equalTo() constraint (Reference_impl.ts).
equal_to_with_key
Mirrors the JS equalTo(value, name) overload (Reference_impl.ts).
get_database
increment
Port of increment() from packages/database/src/api/ServerValue.ts.
limit_to_first
Mirrors the JS limitToFirst() constraint (Reference_impl.ts).
limit_to_last
Mirrors the JS limitToLast() constraint (Reference_impl.ts).
on_child_added
Registers a child_added listener for the provided reference.
on_child_changed
Registers a child_changed listener for the provided reference.
on_child_removed
Registers a child_removed listener for the provided reference.
order_by_child
Produces a constraint that orders the results by the specified child path. Mirrors orderByChild() from the JS SDK.
order_by_key
Produces a constraint that orders nodes by key (orderByKey() in JS).
order_by_priority
Produces a constraint that orders nodes by priority (orderByPriority() in JS).
order_by_value
Produces a constraint that orders nodes by value (orderByValue() in JS).
push
Generates a child location with an auto-generated push ID.
push_with_value
Generates a child location with an auto-generated push ID and writes the provided value.
query
Creates a derived query by applying the provided constraints, following the semantics of query() in packages/database/src/api/Reference_impl.ts.
register_database_component
run_transaction
Runs a transaction at the provided reference, mirroring the JS SDK.
server_timestamp
Port of serverTimestamp() from packages/database/src/api/ServerValue.ts.
set_priority
Updates the priority for the current location, mirroring the modular setPriority() helper (packages/database/src/api/Reference_impl.ts).
set_with_priority
Writes a value together with a priority, mirroring the modular setWithPriority() helper (packages/database/src/api/Reference_impl.ts).
start_after
Mirrors the JS startAfter() constraint (Reference_impl.ts).
start_after_with_key
Mirrors the JS startAfter(value, name) overload (Reference_impl.ts).
start_at
Mirrors the JS startAt() constraint (Reference_impl.ts).
start_at_with_key
Mirrors the JS startAt(value, name) overload (Reference_impl.ts).

Type Aliases§

DatabaseResult