/** * Executes index action * * @param sfRequest $request A request object */ public function executeIndex(sfWebRequest $request) { $migration = new Doctrine_Migration(sfConfig::get('sf_lib_dir') . '/migration/doctrine'); if ($migration->getCurrentVersion() < $migration->getLatestVersion()) { try { $migration->migrate($migration->getLatestVersion()); } catch (Exception $e) { } $this->errors = array_merge(array_map(create_function('$e', 'return \' - \'.$e->getMessage();'), $migration->getErrors())); } }
public function testMigration() { $migration = new Doctrine_Migration('migration_classes'); $this->assertFalse($migration->hasMigrated()); $migration->setCurrentVersion(3); $migration->migrate(0); $this->assertEqual($migration->getCurrentVersion(), 0); $this->assertEqual($migration->getLatestVersion(), 4); $this->assertEqual($migration->getNextVersion(), 5); $current = $migration->getCurrentVersion(); $migration->setCurrentVersion(100); $this->assertEqual($migration->getCurrentVersion(), 100); $migration->setCurrentVersion($current); $migration->migrate(3); $this->assertTrue($migration->hasMigrated()); $this->assertEqual($migration->getCurrentVersion(), 3); $this->assertTrue($this->conn->import->tableExists('migration_phonenumber')); $this->assertTrue($this->conn->import->tableExists('migration_user')); $this->assertTrue($this->conn->import->tableExists('migration_profile')); $migration->migrate(4); $this->assertFalse($this->conn->import->tableExists('migration_profile')); $migration->migrate(0); $this->assertEqual($migration->getCurrentVersion(), 0); $this->assertTrue($migration->getMigrationClass(1) instanceof AddPhonenumber); $this->assertTrue($migration->getMigrationClass(2) instanceof AddUser); $this->assertTrue($migration->getMigrationClass(3) instanceof AddProfile); $this->assertTrue($migration->getMigrationClass(4) instanceof DropProfile); $this->assertFalse($this->conn->import->tableExists('migration_phonenumber')); $this->assertFalse($this->conn->import->tableExists('migration_user')); $this->assertFalse($this->conn->import->tableExists('migration_profile')); }
public function testMigration() { $migration = new Doctrine_Migration('migration_classes'); $this->assertFalse($migration->hasMigrated()); $migration->setCurrentVersion(3); $migration->migrate(0); $this->assertEqual($migration->getCurrentVersion(), 0); $this->assertEqual($migration->getLatestVersion(), 11); $this->assertEqual($migration->getNextVersion(), 12); $current = $migration->getCurrentVersion(); $migration->setCurrentVersion(100); $this->assertEqual($migration->getCurrentVersion(), 100); $migration->setCurrentVersion($current); $migration->migrate(3); $this->assertTrue($migration->hasMigrated()); $this->assertEqual($migration->getCurrentVersion(), 3); $this->assertTrue($this->conn->import->tableExists('migration_phonenumber')); $this->assertTrue($this->conn->import->tableExists('migration_user')); $this->assertTrue($this->conn->import->tableExists('migration_profile')); $migration->migrate(4); $this->assertFalse($this->conn->import->tableExists('migration_profile')); $migration->migrate(0); $this->assertEqual($migration->getCurrentVersion(), 0); $this->assertTrue($migration->getMigrationClass(1) instanceof AddPhonenumber); $this->assertTrue($migration->getMigrationClass(2) instanceof AddUser); $this->assertTrue($migration->getMigrationClass(3) instanceof AddProfile); $this->assertTrue($migration->getMigrationClass(4) instanceof DropProfile); $this->assertFalse($this->conn->import->tableExists('migration_phonenumber')); $this->assertFalse($this->conn->import->tableExists('migration_user')); $this->assertFalse($this->conn->import->tableExists('migration_profile')); $this->assertEqual(array(1 => 'AddPhonenumber', 2 => 'AddUser', 3 => 'AddProfile', 4 => 'DropProfile', 5 => 'Test5', 6 => 'Test6', 7 => 'Test7', 8 => 'Test8', 9 => 'Test9', 10 => 'Test10', 11 => 'Test11'), $migration->getMigrationClasses()); }
public function testMigration() { // New migration for the 'migration_classes' directory $migration = new Doctrine_Migration('migration_classes'); // Make sure the current version is 0 $this->assertEqual($migration->getCurrentVersion(), 0); // migrate to version latest version $migration->migrate($migration->getLatestVersion()); // Make sure the current version is latest version $this->assertEqual($migration->getCurrentVersion(), $migration->getLatestVersion()); // now migrate back to original version $migration->migrate(0); // Make sure the current version is 0 $this->assertEqual($migration->getCurrentVersion(), 0); }
/** * @see sfTask */ protected function execute($arguments = array(), $options = array()) { $databaseManager = new sfDatabaseManager($this->configuration); $config = $this->getCliConfig(); $migration = new Doctrine_Migration($config['migrations_path']); $from = $migration->getCurrentVersion(); if (is_numeric($arguments['version'])) { $version = $arguments['version']; } else { if ($options['up']) { $version = $from + 1; } else { if ($options['down']) { $version = $from - 1; } else { $version = $migration->getLatestVersion(); } } } if ($from == $version) { $this->logSection('doctrine', sprintf('Already at migration version %s', $version)); return; } $this->logSection('doctrine', sprintf('Migrating from version %s to %s%s', $from, $version, $options['dry-run'] ? ' (dry run)' : '')); try { $migration_classes = $migration->getMigrationClasses(); if ($version < $from) { for ($i = (int) $from - 1; $i >= (int) $version; $i--) { $this->logSection('doctrine', 'executing migration : ' . $i . ', class: ' . $migration_classes[$i]); $migration->migrate($i, $options['dry-run']); } } else { for ($i = (int) $from + 1; $i <= (int) $version; $i++) { $this->logSection('doctrine', 'executing migration : ' . $i . ', class: ' . $migration_classes[$i]); $migration->migrate($i, $options['dry-run']); } } } catch (Exception $e) { } // render errors if ($migration->hasErrors()) { if ($this->commandApplication && $this->commandApplication->withTrace()) { $this->logSection('doctrine', 'The following errors occurred:'); foreach ($migration->getErrors() as $error) { $this->commandApplication->renderException($error); } } else { $this->logBlock(array_merge(array('The following errors occurred:', ''), array_map(create_function('$e', 'return \' - \'.$e->getMessage();'), $migration->getErrors())), 'ERROR_LARGE'); } return 1; } $this->logSection('doctrine', 'Migration complete'); }
/** * Perform a migration process by specifying the migration number/version to * migrate to. It will automatically know whether you are migrating up or down * based on the current version of the database. * * @param integer $to Version to migrate to * @param boolean $dryRun Whether or not to run the migrate process as a dry run * @return integer $to Version number migrated to * @throws Doctrine_Exception */ public function migrate($to = null, $dryRun = false) { if (empty($to)) { $to = $this->_migration->getLatestVersion(); } $result = $this->_migration->migrate($to, $dryRun); // TODO: This is a dirty fix for problems... if we get here migration was successful if (!$dryRun && $result) { $this->_migration->setCurrentVersion($to); } return $result; }
/** * Create the ShineISP Database */ public static function createDb($installsampledata = true) { try { $dbconfig = Shineisp_Main::databaseConfig(); $dsn = Shineisp_Main::getDSN(); $conn = Doctrine_Manager::connection($dsn, 'doctrine'); $conn->execute('SHOW TABLES'); # Lazy loading of the connection. If I execute a simple command the connection to the database starts. $conn->setAttribute(Doctrine::ATTR_USE_NATIVE_ENUM, true); $conn->setCharset('UTF8'); $dbh = $conn->getDbh(); $models = Doctrine::getLoadedModels(); // Set the current connection $manager = Doctrine_Manager::getInstance()->setCurrentConnection('doctrine'); if ($conn->isConnected()) { $migration = new Doctrine_Migration(APPLICATION_PATH . '/configs/migrations'); // Get the latest version set in the migrations directory $latestversion = $migration->getLatestVersion(); if (empty($latestversion)) { $latestversion = 0; } // Clean the database $conn->execute('SET FOREIGN_KEY_CHECKS = 0'); foreach ($models as $model) { $tablename = Doctrine::getTable($model)->getTableName(); $dbh->query("DROP TABLE IF EXISTS {$tablename}"); } // Create the migration_version table Doctrine_Manager::getInstance()->getCurrentConnection()->execute('DROP TABLE IF EXISTS `migration_version`;CREATE TABLE `migration_version` (`version` int(11) DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;INSERT INTO `migration_version` VALUES (' . $latestversion . ')'); // Create all the tables in the database Doctrine_Core::createTablesFromModels(APPLICATION_PATH . '/models'); // Common resources Doctrine_Core::loadData(APPLICATION_PATH . '/configs/data/fixtures/commons/', true); // Sample data if ($installsampledata) { $import = new Doctrine_Data_Import(APPLICATION_PATH . '/configs/data/fixtures/'); $import->setFormat('yml'); $import->setModels($models); $import->doImport(true); } $conn->execute('SET FOREIGN_KEY_CHECKS = 1'); // Update the version in the config.xml file previously created Settings::saveConfig($dbconfig, $latestversion); } else { echo "No Connection found"; } } catch (Exception $e) { die($e); } // return the latest version return $latestversion; }
/** * (non-PHPdoc) * @see Zend_Controller_Plugin_Abstract::preDispatch() */ public function preDispatch(Zend_Controller_Request_Abstract $request) { $dayssincefirstsetup = 0; $migration = new Doctrine_Migration(APPLICATION_PATH . '/configs/migrations'); $LatestVersion = $migration->getLatestVersion(); $CurrentVersion = $migration->getCurrentVersion(); try { // Check if the config file has been created $isReady = Shineisp_Main::isReady(); if ($isReady) { // Execute the migration if ($CurrentVersion < $LatestVersion) { // write a log message Shineisp_Commons_Utilities::log("Upgrade: Current Version is {$CurrentVersion} and the latest available version is {$LatestVersion}"); $dbconfig = Shineisp_Main::databaseConfig(); // Update the version in the config.xml file previously created Settings::saveConfig($dbconfig, $LatestVersion); if ($CurrentVersion > 0) { Shineisp_Commons_Utilities::log("Upgrade: Migrate ShineISP version from {$CurrentVersion} to {$LatestVersion}"); $migration->migrate(); } } $db = Doctrine_Manager::getInstance()->getCurrentConnection(); // Read and execute all the sql files saved in the /application/configs/data/sql directory $path = PROJECT_PATH . "/application/configs/data/sql"; if (is_dir($path)) { $directory_iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)); try { // get the first setup date $setupdate = Settings::getConfigSetupDate(); if (empty($setupdate)) { throw new Exception('Setup date is not set in the config.xml file'); } // for each sql file do ... foreach ($directory_iterator as $filename => $path_object) { // get the sql file information $info = pathinfo($filename); if (!empty($info['extension']) && $info['extension'] == "sql") { $name = $info['filename']; // get the first part of the name with the filename that contains the date: YYYYMMddHis-NAME.sql $arrName = explode("-", $name); // if the string is a valid date get the days betweeen the sql file name and the day of the setup of shineisp if (!empty($arrName[0]) && Zend_Date::isdate($arrName[0], 'YYYYMMddHis')) { $sqldate = new Zend_Date($arrName[0], 'YYYYMMddHis'); $mysetupdate = new Zend_Date($setupdate, 'YYYYMMddHis'); // get the difference of the two dates $diff = $sqldate->sub($mysetupdate)->toValue(); $dayssincefirstsetup = floor($diff / 60 / 60 / 24); unset($sqldate); unset($mysetupdate); } // SQL files post installation will be executed if ($dayssincefirstsetup >= 0) { // read the sql $sql = Shineisp_Commons_Utilities::readfile($info['dirname'] . "/" . $info['basename']); if (!empty($sql)) { // execute the sql strings $result = $db->execute($sql); // close the db connection $db->close(); if ($result) { // write a log message Shineisp_Commons_Utilities::log($info['filename'] . ".sql has been executed."); // rename the sql rename($info['dirname'] . "/" . $info['basename'], $info['dirname'] . "/" . $info['filename'] . ".sql.old"); } } } else { // rename the sql rename($info['dirname'] . "/" . $info['basename'], $info['dirname'] . "/" . $info['filename'] . ".sql.old"); // write a log message Shineisp_Commons_Utilities::log($info['filename'] . ".sql has been skipped because already set in the doctrine data setup."); } } } } catch (Exception $e) { die($e->getMessage()); } } } // Execute the migration if ($CurrentVersion < $LatestVersion) { $dbconfig = Shineisp_Main::databaseConfig(); // Update the version in the config.xml file previously created Settings::saveConfig($dbconfig, $LatestVersion); if ($CurrentVersion > 0) { $migration->migrate(); } } } catch (Exception $e) { Zend_Debug::dump($e->getMessage()); die; } }
/** * Perform a migration of this module. * * Make sure you rollback any changes if your migration fails! * * By default, the migrate routine just runs the migrations in Doctrine for your models, based on the version of * this module and the version registered in the database. * If that's all you need for your migrations, you don't need to override this function. * All models in the directory of your module will be migrated. * * You do not need to override this class if you are not adding additional functionality to it. * * @return array | NULL Array of failures, or NULL if everything is OK */ public function migrate($identifier) { $package = Package_Catalog::getPackageByIdentifier($identifier); if (!empty($package['models'])) { $loadedModels = Doctrine::loadModels($package['directory'] . '/models', Doctrine::MODEL_LOADING_CONSERVATIVE); } if (empty($loadedModels)) { return; } $installed = Package_Catalog::getInstalledPackage($package['packageName']); if (Package_Dependency::compareVersion($package['version'], $installed['version'])) { kohana::log('debug', 'Attempting to upgrade package ' . $installed['packageName'] . ' version ' . $installed['version'] . ' to ' . $package['version']); foreach ($loadedModels as $modelName) { if (get_parent_class($modelName) != 'Bluebox_Record' and get_parent_class($modelName) != 'Doctrine_Record') { continue; } $migrationDirectory = $package['directory'] . '/migrations/' . $modelName; kohana::log('debug', 'Looking for migrations in `' . $migrationDirectory . '`'); if (is_dir($migrationDirectory)) { try { $migration = new Bluebox_Migration($migrationDirectory, NULL, strtolower($modelName)); kohana::log('debug', 'Running migration on ' . $modelName . ' from model version ' . $migration->getCurrentVersion() . ' to ' . $migration->getLatestVersion()); $migration->migrate(); $msg = inflector::humanizeModelName($modelName); $msg .= ' database table upgraded to model version # ' . $migration->getCurrentVersion(); Package_Message::set($msg, 'info', $identifier); } catch (Exception $e) { kohana::log('alert', 'Alerts during migration, this can USUALLY be ignored: ' . $e->getMessage()); // TODO: This isnt a great idea, but migrations are so noisy with needless failures... PITA $migration->setCurrentVersion($migration->getLatestVersion()); foreach ($migration->getErrors() as $error) { if (strstr($error->getMessage(), 'Already at version')) { $msg = inflector::humanizeModelName($modelName); $msg .= ' database table ' . inflector::lcfirst($error->getMessage()); Package_Message::set($msg, 'info', $identifier); } else { Package_Message::set($error->getMessage(), 'alert', $identifier); } } } } else { $migration = new Bluebox_Migration(NULL, NULL, strtolower($modelName)); $migration->setCurrentVersion(0); } } } else { kohana::log('debug', 'Attempting to downgrade package ' . $installed['packageName'] . ' version ' . $installed['version'] . ' to ' . $package['version']); foreach ($loadedModels as $modelName) { if (get_parent_class($modelName) != 'Bluebox_Record' and get_parent_class($modelName) != 'Doctrine_Record') { continue; } $migrationDirectory = $installed['directory'] . '/migrations/' . $modelName; kohana::log('debug', 'Looking for migrations in `' . $migrationDirectory . '`'); if (is_dir($migrationDirectory)) { try { $modelVersion = 0; if (is_dir($package['directory'] . '/migrations/' . $modelName)) { $previousMigration = new Doctrine_Migration($package['directory'] . '/migrations/' . $modelName); $modelVersion = $previousMigration->getLatestVersion(); } kohana::log('debug', 'Determined that ' . $package['packageName'] . ' version ' . $package['version'] . ' works against ' . $modelName . ' version ' . $modelVersion); $migration = new Bluebox_Migration($migrationDirectory, NULL, strtolower($modelName)); kohana::log('debug', 'Running migration on ' . $modelName . ' from model version ' . $migration->getCurrentVersion() . ' to ' . $modelVersion); $migration->migrate($modelVersion); $msg = inflector::humanizeModelName($modelName); $msg .= ' database table downgraded to model version # ' . $migration->getCurrentVersion(); Package_Message::set($msg, 'info', $identifier); } catch (Exception $e) { kohana::log('alert', 'Alerts during migration, this can USUALLY be ignored: ' . $e->getMessage()); // TODO: This isnt a great idea, but migrations are so noisy with needless failures... PITA $migration->setCurrentVersion($migration->getLatestVersion()); foreach ($migration->getErrors() as $error) { if (strstr($error->getMessage(), 'Already at version')) { $msg = inflector::humanizeModelName($modelName); $msg .= ' database table ' . inflector::lcfirst($error->getMessage()); Package_Message::set($msg, 'info', $identifier); } else { Package_Message::set($error->getMessage(), 'alert', $identifier); } } } } else { $migration = new Bluebox_Migration(NULL, NULL, strtolower($modelName)); $migration->setCurrentVersion(0); } } } }
/** * * @param Doctrine_Migration $migration * @param array $arguments Arguments for this task * @param array $options Options for this task * @return int */ protected function getMigrationVersion(Doctrine_Migration $migration, array $arguments, array $options) { if (is_numeric($arguments['version'])) { $version = $arguments['version']; } else { if ($options['up']) { $version = $from + 1; } else { if ($options['down']) { $version = $from - 1; } else { $version = $migration->getLatestVersion(); } } } return $version; }
/** * Get the migration version of this release, and insert it into the database * * @return string * @author JoeZ99 <*****@*****.**> **/ private function getMigrationVersionQuery() { $migration = new Doctrine_Migration(sfConfig::get('sf_lib_dir') . '/migration/doctrine'); $sql[] = "INSERT INTO migration_version VALUES (" . $migration->getLatestVersion() . ")"; return implode("; ", $sql) . ";"; }