PHP code example of colopl / laravel-spanner

1. Go to this page and download the library: Download colopl/laravel-spanner library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

colopl / laravel-spanner example snippets


[
    'connections' => [
        'spanner' => [
            'driver' => 'spanner',
            'instance' => '<Cloud Spanner instanceId here>',
            'database' => '<Cloud Spanner database name here>',
        ]
    ]
];

$conn = DB::connection('spanner');
$conn->...

[
    'connections' => [
        'spanner' => [
            'driver' => 'spanner',
            'instance' => '<Cloud Spanner instanceId here>',
            'database' => '<Cloud Spanner database name here>',
            
            // Spanner Client configurations
            'client' => [
                'projectId' => 'xxx',
                'requestTimeout' => 60, // seconds
                ...
            ],
            
            // Isolation level for transactions ('SERIALIZABLE' | 'REPEATABLE READ' | null (default))
            'isolation_level' => 'SERIALIZABLE',
        ]
    ]
];

// `default_sequence_kind` must be set in order to use auto increment
$schemaBuilder->setDatabaseOptions([
    'default_sequence_kind' => 'bit_reversed_positive',
]);

$schemaBuilder->create('user', function (Blueprint $table) {
    $table->integer('id')->primary()->autoIncrement();
});

// BAD: Do not use transactions manually!!
try {
    DB::beginTransaction();
    ...
    DB::commit();
} catch (\Throwable $ex) {
    DB::rollBack();
}

// GOOD: You should always use transaction method
DB::transaction(function() {
    ...
});

// implicit transaction (Read-only transaction)
$conn->select('SELECT ...');

// explicit transaction (Read-write transaction)
$conn->transaction(function() {
    $conn->select('SELECT ...');
});

// implicit transaction (Read-write transaction)
$conn->insert('INSERT ...');

// explicit transaction (Read-write transaction)
$conn->transaction(function() {
    $conn->insert('INSERT ...');
});

// There are four types of timestamp bounds: ExactStaleness, MaxStaleness, MinReadTimestamp and ReadTimestamp.
$timestampBound = new ExactStaleness(10);

// by Connection
$connection->selectWithTimestampBound('SELECT ...', $bindings, $timestampBound);

// by Query Builder
$queryBuilder
    ->withStaleness($timestampBound)
    ->get();

$timestampBound = new ExactStaleness(10);

// by Connection
$connection->snapshot($timestampBound, function() use ($connection) {
    $result1 = $connection->table('foo')->get();
    $result2 = $connection->table('bar')->get();

    return [$result1, $result2];
);

// by Model
User::where('foo', 'bar')
    ->snapshot($timestampBound)
    ->get();

// by Query Builder
$queryBuilder
    ->snapshot($timestampBound)
    ->get();

// Using Connection
$connection->selectWithOptions('SELECT ...', $bindings, ['dataBoostEnabled' => true]);

// Using Query Builder
$queryBuilder
    ->useDataBoost()
    ->setRequestTimeoutSeconds(60)
    ->get();

$requestPath = request()->path();
$tag = 'url=' . $requestPath;
$connection->setRequestTag($tag);
$connection->setTransactionTag($tag);

// by Connection
$connection->runPartitionedDml('UPDATE ...');


// by Query Builder
$queryBuilder->partitionedUpdate($values);
$queryBuilder->partitionedDelete();

$schemaBuilder->create('user_items', function (Blueprint $table) {
    $table->uuid('user_id');
    $table->uuid('id');
    $table->uuid('item_id');
    $table->integer('count');
    $table->timestamps();

    $table->primary(['user_id', 'id']);
    
    // interleaved table
    $table->interleaveInParent('users')->cascadeOnDelete();
    
    // interleaved index
    $table->index(['userId', 'created_at'])->interleaveIn('users');
});

$schemaBuilder->create('user', function (Blueprint $table) {
    $table->uuid('user_id');
    $table->timestamps();
    
    // create a policy
    $table->deleteRowsOlderThan(['updated_at'], 365);
});

$schemaBuilder->table('user', function (Blueprint $table) {
    // add policy
    $table->addRowDeletionPolicy('udpated_at', 100);

    // replace policy
    $table->replaceRowDeletionPolicy('udpated_at', 100);

    // drop policy
    $table->dropRowDeletionPolicy();
});

$schemaBuilder->create('user', function (Blueprint $table) {
    $table->integer('id')->useSequence();
});

$schemaBuilder->create('user_items', function (Blueprint $table) {
    $table->createSequence('sequence_name');
    $table->integer('id')->useSequence('sequence_name');
    
    $table->alterSequence('sequence_name')
        ->startWithCounter(100)
        ->skipRangeMin(1)
        ->skipRangeMax(10);
    
    $table->dropSequence('sequence_name');
});

$schemaBuilder->create('user_items', function (Blueprint $table) {
    $table->createChangeStream('stream_name')
        ->for('user_items', ['userId', 'userItemId'])
        ->retentionPeriod('7d')
        ->valueCaptureType(ChangeStreamValueCaptureType::NewValues)
        ->excludeTtlDeletes(true);

    $table->createChangeStream('stream_name')
        ->excludeInsert(true)
        ->excludeUpdate(true)
        ->excludeDelete(true);
    
    $table->dropChangeStream('stream_name');
});

$schemaBuilder->create('user', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->string('name');
    // adds an invisible column for full text search
    $table->tokenList('UserNameTokens', TokenizerFunction::FullText, 'name', ['language_tag' => 'en']);
    
    // adds a SEARCH INDEX
    $table->fullText(['UserNameTokens']);
});

User::query()->searchFullText('UserNameTokens', 'John OR Kevin', ['enhance_query' => true])->get();

$schemaBuilder->table('user_items', function (Blueprint $table) {
    $table->index('userId')
        // Interleave in parent table
        ->interleaveIn('user')
        // Add null filtering
        ->nullFiltered()
        // Add storing
        ->storing(['itemId', 'count']);
});

$schemaBuilder->createQueue('Jobs', function (Blueprint $queue) {
    $queue->string('MessageId', 36)->primary();
    $queue->string('Payload', 'max');
});

$schemaBuilder->createQueue('UserTasks', function (Blueprint $queue) {
    $queue->string('UserId', 36);
    $queue->string('MessageId', 36);
    $queue->string('Payload', 'max');
    $queue->primary(['UserId', 'MessageId']);
    $queue->interleaveInParent('User')->cascadeOnDelete();
});

$schemaBuilder->dropQueue('UserTasks');

$schemaBuilder->createQueue('Jobs', function (Blueprint $queue) {
    $queue->string('MessageId', 36);
    $queue->timestamp('DeliverTime');
    $queue->string('Payload', 'max');
    $queue->primary(['MessageId', 'DeliverTime']);
    $queue->deleteRowsOlderThan('DeliverTime', 7);
});

use Colopl\Spanner\Schema\QueueDefinition;

$schemaBuilder->createQueue('Jobs', function (Blueprint $queue, QueueDefinition $definition) {
    // Collect messages without delivering them yet.
    $definition->disableDelivery(true);

    $queue->string('MessageId', 36)->primary();
    $queue->string('Payload', 'max');
});

$schemaBuilder->table('Jobs', function (Blueprint $queue) {
    $queue->alterQueue()->disableDelivery(true);
});

// Passing null resets an option back to its default.
$schemaBuilder->table('Jobs', function (Blueprint $queue) {
    $queue->alterQueue()->disableDelivery(null);
});

$schemaBuilder->hasQueue('Jobs'); // true

foreach ($schemaBuilder->getQueues() as $queue) {
    echo $queue['name'], ' => ', $queue['parent'] ?? '-', PHP_EOL;
}

[
    'connections' => [
        'spanner' => [
            'driver' => 'spanner',
            // Database connection from config/database.php. Defaults to the default connection.
            'connection' => 'spanner',
            // Name of the Spanner queue, as created above.
            'queue' => 'Jobs',
            // Seconds a reserved job stays invisible before it is delivered again.
            'retry_after' => 90,
            // Seconds a single receiving call waits for messages.
            'block_for' => 20,
            'after_commit' => false,
        ],
    ],
];

class ProcessUserTask implements ShouldQueue, ProvidesInterleaveKeys
{
    public function __construct(private User $user) {}

    public function getInterleaveKeyValues(): array
    {
        return ['UserId' => $this->user->getKey()];
    }
}

$queue->pushRaw($payload, 'UserTasks', ['keys' => ['UserId' => $userId]]);

DB::connection('spanner')->transaction(function () use ($user) {
    $user->save();
    // Never delivered if the transaction is rolled back.
    ProcessSignup::dispatch($user);
});

$queryBuilder->insertUsingMutation($values);
$queryBuilder->updateUsingMutation($values);
$queryBuilder->insertOrUpdateUsingMutation($values);
$queryBuilder->deleteUsingMutation($values);
ini
grpc.enable_fork_support=1