Population Migrations¶
Population migrations insert deterministic data required by the application.
Common examples:
- roles
- permissions
- countries or islands
- fixed categories
- default statuses
- system configuration
Create one with:
The populate_ prefix automatically selects the population template.
Alternatively, pass --populate to use that template with another migration
name.
A population migration extends PopulatorMigration and implements
population(). This is the single supported way to version application data:
schema migrations describe structure, while population migrations describe
deterministic rows. Add a new population migration when those rows need to
change; do not edit a population migration that has already run.
<?php
use Eril\Migraw\PopulatorMigration;
use Eril\Migraw\Sql\SqlStatement;
return new class extends PopulatorMigration
{
public function population(): string|array|SqlStatement
{
return $this->populate(
'roles',
[
[
'slug' => 'admin',
'name' => 'Administrator',
],
[
'slug' => 'user',
'name' => 'User',
],
],
uniqueBy: 'slug'
);
}
};
Arguments¶
populate() accepts:
| Argument | Description |
|---|---|
$table |
Target table |
$rows |
Rows to insert |
$uniqueBy |
Column(s) identifying an existing row |
$updateColumns |
Optional columns updated on conflict |
The columns used by uniqueBy must correspond to a PRIMARY KEY or UNIQUE constraint.
Preserve existing rows¶
With no update columns, conflicts preserve the existing row:
Update existing rows¶
Pass update columns directly:
return $this->populate(
'roles',
[
[
'slug' => 'admin',
'name' => 'System Administrator',
'active' => true,
],
],
uniqueBy: 'slug',
updateColumns: [
'name',
'active',
]
);
Or use update():
A single column is also valid:
Composite conflict keys¶
Multiple population statements¶
public function population(): array
{
return [
$this->populate(
'roles',
$roles,
uniqueBy: 'slug'
),
$this->populate(
'permissions',
$permissions,
uniqueBy: ['resource', 'action']
),
];
}
Rollback behavior¶
PopulatorMigration does not remove populated data during normal rollback.
Its default down() is empty. Rolling it back removes the migration record so the population can run again later.
Squash and fresh¶
Squashing archives schema migrations and keeps population migrations active,
retimestamping them after the new schema baseline. Repeated squashes preserve
the population files rather than folding them into the baseline. A fresh
rebuild runs the baseline and then the active population migrations; it
recreates their declared rows, but does not preserve unrelated operational
data from the previous database.
Driver support¶
Population statements currently compile for:
- MySQL / MariaDB
- PostgreSQL
- SQLite
See the squash command guide for how population migrations behave during squash and unsquash.