Change Method.

Write your reversible migrations using this method.

More information on writing migrations is available here:
http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
14897
public function change()
    {
        $table = $this->table('link', array('id' => false, 'primary_key' => array('link')));
        $table->addColumn('link', 'string', array('limit' => 100))
              ->addColumn('url', 'string', array('limit' => 500))
              ->addColumn('active', 'boolean')
              ->create();
    }
1364181
def migrate(direction)
      return unless respond_to?(direction)

      case direction
      when :up   then announce "migrating"
      when :down then announce "reverting"
      end

      time   = nil
      ActiveRecord::Base.connection_pool.with_connection do |conn|
        @connection = conn
        if respond_to?(:change)
          if direction == :down
            recorder = CommandRecorder.new(@connection)
            suppress_messages do
              @connection = recorder
              change
            end
            @connection = conn
            time = Benchmark.measure {
              self.revert {
                recorder.inverse.each do |cmd, args|
                  send(cmd, *args)
                end
              }
            }
          else
            time = Benchmark.measure { change }
          end
        else
          time = Benchmark.measure { send(direction) }
        end
        @connection = nil
      end

      case direction
      when :up   then announce "migrated (%.4fs)" % time.real; write
      when :down then announce "reverted (%.4fs)" % time.real; write
      end
    end
1200648
public function change() {
		$this->table('queue_processes')
			->changeColumn('created', 'datetime', ['null' => false, 'default' => null])
			->changeColumn('modified', 'datetime', ['null' => false, 'default' => null])
			->update();

		$this->table('queued_jobs')
			->changeColumn('created', 'datetime', ['null' => false, 'default' => null])
			->update();
	}
1221613
public function change()
    {
        $tableName = 'language_translations';
        if (!$this->hasTable($tableName)) {
            $tableName = 'translations';
        }

        $table = $this->table($tableName);
        if (!$table->hasColumn('is_active')) {
            $table->addColumn('is_active', 'boolean', [
                'default' => 0,
                'null' => false,
            ]);
        }
        $table->update();
    }
657742
public function up()
	{
		if(! Schema::hasColumn('001_028_field_result', 'data_type_type_028'))
		{
			Schema::table('001_028_field_result', function (Blueprint $table) {
				// rename column
				DB::select(DB::raw('ALTER TABLE 001_028_field_result CHANGE type_028 data_type_type_028 VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL'));
			});
		}
	}
801588
def migration(resource, version, previous_version=''):
    """"""
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            migrated = func(*args, **kwargs)

            return migrated

        m = Migration(wrapper, resource, version, previous_version)
        m.register()

        return m

    return decorator
509484
public void undo() {

        if (hasUndo()) {
            ChangeType type = m_current.getType();
            String entityId = m_current.getEntityId();
            String attributeName = m_current.getAttributeName();
            int valueIndex = m_current.getValueIndex();
            m_redo.push(m_current);
            m_current = m_undo.pop();
            changeEntityContentValues(m_current.getEntityData(), entityId, attributeName, valueIndex, type);
            fireStateChange();
        }
    }
1258052
public function generateMigration()
    {
        if (!$this->confirm('Do you want to create a migration?')) {
            return;
        }

        $this->console->call('generate:migration', [
            'name' => "create_{$this->getEntities()}_table",
            '--fields' => $this->console->option('fields'),
            '--force' => $this->console->option('force'),
        ]);
    }
174128
public function migrateDown()
    {
        try {
            $this->builder->table(
                $this->table,
                function ($table) {
                    $table->string('name', 255)->change();
                    $table->unique('name');
                }
            );
        } catch (\Exception $e) {
        }
    }
924650
def migrate1():
    ""

    initial = [
    "create table Chill (version integer);",
    "insert into Chill (version) values (1);",
    "alter table SelectSQL rename to Query;",
    "alter table Node add column template integer references Template (id) on delete set null;",
    "alter table Node add column query integer references Query (id) on delete set null;"
    ]


    cleanup = [
    "drop table SelectSQL_Node;",
    "drop table Template_Node;"
    ]

    c = db.cursor()
    try:
        c.execute("select version from Chill limit 1;")
    except sqlite3.DatabaseError as err:
        pass
    result = c.fetchone()
    if result:
        version = result[0]
        if version == 1:
            current_app.logger.warn("Migration from version 0 to 1 is not needed.")
        else:
            current_app.logger.warn("Migration from version 0 to {0} is not supported.".format(version))
        return

    try:
        for query in initial:
            c.execute(query)
    except sqlite3.DatabaseError as err:
        current_app.logger.error("DatabaseError: %s", err)

    try:
        c.execute(fetch_query_string('select_all_nodes.sql'))
    except sqlite3.DatabaseError as err:
        current_app.logger.error("DatabaseError: %s", err)
    result = c.fetchall()
    if result:
        (result, col_names) = rowify(result, c.description)
        for kw in result:

            try:
                c.execute("""
                update Node set template = (
                select t.id from Template as t
                join Template_Node as tn on ( tn.template_id = t.id )
                join Node as n on ( n.id = tn.node_id )
                where n.id is :node_id
                group by t.id)
                where id is :node_id;
                """, {'node_id':kw['id']})
            except sqlite3.DatabaseError as err:
                current_app.logger.error("DatabaseError: %s", err)

            try:
                c.execute("""
                update Node set query = (
                select s.id from Query as s
                join SelectSQL_Node as sn on ( sn.selectsql_id = s.id )
                join Node as n on ( n.id = sn.node_id )
                where n.id is :node_id
                group by s.id)
                where id is :node_id;
                """, {'node_id':kw['id']})
            except sqlite3.DatabaseError as err:
                current_app.logger.error("DatabaseError: %s", err)
    try:
        for query in cleanup:
            c.execute(query)
    except sqlite3.DatabaseError as err:
        current_app.logger.error("DatabaseError: %s", err)

    db.commit()
877540
public function migrate()
	{
		$this->msg( sprintf( 'Add new type columns for Laravel' ), 0 );
		$this->status( '' );

		foreach( $this->tables as $rname => $list ) {
			$this->addColumn( $rname, $list );
		}

		$this->msg( sprintf( 'Drop old unique indexes for Laravel' ), 0 );
		$this->status( '' );

		foreach( $this->constraints as $rname => $list ) {
			$this->dropIndex( $rname, $list );
		}

		$this->msg( sprintf( 'Migrate typeid to type for Laravel' ), 0 );
		$this->status( '' );

		foreach( $this->migrations as $rname => $list ) {
			$this->migrateData( $rname, $list );
		}
	}
118805
function performMigration(direction, migrateTo, next) {
		if (!next &&
	    Object.prototype.toString.call(migrateTo) === '[object Function]') {
	    next = migrateTo;
	    migrateTo = undefined;
	  }

		if (!next) {
			next = function(err) {
				if (err) {
					console.error(err);
					process.exit(1);
				} else {
					process.exit();
				}
			}
		}

		var db = require('./lib/db');
		db.getConnection(dbConfig || require(process.cwd() + path.sep + configFileName)[dbProperty], function (err, db) {
			if (err) {
				return next(new verror.WError(err, 'Error connecting to database'));
			}
			var migrationCollection = db.migrationCollection,
					dbConnection = db.connection;

			migrationCollection.find({}).sort({num: -1}).limit(1).toArray(function (err, migrationsRun) {
				if (err) {
					return next(new verror.WError(err, 'Error querying migration collection'));
				}

				var lastMigration = migrationsRun[0],
					lastMigrationNum = lastMigration ? lastMigration.num : 0;

				migrate({
					migrationTitle: 'migrations/.migrate',
					db: dbConnection,
					migrationCollection: migrationCollection
				});
				migrations(direction, lastMigrationNum, migrateTo).forEach(function(path){
					var mod = require(process.cwd() + '/' + path);
					migrate({
						num: parseInt(path.split('/')[1].match(/^(\d+)/)[0], 10),
						title: path,
						up: mod.up,
						down: mod.down});
				});

				//Revert working directory to previous state
				process.chdir(previousWorkingDirectory);

				var set = migrate();

				set.on('migration', function(migration, direction){
					log(direction, migration.title);
				});

				set.on('save', function(){
					log('migration', 'complete');
					return next();
				});

				set[direction](null, lastMigrationNum);
			});
		});
	}
1346427
public function up()
    {
        $driver = Schema::getConnection()->getDriverName();
        // Even though we take care of this scenario in the code,
        // SQL Server does not allow potential cascading loops,
        // so set the default no action and clear out created/modified by another user when deleting a user.
        $onDelete = (('sqlsrv' === $driver) ? 'no action' : 'set null');

        $output = new ConsoleOutput();
        $output->writeln("Migration driver used: $driver");

        // Script Service Config
        if (!Schema::hasTable('script_config')) {
            Schema::create(
                'script_config',
                function (Blueprint $t) {
                    $t->integer('service_id')->unsigned()->primary();
                    $t->foreign('service_id')->references('id')->on('service')->onDelete('cascade');
                    $t->mediumText('content')->nullable();
                    $t->text('config')->nullable();
                }
            );
        }

        // Event Scripts
        if (!Schema::hasTable('event_script')) {
            Schema::create(
                'event_script',
                function (Blueprint $t) use ($onDelete) {
                    $t->string('name', 80)->primary();
                    $t->string('type', 40);
                    $t->boolean('is_active')->default(0);
                    $t->mediumText('content')->nullable();
                    $t->text('config')->nullable();
                    $t->timestamp('created_date')->nullable();
                    $t->timestamp('last_modified_date')->useCurrent();
                    $t->integer('created_by_id')->unsigned()->nullable();
                    $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete);
                    $t->integer('last_modified_by_id')->unsigned()->nullable();
                    $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete);
                }
            );
        }
    }
534500
public function change() {
		$table = $this->table('queue_processes');
		$table->changeColumn('pid', 'string', [
			'length' => 40,
			'null' => false,
			'default' => null,
			'encoding' => 'ascii',
			'collation' => 'ascii_general_ci',
		]);
		$table->update();

		$table = $this->table('queued_jobs');
		$table->changeColumn('job_type', 'string', [
			'length' => 45,
			'null' => false,
			'default' => null,
			'encoding' => 'utf8mb4',
			'collation' => 'utf8mb4_unicode_ci',
		]);
		$table->changeColumn('job_group', 'string', [
			'length' => 255,
			'null' => true,
			'default' => null,
			'encoding' => 'utf8mb4',
			'collation' => 'utf8mb4_unicode_ci',
		]);
		$table->changeColumn('reference', 'string', [
			'length' => 255,
			'null' => true,
			'default' => null,
			'encoding' => 'utf8mb4',
			'collation' => 'utf8mb4_unicode_ci',
		]);
		$table->changeColumn('workerkey', 'string', [
			'length' => 45,
			'null' => true,
			'default' => null,
			'encoding' => 'utf8mb4',
			'collation' => 'utf8mb4_unicode_ci',
		]);
		$table->changeColumn('status', 'string', [
			'length' => 255,
			'null' => true,
			'default' => null,
			'encoding' => 'utf8mb4',
			'collation' => 'utf8mb4_unicode_ci',
		]);
		$table->update();

		//TODO: check adapter and skip for postgres, instead of try/catch
		try {
			$table = $this->table('queued_jobs');
			$table->changeColumn('data', 'text', [
				'limit' => MysqlAdapter::TEXT_MEDIUM,
				'null' => true,
				'default' => null,
				'encoding' => 'utf8mb4',
				'collation' => 'utf8mb4_unicode_ci',
			]);
			$table->changeColumn('failure_message', 'text', [
				'limit' => MysqlAdapter::TEXT_MEDIUM,
				'null' => true,
				'default' => null,
				'encoding' => 'utf8mb4',
				'collation' => 'utf8mb4_unicode_ci',
			]);
			$table->update();
		} catch (Exception $e) {
			Debugger::dump($e->getMessage());
		}
	}
129415
public static function rollback()
	{
		// first of all we have to filter only the already migrated versions
		$available = static::available();
		
		foreach( $available as $key => $migrations )
		{
			foreach( $migrations as $time => $migration )
			{
				if ( $time > static::$config->get( $key.'.revision', 0 ) )
				{
					unset( $available[$key][$time] );
				}
			}
		}
		
		$revisions = array();
		
		foreach( $available as $key => $value )
		{
			if ( empty( $value ) )
			{
				continue;
			}
			
			foreach( $value as $name => $path )
			{
				$revisions[$name.'::'.$key] = $path;
			}
		}
		
		// nothing to rollback?
		if ( empty( $revisions ) )
		{
			if ( \ClanCats::is_cli() )
			{
				\CCCli::warning( 'nothing to rollback to.' );
			}
			
			return false;
		}
		
		ksort( $revisions );
		
		end( $revisions ); 
		list( $time, $key ) = explode( '::', key( $revisions ) );
		
		$migration = new static( array_pop( $revisions ) );
		
		// rollback the migration
		$migration->down();
		
		// get the lastet migration from the group
		$others = \CCArr::get( $key, $available );
		
		ksort( $others );
		array_pop( $others );
		end( $others );
		
		// update the config
		static::$config->set( $key.'.revision', key( $others ) );
		static::$config->write();
		
		return true;
	}
1336139
public static function migrate()
    {
        foreach (static::$foreignKeys as $foreignKey) {
            Schema::table($foreignKey['table'], function (Blueprint $table) use ($foreignKey) {
                $table->foreign($foreignKey['column'], $foreignKey['key_name'])
                ->references($foreignKey['primary_key'])
                ->on($foreignKey['reference_table'])
                ->onDelete($foreignKey['on_delete'])
                ->onUpdate($foreignKey['on_update']);
            });
        }

        static::$foreignKeys = [];
    }
475052
public function change() {
		$table = $this->table('queued_tasks');
		$table->addColumn('jobtype', 'string', ['length' => 45])
			->addColumn('data', 'text', ['null' => true])
			->addColumn('group', 'string', ['length' => 255, 'null' => true, 'default' => null])
			->addColumn('reference', 'string', ['length' => 255, 'null' => true, 'default' => null])
			->addColumn('created', 'datetime', ['null' => true, 'default' => null])
			->addColumn('notbefore', 'datetime', ['null' => true, 'default' => null])
			->addColumn('fetched', 'datetime', ['null' => true, 'default' => null])
			->addColumn('completed', 'datetime', ['null' => true, 'default' => null])
			->addColumn('progress', 'float', ['null' => true])
			->addColumn('failed', 'integer', ['default' => 0])
			->addColumn('failure_message', 'text', ['null' => true])
			->addColumn('workerkey', 'string', ['length' => 45, 'null' => true, 'default' => null])
			->create();
	}