XMF Cookbook
Search…
Migrating a Module's Database
Over time, a module can accumulate numerous database changes. For simple situations, where there are a small set of known changes, the Tables class may be an appropriate solution. For larger change sets, possibly spanning multiple generations or versions of a module, determining which changes need to be applied quickly becomes the most serious concern. Xmf\Database\Migrate assists in solving this problem by comparing the existing tables against a prepared schema description and generating the needed data definition language (DDL) statements to convert the existing tables to the target schema definition.
The automated migration DDL fully handles situations such adding or dropping tables or columns, as well as changing column attributes, such as type, length or default value. Indexes are also synchronized.
For more complex requirements, such as renaming tables or columns, and data conversion, it is possible to manually specify DDL or SQL statements that will be run prior to the automatic synchronization.

Basics

Tables must be declared in your module's xoops_version.php file. The $modversion['tables'] entry should be an array of table names. This is an existing standard for all XOOPS modules, an this note is simply to reinforce that Migrate depends on this information.
Typically, a database is initially prepared through a database tool, such as phpMyAdmin, MySQL Workbench or other interactive modeling tool. Once the database is defined, we can generate Migrate's internal schema representation to use in migrating any existing tables. For existing modules, the schema can be prepared from the tables it creates.
Directly editing a generated schema representation is NOT recommended. The schema generation and comparison are closely related, and direct changes may result in tables that work correctly, but appear to need updated on each comparison.
For simple situations, you can use Xmf\Database\Migrate directly. For more involved migrations, it is best to extend Migrate with your own module specific class to take full advantage of the available features.

Generate a Schema Definition

To generate a schema definition from your existing tables, instantiate a Migrate object, passing it your module's directory name (dirname.) Then, invoke the saveCurrentSchema() method.
This will save a schema file to the module's sql directory. The file is named based on the dirname and the module's version.
1
$migrate = new Xmf\Database\Migrate('mymodule');
2
$result = $migrate->saveCurrentSchema();
3
if (false === $result) {
4
// the schema was not saved, handle the error condition
5
}
Copied!

Basic Synchronization

To synchronize any existing table to a stored scheme definition takes only one call to synchronizeSchema().
This can add and drop tables, add and drop columns, and add and drop indexes.
1
function xoops_module_update_mymodule(XoopsModule $module)
2
{
3
$migrate = new Xmf\Database\Migrate('mymodule');
4
$result = $migrate->synchronizeSchema();
5
return true;
6
}
Copied!

Rename a Set of Tables

Naming conventions have changed over time, so preparing an older set of tables to use with a new software version often requires checking to see if renaming is needed, and conditionally renaming the existing tables.
In this scenario we will rename the tables in newbb to conform to module standards that the table name begin with the module name and an underscore.
Migrate can easily handle dropping and adding columns, tables and indexes. Migrate can't automatically handle renaming a table or column. To synchronizeSchema() a renamed column looks just like a dropped column and a added column. To resolve this ambiguity, we need to explicitly rename entities in our custom class that extends Migrate.
For this, we will extend Migrate and take advantage of the preSyncActions() hook. By doing these changes before the synchronization, we can make all the needed changes in one pass. We created a schema file using the new names that is distributed with the module, so once the tables are renamed, we can synchronize any other changes.
Migrate automatically gives us an instance of Xmf\Database\Tables and we can add any extra commands we need.
1
class NewbbMigrate extends Xmf\Database\Migrate
2
{
3
// a array of 'old_name' => 'new_name' pairs
4
private $renameTables = array(
5
'bb_archive' => 'newbb_archive',
6
'bb_categories' => 'newbb_categories',
7
'bb_votedata' => 'newbb_votedata',
8
'bb_forums' => 'newbb_forums',
9
'bb_posts' => 'newbb_posts',
10
'bb_posts_text' => 'newbb_posts_text',
11
'bb_topics' => 'newbb_topics',
12
'bb_online' => 'newbb_online',
13
'bb_digest' => 'newbb_digest',
14
'bb_report' => 'newbb_report',
15
'bb_attachments' => 'newbb_attachments',
16
'bb_moderates' => 'newbb_moderates',
17
'bb_reads_forum' => 'newbb_reads_forum',
18
'bb_reads_topic' => 'newbb_reads_topic',
19
'bb_type' => 'newbb_type',
20
'bb_type_forum' => 'newbb_type_forum',
21
'bb_stats' => 'newbb_stats',
22
'bb_user_stats' => 'newbb_user_stats',
23
);
24
25
/**
26
* NewbbMigrate constructor.
27
*/
28
public function __construct()
29
{
30
parent::__construct('newbb');
31
}
32
33
/**
34
* change table prefix if needed
35
*/
36
private function changePrefix()
37
{
38
foreach ($this->renameTables as $oldName => $newName) {
39
if ($this->tableHandler->useTable($oldName)) {
40
$this->tableHandler->renameTable($oldName, $newName);
41
}
42
}
43
}
44
45
/**
46
* Perform any upfront actions before synchronizing the schema
47
*
48
* @return void
49
*/
50
protected function preSyncActions()
51
{
52
// change 'bb' table prefix to 'newbb'
53
$this->changePrefix();
54
}
55
}
Copied!
We kick this off with this function in our $modversion['onUpdate'] file. We use the pre_update function, so that we change the tables to the correct names before any other update processing.
1
function xoops_module_pre_update_newbb(XoopsModule $module)
2
{
3
XoopsLoad::load('migrate', 'newbb');
4
$newbbMigrate = new NewbbMigrate();
5
$newbbMigrate->synchronizeSchema();
6
7
return true;
8
}
Copied!

Convert a Changed Column

Let's extend the previous example and suppose we also want to convert an IP Address column to handle IPv6 addresses as part of the migration. The old column was integer, with the addresses in network form, but we are changing to a varchar column, with the address in a human readable form.
1
class NewbbMigrate extends Xmf\Database\Migrate
2
{
3
// a array of 'old_name' => 'new_name' pairs
4
private $renameTables = array(
5
'bb_archive' => 'newbb_archive',
6
'bb_categories' => 'newbb_categories',
7
'bb_votedata' => 'newbb_votedata',
8
'bb_forums' => 'newbb_forums',
9
'bb_posts' => 'newbb_posts',
10
'bb_posts_text' => 'newbb_posts_text',
11
'bb_topics' => 'newbb_topics',
12
'bb_online' => 'newbb_online',
13
'bb_digest' => 'newbb_digest',
14
'bb_report' => 'newbb_report',
15
'bb_attachments' => 'newbb_attachments',
16
'bb_moderates' => 'newbb_moderates',
17
'bb_reads_forum' => 'newbb_reads_forum',
18
'bb_reads_topic' => 'newbb_reads_topic',
19
'bb_type' => 'newbb_type',
20
'bb_type_forum' => 'newbb_type_forum',
21
'bb_stats' => 'newbb_stats',
22
'bb_user_stats' => 'newbb_user_stats',
23
);
24
25
/**
26
* NewbbMigrate constructor.
27
*/
28
public function __construct()
29
{
30
parent::__construct('newbb');
31
}
32
33
/**
34
* change table prefix if needed
35
*/
36
private function changePrefix()
37
{
38
foreach ($this->renameTables as $oldName => $newName) {
39
if ($this->tableHandler->useTable($oldName)) {
40
$this->tableHandler->renameTable($oldName, $newName);
41
}
42
}
43
}
44
45
/**
46
* Change integer IPv4 column to varchar IPv6 capable
47
*
48
* Convert to int to big int, and adjust for signed conversion,
49
* then convert to varchar and run INET_NTOA conversion
50
*
51
* @param string $tableName table to convert
52
* @param string $columnName column with IP address
53
*
54
* @return void
55
*/
56
private function convertIPAddresses($tableName, $columnName)
57
{
58
if ($this->tableHandler->useTable($tableName)) {
59
$attributes = $this->tableHandler->getColumnAttributes($tableName, $columnName);
60
if (false !== strpos($attributes, ' int(')) {
61
if (false === strpos($attributes, 'unsigned')) {
62
$this->tableHandler->alterColumn($tableName, $columnName, " bigint(16) NOT NULL DEFAULT '0' ");
63
$this->tableHandler->update(
64
$tableName,
65
array($columnName => "4294967296 + $columnName"),
66
"WHERE $columnName < 0",
67
false
68
);
69
}
70
$this->tableHandler->alterColumn($tableName, $columnName, " varchar(45) NOT NULL DEFAULT '' ");
71
$this->tableHandler->update($tableName, array($columnName => "INET_NTOA($columnName)"), '', false);
72
}
73
}
74
}
75
76
/**
77
* Perform any upfront actions before synchronizing the schema
78
*
79
* @return void
80
*/
81
protected function preSyncActions()
82
{
83
// change 'bb' table prefix to 'newbb'
84
$this->changePrefix();
85
// Convert IP address columns from int to readable varchar(45) for IPv6
86
$this->convertIPAddresses('newbb_posts', 'poster_ip');
87
}
88
}
Copied!
Last modified 3yr ago