phlib/schema-change

用于执行MySQL DDL操作的库,可以使用简单的SQL或Percona Tools在线模式变更。

1.0.0 2022-09-14 11:41 UTC

This package is auto-updated.

Last update: 2024-09-04 09:29:22 UTC


README

Code Checks Codecov Latest Stable Version Total Downloads Licence

用于执行MySQL DDL操作的库,可以使用简单的SQL或Percona Tools在线模式变更。

该库设计为可用于任何现有的迁移管理工具。

用法

设置

$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 = $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 = $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 = $schemaChange->drop('widget');
$schemaChange->execute($drop);

许可证

此软件包是免费软件:您可以自由分发和/或修改它,前提是遵守自由软件基金会发布的GNU通用公共许可证的条款,无论是许可证的第3版,还是(根据您的选择)任何后续版本。

分发此程序是希望它有用,但没有提供任何保证;甚至没有隐含的对适销性或特定用途的适用性的保证。有关详细信息,请参阅GNU通用公共许可证。

您应已收到GNU通用公共许可证的副本。如果没有,请参阅https://gnu.ac.cn/licenses/