Skip to content

✨ v3: migrations run once per site, from a version check on init (#40) - #119

Merged
gfazioli merged 8 commits into
v3from
feat/v3-migrations
Oct 6, 2026
Merged

gfazioli merged 8 commits into
v3from
feat/v3-migrations

Conversation

@gfazioli

@gfazioli gfazioli commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

The migrations redesign agreed in #40 with @balazsnasz (spec: #40 (comment)). It targets v3: it breaks 2.x plugins, and php bones migrate:to-v3 converts them.

What changes

  • Each migration runs once per site, recorded by file name in a WordPress option ({slug}_migrations), in file name order. A migration does not belong to a plugin version: the decision is "files on disk minus names recorded", so one added during development or backported still runs exactly once wherever it is missing.
  • The trigger is a version check on init (priority 1): {slug}_db_version, autoloaded, against the plugin header. It replaces upgrader_post_install, which ran in the request doing the update with the old classes loaded, did nothing for a ZIP replaced through Upload Plugin, and never ran for FTP, git or Composer deploys. Activation calls the same runner. The steady state costs no query.
  • One request at a time: an INSERT IGNORE … /* LOCK */ row on the options table, as WP_Upgrader::create_lock() does, holding time|token, touched before each migration and released only by its owner. Stop at the first failure without recording it, an admin notice with the cause, retries only from the admin (at most every 60 s); a failure of one version does not hold back the next. A ledger write the database refuses stops the run too. The auto-update loopback (wp_scrape_key) is skipped: a slow migration there would get the code rolled back over a migrated database.
  • A pending migration that sorts before one that already ran still runs, with a warning in the log and in migrate:status.
  • Seeders become migrations. runOnce is gone; Migration gains insert(), truncate(), count(), isEmpty(), query() with the table named in each call. Seeder stays as a no-op so that a 2.x seeder file still loads.
  • The base class moves to WPBones\Database\Migration and its constructor runs nothing. The 2.x name stays as a deprecated subclass. The new name is what makes the update to 3.0 safe: that update is run by the 2.x code, whose upgrader hook includes every migration file, and a class name 2.x never had is loaded from the new files, where creating a migration runs nothing.
  • create() fails when the table or a declared column is missing, and tolerates (logs) what dbDelta could not tidy on an existing table. 2.x ran every migration on every update and never saw those errors; without this, the first 3.0 run of a 2.x migration written on one line stopped everything after it.
  • CLI: php bones migrate, php bones migrate:status, php bones migrate:to-v3; migrate:create now creates the table it is given (it always wrote my_plugin_products).
  • Found on the way, 2.x too: activation never read the plugin header (it is read on init, which comes first), so the slug was empty there and the options delta wrote to an options row with no name. Measured on 2.1.0: slug='' Version=NULL during activation. Fixed here.

Proof

  • composer test: 250 tests, 675 assertions (174 / 470 on v2.1.0).
  • .claude/scripts/migrations-live-smoke.sh in the workspace, 32 checks on wpbones.test and in a local Playground:
v2.1.0 this branch
A activation sees the header ✗ slug='' Version=NULL ✓
B reactivating does not run a migration again ✗ 2 rows ✓ 1
C an update by copying files migrates on the next request ✗ nothing runs ✓ once
D three concurrent requests ✗ nothing runs ✓ once
E failure recorded, shown, not retried by a public page, resumed by bones migrate ✗ ✓
U plugin/updated.php gets the version it came from, also when activation finishes an update made while inactive ✗ ✓
F 2.1.0 → this branch through the real Plugin_Upgrader::upgrade() n/a ✓ the 2.1.0 request included the new file and ran nothing; the next request ran it once
G SQLite: the published Database ZIP, converted by migrate:to-v3, on Playground n/a ✓ both tables seeded once, ledger complete, Eloquent page intact

Not in this PR

  • The docs pages (database-orm/migrations.mdx, seeding.mdx), the boilerplates' conversion and the ZIPs: with the 3.0 release cascade.
  • Multisite tables without a prefix (usePrefix = false) are shared by every site, but the ledger is per site: a seed into one would repeat per site. Not tested live (no multisite here).

Refs #40

…eck on init

Every activation and every update used to run every migration and every seeder, and an
update ran them from upgrader_post_install: in the request doing the update, with the old
classes still loaded, and never for a ZIP replaced through Upload Plugin or for files copied
by FTP, git or Composer. A runOnce seeder ran only while its table was empty, so data added
in a later release never arrived (#40).

- Migrator: the files in database/migrations/ run once per site, in file name order,
  recorded by name in an option. A version stored per site is the cheap check on init that
  something may have changed; a pending migration that sorts before one that ran still runs,
  with a warning. One request at a time (INSERT IGNORE lock), stop at the first failure
  without recording it, tell the administrators, retry only from the admin.
- Migration moves to WPBones\Database\Migration and its constructor runs nothing; the 2.x
  name stays as a deprecated subclass. insert(), truncate(), isEmpty() for seed data.
- Seeders do not run any more: seed data is a migration. The class stays as a no-op so that
  a 2.x seeder file still loads during the update to 3.0.
- Activation read the plugin header nowhere: the slug was empty there and the options
  delta wrote to an options row with no name. It now loads the header first.
…table it is given

php bones migrate runs the pending migrations on this site through the plugin's own
runner, the way to run one added during development before a version bump. migrate:status
lists every migration, whether it ran, in which batch and version, and flags one that sorts
before a migration that already ran. Both exit 1 without WordPress above the plugin.

The migrate:create stub ignored the table name and always created my_plugin_products; it
now creates the table it was asked for, on the 3.0 base class.
…t dbDelta could not tidy

The first live run of the 2.1 → 3.0 update stopped at a 2.x migration: dbDelta() re-applying
a schema written on one line tried ALTER COLUMN `id` SET DEFAULT '' and MySQL refused. 2.x
ran that migration again on every activation and update and never saw the error; 3.0 applies
it once more and counted it as a failure, which blocked every migration after it.

create() now decides for itself: it throws when the table, or a column the schema declares
(read the way dbDelta reads them, one per line), is missing afterwards, and logs anything else
dbDelta left behind as tolerated. The Migrator skips exactly those errors, one occurrence
each, and the DESCRIBE probe dbDelta makes of a table it is about to create.
3.0 runs no seeders, so a plugin coming from 2.x needs its database folder converted:

- every database/migrations/*.php moves to the 3.0 base class name;
- every database/seeders/*.php becomes a migration that sorts after the latest migration, in
  the order the seeders ran, and the seeder file is deleted. The body of run() becomes up(),
  read with PHP's tokenizer so that comments and strings stay as they are; insert(),
  truncate() and count() gain the table the seeder implied, $this->tablename keeps working,
  and a seeder with $runOnce seeds only an empty table, as before;
- a seeder it cannot convert (no run(), other methods, no table) is kept and listed for
  review, and so is one that ran on every update and will now run once.

Running it again changes nothing. Migration gains count() and query(), the last two helpers
the 2.x Seeder had.
…Error

A deployed plugin has no namespace file, and getNamespace() died on it. The conversion belongs in
the plugin's sources: say so and exit 1, changing nothing.
…ry for the notice

A plugin moved to 3.0 without migrate:to-v3 now hears about its seeders when it is activated, not
only after an update. The admin notice reads the failure only when the stored version is behind
the plugin's, which a failure always leaves it: the steady state costs no query on admin pages.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Unresolved conversion and migration-state handling issues can lose seeder data or repeat database changes.

Review effort: Balanced
Findings: 4 High severity · 1 Medium severity

Open (5)
What changed in this PR

Redesigns WP Bones migrations for v3, replacing repeated activation/update execution with a per-site ledger and version-triggered runner, addressing #40.

Changes:

  • Adds migration tracking, locking, failure reporting, and controlled retries.
  • Moves seed operations into migrations with a non-executing constructor.
  • Adds migration CLI commands, a v3 converter, and regression coverage.
File Description
tests/​Unit/​SeederTest.php Tests legacy seeders as no-ops.
tests/​Unit/​OptionRepositoryTest.php Tests option persistence and locking behavior.
tests/​Unit/​MigratorTest.php Covers ordering, failures, retries, and tracking.
tests/​Unit/​MigrationTest.php Tests schema validation and seed helpers.
tests/​Support/​WpdbSpy.php Extends database test responses.
tests/​Support/​InMemoryMigrationRepository.php Adds an in-memory migration repository.
tests/​Console/​MigrateToV3Test.php Tests legacy seeder conversion.
tests/​Console/​MakeCommandsTest.php Covers migration generation and CLI prerequisites.
src/​Foundation/​Plugin.php Integrates migration triggers and failure notices.
src/​Database/​Seeder.php Retains a no-op compatibility class.
src/​Database/​Migrations/​OptionRepository.php Stores migration state and locks.
src/​Database/​Migrations/​Migrator.php Runs pending migrations and records outcomes.
src/​Database/​Migrations/​MigrationResult.php Represents migration run results.
src/​Database/​Migrations/​MigrationRepository.php Defines the migration storage contract.
src/​Database/​Migrations/​Migration.php Preserves the legacy class name.
src/​Database/​Migration.php Adds the new base class and seed helpers.
src/​Console/​stubs/​migrate.stub Uses the requested table and new base class.
src/​Console/​bin/​bones Adds execution, status, and conversion commands.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/Database/Migrations/Migrator.php Resolved
Comment thread src/Foundation/Plugin.php Resolved
Comment thread src/Database/Migrations/Migrator.php Resolved
The lock and the ledger:
- the lock row carries `time|token`: unlock() deletes only its own, touch() refreshes it before
  each migration, and an abandoned lock is taken over after an hour (WP_Upgrader's default)
  instead of ten minutes, so a long `php bones migrate` is not run twice;
- log() reports a ledger write the database refused, and the run stops there without moving
  the version, instead of running that migration again on the next update;
- a run started by a page load asks again under the lock: another request may have finished,
  or failed, while it waited, and a public page must not rerun what just failed;
- a cache older than the database (persistent object cache after an import) is dropped when
  refresh() sees it disagree, instead of costing a lock on every request.

Failures:
- the failure option stays, empty and autoloaded, so checking it costs no query; it is checked
  whatever the version, so a migration added without a bump that fails is retried from the admin
  and shown; a failure of 1.1.0 no longer holds back 1.1.1, which may fix it;
- insert(), truncate(), query() and count() throw when wpdb answers false, which it also does
  without recording an error (a value too long for its column).

The rest:
- activation finishes an update made while the plugin was inactive: plugin/updated.php runs;
- create() no longer counts CONSTRAINT, FOREIGN KEY and CHECK lines as columns;
- the automatic run is skipped under the bones CLI, so `php bones migrate` lists what it runs;
- OptionRepository::forget() for an uninstall.php that drops the tables;
- migrate:to-v3 reads the seeder's settings past its comments, keeps a namespace declaration,
  supports $this->wpdb, `$this -> insert(` and `$this?->insert(`, and flags truncate('name')
  under $usePrefix = false, which 2.x prefixed anyway.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🔵 Needs a closer look

Conversion safety and version-persistence failures remain unresolved and can cause lost source code or repeated update callbacks.

Review effort: Balanced
Findings: None

Resolved since last review (5)
Previously missed (1)

In code that hasn't changed since last review

Medium severity Failed version persistence incorrectly advances migration state

src/​Database/​Migrations/​OptionRepository.php:241

If update_option() refuses the version write, this still updates the in-memory version and Migrator marks the result as advanced. Plugin::finishMigration() then runs plugin/updated.php even though the stored version never changed; subsequent requests can repeat that callback for the same update. Verify persistence when update_option() returns false, accounting for an unchanged stored value, and report failure before marking the result advanced.

…rt without losing a seeder

From Copilot's second pass on #119:

- setVersion() reports a write the database refused (a false from update_option() is checked
  against the row), and only the request that stored the new version finishes the update, so
  plugin/updated.php runs once; the next request retries the write.
- migrate:to-v3 deletes a seeder only once its migration is written and passes php -l; a
  migration that does not parse is removed and the seeder kept, listed for review. A migration
  file it cannot rewrite is reported instead of counted as updated.
@gfazioli
gfazioli requested a balanced review from Copilot October 6, 2026 08:49

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@gfazioli
gfazioli merged commit f05c76b into v3 Oct 6, 2026
4 checks passed
@gfazioli
gfazioli deleted the feat/v3-migrations branch October 6, 2026 08:50
gfazioli added a commit that referenced this pull request Oct 6, 2026
The lock and the ledger:
- the lock row carries `time|token`: unlock() deletes only its own, touch() refreshes it before
  each migration, and an abandoned lock is taken over after an hour (WP_Upgrader's default)
  instead of ten minutes, so a long `php bones migrate` is not run twice;
- log() reports a ledger write the database refused, and the run stops there without moving
  the version, instead of running that migration again on the next update;
- a run started by a page load asks again under the lock: another request may have finished,
  or failed, while it waited, and a public page must not rerun what just failed;
- a cache older than the database (persistent object cache after an import) is dropped when
  refresh() sees it disagree, instead of costing a lock on every request.

Failures:
- the failure option stays, empty and autoloaded, so checking it costs no query; it is checked
  whatever the version, so a migration added without a bump that fails is retried from the admin
  and shown; a failure of 1.1.0 no longer holds back 1.1.1, which may fix it;
- insert(), truncate(), query() and count() throw when wpdb answers false, which it also does
  without recording an error (a value too long for its column).

The rest:
- activation finishes an update made while the plugin was inactive: plugin/updated.php runs;
- create() no longer counts CONSTRAINT, FOREIGN KEY and CHECK lines as columns;
- the automatic run is skipped under the bones CLI, so `php bones migrate` lists what it runs;
- OptionRepository::forget() for an uninstall.php that drops the tables;
- migrate:to-v3 reads the seeder's settings past its comments, keeps a namespace declaration,
  supports $this->wpdb, `$this -> insert(` and `$this?->insert(`, and flags truncate('name')
  under $usePrefix = false, which 2.x prefixed anyway.
gfazioli added a commit that referenced this pull request Oct 6, 2026
…rt without losing a seeder

From Copilot's second pass on #119:

- setVersion() reports a write the database refused (a false from update_option() is checked
  against the row), and only the request that stored the new version finishes the update, so
  plugin/updated.php runs once; the next request retries the write.
- migrate:to-v3 deletes a seeder only once its migration is written and passes php -l; a
  migration that does not parse is removed and the seeder kept, listed for review. A migration
  file it cannot rewrite is reported instead of counted as updated.
gfazioli added a commit that referenced this pull request Oct 6, 2026
The lock and the ledger:
- the lock row carries `time|token`: unlock() deletes only its own, touch() refreshes it before
  each migration, and an abandoned lock is taken over after an hour (WP_Upgrader's default)
  instead of ten minutes, so a long `php bones migrate` is not run twice;
- log() reports a ledger write the database refused, and the run stops there without moving
  the version, instead of running that migration again on the next update;
- a run started by a page load asks again under the lock: another request may have finished,
  or failed, while it waited, and a public page must not rerun what just failed;
- a cache older than the database (persistent object cache after an import) is dropped when
  refresh() sees it disagree, instead of costing a lock on every request.

Failures:
- the failure option stays, empty and autoloaded, so checking it costs no query; it is checked
  whatever the version, so a migration added without a bump that fails is retried from the admin
  and shown; a failure of 1.1.0 no longer holds back 1.1.1, which may fix it;
- insert(), truncate(), query() and count() throw when wpdb answers false, which it also does
  without recording an error (a value too long for its column).

The rest:
- activation finishes an update made while the plugin was inactive: plugin/updated.php runs;
- create() no longer counts CONSTRAINT, FOREIGN KEY and CHECK lines as columns;
- the automatic run is skipped under the bones CLI, so `php bones migrate` lists what it runs;
- OptionRepository::forget() for an uninstall.php that drops the tables;
- migrate:to-v3 reads the seeder's settings past its comments, keeps a namespace declaration,
  supports $this->wpdb, `$this -> insert(` and `$this?->insert(`, and flags truncate('name')
  under $usePrefix = false, which 2.x prefixed anyway.
gfazioli added a commit that referenced this pull request Oct 6, 2026
…rt without losing a seeder

From Copilot's second pass on #119:

- setVersion() reports a write the database refused (a false from update_option() is checked
  against the row), and only the request that stored the new version finishes the update, so
  plugin/updated.php runs once; the next request retries the write.
- migrate:to-v3 deletes a seeder only once its migration is written and passes php -l; a
  migration that does not parse is removed and the seeder kept, listed for review. A migration
  file it cannot rewrite is reported instead of counted as updated.
gfazioli added a commit that referenced this pull request Oct 6, 2026
The lock and the ledger:
- the lock row carries `time|token`: unlock() deletes only its own, touch() refreshes it before
  each migration, and an abandoned lock is taken over after an hour (WP_Upgrader's default)
  instead of ten minutes, so a long `php bones migrate` is not run twice;
- log() reports a ledger write the database refused, and the run stops there without moving
  the version, instead of running that migration again on the next update;
- a run started by a page load asks again under the lock: another request may have finished,
  or failed, while it waited, and a public page must not rerun what just failed;
- a cache older than the database (persistent object cache after an import) is dropped when
  refresh() sees it disagree, instead of costing a lock on every request.

Failures:
- the failure option stays, empty and autoloaded, so checking it costs no query; it is checked
  whatever the version, so a migration added without a bump that fails is retried from the admin
  and shown; a failure of 1.1.0 no longer holds back 1.1.1, which may fix it;
- insert(), truncate(), query() and count() throw when wpdb answers false, which it also does
  without recording an error (a value too long for its column).

The rest:
- activation finishes an update made while the plugin was inactive: plugin/updated.php runs;
- create() no longer counts CONSTRAINT, FOREIGN KEY and CHECK lines as columns;
- the automatic run is skipped under the bones CLI, so `php bones migrate` lists what it runs;
- OptionRepository::forget() for an uninstall.php that drops the tables;
- migrate:to-v3 reads the seeder's settings past its comments, keeps a namespace declaration,
  supports $this->wpdb, `$this -> insert(` and `$this?->insert(`, and flags truncate('name')
  under $usePrefix = false, which 2.x prefixed anyway.
gfazioli added a commit that referenced this pull request Oct 6, 2026
…rt without losing a seeder

From Copilot's second pass on #119:

- setVersion() reports a write the database refused (a false from update_option() is checked
  against the row), and only the request that stored the new version finishes the update, so
  plugin/updated.php runs once; the next request retries the write.
- migrate:to-v3 deletes a seeder only once its migration is written and passes php -l; a
  migration that does not parse is removed and the seeder kept, listed for review. A migration
  file it cannot rewrite is reported instead of counted as updated.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants