BasicCompileTests.swift 14 KB

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