Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 ../<Package>--<slug> -b <branch> origin/main`, removed once it is merged.
<!-- ring-master:end -->
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
67 changes: 62 additions & 5 deletions src/Database/Tables.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
* {
Expand All @@ -23,6 +29,8 @@
* }
*
* Schema::create(Tables::name('dashboards'), ...);
* Tables::db()->transaction(fn () => ...);
* Rule::exists(Tables::qualified('dashboards'), 'id');
*/
abstract class Tables
{
Expand All @@ -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.
*
Expand All @@ -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';
}
}
23 changes: 23 additions & 0 deletions src/Testing/Arch.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<int, string> $globs
* @return array<string, array<int, string>>
*/
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.
Expand Down
18 changes: 18 additions & 0 deletions tests/Unit/TablesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
13 changes: 13 additions & 0 deletions tests/Unit/TestingHelpersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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' => "<?php\n\nDB::transaction(fn () => DB::table('x')->get());\nDB::table('y');\n",
'src/Injected.php' => "<?php\n\nfinal class A { public function __construct(private ConnectionInterface \$db) {} }\n",
'src/Package.php' => "<?php\n\nTables::db()->transaction(fn () => null);\n",
]);

expect(Arch::defaultConnectionUses($dir.'/src/*.php'))->toBe([
'Facade' => ['DB::transaction', 'DB::table'],
'Injected' => ['ConnectionInterface $db'],
]);
});
Loading