firestore

package
v0.15.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 3, 2017 License: Apache-2.0 Imports: 28 Imported by: 0

Documentation

Overview

Package firestore provides a client for reading and writing to a Cloud Firestore database.

See https://cloud.google.com/firestore/docs for an introduction to Cloud Firestore and additional help on using the Firestore API.

Creating a Client

To start working with this package, create a client with a project ID:

ctx := context.Background()
client, err := firestore.NewClient(ctx, "projectID")
if err != nil {
	// TODO: Handle error.
}

CollectionRefs and DocumentRefs

In Firestore, documents are sets of key-value pairs, and collections are groups of documents. A Firestore database consists of a hierarchy of alternating collections and documents, referred to by slash-separated paths like "States/California/Cities/SanFrancisco".

This client is built around references to collections and documents. CollectionRefs and DocumentRefs are lightweight values that refer to the corresponding database entities. Creating a ref does not involve any network traffic.

states := client.Collection("States")
ny := states.Doc("NewYork")
// Or, in a single call:
ny = client.Doc("States/NewYork")

Reading

Use DocumentRef.Get to read a document. The result is a DocumentSnapshot. Call its Data method to obtain the entire document contents as a map.

docsnap, err := ny.Get(ctx)
if err != nil {
	// TODO: Handle error.
}
dataMap := docsnap.Data()
fmt.Println(dataMap)

You can also obtain a single field with DataAt, or extract the data into a struct with DataTo. With the type definition

type State struct {
	Capital    string  `firestore:"capital"`
	Population float64 `firestore:"pop"` // in millions
}

we can extract the document's data into a value of type State:

var nyData State
if err := docsnap.DataTo(&nyData); err != nil {
	// TODO: Handle error.
}

Note that this client supports struct tags beginning with "firestore:" that work like the tags of the encoding/json package, letting you rename fields, ignore them, or omit their values when empty.

To retrieve multiple documents from their references in a single call, use Client.GetAll.

docsnaps, err := client.GetAll(ctx, []*firestore.DocumentRef{
	states.Doc("Wisconsin"), states.Doc("Ohio"),
})
if err != nil {
	// TODO: Handle error.
}
for _, ds := range docsnaps {
	_ = ds // TODO: Use ds.
}

Writing

For writing individual documents, use the methods on DocumentReference. Create creates a new document.

wr, err := ny.Create(ctx, State{
	Capital:    "Albany",
	Population: 19.8,
})
if err != nil {
	// TODO: Handle error.
}
fmt.Println(wr)

The first return value is a WriteResult, which contains the time at which the document was updated.

Create fails if the document exists. Another method, Set, either replaces an existing document or creates a new one.

ca := states.Doc("California")
_, err = ca.Set(ctx, State{
	Capital:    "Sacramento",
	Population: 39.14,
})

To update some fields of an existing document, use UpdateMap, UpdateStruct or UpdatePaths. For UpdateMap, the keys of the map specify which fields to change. The others are untouched.

_, err = ca.UpdateMap(ctx, map[string]interface{}{"pop": 39.2})

For UpdateStruct, you must explicitly provide the fields to update. The field names must match exactly.

_, err = ca.UpdateStruct(ctx, []string{"pop"}, State{Population: 39.2})

Use DocumentRef.Delete to delete a document.

_, err = ny.Delete(ctx)

Preconditions

You can condition Deletes or Updates on when a document was last changed. Specify these preconditions as an option to a Delete or Update method. The check and the write happen atomically with a single RPC.

docsnap, err = ca.Get(ctx)
if err != nil {
	// TODO: Handle error.
}
_, err = ca.UpdateStruct(ctx, []string{"capital"}, State{Capital: "Sacramento"},
	firestore.LastUpdateTime(docsnap.UpdateTime))

Here we update a doc only if it hasn't changed since we read it. You could also do this with a transaction.

To perform multiple writes at once, use a WriteBatch. Its methods chain for convenience.

WriteBatch.Commit sends the collected writes to the server, where they happen atomically.

writeResults, err := client.Batch().
	Create(ny, State{Capital: "Albany"}).
	UpdateStruct(ca, []string{"capital"}, State{Capital: "Sacramento"}).
	Delete(client.Doc("States/WestDakota")).
	Commit(ctx)

Queries

You can use SQL to select documents from a collection. Begin with the collection, and build up a query using Select, Where and other methods of Query.

q := states.Where("pop", ">", 10).OrderBy("pop", firestore.Desc)

Call the Query's Documents method to get an iterator, and use it like the other Google Cloud Client iterators.

iter := q.Documents(ctx)
for {
	doc, err := iter.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		// TODO: Handle error.
	}
	fmt.Println(doc.Data())
}

To get all the documents in a collection, you can use the collection itself as a query.

iter = client.Collection("States").Documents(ctx)

Transactions

Use a transaction to execute reads and writes atomically. All reads must happen before any writes. Transaction creation, commit, rollback and retry are handled for you by the Client.RunTransaction method; just provide a function and use the read and write methods of the Transaction passed to it.

ny := client.Doc("States/NewYork")
err := client.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error {
	doc, err := tx.Get(ny) // tx.Get, NOT ny.Get!
	if err != nil {
		return err
	}
	pop, err := doc.DataAt("pop")
	if err != nil {
		return err
	}
	return tx.UpdateStruct(ny, []string{"pop"},
		State{Population: pop.(float64) + 0.2})
})
if err != nil {
	// TODO: Handle error.
}

Authentication

See examples of authorization and authentication at https://godoc.org/cloud.google.com/go#pkg-examples.

Index

Examples

Constants

View Source
const DefaultTransactionMaxAttempts = 5

DefaultTransactionMaxAttempts is the default number of times to attempt a transaction.

View Source
const DocumentID = "__name__"

DocumentID is the special field name representing the ID of a document in queries.

Variables

View Source
var (
	// Delete is used as a value in a call to UpdateMap to indicate that the
	// corresponding key should be deleted.
	Delete = new(int)

	// ServerTimestamp is used as a value in a call to UpdateMap to indicate that the
	// key's value should be set to the time at which the server processed
	// the request.
	ServerTimestamp = new(int)
)
View Source
var (
	// ErrConcurrentTransaction is returned when a transaction is rolled back due
	// to a conflict with a concurrent transaction.
	ErrConcurrentTransaction = errors.New("firestore: concurrent transaction")
)
View Source
var ReadOnly = ro{}

ReadOnly is a TransactionOption that makes the transaction read-only. Read-only transactions cannot issue write operations, but are more efficient.

Functions

func MaxAttempts

func MaxAttempts(n int) maxAttempts

MaxAttempts is a TransactionOption that configures the maximum number of times to try a transaction. In defaults to DefaultTransactionMaxAttempts.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

A Client provides access to the Firestore service.

func NewClient

func NewClient(ctx context.Context, projectID string, opts ...option.ClientOption) (*Client, error)

NewClient creates a new Firestore client that uses the given project.

Example
package main

import (
	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close() // Close client when done.
	_ = client           // TODO: Use client.
}
Output:

func (*Client) Batch

func (c *Client) Batch() *WriteBatch

Batch returns a WriteBatch.

Example
package main

import (
	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()
	b := client.Batch()
	_ = b // TODO: Use batch.
}
Output:

func (*Client) Close

func (c *Client) Close() error

Close closes any resources held by the client.

Close need not be called at program exit.

func (*Client) Collection

func (c *Client) Collection(path string) *CollectionRef

Collection creates a reference to a collection with the given path. A path is a sequence of IDs separated by slashes.

Collection returns nil if path contains an even number of IDs or any ID is empty.

Example
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()
	coll1 := client.Collection("States")
	coll2 := client.Collection("States/NewYork/Cities")
	fmt.Println(coll1, coll2)
}
Output:

func (*Client) Collections

func (c *Client) Collections(ctx context.Context) *CollectionIterator

Collections returns an interator over the top-level collections.

func (*Client) Doc

func (c *Client) Doc(path string) *DocumentRef

Doc creates a reference to a document with the given path. A path is a sequence of IDs separated by slashes.

Doc returns nil if path contains an odd number of IDs or any ID is empty.

Example
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()
	doc1 := client.Doc("States/NewYork")
	doc2 := client.Doc("States/NewYork/Cities/Albany")
	fmt.Println(doc1, doc2)
}
Output:

func (*Client) GetAll

func (c *Client) GetAll(ctx context.Context, docRefs []*DocumentRef) ([]*DocumentSnapshot, error)

GetAll retrieves multiple documents with a single call. The DocumentSnapshots are returned in the order of the given DocumentRefs.

If a document is not present, the corresponding DocumentSnapshot will be nil.

Example
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()
	docs, err := client.GetAll(ctx, []*firestore.DocumentRef{
		client.Doc("States/NorthCarolina"),
		client.Doc("States/SouthCarolina"),
		client.Doc("States/WestCarolina"),
		client.Doc("States/EastCarolina"),
	})
	if err != nil {
		// TODO: Handle error.
	}
	// docs is a slice with four DocumentSnapshots, but the last two are
	// nil because there is no West or East Carolina.
	fmt.Println(docs)
}
Output:

func (*Client) RunTransaction

func (c *Client) RunTransaction(ctx context.Context, f func(context.Context, *Transaction) error, opts ...TransactionOption) error

RunTransaction runs f in a transaction. f should use the transaction it is given for all Firestore operations. For any operation requiring a context, f should use the context it is passed, not the first argument to RunTransaction.

f must not call Commit or Rollback on the provided Transaction.

If f returns nil, RunTransaction commits the transaction. If the commit fails due to a conflicting transaction, RunTransaction retries f. It gives up and returns ErrConcurrentTransaction after a number of attempts that can be configured with the MaxAttempts option. If the commit succeeds, RunTransaction returns a nil error.

If f returns non-nil, then the transaction will be rolled back and this method will return the same error. The function f is not retried.

Note that when f returns, the transaction is not committed. Calling code must not assume that any of f's changes have been committed until RunTransaction returns nil.

Since f may be called more than once, f should usually be idempotent – that is, it should have the same result when called multiple times.

Example
package main

import (
	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	nm := client.Doc("States/NewMexico")
	err = client.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error {
		doc, err := tx.Get(nm) // tx.Get, NOT nm.Get!
		if err != nil {
			return err
		}
		pop, err := doc.DataAt("pop")
		if err != nil {
			return err
		}
		return tx.UpdateMap(nm, map[string]interface{}{
			"pop": pop.(float64) + 0.2,
		})
	})
	if err != nil {
		// TODO: Handle error.
	}
}
Output:

type CollectionIterator

type CollectionIterator struct {
	// contains filtered or unexported fields
}

CollectionIterator is an iterator over sub-collections of a document.

func (*CollectionIterator) GetAll

func (it *CollectionIterator) GetAll() ([]*CollectionRef, error)

GetAll returns all the collections remaining from the iterator.

func (*CollectionIterator) Next

func (it *CollectionIterator) Next() (*CollectionRef, error)

Next returns the next result. Its second return value is iterator.Done if there are no more results. Once Next returns Done, all subsequent calls will return Done.

func (*CollectionIterator) PageInfo

func (it *CollectionIterator) PageInfo() *iterator.PageInfo

PageInfo supports pagination. See the google.golang.org/api/iterator package for details.

type CollectionRef

type CollectionRef struct {

	// Parent is the document of which this collection is a part. It is
	// nil for top-level collections.
	Parent *DocumentRef

	// The full resource path of the collection: "projects/P/databases/D/documents..."
	Path string

	// ID is the collection identifier.
	ID string

	// Use the methods of Query on a CollectionRef to create and run queries.
	Query
	// contains filtered or unexported fields
}

A CollectionRef is a reference to Firestore collection.

func (*CollectionRef) Add

func (c *CollectionRef) Add(ctx context.Context, data interface{}) (*DocumentRef, *WriteResult, error)

Add generates a DocumentRef with a unique ID. It then creates the document with the given data, which can be a map[string]interface{}, a struct or a pointer to a struct.

Add returns an error in the unlikely event that a document with the same ID already exists.

Example
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	doc, wr, err := client.Collection("Users").Add(ctx, map[string]interface{}{
		"name":  "Alice",
		"email": "aj@example.com",
	})
	if err != nil {
		// TODO: Handle error.
	}
	fmt.Println(doc, wr)
}
Output:

func (*CollectionRef) Doc

func (c *CollectionRef) Doc(id string) *DocumentRef

Doc returns a DocumentRef that refers to the document in the collection with the given identifier.

Example
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	fl := client.Collection("States").Doc("Florida")
	ta := client.Collection("States").Doc("Florida/Cities/Tampa")

	fmt.Println(fl, ta)
}
Output:

func (*CollectionRef) NewDoc

func (c *CollectionRef) NewDoc() *DocumentRef

NewDoc returns a DocumentRef with a uniquely generated ID.

Example
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	doc := client.Collection("Users").NewDoc()

	fmt.Println(doc)
}
Output:

type Direction

type Direction int32

Direction is the sort direction for result ordering.

const (
	// Asc sorts results from smallest to largest.
	Asc Direction = Direction(pb.StructuredQuery_ASCENDING)

	// Desc sorts results from largest to smallest.
	Desc Direction = Direction(pb.StructuredQuery_DESCENDING)
)

type DocumentIterator

type DocumentIterator struct {
	// contains filtered or unexported fields
}

DocumentIterator is an iterator over documents returned by a query.

func (*DocumentIterator) GetAll

func (it *DocumentIterator) GetAll() ([]*DocumentSnapshot, error)

GetAll returns all the documents remaining from the iterator.

Example
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	q := client.Collection("States").
		Where("pop", ">", 10).
		OrderBy("pop", firestore.Desc).
		Limit(10) // a good idea with GetAll, to avoid filling memory
	docs, err := q.Documents(ctx).GetAll()
	if err != nil {
		// TODO: Handle error.
	}
	for _, doc := range docs {
		fmt.Println(doc.Data())
	}
}
Output:

func (*DocumentIterator) Next

func (it *DocumentIterator) Next() (*DocumentSnapshot, error)

Next returns the next result. Its second return value is iterator.Done if there are no more results. Once Next returns Done, all subsequent calls will return Done.

Example
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"

	"google.golang.org/api/iterator"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	q := client.Collection("States").
		Where("pop", ">", 10).
		OrderBy("pop", firestore.Desc)
	iter := q.Documents(ctx)
	for {
		doc, err := iter.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			// TODO: Handle error.
		}
		fmt.Println(doc.Data())
	}
}
Output:

type DocumentRef

type DocumentRef struct {
	// The CollectionRef that this document is a part of. Never nil.
	Parent *CollectionRef

	// The full resource path of the document: "projects/P/databases/D/documents..."
	Path string

	// The ID of the document: the last component of the resource path.
	ID string
}

A DocumentRef is a reference to a Firestore document.

func (*DocumentRef) Collection

func (d *DocumentRef) Collection(id string) *CollectionRef

Collection returns a reference to sub-collection of this document.

Example
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	mi := client.Collection("States").Doc("Michigan")
	cities := mi.Collection("Cities")

	fmt.Println(cities)
}
Output:

func (*DocumentRef) Collections

func (d *DocumentRef) Collections(ctx context.Context) *CollectionIterator

Collections returns an interator over the immediate sub-collections of the document.

func (*DocumentRef) Create

func (d *DocumentRef) Create(ctx context.Context, data interface{}) (*WriteResult, error)

Create creates the document with the given data. It returns an error if a document with the same ID already exists.

The data argument can be a map with string keys, a struct, or a pointer to a struct. The map keys or exported struct fields become the fields of the firestore document. The values of data are converted to Firestore values as follows:

  • bool converts to Bool.
  • string converts to String.
  • int, int8, int16, int32 and int64 convert to Integer.
  • uint8, uint16 and uint32 convert to Integer. uint64 is disallowed, because it can represent values that cannot be represented in an int64, which is the underlying type of a Integer.
  • float32 and float64 convert to Double.
  • []byte converts to Bytes.
  • time.Time converts to Timestamp.
  • latlng.LatLng converts to GeoPoint. latlng is the package "google.golang.org/genproto/googleapis/type/latlng".
  • Slices convert to Array.
  • Maps and structs convert to Map.
  • nils of any type convert to Null.

Pointers and interface{} are also permitted, and their elements processed recursively.

Struct fields can have tags like those used by the encoding/json package. Tags begin with "firestore:" and are followed by "-", meaning "ignore this field," or an alternative name for the field. Following the name, these comma-separated options may be provided:

  • omitempty: Do not encode this field if it is empty. A value is empty if it is a zero value, or an array, slice or map of length zero.
  • serverTimestamp: The field must be of type time.Time. When writing, if the field has the zero value, the server will populate the stored document with the time that the request is processed.
Example (Map)
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	wr, err := client.Doc("States/Colorado").Create(ctx, map[string]interface{}{
		"capital": "Denver",
		"pop":     5.5,
	})
	if err != nil {
		// TODO: Handle error.
	}
	fmt.Println(wr.UpdateTime)
}
Output:

Example (Struct)
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	type State struct {
		Capital    string  `firestore:"capital"`
		Population float64 `firestore:"pop"` // in millions
	}

	wr, err := client.Doc("States/Colorado").Create(ctx, State{
		Capital:    "Denver",
		Population: 5.5,
	})
	if err != nil {
		// TODO: Handle error.
	}
	fmt.Println(wr.UpdateTime)
}
Output:

func (*DocumentRef) Delete

func (d *DocumentRef) Delete(ctx context.Context, preconds ...Precondition) (*WriteResult, error)

Delete deletes the document. If the document doesn't exist, it does nothing and returns no error.

Example
package main

import (
	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	// Oops, Ontario is a Canadian province...
	if _, err = client.Doc("States/Ontario").Delete(ctx); err != nil {
		// TODO: Handle error.
	}
}
Output:

func (*DocumentRef) Get

Get retrieves the document. It returns an error if the document does not exist.

Example
package main

import (
	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	docsnap, err := client.Doc("States/Ohio").Get(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	_ = docsnap // TODO: Use DocumentSnapshot.
}
Output:

func (*DocumentRef) Set

func (d *DocumentRef) Set(ctx context.Context, data interface{}, opts ...SetOption) (*WriteResult, error)

Set creates or overwrites the document with the given data. See DocumentRef.Create for the acceptable values of data. Without options, Set overwrites the document completely. Specify one of the Merge options to preserve an existing document's fields.

Example
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	// Overwrite the document with the given data. Any other fields currently
	// in the document will be removed.
	wr, err := client.Doc("States/Alabama").Set(ctx, map[string]interface{}{
		"capital": "Montgomery",
		"pop":     4.9,
	})
	if err != nil {
		// TODO: Handle error.
	}
	fmt.Println(wr.UpdateTime)
}
Output:

Example (Merge)
package main

import (
	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	// Overwrite only the fields in the map; preserve all others.
	_, err = client.Doc("States/Alabama").Set(ctx, map[string]interface{}{
		"pop": 5.2,
	}, firestore.MergeAll)
	if err != nil {
		// TODO: Handle error.
	}

	type State struct {
		Capital    string  `firestore:"capital"`
		Population float64 `firestore:"pop"` // in millions
	}

	// To do a merging Set with struct data, specify the exact fields to overwrite.
	// MergeAll is disallowed here, because it would probably be a mistake: the "capital"
	// field would be overwritten with the empty string.
	_, err = client.Doc("States/Alabama").Set(ctx, State{Population: 5.2}, firestore.Merge("pop"))
	if err != nil {
		// TODO: Handle error.
	}
}
Output:

func (*DocumentRef) UpdateMap

func (d *DocumentRef) UpdateMap(ctx context.Context, data map[string]interface{}, preconds ...Precondition) (*WriteResult, error)

UpdateMap updates the document using the given data. Map keys replace the stored values, but other fields of the stored document are untouched. See DocumentRef.Create for acceptable map values.

If a map key is a multi-element field path, like "a.b", then only key "b" of the map value at "a" is changed; the rest of the map is preserved. For example, if the stored data is

{"a": {"b": 1, "c": 2}}

then

UpdateMap({"a": {"b": 3}}) => {"a": {"b": 3}}

while

UpdateMap({"a.b": 3}) => {"a": {"b": 3, "c": 2}}

To delete a key, specify it in the input with a value of firestore.Delete.

Field paths expressed as map keys must not contain any of the runes "˜*/[]". Use UpdatePaths instead for such paths.

UpdateMap returns an error if the document does not exist.

Example
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	tenn := client.Doc("States/Tennessee")
	wr, err := tenn.UpdateMap(ctx, map[string]interface{}{"pop": 6.6})
	if err != nil {
		// TODO: Handle error.
	}
	fmt.Println(wr.UpdateTime)
}
Output:

func (*DocumentRef) UpdatePaths

func (d *DocumentRef) UpdatePaths(ctx context.Context, data []FieldPathUpdate, preconds ...Precondition) (*WriteResult, error)

UpdatePaths updates the document using the given data. The values at the given field paths are replaced, but other fields of the stored document are untouched.

Example
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	tenn := client.Doc("States/Tennessee")
	wr, err := tenn.UpdatePaths(ctx, []firestore.FieldPathUpdate{
		{Path: []string{"pop"}, Value: 6.6},
		// This odd field path cannot be expressed using the dot-separated form:
		{Path: []string{".", "*", "/"}, Value: "odd"},
	})
	if err != nil {
		// TODO: Handle error.
	}
	fmt.Println(wr.UpdateTime)
}
Output:

func (*DocumentRef) UpdateStruct

func (d *DocumentRef) UpdateStruct(ctx context.Context, fieldPaths []string, data interface{}, preconds ...Precondition) (*WriteResult, error)

UpdateStruct updates the given field paths of the stored document from the fields of data, which must be a struct or a pointer to a struct. Other fields of the stored document are untouched. See DocumentRef.Create for the acceptable values of the struct's fields.

Each element of fieldPaths is a single field or a dot-separated sequence of fields, none of which contain the runes "˜*/[]".

If an element of fieldPaths does not have a corresponding field in the struct, that key is deleted from the stored document.

UpdateStruct returns an error if the document does not exist.

Example
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	type State struct {
		Capital    string  `firestore:"capital"`
		Population float64 `firestore:"pop"` // in millions
	}

	tenn := client.Doc("States/Tennessee")
	wr, err := tenn.UpdateStruct(ctx, []string{"pop"}, State{
		Capital:    "does not matter",
		Population: 6.6,
	})
	if err != nil {
		// TODO: Handle error.
	}
	fmt.Println(wr.UpdateTime)
}
Output:

type DocumentSnapshot

type DocumentSnapshot struct {
	// The DocumentRef for this document.
	Ref *DocumentRef

	// Read-only. The time at which the document was created.
	// Increases monotonically when a document is deleted then
	// recreated. It can also be compared to values from other documents and
	// the read time of a query.
	CreateTime time.Time

	// Read-only. The time at which the document was last changed. This value
	// is initally set to CreateTime then increases monotonically with each
	// change to the document. It can also be compared to values from other
	// documents and the read time of a query.
	UpdateTime time.Time
	// contains filtered or unexported fields
}

A DocumentSnapshot contains document data and metadata.

func (*DocumentSnapshot) Data

func (d *DocumentSnapshot) Data() map[string]interface{}

Data returns the DocumentSnapshot's fields as a map. It is equivalent to

var m map[string]interface{}
d.DataTo(&m)
Example
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	docsnap, err := client.Doc("States/Ohio").Get(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	ohioMap := docsnap.Data()
	fmt.Println(ohioMap["capital"])
}
Output:

func (*DocumentSnapshot) DataAt

func (d *DocumentSnapshot) DataAt(fieldPath string) (interface{}, error)

DataAt returns the data value denoted by fieldPath.

The fieldPath argument can be a single field or a dot-separated sequence of fields, and must not contain any of the runes "˜*/[]". Use DataAtPath instead for such a path.

See DocumentSnapshot.DataTo for how Firestore values are converted to Go values.

Example
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	docsnap, err := client.Doc("States/Ohio").Get(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	cap, err := docsnap.DataAt("capital")
	if err != nil {
		// TODO: Handle error.
	}
	fmt.Println(cap)
}
Output:

func (*DocumentSnapshot) DataAtPath

func (d *DocumentSnapshot) DataAtPath(fp FieldPath) (interface{}, error)

DataAtPath returns the data value denoted by the FieldPath fp.

Example
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	docsnap, err := client.Doc("States/Ohio").Get(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	pop, err := docsnap.DataAtPath([]string{"capital", "population"})
	if err != nil {
		// TODO: Handle error.
	}
	fmt.Println(pop)
}
Output:

func (*DocumentSnapshot) DataTo

func (d *DocumentSnapshot) DataTo(p interface{}) error

DataTo uses the document's fields to populate p, which can be a pointer to a map[string]interface{} or a pointer to a struct.

Firestore field values are converted to Go values as follows:

  • Null converts to nil.
  • Bool converts to bool.
  • String converts to string.
  • Integer converts int64. When setting a struct field, any signed or unsigned integer type is permitted except uint64. Overflow is detected and results in an error.
  • Double converts to float64. When setting a struct field, float32 is permitted. Overflow is detected and results in an error.
  • Bytes is converted to []byte.
  • Timestamp converts to time.Time.
  • GeoPoint converts to latlng.LatLng, where latlng is the package "google.golang.org/genproto/googleapis/type/latlng".
  • Arrays convert to []interface{}. When setting a struct field, the field may be a slice or array of any type and is populated recursively. Slices are resized to the incoming value's size, while arrays that are too long have excess elements filled with zero values. If the array is too short, excess incoming values will be dropped.
  • Maps convert to map[string]interface{}. When setting a struct field, maps of key type string and any value type are permitted, and are populated recursively.
  • References are converted to DocumentRefs.

Field names given by struct field tags are observed, as described in DocumentRef.Create.

Example
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	docsnap, err := client.Doc("States/Ohio").Get(ctx)
	if err != nil {
		// TODO: Handle error.
	}

	type State struct {
		Capital    string  `firestore:"capital"`
		Population float64 `firestore:"pop"` // in millions
	}

	var s State
	if err := docsnap.DataTo(&s); err != nil {
		// TODO: Handle error.
	}
	fmt.Println(s)
}
Output:

type FieldPath

type FieldPath []string

A FieldPath is a non-empty sequence of non-empty fields that reference a value.

A FieldPath value should only be necessary if one of the field names contains one of the runes ".˜*/[]". Most methods accept a simpler form of field path as a string in which the individual fields are separated by dots. For example,

[]string{"a", "b"}

is equivalent to the string form

"a.b"

but

[]string{"*"}

has no equivalent string form.

type FieldPathUpdate

type FieldPathUpdate struct {
	Path  FieldPath
	Value interface{}
}

A FieldPathUpdate describes an update to a value referred to by a FieldPath. See DocumentRef.Create for acceptable values. To delete a field, specify firestore.Delete as the value.

type Precondition

type Precondition interface {
	// contains filtered or unexported methods
}

A Precondition modifies a Firestore update or delete operation.

func Exists

func Exists(b bool) Precondition

Exists returns a Precondition that checks for the existence or non-existence of a resource before writing to it. If the check fails, the write does not occur.

func LastUpdateTime

func LastUpdateTime(t time.Time) Precondition

LastUpdateTime returns a Precondition that checks that a resource must exist and must have last been updated at the given time. If the check fails, the write does not occur.

type Query

type Query struct {
	// contains filtered or unexported fields
}

Query represents a Firestore query.

Query values are immutable. Each Query method creates a new Query; it does not modify the old.

func (Query) Documents

func (q Query) Documents(ctx context.Context) *DocumentIterator

Documents returns an iterator over the query's resulting documents.

Example
package main

import (
	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	q := client.Collection("States").Select("pop").
		Where("pop", ">", 10).
		OrderBy("pop", firestore.Desc).
		Limit(10)
	iter1 := q.Documents(ctx)
	_ = iter1 // TODO: Use iter1.

	// You can call Documents directly on a CollectionRef as well.
	iter2 := client.Collection("States").Documents(ctx)
	_ = iter2 // TODO: Use iter2.
}
Output:

Example (Path_methods)

This example is just like the one above, but illustrates how to use the XXXPath methods of Query for field paths that can't be expressed as a dot-separated string.

package main

import (
	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	q := client.Collection("Unusual").SelectPaths([]string{"*"}, []string{"[~]"}).
		WherePath([]string{"/"}, ">", 10).
		OrderByPath([]string{"/"}, firestore.Desc).
		Limit(10)
	iter1 := q.Documents(ctx)
	_ = iter1 // TODO: Use iter1.

	// You can call Documents directly on a CollectionRef as well.
	iter2 := client.Collection("States").Documents(ctx)
	_ = iter2 // TODO: Use iter2.
}
Output:

func (Query) EndAt

func (q Query) EndAt(fieldValues ...interface{}) Query

EndAt returns a new Query that specifies that results should end at the document with the given field values. See Query.StartAt for more information.

Calling EndAt overrides a previous call to EndAt or EndBefore.

func (Query) EndBefore

func (q Query) EndBefore(fieldValues ...interface{}) Query

EndBefore returns a new Query that specifies that results should end just before the document with the given field values. See Query.StartAt for more information.

Calling EndBefore overrides a previous call to EndAt or EndBefore.

func (Query) Limit

func (q Query) Limit(n int) Query

Limit returns a new Query that specifies the maximum number of results to return. It must not be negative.

func (Query) Offset

func (q Query) Offset(n int) Query

Offset returns a new Query that specifies the number of initial results to skip. It must not be negative.

func (Query) OrderBy

func (q Query) OrderBy(fieldPath string, dir Direction) Query

OrderBy returns a new Query that specifies the order in which results are returned. A Query can have multiple OrderBy/OrderByPath specifications. OrderBy appends the specification to the list of existing ones.

To order by document name, use the special field path DocumentID.

func (Query) OrderByPath

func (q Query) OrderByPath(fp FieldPath, dir Direction) Query

OrderByPath returns a new Query that specifies the order in which results are returned. A Query can have multiple OrderBy/OrderByPath specifications. OrderByPath appends the specification to the list of existing ones.

func (Query) Select

func (q Query) Select(fieldPaths ...string) Query

Select returns a new Query that specifies the field paths to return from the result documents.

func (Query) SelectPaths

func (q Query) SelectPaths(fieldPaths ...FieldPath) Query

SelectPaths returns a new Query that specifies the field paths to return from the result documents.

func (Query) StartAfter

func (q Query) StartAfter(fieldValues ...interface{}) Query

StartAfter returns a new Query that specifies that results should start just after the document with the given field values. See Query.StartAt for more information.

Calling StartAfter overrides a previous call to StartAt or StartAfter.

func (Query) StartAt

func (q Query) StartAt(fieldValues ...interface{}) Query

StartAt returns a new Query that specifies that results should start at the document with the given field values. The field path corresponding to each value is taken from the corresponding OrderBy call. For example, in

q.OrderBy("X", Asc).OrderBy("Y", Desc).StartAt(1, 2)

results will begin at the first document where X = 1 and Y = 2.

If an OrderBy call uses the special DocumentID field path, the corresponding value should be the document ID relative to the query's collection. For example, to start at the document "NewYork" in the "States" collection, write

client.Collection("States").OrderBy(DocumentID, firestore.Asc).StartAt("NewYork")

Calling StartAt overrides a previous call to StartAt or StartAfter.

func (Query) Where

func (q Query) Where(fieldPath, op string, value interface{}) Query

Where returns a new Query that filters the set of results. A Query can have multiple filters.

func (Query) WherePath

func (q Query) WherePath(fp FieldPath, op string, value interface{}) Query

WherePath returns a new Query that filters the set of results. A Query can have multiple filters.

type Queryer

type Queryer interface {
	// contains filtered or unexported methods
}

A Queryer is a Query or a CollectionRef. CollectionRefs act as queries whose results are all the documents in the collection.

type SetOption

type SetOption interface {
	// contains filtered or unexported methods
}

A SetOption modifies a Firestore set operation.

var MergeAll SetOption = merge{/* contains filtered or unexported fields */}

MergeAll is a SetOption that causes all the field paths given in the data argument to Set to be overwritten. It is not supported for struct data.

func Merge

func Merge(fieldPaths ...string) SetOption

Merge returns a SetOption that causes only the given field paths to be overwritten. Other fields on the existing document will be untouched. It is an error if a provided field path does not refer to a value in the data passed to Set.

Each element of fieldPaths must be a single field or a dot-separated sequence of fields, none of which contain the runes "˜*/[]". Use MergePaths instead for such paths.

func MergePaths

func MergePaths(fps ...FieldPath) SetOption

MergePaths returns a SetOption that causes only the given field paths to be overwritten. Other fields on the existing document will be untouched. It is an error if a provided field path does not refer to a value in the data passed to Set.

type Transaction

type Transaction struct {
	// contains filtered or unexported fields
}

Transaction represents a Firestore transaction.

func (*Transaction) Create

func (t *Transaction) Create(dr *DocumentRef, data interface{}) error

Create adds a Create operation to the Transaction. See DocumentRef.Create for details.

func (*Transaction) Delete

func (t *Transaction) Delete(dr *DocumentRef, opts ...Precondition) error

Delete adds a Delete operation to the Transaction. See DocumentRef.Delete for details.

func (*Transaction) Documents

func (t *Transaction) Documents(q Queryer) *DocumentIterator

Documents returns a DocumentIterator based on given Query or CollectionRef. The results will be in the context of the transaction.

func (*Transaction) Get

Get gets the document in the context of the transaction.

func (*Transaction) Set

func (t *Transaction) Set(dr *DocumentRef, data interface{}, opts ...SetOption) error

Set adds a Set operation to the Transaction. See DocumentRef.Set for details.

func (*Transaction) UpdateMap

func (t *Transaction) UpdateMap(dr *DocumentRef, data map[string]interface{}, opts ...Precondition) error

UpdateMap adds a new Update operation to the Transaction. See DocumentRef.UpdateMap for details.

func (*Transaction) UpdatePaths

func (t *Transaction) UpdatePaths(dr *DocumentRef, data []FieldPathUpdate, opts ...Precondition) error

UpdatePaths adds a new Update operation to the Transaction. See DocumentRef.UpdatePaths for details.

func (*Transaction) UpdateStruct

func (t *Transaction) UpdateStruct(dr *DocumentRef, fieldPaths []string, data interface{}, opts ...Precondition) error

UpdateStruct adds a new Update operation to the Transaction. See DocumentRef.UpdateStruct for details.

type TransactionOption

type TransactionOption interface {
	// contains filtered or unexported methods
}

A TransactionOption is an option passed to Client.Transaction.

type WriteBatch

type WriteBatch struct {
	// contains filtered or unexported fields
}

A WriteBatch holds multiple database updates. Build a batch with the Create, Set, Update and Delete methods, then run it with the Commit method. Errors in Create, Set, Update or Delete are recorded instead of being returned immediately. The first such error is returned by Commit.

func (*WriteBatch) Commit

func (b *WriteBatch) Commit(ctx context.Context) ([]*WriteResult, error)

Commit applies all the writes in the batch to the database atomically. Commit returns an error if there are no writes in the batch, if any errors occurred in constructing the writes, or if the Commmit operation fails.

Example
package main

import (
	"fmt"

	"cloud.google.com/go/firestore"
	"golang.org/x/net/context"
)

func main() {
	ctx := context.Background()
	client, err := firestore.NewClient(ctx, "project-id")
	if err != nil {
		// TODO: Handle error.
	}
	defer client.Close()

	type State struct {
		Capital    string  `firestore:"capital"`
		Population float64 `firestore:"pop"` // in millions
	}

	ny := client.Doc("States/NewYork")
	ca := client.Doc("States/California")

	writeResults, err := client.Batch().
		Create(ny, State{Capital: "Albany", Population: 19.8}).
		Set(ca, State{Capital: "Sacramento", Population: 39.14}).
		Delete(client.Doc("States/WestDakota")).
		Commit(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	fmt.Println(writeResults)
}
Output:

func (*WriteBatch) Create

func (b *WriteBatch) Create(dr *DocumentRef, data interface{}) *WriteBatch

Create adds a Create operation to the batch. See DocumentRef.Create for details.

func (*WriteBatch) Delete

func (b *WriteBatch) Delete(dr *DocumentRef, opts ...Precondition) *WriteBatch

Delete adds a Delete operation to the batch. See DocumentRef.Delete for details.

func (*WriteBatch) Set

func (b *WriteBatch) Set(dr *DocumentRef, data interface{}, opts ...SetOption) *WriteBatch

Set adds a Set operation to the batch. See DocumentRef.Set for details.

func (*WriteBatch) UpdateMap

func (b *WriteBatch) UpdateMap(dr *DocumentRef, data map[string]interface{}, opts ...Precondition) *WriteBatch

UpdateMap adds an UpdateMap operation to the batch. See DocumentRef.UpdateMap for details.

func (*WriteBatch) UpdatePaths

func (b *WriteBatch) UpdatePaths(dr *DocumentRef, data []FieldPathUpdate, opts ...Precondition) *WriteBatch

UpdatePaths adds an UpdatePaths operation to the batch. See DocumentRef.UpdatePaths for details.

func (*WriteBatch) UpdateStruct

func (b *WriteBatch) UpdateStruct(dr *DocumentRef, fieldPaths []string, data interface{}, opts ...Precondition) *WriteBatch

UpdateStruct adds an UpdateStruct operation to the batch. See DocumentRef.UpdateStruct for details.

type WriteResult

type WriteResult struct {
	// The time at which the document was updated, or created if it did not
	// previously exist. Writes that do not actually change the document do
	// not change the update time.
	UpdateTime time.Time
}

A WriteResult is returned by methods that write documents.

Directories

Path Synopsis
Package firestore is an auto-generated package for the Google Cloud Firestore API.
Package firestore is an auto-generated package for the Google Cloud Firestore API.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL