Lets assume following situation:
I develop a plugin. The plugin requires custom database table to store some kind of information.
From month to month I release new versions of my plugin. Different versions could have their own sets of changes of the table structure and table’s data. For instance:
- version 1.0.0 has initial setup for table structure
- version 1.1.0 has changes to one column type and requires to perform update operation over data of this column
- version 2.0.0 requires creation of two new columns, splitting data from old column to new columns and removal of old/deprecated column
The problem:
Lets consider two use cases:
- An user downloaded version 1.0.0, skipped update to version 1.1.0 and decided to update the plugin when the version 2.0.0 was released. How to organize database upgrade process, which will handle upgrade from version 1.0.0 to version 2.0.0 including changes from version 1.1.0?
- An user downloaded version 2.0.0 and installed it on a blank instance of WordPress. How to perform the latest version of database installation, which will include all changes from all versions compliance with DRY principles?
Ok, to resolve these issues, let’s implement the cascading upgrade process which will handle both use cases.
First of all lets implement our plugin activation hook, which will be our entry point:
Before start looking at upgrade hooks, lets create a helper function which will help us to execute a set of sql queries:
Finally, lets see our upgrade hooks. Upgrade database from 0.0.0 to 1.0.0:
Upgrade database from 1.0.0 to 1.1.0:
Upgrade database from 1.1.0 to 2.0.0:
Lets see how our approach handle both use cases:
wpse8170_upgrade_to_10000
as we already have database version equals to1.0.0
and pass through hookswpse8170_upgrade_to_11000
andwpse8170_upgrade_to_20000
upgrading our database to the latest version including missed version 1.1.0