Cloud Spanner Client - Class Database (1.66.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
NameDescription
connection Google\Cloud\Spanner\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 Google\Cloud\Spanner\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 Google\Cloud\Spanner\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 Google\Cloud\Spanner\Database::reload() to refresh the cached value.

Example:

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

[optional] Configuration options.

Returns
TypeDescription
int|null

backups

List completed and pending backups belonging to this database.

Example:

$backups = $database->backups();
Parameters
NameDescription
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
TypeDescription
Google\Cloud\Core\Iterator\ItemIterator<\google\cloud\spanner\backup>

createBackup

Create a backup for this database.

Example:

$operation = $database->createBackup('my-backup', new \DateTime('+7 hours'));
Parameters
NameDescription
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
TypeDescription
Google\Cloud\Core\LongRunning\LongRunningOperation<\google\cloud\spanner\backup>

name

Return the fully-qualified database name.

Example:

$name = $database->name();
Returns
TypeDescription
string

info

See also:

Parameter
NameDescription
options array

[optional] Configuration options.

Returns
TypeDescription
array

reload

See also:

Parameter
NameDescription
options array

[optional] Configuration options.

Returns
TypeDescription
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
NameDescription
options array

[optional] Configuration options.

Returns
TypeDescription
bool

create

Parameters
NameDescription
options array

Configuration Options

↳ statements string[]

Additional DDL statements.

Returns
TypeDescription
Google\Cloud\Core\LongRunning\LongRunningOperation<\google\cloud\spanner\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
NameDescription
backup Google\Cloud\Spanner\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
TypeDescription
Google\Cloud\Core\LongRunning\LongRunningOperation<\google\cloud\spanner\database>

updateDatabase

Parameters
NameDescription
options array

Configuration Options

↳ enableDropProtection bool

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

Returns
TypeDescription
Google\Cloud\Core\LongRunning\LongRunningOperation<\google\cloud\spanner\database>

updateDdl

Parameters
NameDescription
statement string

A DDL statements to run against a database.

options array

[optional] Configuration options.

Returns
TypeDescription
Google\Cloud\Core\LongRunning\LongRunningOperation

updateDdlBatch

Parameters
NameDescription
statements string[]

A list of DDL statements to run against a database.

options array

[optional] Configuration options.

Returns
TypeDescription
Google\Cloud\Core\LongRunning\LongRunningOperation

drop

Parameter
NameDescription
options array

[optional] Configuration options.

Returns
TypeDescription
void

ddl

Parameter
NameDescription
options array

[optional] Configuration options.

Returns
TypeDescription
array

iam

Manage the database IAM policy

Example:

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

snapshot

Parameters
NameDescription
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.

Returns
TypeDescription
Google\Cloud\Spanner\Snapshot

transaction

Parameters
NameDescription
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
TypeDescription
Google\Cloud\Spanner\Transaction

runTransaction

Parameters
NameDescription
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
TypeDescription
mixedThe return value of `$operation`.

insert

See also:

Parameters
NameDescription
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 the upstream documentation. Please note, if using the priority setting you may utilize the constants available on Google\Cloud\Spanner\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
TypeDescription
Google\Cloud\Spanner\TimestampThe commit Timestamp.

insertBatch

See also:

Parameters
NameDescription
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 the upstream documentation. Please note, if using the priority setting you may utilize the constants available on Google\Cloud\Spanner\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
TypeDescription
Google\Cloud\Spanner\TimestampThe commit Timestamp.

update

See also:

Parameters
NameDescription
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 the upstream documentation. Please note, if using the priority setting you may utilize the constants available on Google\Cloud\Spanner\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
TypeDescription
Google\Cloud\Spanner\TimestampThe commit Timestamp.

updateBatch

See also:

Parameters
NameDescription
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 the upstream documentation. Please note, if using the priority setting you may utilize the constants available on Google\Cloud\Spanner\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
TypeDescription
Google\Cloud\Spanner\TimestampThe commit Timestamp.

insertOrUpdate

See also:

Parameters
NameDescription
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 the upstream documentation. Please note, if using the priority setting you may utilize the constants available on Google\Cloud\Spanner\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
TypeDescription
Google\Cloud\Spanner\TimestampThe commit Timestamp.

insertOrUpdateBatch

See also:

Parameters
NameDescription
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 the upstream documentation. Please note, if using the priority setting you may utilize the constants available on Google\Cloud\Spanner\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
TypeDescription
Google\Cloud\Spanner\TimestampThe commit Timestamp.

replace

See also:

Parameters
NameDescription
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 the upstream documentation. Please note, if using the priority setting you may utilize the constants available on Google\Cloud\Spanner\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
TypeDescription
Google\Cloud\Spanner\TimestampThe commit Timestamp.

replaceBatch

See also:

Parameters
NameDescription
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 the upstream documentation. Please note, if using the priority setting you may utilize the constants available on Google\Cloud\Spanner\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
TypeDescription
Google\Cloud\Spanner\TimestampThe commit Timestamp.

delete

See also:

Parameters
NameDescription
table string

The table to mutate.

keySet Google\Cloud\Spanner\KeySet

The KeySet to identify rows to delete.

options array

Configuration options.

↳ requestOptions array

Request options. For more information on available options, please see the upstream documentation. Please note, if using the priority setting you may utilize the constants available on Google\Cloud\Spanner\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
TypeDescription
Google\Cloud\Spanner\TimestampThe commit Timestamp.

execute

Parameters
NameDescription
sql string

The query string to execute.

options array

Configuration Options. See 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.

↳ 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 Google\Cloud\Spanner\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 Google\Cloud\Spanner\ArrayType to declare the array parameter types. Likewise, for structs, use Google\Cloud\Spanner\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 the upstream documentation. Please note, if using the priority setting you may utilize the constants available on Google\Cloud\Spanner\V1\RequestOptions\Priority to set a value. Please note, the transactionTag setting will be ignored as it is not supported for read-only transactions.

Returns
TypeDescription
Google\Cloud\Spanner\Result

executePartitionedUpdate

Parameters
NameDescription
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 Google\Cloud\Spanner\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 Google\Cloud\Spanner\ArrayType to declare the array parameter types. Likewise, for structs, use Google\Cloud\Spanner\StructType.

↳ requestOptions array

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

Returns
TypeDescription
intThe number of rows modified.

read

See also:

Parameters
NameDescription
table string

The table name.

keySet Google\Cloud\Spanner\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 the upstream documentation. Please note, if using the priority setting you may utilize the constants available on Google\Cloud\Spanner\V1\RequestOptions\Priority to set a value. Please note, the transactionTag setting will be ignored as it is not supported for read-only transactions.

Returns
TypeDescription
Google\Cloud\Spanner\Result

sessionPool

Get the underlying session pool implementation.

Example:

$pool = $database->sessionPool();
Returns
TypeDescription
Google\Cloud\Spanner\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 Google\Cloud\Spanner\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
NameDescription
options array

[optional] Configuration options.

Returns
TypeDescription
Google\Cloud\Spanner\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 Google\Cloud\Spanner\Session\Session.

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

Parameter
NameDescription
sessionName string

The session's name.

Returns
TypeDescription
Google\Cloud\Spanner\Session\Session

identity

Retrieves the database's identity.

Returns
TypeDescription
array

connection

Returns the underlying connection.

Returns
TypeDescription
Google\Cloud\Spanner\Connection\ConnectionInterface

__debugInfo

Represent the class in a more readable and digestable fashion.

resumeOperation

{ Resume a Long Running Operation

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

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

}

Returns
TypeDescription
void

longRunningOperations

{ List long running operations.

Example:
```php
$operations = $database->longRunningOperations();
```

@param array $options [optional] {
    Configuration Options.

    @type string $name The name of the operation collection.
    @type string $filter The standard list filter.
    @type int $pageSize Maximum number of results to return per
          request.
    @type int $resultLimit Limit the number of results returned in total.
          **Defaults to** `0` (return all results).
    @type string $pageToken A previously-returned page token used to
          resume the loading of results from a specific point.
}
@return ItemIterator<InstanceConfiguration>

}

Returns
TypeDescription
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_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