public function setup()
 {
     $db = $this->databasemanager->getDatabase('doctrine');
     /* @var $db sfDoctrineDatabase */
     // Special Handling for postgre, since droping even when closing the connection, fails with
     // SQLSTATE[55006]: Object in use: 7 ERROR:  database "cs_doctrine_act_as_sortable_test" is being accessed by other users DETAIL:  There are 1 other session(s) using the database.
     if ($db->getDoctrineConnection() instanceof Doctrine_Connection_Pgsql) {
         try {
             $db->getDoctrineConnection()->createDatabase();
         } catch (Exception $e) {
         }
         $export = new Doctrine_Export_Pgsql($db->getDoctrineConnection());
         $import = new Doctrine_Import_Pgsql($db->getDoctrineConnection());
         $tablenames = array(SortableArticleTable::getInstance()->getTableName(), SortableArticleUniqueByTable::getInstance()->getTableName(), SortableArticleCategoryTable::getInstance()->getTableName());
         foreach ($tablenames as $tablename) {
             if ($import->tableExists($tablename)) {
                 $export->dropTable($tablename);
             }
         }
     } else {
         try {
             // ignore error if database does not yet exist (clean CI-env)
             $db->getDoctrineConnection()->dropDatabase();
         } catch (Exception $e) {
         }
         $db->getDoctrineConnection()->createDatabase();
     }
     // Using Doctrine instead of Doctrine_Core keeps it symfony 1.2 compatible, which uses
     Doctrine::loadModels(dirname(__FILE__) . '/../fixtures/project/lib/model/doctrine', Doctrine::MODEL_LOADING_CONSERVATIVE);
     Doctrine::createTablesFromArray(Doctrine::getLoadedModels());
     Doctrine::loadData(dirname(__FILE__) . '/../fixtures/project/data/fixtures/categories.yml');
 }
 /**
  * @see sfTask
  */
 protected function execute($arguments = array(), $options = array())
 {
     $this->logSection('doctrine', 'created tables successfully');
     $databaseManager = new sfDatabaseManager($this->configuration);
     Doctrine::loadModels(sfConfig::get('sf_lib_dir') . '/model/doctrine', Doctrine::MODEL_LOADING_CONSERVATIVE);
     Doctrine::createTablesFromArray(Doctrine::getLoadedModels());
 }
Beispiel #3
0
 /**
  * doExport
  *
  * FIXME: This function has ugly hacks in it for temporarily disabling INDEXBY query parts of tables 
  * to export.
  *
  * Update from jwage: I am not sure if their is any other better solution for this. It may be the correct
  * solution to disable the indexBy settings for tables when exporting data fixtures. Maybe a better idea 
  * would be to extract this functionality to a pair of functions to enable/disable the index by settings 
  * so simply turn them on and off when they need to query for the translations standalone and don't need 
  * it to be indexed by the lang.
  *
  * @return void
  */
 public function doExport()
 {
     $models = Doctrine::getLoadedModels();
     $specifiedModels = $this->getModels();
     $data = array();
     // for situation when the $models array is empty, but the $specifiedModels array isn't
     if (empty($models)) {
         $models = $specifiedModels;
     }
     $models = Doctrine::initializeModels($models);
     // temporarily disable indexBy query parts of selected and related tables
     $originalIndexBy = array();
     foreach ($models as $name) {
         $table = Doctrine::getTable($name);
         if (!is_null($indexBy = $table->getBoundQueryPart('indexBy'))) {
             $originalIndexBy[$name] = $indexBy;
             $table->bindQueryPart('indexBy', null);
         }
     }
     foreach ($models as $name) {
         if (!empty($specifiedModels) and !in_array($name, $specifiedModels)) {
             continue;
         }
         $results = Doctrine::getTable($name)->findAll();
         if ($results->count() > 0) {
             $data[$name] = $results;
         }
     }
     // Restore the temporarily disabled indexBy query parts
     foreach ($originalIndexBy as $name => $indexBy) {
         Doctrine::getTable($name)->bindQueryPart('indexBy', $indexBy);
     }
     $data = $this->prepareData($data);
     return $this->dumpData($data);
 }
Beispiel #4
0
 public function testModelLoadingCacheInformation()
 {
     $models = Doctrine::getLoadedModels();
     $this->assertTrue(in_array('AggressiveModelLoadingUser', $models));
     $this->assertTrue(in_array('ConservativeModelLoadingProfile', $models));
     $this->assertTrue(in_array('ConservativeModelLoadingContact', $models));
     $modelFiles = Doctrine::getLoadedModelFiles();
     $this->assertTrue(file_exists($modelFiles['ConservativeModelLoadingUser']));
     $this->assertTrue(file_exists($modelFiles['ConservativeModelLoadingProfile']));
     $this->assertTrue(file_exists($modelFiles['ConservativeModelLoadingContact']));
 }
Beispiel #5
0
 /**
  * buildSchema
  * 
  * Build schema array that can be dumped to file
  *
  * @param string $directory 
  * @return void
  */
 public function buildSchema($directory = null, $models = array())
 {
     if ($directory) {
         $loadedModels = Doctrine::loadModels($directory);
     } else {
         $loadedModels = Doctrine::getLoadedModels();
     }
     $array = array();
     $parent = new ReflectionClass('Doctrine_Record');
     $sql = array();
     $fks = array();
     // we iterate trhough the diff of previously declared classes
     // and currently declared classes
     foreach ($loadedModels as $className) {
         if (!empty($models) && !in_array($className, $models)) {
             continue;
         }
         $record = new $className();
         $recordTable = $record->getTable();
         $data = $recordTable->getExportableFormat();
         $table = array();
         foreach ($data['columns'] as $name => $column) {
             $data['columns'][$name]['type'] = $column['type'] . '(' . $column['length'] . ')';
             unset($data['columns'][$name]['length']);
         }
         $table['columns'] = $data['columns'];
         $relations = $recordTable->getRelations();
         foreach ($relations as $key => $relation) {
             $relationData = $relation->toArray();
             $relationKey = $relationData['alias'];
             if (isset($relationData['refTable']) && $relationData['refTable']) {
                 $table['relations'][$relationKey]['refClass'] = $relationData['refTable']->getComponentName();
             }
             if (isset($relationData['class']) && $relationData['class'] && $relation['class'] != $relationKey) {
                 $table['relations'][$relationKey]['class'] = $relationData['class'];
             }
             $table['relations'][$relationKey]['local'] = $relationData['local'];
             $table['relations'][$relationKey]['foreign'] = $relationData['foreign'];
             if ($relationData['type'] === Doctrine_Relation::ONE) {
                 $table['relations'][$relationKey]['type'] = 'one';
             } else {
                 if ($relationData['type'] === Doctrine_Relation::MANY) {
                     $table['relations'][$relationKey]['type'] = 'many';
                 } else {
                     $table['relations'][$relationKey]['type'] = 'one';
                 }
             }
         }
         $array[$className] = $table;
     }
     return $array;
 }
 protected function execute($arguments = array(), $options = array())
 {
     $configuration = ProjectConfiguration::getApplicationConfiguration($options['application'], $options['env'], true);
     $databaseManager = new sfDatabaseManager($configuration);
     $databaseManager->initialize($configuration);
     $dir = sfConfig::get('sf_data_dir') . DIRECTORY_SEPARATOR . 'fixtures';
     $excludedModels = array('Modification', 'ModificationField');
     Doctrine::loadModels(sfConfig::get('sf_lib_dir') . DIRECTORY_SEPARATOR . 'model' . DIRECTORY_SEPARATOR . 'doctrine');
     $loadedModels = Doctrine::getLoadedModels();
     $models = array_diff($loadedModels, $excludedModels);
     $data = new Doctrine_Data();
     $data->exportData($dir, 'yml', $models, false);
 }
 /**
  * Rebuilds a db as described by the doctrine models
  *
  */
 public function buildDBFromModels()
 {
     $icinga = $this->project->getUserProperty("PATH_Icinga");
     $modelPath = $icinga . "/app/modules/" . $this->project->getUserProperty("MODULE_Name") . "/lib/";
     $appKitPath = $this->project->getUserProperty("PATH_AppKit");
     Doctrine::loadModels($icinga . "/" . $appKitPath . "database/models/generated/");
     Doctrine::loadModel($icinga . "/" . $appKitPath . "database/models/");
     $tables = Doctrine::getLoadedModels();
     $tableList = array();
     foreach ($tables as $table) {
         $tableList[] = Doctrine::getTable($table)->getTableName();
     }
     Doctrine::createTablesFromModels(array($this->models . '/generated', $this->models));
     file_put_contents($modelPath . "/.models.cfg", implode(",", $tableList));
 }
 public function clearData()
 {
     Doctrine::loadModels(sfConfig::get('sf_lib_dir') . '/model/doctrine');
     $models = Doctrine::getLoadedModels();
     foreach ($models as $model) {
         try {
             Doctrine::getTable($model)->createQuery()->delete()->execute();
         } catch (Doctrine_Connection_Exception $e) {
             // if couldn't delete the first time, try it again at the end
             $models[] = $model;
             unset($models[array_search($model, $models)]);
         }
     }
     return $this;
 }
Beispiel #9
0
 private function removeTables()
 {
     $integrity_violation = 0;
     $models = Doctrine::getLoadedModels();
     foreach ($models as $model) {
         try {
             $Model = new $model();
             $table = $Model->getTable()->tableName;
             Doctrine_Manager::connection()->export->dropTable($table);
         } catch (Exception $e) {
             if ($e->getCode() == 23000) {
                 // 23000: Integrity constraint violation
                 $integrity_violation = 1;
             }
         }
     }
     if ($integrity_violation == 1) {
         $integrity_violation = 0;
         $this->removeTables();
     }
 }
Beispiel #10
0
 /**
  * doExport
  *
  * @return void
  */
 public function doExport()
 {
     $models = Doctrine::getLoadedModels();
     $specifiedModels = $this->getModels();
     $data = array();
     // for situation when the $models array is empty, but the $specifiedModels array isn't
     if (empty($models)) {
         $models = $specifiedModels;
     }
     $models = Doctrine::initializeModels($models);
     foreach ($models as $name) {
         if (!empty($specifiedModels) and !in_array($name, $specifiedModels)) {
             continue;
         }
         $results = Doctrine::getTable($name)->findAll();
         if ($results->count() > 0) {
             $data[$name] = $results;
         }
     }
     $data = $this->prepareData($data);
     return $this->dumpData($data);
 }
Beispiel #11
0
 public function index()
 {
     $loadedModels = Doctrine::getLoadedModels();
     $driver = Telephony::getDriver();
     $driverName = get_class($driver);
     // If no driver is set, just return w/ FALSE.
     if (!$driver) {
         return FALSE;
     }
     foreach ($loadedModels as $model) {
         $modelDriverName = $driverName . '_' . $model . '_Driver';
         if (!class_exists($modelDriverName, TRUE)) {
             continue;
         }
         $outputRows = Doctrine::getTable($model)->findAll();
         foreach ($outputRows as $outputRow) {
             Telephony::set($outputRow, $outputRow->identifier());
         }
     }
     Telephony::save();
     Telephony::commit();
 }
Beispiel #12
0
 public function account($account_id = NULL, $redirect = TRUE)
 {
     if ($account_id && users::masqueradeAccount($account_id)) {
         $masquerade_account = TRUE;
     }
     $loadedModels = Doctrine::getLoadedModels();
     $driver = Telephony::getDriver();
     $driverName = get_class($driver);
     if (!$driver) {
         message::set('Can not rebuild configuration, no telephony driver active');
     } else {
         try {
             foreach ($loadedModels as $model) {
                 $modelDriverName = $driverName . '_' . $model . '_Driver';
                 if (!class_exists($modelDriverName, TRUE)) {
                     continue;
                 }
                 $outputRows = Doctrine::getTable($model)->findAll();
                 foreach ($outputRows as $outputRow) {
                     Telephony::set($outputRow, $outputRow->identifier());
                 }
             }
             Telephony::save();
             Telephony::commit();
             $account = Doctrine::getTable('Account')->find(users::getAttr('account_id'));
             parent::save_succeeded($account);
             message::set(users::getAttr('Account', 'name') . ' configuration rebuild complete!', 'success');
         } catch (Exception $e) {
             message::set($e->getMessage());
         }
     }
     if (!empty($masquerade_account)) {
         users::restoreAccount();
     }
     $this->returnQtipAjaxForm();
     if ($redirect) {
         url::redirect(Router_Core::$controller);
     }
 }
Beispiel #13
0
 /**
  * doExport
  *
  * @return void
  */
 public function doExport()
 {
     $models = Doctrine::getLoadedModels();
     $specifiedModels = $this->getModels();
     $data = array();
     $outputAll = true;
     // for situation when the $models array is empty, but the $specifiedModels array isn't
     if (empty($models)) {
         $models = $specifiedModels;
     }
     foreach ($models as $name) {
         if (!empty($specifiedModels) and !in_array($name, $specifiedModels)) {
             continue;
         }
         $class = new $name();
         $table = $class->getTable();
         $result = $table->findAll();
         if (!empty($result)) {
             $data[$name] = $result;
         }
     }
     $data = $this->prepareData($data);
     return $this->dumpData($data);
 }
 public function updateStructure()
 {
     echo "\nUpdating DB Structure\n";
     $models = Doctrine::loadModels($this->modelPath, Doctrine_Core::MODEL_LOADING_AGGRESSIVE, "Nsm");
     $allAltered = array();
     foreach (Doctrine::getLoadedModels() as $model) {
         $class = new $model();
         $altered = array();
         //test
         $cols = $class->getTable()->getColumns();
         $tn = $class->getTable()->getTableName();
         $conn = Doctrine_Manager::connection();
         foreach ($cols as $name => $columns) {
             try {
                 $conn->export->alterTable($tn, array(add => array($name => $columns)));
                 $altered[] = $name;
                 echo "Added column " . $name . " to " . $model . "\n";
             } catch (Exception $e) {
             }
         }
         $allAltered[$model] = $altered;
     }
     return $allAltered;
 }
Beispiel #15
0
 /**
  * generateMigrationsFromModels
  *
  * @param string $modelsPath 
  * @return void
  */
 public function generateMigrationsFromModels($modelsPath = null, $modelLoading = null)
 {
     if ($modelsPath !== null) {
         $models = Doctrine::filterInvalidModels(Doctrine::loadModels($modelsPath, $modelLoading));
     } else {
         $models = Doctrine::getLoadedModels();
     }
     $models = Doctrine::initializeModels($models);
     $foreignKeys = array();
     foreach ($models as $model) {
         $export = Doctrine::getTable($model)->getExportableFormat();
         $foreignKeys[$export['tableName']] = $export['options']['foreignKeys'];
         $up = $this->buildCreateTable($export);
         $down = $this->buildDropTable($export);
         $className = 'Add' . Doctrine_Inflector::classify($export['tableName']);
         $this->generateMigrationClass($className, array(), $up, $down);
     }
     if (!empty($foreignKeys)) {
         $className = 'ApplyForeignKeyConstraints';
         $up = '';
         $down = '';
         foreach ($foreignKeys as $tableName => $definitions) {
             $tableForeignKeyNames[$tableName] = array();
             foreach ($definitions as $definition) {
                 $definition['name'] = $tableName . '_' . implode('_', (array) $definition['local']);
                 $up .= $this->buildCreateForeignKey($tableName, $definition);
                 $down .= $this->buildDropForeignKey($tableName, $definition);
             }
         }
         $this->generateMigrationClass($className, array(), $up, $down);
     }
     return true;
 }
 /**
  * exportSql
  * returns the sql for exporting Doctrine_Record classes to a schema
  *
  * if the directory parameter is given this method first iterates
  * recursively trhough the given directory in order to find any model classes
  *
  * Then it iterates through all declared classes and creates tables for the ones
  * that extend Doctrine_Record and are not abstract classes
  *
  * @throws Doctrine_Connection_Exception    if some error other than Doctrine::ERR_ALREADY_EXISTS
  *                                          occurred during the create table operation
  * @param string $directory     optional directory parameter
  * @return void
  */
 public function exportSql($directory = null)
 {
     if ($directory !== null) {
         $models = Doctrine::filterInvalidModels(Doctrine::loadModels($directory));
     } else {
         $models = Doctrine::getLoadedModels();
     }
     return $this->exportSortedClassesSql($models, false);
 }
 /** 
  * @group Database
  */
 public function doctrineModelProvider()
 {
     $models = Doctrine::getLoadedModels();
     foreach ($models as &$model) {
         $model = array($model);
     }
     return $models;
 }
Beispiel #18
0
 /**
  * purge
  * 
  * Purge all data for loaded models or for the passed array of Doctrine_Records
  *
  * @param string $models 
  * @return void
  */
 public function purge($models = null)
 {
     if ($models) {
         $models = Doctrine::filterInvalidModels($models);
     } else {
         $models = Doctrine::getLoadedModels();
     }
     $connections = array();
     foreach ($models as $model) {
         $connections[Doctrine::getTable($model)->getConnection()->getName()][] = $model;
     }
     foreach ($connections as $connection => $models) {
         $models = Doctrine_Manager::getInstance()->getConnection($connection)->unitOfWork->buildFlushTree($models);
         $models = array_reverse($models);
         foreach ($models as $model) {
             Doctrine::getTable($model)->createQuery()->delete()->execute();
         }
     }
 }
 /**
  * Loads all Doctrine builders.
  */
 protected function loadModels()
 {
     Doctrine::loadModels($this->generatorManager->getConfiguration()->getModelDirs(), Doctrine::MODEL_LOADING_CONSERVATIVE);
     $models = Doctrine::getLoadedModels();
     $models = Doctrine::initializeModels($models);
     $this->models = Doctrine::filterInvalidModels($models);
     return $this->models;
 }
Beispiel #20
0
 /**
  * doImportDummyData
  *
  * @param string $num 
  * @return void
  */
 public function doImportDummyData($num = 3)
 {
     $models = Doctrine::getLoadedModels();
     $specifiedModels = $this->getModels();
     foreach ($models as $name) {
         if (!empty($specifiedModels) && !in_array($name, $specifiedModels)) {
             continue;
         }
         for ($i = 0; $i < $num; $i++) {
             $obj = new $name();
             $this->populateDummyRecord($obj);
             $obj->save();
             $ids[get_class($obj)][] = $obj->identifier();
         }
     }
 }
Beispiel #21
0
 /**
  * generateMigrationsFromModels
  *
  * @param string $modelsPath 
  * @return void
  */
 public function generateMigrationsFromModels($modelsPath = null)
 {
     if ($modelsPath) {
         $models = Doctrine::loadModels($modelsPath);
     } else {
         $models = Doctrine::getLoadedModels();
     }
     $foreignKeys = array();
     foreach ($models as $model) {
         $export = Doctrine::getTable($model)->getExportableFormat();
         $foreignKeys[$export['tableName']] = $export['options']['foreignKeys'];
         $up = $this->buildCreateTable($export);
         $down = $this->buildDropTable($export);
         $className = 'Add' . Doctrine::classify($export['tableName']);
         $this->generateMigrationClass($className, array(), $up, $down);
     }
     $className = 'ApplyForeignKeyConstraints';
     $up = '';
     $down = '';
     foreach ($foreignKeys as $tableName => $definitions) {
         $tableForeignKeyNames[$tableName] = array();
         foreach ($definitions as $definition) {
             $definition['name'] = $tableName . '_' . $definition['foreignTable'] . '_' . $definition['local'] . '_' . $definition['foreign'];
             $up .= $this->buildCreateForeignKey($tableName, $definition);
             $down .= $this->buildDropForeignKey($tableName, $definition);
         }
     }
     $this->generateMigrationClass($className, array(), $up, $down);
     return true;
 }
Beispiel #22
0
 /**
  * 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;
 }
/**
 * Drops all tables from database
 */
function doctrine_destroy_database()
{
    $conn = Doctrine_Manager::getInstance()->getCurrentConnection();
    $models = Doctrine::getLoadedModels();
    foreach ($models as $model) {
        $conn->export->dropTable(Doctrine::getTable($model)->getTableName());
    }
}
Beispiel #24
0
 /**
  * exportSql
  * returns the sql for exporting Doctrine_Record classes to a schema
  *
  * if the directory parameter is given this method first iterates
  * recursively trhough the given directory in order to find any model classes
  *
  * Then it iterates through all declared classes and creates tables for the ones
  * that extend Doctrine_Record and are not abstract classes
  *
  * @throws Doctrine_Connection_Exception    if some error other than Doctrine::ERR_ALREADY_EXISTS
  *                                          occurred during the create table operation
  * @param string $directory     optional directory parameter
  * @return void
  */
 public function exportSql($directory = null)
 {
     if ($directory !== null) {
         $models = Doctrine::loadModels($directory);
     } else {
         $models = Doctrine::getLoadedModels();
     }
     return $this->exportClassesSql($models);
 }
Beispiel #25
0
 /**
  * purge
  * 
  * Purge all data for loaded models or for the passed array of Doctrine_Records
  *
  * @param string $models 
  * @return void
  */
 public function purge($models = null)
 {
     if ($models) {
         $models = Doctrine::filterInvalidModels($models);
     } else {
         $models = Doctrine::getLoadedModels();
     }
     foreach ($models as $model) {
         $model = new $model();
         $model->getTable()->createQuery()->delete($model)->execute();
     }
 }
Beispiel #26
0
 /**
  * Selector for a module's tables or entities.
  *
  * This method is Backward Compatible with all Core versions back to 1.2.x
  * It scans for tables in `tables.php` as well as locating Doctrine 1 tables
  * or Doctrine 2 entities in either the 1.3.0 type directories or 1.4.0++ type
  *
  * @param string  $modname       Module name.
  * @param string  $name          Select field name.
  * @param string  $selectedValue Selected value.
  * @param string  $defaultValue  Value for "default" option.
  * @param string  $defaultText   Text for "default" option.
  * @param boolean $submit        Submit on choose.
  * @param string  $remove        Remove string from table name.
  * @param boolean $disabled      Add Disabled attribute to select.
  * @param integer $nStripChars   Strip the first n characters.
  * @param integer $multipleSize  Size for multiple selects.
  *
  * @return string The rendered output.
  */
 public static function getSelector_ModuleTables($modname, $name, $selectedValue = '', $defaultValue = 0, $defaultText = '', $submit = false, $remove = '', $disabled = false, $nStripChars = 0, $multipleSize = 1)
 {
     if (!$modname) {
         throw new \Exception(__f('Invalid %1$s passed to %2$s.', array('modname', 'HtmlUtil::getSelector_ModuleTables')));
     }
     // old style 'tables.php' modules (Core 1.2.x--)
     $tables = ModUtil::dbInfoLoad($modname, '', true);
     $data = array();
     if (is_array($tables) && $tables) {
         foreach ($tables as $k => $v) {
             if (strpos($k, '_column') === false && strpos($k, '_db_extra_enable') === false && strpos($k, '_primary_key_column') === false) {
                 $checkColumns = $k . '_column';
                 if (!isset($tables[$checkColumns])) {
                     continue;
                 }
             }
             if (strpos($k, '_column') === false && strpos($k, '_db_extra_enable') === false && strpos($k, '_primary_key_column') === false) {
                 if (strpos($k, 'z_') === 0) {
                     $k = substr($k, 4);
                 }
                 if ($remove) {
                     $k2 = str_replace($remove, '', $k);
                 } else {
                     $k2 = $k;
                 }
                 if ($nStripChars) {
                     $k2 = ucfirst(substr($k2, $nStripChars));
                 }
                 // Use $k2 for display also (instead of showing the internal table name)
                 $data[$k2] = $k2;
             }
         }
     }
     if (!empty($data)) {
         return self::getSelector_Generic($name, $data, $selectedValue, $defaultValue, $defaultText, null, null, $submit, $disabled, $multipleSize);
     }
     // Doctrine 1 models (Core 1.3.0 - 1.3.5)
     DoctrineUtil::loadModels($modname);
     $records = Doctrine::getLoadedModels();
     $data = array();
     foreach ($records as $recordClass) {
         // remove records from other modules
         if (substr($recordClass, 0, strlen($modname)) != $modname) {
             continue;
         }
         // get table name of remove table prefix
         $tableNameRaw = Doctrine::getTable($recordClass)->getTableName();
         sscanf($tableNameRaw, Doctrine_Manager::getInstance()->getAttribute(Doctrine::ATTR_TBLNAME_FORMAT), $tableName);
         if ($remove) {
             $tableName = str_replace($remove, '', $tableName);
         }
         if ($nStripChars) {
             $tableName = ucfirst(substr($tableName, $nStripChars));
         }
         $data[$tableName] = $tableName;
     }
     if (!empty($data)) {
         return self::getSelector_Generic($name, $data, $selectedValue, $defaultValue, $defaultText, null, null, $submit, $disabled, $multipleSize);
     }
     // Doctrine 2 entities (Core 1.3.0++)
     // Core-2.0 spec
     $module = ModUtil::getModule($modname);
     if (null !== $module && !class_exists($module->getVersionClass())) {
         // this check just confirming a Core-2.0 spec bundle - remove in 2.0.0
         $capabilities = $module->getMetaData()->getCapabilities();
         if (isset($capabilities['categorizable'])) {
             $data = array();
             foreach ($capabilities['categorizable'] as $fullyQualifiedEntityName) {
                 $nameParts = explode('\\', $fullyQualifiedEntityName);
                 $entityName = array_pop($nameParts);
                 $data[$entityName] = $entityName;
             }
             $selectedValue = count($data) == 1 ? $entityName : $defaultValue;
             return self::getSelector_Generic($name, $data, $selectedValue, $defaultValue, $defaultText, null, null, $submit, $disabled, $multipleSize);
         }
     }
     // (Core-1.3 spec)
     $modinfo = ModUtil::getInfo(ModUtil::getIdFromName($modname));
     $modpath = $modinfo['type'] == ModUtil::TYPE_SYSTEM ? 'system' : 'modules';
     $osdir = DataUtil::formatForOS($modinfo['directory']);
     $entityDirs = array("{$modpath}/{$osdir}/Entity/", "{$modpath}/{$osdir}/lib/{$osdir}/Entity/");
     $entities = array();
     foreach ($entityDirs as $entityDir) {
         if (file_exists($entityDir)) {
             $files = scandir($entityDir);
             foreach ($files as $file) {
                 if ($file != '.' && $file != '..' && substr($file, -4) === '.php') {
                     $entities[] = $file;
                 }
             }
         }
     }
     $data = array();
     foreach ($entities as $entity) {
         $possibleClassNames = array($modname . '_Entity_' . substr($entity, 0, strlen($entity) - 4));
         if ($module) {
             $possibleClassNames[] = $module->getNamespace() . '\\Entity\\' . substr($entity, 0, strlen($entity) - 4);
             // Core 1.4.0++
         }
         foreach ($possibleClassNames as $class) {
             if (class_exists($class)) {
                 $entityName = substr($entity, 0, strlen($entity) - 4);
                 if ($remove) {
                     $entityName = str_replace($remove, '', $entityName);
                 }
                 if ($nStripChars) {
                     $entityName = ucfirst(substr($entityName, $nStripChars));
                 }
                 $data[$entityName] = $entityName;
             }
         }
     }
     return self::getSelector_Generic($name, $data, $selectedValue, $defaultValue, $defaultText, null, null, $submit, $disabled, $multipleSize);
 }
 protected function updatePgsqlSequences()
 {
     if (substr($this->dsn, 0, 5) != 'pgsql') {
         return true;
     }
     $sqlExec = Doctrine_Manager::getInstance()->getCurrentConnection()->getDbh();
     foreach (Doctrine::getLoadedModels() as $model) {
         $refCl = new ReflectionClass($model);
         if (!$refCl->hasMethod("getPgsqlSequenceOffsets")) {
             continue;
         }
         $cl = new $model();
         foreach ($cl->getPgsqlSequenceOffsets() as $seq => $offset) {
             $sqlExec->query("SELECT setval('" . $seq . "'," . $offset . ")");
         }
     }
 }
 /**
  * Generate a set of migrations from a set of models
  *
  * @param  string $modelsPath    Path to models
  * @param  string $modelLoading  What type of model loading to use when loading the models
  * @return boolean
  */
 public function generateMigrationsFromModels($modelsPath = null, $modelLoading = null)
 {
     if ($modelsPath !== null) {
         $models = Doctrine::filterInvalidModels(Doctrine::loadModels($modelsPath, $modelLoading));
     } else {
         $models = Doctrine::getLoadedModels();
     }
     $models = Doctrine::initializeModels($models);
     $foreignKeys = array();
     foreach ($models as $model) {
         $table = Doctrine::getTable($model);
         if ($table->getTableName() !== $this->migration->getTableName()) {
             $export = $table->getExportableFormat();
             $foreignKeys[$export['tableName']] = $export['options']['foreignKeys'];
             $up = $this->buildCreateTable($export);
             $down = $this->buildDropTable($export);
             $className = 'Add' . Doctrine_Inflector::classify($export['tableName']);
             $this->generateMigrationClass($className, array(), $up, $down);
         }
     }
     if (!empty($foreignKeys)) {
         $className = 'AddFks';
         $up = array();
         $down = array();
         foreach ($foreignKeys as $tableName => $definitions) {
             $tableForeignKeyNames[$tableName] = array();
             foreach ($definitions as $definition) {
                 $up[] = $this->buildCreateForeignKey($tableName, $definition);
                 $down[] = $this->buildDropForeignKey($tableName, $definition);
             }
         }
         $up = implode("\n", $up);
         $down = implode("\n", $down);
         if ($up || $down) {
             $this->generateMigrationClass($className, array(), $up, $down);
         }
     }
     return true;
 }
Beispiel #29
0
 /**
  * buildSchema
  * 
  * Build schema array that can be dumped to file
  *
  * @param string $directory 
  * @return void
  */
 public function buildSchema($directory = null, $models = array())
 {
     if ($directory !== null) {
         $loadedModels = Doctrine::filterInvalidModels(Doctrine::loadModels($directory));
     } else {
         $loadedModels = Doctrine::getLoadedModels();
     }
     $array = array();
     $parent = new ReflectionClass('Doctrine_Record');
     $sql = array();
     $fks = array();
     // we iterate through the diff of previously declared classes
     // and currently declared classes
     foreach ($loadedModels as $className) {
         if (!empty($models) && !in_array($className, $models)) {
             continue;
         }
         $recordTable = Doctrine::getTable($className);
         $data = $recordTable->getExportableFormat();
         $table = array();
         $remove = array('ptype', 'ntype', 'alltypes');
         // Fix explicit length in schema, concat it to type in this format: type(length)
         foreach ($data['columns'] as $name => $column) {
             if (isset($column['length']) && $column['length'] && isset($column['scale']) && $column['scale']) {
                 $data['columns'][$name]['type'] = $column['type'] . '(' . $column['length'] . ', ' . $column['scale'] . ')';
                 unset($data['columns'][$name]['length'], $data['columns'][$name]['scale']);
             } else {
                 $data['columns'][$name]['type'] = $column['type'] . '(' . $column['length'] . ')';
                 unset($data['columns'][$name]['length']);
             }
             // Strip out schema information which is not necessary to be dumped to the yaml schema file
             foreach ($remove as $value) {
                 if (isset($data['columns'][$name][$value])) {
                     unset($data['columns'][$name][$value]);
                 }
             }
             // If type is the only property of the column then lets abbreviate the syntax
             // columns: { name: string(255) }
             if (count($data['columns'][$name]) === 1 && isset($data['columns'][$name]['type'])) {
                 $type = $data['columns'][$name]['type'];
                 unset($data['columns'][$name]);
                 $data['columns'][$name] = $type;
             }
         }
         $table['tableName'] = $data['tableName'];
         $table['columns'] = $data['columns'];
         $relations = $recordTable->getRelations();
         foreach ($relations as $key => $relation) {
             $relationData = $relation->toArray();
             $relationKey = $relationData['alias'];
             if (isset($relationData['refTable']) && $relationData['refTable']) {
                 $table['relations'][$relationKey]['refClass'] = $relationData['refTable']->getComponentName();
             }
             if (isset($relationData['class']) && $relationData['class'] && $relation['class'] != $relationKey) {
                 $table['relations'][$relationKey]['class'] = $relationData['class'];
             }
             $table['relations'][$relationKey]['local'] = $relationData['local'];
             $table['relations'][$relationKey]['foreign'] = $relationData['foreign'];
             if ($relationData['type'] === Doctrine_Relation::ONE) {
                 $table['relations'][$relationKey]['type'] = 'one';
             } else {
                 if ($relationData['type'] === Doctrine_Relation::MANY) {
                     $table['relations'][$relationKey]['type'] = 'many';
                 } else {
                     $table['relations'][$relationKey]['type'] = 'one';
                 }
             }
         }
         $array[$className] = $table;
     }
     return $array;
 }
Beispiel #30
0
 /**
  * Selector for a module's tables.
  *
  * @param string  $modname       Module name.
  * @param string  $name          Select field name.
  * @param string  $selectedValue Selected value.
  * @param string  $defaultValue  Value for "default" option.
  * @param string  $defaultText   Text for "default" option.
  * @param boolean $submit        Submit on choose.
  * @param string  $remove        Remove string from table name.
  * @param boolean $disabled      Add Disabled attribute to select.
  * @param integer $nStripChars   Strip the first n characters.
  * @param integer $multipleSize  Size for multiple selects.
  *
  * @return string The rendered output.
  */
 public static function getSelector_ModuleTables($modname, $name, $selectedValue = '', $defaultValue = 0, $defaultText = '', $submit = false, $remove = '', $disabled = false, $nStripChars = 0, $multipleSize = 1)
 {
     if (!$modname) {
         return z_exit(__f('Invalid %1$s passed to %2$s.', array('modname', 'HtmlUtil::getSelector_ModuleTables')));
     }
     $tables = ModUtil::dbInfoLoad($modname, '', true);
     $data = array();
     if (is_array($tables) && $tables) {
         foreach ($tables as $k => $v) {
             if (strpos($k, '_column') === false && strpos($k, '_db_extra_enable') === false && strpos($k, '_primary_key_column') === false) {
                 $checkColumns = $k . '_column';
                 if (!isset($tables[$checkColumns])) {
                     continue;
                 }
             }
             if (strpos($k, '_column') === false && strpos($k, '_db_extra_enable') === false && strpos($k, '_primary_key_column') === false) {
                 if (strpos($k, 'z_') === 0) {
                     $k = substr($k, 4);
                 }
                 if ($remove) {
                     $k2 = str_replace($remove, '', $k);
                 } else {
                     $k2 = $k;
                 }
                 if ($nStripChars) {
                     $k2 = ucfirst(substr($k2, $nStripChars));
                 }
                 // Use $k2 for display also (instead of showing the internal table name)
                 $data[$k2] = $k2;
             }
         }
     }
     // Doctrine models
     DoctrineUtil::loadModels($modname);
     $records = Doctrine::getLoadedModels();
     foreach ($records as $recordClass) {
         // remove records from other modules
         if (substr($recordClass, 0, strlen($modname)) != $modname) {
             continue;
         }
         // get table name of remove table prefix
         $tableNameRaw = Doctrine::getTable($recordClass)->getTableName();
         sscanf($tableNameRaw, Doctrine_Manager::getInstance()->getAttribute(Doctrine::ATTR_TBLNAME_FORMAT), $tableName);
         if ($remove) {
             $tableName = str_replace($remove, '', $tableName);
         }
         if ($nStripChars) {
             $tableName = ucfirst(substr($tableName, $nStripChars));
         }
         $data[$tableName] = $tableName;
     }
     // Doctrine2 models
     $modinfo = ModUtil::getInfo(ModUtil::getIdFromName($modname));
     $modpath = $modinfo['type'] == ModUtil::TYPE_SYSTEM ? 'system' : 'modules';
     $osdir = DataUtil::formatForOS($modinfo['directory']);
     $entityDir = "{$modpath}/{$osdir}/lib/{$osdir}/Entity/";
     $entities = array();
     if (file_exists($entityDir)) {
         $entities = scandir($entityDir);
     }
     foreach ($entities as $entity) {
         if (!($entity[0] != '.' && substr($entity, -4) === '.php')) {
             continue;
         }
         $class = $modname . '_Entity_' . substr($entity, 0, strlen($entity) - 4);
         if (class_exists($class) && !in_array('Doctrine_Record', class_parents($class))) {
             $tableName = substr($entity, 0, strlen($entity) - 4);
             if ($remove) {
                 $tableName = str_replace($remove, '', $tableName);
             }
             if ($nStripChars) {
                 $tableName = ucfirst(substr($tableName, $nStripChars));
             }
             $data[$tableName] = $tableName;
         }
     }
     return self::getSelector_Generic($name, $data, $selectedValue, $defaultValue, $defaultText, null, null, $submit, $disabled, $multipleSize);
 }