/framework/experimental/migration/Migration.php
PHP | 83 lines | 62 code | 13 blank | 8 comment | 3 complexity | 5a15233a83e787518a9b4ceeb1b79f22 MD5 | raw file
1<?php 2class Migration 3{ 4 static function initDb() 5 { 6 // create the migration table if it does not exist 7 $schema = SqlGetSchema(); 8 if(!$schema->tableExists('migration')) 9 { 10 $sql = "create table migration ( 11 id serial primary key, 12 name text not null, 13 applied int2 not null default 0)"; 14 SqlAlterSchema($sql); 15 } 16 } 17 18 // static 19 function getAllMigrationNames() 20 { 21 $filenames = ListDir(getcwd() . '/migrations', array('extentions' => array('php'))); 22 $versions = array(); 23 foreach($filenames as $thisFilename) 24 { 25 $parts = explode('_', $thisFilename); 26 $version = $parts[0]; 27 $versions[$thisFilename] = $version; 28 } 29 30 return $versions; 31 } 32 33 // static 34 function filenameFromVersion($version) 35 { 36 $filenames = ListDir(getcwd() . '/migrations', array('extentions' => array('php'))); 37 38 foreach($filenames as $thisFilename) 39 { 40 $parts = explode('_', $thisFilename); 41 $thisVersion = str_replace('.', '_', $parts[0]); 42 if($version == $thisVersion) 43 return $thisFilename; 44 } 45 46 trigger_error("version not found: " . $version); 47 } 48 49 // static 50 function getAllAppiedMigrationNames() 51 { 52 return SqlFetchColumn("select name from migration where applied = 1", array()); 53 } 54 55 // static 56 function apply($filename, $name) 57 { 58 include_once(getcwd() . '/migrations/' . $filename); 59 60 $className = 'Migration_' . str_replace('.', '_', $name); 61 $migration = new $className(); 62 $migration->up(); 63 64 // mark it as applied 65 SqlUpsertRow('migration', array('name' => $name), array('applied' => 1)); 66 67 print_r($migration); 68 } 69 70 // static 71 function undo($filename, $name) 72 { 73 include_once(getcwd() . '/migrations/' . $filename); 74 $className = 'Migration_' . str_replace('.', '_', $name); 75 $migration = new $className(); 76 $migration->down(); 77 78 // mark it as applied 79 SqlUpsertRow('migration', array('name' => $name), array('applied' => 0)); 80 81 print_r($migration); 82 } 83}