diff --git a/docs/SEEDING.md b/docs/SEEDING.md new file mode 100644 index 0000000..84f3044 --- /dev/null +++ b/docs/SEEDING.md @@ -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. diff --git a/src/Exception/ConfigurationException.php b/src/Exception/ConfigurationException.php index 5b897b6..523b940 100644 --- a/src/Exception/ConfigurationException.php +++ b/src/Exception/ConfigurationException.php @@ -38,4 +38,17 @@ final class ConfigurationException extends OrmException $max, )); } + + /** + * @param list $unknown + * @param list $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), + )); + } } diff --git a/src/Seeding/AbstractSeeder.php b/src/Seeding/AbstractSeeder.php new file mode 100644 index 0000000..cfcc330 --- /dev/null +++ b/src/Seeding/AbstractSeeder.php @@ -0,0 +1,62 @@ + $repository + * @param array $criteria + * @param array $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; + } +} diff --git a/src/Seeding/Seeder.php b/src/Seeding/Seeder.php new file mode 100644 index 0000000..26942c9 --- /dev/null +++ b/src/Seeding/Seeder.php @@ -0,0 +1,29 @@ +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, + ); + } +} diff --git a/src/Seeding/SeederRunner.php b/src/Seeding/SeederRunner.php new file mode 100644 index 0000000..d88484d --- /dev/null +++ b/src/Seeding/SeederRunner.php @@ -0,0 +1,114 @@ + */ + private array $seeders = []; + + public function __construct( + private readonly Orm $orm, + ) {} + + /** + * @param list $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 ` without running anything. + * + * @return list + */ + public function names(): array + { + return array_map(static fn(Seeder $seeder): string => $seeder->name(), $this->seeders); + } + + /** + * @param list $only run just these, in the order given + * @return list + */ + 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 $only + * @return list + */ + 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); + } +} diff --git a/tests/Unit/Seeding/SeederRunnerTest.php b/tests/Unit/Seeding/SeederRunnerTest.php new file mode 100644 index 0000000..2ada13a --- /dev/null +++ b/tests/Unit/Seeding/SeederRunnerTest.php @@ -0,0 +1,205 @@ +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 $log + */ + private function recordingSeeder(string $name, \ArrayObject $log): Seeder + { + return new class($name, $log) implements Seeder { + /** + * @param \ArrayObject $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); + } + }; + } +}