XMF Cookbook
Search…
Altering Database Tables
As a module grows, so does its database requirements. There have been many strategies to deal with the inevitable database changes, from custom .sql files to handwritten queries. Xmf\Database\Tables is an object oriented approach to a standard solution to this common problem.

Rename a Database Table

This scenario references a module called 'pedigree' and we are going to define an update function that will rename an old table named 'eigenaar' to a standardized name of 'pedigree_owner'.
First, the old way:
1
function tableExists($tablename)
2
{
3
global $xoopsDB;
4
$result=$xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
5
return($xoopsDB->getRowsNum($result) > 0);
6
}
7
8
function xoops_module_update_pedigree()
9
{
10
global $xoopsDB;
11
12
if (tableExists($xoopsDB->prefix('eigenaar'))) {
13
$sql = sprintf(
14
'ALTER TABLE ' . $xoopsDB->prefix('eigenaar')
15
. ' RENAME ' . $xoopsDB->prefix('pedigree_owner')
16
);
17
$result = $xoopsDB->queryF($sql);
18
if (!$result) {
19
echo '<br />' . _AM_PED_UPGRADEFAILED
20
. ' ' . _AM_PED_UPGRADEFAILED2;
21
$errors++;
22
}
23
}
24
return TRUE;
25
}
Copied!
Here is the same operation using the \Xmf\Database\Tables class:
1
function xoops_module_update_pedigree()
2
{
3
$tables = new \Xmf\Database\Tables();
4
if($tables->useTable('eigenaar')) { // if this returns false, there is no table
5
$tables->renameTable('eigenaar', 'pedigree_owner');
6
if(!$tables->executeQueue()) {
7
echo '<br />' . _AM_PED_UPGRADEFAILED . ' ' . $migrate->getLastError();
8
}
9
}
10
}
Copied!

Add a Column to a Table

Let's extend the previous example and suppose we also want to add a column, named 'registrar_code', as a varchar(24) at the same time. Here is the new function:
1
function xoops_module_update_pedigree()
2
{
3
$tables = new \Xmf\Database\Tables();
4
if($tables->useTable('eigenaar')) {
5
$tables->renameTable('eigenaar', 'pedigree_owner');
6
$tables->addColumn('pedigree_owner', 'registrar_code', "varchar(24) NOT NULL DEFAULT ''");
7
if(!$tables->executeQueue()) {
8
echo '<br />' . _AM_PED_UPGRADEFAILED . ' ' . $migrate->getLastError();
9
}
10
}
11
}
Copied!

Going Further

There are methods available to handle any needed table changes. Tables can be created, dropped, and altered. You can modify multiple tables in one pass. All modifications go into a queue, so you can halt the entire process easily if you find something is amiss. Refer to the reference documentation for Xmf\Database\Tables for details.
There are companion objects, too. Xmf\Database\TableLoad can assist in adding data to tables. Xmf\Database\Migrate builds on Tables, adding automated schema comparison and synchronization.
It is worth considering these classes whenever you need to add or modify tables for your module.
Last modified 3yr ago