Cloud Spanner Client - Class Database (1.89.0)

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

Represents a Cloud Spanner Database.

Example:

use Google\Cloud\Spanner\SpannerClient;

$spanner = new SpannerClient();

$database = $spanner->connect('my-instance', 'my-database');
// Databases can also be connected to via an Instance.
use Google\Cloud\Spanner\SpannerClient;

$spanner = new SpannerClient();

$instance = $spanner->instance('my-instance');
$database = $instance->database('my-database');

Namespace

Google \ Cloud \ Spanner

Methods

__construct

Create an object representing a Database.

Parameters
Name Description
connection Connection\ConnectionInterface

The connection to the Cloud Spanner Admin API. This object is created by SpannerClient, and should not be instantiated outside of this client.

instance Instance

The instance in which the database exists.

lroConnection Google\Cloud\Core\LongRunning\LongRunningConnectionInterface

An implementation mapping to methods which handle LRO resolution in the service.

lroCallables array
projectId string

The project ID.

name string

The database name or ID.

sessionPool Session\SessionPoolInterface

[optional] The session pool implementation.

returnInt64AsObject bool

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

info array
databaseRole string

The user created database role which creates the session.

state

Return the database state.

When databases are created or restored, they may take some time before they are ready for use. This method allows for checking whether a database is ready. Note that this value is cached within the class instance, so if you are polling it, first call Database::reload() to refresh the cached value.

Example:

if ($database->state() === Database::STATE_READY) {
    echo 'Database is ready!';
}
Parameter
Name Description
options array

[optional] Configuration options.

Returns
Type Description
int|null

backups

List completed and pending backups belonging to this database.

Example:

$backups = $database->backups();
Parameters
Name Description
options array

Configuration options.

↳ filter string

The standard list filter. NOTE: This method always sets the database filter as a name of this database. User may provide additional filter expressions which would be appended in the form of "(database:

↳ 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<Backup>

createBackup

Create a backup for this database.

Example:

$operation = $database->createBackup('my-backup', new \DateTime('+7 hours'));
Parameters
Name Description
name string

The backup name.

expireTime DateTimeInterface

​The expiration time of the backup, with microseconds granularity that must be at least 6 hours and at most 366 days. Once the expireTime has passed, the backup is eligible to be automatically deleted by Cloud Spanner.

options array

[optional] Configuration options.

Returns
Type Description
Google\Cloud\Core\LongRunning\LongRunningOperation<Backup>

name

Return the fully-qualified database name.

Example:

$name = $database->name();
Returns
Type Description
string

info

See also:

Parameter
Name Description
options array

[optional] Configuration options.

Returns
Type Description
array

reload

See also:

Parameter
Name Description
options array

[optional] Configuration options.

Returns
Type Description
array

exists

Check if the database exists.

This method sends a service request.

NOTE: Requires https://www.googleapis.com/auth/spanner.admin scope.

Example:

if ($database->exists()) {
    echo 'Database exists!';
}
Parameter
Name Description
options array

[optional] Configuration options.

Returns
Type Description
bool

create

Parameters
Name Description
options array

Configuration Options

↳ statements string[]

Additional DDL statements.

Returns
Type Description
Google\Cloud\Core\LongRunning\LongRunningOperation<Database>

restore

Restores to this database from a backup.

NOTE: A restore operation can only be made to a non-existing database.

Example:

$operation = $database->restore($backup);
Parameters
Name Description
backup Backup|string

The backup to restore, given as a Backup instance or a string of the form projects/<project>/instances/<instance>/backups/<backup>.

options array

[optional] Configuration options.

Returns
Type Description
Google\Cloud\Core\LongRunning\LongRunningOperation<Database>

updateDatabase

Parameters
Name Description
options array

Configuration Options

↳ enableDropProtection bool

If true, delete operations for Database and Instance will be blocked. Defaults to false.

Returns
Type Description
Google\Cloud\Core\LongRunning\LongRunningOperation<Database>

updateDdl

Parameters
Name Description
statement string

A DDL statements to run against a database.

options array

[optional] Configuration options.

Returns
Type Description
Google\Cloud\Core\LongRunning\LongRunningOperation

updateDdlBatch

Parameters
Name Description
statements string[]

A list of DDL statements to run against a database.

options array

[optional] Configuration options.

Returns
Type Description
Google\Cloud\Core\LongRunning\LongRunningOperation

drop

Parameter
Name Description
options array

[optional] Configuration options.

Returns
Type Description
void

ddl

Parameter
Name Description
options array

[optional] Configuration options.

Returns
Type Description
array

iam

Manage the database IAM policy

Example:

$iam = $database->iam();
Returns
Type Description
Google\Cloud\Core\Iam\Iam

snapshot

Parameters
Name Description
options array

Configuration Options

See [ReadOnly](https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.TransactionOptions.ReadOnly)
for detailed description of available options.

Please note that only one of `$strong`, `$readTimestamp` or
`$exactStaleness` may be set in a request.
↳ returnReadTimestamp bool

If true, the Cloud Spanner-selected read timestamp is included in the Transaction message that describes the transaction.

↳ strong bool

Read at a timestamp where all previously committed transactions are visible.

↳ readTimestamp Timestamp

Executes all reads at the given timestamp.

↳ exactStaleness Duration

Represents a number of seconds. Executes all reads at a timestamp that is $exactStaleness old.

↳ minReadTimestamp Timestamp

Executes all reads at a timestamp >= min_read_timestamp. Only available when $options.singleUse is true.

↳ maxStaleness Duration

Read data at a timestamp >= NOW - max_staleness seconds. Guarantees that all writes that have committed more than the specified number of seconds ago are visible. Only available when $options.singleUse is true.

↳ singleUse bool

If true, a Transaction ID will not be allocated up front. Instead, the transaction will be considered "single-use", and may be used for only a single operation. Defaults to false.

↳ sessionOptions array

Session configuration and request options. Session labels may be applied using the labels key.

↳ directedReadOptions array

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

Returns
Type Description
Snapshot

transaction

Parameters
Name Description
options array

Configuration Options.

↳ singleUse bool

If true, a Transaction ID will not be allocated up front. Instead, the transaction will be considered "single-use", and may be used for only a single operation. Defaults to false.

↳ sessionOptions array

Session configuration and request options. Session labels may be applied using the labels key.

↳ tag string

A transaction tag. Requests made using this transaction will use this as the transaction tag.

Returns
Type Description
Transaction

runTransaction

Parameters
Name Description
operation callable

The operations to run in the transaction. Signature:* function (Transaction $transaction).

options array

Configuration Options

↳ maxRetries int

The number of times to attempt to apply the operation before failing. **Defaults to ** 10.

↳ singleUse bool

If true, a Transaction ID will not be allocated up front. Instead, the transaction will be considered "single-use", and may be used for only a single operation. Note that in a single-use transaction, only a single operation may be executed, and rollback is not available. Defaults to false.

↳ sessionOptions array

Session configuration and request options. Session labels may be applied using the labels key.

↳ tag string

A transaction tag. Requests made using this transaction will use this as the transaction tag.

Returns
Type Description
mixed The return value of `$operation`.

insert

See also:

Parameters
Name Description
table string

The table to mutate.

data array

The row data to insert.

options array

Configuration options.

↳ requestOptions array

Request options. For more information on available options, please see RequestOptions. Please note, if using the priority setting you may utilize the constants available on V1\RequestOptions\Priority to set a value. Please note, the transactionTag setting will be ignored as it is not supported for single-use transactions.

Returns
Type Description
Timestamp The commit Timestamp.

insertBatch

See also:

Parameters
Name Description
table string

The table to mutate.

dataSet array

The row data to insert.

options array

Configuration options.

↳ requestOptions array

Request options. For more information on available options, please see RequestOptions. Please note, if using the priority setting you may utilize the constants available on V1\RequestOptions\Priority to set a value. Please note, the transactionTag setting will be ignored as it is not supported for single-use transactions.

Returns
Type Description
Timestamp The commit Timestamp.

update

See also:

Parameters
Name Description
table string

The table to mutate.

data array

The row data to update.

options array

Configuration options.

↳ requestOptions array

Request options. For more information on available options, please see RequestOptions. Please note, if using the priority setting you may utilize the constants available on V1\RequestOptions\Priority to set a value. Please note, the transactionTag setting will be ignored as it is not supported for single-use transactions.

Returns
Type Description
Timestamp The commit Timestamp.

updateBatch

See also:

Parameters
Name Description
table string

The table to mutate.

dataSet array

The row data to update.

options array

Configuration options.

↳ requestOptions array

Request options. For more information on available options, please see RequestOptions. Please note, if using the priority setting you may utilize the constants available on V1\RequestOptions\Priority to set a value. Please note, the transactionTag setting will be ignored as it is not supported for single-use transactions.

Returns
Type Description
Timestamp The commit Timestamp.

insertOrUpdate

See also:

Parameters
Name Description
table string

The table to mutate.

data array

The row data to insert or update.

options array

Configuration options.

↳ requestOptions array

Request options. For more information on available options, please see RequestOptions. Please note, if using the priority setting you may utilize the constants available on V1\RequestOptions\Priority to set a value. Please note, the transactionTag setting will be ignored as it is not supported for single-use transactions.

Returns
Type Description
Timestamp The commit Timestamp.

insertOrUpdateBatch

See also:

Parameters
Name Description
table string

The table to mutate.

dataSet array

The row data to insert or update.

options array

Configuration options.

↳ requestOptions array

Request options. For more information on available options, please see RequestOptions. Please note, if using the priority setting you may utilize the constants available on V1\RequestOptions\Priority to set a value. Please note, the transactionTag setting will be ignored as it is not supported for single-use transactions.

Returns
Type Description
Timestamp The commit Timestamp.

replace

See also:

Parameters
Name Description
table string

The table to mutate.

data array

The row data to replace.

options array

Configuration options.

↳ requestOptions array

Request options. For more information on available options, please see RequestOptions. Please note, if using the priority setting you may utilize the constants available on V1\RequestOptions\Priority to set a value. Please note, the transactionTag setting will be ignored as it is not supported for single-use transactions.

Returns
Type Description
Timestamp The commit Timestamp.

replaceBatch

See also:

Parameters
Name Description
table string

The table to mutate.

dataSet array

The row data to replace.

options array

Configuration options.

↳ requestOptions array

Request options. For more information on available options, please see RequestOptions. Please note, if using the priority setting you may utilize the constants available on V1\RequestOptions\Priority to set a value. Please note, the transactionTag setting will be ignored as it is not supported for single-use transactions.

Returns
Type Description
Timestamp The commit Timestamp.

delete

See also:

Parameters
Name Description
table string

The table to mutate.

keySet KeySet

The KeySet to identify rows to delete.

options array

Configuration options.

↳ requestOptions array

Request options. For more information on available options, please see RequestOptions. Please note, if using the priority setting you may utilize the constants available on V1\RequestOptions\Priority to set a value. Please note, the transactionTag setting will be ignored as it is not supported for single-use transactions.

Returns
Type Description
Timestamp The commit Timestamp.

execute

Parameters
Name Description
sql string

The query string to execute.

options array

Configuration Options. See V1\TransactionOptions\PBReadOnly for detailed description of available transaction options. Please note that only one of $strong, $minReadTimestamp, $maxStaleness, $readTimestamp or $exactStaleness may be set in a request.

↳ parameters array

A key/value array of Query Parameters, where the key is represented in the query string prefixed by a @ symbol.

↳ types array

A key/value array of Query Parameter types. Generally, Google Cloud PHP can infer types. Explicit type declarations are required in the case of struct parameters, or when a null value exists as a parameter. Accepted values for primitive types are defined as constants on Database, and are as follows: Database::TYPE_BOOL, Database::TYPE_INT64, Database::TYPE_FLOAT64, Database::TYPE_TIMESTAMP, Database::TYPE_DATE, Database::TYPE_STRING, Database::TYPE_BYTES. If the value is an array, use ArrayType to declare the array parameter types. Likewise, for structs, use StructType.

↳ returnReadTimestamp bool

If true, the Cloud Spanner-selected read timestamp is included in the Transaction message that describes the transaction.

↳ strong bool

Read at a timestamp where all previously committed transactions are visible.

↳ minReadTimestamp Timestamp

Execute reads at a timestamp >= the given timestamp. Only available in single-use transactions.

↳ maxStaleness Duration

Read data at a timestamp >= NOW - the given timestamp. Only available in single-use transactions.

↳ readTimestamp Timestamp

Executes all reads at the given timestamp.

↳ exactStaleness Duration

Represents a number of seconds. Executes all reads at a timestamp that is $exactStaleness old.

↳ begin bool

If true, will begin a new transaction. If a read/write transaction is desired, set the value of $transactionType. If a transaction or snapshot is created, it will be returned as $result->transaction() or $result->snapshot(). Defaults to false.

↳ transactionType string

One of SessionPoolInterface::CONTEXT_READ or SessionPoolInterface::CONTEXT_READWRITE. If read/write is chosen, any snapshot options will be disregarded. If $begin is false, transaction type MUST be SessionPoolInterface::CONTEXT_READ. Defaults to SessionPoolInterface::CONTEXT_READ.

↳ sessionOptions array

Session configuration and request options. Session labels may be applied using the labels key.

↳ queryOptions array

Query optimizer configuration.

↳ queryOptions string

.optimizerVersion An option to control the selection of optimizer version. This parameter allows individual queries to pick different query optimizer versions. Specifying "latest" as a value instructs Cloud Spanner to use the latest supported query optimizer version. If not specified, Cloud Spanner uses optimizer version set at the client level options or set by the SPANNER_OPTIMIZER_VERSION environment variable. 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.

↳ requestOptions array

Request options. For more information on available options, please see RequestOptions. Please note, if using the priority setting you may utilize the constants available on V1\RequestOptions\Priority to set a value. Please note, the transactionTag setting will be ignored as it is not supported for read-only transactions.

↳ directedReadOptions array

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

Returns
Type Description
Result

mutationGroup

Create a new MutationGroup object.

Returns
Type Description
MutationGroup

batchWrite

Batches the supplied mutation groups in a collection of efficient transactions. All mutations in a group are committed atomically. However, mutations across groups can be committed non-atomically in an unspecified order and thus, they must be independent of each other. Partial failure is possible, i.e., some groups may have been committed successfully, while some may have failed. The results of individual batches are streamed into the response as the batches are applied.

BatchWrite requests are not replay protected, meaning that each mutation group may be applied more than once. Replays of non-idempotent mutations may have undesirable effects. For example, replays of an insert mutation may produce an already exists error or if you use generated or commit timestamp-based keys, it may result in additional rows being added to the mutation's table. We recommend structuring your mutation groups to be idempotent to avoid this issue.

Sample code:


Parameters
Name Description
mutationGroups array<MutationGroup>

Required. The groups of mutations to be applied.

options array

Optional.

↳ requestOptions array

Common options for this request.

↳ excludeTxnFromChangeStreams bool

Optional. When exclude_txn_from_change_streams is set to true: * * Mutations from all transactions in this batch write operation will not be recorded in change streams with DDL option allow_txn_exclusion=true that are tracking columns modified by these transactions. * * Mutations from all transactions in this batch write operation will be recorded in change streams with DDL option allow_txn_exclusion=false or not set that are tracking columns modified by these transactions. When exclude_txn_from_change_streams is set to false or not set, mutations from all transactions in this batch write operation will be recorded in all change streams that are tracking columns modified by these transactions.

executePartitionedUpdate

Parameters
Name Description
statement string

The DML statement to execute.

options array

Configuration Options.

↳ parameters array

A key/value array of Query Parameters, where the key is represented in the statement prefixed by a @ symbol.

↳ types array

A key/value array of Query Parameter types. Generally, Google Cloud PHP can infer types. Explicit type declarations are required in the case of struct parameters, or when a null value exists as a parameter. Accepted values for primitive types are defined as constants on Database, and are as follows: Database::TYPE_BOOL, Database::TYPE_INT64, Database::TYPE_FLOAT64, Database::TYPE_TIMESTAMP, Database::TYPE_DATE, Database::TYPE_STRING, Database::TYPE_BYTES. If the value is an array, use ArrayType to declare the array parameter types. Likewise, for structs, use StructType.

↳ requestOptions array

Request options. For more information on available options, please see RequestOptions. Please note, if using the priority setting you may utilize the constants available on V1\RequestOptions\Priority to set a value. Please note, the transactionTag setting will be ignored as it is not supported for partitioned DML.

Returns
Type Description
int The number of rows modified.

read

See also:

Parameters
Name Description
table string

The table name.

keySet KeySet

The KeySet to select rows.

columns array

A list of column names to return.

options array

Configuration Options.

See [TransactionOptions](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.TransactionOptions)
for detailed description of available transaction options.

Please note that only one of `$strong`, `$minReadTimestamp`,
`$maxStaleness`, `$readTimestamp` or `$exactStaleness` may be set in
a request.
↳ index string

The name of an index on the table.

↳ limit int

The number of results to return.

↳ returnReadTimestamp bool

If true, the Cloud Spanner-selected read timestamp is included in the Transaction message that describes the transaction.

↳ strong bool

Read at a timestamp where all previously committed transactions are visible.

↳ minReadTimestamp Timestamp

Execute reads at a timestamp >= the given timestamp. Only available in single-use transactions.

↳ maxStaleness Duration

Read data at a timestamp >= NOW - the given timestamp. Only available in single-use transactions.

↳ readTimestamp Timestamp

Executes all reads at the given timestamp.

↳ exactStaleness Duration

Represents a number of seconds. Executes all reads at a timestamp that is $exactStaleness old.

↳ begin bool

If true, will begin a new transaction. If a read/write transaction is desired, set the value of $transactionType. If a transaction or snapshot is created, it will be returned as $result->transaction() or $result->snapshot(). Defaults to false.

↳ transactionType string

One of SessionPoolInterface::CONTEXT_READ or SessionPoolInterface::CONTEXT_READWRITE. If read/write is chosen, any snapshot options will be disregarded. If $begin is false, transaction type MUST be SessionPoolInterface::CONTEXT_READ. Defaults to SessionPoolInterface::CONTEXT_READ.

↳ sessionOptions array

Session configuration and request options. Session labels may be applied using the labels key.

↳ requestOptions array

Request options. For more information on available options, please see RequestOptions. Please note, if using the priority setting you may utilize the constants available on V1\RequestOptions\Priority to set a value. Please note, the transactionTag setting will be ignored as it is not supported for read-only transactions.

↳ directedReadOptions array

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

Returns
Type Description
Result

sessionPool

Get the underlying session pool implementation.

Example:

$pool = $database->sessionPool();
Returns
Type Description
Session\SessionPoolInterface|null

close

Closes the database connection by returning the active session back to the session pool queue or by deleting the session if there is no pool associated.

It is highly important to ensure this is called as it is not always safe to rely soley on Database::__destruct().

Example:

$database->close();

__destruct

Closes the database connection.

createSession

Create a new session.

Sessions are handled behind the scenes and this method does not need to be called directly.

Parameter
Name Description
options array

[optional] Configuration options.

Returns
Type Description
Session\Session

session

Lazily instantiates a session. There are no network requests made at this point. To see the operations that can be performed on a session please see Session\Session.

Sessions are handled behind the scenes and this method does not need to be called directly.

Parameter
Name Description
sessionName string

The session's name.

Returns
Type Description
Session\Session

identity

Retrieves the database's identity.

Returns
Type Description
array

connection

Returns the underlying connection.

Returns
Type Description
Connection\ConnectionInterface

__debugInfo

Represent the class in a more readable and digestable fashion.

resumeOperation

{ Resume a Long Running Operation

Returns
Type Description
void

longRunningOperations

{ List long running operations.

Returns
Type Description
void

Constants

STATE_CREATING

Value: \Google\Cloud\Spanner\Admin\Database\V1\Database\State::CREATING

STATE_READY

Value: \Google\Cloud\Spanner\Admin\Database\V1\Database\State::READY

STATE_READY_OPTIMIZING

Value: \Google\Cloud\Spanner\Admin\Database\V1\Database\State::READY_OPTIMIZING

MAX_RETRIES

Value: 10

TYPE_BOOL

Value: \Google\Cloud\Spanner\V1\TypeCode::BOOL

TYPE_INT64

Value: \Google\Cloud\Spanner\V1\TypeCode::INT64

TYPE_FLOAT32

Value: \Google\Cloud\Spanner\V1\TypeCode::FLOAT32

TYPE_FLOAT64

Value: \Google\Cloud\Spanner\V1\TypeCode::FLOAT64

TYPE_TIMESTAMP

Value: \Google\Cloud\Spanner\V1\TypeCode::TIMESTAMP

TYPE_DATE

Value: \Google\Cloud\Spanner\V1\TypeCode::DATE

TYPE_STRING

Value: \Google\Cloud\Spanner\V1\TypeCode::STRING

TYPE_BYTES

Value: \Google\Cloud\Spanner\V1\TypeCode::BYTES

TYPE_ARRAY

Value: \Google\Cloud\Spanner\V1\TypeCode::PBARRAY

TYPE_STRUCT

Value: \Google\Cloud\Spanner\V1\TypeCode::STRUCT

TYPE_NUMERIC

Value: \Google\Cloud\Spanner\V1\TypeCode::NUMERIC

TYPE_PG_NUMERIC

Value: 'pgNumeric'

TYPE_PG_JSONB

Value: 'pgJsonb'

TYPE_JSON

Value: \Google\Cloud\Spanner\V1\TypeCode::JSON

TYPE_PG_OID

Value: 'pgOid'