jgamboa / laravel-aurora-dsql
Laravel driver for Amazon Aurora DSQL: IAM token auth, DSQL-compatible schema builder (inline PK/FK, ASYNC indexes, identity) and migration helpers.
Requires
- php: ^8.2
- awslabs/aurora-dsql-pdo-pgsql: ^0.1.1
- illuminate/database: ^12.0|^13.0
- illuminate/support: ^12.0|^13.0
Requires (Dev)
- orchestra/testbench: ^10.0|^11.0
- phpunit/phpunit: ^11.0|^12.0
Suggests
None
Provides
None
Conflicts
None
Replaces
- jgamboa/laravel-aurora-dsql: v0.5.0
README
Laravel (12+) database driver for Amazon Aurora DSQL.
- Connects with an IAM auth token through the official
awslabs/aurora-dsql-pdo-pgsqlconnector (SSLverify-full, OCC retries). - DSQL-compatible schema builder: regular Laravel migrations just work.
primary()andforeign()/constrained()are emitted inline inCREATE TABLE.unique()inSchema::create()→ an inlineUNIQUEtable constraint: built with the table, valid at once, no background job.index(), andunique()on an existing table →CREATE [UNIQUE] INDEX ASYNC, waiting for the index build to finish.migratebuilds them together instead of one by one: see Index builds duringmigrate.dropUnique()anddropIndex()drop either kind of unique (constraint or index): see Unique indexes.id()/increments()→bigint generated by default as identity (cache 65536).- No schema transactions (DSQL allows a single DDL statement per transaction).
Schema::getTables(),db:show,db:wipeandmigrate:freshwork.
DsqlMigrationbase class for raw SQL migrations.
Nested transactions
Aurora DSQL does not support SAVEPOINT, so the connection reports supportsSavepoints() === false and a
nested DB::transaction() runs inside the outer transaction. An exception caught inside the nested
closure does not undo that closure's writes; one that reaches the outermost transaction rolls back
everything (and an OCC conflict retries the outermost closure).
Installation
composer require multiapi/laravel-aurora-dsql
Moved from
jgamboa/laravel-aurora-dsql(now abandoned, versions up to v0.2.2 stay installable). To switch,composer remove jgamboa/laravel-aurora-dsql && composer require multiapi/laravel-aurora-dsql. Since v0.3.0 the classes live underMultiapi\LaravelAuroraDsql; the oldJGamboa\LaravelAuroraDsqlnames keep working as aliases until 1.0. The configuration is unchanged.
The service provider is auto-discovered. Add a connection to config/database.php:
'dsql' => [ 'driver' => 'dsql', 'host' => env('DSQL_HOST'), // xxxx.dsql.us-east-1.on.aws 'port' => env('DSQL_PORT', 5432), // 5432 on AWS; another port for a local emulator (e.g. Floci) 'region' => env('AWS_REGION', 'us-east-1'), 'username' => env('DSQL_USER', 'admin'), // 'admin' => dsql:DbConnectAdmin; other roles => dsql:DbConnect 'database' => 'postgres', // DSQL has a single database per cluster 'profile' => env('DSQL_PROFILE'), // local AWS profile (e.g. SSO). Leave empty on Lambda/EC2/ECS 'sslrootcert' => env('DSQL_SSLROOTCERT', 'system'), // 'system' requires libpq 17+ 'occ_max_retries' => 3, 'wait_for_indexes' => true, // wait for CREATE INDEX ASYNC jobs 'index_builds' => env('DSQL_INDEX_BUILDS', 'deferred'), // `migrate` builds indexes together; 'per-index' waits after each 'prefix' => '', 'prefix_indexes' => true, 'search_path' => env('DSQL_SEARCH_PATH', 'public'), ],
The CA setting. The AWS connector always connects with sslmode=verify-full and takes no sslrootcert, so libpq
reads PGSSLROOTCERT from the process environment. The driver sets it from sslrootcert with putenv() when it is
not set, which works under PHP-FPM and the CLI but does not reach libpq inside FrankenPHP workers (Laravel Octane
with FrankenPHP, or a FrankenPHP-based Lambda runtime): there the connection fails with
root certificate file "…/.postgresql/root.crt" does not exist. Set PGSSLROOTCERT=system (or a CA bundle path) as a
real environment variable of the process instead. Arco Cloud sends it with its managed databases.
The driver applies search_path (or schema) to the session on connect, like Laravel's pgsql driver; leave both unset to keep the role's default search_path.
On Aurora DSQL a non-admin role cannot create objects in public (permission denied for schema public, and GRANT … ON SCHEMA public fails with "feature not supported on system entity"). An app that connects with its own role therefore uses its own schema and sets DSQL_SEARCH_PATH to it. Arco Cloud sets it automatically for its managed databases.
Usage
// A regular migration (no raw SQL) return new class extends Migration { protected $connection = 'dsql'; public function up(): void { Schema::create('products', function (Blueprint $table) { $table->uuid('id')->primary(); $table->foreignUuid('category_id')->constrained()->cascadeOnDelete(); $table->string('sku')->unique(); $table->timestamps(); }); } };
// Model: UUID v7 primary keys with HasUuids (Laravel 12+) class Product extends Model { use HasUuids; protected $connection = 'dsql'; }
Optimistic concurrency
DSQL uses optimistic concurrency control: a conflicting write fails with SQLSTATE 40001 (OC000/OC001), frequently at COMMIT. This package retries those conflicts for you, with exponential backoff (base 50 ms, cap 1000 ms, jitter):
DB::connection('dsql')->transaction(fn () => ...)re-runs the whole closure, up toocc_max_retries + 1attempts (default 4). Passingattempts:explicitly overrides this. The closure must be idempotent: it can run several times, so avoid side effects such as sending emails or dispatching non-transactional jobs inside it.- Autocommit writes (
INSERT/UPDATE/DELETEoutside a transaction, e.g. Eloquentsave()) are retried the same way. - Writes inside an open transaction are not retried individually: the conflict bubbles up to the outermost
transaction()call, which retries the whole closure. Nested transactions do not retry on their own. - Other errors are never retried, and the original exception is rethrown once attempts are exhausted.
Configure it per connection with 'occ_max_retries' => 3.
Unique indexes
DSQL has two kinds of unique, and the driver uses both:
- Declared in
Schema::create()(->unique()on a column, or$table->unique([...])): aUNIQUEtable constraint insideCREATE TABLE. DSQL builds it with the empty table, so it is valid as soon as the table exists, and there is noCREATE INDEX ASYNCjob to wait for.nullsNotDistinct()is honoured. A unique with an index method ($table->unique('a', null, 'btree')) stays an async index. - Added to an existing table (
Schema::table()):CREATE UNIQUE INDEX ASYNC, as DSQL requires; the connection waits for the build ('wait_for_indexes' => true). DSQL cannot add aUNIQUEconstraint to an existing table exceptUSING INDEXan already valid index.
The index behind a constraint cannot be dropped with DROP INDEX ("cannot drop index ... because constraint ...
requires it"), and an async unique index has no constraint to drop. So dropUnique() and dropIndex() both compile
to DROP INDEX, and the connection checks pg_constraint first: a unique constraint of that name (current schema)
is dropped with ALTER TABLE ... DROP CONSTRAINT, anything else with DROP INDEX. Either method drops either kind,
so migrations written for 0.3 keep working on tables created by either version.
Index builds during migrate
CREATE INDEX ASYNC starts a background job that takes about 10 to 13 seconds even on an empty table, while
CREATE TABLE and ALTER TABLE take milliseconds. Waiting for each job in turn makes a migrate run wait for every
index one after another (about 20 minutes for Arco Cloud's schema from scratch). Not waiting is not an answer: a
job that finishes while a CREATE TABLE or ALTER TABLE runs fails that statement with OC001.
So during migrate (not --pretend), each dsql connection holds back the indexes the schema builder creates and
builds them together. Nothing changes in the migrations.
- Every other statement runs in migration order, with no build job alive.
- First install (no migration recorded yet): every index of the run is built when the run ends (under a minute for that same schema).
- Deploy (some migration already ran): each migration's indexes are built when it ends, before Laravel records it as run. If a build fails, the migration fails and is not recorded.
- A statement that names a table with held-back indexes and could notice they are missing builds that table's indexes
first: any DDL except the
CREATE TABLEandADD COLUMNof the schema builder, and any insert, update or delete. On a first install only an upsert does (it needs its unique index); a unique index built at the end still rejects duplicates the run wrote, and fails the run. - A
dropIndex()of a held-back index takes it off the queue: it is never built. - After waiting, the driver reads each job's status in
sys.jobsand checks that no index is left invalid. A failed job or an invalid index fails the run with the job's details. - If a migration throws, the indexes already held back are still built: earlier migrations of the run are recorded as run and would otherwise lose theirs. (Laravel 13.43+ reports the failure with an event; on older versions the driver builds them when the process ends.)
Each connection has its own queue, and connections of other drivers are not touched.
Limits:
- A
CREATE INDEX ASYNCwritten by hand (DB::statement(),DsqlMigration::createIndexAsync()) is not held back: the connection waits for it on the spot, as before. It is correct, only slower. - DSQL does not mix DDL and DML in a transaction, so nothing can be built once one is open. On a deploy the queue is built before a transaction opens. On a first install an upsert inside a transaction, on a table with a held-back unique index, fails with a message that names the index: run it outside the transaction.
- On a first install the migrations are recorded before their indexes exist. If an index build fails at the end, fix
the cause and build that index again by hand, or start over with
migrate:fresh.
'index_builds' => 'per-index' turns this off: the connection waits after each index, in migration order.
'wait_for_indexes' => false turns it off too (nothing waits at all).
DSQL limitations (verified against a live cluster)
| Not supported | Alternative |
|---|---|
| Adding a PK / FK / UNIQUE / CHECK to an existing table | Declare them in Schema::create(); on an existing table ->unique() is an async unique index |
ADD COLUMN with DEFAULT, NOT NULL or a FK |
Add it nullable → SET DEFAULT → backfill |
->change() (changing a column type), SET NOT NULL |
New table + copy + rename |
| Nested transactions (SAVEPOINT) | Avoid DB::transaction() inside another one |
TRUNCATE |
delete() |
Temporary tables, triggers, plpgsql, extensions, advisory locks, sharedLock() |
— |
| Full-text search with a language config | Only simple is available |
CREATE DATABASE |
One cluster per database |
Supported: lockForUpdate, upsert (needs a unique index), JSON/JSONB, CTEs, window functions, views, sequences, language sql functions.
Prepared statements
Every dsql connection uses emulated prepares (PDO::ATTR_EMULATE_PREPARES, since v0.3.1): pdo_pgsql built against
libpq 17+ closes server-side prepared statements with a protocol message that DSQL rejects, which aborted the
transaction after its first statement (SQLSTATE 25P02). Bindings are escaped by PDO and booleans are sent as
true/false; nothing changes in application code.
Operational notes: connections last at most 60 minutes (long-running processes must reconnect); the IAM token is signed locally (no network call).
Testing
vendor/bin/phpunit --testsuite Unit DSQL_HOST=xxxx.dsql.us-east-1.on.aws DSQL_PROFILE=my-profile vendor/bin/phpunit --testsuite Integration
License
MIT