Cloud Spanner Client - Class Transaction (1.60.0)

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

Manages interaction with Cloud Spanner inside a Transaction.

Transactions can be started via Google\Cloud\Spanner\Google\Cloud\Spanner\Database::runTransaction() (recommended) or via Google\Cloud\Spanner\Google\Cloud\Spanner\Database::transaction(). Transactions should always call Google\Cloud\Spanner\Google\Cloud\Spanner\Transaction::commit() or Google\Cloud\Spanner\Google\Cloud\Spanner\Transaction::rollback() to ensure that locks are released in a timely manner.

If you do not plan on performing any writes in your transaction, a Google\Cloud\Spanner\Google\Cloud\Spanner\Snapshot is a better solution which does not require a commit or rollback and does not lock any data.

Transactions may raise Google\Cloud\Spanner\Google\Cloud\Core\Exception\AbortedException errors when the transaction cannot complete for any reason. In this case, the entire operation (all reads and writes) should be reapplied atomically. Google Cloud PHP handles this transparently when using Google\Cloud\Spanner\Google\Cloud\Spanner\Database::runTransaction(). In other cases, it is highly recommended that applications implement their own retry logic.

Example:

use Google\Cloud\Spanner\SpannerClient;

$spanner = new SpannerClient();

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

$database->runTransaction(function (Transaction $t) {
    // do stuff.

    $t->commit();
});
// Get a transaction to manage manually.
$transaction = $database->transaction();

Methods

__construct

Parameters
NameDescription
operation Google\Cloud\Spanner\Operation

The Operation instance.

session Google\Cloud\Spanner\Session\Session

The session to use for spanner interactions.

transactionId string

[optional] The Transaction ID. If no ID is provided, the Transaction will be a Single-Use Transaction.

isRetry bool

Whether the transaction will automatically retry or not.

tag string

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

getCommitStats

Get the commit stats for this transaction. Commit stats are only available after commit has been called with return_commit_stats => true. If commit is called multiple times, only the commitStats for the last commit will be available.

Example:

$transaction->commit(["returnCommitStats" => true]);
$commitStats = $transaction->getCommitStats();
Returns
TypeDescription
arrayThe commit stats

insert

Enqueue an insert mutation.

Example:

$transaction->insert('Posts', [
    'ID' => 10,
    'title' => 'My New Post',
    'content' => 'Hello World'
]);
Parameters
NameDescription
table string

The table to insert into.

data array

The data to insert.

Returns
TypeDescription
Google\Cloud\Spanner\TransactionThe transaction, to enable method chaining.

insertBatch

Enqueue one or more insert mutations.

Example:

$transaction->insertBatch('Posts', [
    [
        'ID' => 10,
        'title' => 'My New Post',
        'content' => 'Hello World'
    ]
]);
Parameters
NameDescription
table string

The table to insert into.

dataSet array

The data to insert.

Returns
TypeDescription
Google\Cloud\Spanner\TransactionThe transaction, to enable method chaining.

update

Enqueue an update mutation.

Example:

$transaction->update('Posts', [
    'ID' => 10,
    'title' => 'My New Post [Updated!]',
    'content' => 'Modified Content'
]);
Parameters
NameDescription
table string

The table to update.

data array

The data to update.

Returns
TypeDescription
Google\Cloud\Spanner\TransactionThe transaction, to enable method chaining.

updateBatch

Enqueue one or more update mutations.

Example:

$transaction->updateBatch('Posts', [
    [
        'ID' => 10,
        'title' => 'My New Post [Updated!]',
        'content' => 'Modified Content'
    ]
]);
Parameters
NameDescription
table string

The table to update.

dataSet array

The data to update.

Returns
TypeDescription
Google\Cloud\Spanner\TransactionThe transaction, to enable method chaining.

insertOrUpdate

Enqueue an insert or update mutation.

Example:

$transaction->insertOrUpdate('Posts', [
    'ID' => 10,
    'title' => 'My New Post',
    'content' => 'Hello World'
]);
Parameters
NameDescription
table string

The table to insert into or update.

data array

The data to insert or update.

Returns
TypeDescription
Google\Cloud\Spanner\TransactionThe transaction, to enable method chaining.

insertOrUpdateBatch

Enqueue one or more insert or update mutations.

Example:

$transaction->insertOrUpdateBatch('Posts', [
    [
        'ID' => 10,
        'title' => 'My New Post',
        'content' => 'Hello World'
    ]
]);
Parameters
NameDescription
table string

The table to insert into or update.

dataSet array

The data to insert or update.

Returns
TypeDescription
Google\Cloud\Spanner\TransactionThe transaction, to enable method chaining.

replace

Enqueue an replace mutation.

Example:

$transaction->replace('Posts', [
    'ID' => 10,
    'title' => 'My New Post [Replaced]',
    'content' => 'Hello Moon'
]);
Parameters
NameDescription
table string

The table to replace into.

data array

The data to replace.

Returns
TypeDescription
Google\Cloud\Spanner\TransactionThe transaction, to enable method chaining.

replaceBatch

Enqueue one or more replace mutations.

Example:

$transaction->replaceBatch('Posts', [
    [
        'ID' => 10,
        'title' => 'My New Post [Replaced]',
        'content' => 'Hello Moon'
    ]
]);
Parameters
NameDescription
table string

The table to replace into.

dataSet array

The data to replace.

Returns
TypeDescription
Google\Cloud\Spanner\TransactionThe transaction, to enable method chaining.

delete

Enqueue an delete mutation.

Example:

$keySet = new KeySet([
    'keys' => [10]
]);

$transaction->delete('Posts', $keySet);
Parameters
NameDescription
table string

The table to mutate.

keySet Google\Cloud\Spanner\KeySet

The KeySet to identify rows to delete.

Returns
TypeDescription
Google\Cloud\Spanner\TransactionThe transaction, to enable method chaining.

executeUpdate

Execute a Cloud Spanner DML statement.

Data Manipulation Language (DML) allows you to execute statements which modify the state of the database (i.e. inserting, updating or deleting rows). DML supports INSERT, UPDATE and DELETE statements. For more on DML syntax, visit the DML syntax guide.

To execute a SQL query (such as a SELECT), use Google\Cloud\Spanner\Google\Cloud\Spanner\Transaction::execute().

Mutations performed via DML will be visible to subsequent operations within the same transaction. In other words, unlike with other mutation methods provided, you can read your uncommitted writes. If a transaction is not committed (either because of a rollback or error), the DML writes will not be applied.

Example:

$modifiedRowCount = $transaction->executeUpdate('UPDATE Posts SET content = @content WHERE id = @id', [
    'parameters' => [
        'content' => 'Hello world!',
        'id' => 10
    ]
]);
// Example of executeUpdate while using DML Structs
$statement = "UPDATE Posts SET title = 'Updated Title' " .
    "WHERE STRUCT<Title STRING, Content STRING>(Title, Content) = @post";

$postValue = new StructValue();
$postValue->add('Title', 'Updated Title')
          ->add('Content', 'Sample Content');

$postType = new StructType();
$postType->add('Title', Database::TYPE_STRING)
         ->add('Content', Database::TYPE_STRING);

$modifiedRowCount = $transaction->executeUpdate($statement, [
    'parameters' => [
        'post' => $postValue
    ],
    'types' => [
        'post' => $postType
    ]
]);
Parameters
NameDescription
sql string

The query string to execute.

options array

Configuration Options.

↳ 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\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\Google\Cloud\Spanner\ArrayType to declare the array parameter types. Likewise, for structs, use Google\Cloud\Spanner\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\Google\Cloud\Spanner\V1\RequestOptions\Priority to set a value. Please note, the transactionTag setting will be ignored as the transaction tag should have already been set when creating the transaction.

Returns
TypeDescription
intThe number of rows modified.

executeUpdateBatch

Execute multiple DML statements.

This method allows many statements to be run with lower latency than submitting them sequentially with Google\Cloud\Spanner\Google\Cloud\Spanner\Transaction::executeUpdate().

Statements are executed in order, sequentially. Execution will stop at the first failed statement; the remaining statements will not be run.

Please note that in the case of failure of any provided statement, this method will NOT throw an exception. Rather, check the successful key in the returned array. If successful is false, some statements may have been applied; you must inspect the results key in the returned array to find the first failed statement. Error details are returned inline with the first failed statement. Subsequent statements after an error will never be applied.

Example:

use Google\Cloud\Spanner\Database;

$res = $transaction->executeUpdateBatch([
    [
        'sql' => 'UPDATE posts SET post_status = @status WHERE author_id = @authorId',
        'parameters' => [
            'status' => 'unpublished',
            'authorId' => 1
        ]
    ], [
        'sql' => 'UPDATE authors SET author_permissions = @permissions WHERE author_id = @authorId',
        'parameters' => [
            'permissions' => null,
            'authorId' => 1
        ],
        'types' => [
            'permissions' => Database::TYPE_ARRAY
        ]
    ]
]);

if ($res->error()) {
    echo 'An error occurred: ' . $res->error()['status']['message'];
} else {
    echo 'Updated ' . array_sum($res->rowCounts()) . ' row(s) ' .
         'across ' . count($res->rowCounts()) . ' statement(s)';
}
Parameters
NameDescription
statements array[]

A list of DML statements to run. Each statement must contain a sql key, where the value is a DML string. If the DML contains placeholders, values are provided as a key/value array in key parameters. If parameter types are required, they must be provided in key 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 {@see \Google\Cloud\Spanner\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 {@see \Google\Cloud\Spanner\Google\Cloud\Spanner\ArrayType} to declare the array parameter types. Likewise, for structs, use {@see \Google\Cloud\Spanner\Google\Cloud\Spanner\StructType}.

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\Google\Cloud\Spanner\V1\RequestOptions\Priority to set a value. Please note, the transactionTag setting will be ignored as the transaction tag should have already been set when creating the transaction.

Returns
TypeDescription
Google\Cloud\Spanner\BatchDmlResult

rollback

Roll back a transaction.

Rolls back a transaction, releasing any locks it holds. It is a good idea to call this for any transaction that includes one or more Read or ExecuteSql requests and ultimately decides not to commit.

This closes the transaction, preventing any future API calls inside it.

Rollback will NOT error if the transaction is not found or was already aborted.

Example:

$transaction->rollback();
Parameter
NameDescription
options array

[optional] Configuration Options.

Returns
TypeDescription
void

commit

Commit and end the transaction.

It is advised that transactions be run inside Google\Cloud\Spanner\Google\Cloud\Spanner\Database::runTransaction() in order to take advantage of automated transaction retry in case of a transaction aborted error.

Example:

$transaction->commit();
Parameters
NameDescription
options array

Configuration Options.

↳ mutations array

An array of mutations to commit. May be used instead of or in addition to enqueing mutations separately.

↳ returnCommitStats bool

If true, commit statistics will be returned and accessible via Google\Cloud\Spanner\Google\Cloud\Spanner\Transaction::getCommitStats(). Defaults to false.

↳ 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\Google\Cloud\Spanner\V1\RequestOptions\Priority to set a value. Please note, the requestTag setting will be ignored as it is not supported for commit requests.

Returns
TypeDescription
Google\Cloud\Spanner\TimestampThe commit timestamp.

state

Retrieve the Transaction State.

Will be one of Transaction::STATE_ACTIVE, Transaction::STATE_COMMITTED, or Transaction::STATE_ROLLED_BACK.

Example:

$state = $transaction->state();
Returns
TypeDescription
int

isRetry

Check whether the current transaction is a retry transaction.

When using Google\Cloud\Spanner\Google\Cloud\Spanner\Database::runTransaction(), transactions are automatically retried when a conflict causes it to abort. In such cases, subsequent invocations of the transaction callable will provide a transaction where $transaction->isRetry() is true. This can be useful for debugging and understanding how code is working.

Example:

if ($transaction->isRetry()) {
    echo 'This is a retry transaction!';
}
Returns
TypeDescription
bool