firestore-cli 0.3.0

fsq, a command line client for Google Firestore: a SQL REPL with tables, query plans and index statements, and a scripting mode with JSON output
//! Browsers, documents and paths for the browser's tests.

use super::editor::FilterHistory;
use super::external::EditorOutcome;
use super::state::{Browser, DocumentsQuery, Effect, Message, Movement};
use super::tree::{NodePath, Row};
use super::{BrowseTarget, FilterTail};
use crate::render::fixtures::{document, string, DOCUMENTS_PATH};
use firestore::gcloud_sdk::prost_types::Timestamp;
use firestore::timestamp_utils::from_timestamp;
use firestore::{FirestoreDocument, FirestoreWritePrecondition};

/// The update time the documents of a test were read with.
pub const READ_AT: Timestamp = Timestamp {
    seconds: 1_700_000_100,
    nanos: 0,
};

/// The update time of a write after [`READ_AT`].
pub const WRITTEN_AT: Timestamp = Timestamp {
    seconds: 1_700_000_200,
    nanos: 0,
};

/// `document` as stored with the update time `update_time`.
pub fn stored(mut document: FirestoreDocument, update_time: Timestamp) -> FirestoreDocument {
    document.update_time = Some(update_time);
    document
}

pub fn unchanged_since(update_time: Timestamp) -> FirestoreWritePrecondition {
    FirestoreWritePrecondition::UpdateTime(from_timestamp(update_time).expect("a valid instant"))
}

/// A browser of `collection` read with `filter`, before its first documents, and the query that
/// reads them.
pub fn opened(collection: &str, filter: &str) -> (Browser, DocumentsQuery) {
    let target = BrowseTarget {
        collection: collection.parse().expect("a collection path"),
        filter: FilterTail::from(filter),
    };
    match Browser::open(target, DOCUMENTS_PATH, FilterHistory::default()) {
        (browser, Effect::Query(query)) => (browser, query),
        (_, other) => panic!("no query: {other:?}"),
    }
}

/// A browser of `collection` read with `filter` that has read `documents`.
pub fn browser_of(collection: &str, filter: &str, documents: Vec<FirestoreDocument>) -> Browser {
    let (mut browser, query) = opened(collection, filter);
    browser.update(Message::DocumentsLoaded {
        request: query.request,
        outcome: Ok(documents),
    });
    browser
}

/// `count` books from `book-001` on, each with a title.
pub fn books(count: usize) -> Vec<FirestoreDocument> {
    (1..=count)
        .map(|number| document(&format!("book-{number:03}"), vec![("title", string("t"))]))
        .collect()
}

/// The path of the field `names` leads to, each name a field of the map before it.
pub fn field_path(names: &[&str]) -> NodePath {
    names
        .iter()
        .fold(NodePath::default(), |path, name| path.field(name))
}

pub fn point_at(browser: &mut Browser, path: &NodePath) {
    let level = browser.level();
    let document = level.selected_document().expect("a document");
    let row = level
        .tree()
        .rows(document)
        .iter()
        .position(|row| matches!(row, Row::Field { path: at, .. } if at == path))
        .unwrap_or_else(|| panic!("no row for {path:?}"));
    browser.update(Message::Move(Movement::First));
    browser.update(Message::Move(Movement::Down(row)));
}

pub fn save(browser: &mut Browser, text: &str) -> Option<Effect> {
    let saved = EditorOutcome::Saved(text.to_string());
    browser.update(Message::EditorClosed(Ok(saved)))
}

/// The Enterprise edition database `GCP_PROJECT` and `GCP_ENTERPRISE_DATABASE_ID` name, and a
/// collection of it no other run uses, named after `test`.
#[cfg(feature = "ci-live")]
pub async fn live_collection(test: &str) -> (firestore::FirestoreDb, String) {
    use firestore::{FirestoreDb, FirestoreDbOptions};
    use std::time::{SystemTime, UNIX_EPOCH};

    let options = FirestoreDbOptions::new(std::env::var("GCP_PROJECT").expect("GCP_PROJECT"))
        .with_database_id(
            std::env::var("GCP_ENTERPRISE_DATABASE_ID").expect("GCP_ENTERPRISE_DATABASE_ID"),
        );
    let db = FirestoreDb::with_options(options)
        .await
        .expect("a connection to the live database");
    let stamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("a time after the epoch")
        .as_nanos();
    (db, format!("fsq-live-{test}-{stamp}"))
}