Download the PHP package colopl/laravel-spanner without Composer

On this page you can find all versions of the php package colopl/laravel-spanner. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-spanner

laravel-spanner

Laravel database driver for Google Cloud Spanner

License Latest Stable Version Minimum PHP Version

Requirements

Installation

Put JSON credential file path to env variable: GOOGLE_APPLICATION_CREDENTIALS

Install via composer

Add connection config to config/database.php

That's all. You can use database connection as usual.

Additional Configurations

You can pass SpannerClient config options as below. For more information, please see Google Client Library docs

Recommended Setup

Please note that the following are not required, but are strongly recommended for better performance.

Unsupported features

Limitations

SQL Mode

Currently only supports Spanner running GoogleSQL (PostgreSQL mode is not supported).

Query

Eloquent

If you use interleaved keys, you MUST define them in the interleaveKeys property, or else you won't be able to save. For more detailed instructions, see Colopl\Spanner\Tests\Eloquent\ModelTest.

Additional Information

Migrations

Since Spanner recommends using UUID as a primary key, Blueprint::increments (and all of its variants) will create a column of type STRING(36) DEFAULT (GENERATE_UUID()) to generate and fill the column with a UUID and flag it as a primary key. If you want to use AUTO_INCREMENT, you can do so by specifying it directly like this:

Transactions

Google Cloud Spanner sometimes requests transaction retries (e.g. UNAVAILABLE, and ABORTED), even if the logic is correct. For that reason, please do not manage transactions manually.

You should always use the transaction method which handles retry requests internally.

Google Cloud Spanner creates transactions for all data operations even if you do not explicitly create transactions.

In particular, in the SELECT statement, the type of transaction varies depending on whether it is explicit or implicit.

Transaction type SELECT statement INSERT/UPDATE/DELETE statement
implicit transaction Read-only transaction with singleUse option Read-write transaction with singleUse option
explicit transaction Read-write transaction Read-write transaction

For more information, see Cloud Spanner Documentation about transactions

Stale reads

You can use Stale reads (timestamp bounds) as below.

Stale reads always runs as read-only transaction with singleUse option. So you can not run as read-write transaction.

Snapshot reads

You can use explicit Snapshot reads, either on Connection, or on Model or Builder instances. When running snapshot() on Connection, you pass a Closure that you can use to run multiple reads from within the same Snapshot.

Data Boost

Data boost creates snapshot and runs the query in parallel without affecting existing workloads.

You can read more about it here.

Below are some examples of how to use it.

[!NOTE] This creates a new snapshot request which does not share state with any ongoing transactions. This means, queries running with data boost will not take into account any changes made in the ongoing transaction.

Request Tags and Transaction Tags

Spanner allows you to attach tags to your queries and transactions that can be used for troubleshooting.

You can set request tags and transaction tags as below.

Data Types

Some data types of Google Cloud Spanner does not have corresponding built-in type of PHP. You can use following classes by Google Cloud PHP Client

When fetching rows, the library coverts the following column types

Note that if you execute a query without QueryBuilder, it will not have these conversions.

Partitioned DML

You can run partitioned DML as below.

However, Partitioned DML has some limitations. See Cloud Spanner Documentation about Partitioned DML for more information.

Interleave

You can define interleaved tables as below.

Row Deletion Policy

You can define row deletion policy as below.

Sequence

If you want a simple sequence to be used as a primary key, you can use useSequence() method. If useSequence() is called without providing a $name, a sequence with name user_id_sequence will be created with start_with_counter set with a random value between 1 and 1,000,000.

If you want more flexibility, you can also create, alter, and drop sequences directly as below.

Change Streams

Spanner supports Change Streams which allows you to listen to changes in the database. Change streams can be created/altered/dropped through the schema builder as shown below.

Full Text Search

Spanner supports Full Text Search which allows you to search for text in columns.

You can define a token list column and a search index for the column as below.

Once the schema has been applied, you can use the search methods in the query builder to search for text in the columns as below.

The methods available are searchFullText, searchSubstring, and searchNgrams.

Secondary Index Options

You can define Spanner specific index options like null filtering and storing as below.

Queues

Spanner supports Queues, a transactional messaging feature that lets you send and acknowledge messages atomically together with your other writes. This package ships a Laravel queue driver built on top of it.

[!IMPORTANT] Spanner queues require the Enterprise or Enterprise Plus edition. The Spanner emulator supports them from version 1.5.59, with a few differences described in Using the emulator. An instance is limited to 100 queues.

Creating a queue

Every Laravel queue name maps to one Spanner QUEUE object, which is created through the schema builder. The queue must have a Payload column, and every other column has to be part of the primary key. The driver expects a MessageId primary key and a Payload column holding the serialized job:

Payload has to be a STRING column. The driver writes the job's JSON as a string, so a BYTES payload, as $queue->binary('Payload') would create, is rejected by Spanner on the first push with "Value has type STRING which cannot be inserted into column Payload, which has type BYTES".

Spanner adds a DeliverTime column to every queue implicitly, so you don't declare it.

Queues can also be interleaved into a table. Interleaving requires the queue's primary key to be prefixed by the parent's key columns, positionally matching in name and type, so the queue gains key columns in front of MessageId (see Interleaved queues for what the driver needs in order to write them):

interleaveInParent() requires the parent row to exist for every message. interleaveIn() is part of the documented grammar as well, but the emulator rejects it for queues, so it has not been verified.

Expiring stale messages

A Row Deletion Policy can remove messages that nothing has picked up. The policy has to use a column that the queue declares itself, so the implicit DeliverTime has to be declared explicitly, as part of the primary key:

A message gets a fresh DeliverTime each time a job is reserved or released, so a job that keeps being retried does not expire. Only a message that has gone unhandled for the given number of days does.

Queue options are set on the QueueDefinition that the callback receives as its second argument. disableSend rejects all new messages, including the replacements this driver sends when reserving and releasing jobs, so workers cannot drain the queue while it is enabled. Stop producers instead when draining. disableDelivery pauses delivery to consumers:

Don't call $queue->createQueue() yourself in that callback, since the schema builder already did. A second call would declare a second queue.

Options can be changed afterwards with alterQueue():

Queues are not tables, so hasTable() and getTables() never report them. Use hasQueue() and getQueues() instead, the latter also telling which table a queue is interleaved in:

dropAllTables(), and with it db:wipe and migrate:fresh, drops queues too. Queues go first, since a table can't be dropped while a queue is interleaved in it.

Configuration

Add a spanner queue connection to config/queue.php:

retry_after works like it does for the database and redis drivers and must be longer than your longest job, otherwise the job will be processed twice. A job that declares a $timeout is covered without raising it for every job: its reserved message stays invisible for the $timeout plus 10 seconds when that is longer than retry_after. Jobs without a $timeout rely on retry_after alone, and queue:work --timeout is not visible to the driver, so keep retry_after above it.

block_for is the max_duration of the RECEIVE_<queue>() call. Receiving is a long running streaming query rather than a poll, so a worker blocks inside it until a message arrives or the duration elapses. A longer duration means fewer requests, but a worker can only react to queue:restart and to signals such as SIGTERM once the current call returns, so it also delays graceful shutdown by up to that long.

[!WARNING] As with the redis driver's block_for, avoid giving one worker several queues (queue:work spanner --queue=High,Low) while block_for is long. Queues are read in order, so an empty High makes the worker wait block_for seconds before it even looks at Low.

Interleaved queues

A queue interleaved into a table is keyed by that table's key columns followed by MessageId. These are the same interleave keys an Eloquent model declares in its $interleaveKeys property. No configuration names them: the job that is sent provides their values, and a received message brings its own.

A job sent to an interleaved queue implements Colopl\Spanner\Queue\ProvidesInterleaveKeys and returns a value for each key column, keyed by column name:

A dispatched job object is serialized into an opaque blob inside the payload, so the driver asks the job before the payload is built. A job that doesn't implement the interface is sent without interleave keys, which is right for a queue that is not interleaved, and which Spanner rejects for an interleaved one with an error naming the missing column. One connection can therefore serve queues of different shapes.

pushRaw() has no job to ask, so it takes the values directly:

queue:retry sends a failed job object back under the same parent row, because Laravel unserializes the job and asks the queue for its options. A job sent with pushRaw() has no job object, so queue:retry cannot recover its keys and Spanner rejects the retry. Send such a job again with pushRaw() and its keys instead.

Receiving selects every column of RECEIVE_<queue>(), and every column of a queue other than Payload is part of its primary key. The driver therefore takes a received message's key to be all of its columns except Payload, DeliverTime and those starting with Spanner, which RECEIVE_<queue>() adds (SpannerLeaseExpirationTimestamp, SpannerLeaseToken and SpannerLastBatchMessage). Don't give a queue's key columns names starting with Spanner.

Only newly sent jobs are asked. Reserving and releasing a job carry the key values of the message they came from, so a job never moves to a different parent row.

With interleaveInParent() the parent row must already exist when the message is sent, so send it in the same transaction that creates the parent.

Dispatching jobs transactionally

Because messages are rows, dispatching a job inside a transaction makes it part of that transaction. The job becomes deliverable only if the transaction commits, without needing the afterCommit dance:

How a job is dequeued and retried

Dequeuing. Each worker keeps one RECEIVE_<queue>(max_duration => block_for) stream open per queue and reads messages from it as queue:work asks for them, instead of polling. A stream is a single-use strong read, which is why messages cannot be received from inside a transaction. When a stream has reached its max_duration it is replaced rather than reused.

[!WARNING] On Cloud Spanner, an open stream can lease a burst of messages ahead of its worker. With slow jobs, unread messages can outlive their 10 second leases and incur growing redelivery backoff, delaying them even when other workers are idle.

Spanner hands out a message with a fixed, non-configurable 10 second lease, which is too short for most Laravel jobs, and PHP cannot renew it from a background thread while a job is running. The driver therefore uses the pattern Google documents for long running work, and reserves every message it receives:

  1. The attempt counter in the payload (attempts, which $job->attempts() returns) is incremented.
  2. In one read-write transaction, the received message is acknowledged (deleted by its primary key) and a fresh message with a new MessageId and the incremented payload is sent, scheduled retry_after seconds ahead (or the job's $timeout plus 10 seconds, if that is longer). An interleaved queue keeps the key columns of the message it replaces.
  3. If the acknowledging DELETE removes no row, another worker reserved the message first and it is skipped. This also covers a message whose 10 second lease ran out and was delivered to a second worker: only one of them can delete it, so no locking is needed, and the worker's clock is never compared with Spanner's.
  4. The worker runs the job against the reserved message.

A message whose payload is not a JSON object, for example one sent by another service, cannot be run by any worker and would otherwise be redelivered forever. It is deleted instead of reserved, and pop() then throws Colopl\Spanner\Queue\UndecodablePayloadException. The worker reports it to the exception handler and moves on, and the exception's context() puts the full payload in the log entry, since the log is the only trace of it that remains.

What happens next depends on how the job ends:

Outcome What the driver does
The job succeeds The reserved message is acknowledged, so the job is gone.
The job throws and has tries left Laravel calls release($backoff). In one transaction the reserved message is acknowledged and the payload is sent again, deliverable after $backoff seconds (immediately without a backoff).
The job exceeds --tries or --max-exceptions, or calls fail() Laravel records it in the failed jobs provider and the reserved message is acknowledged.
The worker is killed, crashes or times out Nothing is released. Once retry_after seconds have passed the reserved message becomes deliverable and the next worker receives and reserves it again.

Because every delivery goes through reservation, the attempt counter also counts deliveries after a crash, so a job that kills its worker cannot retry forever. --tries and --backoff behave as they do with the database and redis drivers, since the retry decisions are made by Laravel's worker, not by the driver.

If a job runs longer than its reservation (retry_after, or the longer $timeout window), its reserved message becomes deliverable while it is still running and another worker may start the same job. When the first worker finishes, its acknowledgement finds no row and does nothing. Keep retry_after above your longest job, or give long jobs a $timeout.

Two more consequences are worth knowing:

Using the emulator

The emulator can run queues, but it differs from Cloud Spanner in ways that matter to a worker:

Other notes

Mutations

You can insert, update, and delete data using mutations to modify data instead of using DML to improve performance.

Please note that mutation api does not work the same way as DML. All mutations calls within a transaction are queued and sent as batch at the time you commit. This means that if you make any modifications through the above functions and then try to SELECT the same records before committing, the returned results will not include any of the modifications you've made inside the transaction.

SessionCache and AuthCache

In order to improve the performance of the first connection per request, we use AuthCache and SessionCache.

By default, this library uses Filesystem Cache Adapter for caching sessions. If you want to use a different adapter, you can extend ServiceProvider and inject it into the constructor of Colopl\Spanner\Connection.

Session initialization takes about a second, so warming up the session during the boot up phase of your server is recommended. This can be achieved by running the php artisan spanner:warmup command.

Laravel Tinker

You can use Laravel Tinker with commands such as php artisan tinker. But your session may hang when accessing Cloud Spanner. This is known gRPC issue that occurs when PHP forks a process. The workaround is to add following line to php.ini.

Development

Testing

You can run tests on docker by the following command. Note that some environment variables must be set. In order to set the variables, rename .env.sample to .env and edit the values of the defined variables.

Name Value
GOOGLE_APPLICATION_CREDENTIALS The path of the service account key file with access privilege to Google Cloud Spanner instance
DB_SPANNER_INSTANCE_ID Instance ID of your Google Cloud Spanner
DB_SPANNER_DATABASE_ID Name of the database with in the Google Cloud Spanner instance
DB_SPANNER_PROJECT_ID Not required if your credential includes the project ID

License

Apache 2.0 - See LICENSE for more information.


All versions of laravel-spanner with dependencies

PHP Build Version
Package Version
Requires php Version ^8.3
ext-grpc Version *
ext-json Version *
laravel/framework Version ^13.20
google/cloud-spanner Version ^2.10.5
grpc/grpc Version ^1.42
symfony/cache Version ~7 || ~8
symfony/lock Version ~7 || ~8
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package colopl/laravel-spanner contains the following files

Loading the files please wait ...