public function execute() { try { $migrationsPath = $this->getArgument('migrations_path'); $yamlSchemaPath = $this->getArgument('yaml_schema_path'); $migration = new Doctrine_Migration($migrationsPath); $result1 = false; if (!count($migration->getMigrationClasses())) { $result1 = Doctrine_Core::generateMigrationsFromDb($migrationsPath); } $connections = array(); foreach (Doctrine_Manager::getInstance() as $connection) { $connections[] = $connection->getName(); } $changes = Doctrine_Core::generateMigrationsFromDiff($migrationsPath, $connections, $yamlSchemaPath); $numChanges = count($changes, true) - count($changes); $result = $result1 || $numChanges ? true : false; } catch (Exception $e) { $result = false; } if (!$result) { throw new Doctrine_Task_Exception('Could not generate migration classes from database'); } else { $this->notify('Generated migration classes successfully from database'); } }
public function execute() { try { $migrationsPath = $this->getArgument('migrations_path'); $modelsPath = $this->getArgument('models_path'); $yamlSchemaPath = $this->getArgument('yaml_schema_path'); $migration = new Doctrine_Migration($migrationsPath); $result1 = false; if (!count($migration->getMigrationClasses())) { $builder = new Doctrine_Migration_Builder($migration); $result1 = $builder->generateMigrationsFromModels($modelsPath); } $diff = new Doctrine_Migration_Diff($modelsPath, $yamlSchemaPath, $migration); $changes = $diff->generateMigrationClasses(); $numChanges = count($changes, true) - count($changes); $result = $result1 || $numChanges ? true : false; } catch (Exception $e) { $result = false; } if (!$result) { throw new Doctrine_Task_Exception('Could not generate migration classes from models' . (isset($e) ? ': ' . $e->getMessage() : null)); } else { $this->notify('Generated migration classes successfully from models'); } }
function migrate_db() { try { $path = makeMigrationsDir(); $migration = new Doctrine_Migration($path); $migration->migrate(); $account = db_get_account('alice'); if (!$account) { $account = array('login' => 'alice', 'crypted_password' => 'b6263bb14858294c08e4bdfceba90363e10d72b4', 'name' => 'Alice Yamada', 'name_ja_kana_jp' => 'ヤマダアリサ', 'name_ja_hani_jp' => '山田亜理紗', 'given_name' => 'Alice', 'given_name_ja_kana_jp' => 'アリサ', 'given_name_ja_hani_jp' => '亜理紗', 'family_name' => 'Yamada', 'family_name_ja_kana_jp' => 'ヤマダ', 'family_name_ja_hani_jp' => '山田', 'nickname' => 'Alice Nickname', 'preferred_username' => 'AlicePreferred', 'profile' => 'http://www.wonderland.com/alice', 'picture' => 'smiling_woman.jpg', 'website' => 'http://www.wonderland.com', 'email' => '*****@*****.**', 'email_verified' => 1, 'gender' => 'Female', 'birthdate' => '2000-01-01', 'zoneinfo' => 'america/Los Angeles', 'locale' => 'en', 'phone_number' => '123-456-7890', 'phone_number_verified' => 1, 'address' => '123 Wonderland Way', 'updated_at' => time()); db_save_account('alice', $account); } $account = db_get_account('bob'); if (!$account) { $account = array('login' => 'bob', 'crypted_password' => 'cc8684eed2b6544e89242558df73a7208c9391b4', 'name' => 'Bob Ikeda', 'name_ja_kana_jp' => 'イケダボブ', 'name_ja_hani_jp' => '池田保夫', 'given_name' => 'Bob', 'given_name_ja_kana_jp' => 'ボブ', 'given_name_ja_hani_jp' => '保夫', 'family_name' => 'Ikeda', 'family_name_ja_kana_jp' => 'イケダ', 'family_name_ja_hani_jp' => '池田', 'nickname' => 'Bob Nickname', 'preferred_username' => 'BobPreferred', 'profile' => 'http://www.underland.com/bob', 'picture' => 'smiling_man.jpg', 'website' => 'http://www.underland.com', 'email' => '*****@*****.**', 'email_verified' => 1, 'gender' => 'Male', 'birthdate' => '1980-02-09', 'zoneinfo' => 'France/Paris', 'locale' => 'fr', 'phone_number' => '987-234-1234', 'phone_number_verified' => 1, 'address' => '456 Underland Ct.', 'updated_at' => time()); db_save_account('bob', $account); } } catch (Doctrine_Migration_Exception $e) { if (strstr($e->getMessage(), "Already at version") === false) { throw $e; } } catch (Doctrine_Connection_Exception $e) { printf("migration exception %s\n", $e); die(2); } }
/** * @see sfTask */ protected function execute($arguments = array(), $options = array()) { $databaseManager = new sfDatabaseManager($this->configuration); $config = $this->getCliConfig(); $migration = new Doctrine_Migration($config['migrations_path']); $intValidator = new sfValidatorInteger(); $migration->setCurrentVersion($arguments['version']); $this->logSection('doctrine', 'Migration version set to ' . $arguments['version']); }
/** * @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'); }
protected function execute($arguments = array(), $options = array()) { // initialize the database connection $databaseManager = new sfDatabaseManager($this->configuration); $connection = $databaseManager->getDatabase($options['connection'])->getConnection(); $config = $this->getCliConfig(); $migration = new Doctrine_Migration($config['migrations_path']); $from = $migration->getCurrentVersion(); $new_version = $arguments['new_version']; if ($new_version !== $from) { $migration->setCurrentVersion($new_version); } $this->log('Current migration version is ' . $new_version); }
/** * Generate a migration class * * @param string $className Class name to generate * @param array $options Options for the migration class * @param string $up The code for the up function * @param string $down The code for the down function * @param boolean $return Whether or not to return the code. * If true return and false it writes the class to disk. * @return mixed */ public function generateMigrationClass($className, $options = array(), $up = null, $down = null, $return = false) { $className = Doctrine_Inflector::urlize($className); $className = str_replace('-', '_', $className); $className = Doctrine_Inflector::classify($className); if ($return || !$this->getMigrationsPath()) { return $this->buildMigrationClass($className, null, $options, $up, $down); } else { if (!$this->getMigrationsPath()) { throw new Doctrine_Migration_Exception('You must specify the path to your migrations.'); } $next = time() + $this->migration->getNextMigrationClassVersion(); $fileName = $next . '_' . Doctrine_Inflector::tableize($className) . $this->suffix; $class = $this->buildMigrationClass($className, $fileName, $options, $up, $down); $path = $this->getMigrationsPath() . DIRECTORY_SEPARATOR . $fileName; if (class_exists($className) || file_exists($path)) { $this->migration->loadMigrationClass($className); return false; } file_put_contents($path, $class); require_once $path; $this->migration->loadMigrationClass($className); return true; } }
/** * @see sfTask */ protected function execute($arguments = array(), $options = array()) { $databaseManager = new sfDatabaseManager($this->configuration); $migration = new Doctrine_Migration(); $currentVersion = $migration->getCurrentVersion(); if (!isset($arguments['version'])) { $this->logSection('doctrine', 'Current migration version is ' . $currentVersion); } else { $version = $arguments['version']; if (!is_numeric($version)) { $this->logSection('doctrine', 'Unknown version ' . $version, null, 'ERROR'); return; } $migration->setCurrentVersion($version); $this->logSection('doctrine', 'Current migration version was forced to ' . $version); } }
/** * Set a current migration version, without doing an actual migration. * Useful when fixing bugs, testing etc. */ private function actionSetMigrationVersion() { $version = $this->getDestinationVersion(); // Show information about current and latest available version $this->showMigrationVersions(); printf("Setting migration version: %s\n", ($this->cli->command->args['version'] === null ? 'latest' : $version)); if ($version > $this->getLatestVersion()) { printf("Warning: version provided (%d) greater than latest available migration (%d), Cthulhu will eat you!\n", $version, $this->getLatestVersion()); } // Dry run? Stop here. If not, process. if ($this->cli->options['dryrun'] === true) return; $this->migration->setCurrentVersion($version); }
/** * 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() { // 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); }
public function testMigrateClearsErrors() { $migration = new Doctrine_Migration('migration_classes'); $migration->setCurrentVersion(3); try { $migration->migrate(3); } catch (Doctrine_Migration_Exception $e) { $this->assertTrue($migration->hasErrors()); $this->assertEqual(1, $migration->getNumErrors()); } try { $migration->migrate(3); } catch (Doctrine_Migration_Exception $e) { $this->assertTrue($migration->hasErrors()); $this->assertEqual(1, $migration->getNumErrors()); } $migration->clearErrors(); $this->assertFalse($migration->hasErrors()); $this->assertEqual(0, $migration->getNumErrors()); }
public function testTest() { $migration1 = new Doctrine_Migration(dirname(__FILE__) . '/DC221'); $migration2 = new Doctrine_Migration(dirname(__FILE__) . '/DC221'); $this->assertEqual($migration1->getMigrationClasses(), $migration2->getMigrationClasses()); }
/** * Load migration classes from the passed directory. Any file found with a .php * extension will be passed to the loadMigrationClass() * * @param string $directory Directory to load migration classes from * @return void */ public function loadMigrationClassesFromDirectory($directory = null) { $directory = $directory ? $directory : $this->_migrationClassesDirectory; self::$_migrationClassesForDirectories = array(); $this->_migrationClasses = array(); $classesToLoad = array(); $classes = get_declared_classes(); foreach ((array) $directory as $dir) { $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY); foreach ($it as $file) { $info = pathinfo($file->getFileName()); if (isset($info['extension']) && $info['extension'] == 'php') { require_once $file->getPathName(); $array = array_diff(get_declared_classes(), $classes); $className = end($array); if ($className) { $e = explode('_', $file->getFileName()); $timestamp = $e[0]; $classesToLoad[$timestamp] = array('className' => $className, 'path' => $file->getPathName()); } } } } ksort($classesToLoad); foreach ($classesToLoad as $class) { $this->loadMigrationClass($class['className'], $class['path']); } }
protected function getCurrentMigrationVersion() { $migratePath = $this->_getMigrationsDirectoryPath(); $migration = new Doctrine_Migration($migratePath); return $migration->getCurrentVersion(); }
/** * Set the current version of the database * * @param integer $number * @return void */ public function setCurrentVersion($number) { $this->_migration->setCurrentVersion($number); }
public function migrate($version = null) { $migration = new Doctrine_Migration('application/migrations'); $migration->migrate($version); }
/** * generateMigrationClass * * @return void */ public function generateMigrationClass($className, $options = array(), $up = null, $down = null, $return = false) { if ($return || !$this->getMigrationsPath()) { return $this->buildMigrationClass($className, null, $options, $up, $down); } else { if (!$this->getMigrationsPath()) { throw new Doctrine_Migration_Exception('You must specify the path to your migrations.'); } $migration = new Doctrine_Migration($this->getMigrationsPath()); $next = (string) $migration->getNextVersion(); $fileName = str_repeat('0', 3 - strlen($next)) . $next . '_' . Doctrine::tableize($className) . $this->suffix; $class = $this->buildMigrationClass($className, $fileName, $options, $up, $down); $path = $this->getMigrationsPath() . DIRECTORY_SEPARATOR . $fileName; file_put_contents($path, $class); } }
<?php require_once 'bootstrap.php'; echo "Executing migration scripts..."; $migration = new Doctrine_Migration('migrations'); $migration->migrate();
public function __construct(Doctrine_Migration $migration) { $this->_migration = $migration; $this->_connection = $migration->getConnection(); }
echo '<br/>'; } $db = new PDO($dsn[0], $user, $pass); $conn = Doctrine_Manager::connection($db); $dbtable = $conn->fetchOne("SELECT schema_name FROM information_schema.schemata WHERE schema_name='" . $dbname . "'"); if (!$dbtable) { $sql = "CREATE DATABASE `" . $dbname . "` CHARACTER SET utf8;\n CREATE USER '" . $config['db.user'] . "'@'localhost' IDENTIFIED BY '" . $config['db.pass'] . "';\n GRANT ALL PRIVILEGES ON " . $dbname . ".* TO '" . $config['db.user'] . "'@'%' WITH GRANT OPTION;\n "; $db->exec($sql); } $conn->close(); $db = new PDO($config['db.dsn'], $config['db.user'], $config['db.pass']); $conn = Doctrine_Manager::connection($db); if (isset($google_user)) { echo 'user: '******'<br>'; } $migration = new Doctrine_Migration(__DIR__ . '/classes', $conn); $migration->setTableName('doctrine_migration_version'); if (isset($_REQUEST['ver']) && (!isset($google_user) || $google_user->getNickname() == '*****@*****.**')) { $version = 0 + intval($_REQUEST['ver']); } else { $classesKeys = array_keys($migration->getMigrationClasses()); $version = 0 + array_pop($classesKeys); } if (isset($_SERVER['HTTP_HOST'])) { echo '<h1>'; } if ($migration->getCurrentVersion() == $version) { echo 'Database at version ' . $version . PHP_EOL; } else { $migration->migrate($version); echo 'Migrated succesfully to version ' . $migration->getCurrentVersion() . PHP_EOL;
/** * 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); } } } }
<?php require_once 'bootstrap.php'; $migration = new Doctrine_Migration('db/migrations'); // If we got a command line argument, use that as the migration target if ($argc == 2) { $migrate_to = $argv[1]; $migration->migrate($migrate_to); } else { $migration->migrate(); }
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 loadMigrationClass($name, $path = null) { // ignores generated directory if (!is_null($path) && 'generated' === basename(dirname($path))) { return false; } return parent::loadMigrationClass($name, $path); }
/** * Migrate database to specified $to version. Migrates from current to latest if you do not specify. * * @param string $migrationsPath Path to migrations directory which contains your migration classes * @param string $to Version you wish to migrate to. * @return bool true * @throws new Doctrine_Migration_Exception */ public static function migrate($migrationsPath, $to = null) { $migration = new Doctrine_Migration($migrationsPath); return $migration->migrate($to); }
/** * (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; } }
public function Version() { $migration = new Doctrine_Migration(APPLICATION_PATH . '/configs/migrations'); return $migration->getCurrentVersion(); }
/** * 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; }
/** * Output any errors caused by the migration * * @param Doctrine_Migration $migration * @return void */ protected function outputMigrationErrors(Doctrine_Migration $migration) { 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 migration errors occurred:', ''), array_map(create_function('$e', 'return \' - \'.$e->getMessage();'), $migration->getErrors())), 'ERROR_LARGE'); } }