BasicCompileTests.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. // These aren't tests in the usual sense--they just verify that the Objective-C to Swift translation
  17. // results in the right names.
  18. import Foundation
  19. import XCTest
  20. import FirebaseCore
  21. import FirebaseFirestore
  22. class BasicCompileTests: XCTestCase {
  23. func testCompiled() {
  24. XCTAssertTrue(true)
  25. }
  26. }
  27. func main() {
  28. let db = initializeDb()
  29. let (collectionRef, documentRef) = makeRefs(database: db)
  30. let query = makeQuery(collection: collectionRef)
  31. writeDocument(at: documentRef)
  32. writeDocuments(at: documentRef, database: db)
  33. addDocument(to: collectionRef)
  34. readDocument(at: documentRef)
  35. readDocumentWithSource(at: documentRef)
  36. readDocuments(matching: query)
  37. readDocumentsWithSource(matching: query)
  38. listenToDocument(at: documentRef)
  39. listenToDocuments(matching: query)
  40. enableDisableNetwork(database: db)
  41. clearPersistence(database: db)
  42. types()
  43. waitForPendingWrites(database: db)
  44. addSnapshotsInSyncListener(database: db)
  45. terminateDb(database: db)
  46. }
  47. func initializeDb() -> Firestore {
  48. // Initialize with ProjectID.
  49. let firestore = Firestore.firestore()
  50. // Apply settings
  51. let settings = FirestoreSettings()
  52. settings.host = "localhost"
  53. settings.isPersistenceEnabled = true
  54. settings.cacheSizeBytes = FirestoreCacheSizeUnlimited
  55. firestore.settings = settings
  56. return firestore
  57. }
  58. func makeRefs(database db: Firestore) -> (CollectionReference, DocumentReference) {
  59. var collectionRef = db.collection("my-collection")
  60. var documentRef: DocumentReference
  61. documentRef = collectionRef.document("my-doc")
  62. // or
  63. documentRef = db.document("my-collection/my-doc")
  64. // deeper collection (my-collection/my-doc/some/deep/collection)
  65. collectionRef = documentRef.collection("some/deep/collection")
  66. // parent doc (my-collection/my-doc/some/deep)
  67. documentRef = collectionRef.parent!
  68. // print paths.
  69. print("Collection: \(collectionRef.path), document: \(documentRef.path)")
  70. return (collectionRef, documentRef)
  71. }
  72. func makeQuery(collection collectionRef: CollectionReference) -> Query {
  73. var query = collectionRef.whereField(FieldPath(["name"]), isEqualTo: "Fred")
  74. .whereField("age", isGreaterThanOrEqualTo: 24)
  75. .whereField("tags", arrayContains: "active")
  76. .whereField(FieldPath(["tags"]), arrayContains: "active")
  77. .whereField("tags", arrayContainsAny: ["active", "squat"])
  78. .whereField(FieldPath(["tags"]), arrayContainsAny: ["active", "squat"])
  79. .whereField("tags", in: ["active", "squat"])
  80. .whereField(FieldPath(["tags"]), in: ["active", "squat"])
  81. .whereField("tags", notIn: ["active", "squat"])
  82. .whereField(FieldPath(["tags"]), notIn: ["active", "squat"])
  83. .whereField(FieldPath.documentID(), isEqualTo: "fred")
  84. .whereField(FieldPath.documentID(), isNotEqualTo: "fred")
  85. .whereField(FieldPath(["name"]), isEqualTo: "fred")
  86. .order(by: FieldPath(["age"]))
  87. .order(by: "name", descending: true)
  88. .limit(to: 10)
  89. .limit(toLast: 10)
  90. query = collectionRef.firestore.collectionGroup("collection")
  91. return query
  92. }
  93. func writeDocument(at docRef: DocumentReference) {
  94. let setData = [
  95. "foo": 42,
  96. "bar": [
  97. "baz": "Hello world!",
  98. ],
  99. ] as [String: Any]
  100. let updateData = [
  101. "bar.baz": 42,
  102. FieldPath(["foobar"]): 42,
  103. "server_timestamp": FieldValue.serverTimestamp(),
  104. "array_union": FieldValue.arrayUnion(["a", "b"]),
  105. "array_remove": FieldValue.arrayRemove(["a", "b"]),
  106. "field_delete": FieldValue.delete(),
  107. ] as [AnyHashable: Any]
  108. docRef.setData(setData)
  109. // Completion callback (via trailing closure syntax).
  110. docRef.setData(setData) { error in
  111. if let error = error {
  112. print("Uh oh! \(error)")
  113. return
  114. }
  115. print("Set complete!")
  116. }
  117. // merge
  118. docRef.setData(setData, merge: true)
  119. docRef.setData(setData, merge: true) { error in
  120. if let error = error {
  121. print("Uh oh! \(error)")
  122. return
  123. }
  124. print("Set complete!")
  125. }
  126. docRef.updateData(updateData)
  127. docRef.delete()
  128. docRef.delete { error in
  129. if let error = error {
  130. print("Uh oh! \(error)")
  131. return
  132. }
  133. print("Set complete!")
  134. }
  135. }
  136. func enableDisableNetwork(database db: Firestore) {
  137. // closure syntax
  138. db.disableNetwork(completion: { error in
  139. if let e = error {
  140. print("Uh oh! \(e)")
  141. return
  142. }
  143. })
  144. // trailing block syntax
  145. db.enableNetwork { error in
  146. if let e = error {
  147. print("Uh oh! \(e)")
  148. return
  149. }
  150. }
  151. }
  152. func clearPersistence(database db: Firestore) {
  153. db.clearPersistence { error in
  154. if let e = error {
  155. print("Uh oh! \(e)")
  156. return
  157. }
  158. }
  159. }
  160. func writeDocuments(at docRef: DocumentReference, database db: Firestore) {
  161. var batch: WriteBatch
  162. batch = db.batch()
  163. batch.setData(["a": "b"], forDocument: docRef)
  164. batch.setData(["a": "b"], forDocument: docRef, merge: true)
  165. batch.setData(["c": "d"], forDocument: docRef)
  166. // commit without completion callback.
  167. batch.commit()
  168. print("Batch write without completion complete!")
  169. batch = db.batch()
  170. batch.setData(["a": "b"], forDocument: docRef)
  171. batch.setData(["c": "d"], forDocument: docRef)
  172. // commit with completion callback via trailing closure syntax.
  173. batch.commit { error in
  174. if let error = error {
  175. print("Uh oh! \(error)")
  176. return
  177. }
  178. print("Batch write callback complete!")
  179. }
  180. print("Batch write with completion complete!")
  181. }
  182. func addDocument(to collectionRef: CollectionReference) {
  183. _ = collectionRef.addDocument(data: ["foo": 42])
  184. // or
  185. collectionRef.document().setData(["foo": 42])
  186. }
  187. func readDocument(at docRef: DocumentReference) {
  188. // Trailing closure syntax.
  189. docRef.getDocument { document, error in
  190. if let document = document {
  191. // Note that both document and document.data() is nullable.
  192. if let data = document.data() {
  193. print("Read document: \(data)")
  194. }
  195. if let data = document.data(with: .estimate) {
  196. print("Read document: \(data)")
  197. }
  198. if let foo = document.get("foo") {
  199. print("Field: \(foo)")
  200. }
  201. if let foo = document.get("foo", serverTimestampBehavior: .previous) {
  202. print("Field: \(foo)")
  203. }
  204. // Fields can also be read via subscript notation.
  205. if let foo = document["foo"] {
  206. print("Field: \(foo)")
  207. }
  208. } else if let error = error {
  209. // New way to handle errors.
  210. switch error {
  211. case FirestoreErrorCode.unavailable:
  212. print("Can't read document due to being offline!")
  213. default:
  214. print("Failed to read.")
  215. }
  216. // Old way to handle errors.
  217. let nsError = error as NSError
  218. guard nsError.domain == FirestoreErrorDomain else {
  219. print("Unknown error!")
  220. return
  221. }
  222. // Option 1: try to initialize the error code enum.
  223. if let errorCode = FirestoreErrorCode.Code(rawValue: nsError.code) {
  224. switch errorCode {
  225. case .unavailable:
  226. print("Can't read document due to being offline!")
  227. default:
  228. print("Failed to read.")
  229. }
  230. }
  231. // Option 2: switch on the code and compare agianst raw values.
  232. switch nsError.code {
  233. case FirestoreErrorCode.unavailable.rawValue:
  234. print("Can't read document due to being offline!")
  235. default:
  236. print("Failed to read.")
  237. }
  238. } else {
  239. print("No error or document. Thanks, ObjC.")
  240. }
  241. }
  242. }
  243. func readDocumentWithSource(at docRef: DocumentReference) {
  244. docRef.getDocument(source: FirestoreSource.default) { _, _ in
  245. }
  246. docRef.getDocument(source: .server) { _, _ in
  247. }
  248. docRef.getDocument(source: FirestoreSource.cache) { _, _ in
  249. }
  250. }
  251. func readDocuments(matching query: Query) {
  252. query.getDocuments { querySnapshot, _ in
  253. // TODO(mikelehen): Figure out how to make "for..in" syntax work
  254. // directly on documentSet.
  255. for document in querySnapshot!.documents {
  256. print(document.data())
  257. }
  258. }
  259. }
  260. func readDocumentsWithSource(matching query: Query) {
  261. query.getDocuments(source: FirestoreSource.default) { _, _ in
  262. }
  263. query.getDocuments(source: .server) { _, _ in
  264. }
  265. query.getDocuments(source: FirestoreSource.cache) { _, _ in
  266. }
  267. }
  268. func listenToDocument(at docRef: DocumentReference) {
  269. let listener = docRef.addSnapshotListener { document, error in
  270. if let error = error {
  271. print("Uh oh! Listen canceled: \(error)")
  272. return
  273. }
  274. if let document = document {
  275. // Note that document.data() is nullable.
  276. if let data: [String: Any] = document.data() {
  277. print("Current document: \(data)")
  278. }
  279. if document.metadata.isFromCache {
  280. print("From Cache")
  281. } else {
  282. print("From Server")
  283. }
  284. }
  285. }
  286. // Unsubscribe.
  287. listener.remove()
  288. }
  289. func listenToDocumentWithMetadataChanges(at docRef: DocumentReference) {
  290. let listener = docRef.addSnapshotListener(includeMetadataChanges: true) { document, _ in
  291. if let document = document {
  292. if document.metadata.hasPendingWrites {
  293. print("Has pending writes")
  294. }
  295. }
  296. }
  297. // Unsubscribe.
  298. listener.remove()
  299. }
  300. func listenToDocuments(matching query: Query) {
  301. let listener = query.addSnapshotListener { snap, error in
  302. if let error = error {
  303. print("Uh oh! Listen canceled: \(error)")
  304. return
  305. }
  306. if let snap = snap {
  307. print("NEW SNAPSHOT (empty=\(snap.isEmpty) count=\(snap.count)")
  308. // TODO(mikelehen): Figure out how to make "for..in" syntax work
  309. // directly on documentSet.
  310. for document in snap.documents {
  311. // Note that document.data() is not nullable.
  312. let data: [String: Any] = document.data()
  313. print("Doc: ", data)
  314. }
  315. }
  316. }
  317. // Unsubscribe
  318. listener.remove()
  319. }
  320. func listenToQueryDiffs(onQuery query: Query) {
  321. let listener = query.addSnapshotListener { snap, _ in
  322. if let snap = snap {
  323. for change in snap.documentChanges {
  324. switch change.type {
  325. case .added:
  326. print("New document: \(change.document.data())")
  327. case .modified:
  328. print("Modified document: \(change.document.data())")
  329. case .removed:
  330. print("Removed document: \(change.document.data())")
  331. }
  332. }
  333. }
  334. }
  335. // Unsubscribe
  336. listener.remove()
  337. }
  338. func listenToQueryDiffsWithMetadata(onQuery query: Query) {
  339. let listener = query.addSnapshotListener(includeMetadataChanges: true) { snap, _ in
  340. if let snap = snap {
  341. for change in snap.documentChanges(includeMetadataChanges: true) {
  342. switch change.type {
  343. case .added:
  344. print("New document: \(change.document.data())")
  345. case .modified:
  346. print("Modified document: \(change.document.data())")
  347. case .removed:
  348. print("Removed document: \(change.document.data())")
  349. }
  350. }
  351. }
  352. }
  353. // Unsubscribe
  354. listener.remove()
  355. }
  356. func transactions() {
  357. let db = Firestore.firestore()
  358. let collectionRef = db.collection("cities")
  359. let accA = collectionRef.document("accountA")
  360. let accB = collectionRef.document("accountB")
  361. let amount = 20.0
  362. db.runTransaction({ transaction, errorPointer -> Any? in
  363. do {
  364. let balanceA = try transaction.getDocument(accA)["balance"] as! Double
  365. let balanceB = try transaction.getDocument(accB)["balance"] as! Double
  366. if balanceA < amount {
  367. errorPointer?.pointee = NSError(domain: "Foo", code: 123, userInfo: nil)
  368. return nil
  369. }
  370. transaction.updateData(["balance": balanceA - amount], forDocument: accA)
  371. transaction.updateData(["balance": balanceB + amount], forDocument: accB)
  372. } catch let error as NSError {
  373. print("Uh oh! \(error)")
  374. }
  375. return 0
  376. }) { _, _ in
  377. // handle result.
  378. }
  379. }
  380. func types() {
  381. let _: CollectionReference
  382. let _: DocumentChange
  383. let _: DocumentReference
  384. let _: DocumentSnapshot
  385. let _: FieldPath
  386. let _: FieldValue
  387. let _: Firestore
  388. let _: FirestoreSettings
  389. let _: GeoPoint
  390. let _: Timestamp
  391. let _: ListenerRegistration
  392. let _: Query
  393. let _: QuerySnapshot
  394. let _: SnapshotMetadata
  395. let _: Transaction
  396. let _: WriteBatch
  397. }
  398. func waitForPendingWrites(database db: Firestore) {
  399. db.waitForPendingWrites { error in
  400. if let e = error {
  401. print("Uh oh! \(e)")
  402. return
  403. }
  404. }
  405. }
  406. func addSnapshotsInSyncListener(database db: Firestore) {
  407. let listener = db.addSnapshotsInSyncListener {}
  408. // Unsubscribe
  409. listener.remove()
  410. }
  411. func terminateDb(database db: Firestore) {
  412. db.terminate { error in
  413. if let e = error {
  414. print("Uh oh! \(e)")
  415. return
  416. }
  417. }
  418. }
  419. #if swift(>=5.5.2)
  420. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  421. func testAsyncAwait(database db: Firestore) async throws {
  422. try await db.enableNetwork()
  423. try await db.disableNetwork()
  424. try await db.waitForPendingWrites()
  425. try await db.clearPersistence()
  426. try await db.terminate()
  427. try await db.runTransaction { _, _ in
  428. 0
  429. }
  430. let batch = db.batch()
  431. try await batch.commit()
  432. _ = await db.getQuery(named: "foo")
  433. _ = try await db.loadBundle(Data())
  434. let collection = db.collection("coll")
  435. try await collection.getDocuments()
  436. try await collection.getDocuments(source: FirestoreSource.default)
  437. let document = try await collection.addDocument(data: [:])
  438. try await document.setData([:])
  439. try await document.setData([:], merge: true)
  440. try await document.setData([:], mergeFields: [])
  441. try await document.updateData([:])
  442. try await document.delete()
  443. try await document.getDocument()
  444. try await document.getDocument(source: FirestoreSource.default)
  445. }
  446. #endif