LoginSignup
2
2

More than 5 years have passed since last update.

FuelPHPでMySQLにインデックスを追加するタスク

Last updated at Posted at 2014-12-25

マイグレーションでも追加できるけど、運用後にインデックスだけメンテナンスしたい場合に不便なので、インデックス関係だけタスクにまとめてしまおうということ。

タスクを作成

ダウンロード(Gist)

fuel/app/tasks/migrate_indexes.php
<?php

namespace Fuel\Tasks;

class Migrate_indexes
{

    public static function run()
    {
    }

    public static function up()
    {
        static::_up('topics', array('id'), 'idx_id');
        static::_up('topics', array('deleted_at'), 'idx_dl');
        static::_up('topics', array('id','deleted_at'), 'idx_id_dl');
        static::_up('topics', array('deleted_at','created_at'), 'idx_dl_cr');
        static::_up('topics', array('created_at'), 'idx_cr');

        static::_up('comments', array('id'), 'idx_id');
        static::_up('comments', array('deleted_at'), 'idx_dl');
        static::_up('comments', array('id','deleted_at'), 'idx_id_dl');
        static::_up('comments', array('deleted_at','created_at'), 'idx_dl_cr');
    }

    public static function down()
    {
        static::_down('topics', 'idx_id');
        static::_down('topics', 'idx_dl');
        static::_down('topics', 'idx_id_dl');
        static::_down('topics', 'idx_dl_cr');
        static::_down('topics', 'idx_cr');

        static::_down('comments', 'idx_id');
        static::_down('comments', 'idx_dl');
        static::_down('comments', 'idx_dl_cr');
        static::_down('comments', 'idx_cr');
    }

    protected static function _up($table, $index_columns, $index_name)
    {
        try{
            \DBUtil::create_index($table, $index_columns, $index_name);
            \Cli::write(\Cli::color('Created index: '.$table. ' : '. implode(',',$index_columns). ' : '. $index_name, 'green'));
        }catch( \Fuel\Core\Database_Exception $e ){
        }
    }

    protected static function _down($table, $index_name)
    {
        try{
            \DBUtil::drop_index($table, $index_name);
            \Cli::write(\Cli::color('Dropped index: '.$table. ' : '. $index_name, 'green'));
        }catch( \Fuel\Core\Database_Exception $e ){
        }
    }
}

実行

インデックスを追加

php oil r migrate_indexes:up

インデックスを削除

php oil r migrate_indexes:down
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2