Demo data, baselines and user content: preserving manual changes
Replay initial data in Symfony and MySQL 8.4/InnoDB with stable source keys, sort_order-only updates, preserved author content and an atomic batch of changes.
The first run of an empty application is a convenient opportunity for automation. Create a reference list, add a few learning notes, and show a useful screen. Running the same command a second time raises a harder question: what should happen to data that someone has already changed?
The Seed module runs in the same Symfony Kernel. Its command uses the shared App\Infrastructure\MysqlLab helper to create its own disposable MySQL 8.4 schema; it neither clears nor seeds the existing note store. A separate migrator connection prepares the table before import; import and replay use one runtime connection with DML-only privileges. The command removes its teaching schema when finished.
Imagine a catalogue of notes. The initial set included a title and body to introduce the interface. The author rewrote the title and deliberately cleared the body to begin a new draft. Later, a developer improved the initial set and ran it again. Assigning every field would put the original content back over the author's work. A rule that says “fill it if it is empty” would also be wrong: the empty field was already a deliberate choice.
We need to identify the owner of each field and distinguish creating a record from reapplying a set. We will use a small module in the shared article_demo project with Symfony and MySQL 8.4/InnoDB through native PDO MySQL. It demonstrates a replay policy with synthetic notes, not an import into an existing website or automatic copying of data from an old SQLite database.
Three sets of data with different rules
The phrase “initial data” often conceals three different tasks.
| Set | Purpose | What replay means |
|---|---|---|
| Demo data | Show a screen or reproduce a test case in a temporary environment | The environment can be recreated if it is genuinely disposable |
| Baseline | Provide records and values required by the product, such as system codes or ordering | Add missing records and update only fields owned by the system |
| User content | Preserve a person's work | Reapplying the initial set does not grant permission to replace it |
These are different contracts, regardless of command names. For example, DoctrineFixturesBundle purges the database before loading fixtures by default. The --append option changes that rule, but does not itself define record identity or permission to overwrite fields. The code of a particular fixture still determines its behaviour.
In our example, the set may create a note, but its title and body belong to the author after creation. Ordering in the learning catalogue remains a system field. This is a deliberate choice for this model, not a universal rule for every list. If a person also edits the order, it belongs in a different column of our contract.
Identity does not change with the title
We need a stable source_key to link a record to its source. The title is unsuitable because it can be translated and edited. An item's position in an array is unsuitable too: inserting a new item changes every subsequent position. The database assigns the local id, so it may differ in another environment.
| Field | On first creation | On replay |
|---|---|---|
source_key |
A stable source key | Finds the same record; renaming requires a separate decision |
title |
The initial title | Keep the current value |
body |
The initial body | Keep the current value, including an empty string |
sort_order |
The baseline order | Update from the baseline |
id |
Generated by storage | Keep it |
A user note that did not originate in the set has source_key = NULL. MySQL allows multiple NULL values in a UNIQUE index. Every non-null source key must be unique. Here, source_key is a VARCHAR(64) using utf8mb4_0900_bin comparisons: case matters. The SeedNote format additionally permits only keys of up to 64 characters containing lowercase ASCII letters, digits and hyphens, starting with a letter. In a real interface, users must not be able to assign reserved keys from the initial set arbitrarily.
The next step in the shared project
Continue the same Symfony project, article_demo, created from the official skeleton in the earlier articles. Run commands from its root. Add the required dependencies and files while preserving earlier routes, services and data. PHP 8.4+, Symfony 8.1 and Composer 2 remain the example requirements.
composer require 'ext-pdo:*' 'ext-pdo_mysql:*' --no-interaction
composer require --dev symfony/test-pack --no-interaction
mkdir -p src/Seed src/Command tests/Seed
Save the files below at the indicated paths. Use the shared guarded MySQL fixture introduced earlier in article_demo, and run laboratory commands through fixtures/mysql_labs/run.sh. The factory in src/Seed/LabDatabase.php calls MysqlLab::create('seed') and uses a separate migrator connection to create an InnoDB table with CHECK (sort_order >= 0), LONGTEXT titles and bodies, and the utf8mb4 character set. The runtime connection has no CREATE, ALTER or DROP privileges. DDL runs before the business transaction: because of MySQL's implicit commits, this is not an atomic schema upgrade combined with import.
<?php
declare(strict_types=1);
namespace App\Seed;
use App\Infrastructure\MysqlLab;
use PDO;
final class LabDatabase
{
public static function connect(): PDO
{
return self::createFixture()->runtime();
}
public static function createFixture(): MysqlLab
{
$fixture = MysqlLab::create('seed');
try {
$fixture->migrator()->exec(<<<'SQL'
CREATE TABLE note (
id BIGINT SIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
source_key VARCHAR(64) NULL UNIQUE,
title LONGTEXT NOT NULL,
body LONGTEXT NOT NULL,
sort_order BIGINT SIGNED NOT NULL CHECK (sort_order >= 0)
) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin
SQL);
return $fixture;
} catch (\Throwable $error) {
$fixture->close();
throw $error;
}
}
}
In src/Seed/SeedNote.php, define the shape of one item. The key and title rules protect this particular teaching format. An empty body is permitted. These checks do not establish who may change an existing note.
<?php
declare(strict_types=1);
namespace App\Seed;
use InvalidArgumentException;
final readonly class SeedNote
{
public function __construct(
public string $sourceKey,
public string $title,
public string $body,
public int $sortOrder,
) {
if (preg_match('/\A[a-z][a-z0-9-]{0,63}\z/', $sourceKey) !== 1) {
throw new InvalidArgumentException('Invalid seed identity.');
}
if (trim($title) === '') {
throw new InvalidArgumentException('A seed title is required.');
}
if ($sortOrder < 0) {
throw new InvalidArgumentException('Sort order cannot be negative.');
}
}
}
Replay updates only the permitted column
The importer in src/Seed/NoteSeedImporter.php first checks that the same key does not appear twice in one set. Otherwise, two definitions of one record would make the outcome depend on their order in the input array. An error in such a set should be visible, rather than silently resolved by whichever item comes last.
<?php
declare(strict_types=1);
namespace App\Seed;
use InvalidArgumentException;
use LogicException;
use PDO;
use Throwable;
final readonly class NoteSeedImporter
{
public function __construct(private PDO $pdo)
{
if ($pdo->getAttribute(PDO::ATTR_DRIVER_NAME) !== 'mysql') {
throw new InvalidArgumentException('This teaching importer requires MySQL.');
}
if ((int) $pdo->getAttribute(PDO::ATTR_ERRMODE) !== PDO::ERRMODE_EXCEPTION
|| (bool) $pdo->getAttribute(PDO::ATTR_EMULATE_PREPARES)
|| (int) $pdo->getAttribute(PDO::ATTR_DEFAULT_FETCH_MODE) !== PDO::FETCH_ASSOC) {
throw new InvalidArgumentException('Native prepares, exception mode and associative fetch are required.');
}
}
/** @param list<SeedNote> $seeds */
public function apply(array $seeds): void
{
$seen = [];
foreach ($seeds as $seed) {
if (!$seed instanceof SeedNote || isset($seen[$seed->sourceKey])) {
throw new InvalidArgumentException('Expected unique SeedNote identities.');
}
$seen[$seed->sourceKey] = true;
}
if ($this->pdo->inTransaction()) {
throw new LogicException('This importer owns its transaction.');
}
if ($seeds === []) {
return;
}
$statement = $this->pdo->prepare(<<<'SQL'
INSERT INTO note (source_key, title, body, sort_order)
VALUES (:source_key, :title, :body, :sort_order) AS incoming
ON DUPLICATE KEY UPDATE sort_order = incoming.sort_order
SQL);
$this->pdo->beginTransaction();
try {
foreach ($seeds as $seed) {
$statement->execute([
'source_key' => $seed->sourceKey,
'title' => $seed->title,
'body' => $seed->body,
'sort_order' => $seed->sortOrder,
]);
}
$this->pdo->commit();
} catch (Throwable $error) {
if ($this->pdo->inTransaction()) {
$this->pdo->rollBack();
}
throw $error;
}
}
}
The key part is the assignment list after ON DUPLICATE KEY UPDATE. It contains only sort_order = incoming.sort_order. The initial title and body are supplied for creating a new row, but are not copied over an existing one. The incoming alias denotes the proposed new row; the MySQL documentation defines the semantics. There is no separate condition to skip an unchanged order here: we check repeatability through stored values and row identity, not affected-row counts.
This is native MySQL SQL, not a translation layer between database systems. The importer explicitly requires the mysql driver, native prepared statements, exception mode and associative fetching; the PDO MySQL documentation describes the connection driver. Replay updates an existing row while retaining its id, rather than deleting and recreating it. AUTO_INCREMENT values may have gaps: the contract requires stable existing identifiers, not gapless numbering.
Values go through PDO::prepare parameters while the SQL structure stays fixed. One PDO transaction covers the entire set. If one row changes successfully and the next record causes an error, the handler should roll back the whole batch and propagate the error. The importer does not join somebody else's active transaction: it explicitly rejects such a call to avoid completing work owned by another operation.
Database uniqueness matters even with a PHP check in place. The check detects contradictory input, while the constraint protects stored state. They have different responsibilities. However, this example does not resolve a conflict between two different baseline versions applied concurrently: that requires a separate policy for versions and execution order.
From a manual edit to the third pass
The command in src/Command/ReplaySeedCommand.php puts the scenario into one process. It obtains its own disposable MySQL fixture, creates two initial notes, simulates an author's edit, adds a personal note without a source key, and then applies the revised set twice. All these data operations use the runtime connection; a finally block closes the fixture and removes its schema even if an error occurs.
<?php
declare(strict_types=1);
namespace App\Command;
use App\Seed\LabDatabase;
use App\Seed\NoteSeedImporter;
use App\Seed\SeedNote;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(name: 'app:seed-replay-demo', description: 'Run an isolated seed replay scenario.')]
final class ReplaySeedCommand extends Command
{
protected function execute(InputInterface $input, OutputInterface $output): int
{
$fixture = LabDatabase::createFixture();
try {
$pdo = $fixture->runtime();
$importer = new NoteSeedImporter($pdo);
$importer->apply([
new SeedNote('guide-intro', 'Initial title', 'Initial body', 10),
new SeedNote('guide-tags', 'Tags', 'Tags body', 20),
]);
$edit = $pdo->prepare('UPDATE note SET title = :title, body = :body WHERE source_key = :key');
$edit->execute(['title' => 'My edited title', 'body' => '', 'key' => 'guide-intro']);
$pdo->exec("INSERT INTO note (source_key, title, body, sort_order) VALUES (NULL, 'Personal note', 'Keep me', 90)");
$next = [
new SeedNote('guide-intro', 'Revised seed title', 'Revised seed body', 5),
new SeedNote('guide-new', 'New guide', 'New body', 30),
];
$importer->apply($next);
$rows = $pdo->query('SELECT * FROM note ORDER BY id')->fetchAll();
$importer->apply($next);
$again = $pdo->query('SELECT * FROM note ORDER BY id')->fetchAll();
$output->writeln(json_encode([
'rows' => $rows,
'unchanged_by_third_pass' => $rows === $again,
], JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT));
return $rows === $again ? Command::SUCCESS : Command::FAILURE;
} finally {
$fixture->close();
}
}
}
Merge this fragment into the existing services block in config/services.yaml, preserving earlier registrations and imports. Keep the rest of the file.
services:
App\Command\ReplaySeedCommand: ~
In an ordinary application, the connection and application service should generally come through the container. Here, explicit construction through MysqlLab defines the disposable laboratory boundary. Before running the command, prepare the shared MySQL fixture from the earlier article; the wrapper below supplies that fixture's configuration, not a connection to the existing note store. The Console documentation describes the AsCommand attribute.
bash fixtures/mysql_labs/run.sh php bin/console app:seed-replay-demo
For this scenario, the following values are expected after the second pass:
| Record | Expected state |
|---|---|
guide-intro |
My edited title, an empty body, order 5 |
guide-tags |
The initial body and order 20 remain, although this record is absent from the revised set |
| Personal note | Personal note, body Keep me, order 90 |
guide-new |
One new record with order 30 |
The third pass with the same set should leave the same four rows and their id values. That is what repeatability means within our contract: applying the same set again to the resulting state does not change that state. The output flag unchanged_by_third_pass is calculated by comparing two actual reads rather than being written as a constant.
The absence of an old key from a revised set does not instruct the importer to delete a record. Likewise, changing guide-intro to another key is not a rename: it creates a new identity. Archiving, deleting, or transferring a key requires a separate explicit operation.
Check that work survives, not just the count
Zero duplicates is an insufficient check. An importer can leave the same number of rows while damaging every body. In tests/Seed/NoteSeedImporterTest.php, capture the manual title, intentionally empty field, stable id values, insertion of a new record, preservation of omitted records, and rollback of a partially applied set.
<?php
declare(strict_types=1);
namespace App\Tests\Seed;
use App\Infrastructure\MysqlLab;
use App\Seed\LabDatabase;
use App\Seed\NoteSeedImporter;
use App\Seed\SeedNote;
use InvalidArgumentException;
use LogicException;
use PDO;
use PDOException;
use PHPUnit\Framework\TestCase;
final class NoteSeedImporterTest extends TestCase
{
private MysqlLab $fixture;
private PDO $pdo;
private NoteSeedImporter $importer;
protected function setUp(): void
{
$this->fixture = LabDatabase::createFixture();
$this->pdo = $this->fixture->runtime();
$this->importer = new NoteSeedImporter($this->pdo);
}
protected function tearDown(): void
{
$this->fixture->close();
}
public function testReplayPreservesManualTitleAndEmptyBody(): void
{
$this->importer->apply([new SeedNote('guide-intro', 'Original', 'Original body', 10)]);
$id = $this->rows()[0]['id'];
$this->pdo->exec("UPDATE note SET title = 'My edit', body = '' WHERE source_key = 'guide-intro'");
$this->importer->apply([new SeedNote('guide-intro', 'New default', 'New body', 5)]);
$row = $this->rows()[0];
self::assertSame($id, $row['id']);
self::assertSame('My edit', $row['title']);
self::assertSame('', $row['body']);
self::assertSame(5, (int) $row['sort_order']);
}
public function testNewSeedIsAddedOnceAndKeepsStableIds(): void
{
$first = new SeedNote('guide-intro', 'Intro', 'Body', 10);
$next = [$first, new SeedNote('guide-new', 'New', 'New body', 20)];
$this->importer->apply([$first]);
$id = $this->rows()[0]['id'];
$this->importer->apply($next);
$snapshot = $this->rows();
$this->importer->apply($next);
self::assertCount(2, $snapshot);
self::assertSame($id, $snapshot[0]['id']);
self::assertSame($snapshot, $this->rows());
}
public function testOmittedSeedsAndUserRowsSurvive(): void
{
$this->importer->apply([new SeedNote('guide-old', 'Old guide', 'Old body', 10)]);
$this->pdo->exec("INSERT INTO note (source_key, title, body, sort_order) VALUES (NULL, 'Personal', 'Keep', 90)");
$snapshot = $this->rows();
$this->importer->apply([]);
self::assertSame($snapshot, $this->rows());
$this->importer->apply([new SeedNote('guide-new', 'New guide', 'New body', 20)]);
self::assertCount(3, $this->rows());
self::assertSame($snapshot, array_slice($this->rows(), 0, 2));
}
public function testDuplicateInputIsRejectedBeforeWrites(): void
{
$this->importer->apply([new SeedNote('guide-existing', 'Existing', 'Body', 10)]);
$snapshot = $this->rows();
try {
$this->importer->apply([
new SeedNote('guide-duplicate', 'First', 'Body', 20),
new SeedNote('guide-duplicate', 'Second', 'Body', 30),
]);
self::fail('Duplicate source identities must be rejected.');
} catch (InvalidArgumentException) {
self::assertSame($snapshot, $this->rows());
self::assertFalse($this->pdo->inTransaction());
}
}
public function testDatabaseFailureRollsBackWholeBatch(): void
{
$this->importer->apply([new SeedNote('guide-existing', 'Existing', 'Body', 10)]);
$snapshot = $this->rows();
$this->fixture->migrator()->exec(<<<'SQL'
CREATE TRIGGER reject_failure BEFORE INSERT ON note FOR EACH ROW
BEGIN
IF NEW.source_key = 'guide-fail' THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'injected failure';
END IF;
END
SQL);
try {
$this->importer->apply([
new SeedNote('guide-existing', 'Ignored default', 'Ignored body', 5),
new SeedNote('guide-new', 'New', 'Body', 20),
new SeedNote('guide-fail', 'Failure', 'Body', 30),
]);
self::fail('The injected database failure must propagate.');
} catch (PDOException $error) {
self::assertStringContainsString('injected failure', $error->getMessage());
self::assertSame($snapshot, $this->rows());
self::assertFalse($this->pdo->inTransaction());
}
$this->fixture->migrator()->exec('DROP TRIGGER reject_failure');
$this->importer->apply([new SeedNote('guide-new', 'Retry', 'Body', 20)]);
self::assertCount(2, $this->rows());
}
public function testCallerTransactionIsNotCommittedOrRolledBack(): void
{
$this->pdo->beginTransaction();
try {
$this->importer->apply([new SeedNote('guide-intro', 'Intro', 'Body', 10)]);
self::fail('An active caller transaction must be rejected.');
} catch (LogicException) {
self::assertTrue($this->pdo->inTransaction());
self::assertSame([], $this->rows());
} finally {
$this->pdo->rollBack();
}
}
public function testIdentityBoundaryAndBinaryUniqueness(): void
{
$key = 'a'.str_repeat('b', 63);
$this->importer->apply([new SeedNote($key, 'Boundary', 'Body', 0)]);
try {
new SeedNote($key.'c', 'Too long', 'Body', 0);
self::fail('Oversized identity must be rejected.');
} catch (InvalidArgumentException) {
self::assertCount(1, $this->rows());
}
$insert = $this->pdo->prepare('INSERT INTO note (source_key, title, body, sort_order) VALUES (?, ?, ?, ?)');
$insert->execute(['Case', 'Upper', '', 0]);
$insert->execute(['case', 'Lower', '', 0]);
$insert->execute([null, 'Unowned one', '', 0]);
$insert->execute([null, 'Unowned two', '', 0]);
self::assertCount(5, $this->rows());
}
private function rows(): array
{
return $this->pdo->query('SELECT * FROM note ORDER BY id')->fetchAll();
}
}
bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/Seed/NoteSeedImporterTest.php --testdox
The tests use actual MySQL 8.4: separate native migrator and runtime connections share one disposable schema. The migrator installs the trigger before the importer is called; it raises a controlled error through SIGNAL SQLSTATE '45000' after earlier changes in the batch. Assertions cover error propagation, rollback of the whole batch to the previous snapshot, closure of the importer's own transaction, and a successful retry after the test trigger is removed. Separate checks cover leaving a caller's transaction untouched, the 64-character key boundary, case-sensitive database identity and multiple rows with source_key = NULL. These checks cover this importer's contract, not every possible concurrent scenario.
The example does not send messages, update search, or write files. An unchanged table does not prove repeatability of those side effects. If they are added later, each needs its own replay rule and coordination with the transaction.
What happens when the initial text changes?
The chosen policy deliberately does not deliver a revised seed body to an existing note. Even if nobody edited the note, replay keeps the old title and body. That is the cost of a simple, transparent rule: initial values apply only at creation.
If the product needs to update fields automatically when the author has not changed them, it will need to retain the previously applied baseline revision and compare three values: the previous source, the current record, and the new source. A divergence requires a conflict decision; checking for an empty string does not replace one. For this small example, that mechanism would be a separate task.
A useful initial set knows the limits of its authority. It creates what is missing, maintains explicitly designated system fields, and leaves the author's work with the author. Record that agreement before the first replay—in the field table, in SQL, and in behavioural checks.
The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.
Check the current example against an owned disposable MySQL schema: