PHP Class Google\Cloud\Datastore\DatastoreClient

Cloud Datastore supports multi-tenant applications through use of data partitions. A partition ID can be supplied when creating an instance of Cloud Datastore, and will be used in all operations executed in that instance. To enable the Google Cloud Datastore Emulator, set the PUBSUB_EMULATOR_HOST environment variable. Example: use Google\Cloud\ServiceBuilder; $cloud = new ServiceBuilder(); $datastore = $cloud->datastore(); DatastoreClient can be instantiated directly. use Google\Cloud\Datastore\DatastoreClient; $datastore = new DatastoreClient(); Multi-tenant applications can supply a namespace ID. use Google\Cloud\ServiceBuilder; $cloud = new ServiceBuilder(); $datastore = $cloud->datastore([ 'namespaceId' => 'my-application-namespace' ]); Using the Datastore Emulator use Google\Cloud\ServiceBuilder; Be sure to use the port specified when starting the emulator. 8900 is used as an example only. putenv('DATASTORE_EMULATOR_HOST=http://localhost:8900'); $cloud = new ServiceBuilder(); $datastore = $cloud->datastore();
Inheritance: use trait Google\Cloud\ClientTrait, use trait DatastoreTrait
Datei anzeigen Open project: GoogleCloudPlatform/gcloud-php

Protected Properties

Property Type Description
$connection ConnectionInterface
$operation Operation

Public Methods

Method Description
__construct ( array $config = [] ) Create a Datastore client.
allocateId ( Key $key, array $options = [] ) : Key Allocates an available ID to a given incomplete key
allocateIds ( array $keys, array $options = [] ) : Key[] Allocate available IDs to a set of keys
blob ( string | resource | StreamInterface $value ) : Blob Create a new Blob
delete ( Key $key, array $options = [] ) : string Delete an entity
deleteBatch ( array $keys, array $options = [] ) : array Delete multiple entities
entity ( Key | string $key, array $entity = [], array $options = [] ) : Entity Create an entity.
geoPoint ( float $latitude, float $longitude ) : GeoPoint Create a new GeoPoint
gqlQuery ( string $query, array $options = [] ) : GqlQuery Create a GqlQuery
insert ( Entity $entity, array $options = [] ) : string Insert an entity
insertBatch ( array $entities, array $options = [] ) : array Insert multiple entities
int64 ( string $value ) : Int64 Create an Int64 object. This can be used to work with 64 bit integers as a string value while on a 32 bit platform.
key ( string $kind, string | integer $identifier = null, array $options = [] ) : Key Create a single Key instance
keys ( string $kind, array $options = [] ) : Key[] Create multiple keys with the same configuration.
lookup ( Key $key, array $options = [] ) : Entity | null Retrieve an entity from the datastore
lookupBatch ( array $keys, array $options = [] ) : array Get multiple entities
query ( array $query = [] ) : Query Create a Query
runQuery ( Google\Cloud\Datastore\Query\QueryInterface $query, array $options = [] ) : Generator Run a query and return entities
transaction ( array $options = [] ) : Transaction Create a Transaction
update ( Entity $entity, array $options = [] ) : string Update an entity
updateBatch ( array $entities, array $options = [] ) : array Update multiple entities
upsert ( Entity $entity, array $options = [] ) : string Upsert an entity
upsertBatch ( array $entities, array $options = [] ) : array Upsert multiple entities

Private Methods

Method Description
parseSingleMutationResult ( array $res ) : string Handle mutation results

Method Details

__construct() public method

Create a Datastore client.
public __construct ( array $config = [] )
$config array [optional] { Configuration Options. @type string $projectId The project ID from the Google Developer's Console. @type CacheItemPoolInterface $authCache A cache for storing access tokens. **Defaults to** a simple in memory implementation. @type array $authCacheOptions Cache configuration options. @type callable $authHttpHandler A handler used to deliver Psr7 requests specifically for authentication. @type callable $httpHandler A handler used to deliver Psr7 requests. Only valid for requests sent over REST. @type string $keyFile The contents of the service account credentials .json file retrieved from the Google Developers Console. @type string $keyFilePath The full path to your service account credentials .json file retrieved from the Google Developers Console. @type int $retries Number of retries for a failed request. **Defaults to** `3`. @type array $scopes Scopes to be used for the request. @type string $namespaceId Partitions data under a namespace. Useful for [Multitenant Projects](https://cloud.google.com/datastore/docs/concepts/multitenancy). @type bool $returnInt64AsObject If true, 64 bit integers will be returned as a {@see \Google\Cloud\Int64} object for 32 bit platform compatibility. **Defaults to** false. }

allocateId() public method

Key MUST be in an incomplete state (i.e. including a kind but not an ID or name in its final pathElement). This method will execute a service request. Example: $key = $datastore->key('Person'); $keyWithAllocatedId = $datastore->allocateId($key);
See also: https://cloud.google.com/datastore/reference/rest/v1/projects/allocateIds allocateIds
public allocateId ( Key $key, array $options = [] ) : Key
$key Key The incomplete key.
$options array [optional] Configuration options.
return Key

allocateIds() public method

Keys MUST be in an incomplete state (i.e. including a kind but not an ID or name in their final pathElement). This method will execute a service request. Example: $keys = [ $datastore->key('Person'), $datastore->key('Person') ]; $keysWithAllocatedIds = $datastore->allocateIds($keys);
See also: https://cloud.google.com/datastore/reference/rest/v1/projects/allocateIds allocateIds
public allocateIds ( array $keys, array $options = [] ) : Key[]
$keys array The incomplete keys.
$options array [optional] Configuration options.
return Key[]

blob() public method

Example: $blob = $datastore->blob('hello world'); Blobs can be used to store binary data $blob = $datastore->blob(file_get_contents(__DIR__ .'/family-photo.jpg'));
public blob ( string | resource | StreamInterface $value ) : Blob
$value string | resource | StreamInterface
return Blob

delete() public method

Deletion by this method is non-transactional. If you need transaction support, use {@see \Google\Cloud\Datastore\Transaction::delete()}. Example: $key = $datastore->key('Person', 'Bob'); $datastore->delete($key);
public delete ( Key $key, array $options = [] ) : string
$key Key The identifier to delete.
$options array [optional] { Configuration options @type string $baseVersion Provides concurrency control. The version of the entity that this mutation is being applied to. If this does not match the current version on the server, the mutation conflicts. }
return string The updated entity version number.

deleteBatch() public method

Deletion by this method is non-transactional. If you need transaction support, use {@see \Google\Cloud\Datastore\Transaction::deleteBatch()}. Example: $keys = [ $datastore->key('Person', 'Bob'), $datastore->key('Person', 'John') ]; $datastore->deleteBatch($keys);
public deleteBatch ( array $keys, array $options = [] ) : array
$keys array The identifiers to delete.
$options array [optional] { Configuration options @type string $baseVersion Provides concurrency control. The version of the entity that this mutation is being applied to. If this does not match the current version on the server, the mutation conflicts. }
return array [Response Body](https://cloud.google.com/datastore/reference/rest/v1/projects/commit#response-body)

entity() public method

This method does not execute any service requests. Entities are created with a Datastore Key, or by specifying a Kind. Kinds are only allowed for insert operations. For any other case, you must specify a named key. If a kind is given, an ID will be automatically allocated for the entity upon insert. Additionally, if your entity requires a complex key elementPath, you must create the key separately. In complex applications you may want to create your own entity types. Google Cloud PHP supports subclassing of {@see \Google\Cloud\Datastore\Entity}. If the name of a subclass of Entity is given in the options array, an entity will be created with that class rather than the default class. Example: $key = $datastore->key('Person', 'Bob'); $entity = $datastore->entity($key, [ 'firstName' => 'Bob', 'lastName' => 'Testguy' ]); [snippet=array] Entity values can be assigned and accessed via the array syntax. $entity = $datastore->entity($key); $entity['firstName'] = 'Bob'; $entity['lastName'] = 'Testguy'; [snippet=object_accessor] Entity values can also be assigned and accessed via an object syntax. $entity = $datastore->entity($key); $entity->firstName = 'Bob'; $entity->lastName = 'Testguy'; [snippet=incomplete] Entities can be created with a Kind only, for inserting into datastore $entity = $datastore->entity('Person'); [snippet=custom_class] Entities can be custom classes extending the built-in Entity class. class Person extends Google\Cloud\Datastore\Entity } $person = $datastore->entity('Person', [ 'firstName' => 'Bob'], [ 'className' => Person::class ]); echo get_class($person); // Person [snippet=exclude_indexes] If you wish to exclude certain properties from datastore indexes, property names may be supplied in the method $options: $entity = $datastore->entity('Person', [ 'firstName' => 'Bob', 'dateOfBirth' => new DateTime('January 31, 1969') ], [ 'excludeFromIndexes' => [ 'dateOfBirth' ] ]);
See also: https://cloud.google.com/datastore/reference/rest/v1/Entity Entity
public entity ( Key | string $key, array $entity = [], array $options = [] ) : Entity
$key Key | string The key used to identify the record, or a string $kind.
$entity array [optional] The data to fill the entity with.
$options array [optional] { Configuration Options @type string $className The name of a class extending {@see \Google\Cloud\Datastore\Entity}. If provided, an instance of that class will be returned instead of Entity. If not set, {@see \Google\Cloud\Datastore\Entity} will be used. @type array $excludeFromIndexes A list of entity keys to exclude from datastore indexes. }
return Entity

geoPoint() public method

Example: $geoPoint = $datastore->geoPoint(37.4220, -122.0841);
See also: https://cloud.google.com/datastore/reference/rest/Shared.Types/LatLng LatLng
public geoPoint ( float $latitude, float $longitude ) : GeoPoint
$latitude float The latitude
$longitude float The longitude
return GeoPoint

gqlQuery() public method

Example: $query = $datastore->gqlQuery('SELECT * FROM Companies'); [snippet=bindings] Literals must be provided as bound parameters by default: $query = $datastore->gqlQuery('SELECT * FROM Companies WHERE companyName = @companyName', [ 'bindings' => [ 'companyName' => 'Bob' ] ]); [snippet=pos_bindings] Positional binding is also supported: $query = $datastore->gqlQuery('SELECT * FROM Companies WHERE companyName = @1 LIMIT 1', [ 'bindings' => [ 'Google' ] ]); [snippet=literals] While not recommended, you can use literals in your query string: $query = $datastore->gqlQuery("SELECT * FROM Companies WHERE companyName = 'Google'", [ 'allowLiterals' => true ]);
public gqlQuery ( string $query, array $options = [] ) : GqlQuery
$query string The [GQL Query](https://cloud.google.com/datastore/docs/apis/gql/gql_reference) string.
$options array [optional] { Configuration Options @type bool $allowLiterals Whether literal values will be allowed in the query string. Parameter binding is strongly encouraged over literals. **Defaults to** `false`. @type array $bindings An array of values to bind to the query string. Queries using Named Bindings should provide a key/value set, while queries using Positional Bindings must provide a simple array. @type string $readConsistency See [ReadConsistency](https://cloud.google.com/datastore/reference/rest/v1/ReadOptions#ReadConsistency). }
return Google\Cloud\Datastore\Query\GqlQuery

insert() public method

An entity with incomplete keys will be allocated an ID prior to insertion. Insert by this method is non-transactional. If you need transaction support, use {@see \Google\Cloud\Datastore\Transaction::insert()}. Example: $key = $datastore->key('Person', 'Bob'); $entity = $datastore->entity($key, ['firstName' => 'Bob']); $datastore->insert($entity);
public insert ( Entity $entity, array $options = [] ) : string
$entity Entity The entity to be inserted.
$options array [optional] Configuration options.
return string The entity version.

insertBatch() public method

Any entity with incomplete keys will be allocated an ID prior to insertion. Insert by this method is non-transactional. If you need transaction support, use {@see \Google\Cloud\Datastore\Transaction::insertBatch()}. Example: $entities = [ $datastore->entity('Person', ['firstName' => 'Bob']), $datastore->entity('Person', ['firstName' => 'John']) ]; $datastore->insertBatch($entities);
public insertBatch ( array $entities, array $options = [] ) : array
$entities array The entities to be inserted.
$options array [optional] Configuration options.
return array [Response Body](https://cloud.google.com/datastore/reference/rest/v1/projects/commit#response-body)

int64() public method

Example: $int64 = $datastore->int64('9223372036854775807');
public int64 ( string $value ) : Int64
$value string
return Google\Cloud\Int64

key() public method

Example: $key = $datastore->key('Person', 'Bob'); To override the internal detection of identifier type, you can specify which type to use. $key = $datastore->key('Robots', '1337', [ 'identifierType' => Key::TYPE_NAME ]);
See also: https://cloud.google.com/datastore/reference/rest/v1/Key Key
See also: https://cloud.google.com/datastore/reference/rest/v1/Key#PathElement PathElement
public key ( string $kind, string | integer $identifier = null, array $options = [] ) : Key
$kind string The kind.
$identifier string | integer [optional] The ID or name.
$options array [optional] { Configuration Options @type string $identifierType If omitted, type will be determined internally. In cases where any ambiguity can be expected (i.e. if you want to create keys with `name` but your values may pass PHP's `is_numeric()` check), this value may be explicitly set using `Key::TYPE_ID` or `Key::TYPE_NAME`. }
return Key

keys() public method

When inserting multiple entities, creating a set of keys at once can be useful. By defining the Key's kind and any ancestors up front, and allowing Cloud Datastore to allocate IDs, you can be sure that your entity identity and ancestry are correct and that there will be no collisions during the insert operation. Example: $keys = $datastore->keys('Person', [ 'number' => 10 ]); Ancestor paths can be specified $keys = $datastore->keys('Person', [ 'ancestors' => [ ['kind' => 'Person', 'name' => 'Grandpa Joe'], ['kind' => 'Person', 'name' => 'Dad Mike'] ], 'number' => 3 ]);
See also: https://cloud.google.com/datastore/reference/rest/v1/Key Key
See also: https://cloud.google.com/datastore/reference/rest/v1/Key#PathElement PathElement
public keys ( string $kind, array $options = [] ) : Key[]
$kind string The kind to use in the final path element.
$options array [optional] { Configuration Options @type array[] $ancestors An array of [PathElement](https://cloud.google.com/datastore/reference/rest/v1/Key#PathElement) arrays. Use to create [ancestor paths](https://cloud.google.com/datastore/docs/concepts/entities#ancestor_paths). @type int $number The number of keys to generate. @type string|int $id The ID for the last pathElement. @type string $name The Name for the last pathElement. }
return Key[]

lookup() public method

To lookup an entity inside a transaction, use {@see \Google\Cloud\Datastore\Transaction::lookup()}. Example: $key = $datastore->key('Person', 'Bob'); $entity = $datastore->lookup($key); if (!is_null($entity)) { echo $entity['firstName']; // 'Bob' }
public lookup ( Key $key, array $options = [] ) : Entity | null
$key Key The identifier to use to locate a desired entity.
$options array [optional] { Configuration Options @type string $readConsistency See [ReadConsistency](https://cloud.google.com/datastore/reference/rest/v1/ReadOptions#ReadConsistency). @type string $className The name of the class to return results as. Must be a subclass of {@see \Google\Cloud\Datastore\Entity}. If not set, {@see \Google\Cloud\Datastore\Entity} will be used. }
return Entity | null

lookupBatch() public method

To lookup entities inside a transaction, use {@see \Google\Cloud\Datastore\Transaction::lookupBatch()}. Example: $keys = [ $datastore->key('Person', 'Bob'), $datastore->key('Person', 'John') ]; $entities = $datastore->lookupBatch($keys); foreach ($entities['found'] as $entity) { echo $entity['firstName'] . PHP_EOL; }
public lookupBatch ( array $keys, array $options = [] ) : array
$keys array
$options array [optional] { Configuration Options @type string $readConsistency See [ReadConsistency](https://cloud.google.com/datastore/reference/rest/v1/ReadOptions#ReadConsistency). @type string|array $className If a string, the name of the class to return results as. Must be a subclass of {@see \Google\Cloud\Datastore\Entity}. If not set, {@see \Google\Cloud\Datastore\Entity} will be used. If an array is given, it must be an associative array, where the key is a Kind and the value is the name of a subclass of {@see \Google\Cloud\Datastore\Entity}. @type bool $sort If set to true, results in each set will be sorted to match the order given in $keys. **Defaults to** `false`. }
return array Returns an array with keys [`found`, `missing`, and `deferred`]. Members of `found` will be instance of {@see \Google\Cloud\Datastore\Entity}. Members of `missing` and `deferred` will be instance of {@see \Google\Cloud\Datastore\Key}.

query() public method

The Query class can be used as a builder, or it can accept a query representation at instantiation. Example: $query = $datastore->query();
public query ( array $query = [] ) : Query
$query array [Query](https://cloud.google.com/datastore/reference/rest/v1/projects/runQuery#query)
return Google\Cloud\Datastore\Query\Query

runQuery() public method

To query datastore inside a transaction, use {@see \Google\Cloud\Datastore\Transaction::runQuery()}. Example: $result = $datastore->runQuery($query); foreach ($result as $entity) { echo $entity['firstName']; }
public runQuery ( Google\Cloud\Datastore\Query\QueryInterface $query, array $options = [] ) : Generator
$query Google\Cloud\Datastore\Query\QueryInterface A query object.
$options array [optional] { Configuration Options @type string $className The name of the class to return results as. Must be a subclass of {@see \Google\Cloud\Datastore\Entity}. If not set, {@see \Google\Cloud\Datastore\Entity} will be used. @type string $readConsistency See [ReadConsistency](https://cloud.google.com/datastore/reference/rest/v1/ReadOptions#ReadConsistency). }
return Generator

transaction() public method

Example: $transaction = $datastore->transaction();
See also: https://cloud.google.com/datastore/docs/concepts/transactions Datastore Transactions
public transaction ( array $options = [] ) : Transaction
$options array [optional] Configuration options.
return Transaction

update() public method

Please note that updating a record in Cloud Datastore will replace the existing record. Adding, editing or removing a single property is only possible by first retrieving the entire entity in its existing state. Update by this method is non-transactional. If you need transaction support, use {@see \Google\Cloud\Datastore\Transaction::update()}. Example: $entity['firstName'] = 'John'; $datastore->update($entity);
public update ( Entity $entity, array $options = [] ) : string
$entity Entity The entity to be updated.
$options array [optional] { Configuration Options @type bool $allowOverwrite Entities must be updated as an entire resource. Patch operations are not supported. Because entities can be created manually, or obtained by a lookup or query, it is possible to accidentally overwrite an existing record with a new one when manually creating an entity. To provide additional safety, this flag must be set to `true` in order to update a record when the entity provided was not obtained through a lookup or query. **Defaults to** `false`. }
return string The entity version.

updateBatch() public method

Please note that updating a record in Cloud Datastore will replace the existing record. Adding, editing or removing a single property is only possible by first retrieving the entire entity in its existing state. Update by this method is non-transactional. If you need transaction support, use {@see \Google\Cloud\Datastore\Transaction::updateBatch()}. Example: $entities[0]['firstName'] = 'Bob'; $entities[1]['firstName'] = 'John'; $datastore->updateBatch($entities);
public updateBatch ( array $entities, array $options = [] ) : array
$entities array The entities to be updated.
$options array [optional] { Configuration Options @type bool $allowOverwrite Entities must be updated as an entire resource. Patch operations are not supported. Because entities can be created manually, or obtained by a lookup or query, it is possible to accidentally overwrite an existing record with a new one when manually creating an entity. To provide additional safety, this flag must be set to `true` in order to update a record when the entity provided was not obtained through a lookup or query. **Defaults to** `false`. }
return array [Response Body](https://cloud.google.com/datastore/reference/rest/v1/projects/commit#response-body)

upsert() public method

Upsert will create a record if one does not already exist, or overwrite existing record if one already exists. Please note that upserting a record in Cloud Datastore will replace the existing record, if one exists. Adding, editing or removing a single property is only possible by first retrieving the entire entity in its existing state. Upsert by this method is non-transactional. If you need transaction support, use {@see \Google\Cloud\Datastore\Transaction::upsert()}. Example: $key = $datastore->key('Person', 'Bob'); $entity = $datastore->entity($key, ['firstName' => 'Bob']); $datastore->upsert($entity);
public upsert ( Entity $entity, array $options = [] ) : string
$entity Entity The entity to be upserted.
$options array [optional] Configuration Options.
return string The entity version.

upsertBatch() public method

Upsert will create a record if one does not already exist, or overwrite an existing record if one already exists. Please note that upserting a record in Cloud Datastore will replace the existing record, if one exists. Adding, editing or removing a single property is only possible by first retrieving the entire entity in its existing state. Upsert by this method is non-transactional. If you need transaction support, use {@see \Google\Cloud\Datastore\Transaction::upsertBatch()}. Example: $keys = [ $datastore->key('Person', 'Bob'), $datastore->key('Person', 'John') ]; $entities = [ $datastore->entity($keys[0], ['firstName' => 'Bob']), $datastore->entity($keys[1], ['firstName' => 'John']) ]; $datastore->upsertBatch($entities);
public upsertBatch ( array $entities, array $options = [] ) : array
$entities array The entities to be upserted.
$options array [optional] Configuration Options.
return array [Response Body](https://cloud.google.com/datastore/reference/rest/v1/projects/commit#response-body)

Property Details

$connection protected_oe property

protected ConnectionInterface $connection
return ConnectionInterface

$operation protected_oe property

protected Operation,Google\Cloud\Datastore $operation
return Operation