You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

610 lines
14 KiB

  1. // Copyright 2017 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // TODO(jba): add Output comments to examples when feasible.
  15. package firestore_test
  16. import (
  17. "context"
  18. "fmt"
  19. "cloud.google.com/go/firestore"
  20. "google.golang.org/api/iterator"
  21. )
  22. func ExampleNewClient() {
  23. ctx := context.Background()
  24. client, err := firestore.NewClient(ctx, "project-id")
  25. if err != nil {
  26. // TODO: Handle error.
  27. }
  28. defer client.Close() // Close client when done.
  29. _ = client // TODO: Use client.
  30. }
  31. func ExampleClient_Collection() {
  32. ctx := context.Background()
  33. client, err := firestore.NewClient(ctx, "project-id")
  34. if err != nil {
  35. // TODO: Handle error.
  36. }
  37. defer client.Close()
  38. coll1 := client.Collection("States")
  39. coll2 := client.Collection("States/NewYork/Cities")
  40. fmt.Println(coll1, coll2)
  41. }
  42. func ExampleClient_Doc() {
  43. ctx := context.Background()
  44. client, err := firestore.NewClient(ctx, "project-id")
  45. if err != nil {
  46. // TODO: Handle error.
  47. }
  48. defer client.Close()
  49. doc1 := client.Doc("States/NewYork")
  50. doc2 := client.Doc("States/NewYork/Cities/Albany")
  51. fmt.Println(doc1, doc2)
  52. }
  53. func ExampleClient_GetAll() {
  54. ctx := context.Background()
  55. client, err := firestore.NewClient(ctx, "project-id")
  56. if err != nil {
  57. // TODO: Handle error.
  58. }
  59. defer client.Close()
  60. docs, err := client.GetAll(ctx, []*firestore.DocumentRef{
  61. client.Doc("States/NorthCarolina"),
  62. client.Doc("States/SouthCarolina"),
  63. client.Doc("States/WestCarolina"),
  64. client.Doc("States/EastCarolina"),
  65. })
  66. if err != nil {
  67. // TODO: Handle error.
  68. }
  69. // docs is a slice with four DocumentSnapshots, but the last two are
  70. // nil because there is no West or East Carolina.
  71. fmt.Println(docs)
  72. }
  73. func ExampleClient_Batch() {
  74. ctx := context.Background()
  75. client, err := firestore.NewClient(ctx, "project-id")
  76. if err != nil {
  77. // TODO: Handle error.
  78. }
  79. defer client.Close()
  80. b := client.Batch()
  81. _ = b // TODO: Use batch.
  82. }
  83. func ExampleWriteBatch_Commit() {
  84. ctx := context.Background()
  85. client, err := firestore.NewClient(ctx, "project-id")
  86. if err != nil {
  87. // TODO: Handle error.
  88. }
  89. defer client.Close()
  90. type State struct {
  91. Capital string `firestore:"capital"`
  92. Population float64 `firestore:"pop"` // in millions
  93. }
  94. ny := client.Doc("States/NewYork")
  95. ca := client.Doc("States/California")
  96. writeResults, err := client.Batch().
  97. Create(ny, State{Capital: "Albany", Population: 19.8}).
  98. Set(ca, State{Capital: "Sacramento", Population: 39.14}).
  99. Delete(client.Doc("States/WestDakota")).
  100. Commit(ctx)
  101. if err != nil {
  102. // TODO: Handle error.
  103. }
  104. fmt.Println(writeResults)
  105. }
  106. func ExampleCollectionRef_Add() {
  107. ctx := context.Background()
  108. client, err := firestore.NewClient(ctx, "project-id")
  109. if err != nil {
  110. // TODO: Handle error.
  111. }
  112. defer client.Close()
  113. doc, wr, err := client.Collection("Users").Add(ctx, map[string]interface{}{
  114. "name": "Alice",
  115. "email": "aj@example.com",
  116. })
  117. if err != nil {
  118. // TODO: Handle error.
  119. }
  120. fmt.Println(doc, wr)
  121. }
  122. func ExampleCollectionRef_Doc() {
  123. ctx := context.Background()
  124. client, err := firestore.NewClient(ctx, "project-id")
  125. if err != nil {
  126. // TODO: Handle error.
  127. }
  128. defer client.Close()
  129. fl := client.Collection("States").Doc("Florida")
  130. ta := client.Collection("States").Doc("Florida/Cities/Tampa")
  131. fmt.Println(fl, ta)
  132. }
  133. func ExampleCollectionRef_NewDoc() {
  134. ctx := context.Background()
  135. client, err := firestore.NewClient(ctx, "project-id")
  136. if err != nil {
  137. // TODO: Handle error.
  138. }
  139. defer client.Close()
  140. doc := client.Collection("Users").NewDoc()
  141. fmt.Println(doc)
  142. }
  143. func ExampleDocumentRef_Collection() {
  144. ctx := context.Background()
  145. client, err := firestore.NewClient(ctx, "project-id")
  146. if err != nil {
  147. // TODO: Handle error.
  148. }
  149. defer client.Close()
  150. mi := client.Collection("States").Doc("Michigan")
  151. cities := mi.Collection("Cities")
  152. fmt.Println(cities)
  153. }
  154. func ExampleDocumentRef_Create_map() {
  155. ctx := context.Background()
  156. client, err := firestore.NewClient(ctx, "project-id")
  157. if err != nil {
  158. // TODO: Handle error.
  159. }
  160. defer client.Close()
  161. wr, err := client.Doc("States/Colorado").Create(ctx, map[string]interface{}{
  162. "capital": "Denver",
  163. "pop": 5.5,
  164. })
  165. if err != nil {
  166. // TODO: Handle error.
  167. }
  168. fmt.Println(wr.UpdateTime)
  169. }
  170. func ExampleDocumentRef_Create_struct() {
  171. ctx := context.Background()
  172. client, err := firestore.NewClient(ctx, "project-id")
  173. if err != nil {
  174. // TODO: Handle error.
  175. }
  176. defer client.Close()
  177. type State struct {
  178. Capital string `firestore:"capital"`
  179. Population float64 `firestore:"pop"` // in millions
  180. }
  181. wr, err := client.Doc("States/Colorado").Create(ctx, State{
  182. Capital: "Denver",
  183. Population: 5.5,
  184. })
  185. if err != nil {
  186. // TODO: Handle error.
  187. }
  188. fmt.Println(wr.UpdateTime)
  189. }
  190. func ExampleDocumentRef_Set() {
  191. ctx := context.Background()
  192. client, err := firestore.NewClient(ctx, "project-id")
  193. if err != nil {
  194. // TODO: Handle error.
  195. }
  196. defer client.Close()
  197. // Overwrite the document with the given data. Any other fields currently
  198. // in the document will be removed.
  199. wr, err := client.Doc("States/Alabama").Set(ctx, map[string]interface{}{
  200. "capital": "Montgomery",
  201. "pop": 4.9,
  202. })
  203. if err != nil {
  204. // TODO: Handle error.
  205. }
  206. fmt.Println(wr.UpdateTime)
  207. }
  208. func ExampleDocumentRef_Set_merge() {
  209. ctx := context.Background()
  210. client, err := firestore.NewClient(ctx, "project-id")
  211. if err != nil {
  212. // TODO: Handle error.
  213. }
  214. defer client.Close()
  215. // Overwrite only the fields in the map; preserve all others.
  216. _, err = client.Doc("States/Alabama").Set(ctx, map[string]interface{}{
  217. "pop": 5.2,
  218. }, firestore.MergeAll)
  219. if err != nil {
  220. // TODO: Handle error.
  221. }
  222. type State struct {
  223. Capital string `firestore:"capital"`
  224. Population float64 `firestore:"pop"` // in millions
  225. }
  226. // To do a merging Set with struct data, specify the exact fields to overwrite.
  227. // MergeAll is disallowed here, because it would probably be a mistake: the "capital"
  228. // field would be overwritten with the empty string.
  229. _, err = client.Doc("States/Alabama").Set(ctx, State{Population: 5.2}, firestore.Merge([]string{"pop"}))
  230. if err != nil {
  231. // TODO: Handle error.
  232. }
  233. }
  234. func ExampleDocumentRef_Update() {
  235. ctx := context.Background()
  236. client, err := firestore.NewClient(ctx, "project-id")
  237. if err != nil {
  238. // TODO: Handle error.
  239. }
  240. defer client.Close()
  241. tenn := client.Doc("States/Tennessee")
  242. wr, err := tenn.Update(ctx, []firestore.Update{
  243. {Path: "pop", Value: 6.6},
  244. {FieldPath: []string{".", "*", "/"}, Value: "odd"},
  245. })
  246. if err != nil {
  247. // TODO: Handle error.
  248. }
  249. fmt.Println(wr.UpdateTime)
  250. }
  251. func ExampleDocumentRef_Delete() {
  252. ctx := context.Background()
  253. client, err := firestore.NewClient(ctx, "project-id")
  254. if err != nil {
  255. // TODO: Handle error.
  256. }
  257. defer client.Close()
  258. // Oops, Ontario is a Canadian province...
  259. if _, err = client.Doc("States/Ontario").Delete(ctx); err != nil {
  260. // TODO: Handle error.
  261. }
  262. }
  263. func ExampleDocumentRef_Get() {
  264. ctx := context.Background()
  265. client, err := firestore.NewClient(ctx, "project-id")
  266. if err != nil {
  267. // TODO: Handle error.
  268. }
  269. defer client.Close()
  270. docsnap, err := client.Doc("States/Ohio").Get(ctx)
  271. if err != nil {
  272. // TODO: Handle error.
  273. }
  274. _ = docsnap // TODO: Use DocumentSnapshot.
  275. }
  276. func ExampleDocumentRef_Snapshots() {
  277. ctx := context.Background()
  278. client, err := firestore.NewClient(ctx, "project-id")
  279. if err != nil {
  280. // TODO: Handle error.
  281. }
  282. defer client.Close()
  283. iter := client.Doc("States/Idaho").Snapshots(ctx)
  284. defer iter.Stop()
  285. for {
  286. docsnap, err := iter.Next()
  287. if err != nil {
  288. // TODO: Handle error.
  289. }
  290. _ = docsnap // TODO: Use DocumentSnapshot.
  291. }
  292. }
  293. func ExampleDocumentSnapshot_Data() {
  294. ctx := context.Background()
  295. client, err := firestore.NewClient(ctx, "project-id")
  296. if err != nil {
  297. // TODO: Handle error.
  298. }
  299. defer client.Close()
  300. docsnap, err := client.Doc("States/Ohio").Get(ctx)
  301. if err != nil {
  302. // TODO: Handle error.
  303. }
  304. ohioMap := docsnap.Data()
  305. fmt.Println(ohioMap["capital"])
  306. }
  307. func ExampleDocumentSnapshot_DataAt() {
  308. ctx := context.Background()
  309. client, err := firestore.NewClient(ctx, "project-id")
  310. if err != nil {
  311. // TODO: Handle error.
  312. }
  313. defer client.Close()
  314. docsnap, err := client.Doc("States/Ohio").Get(ctx)
  315. if err != nil {
  316. // TODO: Handle error.
  317. }
  318. cap, err := docsnap.DataAt("capital")
  319. if err != nil {
  320. // TODO: Handle error.
  321. }
  322. fmt.Println(cap)
  323. }
  324. func ExampleDocumentSnapshot_DataAtPath() {
  325. ctx := context.Background()
  326. client, err := firestore.NewClient(ctx, "project-id")
  327. if err != nil {
  328. // TODO: Handle error.
  329. }
  330. defer client.Close()
  331. docsnap, err := client.Doc("States/Ohio").Get(ctx)
  332. if err != nil {
  333. // TODO: Handle error.
  334. }
  335. pop, err := docsnap.DataAtPath([]string{"capital", "population"})
  336. if err != nil {
  337. // TODO: Handle error.
  338. }
  339. fmt.Println(pop)
  340. }
  341. func ExampleDocumentSnapshot_DataTo() {
  342. ctx := context.Background()
  343. client, err := firestore.NewClient(ctx, "project-id")
  344. if err != nil {
  345. // TODO: Handle error.
  346. }
  347. defer client.Close()
  348. docsnap, err := client.Doc("States/Ohio").Get(ctx)
  349. if err != nil {
  350. // TODO: Handle error.
  351. }
  352. type State struct {
  353. Capital string `firestore:"capital"`
  354. Population float64 `firestore:"pop"` // in millions
  355. }
  356. var s State
  357. if err := docsnap.DataTo(&s); err != nil {
  358. // TODO: Handle error.
  359. }
  360. fmt.Println(s)
  361. }
  362. func ExampleQuery_Documents() {
  363. ctx := context.Background()
  364. client, err := firestore.NewClient(ctx, "project-id")
  365. if err != nil {
  366. // TODO: Handle error.
  367. }
  368. defer client.Close()
  369. q := client.Collection("States").Select("pop").
  370. Where("pop", ">", 10).
  371. OrderBy("pop", firestore.Desc).
  372. Limit(10)
  373. iter1 := q.Documents(ctx)
  374. _ = iter1 // TODO: Use iter1.
  375. // You can call Documents directly on a CollectionRef as well.
  376. iter2 := client.Collection("States").Documents(ctx)
  377. _ = iter2 // TODO: Use iter2.
  378. }
  379. // This example is just like the one above, but illustrates
  380. // how to use the XXXPath methods of Query for field paths
  381. // that can't be expressed as a dot-separated string.
  382. func ExampleQuery_Documents_path_methods() {
  383. ctx := context.Background()
  384. client, err := firestore.NewClient(ctx, "project-id")
  385. if err != nil {
  386. // TODO: Handle error.
  387. }
  388. defer client.Close()
  389. q := client.Collection("Unusual").SelectPaths([]string{"*"}, []string{"[~]"}).
  390. WherePath([]string{"/"}, ">", 10).
  391. OrderByPath([]string{"/"}, firestore.Desc).
  392. Limit(10)
  393. iter1 := q.Documents(ctx)
  394. _ = iter1 // TODO: Use iter1.
  395. // You can call Documents directly on a CollectionRef as well.
  396. iter2 := client.Collection("States").Documents(ctx)
  397. _ = iter2 // TODO: Use iter2.
  398. }
  399. func ExampleQuery_Snapshots() {
  400. ctx := context.Background()
  401. client, err := firestore.NewClient(ctx, "project-id")
  402. if err != nil {
  403. // TODO: Handle error.
  404. }
  405. defer client.Close()
  406. q := client.Collection("States").
  407. Where("pop", ">", 10).
  408. OrderBy("pop", firestore.Desc).
  409. Limit(10)
  410. qsnapIter := q.Snapshots(ctx)
  411. // Listen forever for changes to the query's results.
  412. for {
  413. qsnap, err := qsnapIter.Next()
  414. if err == iterator.Done {
  415. break
  416. }
  417. if err != nil {
  418. // TODO: Handle error.
  419. }
  420. fmt.Printf("At %s there were %d results.\n", qsnap.ReadTime, qsnap.Size)
  421. _ = qsnap.Documents // TODO: Iterate over the results if desired.
  422. _ = qsnap.Changes // TODO: Use the list of incremental changes if desired.
  423. }
  424. }
  425. func ExampleDocumentIterator_Next() {
  426. ctx := context.Background()
  427. client, err := firestore.NewClient(ctx, "project-id")
  428. if err != nil {
  429. // TODO: Handle error.
  430. }
  431. defer client.Close()
  432. q := client.Collection("States").
  433. Where("pop", ">", 10).
  434. OrderBy("pop", firestore.Desc)
  435. iter := q.Documents(ctx)
  436. defer iter.Stop()
  437. for {
  438. doc, err := iter.Next()
  439. if err == iterator.Done {
  440. break
  441. }
  442. if err != nil {
  443. // TODO: Handle error.
  444. }
  445. fmt.Println(doc.Data())
  446. }
  447. }
  448. func ExampleDocumentIterator_GetAll() {
  449. ctx := context.Background()
  450. client, err := firestore.NewClient(ctx, "project-id")
  451. if err != nil {
  452. // TODO: Handle error.
  453. }
  454. defer client.Close()
  455. q := client.Collection("States").
  456. Where("pop", ">", 10).
  457. OrderBy("pop", firestore.Desc).
  458. Limit(10) // a good idea with GetAll, to avoid filling memory
  459. docs, err := q.Documents(ctx).GetAll()
  460. if err != nil {
  461. // TODO: Handle error.
  462. }
  463. for _, doc := range docs {
  464. fmt.Println(doc.Data())
  465. }
  466. }
  467. func ExampleClient_RunTransaction() {
  468. ctx := context.Background()
  469. client, err := firestore.NewClient(ctx, "project-id")
  470. if err != nil {
  471. // TODO: Handle error.
  472. }
  473. defer client.Close()
  474. nm := client.Doc("States/NewMexico")
  475. err = client.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error {
  476. doc, err := tx.Get(nm) // tx.Get, NOT nm.Get!
  477. if err != nil {
  478. return err
  479. }
  480. pop, err := doc.DataAt("pop")
  481. if err != nil {
  482. return err
  483. }
  484. return tx.Update(nm, []firestore.Update{{Path: "pop", Value: pop.(float64) + 0.2}})
  485. })
  486. if err != nil {
  487. // TODO: Handle error.
  488. }
  489. }
  490. func ExampleArrayUnion_create() {
  491. ctx := context.Background()
  492. client, err := firestore.NewClient(ctx, "project-id")
  493. if err != nil {
  494. // TODO: Handle error.
  495. }
  496. defer client.Close()
  497. wr, err := client.Doc("States/Colorado").Create(ctx, map[string]interface{}{
  498. "cities": firestore.ArrayUnion("Denver", "Golden", "Boulder"),
  499. "pop": 5.5,
  500. })
  501. if err != nil {
  502. // TODO: Handle error.
  503. }
  504. fmt.Println(wr.UpdateTime)
  505. }
  506. func ExampleArrayUnion_update() {
  507. ctx := context.Background()
  508. client, err := firestore.NewClient(ctx, "project-id")
  509. if err != nil {
  510. // TODO: Handle error.
  511. }
  512. defer client.Close()
  513. co := client.Doc("States/Colorado")
  514. wr, err := co.Update(ctx, []firestore.Update{
  515. {Path: "cities", Value: firestore.ArrayUnion("Broomfield")},
  516. })
  517. if err != nil {
  518. // TODO: Handle error.
  519. }
  520. fmt.Println(wr.UpdateTime)
  521. }
  522. func ExampleArrayRemove_update() {
  523. ctx := context.Background()
  524. client, err := firestore.NewClient(ctx, "project-id")
  525. if err != nil {
  526. // TODO: Handle error.
  527. }
  528. defer client.Close()
  529. co := client.Doc("States/Colorado")
  530. wr, err := co.Update(ctx, []firestore.Update{
  531. {Path: "cities", Value: firestore.ArrayRemove("Denver")},
  532. })
  533. if err != nil {
  534. // TODO: Handle error.
  535. }
  536. fmt.Println(wr.UpdateTime)
  537. }