Skip to content

Instantly share code, notes, and snippets.

@lukearmstrong
Created March 8, 2012 09:43
Show Gist options
  • Save lukearmstrong/1999995 to your computer and use it in GitHub Desktop.
Save lukearmstrong/1999995 to your computer and use it in GitHub Desktop.
Migrations Example
<?php
namespace Fuel\Migrations;
class Create_Users
{
protected static $users_table;
public function __construct()
{
\Config::load('propauth', true);
$user_model = \Config::get('propauth.users_model', 'PropAuth\Model_User');
static::$users_table = $user_model::table();
}
public function up()
{
try {
\DB::start_transaction();
\DBUtil::create_table(
static::$users_table,
array(
'id' => array(
'type' => 'int',
'constraint' => 11,
'auto_increment' => true,
'unsigned' => true,
),
'email' => array(
'type' => 'varchar',
'constraint' => 254, // An E-Mail address cannot be longer than 254 characters
),
'display_name' => array(
'type' => 'tinytext',
),
'password' => array(
'type' => 'char',
'constraint' => 128,
'null' => true
),
'last_login' => array(
'type' => 'datetime',
'null' => true
),
'created_at' => array(
'type' => 'timestamp',
'default' => \DB::expr('CURRENT_TIMESTAMP')
),
'updated_at' => array(
'type' => 'datetime',
'null' => true
),
),
array('id'),
true,
'InnoDB',
'utf8_general_ci'
);
\DBUtil::create_index(static::$users_table, array('email'), 'UK_email', 'unique'); // UK = Unique Key
\DB::commit_transaction();
\Cli::write('Migration Successful: '.__METHOD__.' in '. __FILE__, 'green');
}
catch (\Exception $e) {
\DB::rollback_transaction();
\Cli::error('Migration Failed: '.__METHOD__.' in '. __FILE__);
\Cli::write($e->getMessage());
// Unless there is a better way to prevent the Migration version from incrementing on failure.
exit;
}
}
public function down()
{
try {
\DB::start_transaction();
\DBUtil::drop_index(static::$users_table, 'UK_email');
\DBUtil::drop_table(static::$users_table);
\DB::commit_transaction();
\Cli::write('Migration Successful: '. __METHOD__.' in '. __FILE__, 'green');
}
catch (\Exception $e) {
\DB::rollback_transaction();
\Cli::error('Migration Failed: '.__METHOD__.' in '. __FILE__);
\Cli::write($e->getMessage());
// Unless there is a better way to prevent the Migration version from incrementing on failure.
exit;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment