6.0.0-git
2024-03-19
Last Modified 2020-05-07 by Guest

Horde_Db Library and Horde Database Migrations

Horde DB: Usage by Example

Get a Connection object

Selecting Values

Insert

Delete

Getting a DB handle from inside a Horde_Core_Application context

Migrations: Usage by Example

Migrations are PHP Class files in the /migration/ sub folder of an app or library. They can be run via the horde-db-migrate script or the web UI.
They allow schema and data conversions forward and back.

Schema files prepend the lowercased class name with a version:

The first version's file would be 1_$app_foo (usually 1_$app_base_tables) which would contain the class named $AppFoo ($AppBaseTables) derived from Horde_Db_Migration_Base. See https://github.com/horde/skeleton/blob/master/migration/1_skeleton_base_tables.php for a complete example.

These classes usually contain an up() and down() method to implement upgrades or downgrades to the next/previous schema.

Errors during Schema upgrades need to be handled by the implementer himself. There is no implicit rollback of schema upgrades which fail halfway through the up() method unless you implement an appropriate try/catch block yourself.

Adding a new table

Removing a table

Adding a new column to an existing table

Dropping a column from an existing table

Adding an index

It's possible to use a helper function to check if an index is already set:

/**
 * Helper function to test if an index already exists
 */
private function hasIndex($tableName, $column)
{
    $indexedColumns = array();
    foreach ($this->indexes($tableName) as $index) {
        $indexedColumns = array_merge($indexedColumns, $index->columns);
    }

    if (is_array($column)) {
        foreach ($column as $entry) {
            return in_array($entry, $indexedColumns);
        }
    } else {
        return in_array($column, $indexedColumns);
    }
}

Add the index

if (!$this->hasIndex('my_table', array('my_column', 'my_column2'))) {
    $this->addIndex('my_table', array('my_column', 'my_column2'));
}

It's also possible to add unique keys or a self defined names via the options:

if (!$this->hasIndex('my_table', 'my_column')) {
    $this->addIndex('my_table', 'my_column', array('unique' => true));
}

Adding a unique key / unique index

Converting for Non-Horde or Pre-H4 schemas

Check for all table's existence before adding them

Manipulating data while changing fields