Cloud Spanner Client - Class SpannerClient (1.78.0)

Reference documentation and code samples for the Cloud Spanner Client class SpannerClient.

Cloud Spanner is a highly scalable, transactional, managed, NewSQL database service. Find more information at Cloud Spanner docs.

In production environments, it is highly recommended that you make use of the Protobuf PHP extension for improved performance. Protobuf can be installed via PECL.

$ pecl install protobuf

Example:

use Google\Cloud\Spanner\SpannerClient;

$spanner = new SpannerClient();
// Using a Spanner Emulator
use Google\Cloud\Spanner\SpannerClient;

// Be sure to use the port specified when starting the emulator.
// `9010` is used as an example only.
putenv('SPANNER_EMULATOR_HOST=localhost:9010');

$spanner = new SpannerClient();
use Google\Cloud\Spanner\SpannerClient;
use Google\Cloud\Spanner\V1\DirectedReadOptions\ReplicaSelection\Type as ReplicaType;

$directedOptions = [
    'directedReadOptions' => [
        'includeReplicas' => [
            'replicaSelections' => [
                [
                    'location' => 'us-central1',
                    'type' => ReplicaType::READ_WRITE
                ]
            ],
            'autoFailoverDisabled' => false
        ]
    ]
];
$spanner = new SpannerClient($directedOptions);
use Google\Cloud\Spanner\SpannerClient;

$config = ['routeToLeader' => false];
$spanner = new SpannerClient($config);

Namespace

Google \ Cloud \ Spanner

Methods

__construct

Create a Spanner client. Please note that this client requires the gRPC extension.

Parameters
Name Description
config array

Configuration Options.

↳ apiEndpoint string

A hostname with optional port to use in place of the service's default endpoint.

↳ projectId string

The project ID from the Google Developer's Console.

↳ authCache CacheItemPoolInterface

A cache for storing access tokens. Defaults to a simple in memory implementation.

↳ authCacheOptions array

Cache configuration options.

↳ authHttpHandler callable

A handler used to deliver Psr7 requests specifically for authentication.

↳ credentialsFetcher FetchAuthTokenInterface

A credentials fetcher instance.

↳ httpHandler callable

A handler used to deliver Psr7 requests. Only valid for requests sent over REST.

↳ keyFile array

The contents of the service account credentials .json file retrieved from the Google Developer's Console. Ex: json_decode(file_get_contents($path), true).

↳ keyFilePath string

The full path to your service account credentials .json file retrieved from the Google Developers Console.

↳ requestTimeout float

Seconds to wait before timing out the request. Defaults to 0 with REST and 60 with gRPC.

↳ retries int

Number of retries for a failed request. Used only with default backoff strategy. Defaults to 3.

↳ scopes array

Scopes to be used for the request.

↳ quotaProject string

Specifies a user project to bill for access charges associated with the request.

↳ returnInt64AsObject bool

If true, 64 bit integers will be returned as a Google\Cloud\Core\Int64 object for 32 bit platform compatibility. Defaults to false.

↳ queryOptions array

Query optimizer configuration.

↳ queryOptions string

.optimizerVersion An option to control the selection of optimizer version. This parameter allows all execute queries to use a specific query optimizer version. Specifying "latest" as a value instructs Cloud Spanner to use the latest supported query optimizer version. query-level values will take precedence over any global settings. If the SPANNER_OPTIMIZER_VERSION environment variable is set, it will take second priority. This value is used when neither a query-level value nor the environment variable is set. Any other positive integer (from the list of supported optimizer versions) overrides the default optimizer version for query execution. Executing a SQL statement with an invalid optimizer version will fail with a syntax error (INVALID_ARGUMENT) status.

↳ useDiscreteBackoffs bool

false: use default backoff strategy (retry every failed request up to retries times). true: use discrete backoff settings based on called method name. Defaults to false.

↳ directedReadOptions array

Directed read options. Google\Cloud\Spanner\V1\DirectedReadOptions If using the replicaSelection::type setting, utilize the constants available in Google\Cloud\Spanner\V1\DirectedReadOptions\ReplicaSelection\Type to set a value.

↳ routeToLeader bool

Enable/disable Leader Aware Routing. Defaults to true (enabled).

batch

Get a Batch Client.

Batch Clients allow you to execute reads of very large data sets, spread across multiple partitions.

Example:

$batch = $spanner->batch('instance-id', 'database-id');

Database role configured in the optional $options array will be applied to the session created by this object.

$batch = $spanner->batch('instance-id', 'database-id', ['databaseRole' => 'Reader']);
Parameters
Name Description
instanceId string

The instance to connect to.

databaseId string

The database to connect to.

options array

Configuration options.

↳ databaseRole string

The user created database role which creates the session.

Returns
Type Description
Google\Cloud\Spanner\Batch\BatchClient

createInstanceConfiguration

Parameters
Name Description
baseConfig Google\Cloud\Spanner\InstanceConfiguration

The base configuration to extend for this custom instance configuration.

name string

The configuration name. Should be prefixed with "custom-".

replicas array<Google\Cloud\Spanner\Admin\Instance\V1\ReplicaInfo>|array

The replica information for the new instance configuration. This array must contain all the replicas from the base configuration, plus at least one from list of optional replicas of the base configuration. One of the replicas must be set as the default leader location.

options array

Configuration options.

↳ displayName string

Defaults to the value of $name.

↳ leaderOptions array

Allowed values of the "default_leader" schema option for databases in instances that use this instance configuration. Defaults to the leader options of the base configuration. Please note it may be possible for the default value to be an empty array when lazy loading the base configuration. To ensure the default value matches the upstream values please make sure to trigger a network request on the base configuration with either Google\Cloud\Spanner\InstanceConfiguration::reload() or Google\Cloud\Spanner\InstanceConfiguration::info().

↳ labels array

For more information, see Using labels to organize Google Cloud Platform resources.

↳ validateOnly bool

An option to validate, but not actually execute, the request, and provide the same response. Defaults to false.

Returns
Type Description
Google\Cloud\Core\LongRunning\LongRunningOperation<\google\cloud\spanner\instanceconfiguration>

instanceConfigurations

Parameters
Name Description
options array

Configuration Options.

↳ pageSize int

Maximum number of results to return per request.

↳ resultLimit int

Limit the number of results returned in total. Defaults to 0 (return all results).

↳ pageToken string

A previously-returned page token used to resume the loading of results from a specific point.

Returns
Type Description
Google\Cloud\Core\Iterator\ItemIterator<\google\cloud\spanner\instanceconfiguration>

instanceConfiguration

Parameters
Name Description
name string

The Configuration name.

options array
Returns
Type Description
Google\Cloud\Spanner\InstanceConfiguration

instanceConfigOperations

Lists instance configuration operations for the project.

Example:

$instanceConfigOperations = $spanner->instanceConfigOperations();
Parameters
Name Description
options array

Configuration options.

↳ pageSize int

The maximum number of resources contained in the underlying API response. The API may return fewer values in a page, even if there are additional values to be retrieved.

↳ resultLimit int

Limit the number of results returned in total. Defaults to 0 (return all results).

↳ pageToken string

A page token is used to specify a page of values to be returned. If no page token is specified (the default), the first page of values will be returned. Any page token used here must have been generated by a previous call to the API.

Returns
Type Description
Google\Cloud\Core\Iterator\ItemIterator<\google\cloud\core\longrunning\longrunningoperation>

createInstance

Parameters
Name Description
config Google\Cloud\Spanner\InstanceConfiguration

The configuration to use

name string

The instance name

options array

Configuration options

↳ displayName string

Defaults to the value of $name.

↳ nodeCount int

Defaults to 1.

↳ labels array

For more information, see Using labels to organize Google Cloud Platform resources.

Returns
Type Description
Google\Cloud\Core\LongRunning\LongRunningOperation<\google\cloud\spanner\instance>

instance

Lazily instantiate an instance.

Example:

$instance = $spanner->instance('my-instance');
Parameters
Name Description
name string

The instance name

instance array
Returns
Type Description
Google\Cloud\Spanner\Instance

instances

Parameters
Name Description
options array

Configuration options

↳ filter string

An expression for filtering the results of the request.

↳ pageSize int

Maximum number of results to return per request.

↳ resultLimit int

Limit the number of results returned in total. Defaults to 0 (return all results).

↳ pageToken string

A previously-returned page token used to resume the loading of results from a specific point.

Returns
Type Description
Google\Cloud\Core\Iterator\ItemIterator<\google\cloud\spanner\instance>

connect

Connect to a database to run queries or mutations.

Example:

$database = $spanner->connect('instance-id', 'database-id');

Database role configured on the $options parameter will be applied to the session created by this object. Note: When the databseRole and sessionPool both are present in the options, we prioritize the sessionPool.

$database = $spanner->connect('instance-id', 'database-id', ['databaseRole' => 'Reader']);
Parameters
Name Description
instance Google\Cloud\Spanner\Instance|string

The instance object or instance name.

name string

The database name.

options array

Configuration options.

↳ sessionPool SessionPoolInterface

A pool used to manage sessions.

↳ databaseRole string

The user created database role which creates the session.

Returns
Type Description
Google\Cloud\Spanner\Database

keySet

Create a new KeySet object

Example:

$keySet = $spanner->keySet();
// Create a keyset to return all rows in a table.
$keySet = $spanner->keySet(['all' => true]);
Parameters
Name Description
options array

Configuration Options

↳ keys array

A list of keys

↳ ranges KeyRange[]

A list of key ranges

↳ all bool

Whether to include all keys in a table

Returns
Type Description
Google\Cloud\Spanner\KeySet

keyRange

Create a new KeyRange object

Example:

$range = $spanner->keyRange();
// Ranges can be created with all data supplied.
$range = $spanner->keyRange([
    'startType' => KeyRange::TYPE_OPEN,
    'start' => ['Bob'],
    'endType' => KeyRange::TYPE_OPEN,
    'end' => ['Jill']
]);
Parameters
Name Description
options array

Configuration Options.

↳ startType string

Either "open" or "closed". Use constants KeyRange::TYPE_OPEN and KeyRange::TYPE_CLOSED for guaranteed correctness.

↳ start array

The key with which to start the range.

↳ endType string

Either "open" or "closed". Use constants KeyRange::TYPE_OPEN and KeyRange::TYPE_CLOSED for guaranteed correctness.

↳ end array

The key with which to end the range.

Returns
Type Description
Google\Cloud\Spanner\KeyRange

bytes

Create a Bytes object.

Example:

$bytes = $spanner->bytes('hello world');
Parameter
Name Description
bytes Psr\Http\StreamInterface|string|resource

The bytes value.

Returns
Type Description
Google\Cloud\Spanner\Bytes

date

Create a Date object.

Example:

$date = $spanner->date(new \DateTime('1995-02-04'));
Parameter
Name Description
date DateTimeInterface

The date value.

Returns
Type Description
Google\Cloud\Spanner\Date

timestamp

Create a Timestamp object.

Example:

$timestamp = $spanner->timestamp(new \DateTime('2003-02-05 11:15:02.421827Z'));
Parameters
Name Description
timestamp DateTimeInterface

The timestamp value.

nanoSeconds int

[optional] The number of nanoseconds in the timestamp.

Returns
Type Description
Google\Cloud\Spanner\Timestamp

numeric

Create a Numeric object.

Numeric represents a value with a data type of Numeric.

It supports a fixed 38 decimal digits of precision and 9 decimal digits of scale, and values are in the range of -99999999999999999999999999999.999999999 to 99999999999999999999999999999.999999999.

Example:

$numeric = $spanner->numeric('99999999999999999999999999999999999999.999999999');
Parameter
Name Description
value string|int|float

The Numeric value.

Returns
Type Description
numeric

pgNumeric

Represents a value with a data type of PG Numeric for the Postgres Dialect database.

It supports a value precision of up to 131072 digits before the decimal point and up to 16383 digits after the decimal point.

Example:

$pgNumeric = $spanner->pgNumeric('99999999999999999999999999999999999999.000000999999999');
Parameter
Name Description
value string|int|float|null

The PgNumeric value.

Returns
Type Description
Google\Cloud\Spanner\PgNumeric

pgJsonb

Represents a value with a data type of PG JSONB for the Postgres Dialect database.

Example:

$pgJsonb = $spanner->pgJsonb('}');
Parameter
Name Description
value mixed

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.

Example:

$int64 = $spanner->int64('9223372036854775807');
Parameter
Name Description
value string
Returns
Type Description
Google\Cloud\Core\Int64

duration

Create a Duration object.

Example:

$duration = $spanner->duration(100, 00001);
Parameters
Name Description
seconds int

The number of seconds in the duration.

nanos int

[optional] The number of nanoseconds in the duration. Defaults to 0.

Returns
Type Description
Google\Cloud\Spanner\Duration

commitTimestamp

Create a CommitTimestamp object.

Commit Timestamps may be used to implement server-side commit timestamp tracking in tables. Refer to Google\Cloud\Spanner\CommitTimestamp for usage details.

Example:

$commitTimestamp = $spanner->commitTimestamp();
Returns
Type Description
Google\Cloud\Spanner\CommitTimestamp

resumeOperation

{ Resume a Long Running Operation

Example:
```php
$operation = $spanner->resumeOperation($operationName);
```

@param string $operationName The Long Running Operation name.
@param array $info [optional] The operation data.
@return LongRunningOperation

}

Returns
Type Description
void

Constants

VERSION

Value: '1.78.0'

FULL_CONTROL_SCOPE

Value: 'https://www.googleapis.com/auth/spanner.data'

ADMIN_SCOPE

Value: 'https://www.googleapis.com/auth/spanner.admin'