FIRFirestore.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import <Foundation/Foundation.h>
  17. #import "FIRListenerRegistration.h"
  18. @class FIRApp;
  19. @class FIRCollectionReference;
  20. @class FIRDocumentReference;
  21. @class FIRFirestoreSettings;
  22. @class FIRLoadBundleTask;
  23. @class FIRLoadBundleTaskProgress;
  24. @class FIRQuery;
  25. @class FIRTransaction;
  26. @class FIRTransactionOptions;
  27. @class FIRWriteBatch;
  28. @class FIRPersistentCacheIndexManager;
  29. NS_ASSUME_NONNULL_BEGIN
  30. /**
  31. * `Firestore` represents a Firestore Database and is the entry point for all Firestore
  32. * operations.
  33. */
  34. NS_SWIFT_NAME(Firestore)
  35. @interface FIRFirestore : NSObject
  36. #pragma mark - Initializing
  37. /** :nodoc: */
  38. - (instancetype)init __attribute__((unavailable("Use a static constructor method.")));
  39. /**
  40. * Creates, caches, and returns the default `Firestore` using the default `FirebaseApp`. Each
  41. * subsequent invocation returns the same `Firestore` object.
  42. *
  43. * @return The default `Firestore` instance.
  44. */
  45. + (instancetype)firestore NS_SWIFT_NAME(firestore());
  46. /**
  47. * Creates, caches, and returns the default `Firestore` object for the specified _app_. Each
  48. * subsequent invocation returns the same `Firestore` object.
  49. *
  50. * @param app The `FirebaseApp` instance to use for authentication and as a source of the Google
  51. * Cloud Project ID for your Firestore Database. If you want the default instance, you should
  52. * explicitly set it to `FirebaseApp.app()`.
  53. *
  54. * @return The default `Firestore` instance.
  55. */
  56. + (instancetype)firestoreForApp:(FIRApp *)app NS_SWIFT_NAME(firestore(app:));
  57. /**
  58. * This method is in preview. API signature and functionality are subject to change.
  59. *
  60. * Creates, caches, and returns named `Firestore` object for the specified `FirebaseApp`. Each
  61. * subsequent invocation returns the same `Firestore` object.
  62. *
  63. * @param app The `FirebaseApp` instance to use for authentication and as a source of the Google
  64. * Cloud Project ID for your Firestore Database. If you want the default instance, you should
  65. * explicitly set it to `FirebaseApp.app()`.
  66. * @param database The database name.
  67. *
  68. * @return The named `Firestore` instance.
  69. */
  70. + (instancetype)firestoreForApp:(FIRApp *)app
  71. database:(NSString *)database NS_SWIFT_NAME(firestore(app:database:));
  72. /**
  73. * This method is in preview. API signature and functionality are subject to change.
  74. *
  75. * Creates, caches, and returns named `Firestore` object for the default _app_. Each subsequent
  76. * invocation returns the same `Firestore` object.
  77. *
  78. * @param database The database name.
  79. *
  80. * @return The named `Firestore` instance.
  81. */
  82. + (instancetype)firestoreForDatabase:(NSString *)database NS_SWIFT_NAME(firestore(database:));
  83. /**
  84. * Custom settings used to configure this `Firestore` object.
  85. */
  86. @property(nonatomic, copy) FIRFirestoreSettings *settings;
  87. /**
  88. * The Firebase App associated with this Firestore instance.
  89. */
  90. @property(strong, nonatomic, readonly) FIRApp *app;
  91. #pragma mark - Configure FieldIndexes
  92. /**
  93. * A PersistentCacheIndexManager which you can config persistent cache indexes used for
  94. * local query execution.
  95. */
  96. @property(nonatomic, readonly, nullable)
  97. FIRPersistentCacheIndexManager *persistentCacheIndexManager;
  98. /**
  99. * NOTE: This preview method will be deprecated in a future major release. Consider using
  100. * `PersistentCacheIndexManager.enableIndexAutoCreation()` to let the SDK decide whether to create
  101. * cache indexes for queries running locally.
  102. *
  103. * Configures indexing for local query execution. Any previous index configuration is overridden.
  104. *
  105. * The index entries themselves are created asynchronously. You can continue to use queries
  106. * that require indexing even if the indices are not yet available. Query execution will
  107. * automatically start using the index once the index entries have been written.
  108. *
  109. * The method accepts the JSON format exported by the Firebase CLI (`firebase
  110. * firestore:indexes`). If the JSON format is invalid, the completion block will be
  111. * invoked with an NSError.
  112. *
  113. * @param json The JSON format exported by the Firebase CLI.
  114. * @param completion A block to execute when setting is in a final state. The `error` parameter
  115. * will be set if the block is invoked due to an error.
  116. */
  117. - (void)setIndexConfigurationFromJSON:(NSString *)json
  118. completion:(nullable void (^)(NSError *_Nullable error))completion
  119. NS_SWIFT_NAME(setIndexConfiguration(_:completion:)) DEPRECATED_MSG_ATTRIBUTE(
  120. "Instead of creating cache indexes manually, consider using "
  121. "`PersistentCacheIndexManager.enableIndexAutoCreation()` to let the SDK decide whether to "
  122. "create cache indexes for queries running locally.");
  123. /**
  124. * NOTE: This preview method will be deprecated in a future major release. Consider using
  125. * `PersistentCacheIndexManager.enableIndexAutoCreation()` to let the SDK decide whether to create
  126. * cache indexes for queries running locally.
  127. *
  128. * Configures indexing for local query execution. Any previous index configuration is overridden.
  129. *
  130. * The index entries themselves are created asynchronously. You can continue to use queries
  131. * that require indexing even if the indices are not yet available. Query execution will
  132. * automatically start using the index once the index entries have been written.
  133. *
  134. * Indexes are only supported with LevelDB persistence. Invoke `set_persistence_enabled(true)`
  135. * before setting an index configuration. If LevelDB is not enabled, any index configuration
  136. * will be rejected.
  137. *
  138. * The method accepts the JSON format exported by the Firebase CLI (`firebase
  139. * firestore:indexes`). If the JSON format is invalid, this method ignores the changes.
  140. *
  141. * @param stream An input stream from which the configuration can be read.
  142. * @param completion A block to execute when setting is in a final state. The `error` parameter
  143. * will be set if the block is invoked due to an error.
  144. */
  145. - (void)setIndexConfigurationFromStream:(NSInputStream *)stream
  146. completion:(nullable void (^)(NSError *_Nullable error))completion
  147. NS_SWIFT_NAME(setIndexConfiguration(_:completion:)) DEPRECATED_MSG_ATTRIBUTE(
  148. "Instead of creating cache indexes manually, consider using "
  149. "`PersistentCacheIndexManager.enableIndexAutoCreation()` to let the SDK decide whether to "
  150. "create cache indexes for queries running locally.");
  151. #pragma mark - Collections and Documents
  152. /**
  153. * Gets a `CollectionReference` referring to the collection at the specified path within the
  154. * database.
  155. *
  156. * @param collectionPath The slash-separated path of the collection for which to get a
  157. * `CollectionReference`.
  158. *
  159. * @return The `CollectionReference` at the specified _collectionPath_.
  160. */
  161. - (FIRCollectionReference *)collectionWithPath:(NSString *)collectionPath
  162. NS_SWIFT_NAME(collection(_:));
  163. /**
  164. * Gets a `DocumentReference` referring to the document at the specified path within the
  165. * database.
  166. *
  167. * @param documentPath The slash-separated path of the document for which to get a
  168. * `DocumentReference`.
  169. *
  170. * @return The `DocumentReference` for the specified _documentPath_.
  171. */
  172. - (FIRDocumentReference *)documentWithPath:(NSString *)documentPath NS_SWIFT_NAME(document(_:));
  173. #pragma mark - Collection Group Queries
  174. /**
  175. * Creates and returns a new `Query` that includes all documents in the database that are contained
  176. * in a collection or subcollection with the given collectionID.
  177. *
  178. * @param collectionID Identifies the collections to query over. Every collection or subcollection
  179. * with this ID as the last segment of its path will be included. Cannot contain a slash.
  180. * @return The created `Query`.
  181. */
  182. - (FIRQuery *)collectionGroupWithID:(NSString *)collectionID NS_SWIFT_NAME(collectionGroup(_:));
  183. #pragma mark - Transactions and Write Batches
  184. /**
  185. * Executes the given updateBlock and then attempts to commit the changes applied within an atomic
  186. * transaction.
  187. *
  188. * The maximum number of writes allowed in a single transaction is 500, but note that each usage of
  189. * `FieldValue.serverTimestamp()`, `FieldValue.arrayUnion()`, `FieldValue.arrayRemove()`, or
  190. * `FieldValue.increment()` inside a transaction counts as an additional write.
  191. *
  192. * In the updateBlock, a set of reads and writes can be performed atomically using the
  193. * `Transaction` object passed to the block. After the updateBlock is run, Firestore will attempt
  194. * to apply the changes to the server. If any of the data read has been modified outside of this
  195. * transaction since being read, then the transaction will be retried by executing the updateBlock
  196. * again. If the transaction still fails after 5 retries, then the transaction will fail.
  197. *
  198. * Since the updateBlock may be executed multiple times, it should avoiding doing anything that
  199. * would cause side effects.
  200. *
  201. * Any value maybe be returned from the updateBlock. If the transaction is successfully committed,
  202. * then the completion block will be passed that value. The updateBlock also has an `NSErrorPointer`
  203. * out parameter. If this is set, then the transaction will not attempt to commit, and the given
  204. * error will be passed to the completion block.
  205. *
  206. * The `Transaction` object passed to the updateBlock contains methods for accessing documents
  207. * and collections. Unlike other firestore access, data accessed with the transaction will not
  208. * reflect local changes that have not been committed. For this reason, it is required that all
  209. * reads are performed before any writes. Transactions must be performed while online. Otherwise,
  210. * reads will fail, the final commit will fail, and the completion block will return an error.
  211. *
  212. * @param updateBlock The block to execute within the transaction context.
  213. * @param completion The block to call with the result or error of the transaction. This
  214. * block will run even if the client is offline, unless the process is killed.
  215. */
  216. - (void)runTransactionWithBlock:(id _Nullable (^)(FIRTransaction *, NSError **))updateBlock
  217. completion:(void (^)(id _Nullable result, NSError *_Nullable error))completion
  218. __attribute__((swift_async(none))); // Disable async import due to #9426.
  219. /**
  220. * Executes the given updateBlock and then attempts to commit the changes applied within an atomic
  221. * transaction.
  222. *
  223. * The maximum number of writes allowed in a single transaction is 500, but note that each usage of
  224. * `FieldValue.serverTimestamp()`, `FieldValue.arrayUnion()`, `FieldValue.arrayRemove()`, or
  225. * `FieldValue.increment()` inside a transaction counts as an additional write.
  226. *
  227. * In the updateBlock, a set of reads and writes can be performed atomically using the
  228. * `Transaction` object passed to the block. After the updateBlock is run, Firestore will attempt
  229. * to apply the changes to the server. If any of the data read has been modified outside of this
  230. * transaction since being read, then the transaction will be retried by executing the updateBlock
  231. * again. If the transaction still fails after the attempting the number of times specified by the
  232. * `max_attempts` property of the given `TransactionOptions` object, then the transaction will fail.
  233. * If the given `TransactionOptions` is `nil`, then the default `max_attempts` of 5 will be used.
  234. *
  235. * Since the updateBlock may be executed multiple times, it should avoiding doing anything that
  236. * would cause side effects.
  237. *
  238. * Any value maybe be returned from the updateBlock. If the transaction is successfully committed,
  239. * then the completion block will be passed that value. The updateBlock also has an `NSErrorPointer`
  240. * out parameter. If this is set, then the transaction will not attempt to commit, and the given
  241. * error will be passed to the completion block.
  242. *
  243. * The `Transaction` object passed to the updateBlock contains methods for accessing documents
  244. * and collections. Unlike other firestore access, data accessed with the transaction will not
  245. * reflect local changes that have not been committed. For this reason, it is required that all
  246. * reads are performed before any writes. Transactions must be performed while online. Otherwise,
  247. * reads will fail, the final commit will fail, and the completion block will return an error.
  248. *
  249. * @param options The transaction options for controlling execution, or `nil` to use the default
  250. * transaction options.
  251. * @param updateBlock The block to execute within the transaction context.
  252. * @param completion The block to call with the result or error of the transaction. This
  253. * block will run even if the client is offline, unless the process is killed.
  254. */
  255. - (void)runTransactionWithOptions:(FIRTransactionOptions *_Nullable)options
  256. block:(id _Nullable (^)(FIRTransaction *, NSError **))updateBlock
  257. completion:
  258. (void (^)(id _Nullable result, NSError *_Nullable error))completion
  259. __attribute__((swift_async(none))); // Disable async import due to #9426.
  260. /**
  261. * Creates a write batch, used for performing multiple writes as a single
  262. * atomic operation.
  263. *
  264. * The maximum number of writes allowed in a single batch is 500, but note that each usage of
  265. * `FieldValue.serverTimestamp()`, `FieldValue.arrayUnion()`, `FieldValue.arrayRemove()`, or
  266. * `FieldValue.increment()` inside a batch counts as an additional write.
  267. * Unlike transactions, write batches are persisted offline and therefore are preferable when you
  268. * don't need to condition your writes on read data.
  269. */
  270. - (FIRWriteBatch *)batch;
  271. #pragma mark - Logging
  272. /** Enables or disables logging from the Firestore client. */
  273. + (void)enableLogging:(BOOL)logging;
  274. #pragma mark - Network
  275. /**
  276. * Configures Firestore to connect to an emulated host instead of the default remote backend. After
  277. * Firestore has been used (i.e. a document reference has been instantiated), this value cannot be
  278. * changed.
  279. */
  280. - (void)useEmulatorWithHost:(NSString *)host port:(NSInteger)port;
  281. /**
  282. * Re-enables usage of the network by this Firestore instance after a prior call to
  283. * `disableNetwork(completion:)`. Completion block, if provided, will be called once network uasge
  284. * has been enabled.
  285. */
  286. - (void)enableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable error))completion;
  287. /**
  288. * Disables usage of the network by this Firestore instance. It can be re-enabled by via
  289. * `enableNetwork`. While the network is disabled, any snapshot listeners or get calls will return
  290. * results from cache and any write operations will be queued until the network is restored. The
  291. * completion block, if provided, will be called once network usage has been disabled.
  292. */
  293. - (void)disableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable error))completion;
  294. /**
  295. * Clears the persistent storage. This includes pending writes and cached documents.
  296. *
  297. * Must be called while the firestore instance is not started (after the app is shutdown or when
  298. * the app is first initialized). On startup, this method must be called before other methods
  299. * (other than `Firestore.settings`). If the firestore instance is still running, the function
  300. * will complete with an error code of `FailedPrecondition`.
  301. *
  302. * Note: `clearPersistence(completion:)` is primarily intended to help write reliable tests that
  303. * use Firestore. It uses the most efficient mechanism possible for dropping existing data but
  304. * does not attempt to securely overwrite or otherwise make cached data unrecoverable. For
  305. * applications that are sensitive to the disclosure of cache data in between user sessions we
  306. * strongly recommend not to enable persistence in the first place.
  307. */
  308. - (void)clearPersistenceWithCompletion:(nullable void (^)(NSError *_Nullable error))completion;
  309. /**
  310. * Waits until all currently pending writes for the active user have been acknowledged by the
  311. * backend.
  312. *
  313. * The completion block is called immediately without error if there are no outstanding writes.
  314. * Otherwise, the completion block is called when all previously issued writes (including those
  315. * written in a previous app session) have been acknowledged by the backend. The completion
  316. * block does not wait for writes that were added after the method is called. If you
  317. * wish to wait for additional writes, you have to call `waitForPendingWrites` again.
  318. *
  319. * Any outstanding `waitForPendingWrites(completion:)` completion blocks are called with an error
  320. * during user change.
  321. */
  322. - (void)waitForPendingWritesWithCompletion:(void (^)(NSError *_Nullable error))completion;
  323. /**
  324. * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync event indicates that all
  325. * listeners affected by a given change have fired, even if a single server-generated change affects
  326. * multiple listeners.
  327. *
  328. * NOTE: The snapshots-in-sync event only indicates that listeners are in sync with each other, but
  329. * does not relate to whether those snapshots are in sync with the server. Use SnapshotMetadata in
  330. * the individual listeners to determine if a snapshot is from the cache or the server.
  331. *
  332. * @param listener A callback to be called every time all snapshot listeners are in sync with each
  333. * other.
  334. * @return A `ListenerRegistration` object that can be used to remove the listener.
  335. */
  336. - (id<FIRListenerRegistration>)addSnapshotsInSyncListener:(void (^)(void))listener
  337. NS_SWIFT_NAME(addSnapshotsInSyncListener(_:));
  338. #pragma mark - Terminating
  339. /**
  340. * Terminates this `Firestore` instance.
  341. *
  342. * After calling `terminate` only the `clearPersistence` method may be used. Any other method will
  343. * throw an error.
  344. *
  345. * To restart after termination, simply create a new instance of `Firestore` with the `firestore`
  346. * method.
  347. *
  348. * Termination does not cancel any pending writes and any tasks that are awaiting a response from
  349. * the server will not be resolved. The next time you start this instance, it will resume attempting
  350. * to send these writes to the server.
  351. *
  352. * Note: Under normal circumstances, calling this method is not required. This method is useful only
  353. * when you want to force this instance to release all of its resources or in combination with
  354. * `clearPersistence` to ensure that all local state is destroyed between test runs.
  355. *
  356. * @param completion A block to execute once everything has been terminated.
  357. */
  358. - (void)terminateWithCompletion:(nullable void (^)(NSError *_Nullable error))completion
  359. NS_SWIFT_NAME(terminate(completion:));
  360. #pragma mark - Bundles
  361. /**
  362. * Loads a Firestore bundle into the local cache.
  363. *
  364. * @param bundleData Data from the bundle to be loaded.
  365. * @return A `LoadBundleTask` which allows registered observers
  366. * to receive progress updates and completion or error events.
  367. */
  368. - (FIRLoadBundleTask *)loadBundle:(NSData *)bundleData NS_SWIFT_NAME(loadBundle(_:));
  369. /**
  370. * Loads a Firestore bundle into the local cache.
  371. *
  372. * @param bundleData Data from the bundle to be loaded.
  373. * @param completion A block to execute when loading is in a final state. The `error` parameter
  374. * will be set if the block is invoked due to an error. If observers are registered to the
  375. * `LoadBundleTask`, this block will be called after all observers are notified.
  376. * @return A `LoadBundleTask` which allows registered observers to receive progress updates and
  377. * completion or error events.
  378. */
  379. - (FIRLoadBundleTask *)loadBundle:(NSData *)bundleData
  380. completion:(nullable void (^)(FIRLoadBundleTaskProgress *_Nullable progress,
  381. NSError *_Nullable error))completion
  382. NS_SWIFT_NAME(loadBundle(_:completion:));
  383. /**
  384. * Loads a Firestore bundle into the local cache.
  385. *
  386. * @param bundleStream An input stream from which the bundle can be read.
  387. * @return A `LoadBundleTask` which allows registered observers to receive progress updates and
  388. * completion or error events.
  389. */
  390. - (FIRLoadBundleTask *)loadBundleStream:(NSInputStream *)bundleStream NS_SWIFT_NAME(loadBundle(_:));
  391. /**
  392. * Loads a Firestore bundle into the local cache.
  393. *
  394. * @param bundleStream An input stream from which the bundle can be read.
  395. * @param completion A block to execute when the loading is in a final state. The `error` parameter
  396. * of the block will be set if it is due to an error. If observers are registered to the returning
  397. * `LoadBundleTask`, this block will be called after all observers are notified.
  398. * @return A `LoadBundleTask` which allow registering observers to receive progress updates, and
  399. * completion or error events.
  400. */
  401. - (FIRLoadBundleTask *)loadBundleStream:(NSInputStream *)bundleStream
  402. completion:
  403. (nullable void (^)(FIRLoadBundleTaskProgress *_Nullable progress,
  404. NSError *_Nullable error))completion
  405. NS_SWIFT_NAME(loadBundle(_:completion:));
  406. /**
  407. * Reads a `Query` from the local cache, identified by the given name.
  408. *
  409. * Named queries are packaged into bundles on the server side (along with the resulting documents)
  410. * and loaded into local cache using `loadBundle`. Once in the local cache, you can use this method
  411. * to extract a query by name.
  412. *
  413. * @param completion A block to execute with the query read from the local cache. If no query can be
  414. * found, its parameter will be `nil`.
  415. */
  416. - (void)getQueryNamed:(NSString *)name
  417. completion:(void (^)(FIRQuery *_Nullable query))completion
  418. NS_SWIFT_NAME(getQuery(named:completion:));
  419. @end
  420. NS_ASSUME_NONNULL_END