Complete Example (A)
Create a few migrations, which create a set of tables and modify some existing data.
``` php generate.php create_users_table php generate.php create_posts_table php generate.php fix_dangling_phones_data_bug php generate.php add_deleted_at_column_to_posts_table
```
Assuming these were the first migrations in the system, the above commands would create:
db/migrate/001_CreateUsersTable.php
db/migrate/002_CreatePostsTable.php
db/migrate/003_FixDanglingPhonesDataBug.php
db/migrate/004_AddDeletedAtColumnToPostsTable.php
Contents of db/migrate/001_CreateUsersTable.php
:
```
class CreateUsersTable extends Ruckusing_BaseMigration {
public function up() { $t = $this->create_table("users"); $t->column("first_name", "string"); $t->column("last_name", "string"); $t->column("email", "string", array('limit' => 128)); $t->column("title", "string"); $t->finish();
$this->add_index("users", "email", array('unique' => true));
}//up()
public function down() { $this->drop_table("users"); }//down() } ?> ```
The contents of db/migrate/002_CreatePostsTable.php
might be:
```
class CreatePostsTable extends Ruckusing_BaseMigration {
public function up() { $t = $this->create_table("posts"); $t->column("subject", "string"); $t->column("body", "string"); $t->column("created_at", "datetime", array('null' => false)); $t->column("author_id", "integer"); $t->finish();
$this->add_index("posts", "author_id");
}//up()
public function down() { $this->drop_table("posts"); }//down() } ?> ```
The contents of db/migrate/003_FixDanglingPhonesDataBug.php
might be:
```
class FixDanglingPhonesDataBug extends Ruckusing_BaseMigration {
public function up() { $this->execute("UPDATE phones SET area_code = '415' WHERE area_code IS NULL"); }//up()
public function down() { //Nothing to do. Data was wrong due to bug (#3461), so lets just fix // it once and for all. }//down() } ?> ```
The contents of db/migrate/004_AddDeletedAtColumnToPostsTable.php
might be:
```
class AddDeletedAtColumnToPostsTable extends Ruckusing_BaseMigration {
public function up() { $this->add_column("posts", "deleted_at", "datetime"); }//up()
public function down() { $this->remove_column("posts", "deleted_at"); }//down() } ?> ```
Finally, lets execute the above migrations:
``` php main.php db:migrate
Started: 2007-09-03 9:26pm PDT
[db:migrate]: Migrating UP to: 4 (current version: 0) ========= CreateUsersTable ======== (0.11) ========= CreatePostsTable ======== (0.00) ========= FixDanglingPhonesDataBug ======== (0.00) ========= AddDeletedAtColumnToPostsTable ======== (0.00)
Finished: 2007-09-03 9:26pm PDT
```
Summary
For every migration it is important to also implement the down()
method which just undos what was done in the up()
method. Of course, not all migrations have appropriate logic to be performed when going down()
, in which cases one should just document the reasons.