Class: Google::Cloud::Firestore::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/google/cloud/firestore/client.rb

Overview

Client

The Cloud Firestore Client used is to access and manipulate the collections and documents in the Firestore database.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

# Get a document reference
nyc_ref = firestore.doc "cities/NYC"

firestore.batch do |b|
  b.update(nyc_ref, { name: "New York City" })
end

Access collapse

Operations collapse

Instance Method Summary collapse

Instance Method Details

#batch {|batch| ... } ⇒ CommitResponse

Perform multiple changes at the same time.

All changes are accumulated in memory until the block completes. Unlike transactions, batches don't lock on document reads, should only fail if users provide preconditions, and are not automatically retried. See Batch.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

firestore.batch do |b|
  # Set the data for NYC
  b.set("cities/NYC", { name: "New York City" })

  # Update the population for SF
  b.update("cities/SF", { population: 1000000 })

  # Delete LA
  b.delete("cities/LA")
end

Yields:

  • (batch)

    The block for reading data and making changes.

Yield Parameters:

  • batch (Batch)

    The write batch object for making changes.

Returns:

See Also:



338
339
340
341
342
# File 'lib/google/cloud/firestore/client.rb', line 338

def batch
  batch = Batch.from_client self
  yield batch
  batch.commit
end

#col(collection_path) ⇒ CollectionReference Also known as: collection

Retrieves a collection.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

# Get the cities collection
cities_col = firestore.col "cities"

# Get the document for NYC
nyc_ref = cities_col.doc "NYC"

Parameters:

  • collection_path (String)

    A string representing the path of the collection, relative to the document root of the database.

Returns:



131
132
133
134
135
136
137
138
# File 'lib/google/cloud/firestore/client.rb', line 131

def col collection_path
  if collection_path.to_s.split("/").count.even?
    fail ArgumentError, "collection_path must refer to a collection."
  end

  CollectionReference.from_path \
    "#{path}/documents/#{collection_path}", self
end

#cols {|collections| ... } ⇒ Enumerator<CollectionReference> Also known as: collections

Retrieves a list of collections.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

# Get the root collections
firestore.cols.each do |col|
  puts col.collection_id
end

Yields:

  • (collections)

    The block for accessing the collections.

Yield Parameters:

Returns:



102
103
104
105
106
107
108
109
# File 'lib/google/cloud/firestore/client.rb', line 102

def cols
  ensure_service!

  return enum_for(:cols) unless block_given?

  collection_ids = service.list_collections "#{path}/documents"
  collection_ids.each { |collection_id| yield col(collection_id) }
end

#database_idString

The database identifier for the Cloud Firestore database.

Returns:

  • (String)

    database identifier.



70
71
72
# File 'lib/google/cloud/firestore/client.rb', line 70

def database_id
  "(default)"
end

#doc(document_path) ⇒ DocumentReference Also known as: document

Retrieves a document reference.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

# Get a document
nyc_ref = firestore.doc "cities/NYC"

puts nyc_ref.document_id

Parameters:

  • document_path (String)

    A string representing the path of the document, relative to the document root of the database.

Returns:



159
160
161
162
163
164
165
166
167
# File 'lib/google/cloud/firestore/client.rb', line 159

def doc document_path
  if document_path.to_s.split("/").count.odd?
    fail ArgumentError, "document_path must refer to a document."
  end

  doc_path = "#{path}/documents/#{document_path}"

  DocumentReference.from_path doc_path, self
end

#document_idFieldPath

Creates a field path object representing the sentinel ID of a document. It can be used in queries to sort or filter by the document ID. See #document_id.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

# Get a collection reference
cities_col = firestore.col "cities"

# Create a query
query = cities_col.start_at("NYC").order(
  Google::Cloud::Firestore::FieldPath.document_id
)

query.get do |city|
  puts "#{city.document_id} has #{city[:population]} residents."
end

Returns:



236
237
238
# File 'lib/google/cloud/firestore/client.rb', line 236

def document_id
  FieldPath.document_id
end

#field_deleteFieldValue

Creates a field value object representing the deletion of a field in document data.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

# Get a document reference
nyc_ref = firestore.doc "cities/NYC"

nyc_ref.update({ name: "New York City",
                 trash: firestore.field_delete })

Returns:



277
278
279
# File 'lib/google/cloud/firestore/client.rb', line 277

def field_delete
  FieldValue.delete
end

#field_path(*fields) ⇒ Array<String>

Creates a field path object representing the nested fields for document data.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

user_snap = firestore.doc("users/frank").get

nested_field_path = firestore.field_path :favorites, :food
user_snap.get(nested_field_path) #=> "Pizza"

Returns:

  • (Array<String>)

    The fields.



256
257
258
# File 'lib/google/cloud/firestore/client.rb', line 256

def field_path *fields
  FieldPath.new(*fields)
end

#field_server_timeFieldValue

Creates a field value object representing set a field's value to the server timestamp when accessing the document data.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

# Get a document reference
nyc_ref = firestore.doc "cities/NYC"

nyc_ref.update({ name: "New York City",
                 updated_at: firestore.field_server_time })

Returns:

  • (FieldValue)

    The server time field value object.



298
299
300
# File 'lib/google/cloud/firestore/client.rb', line 298

def field_server_time
  FieldValue.server_time
end

#get_all(*docs) {|documents| ... } ⇒ Enumerator<DocumentSnapshot> Also known as: get_docs, get_documents, find

Retrieves a list of document snapshots.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

# Get and print city documents
cities = ["cities/NYC", "cities/SF", "cities/LA"]
firestore.get_all(cities).each do |city|
  puts "#{city.document_id} has #{city[:population]} residents."
end

Parameters:

  • docs (String, DocumentReference)

    One or more strings representing the path of the document, or document reference objects.

Yields:

  • (documents)

    The block for accessing the document snapshots.

Yield Parameters:

Returns:



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/google/cloud/firestore/client.rb', line 193

def get_all *docs
  ensure_service!

  return enum_for(:get_all, docs) unless block_given?

  doc_paths = Array(docs).flatten.map do |doc_path|
    coalesce_doc_path_argument doc_path
  end

  results = service.get_documents doc_paths
  results.each do |result|
    next if result.result.nil?
    yield DocumentSnapshot.from_batch_result(result, self)
  end
end

#project_idString

The project identifier for the Cloud Firestore database.

Returns:

  • (String)

    project identifier.



62
63
64
# File 'lib/google/cloud/firestore/client.rb', line 62

def project_id
  service.project
end

#transaction(max_retries: nil) {|transaction| ... } ⇒ CommitResponse

Create a transaction to perform multiple reads and writes that are executed atomically at a single logical point in time in a database.

All changes are accumulated in memory until the block completes. Transactions will be automatically retried when documents change before the transaction is committed. See Transaction.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

firestore.transaction do |tx|
  # Set the data for NYC
  tx.set("cities/NYC", { name: "New York City" })

  # Update the population for SF
  tx.update("cities/SF", { population: 1000000 })

  # Delete LA
  tx.delete("cities/LA")
end

Parameters:

  • max_retries (Integer)

    The maximum number of retries for transactions failed due to errors. Default is 5. Optional.

Yields:

  • (transaction)

    The block for reading data and making changes.

Yield Parameters:

  • transaction (Transaction)

    The transaction object for making changes.

Returns:

See Also:



380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# File 'lib/google/cloud/firestore/client.rb', line 380

def transaction max_retries: nil
  max_retries = 5 unless max_retries.is_a? Integer
  retries = 0
  backoff = 1.0

  transaction = Transaction.from_client self
  begin
    yield transaction
    transaction.commit
  rescue Google::Cloud::UnavailableError => err
    # Re-raise if deadline has passed
    raise err if retries >= max_retries
    # Sleep with incremental backoff
    sleep(backoff *= 1.3)
    # Create new transaction and retry
    transaction = Transaction.from_client \
      self, previous_transaction: transaction.transaction_id
    retries += 1
    retry
  rescue Google::Cloud::InvalidArgumentError => err
    # Return if a previous call has succeeded
    return nil if retries > 0
    # Re-raise error.
    raise err
  rescue => err
    # Rollback transaction when handling unexpected error
    transaction.rollback rescue nil
    # Re-raise error.
    raise err
  end
end