Skip to main content

FirestoreDb

Struct FirestoreDb 

Source
pub struct FirestoreDb { /* private fields */ }
Expand description

Re-exports all public items from the db module.

The db module contains the core FirestoreDb client and functionalities for interacting with the Firestore database, such as CRUD operations, queries, and transactions. The main entry point for interacting with a Google Firestore database.

FirestoreDb provides methods for database operations such as creating, reading, updating, and deleting documents, as well as querying collections and running transactions. It manages the connection and authentication with the Firestore service.

Instances of FirestoreDb are cloneable and internally use Arc for shared state, making them cheap to clone and safe to share across threads.

Implementations§

Source§

impl FirestoreDb

Source§

impl FirestoreDb

Source

pub async fn create_listener<S>( &self, storage: S, ) -> FirestoreResult<FirestoreListener<FirestoreDb, S>>
where S: FirestoreResumeStateStorage + Clone + Send + Sync + 'static,

Source

pub async fn create_listener_with_params<S>( &self, storage: S, params: FirestoreListenerParams, ) -> FirestoreResult<FirestoreListener<FirestoreDb, S>>
where S: FirestoreResumeStateStorage + Clone + Send + Sync + 'static,

Source§

impl FirestoreDb

Source

pub async fn begin_transaction( &self, ) -> FirestoreResult<FirestoreTransaction<'_>>

Source

pub async fn begin_transaction_with_options( &self, options: FirestoreTransactionOptions, ) -> FirestoreResult<FirestoreTransaction<'_>>

Source

pub async fn run_transaction<T, FN, E>(&self, func: FN) -> FirestoreResult<T>
where for<'b> FN: Fn(FirestoreDb, &'b mut FirestoreTransaction<'_>) -> BoxFuture<'b, Result<T, BackoffError<E>>>, E: Error + Send + Sync + 'static,

Source

pub async fn run_transaction_with_options<T, FN, E>( &self, func: FN, options: FirestoreTransactionOptions, ) -> FirestoreResult<T>
where for<'b> FN: Fn(FirestoreDb, &'b mut FirestoreTransaction<'_>) -> BoxFuture<'b, Result<T, BackoffError<E>>>, E: Error + Send + Sync + 'static,

Source§

impl FirestoreDb

Source§

impl FirestoreDb

Source§

impl FirestoreDb

Source

pub async fn new<S>(google_project_id: S) -> FirestoreResult<Self>
where S: AsRef<str>,

Creates a new FirestoreDb instance with the specified Google Project ID.

This is a convenience method that uses default FirestoreDbOptions. For more control over configuration, use FirestoreDb::with_options.

§Arguments
  • google_project_id: The Google Cloud Project ID that owns the Firestore database.
§Example
use firestore::*; // Imports FirestoreDb, FirestoreResult, etc.

let db = FirestoreDb::new("my-gcp-project-id").await?;
// Use db for Firestore operations
Source

pub async fn with_options(options: FirestoreDbOptions) -> FirestoreResult<Self>

Creates a new FirestoreDb instance with the specified options.

This method allows for detailed configuration of the Firestore client, such as setting a custom database ID or API URL. It uses default token scopes and token source.

§Arguments
Source

pub async fn for_default_project_id() -> FirestoreResult<Self>

Creates a new FirestoreDb instance attempting to infer the Google Project ID from the environment (e.g., Application Default Credentials).

This is useful in environments where the project ID is implicitly available.

§Errors

Returns an FirestoreError::InvalidParametersError if the project ID cannot be inferred.

Source

pub async fn with_options_service_account_key_file( options: FirestoreDbOptions, service_account_key_path: PathBuf, ) -> FirestoreResult<Self>

Creates a new FirestoreDb instance with specified options and a service account key file for authentication.

§Arguments
  • options: The FirestoreDbOptions to configure the client.
  • service_account_key_path: Path to the JSON service account key file.
Source

pub async fn with_options_token_source( options: FirestoreDbOptions, token_scopes: Vec<String>, token_source_type: TokenSourceType, ) -> FirestoreResult<Self>

Creates a new FirestoreDb instance with full control over options, token scopes, and token source type.

This is the most flexible constructor, allowing customization of authentication and authorization aspects.

§Arguments
  • options: The FirestoreDbOptions to configure the client.
  • token_scopes: A list of OAuth2 scopes required for Firestore access.
  • token_source_type: The TokenSourceType specifying how to obtain authentication tokens (e.g., default, file, metadata server).
Source

pub fn deserialize_doc_to<T>(doc: &Document) -> FirestoreResult<T>
where for<'de> T: Deserialize<'de>,

Deserializes a Firestore Document into a Rust type T.

This function uses the custom Serde deserializer provided by this crate to map Firestore’s native data types to Rust structs.

§Arguments
  • doc: A reference to the Firestore Document to deserialize.
§Type Parameters
  • T: The target Rust type that implements serde::Deserialize.
§Errors

Returns a FirestoreError::DeserializeError if deserialization fails.

Source

pub fn serialize_to_doc<S, T>( document_path: S, obj: &T, ) -> FirestoreResult<Document>
where S: AsRef<str>, T: Serialize,

Serializes a Rust type T into a Firestore Document.

This function uses the custom Serde serializer to convert Rust structs into Firestore’s native data format.

§Arguments
  • document_path: The full path to the document (e.g., “projects/my-project/databases/(default)/documents/my-collection/my-doc”). This is used to set the name field of the resulting Firestore document.
  • obj: A reference to the Rust object to serialize.
§Type Parameters
  • S: A type that can be converted into a string for the document path.
  • T: The source Rust type that implements serde::Serialize.
§Errors

Returns a FirestoreError::SerializeError if serialization fails.

Source

pub fn serialize_map_to_doc<S, I, IS>( document_path: S, fields: I, ) -> FirestoreResult<FirestoreDocument>
where S: AsRef<str>, I: IntoIterator<Item = (IS, FirestoreValue)>, IS: AsRef<str>,

Serializes a map of field names to FirestoreValues into a Firestore Document.

This is useful for constructing documents dynamically or when working with partially structured data.

§Arguments
  • document_path: The full path to the document.
  • fields: An iterator yielding pairs of field names (as strings) and their corresponding FirestoreValues.
§Type Parameters
  • S: A type that can be converted into a string for the document path.
  • I: An iterator type for the fields.
  • IS: A type that can be converted into a string for field names.
§Errors

Returns a FirestoreError::SerializeError if serialization fails.

Source

pub async fn ping(&self) -> FirestoreResult<()>

Performs a simple “ping” to the Firestore database to check connectivity.

This method attempts to read a non-existent document. A successful outcome (even if the document is not found) indicates that the database is reachable and the client is authenticated.

§Errors

May return network or authentication errors if the database is unreachable.

Source

pub fn get_database_path(&self) -> &String

Returns the full database path string (e.g., “projects/my-project/databases/(default)”).

Source

pub fn get_documents_path(&self) -> &String

Returns the base path for documents within this database (e.g., “projects/my-project/databases/(default)/documents”).

Source

pub fn parent_path<S>( &self, collection_name: &str, document_id: S, ) -> FirestoreResult<ParentPathBuilder>
where S: AsRef<str>,

Constructs a ParentPathBuilder for creating paths to sub-collections under a specified document.

§Arguments
  • collection_name: The name of the collection containing the parent document.
  • document_id: The ID of the parent document.
§Errors

Returns FirestoreError::InvalidParametersError if the document_id is invalid.

Source

pub fn get_options(&self) -> &FirestoreDbOptions

Returns a reference to the FirestoreDbOptions used to configure this client.

Source

pub fn get_session_params(&self) -> &FirestoreDbSessionParams

Returns a reference to the current FirestoreDbSessionParams for this client instance. Session parameters can control aspects like consistency and caching for operations performed with this specific FirestoreDb instance.

Source

pub fn client(&self) -> &GoogleApi<FirestoreClient<GoogleAuthMiddleware>>

Returns a reference to the underlying gcloud-sdk gRPC client.

Unsupported escape hatch. The Fluent API is the supported way to use this crate; this method exists only for the rare case where it does not yet cover something you need.

It exposes types from gcloud-sdk, whose version is not part of this crate’s semver contract: this signature and the types behind it may change in any release, including a patch release. You also need to depend on gcloud-sdk yourself, at a matching version, since this crate does not re-export it.

Source

pub fn clone_with_session_params( &self, session_params: FirestoreDbSessionParams, ) -> Self

Clones the FirestoreDb instance, replacing its session parameters.

This is useful for creating a new client instance that shares the same underlying connection and configuration but has different session-level settings (e.g., for a specific transaction or consistency requirement).

§Arguments
Source

pub fn with_session_params( self, session_params: FirestoreDbSessionParams, ) -> Self

Consumes the FirestoreDb instance and returns a new one with replaced session parameters.

Similar to clone_with_session_params but takes ownership of self.

§Arguments
Source

pub fn clone_with_consistency_selector( &self, consistency_selector: FirestoreConsistencySelector, ) -> Self

Clones the FirestoreDb instance with a specific consistency selector.

This creates a new FirestoreDb instance configured to use the provided FirestoreConsistencySelector for subsequent operations.

§Arguments
  • consistency_selector: The consistency mode to apply (e.g., read at a specific time).
Source

pub fn clone_with_request_options( &self, request_options: FirestoreRequestOptions, ) -> Self

Clones the FirestoreDb instance with default request options.

Every request issued through the returned instance carries these options, unless an operation overrides them explicitly.

§Arguments
Source

pub fn clone_with_request_tags<I>(&self, request_tags: I) -> Self

Clones the FirestoreDb instance with default request tags.

A convenience shortcut for clone_with_request_options. This is also the way to attach request tags to the CRUD operations (get/create/update/delete), which have no per operation options.

§Arguments
  • request_tags: An iterator of tags to attach to every request.
§Examples
use firestore::*;
let db = FirestoreDb::new("my-gcp-project-id").await?;
let tagged_db = db.clone_with_request_tags(["nightly-report"]);
Source

pub fn with_request_options( self, request_options: FirestoreRequestOptions, ) -> Self

Consumes the FirestoreDb instance and returns a new one with default request options.

§Arguments
Source

pub fn with_request_tags<I>(self, request_tags: I) -> Self

Consumes the FirestoreDb instance and returns a new one with default request tags.

A convenience shortcut for with_request_options.

§Arguments
  • request_tags: An iterator of tags to attach to every request.
Source

pub fn with_cache(&self, cache_mode: FirestoreDbSessionCacheMode) -> Self

Clones the FirestoreDb instance with a specific cache mode.

This method is only available if the caching feature is enabled.

§Arguments
Source

pub fn read_through_cache<B, LS>(&self, cache: &FirestoreCache<B, LS>) -> Self
where B: FirestoreCacheBackend + Send + Sync + 'static, LS: FirestoreResumeStateStorage + Clone + Send + Sync + 'static,

Clones this FirestoreDb so that reads go through the given cache, falling back to Firestore.

This is the mode to reach for by default: anything the cache can answer is served locally, and anything it cannot is fetched from Firestore as usual.

Reads by ID are served from the cache for any cached collection, and populate it on a miss. list and query are served from the cache only for collections configured to be preloaded - for others they transparently go to Firestore, because a lazily filled collection could only answer them with partial results.

Results are eventually consistent; see FirestoreCache for what that means in practice.

This method is only available if the caching feature is enabled.

§Arguments
Source

pub fn read_cached_only<B, LS>(&self, cache: &FirestoreCache<B, LS>) -> Self
where B: FirestoreCacheBackend + Send + Sync + 'static, LS: FirestoreResumeStateStorage + Clone + Send + Sync + 'static,

Clones this FirestoreDb so that reads come exclusively from the given cache, never from Firestore.

Reads by ID return None when the document is not cached. Requests that the cache cannot answer completely - a list or query on a collection that is not preloaded, on a collection the cache does not know about, or a collection group query - return a FirestoreError::CacheError rather than a partial result that would look complete.

Use read_through_cache if you would rather fall back to Firestore, or FirestoreCacheIncompleteCollectionPolicy::PartialResults if partial results are genuinely acceptable for your use case.

This method is only available if the caching feature is enabled.

§Arguments
Source§

impl FirestoreDb

Source

pub fn fluent(&self) -> FirestoreExprBuilder<'_, FirestoreDb>

Provides access to the fluent API for building Firestore operations.

This is the main entry point for using the chainable builder pattern.

Trait Implementations§

Source§

impl Clone for FirestoreDb

Source§

fn clone(&self) -> FirestoreDb

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for FirestoreDb

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more