phlib/schema-change

Library for performing MySQL DDL operations, using either simple SQL or Percona Tools Online Schema Change

1.0.0 2022-09-14 11:41 UTC

This package is auto-updated.

Last update: 2024-07-04 09:08:39 UTC


README

phlib/schema-change

Code Checks Codecov Latest Stable Version Total Downloads Licence

Library for performing MySQL DDL operations, using either simple SQL or Percona Tools Online Schema Change.

This library is designed to be able to be used in any existing migrations management tool.

Usage

Setup

$db = new Phlib\Db\Adapter([
    'host' => '127.0.0.1',
    'port' => '3306',
    'username' => 'root',
    'password' => '',
    'dbname' => 'base_schema',
]);


$schemaChange = new \Phlib\SchemaChange\SchemaChange(
    $db,
    new \Phlib\SchemaChange\OnlineChangeRunner('/usr/local/bin/pt-online-schema-change')
);

$schemaChange->mapNames(new class implements \Phlib\SchemaChange\NameMapper {
    public function mapTableName(string $table): string
    {
        return 'prefix_' . $table;
    }
});

Create a table

$create = $schemaChange->create('widget');

$create->addColumn('id', 'int(11)')->unsigned()->notNull()->autoIncrement();
$create->addColumn('folder_id', 'int(11)')->notNull();
$create->addColumn('name', 'varchar(255)')->notNull();
$create->addColumn('data', 'text')->notNull()->defaultTo('');
$create->addColumn('create_ts', 'timestamp')->notNull()->defaultRaw('CURRENT_TIMESTAMP')

$create->primary('id');
$create->addIndex('folder_id', 'name')->unique();
$create->attribute('DEFAULT CHARSET', 'ascii');

$schemaChange->execute($create);

Alter a table

$alter = $schemaChange->alter('widget')
    ->onlineChange();

$alter->removeColumn('data');
$alter->addColumn('alias', 'varchar(100)')->nullable()->after('name');
$alter->addColumn('update_ts', 'timestamp')->after('create_ts')->notNull()
    ->defaultRaw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP');

$alter->removeIndex('widget_folder_id_name_idx');

$schemaChange->execute($alter);

Drop a table

$drop = $schemaChange->drop('widget');
$schemaChange->execute($drop);

License

This package is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/.