From fdb591065a84d4f47d42203920db5b0b4332b2f2 Mon Sep 17 00:00:00 2001 From: Jay Fletcher <5743488+jayjfletcher@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:55:25 -0500 Subject: [PATCH] feat: let a package keep its tables on a dedicated database connection Tables::connection() reads {key}.database.connection (null keeps the app default); Tables::db() and Tables::qualified() route raw queries, transactions and validation rules through it. Arch::defaultConnectionUses() finds code still reaching the default connection. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + CHANGELOG.md | 5 +++ README.md | 21 ++++++++++ src/Database/Tables.php | 67 ++++++++++++++++++++++++++++--- src/Testing/Arch.php | 23 +++++++++++ tests/Unit/TablesTest.php | 18 +++++++++ tests/Unit/TestingHelpersTest.php | 13 ++++++ 7 files changed, 143 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e830529..ec3c35d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,4 +39,5 @@ This repository is a Laravel package. Keep the package focused, idiomatic, and e - Specs, product docs and local standards live in `docs/agent/`. Shared standards come from `vendor/` through `docs/agent/standards.index.yml`; read the matching standards before changing code. - Workflow: `/ring-master-shape-spec` → `/ring-master-write-spec` → `/ring-master-create-tasks` → `/ring-master-implement` → `/ring-master-verify-spec`. - Done means `composer test` passes. When work must break a standard, add a row to `docs/agent/standards-feedback.md`. +- Keep this checkout on `main`: other packages' jobs build against it. Never switch branches, commit or stash here; do any change that is not a factory job (which makes its own) in a worktree beside the package: `git worktree add ../-- -b origin/main`, removed once it is merged. diff --git a/CHANGELOG.md b/CHANGELOG.md index 93848e4..580d2d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## [Unreleased](https://github.com/Refactor-Circus/Keystone/compare/v0.1.0...main) +### Added + +- `Database\Tables` gives a package its own database connection: `Tables::connection()` reads `{key}.database.connection` (null, the default, means the app's default connection; override the key with `CONNECTION`), `Tables::db()` is that connection for raw queries and transactions, and `Tables::qualified('dashboards')` is the `{connection}.{table}` name `exists`/`unique` rules expect. Models return `Tables::connection()` from `getConnectionName()` and migrations from `getConnection()`. +- `Testing\Arch::defaultConnectionUses()`: files that reach the app's default connection through the `DB` facade or an injected `ConnectionInterface`/`DatabaseManager`/`ConnectionResolverInterface` instead of `Tables::db()`. + ## [v0.1.0](https://github.com/Refactor-Circus/Keystone/commits/v0.1.0) - 2026-10-30 ### Breaking diff --git a/README.md b/README.md index 25c5b74..7c98a14 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,27 @@ final class Tables extends \RefactorCircus\Keystone\Database\Tables Models return `Tables::name('dashboards')` from `getTable()`, and migrations, `Rule::unique`/`exists` and joins use it too, never a literal name. A published config that lists only some tables keeps the defaults for the rest. `Testing\Arch::literalTableNames()` finds literal names left in migrations or code, and `Arch::modelsWithoutPolicies()` finds models missing from `{key}.policies`. +### Database connection + +A package can keep its tables on their own connection. `Tables::connection()` reads `{key}.database.connection` (null means the app's default); models, migrations, queries and rules all go through it: + +```php +public function getConnectionName(): ?string // on each model +{ + return $this->connection ?? Tables::connection(); +} + +public function getConnection(): ?string // on each migration +{ + return Tables::connection(); +} + +Tables::db()->transaction(fn () => ...); // not DB::transaction() +Rule::exists(Tables::qualified('dashboards'), 'id'); // "{connection}.{table}" +``` + +`Arch::defaultConnectionUses()` finds code still reaching the default connection through `DB::` or an injected connection. Joins and `whereHas` against host models (users, teams) only work while both sit on the same database. + ## Audit seams Keystone defines how packages talk to an audit log without depending on one. [refactor-circus/keen](https://github.com/Refactor-Circus/Keen) is the audit log; until it is installed, `AuditTrail` is bound to `NullAuditTrail`. diff --git a/src/Database/Tables.php b/src/Database/Tables.php index 9906bad..f9edf85 100644 --- a/src/Database/Tables.php +++ b/src/Database/Tables.php @@ -5,13 +5,19 @@ namespace RefactorCircus\Keystone\Database; use Illuminate\Contracts\Config\Repository; +use Illuminate\Database\ConnectionInterface; +use Illuminate\Database\ConnectionResolverInterface; /** - * The table each of a package's records lives in, from its `{key}.tables` - * config. Models (`getTable()`), migrations, validation rules and joins all - * ask here, so renaming a table is one config change made before the - * migrations run. A published config that lists only some tables keeps the - * defaults for the rest. + * Where a package's records live: the table each one is in, from its + * `{key}.tables` config, and the database connection they all share, from + * its `{key}.database.connection` config. Models (`getTable()`, + * `getConnectionName()`), migrations (`getConnection()`), validation rules, + * joins, raw queries and transactions all ask here, so renaming a table or + * moving the package to its own database is one config change made before + * the migrations run. A published config that lists only some tables keeps + * the defaults for the rest; no connection configured means the app's + * default connection. * * final class Tables extends \RefactorCircus\Keystone\Database\Tables * { @@ -23,6 +29,8 @@ * } * * Schema::create(Tables::name('dashboards'), ...); + * Tables::db()->transaction(fn () => ...); + * Rule::exists(Tables::qualified('dashboards'), 'id'); */ abstract class Tables { @@ -31,6 +39,13 @@ abstract class Tables */ protected const string CONFIG = ''; + /** + * The config key holding the package's database connection name. Empty + * means `{key}.database.connection`, `{key}` being the first segment of + * CONFIG. + */ + protected const string CONNECTION = ''; + /** * Each table's key and default name. * @@ -47,4 +62,46 @@ public static function name(string $key): string return is_string($name) && $name !== '' ? $name : static::DEFAULTS[$key]; } + + /** + * The database connection the package's tables live on, or null for the + * app's default connection. + */ + public static function connection(): ?string + { + $name = app(Repository::class)->get(static::connectionKey()); + + return is_string($name) && $name !== '' ? $name : null; + } + + /** + * The package's database connection, for raw queries, schema checks and + * transactions around the package's writes. + */ + public static function db(): ConnectionInterface + { + return app(ConnectionResolverInterface::class)->connection(static::connection()); + } + + /** + * One of the package's tables as validation rules (`exists`, `unique`) + * expect it: `{connection}.{table}` when the package has its own + * connection, else the bare table name. + */ + public static function qualified(string $key): string + { + $connection = static::connection(); + + return ($connection === null ? '' : $connection.'.').static::name($key); + } + + /** + * The config key holding the package's database connection name. + */ + protected static function connectionKey(): string + { + return static::CONNECTION !== '' + ? static::CONNECTION + : explode('.', static::CONFIG, 2)[0].'.database.connection'; + } } diff --git a/src/Testing/Arch.php b/src/Testing/Arch.php index ac0ba49..6a6362f 100644 --- a/src/Testing/Arch.php +++ b/src/Testing/Arch.php @@ -182,6 +182,29 @@ public static function writesOutsideTransactions(string|array $globs, array $wri return $gaps; } + /** + * Files that reach the database through the `DB` facade or an injected + * default connection (`ConnectionInterface`, `DatabaseManager`) instead + * of the package's `Tables::db()`, by their source, with the calls each + * makes. Those go to the app's default connection and miss a package's + * own `{key}.database.connection`. + * + * @param string|array $globs + * @return array> + */ + public static function defaultConnectionUses(string|array $globs): array + { + $gaps = []; + + foreach (array_merge(...array_map(fn (string $glob): array => glob($glob) ?: [], (array) $globs)) as $path) { + if (preg_match_all('/\bDB::\w+|\b(?:ConnectionInterface|DatabaseManager|ConnectionResolverInterface)\s+\$\w+/', (string) file_get_contents($path), $matches) > 0) { + $gaps[basename($path, '.php')] = array_values(array_unique($matches[0])); + } + } + + return $gaps; + } + /** * Models without a policy in the package's `{key}.policies` config, or * whose configured policy class does not exist. diff --git a/tests/Unit/TablesTest.php b/tests/Unit/TablesTest.php index 6c2af07..c51a0b9 100644 --- a/tests/Unit/TablesTest.php +++ b/tests/Unit/TablesTest.php @@ -10,3 +10,21 @@ expect(WidgetTables::name('widgets'))->toBe('crm_widgets') ->and(WidgetTables::name('parts'))->toBe('acme_parts'); }); + +it('uses the default connection when the package configures none', function (mixed $connection): void { + config()->set('acme.database.connection', $connection); + + expect(WidgetTables::connection())->toBeNull() + ->and(WidgetTables::db()->getName())->toBe(config('database.default')) + ->and(WidgetTables::qualified('widgets'))->toBe('acme_widgets'); +})->with([null, '', 42]); + +it('puts the package on its own connection when one is configured', function (): void { + config()->set('database.connections.acme', ['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '']); + config()->set('acme.database.connection', 'acme'); + config()->set('acme.tables.widgets', 'crm_widgets'); + + expect(WidgetTables::connection())->toBe('acme') + ->and(WidgetTables::db()->getName())->toBe('acme') + ->and(WidgetTables::qualified('widgets'))->toBe('acme.crm_widgets'); +}); diff --git a/tests/Unit/TestingHelpersTest.php b/tests/Unit/TestingHelpersTest.php index f9bf5d1..1bdf7c1 100644 --- a/tests/Unit/TestingHelpersTest.php +++ b/tests/Unit/TestingHelpersTest.php @@ -99,3 +99,16 @@ function scratch(array $files): string expect(Arch::literalTableNames($dir.'/migrations/*.php', ['acme_widgets', 'acme_parts']))->toBe(['create.php' => ['acme_widgets']]); }); + +it('lists the files that reach the default connection instead of the package one', function (): void { + $dir = scratch([ + 'src/Facade.php' => " DB::table('x')->get());\nDB::table('y');\n", + 'src/Injected.php' => " "transaction(fn () => null);\n", + ]); + + expect(Arch::defaultConnectionUses($dir.'/src/*.php'))->toBe([ + 'Facade' => ['DB::transaction', 'DB::table'], + 'Injected' => ['ConnectionInterface $db'], + ]); +});