PHP code example of phlib / schema-change

1. Go to this page and download the library: Download phlib/schema-change library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phlib / schema-change example snippets


$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);