firebase::firestore::Firestore

#include <firestore.h>

Entry point for the FirebaseFirestore C++ SDK.

Summary

To use the SDK, callfirebase::firestore::Firestore::GetInstance() to obtain an instance ofFirestore, then useCollection() orDocument() to obtain references to child paths within the database. From there, you can set data viaCollectionReference::Add() andDocumentReference::Set(), or get data viaCollectionReference::Get() andDocumentReference::Get(), attach listeners, and more.

Note: Firestore classes are not meant to be subclassed except for use in test mocks. Subclassing is not supported in production code and new SDK releases may break code that does so.

Constructors and Destructors

Firestore(constFirestore & src)
Deleted copy constructor;Firestore must be created withFirestore::GetInstance().
~Firestore()
Destructor for theFirestore object.

Friend classes

csharp::ApiHeaders
friend class
csharp::TransactionManager
friend class

Public static functions

GetInstance(::firebase::App *app,InitResult *init_result_out)
Returns an instance ofFirestore corresponding to the givenApp with default database ID.
GetInstance(InitResult *init_result_out)
Returns an instance ofFirestore corresponding to the defaultApp with default database ID.
GetInstance(::firebase::App *app, const char *db_name,InitResult *init_result_out)
Returns an instance ofFirestore corresponding to the givenApp with the given database ID.
GetInstance(const char *db_name,InitResult *init_result_out)
Returns an instance ofFirestore corresponding to the defaultApp with the given database ID.
set_log_level(LogLevel log_level)
void
Sets the log verbosity of allFirestore instances.

Public functions

AddSnapshotsInSyncListener(std::function< void()> callback)
Attaches a listener for a snapshots-in-sync event.
ClearPersistence()
virtualFuture< void >
Clears the persistent storage.
Collection(const char *collection_path) const
Returns aCollectionReference instance that refers to the collection at the specified path within the database.
Collection(const std::string & collection_path) const
Returns aCollectionReference instance that refers to the collection at the specified path within the database.
CollectionGroup(const char *collection_id) const
virtualQuery
Returns aQuery instance that includes all documents in the database that are contained in a collection or subcollection with the given collection_id.
CollectionGroup(const std::string & collection_id) const
virtualQuery
Returns aQuery instance that includes all documents in the database that are contained in a collection or subcollection with the given collection_id.
DisableNetwork()
virtualFuture< void >
Disables network access for this instance.
Document(const char *document_path) const
Returns aDocumentReference instance that refers to the document at the specified path within the database.
Document(const std::string & document_path) const
Returns aDocumentReference instance that refers to the document at the specified path within the database.
EnableNetwork()
virtualFuture< void >
Re-enables network usage for this instance after a prior call toDisableNetwork().
LoadBundle(const std::string & bundle)
Loads aFirestore bundle into the local cache.
LoadBundle(const std::string & bundle, std::function< void(constLoadBundleTaskProgress &)> progress_callback)
Loads aFirestore bundle into the local cache, with the provided callback executed for progress updates.
NamedQuery(const std::string & query_name)
virtualFuture<Query >
Reads aFirestoreQuery from the local cache, identified by the given name.
RunTransaction(std::function<Error(Transaction &, std::string &)> update)
virtualFuture< void >
Executes the given update and then attempts to commit the changes applied within the transaction.
RunTransaction(TransactionOptions options, std::function<Error(Transaction &, std::string &)> update)
virtualFuture< void >
Executes the given update and then attempts to commit the changes applied within the transaction.
Terminate()
virtualFuture< void >
Terminates thisFirestore instance.
WaitForPendingWrites()
virtualFuture< void >
Waits until all currently pending writes for the active user have been acknowledged by the backend.
app() const
virtual constApp *
Returns thefirebase::App that thisFirestore was created with.
app()
virtualApp *
Returns thefirebase::App that thisFirestore was created with.
batch() const
virtualWriteBatch
Creates a write batch, used for performing multiple writes as a single atomic operation.
operator=(constFirestore & src)=delete
Deleted copy assignment operator;Firestore must be created withFirestore::GetInstance().
set_settings(Settings settings)
virtual void
Sets any custom settings used to configure thisFirestore object.
settings() const
virtualSettings
Returns the settings used by thisFirestore object.

Protected functions

Firestore()=default
Default constructor, to be used only for mockingFirestore.

Friend classes

csharp::ApiHeaders

friendclasscsharp::ApiHeaders

csharp::TransactionManager

friendclasscsharp::TransactionManager

Public static functions

GetInstance

Firestore*GetInstance(::firebase::App*app,InitResult*init_result_out)

Returns an instance ofFirestore corresponding to the givenApp with default database ID.

FirebaseFirestore usesfirebase::App to communicate with Firebase Authentication to authenticate users to theFirestore server backend.

If you callGetInstance() multiple times with the sameApp, you will get the same instance ofFirestore.

Details
Parameters
app
Your instance offirebase::App. FirebaseFirestore will use this to communicate with Firebase Authentication.
init_result_out
If provided, the initialization result will be written here. Will be set tofirebase::kInitResultSuccess if initialization succeeded, orfirebase::kInitResultFailedMissingDependency on Android if Google Play services is not available on the current device.
Returns
An instance ofFirestore corresponding to the givenApp with default database ID.

GetInstance

Firestore*GetInstance(InitResult*init_result_out)

Returns an instance ofFirestore corresponding to the defaultApp with default database ID.

FirebaseFirestore uses the defaultApp to communicate with Firebase Authentication to authenticate users to theFirestore server backend.

If you callGetInstance() multiple times, you will get the same instance.

Details
Parameters
init_result_out
If provided, the initialization result will be written here. Will be set tofirebase::kInitResultSuccess if initialization succeeded, orfirebase::kInitResultFailedMissingDependency on Android if Google Play services is not available on the current device.
Returns
An instance ofFirestore corresponding to the defaultApp with default database ID.

GetInstance

Firestore*GetInstance(::firebase::App*app,constchar*db_name,InitResult*init_result_out)

Returns an instance ofFirestore corresponding to the givenApp with the given database ID.

FirebaseFirestore usesfirebase::App to communicate with Firebase Authentication to authenticate users to theFirestore server backend.

If you callGetInstance() multiple times with the sameApp, you will get the same instance ofFirestore.

Details
Parameters
app
Your instance offirebase::App. FirebaseFirestore will use this to communicate with Firebase Authentication.
db_name
Name of the database. FirebaseFirestore will use this to communicate with Firebase Authentication.
init_result_out
If provided, the initialization result will be written here. Will be set tofirebase::kInitResultSuccess if initialization succeeded, orfirebase::kInitResultFailedMissingDependency on Android if Google Play services is not available on the current device.
Returns
An instance ofFirestore corresponding to the givenApp with the given database ID.

GetInstance

Firestore*GetInstance(constchar*db_name,InitResult*init_result_out)

Returns an instance ofFirestore corresponding to the defaultApp with the given database ID.

FirebaseFirestore usesfirebase::App to communicate with Firebase Authentication to authenticate users to theFirestore server backend.

If you callGetInstance() multiple times with the sameApp, you will get the same instance ofFirestore.

Details
Parameters
db_name
Name of the database. FirebaseFirestore will use this to communicate with Firebase Authentication.
init_result_out
If provided, the initialization result will be written here. Will be set tofirebase::kInitResultSuccess if initialization succeeded, orfirebase::kInitResultFailedMissingDependency on Android if Google Play services is not available on the current device.
Returns
An instance ofFirestore corresponding to the defaultApp with the given database ID.

set_log_level

voidset_log_level(LogLevellog_level)

Sets the log verbosity of allFirestore instances.

The default verbosity level iskLogLevelInfo.

Details
Parameters
log_level
The desired verbosity.

Public functions

AddSnapshotsInSyncListener

virtualListenerRegistrationAddSnapshotsInSyncListener(std::function<void()>callback)

Attaches a listener for a snapshots-in-sync event.

Server-generated updates and local changes can affect multiple snapshot listeners. The snapshots-in-sync event indicates that all listeners affected by a given change have fired.

NOTE: The snapshots-in-sync event only indicates that listeners are in sync with each other, but does not relate to whether those snapshots are in sync with the server. UseSnapshotMetadata in the individual listeners to determine if a snapshot is from the cache or the server.

Details
Parameters
callback
A callback to be called every time all snapshot listeners are in sync with each other.
Returns
AListenerRegistration object that can be used to remove the listener.

ClearPersistence

virtualFuture<void>ClearPersistence()

Clears the persistent storage.

This includes pending writes and cached documents.

Must be called while theFirestore instance is not started (after the app is shut down or when the app is first initialized). On startup, this method must be called before other methods (other thansettings() andset_settings()). If theFirestore instance is still running, the function will complete with an error code ofFailedPrecondition.

Note:ClearPersistence() is primarily intended to help write reliable tests that useFirestore. It uses the most efficient mechanism possible for dropping existing data but does not attempt to securely overwrite or otherwise make cached data unrecoverable. For applications that are sensitive to the disclosure of cache data in between user sessions we strongly recommend not to enable persistence in the first place.

Collection

virtualCollectionReferenceCollection(constchar*collection_path)const

Returns aCollectionReference instance that refers to the collection at the specified path within the database.

Details
Parameters
collection_path
A slash-separated path to a collection.
Returns
TheCollectionReference instance.

Collection

virtualCollectionReferenceCollection(conststd::string&collection_path)const

Returns aCollectionReference instance that refers to the collection at the specified path within the database.

Details
Parameters
collection_path
A slash-separated path to a collection.
Returns
TheCollectionReference instance.

CollectionGroup

virtualQueryCollectionGroup(constchar*collection_id)const

Returns aQuery instance that includes all documents in the database that are contained in a collection or subcollection with the given collection_id.

Details
Parameters
collection_id
Identifies the collections to query over. Every collection or subcollection with this ID as the last segment of its path will be included. Cannot contain a slash.
Returns
TheQuery instance.

CollectionGroup

virtualQueryCollectionGroup(conststd::string&collection_id)const

Returns aQuery instance that includes all documents in the database that are contained in a collection or subcollection with the given collection_id.

Details
Parameters
collection_id
Identifies the collections to query over. Every collection or subcollection with this ID as the last segment of its path will be included. Cannot contain a slash.
Returns
TheQuery instance.

DisableNetwork

virtualFuture<void>DisableNetwork()

Disables network access for this instance.

While the network is disabled, any snapshot listeners or Get() calls will return results from cache, and any write operations will be queued until network usage is re-enabled via a call toEnableNetwork().

If the network was already disabled, callingDisableNetwork() again is a no-op.

Document

virtualDocumentReferenceDocument(constchar*document_path)const

Returns aDocumentReference instance that refers to the document at the specified path within the database.

Details
Parameters
document_path
A slash-separated path to a document.
Returns
TheDocumentReference instance.

Document

virtualDocumentReferenceDocument(conststd::string&document_path)const

Returns aDocumentReference instance that refers to the document at the specified path within the database.

Details
Parameters
document_path
A slash-separated path to a document.
Returns
TheDocumentReference instance.

EnableNetwork

virtualFuture<void>EnableNetwork()

Re-enables network usage for this instance after a prior call toDisableNetwork().

If the network is currently enabled, callingEnableNetwork() is a no-op.

Firestore

Firestore(constFirestore&src)=delete

Deleted copy constructor;Firestore must be created withFirestore::GetInstance().

LoadBundle

virtualFuture<LoadBundleTaskProgress>LoadBundle(conststd::string&bundle)

Loads aFirestore bundle into the local cache.

Details
Parameters
bundle
A string containing the bundle to be loaded.
Returns
AFuture that is resolved when the loading is either completed or aborted due to an error.

LoadBundle

virtualFuture<LoadBundleTaskProgress>LoadBundle(conststd::string&bundle,std::function<void(constLoadBundleTaskProgress&)>progress_callback)

Loads aFirestore bundle into the local cache, with the provided callback executed for progress updates.

Details
Parameters
bundle
A string containing the bundle to be loaded.
progress_callback
A callback that is called with progress updates, and completion or error updates.
Returns
AFuture that is resolved when the loading is either completed or aborted due to an error.

NamedQuery

virtualFuture<Query>NamedQuery(conststd::string&query_name)

Reads aFirestoreQuery from the local cache, identified by the given name.

Named queries are packaged into bundles on the server side (along with the resulting documents) and loaded into local cache usingLoadBundle. Once in the local cache, you can use this method to extract a query by name.

If a query cannot be found, the returned future will complete with itserror() set to a non-zero error code.

Details
Parameters
query_name
The name of the query to read from saved bundles.

RunTransaction

virtualFuture<void>RunTransaction(std::function<Error(Transaction&,std::string&)>update)

Executes the given update and then attempts to commit the changes applied within the transaction.

If any document read within the transaction has changed, the update function will be retried. If it fails to commit after 5 attempts, the transaction will fail.

Details
Parameters
update
function or lambda to execute within the transaction context. The string reference parameter can be used to set the error message.
Returns
AFuture that will be resolved when the transaction finishes.

RunTransaction

virtualFuture<void>RunTransaction(TransactionOptionsoptions,std::function<Error(Transaction&,std::string&)>update)

Executes the given update and then attempts to commit the changes applied within the transaction.

If any document read within the transaction has changed, the update function will be retried. If it fails to commit after themax_attempts specified in the givenTransactionOptions, the transaction will fail.

Details
Parameters
options
The transaction options for controlling execution.
update
function or lambda to execute within the transaction context. The string reference parameter can be used to set the error message.
Returns
AFuture that will be resolved when the transaction finishes.

Terminate

virtualFuture<void>Terminate()

Terminates thisFirestore instance.

After callingTerminate(), only theClearPersistence() method may be used. Calling any other methods will result in an error.

To restart after termination, simply create a new instance ofFirestore withFirestore::GetInstance().

Terminate() does not cancel any pending writes and any tasks that are awaiting a response from the server will not be resolved. The next time you start this instance, it will resume attempting to send these writes to the server.

Note: under normal circumstances, callingTerminate() is not required. This method is useful only when you want to force this instance to release all of its resources or in combination withClearPersistence() to ensure that all local state is destroyed between test runs.

Details
Returns
AFuture that is resolved when the instance has been successfully terminated.

WaitForPendingWrites

virtualFuture<void>WaitForPendingWrites()

Waits until all currently pending writes for the active user have been acknowledged by the backend.

The returned future is resolved immediately without error if there are no outstanding writes. Otherwise, the future is resolved when all previously issued writes (including those written in a previous app session) have been acknowledged by the backend. The future does not wait for writes that were added after the method is called. If you wish to wait for additional writes, you have to callWaitForPendingWrites again.

Any outstandingWaitForPendingWrites futures are resolved with an error during user change.

app

virtualconstApp*app()const

Returns thefirebase::App that thisFirestore was created with.

Details
Returns
Thefirebase::App thisFirestore was created with.

app

virtualApp*app()

Returns thefirebase::App that thisFirestore was created with.

Details
Returns
Thefirebase::App thisFirestore was created with.

batch

virtualWriteBatchbatch()const

Creates a write batch, used for performing multiple writes as a single atomic operation.

Unlike transactions, write batches are persisted offline and therefore are preferable when you don't need to condition your writes on read data.

Details
Returns
The createdWriteBatch object.

operator=

Firestore&operator=(constFirestore&src)=delete

Deleted copy assignment operator;Firestore must be created withFirestore::GetInstance().

set_settings

virtualvoidset_settings(Settingssettings)

Sets any custom settings used to configure thisFirestore object.

settings

virtualSettingssettings()const

Returns the settings used by thisFirestore object.

~Firestore

virtual~Firestore()

Destructor for theFirestore object.

When deleted, this instance will be removed from the cache ofFirestore objects. If you callGetInstance() in the future with the sameApp, a newFirestore instance will be created.

Protected functions

Firestore

Firestore()=default

Default constructor, to be used only for mockingFirestore.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-01-23 UTC.