FIRFirestore.h 19 KB

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