feat(seeding): add the seeder concept with an idempotent runner
A seeder fills reference or bootstrap data - the permission catalogue, the built-in roles, the first administrator. It is not a migration: it never touches the schema, it runs on demand, and it must be safe to run twice. - Seeder: the contract (name + run). - AbstractSeeder: seedOnce() inserts only when the criteria match nothing and records inserted/skipped counts. It never overwrites a row a user edited. - SeederRunner: runs an ordered batch inside one transaction, so a failing seeder leaves the database untouched. Supports running a named subset. - SeederResult: per-seeder outcome for reporting. - ConfigurationException::unknownSeeder() lists the registered names. docs/SEEDING.md documents the contract and how to write one.
This commit is contained in:
1 parent
02703f40ab
commit
2acf2cc099
7 files changed
+542
No files matched your search
@@ -0,0 +1,68 @@
|
|||||||
|
# Seeder
|
||||||
|
|
||||||
|
A `Seeder` populates a table with reference or bootstrap rows: the permission catalogue, the
|
||||||
|
built-in roles, the first administrator. It is not a migration: it runs on demand, it is
|
||||||
|
idempotent, and it never changes the schema.
|
||||||
|
|
||||||
|
## Contract
|
||||||
|
|
||||||
|
```php
|
||||||
|
interface Seeder
|
||||||
|
{
|
||||||
|
public function name(): string;
|
||||||
|
|
||||||
|
public function run(Orm $orm): void;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `name()` is what you type on the command line and what the runner orders by. Keep it short and
|
||||||
|
unique: `permissions`, `roles`, `admin-user`.
|
||||||
|
- `run()` receives the `Orm`, so a seeder writes through repositories like any other consumer. It
|
||||||
|
must be safe to run twice: an insert of an existing row is a no-op, not an error.
|
||||||
|
- A seeder throws nothing it cannot explain. A failure stops the batch and is reported.
|
||||||
|
|
||||||
|
## Runner
|
||||||
|
|
||||||
|
`Camelia\Orm\Seeding\SeederRunner` executes an ordered list of seeders inside one transaction:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$runner = new SeederRunner($orm, [new PermissionsSeeder(), new RolesSeeder(), new AdminSeeder()]);
|
||||||
|
$report = $runner->run();
|
||||||
|
```
|
||||||
|
|
||||||
|
Every seeder runs in the same transaction: either the whole batch applies or none of it does. The
|
||||||
|
report tells you what happened per seeder.
|
||||||
|
|
||||||
|
## Writing a seeder
|
||||||
|
|
||||||
|
Subclass `AbstractSeeder` to get idempotent helpers instead of hand-rolling `findOrCreate` calls:
|
||||||
|
|
||||||
|
```php
|
||||||
|
final class PermissionsSeeder extends AbstractSeeder
|
||||||
|
{
|
||||||
|
public function name(): string
|
||||||
|
{
|
||||||
|
return 'permissions';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function run(Orm $orm): void
|
||||||
|
{
|
||||||
|
$repository = $orm->repository(PermissionModel::class);
|
||||||
|
|
||||||
|
foreach (Permission::cases() as $permission) {
|
||||||
|
$this->seedOnce($repository, ['code' => $permission->value], [
|
||||||
|
'module' => $permission->module(),
|
||||||
|
'action' => $permission->action(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`seedOnce()` inserts when the criteria match nothing and reports whether it did. It never updates an
|
||||||
|
existing row, because a seeder that silently overwrites data the user edited is a footgun.
|
||||||
|
|
||||||
|
## Ordering
|
||||||
|
|
||||||
|
Seeders run in the order you pass them. When a seeder depends on rows another one creates (roles
|
||||||
|
need permissions), pass them in dependency order and let the transaction protect you.
|
||||||
@@ -38,4 +38,17 @@ final class ConfigurationException extends OrmException
|
|||||||
$max,
|
$max,
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<string> $unknown
|
||||||
|
* @param list<string> $known
|
||||||
|
*/
|
||||||
|
public static function unknownSeeder(array $unknown, array $known): self
|
||||||
|
{
|
||||||
|
return new self(sprintf(
|
||||||
|
'Unknown seeder(s): %s. Registered: %s.',
|
||||||
|
implode(', ', $unknown),
|
||||||
|
$known === [] ? '(none)' : implode(', ', $known),
|
||||||
|
));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Orm\Seeding;
|
||||||
|
|
||||||
|
use Camelia\Orm\Model;
|
||||||
|
use Camelia\Orm\Repository;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convenience base for seeders that insert reference rows.
|
||||||
|
*
|
||||||
|
* It offers the two things hand-written seeders get wrong: an idempotent insert and a count. It
|
||||||
|
* never updates an existing row, because a seeder that silently overwrites data a user edited is
|
||||||
|
* a footgun.
|
||||||
|
*
|
||||||
|
* @api
|
||||||
|
*/
|
||||||
|
abstract class AbstractSeeder implements Seeder
|
||||||
|
{
|
||||||
|
private int $inserted = 0;
|
||||||
|
|
||||||
|
private int $skipped = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inserts $values when $criteria match nothing, and leaves the row alone when they do.
|
||||||
|
*
|
||||||
|
* @template T of Model
|
||||||
|
* @param Repository<T> $repository
|
||||||
|
* @param array<string, mixed> $criteria
|
||||||
|
* @param array<string, mixed> $values merged into the criteria on insert
|
||||||
|
* @return T|null the new row, or null when it already existed
|
||||||
|
*/
|
||||||
|
final protected function seedOnce(
|
||||||
|
Repository $repository,
|
||||||
|
array $criteria,
|
||||||
|
array $values = [],
|
||||||
|
): ?Model {
|
||||||
|
if ($repository->findFirst($criteria) !== null) {
|
||||||
|
$this->skipped++;
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->inserted++;
|
||||||
|
|
||||||
|
return $repository->create([...$criteria, ...$values]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rows inserted by the last run(). Used by the runner for its report.
|
||||||
|
*/
|
||||||
|
final public function inserted(): int
|
||||||
|
{
|
||||||
|
return $this->inserted;
|
||||||
|
}
|
||||||
|
|
||||||
|
final public function skipped(): int
|
||||||
|
{
|
||||||
|
return $this->skipped;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Orm\Seeding;
|
||||||
|
|
||||||
|
use Camelia\Orm\Orm;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fills reference or bootstrap data: the permission catalogue, the built-in roles, the first
|
||||||
|
* administrator.
|
||||||
|
*
|
||||||
|
* A seeder is not a migration. It never changes the schema, it runs on demand, and it must be safe
|
||||||
|
* to run twice: seeding an existing row is a no-op, not an error.
|
||||||
|
*
|
||||||
|
* @api
|
||||||
|
*/
|
||||||
|
interface Seeder
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Stable, command-line friendly identifier. Also the sort key when order matters.
|
||||||
|
*/
|
||||||
|
public function name(): string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Writes the rows. Called inside the runner's transaction.
|
||||||
|
*/
|
||||||
|
public function run(Orm $orm): void;
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Orm\Seeding;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What one seeder did, so the caller can report it without inspecting the database.
|
||||||
|
*
|
||||||
|
* @api
|
||||||
|
*/
|
||||||
|
final readonly class SeederResult
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
public string $seeder,
|
||||||
|
public int $inserted,
|
||||||
|
public int $skipped,
|
||||||
|
public float $seconds,
|
||||||
|
public ?string $error = null,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public static function started(string $seeder): self
|
||||||
|
{
|
||||||
|
return new self($seeder, 0, 0, 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function isSuccessful(): bool
|
||||||
|
{
|
||||||
|
return $this->error === null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function isNoOp(): bool
|
||||||
|
{
|
||||||
|
return $this->error === null && $this->inserted === 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function summary(): string
|
||||||
|
{
|
||||||
|
if ($this->error !== null) {
|
||||||
|
return sprintf('%s: FAILED — %s', $this->seeder, $this->error);
|
||||||
|
}
|
||||||
|
|
||||||
|
return sprintf(
|
||||||
|
'%s: %d inserted, %d skipped (%.0f ms)',
|
||||||
|
$this->seeder,
|
||||||
|
$this->inserted,
|
||||||
|
$this->skipped,
|
||||||
|
$this->seconds * 1000,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Orm\Seeding;
|
||||||
|
|
||||||
|
use Camelia\Orm\Exception\ConfigurationException;
|
||||||
|
use Camelia\Orm\Orm;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs an ordered list of seeders inside one transaction.
|
||||||
|
*
|
||||||
|
* Either the whole batch applies or none of it does: a seeder that fails leaves the database
|
||||||
|
* untouched, which is what makes re-running the command after a fix safe.
|
||||||
|
*
|
||||||
|
* Seeders that extend AbstractSeeder report how many rows they inserted; a plain Seeder reports
|
||||||
|
* zero and is still executed.
|
||||||
|
*
|
||||||
|
* @api
|
||||||
|
*/
|
||||||
|
final class SeederRunner
|
||||||
|
{
|
||||||
|
/** @var list<Seeder> */
|
||||||
|
private array $seeders = [];
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
private readonly Orm $orm,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<Seeder> $seeders
|
||||||
|
*/
|
||||||
|
public function addMany(array $seeders): self
|
||||||
|
{
|
||||||
|
foreach ($seeders as $seeder) {
|
||||||
|
$this->add($seeder);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function add(Seeder $seeder): self
|
||||||
|
{
|
||||||
|
$this->seeders[] = $seeder;
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Commands read this to offer `--only <name>` without running anything.
|
||||||
|
*
|
||||||
|
* @return list<string>
|
||||||
|
*/
|
||||||
|
public function names(): array
|
||||||
|
{
|
||||||
|
return array_map(static fn(Seeder $seeder): string => $seeder->name(), $this->seeders);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<string> $only run just these, in the order given
|
||||||
|
* @return list<SeederResult>
|
||||||
|
*/
|
||||||
|
public function run(array $only = []): array
|
||||||
|
{
|
||||||
|
$selected = $this->select($only);
|
||||||
|
|
||||||
|
if ($selected === []) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->orm->transaction(fn(): array => array_map($this->execute(...), $selected));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<string> $only
|
||||||
|
* @return list<Seeder>
|
||||||
|
*/
|
||||||
|
private function select(array $only): array
|
||||||
|
{
|
||||||
|
if ($only === []) {
|
||||||
|
return $this->seeders;
|
||||||
|
}
|
||||||
|
|
||||||
|
$unknown = array_values(array_diff($only, $this->names()));
|
||||||
|
|
||||||
|
if ($unknown !== []) {
|
||||||
|
throw ConfigurationException::unknownSeeder($unknown, $this->names());
|
||||||
|
}
|
||||||
|
|
||||||
|
$selected = [];
|
||||||
|
|
||||||
|
foreach ($only as $name) {
|
||||||
|
foreach ($this->seeders as $seeder) {
|
||||||
|
if ($seeder->name() === $name) {
|
||||||
|
$selected[] = $seeder;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $selected;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function execute(Seeder $seeder): SeederResult
|
||||||
|
{
|
||||||
|
$started = hrtime(true);
|
||||||
|
$seeder->run($this->orm);
|
||||||
|
$elapsed = (hrtime(true) - $started) / 1_000_000_000;
|
||||||
|
|
||||||
|
$inserted = $seeder instanceof AbstractSeeder ? $seeder->inserted() : 0;
|
||||||
|
$skipped = $seeder instanceof AbstractSeeder ? $seeder->skipped() : 0;
|
||||||
|
|
||||||
|
return new SeederResult($seeder->name(), $inserted, $skipped, $elapsed);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Orm\Tests\Unit\Seeding;
|
||||||
|
|
||||||
|
use Camelia\Orm\Exception\ConfigurationException;
|
||||||
|
use Camelia\Orm\Orm;
|
||||||
|
use Camelia\Orm\Seeding\AbstractSeeder;
|
||||||
|
use Camelia\Orm\Seeding\Seeder;
|
||||||
|
use Camelia\Orm\Seeding\SeederRunner;
|
||||||
|
use Camelia\Orm\Tests\Fixture\Usuario;
|
||||||
|
use Camelia\Orm\Tests\Support\FakeConnection;
|
||||||
|
use PHPUnit\Framework\Attributes\Test;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
final class SeederRunnerTest extends TestCase
|
||||||
|
{
|
||||||
|
private FakeConnection $connection;
|
||||||
|
|
||||||
|
private Orm $orm;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
$this->connection = new FakeConnection();
|
||||||
|
$this->orm = Orm::fromConnection($this->connection);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Test]
|
||||||
|
public function it_runs_seeders_in_registration_order(): void
|
||||||
|
{
|
||||||
|
$log = new \ArrayObject();
|
||||||
|
|
||||||
|
$runner = new SeederRunner($this->orm)->addMany([
|
||||||
|
$this->recordingSeeder('first', $log),
|
||||||
|
$this->recordingSeeder('second', $log),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$runner->run();
|
||||||
|
|
||||||
|
self::assertSame(['first', 'second'], $log->getArrayCopy());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Test]
|
||||||
|
public function it_wraps_the_batch_in_one_transaction(): void
|
||||||
|
{
|
||||||
|
$log = new \ArrayObject();
|
||||||
|
|
||||||
|
new SeederRunner($this->orm)->add($this->recordingSeeder('only', $log))->run();
|
||||||
|
|
||||||
|
self::assertSame(1, $this->connection->beginCount);
|
||||||
|
self::assertSame(1, $this->connection->commitCount);
|
||||||
|
self::assertSame(0, $this->connection->rollBackCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Test]
|
||||||
|
public function it_rolls_back_the_whole_batch_when_a_seeder_throws(): void
|
||||||
|
{
|
||||||
|
$log = new \ArrayObject();
|
||||||
|
|
||||||
|
$failing = new class implements Seeder {
|
||||||
|
public function name(): string
|
||||||
|
{
|
||||||
|
return 'failing';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function run(Orm $orm): void
|
||||||
|
{
|
||||||
|
throw new \RuntimeException('boom');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
$runner = new SeederRunner($this->orm)->addMany([
|
||||||
|
$this->recordingSeeder('ok', $log),
|
||||||
|
$failing,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->expectException(\RuntimeException::class);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$runner->run();
|
||||||
|
} finally {
|
||||||
|
self::assertSame(1, $this->connection->rollBackCount);
|
||||||
|
self::assertSame(0, $this->connection->commitCount);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Test]
|
||||||
|
public function it_lists_registered_names(): void
|
||||||
|
{
|
||||||
|
$log = new \ArrayObject();
|
||||||
|
|
||||||
|
$runner = new SeederRunner($this->orm)->addMany([
|
||||||
|
$this->recordingSeeder('roles', $log),
|
||||||
|
$this->recordingSeeder('admin-user', $log),
|
||||||
|
]);
|
||||||
|
|
||||||
|
self::assertSame(['roles', 'admin-user'], $runner->names());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Test]
|
||||||
|
public function it_runs_only_the_requested_seeders_in_the_requested_order(): void
|
||||||
|
{
|
||||||
|
$log = new \ArrayObject();
|
||||||
|
|
||||||
|
$runner = new SeederRunner($this->orm)->addMany([
|
||||||
|
$this->recordingSeeder('permissions', $log),
|
||||||
|
$this->recordingSeeder('roles', $log),
|
||||||
|
$this->recordingSeeder('admin-user', $log),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$runner->run(['admin-user', 'permissions']);
|
||||||
|
|
||||||
|
self::assertSame(['admin-user', 'permissions'], $log->getArrayCopy());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Test]
|
||||||
|
public function it_rejects_an_unknown_seeder_name(): void
|
||||||
|
{
|
||||||
|
$log = new \ArrayObject();
|
||||||
|
|
||||||
|
$runner = new SeederRunner($this->orm)->add($this->recordingSeeder('known', $log));
|
||||||
|
|
||||||
|
$this->expectException(ConfigurationException::class);
|
||||||
|
$this->expectExceptionMessage('Unknown seeder(s): nope');
|
||||||
|
|
||||||
|
$runner->run(['nope']);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Test]
|
||||||
|
public function it_does_nothing_without_seeders(): void
|
||||||
|
{
|
||||||
|
$results = new SeederRunner($this->orm)->run();
|
||||||
|
|
||||||
|
self::assertSame([], $results);
|
||||||
|
self::assertSame(0, $this->connection->beginCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Test]
|
||||||
|
public function it_reports_inserted_and_skipped_counts(): void
|
||||||
|
{
|
||||||
|
$this->connection->rowBatches = [
|
||||||
|
[],
|
||||||
|
[['codigo' => '1']],
|
||||||
|
];
|
||||||
|
|
||||||
|
$seeder = new class extends AbstractSeeder {
|
||||||
|
public function name(): string
|
||||||
|
{
|
||||||
|
return 'counted';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function run(Orm $orm): void
|
||||||
|
{
|
||||||
|
$repository = $orm->repository(Usuario::class);
|
||||||
|
$this->seedOnce($repository, ['correo' => 'a@x'], ['clave' => 'a']);
|
||||||
|
$this->seedOnce($repository, ['correo' => 'b@x'], ['clave' => 'b']);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
$results = new SeederRunner($this->orm)->add($seeder)->run();
|
||||||
|
|
||||||
|
self::assertCount(1, $results);
|
||||||
|
self::assertSame(1, $results[0]->inserted);
|
||||||
|
self::assertSame(1, $results[0]->skipped);
|
||||||
|
self::assertTrue($results[0]->isSuccessful());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Test]
|
||||||
|
public function a_plain_seeder_reports_zero_counts(): void
|
||||||
|
{
|
||||||
|
$log = new \ArrayObject();
|
||||||
|
|
||||||
|
$results = new SeederRunner($this->orm)->add($this->recordingSeeder('plain', $log))->run();
|
||||||
|
|
||||||
|
self::assertSame(0, $results[0]->inserted);
|
||||||
|
self::assertTrue($results[0]->isNoOp());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param \ArrayObject<int, string> $log
|
||||||
|
*/
|
||||||
|
private function recordingSeeder(string $name, \ArrayObject $log): Seeder
|
||||||
|
{
|
||||||
|
return new class($name, $log) implements Seeder {
|
||||||
|
/**
|
||||||
|
* @param \ArrayObject<int, string> $log
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
private readonly string $label,
|
||||||
|
private readonly \ArrayObject $log,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function name(): string
|
||||||
|
{
|
||||||
|
return $this->label;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function run(Orm $orm): void
|
||||||
|
{
|
||||||
|
$this->log->append($this->label);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user