public function testSavingTwiceWithAModelThatHasACurrencyValueAsARelation()
 {
     if (!RedBeanDatabase::isFrozen()) {
         Yii::app()->user->userModel = User::getByUsername('super');
         $testItem = new OwnedSecurableTestItem();
         $testItem->member = 'test';
         $saved = $testItem->save();
         $this->assertTrue($saved);
         //Because OwnedSecurableTestItem as a relatedCurrency, there are some strange issues with saving again.
         //It creates currency validation issues for any of the related users like owner, modifiedUser etc.
         //Need to investigate further to fix.
         //$testItem->forget();
         //$testItem = OwnedSecurableTestItem::getById($testItem->id);
         //Save again immediately after.
         $validated = $testItem->validate();
         // echo "<pre>";
         // print_r($testItem->getErrors());
         // echo "</pre>";
         $this->assertTrue($validated);
         $saved = $testItem->save();
         $this->assertTrue($saved);
         //Reset count of test items to 0.
         $testItem->delete();
     }
 }
 public function onEvent($type, $info)
 {
     assert('$type == "after_update"');
     if (RedBeanDatabase::isFrozen()) {
         return;
     }
     $hints = $info->getMeta("hint");
     if ($hints !== null) {
         assert('is_array($hints)');
         foreach ($hints as $key => $value) {
             switch ($value) {
                 case 'date':
                     $this->dateOptimizer->setTable($info->getMeta("type"));
                     $this->dateOptimizer->setColumn($key);
                     $this->dateOptimizer->setValue($info->{$key});
                     $this->dateOptimizer->optimize();
                     break;
                 case 'datetime':
                     $this->datetimeOptimizer->setTable($info->getMeta("type"));
                     $this->datetimeOptimizer->setColumn($key);
                     $this->datetimeOptimizer->setValue($info->{$key});
                     $this->datetimeOptimizer->optimize();
                     break;
                 case 'id':
                     $this->idOptimizer->setTable($info->getMeta("type"));
                     $this->idOptimizer->setColumn($key);
                     $this->idOptimizer->setValue($info->{$key});
                     $this->idOptimizer->optimize();
                     break;
             }
         }
     }
 }
 public function testSaveModelFromPostSuccessfulSave()
 {
     //Unfreeze since the test model is not part of the standard schema.
     $freezeWhenComplete = false;
     if (RedBeanDatabase::isFrozen()) {
         RedBeanDatabase::unfreeze();
         $freezeWhenComplete = true;
     }
     Yii::app()->user->userModel = User::getByUsername('super');
     $savedSuccessfully = false;
     $modelToStringValue = null;
     $postData = array('member' => 'abc');
     $model = new OwnedSecurableTestItem();
     $this->assertFalse($model->hasErrors());
     $controllerUtil = new ZurmoControllerUtil();
     $model = $controllerUtil->saveModelFromPost($postData, $model, $savedSuccessfully, $modelToStringValue);
     $this->assertTrue($savedSuccessfully);
     $this->assertEquals('abc', $modelToStringValue);
     $this->assertFalse($model->hasErrors());
     $this->assertTrue($model->id > 0);
     //Re-freeze if needed.
     if ($freezeWhenComplete) {
         RedBeanDatabase::freeze();
     }
 }
 public function teardown()
 {
     if ($this->freeze) {
         RedBeanDatabase::freeze();
     }
     parent::teardown();
 }
 public function testBackupAndRestoreDatabase()
 {
     chdir(COMMON_ROOT . DIRECTORY_SEPARATOR . 'protected' . DIRECTORY_SEPARATOR . 'commands');
     // Create new database (zurmo_temp).
     if (RedBeanDatabase::getDatabaseType() == 'mysql') {
         $this->assertTrue(DatabaseCompatibilityUtil::createDatabase('mysql', $this->temporaryDatabaseHostname, $this->temporaryDatabaseUsername, $this->temporaryDatabasePassword, $this->temporaryDatabasePort, $this->temporaryDatabaseName));
         $connection = @mysql_connect($this->temporaryDatabaseHostname . ':' . $this->temporaryDatabasePort, $this->temporaryDatabaseUsername, $this->temporaryDatabasePassword);
         $this->assertTrue(is_resource($connection));
         @mysql_select_db($this->temporaryDatabaseName);
         @mysql_query("create table temptable (temptable_id int(11) unsigned not null)", $connection);
         @mysql_query("insert into temptable values ('5')", $connection);
         @mysql_query("insert into temptable values ('10')", $connection);
         $result = @mysql_query("SELECT count(*) from temptable");
         $totalRows = mysql_fetch_row($result);
         @mysql_close($connection);
         $this->assertEquals(2, $totalRows[0]);
         $command = "php zurmocTest.php database backup {$this->databaseBackupTestFile} mysql ";
         $command .= "{$this->temporaryDatabaseHostname} {$this->temporaryDatabaseName} ";
         $command .= "{$this->temporaryDatabasePort} {$this->temporaryDatabaseUsername} {$this->temporaryDatabasePassword}";
         if (!IS_WINNT) {
             $command .= ' 2>&1';
         }
         exec($command, $output);
         sleep(2);
         $this->assertTrue(is_file($this->databaseBackupTestFile));
         //Drop database, and restore it from backup.
         $this->assertTrue(DatabaseCompatibilityUtil::createDatabase('mysql', $this->temporaryDatabaseHostname, $this->temporaryDatabaseUsername, $this->temporaryDatabasePassword, $this->temporaryDatabasePort, $this->temporaryDatabaseName));
         // Ensure that database don't exist
         $connection = @mysql_connect($this->temporaryDatabaseHostname . ':' . $this->temporaryDatabasePort, $this->temporaryDatabaseUsername, $this->temporaryDatabasePassword);
         $this->assertTrue(is_resource($connection));
         @mysql_select_db($this->temporaryDatabaseName, $connection);
         $result = @mysql_query("SELECT count(*) from temptable", $connection);
         $this->assertFalse($result);
         // Now restore database
         $command = "php zurmocTest.php database restore {$this->databaseBackupTestFile} mysql ";
         $command .= "{$this->temporaryDatabaseHostname} {$this->temporaryDatabaseName} ";
         $command .= "{$this->temporaryDatabasePort} {$this->temporaryDatabaseUsername} {$this->temporaryDatabasePassword}";
         if (!IS_WINNT) {
             $command .= ' 2>&1';
         }
         exec($command, $output);
         sleep(2);
         $connection = @mysql_connect($this->temporaryDatabaseHostname . ':' . $this->temporaryDatabasePort, $this->temporaryDatabaseUsername, $this->temporaryDatabasePassword);
         $this->assertTrue(is_resource($connection));
         $result = @mysql_select_db($this->temporaryDatabaseName, $connection);
         $this->assertTrue($result);
         $result = @mysql_query("SELECT count(*) from temptable", $connection);
         $this->assertTrue(is_resource($result));
         $totalRows = mysql_fetch_row($result);
         $result = @mysql_query("SELECT * from temptable", $connection);
         $rows1 = mysql_fetch_row($result);
         $rows2 = mysql_fetch_row($result);
         @mysql_close($connection);
         $this->assertEquals(2, $totalRows[0]);
         $this->assertEquals(5, $rows1[0]);
         $this->assertEquals(10, $rows2[0]);
     }
 }
 /**
  * @expectedException FailedAssertionException
  */
 public function testGetDatabaseNameFromConnectionString()
 {
     $dsn = 'mysql:host=localhost;port=3306;dbname=zurmo';
     // Not Coding Standard
     $databaseName = RedBeanDatabase::getDatabaseNameFromDsnString($dsn);
     $this->assertEquals('zurmo', $databaseName);
     $dsn = 'mysql:host=localhost;';
     // Not Coding Standard
     $databaseName = RedBeanDatabase::getDatabaseNameFromDsnString($dsn);
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     SecurityTestHelper::createSuperAdmin();
     if (!RedBeanDatabase::isFrozen()) {
         // TODO: @Shoaibi: High: get rid of this for God's sake.
         $campaignItem = CampaignItemTestHelper::createCampaignItem(0);
         $campaignItem->delete();
     }
 }
 public function onEvent($type, $info)
 {
     assert('$type == "sql_exec"');
     if (!RedBeanDatabase::isFrozen()) {
         return;
     }
     //echo "<pre>";
     //print_r($info->getSQL());
     //echo "</pre>";
     //now we can count total queries, how many time the same query is run,
     //if we want to do db timings we would need to do this from a different listener. (actually not sure how this will work...)
 }
Exemple #9
0
 public static function tearDownAfterClass()
 {
     if (RedBeanDatabase::isFrozen()) {
         TestDatabaseUtil::deleteRowsFromAllTablesExceptLog();
     } else {
         TestDatabaseUtil::deleteAllTablesExceptLog();
     }
     RedBeanModel::forgetAll();
     RedBeanDatabase::close();
     assert('!RedBeanDatabase::isSetup()');
     // Not Coding Standard
     GeneralCache::forgetAll();
 }
Exemple #10
0
 public function testResolveModelsHasManyFilesFromPost()
 {
     if (!RedBeanDatabase::isFrozen()) {
         Yii::app()->user->userModel = User::getByUsername('super');
         $fileCount = count(FileModel::getAll());
         $this->assertEquals(0, $fileCount);
         $file1 = ZurmoTestHelper::createFileModel();
         $file2 = ZurmoTestHelper::createFileModel();
         $file3 = ZurmoTestHelper::createFileModel();
         $model = new ModelWithAttachmentTestItem();
         $_POST['myTest'] = array($file1->id, $file2->id, $file3->id);
         FileModelUtil::resolveModelsHasManyFilesFromPost($model, 'files', 'myTest');
         $model->member = 'test';
         $saved = $model->save();
         $this->assertTrue($saved);
         $fileCount = count(FileModel::getAll());
         $this->assertEquals(3, $fileCount);
         $modelId = $model->id;
         $model->forget();
         $model = ModelWithAttachmentTestItem::getById($modelId);
         $this->assertEquals(3, $model->files->count());
         //Add a fourth file.
         $file4 = ZurmoTestHelper::createFileModel();
         $_POST['myTest'] = array($file1->id, $file2->id, $file3->id, $file4->id);
         FileModelUtil::resolveModelsHasManyFilesFromPost($model, 'files', 'myTest');
         $saved = $model->save();
         $this->assertTrue($saved);
         $fileCount = count(FileModel::getAll());
         $this->assertEquals(4, $fileCount);
         $model->forget();
         $model = ModelWithAttachmentTestItem::getById($modelId);
         $this->assertEquals(4, $model->files->count());
         //Remove the 2nd file.
         $_POST['myTest'] = array($file1->id, $file3->id, $file4->id);
         FileModelUtil::resolveModelsHasManyFilesFromPost($model, 'files', 'myTest');
         $saved = $model->save();
         $this->assertTrue($saved);
         $fileCount = count(FileModel::getAll());
         $this->assertEquals(3, $fileCount);
         $model->forget();
         $model = ModelWithAttachmentTestItem::getById($modelId);
         $this->assertEquals(3, $model->files->count());
         $compareIds = array($file1->id, $file3->id, $file4->id);
         foreach ($model->files as $fileModel) {
             $this->assertTrue(in_array($fileModel->id, $compareIds));
         }
     }
 }
 public function onEvent($type, $info)
 {
     assert('$type == "update"');
     if (RedBeanDatabase::isFrozen()) {
         return;
     }
     $hints = $info->getMeta("hint");
     if ($hints !== null) {
         assert('is_array($hints)');
         foreach ($hints as $key => $value) {
             if (in_array($value, array('blob', 'longblob', 'boolean', 'date', 'datetime', 'string', 'text', 'longtext', 'id'))) {
                 RedBeanColumnTypeOptimizer::optimize($info->getMeta("type"), $key, $value);
             }
         }
     }
 }
 /**
  * Make sure the query actually runs correctly.
  */
 public function testASingleAttributeThatRunsFrozenQueryCorrectly()
 {
     if (RedBeanDatabase::isFrozen()) {
         $q = DatabaseCompatibilityUtil::getQuote();
         $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter('ReportModelTestItem');
         $builder = new FiltersReportQueryBuilder($joinTablesAdapter, '1');
         $filter = new FilterForReportForm('AccountsModule', 'Account', Report::TYPE_ROWS_AND_COLUMNS);
         $filter->attributeIndexOrDerivedType = 'ReadOptimization';
         $content = $builder->makeQueryContent(array($filter));
         $compareContent = "({$q}ownedsecurableitem{$q}.{$q}securableitem_id{$q} = (select securableitem_id " . "from {$q}account_read{$q} where {$q}securableitem_id{$q} = {$q}ownedsecurableitem" . "{$q}.{$q}securableitem_id{$q} and {$q}munge_id{$q} in ('U" . self::$superUserId . "', 'G" . self::$everyoneGroupId . "') limit 1))";
         $this->assertEquals($compareContent, $content);
         $this->assertEquals(1, $joinTablesAdapter->getFromTableJoinCount());
         $this->assertEquals(0, $joinTablesAdapter->getLeftTableJoinCount());
         $selectQueryAdapter = new RedBeanModelSelectQueryAdapter();
         $selectQueryAdapter->addClause(Account::getTableName('Account'), 'id');
         $sql = SQLQueryUtil::makeQuery(Account::getTableName('Account'), $selectQueryAdapter, $joinTablesAdapter, null, null, $content, null, null);
         $rows = R::getAll($sql);
         $this->assertEquals(0, count($rows));
     }
 }
 public function save($runValidation = true)
 {
     foreach ($this->deferredRelateBeans as $bean) {
         R::associate($this->bean, $bean);
         if (!RedBeanDatabase::isFrozen()) {
             $types = array($this->bean->getMeta("type"), $bean->getMeta("type"));
             sort($types);
             $tableName = implode("_", $types);
             foreach ($types as $type) {
                 $columnName = "{$type}_id";
                 RedBeanColumnTypeOptimizer::optimize($tableName, $columnName, 'id');
             }
         }
     }
     $this->deferredRelateBeans = array();
     foreach ($this->deferredUnrelateBeans as $bean) {
         R::unassociate($this->bean, $bean);
     }
     $this->deferredUnrelateBeans = array();
     return true;
 }
 /**
  * Given a file resource, convert the file into a database table based on the table name provided.
  * Assumes the file is a csv.
  * @param resource $fileHandle
  * @param string $tableName
  * @return true on success.
  */
 public static function makeDatabaseTableByFileHandleAndTableName($fileHandle, $tableName, $delimiter = ',', $enclosure = "'")
 {
     assert('gettype($fileHandle) == "resource"');
     assert('is_string($tableName)');
     assert('$tableName == strtolower($tableName)');
     assert('$delimiter != null && is_string($delimiter)');
     assert('$enclosure != null && is_string($enclosure)');
     $freezeWhenComplete = false;
     if (RedBeanDatabase::isFrozen()) {
         RedBeanDatabase::unfreeze();
         $freezeWhenComplete = true;
     }
     R::exec("drop table if exists {$tableName}");
     $columns = self::optimizeTableImportColumnsAndGetColumnNames($fileHandle, $tableName, $delimiter, $enclosure);
     rewind($fileHandle);
     self::convertCsvIntoRowsInTable($fileHandle, $tableName, $delimiter, $enclosure, $columns);
     self::optimizeTableNonImportColumns($tableName);
     if ($freezeWhenComplete) {
         RedBeanDatabase::freeze();
     }
     return true;
 }
 public static function close()
 {
     // TODO - find out if there is a proper way.
     ZurmoRedBean::$toolboxes = array();
     ZurmoRedBean::$toolbox = null;
     ZurmoRedBean::$redbean = null;
     ZurmoRedBean::$writer = null;
     ZurmoRedBean::$adapter = null;
     ZurmoRedBean::$associationManager = null;
     ZurmoRedBean::$extAssocManager = null;
     ZurmoRedBean::$exporter = null;
     ZurmoRedBean::$tagManager = null;
     ZurmoRedBean::$currentDB = '';
     ZurmoRedBean::$f = null;
     ZurmoRedBean::close();
     self::$isSetup = false;
 }
 /**
  * Set a global configuration value by module name and key
  */
 public static function setByModuleName($moduleName, $key, $value)
 {
     assert('is_string($moduleName)');
     assert('is_string($key)');
     if (!RedBeanDatabase::isSetup()) {
         return null;
     }
     $metadata = $moduleName::getMetadata();
     $metadata['global'][$key] = $value;
     static::cacheValue($moduleName, $key, $value);
     $moduleName::setMetadata($metadata);
 }
 public function testMapHintTypeIntoDatabaseColumnType()
 {
     if (RedBeanDatabase::getDatabaseType() == 'mysql') {
         $databaseColumnType = DatabaseCompatibilityUtil::mapHintTypeIntoDatabaseColumnType('blob');
         $this->assertEquals('BLOB', $databaseColumnType);
         $databaseColumnType = DatabaseCompatibilityUtil::mapHintTypeIntoDatabaseColumnType('longblob');
         $this->assertEquals('LONGBLOB', $databaseColumnType);
         $databaseColumnType = DatabaseCompatibilityUtil::mapHintTypeIntoDatabaseColumnType('boolean');
         $this->assertEquals('TINYINT(1)', $databaseColumnType);
         $databaseColumnType = DatabaseCompatibilityUtil::mapHintTypeIntoDatabaseColumnType('date');
         $this->assertEquals('DATE', $databaseColumnType);
         $databaseColumnType = DatabaseCompatibilityUtil::mapHintTypeIntoDatabaseColumnType('datetime');
         $this->assertEquals('DATETIME', $databaseColumnType);
         $databaseColumnType = DatabaseCompatibilityUtil::mapHintTypeIntoDatabaseColumnType('string');
         $this->assertEquals('VARCHAR(255)', $databaseColumnType);
         $databaseColumnType = DatabaseCompatibilityUtil::mapHintTypeIntoDatabaseColumnType('text');
         $this->assertEquals('TEXT', $databaseColumnType);
         $databaseColumnType = DatabaseCompatibilityUtil::mapHintTypeIntoDatabaseColumnType('longtext');
         $this->assertEquals('LONGTEXT', $databaseColumnType);
         $databaseColumnType = DatabaseCompatibilityUtil::mapHintTypeIntoDatabaseColumnType('id');
         $this->assertEquals('INT(11) UNSIGNED', $databaseColumnType);
         try {
             $databaseColumnType = DatabaseCompatibilityUtil::mapHintTypeIntoDatabaseColumnType('invalidType');
             $this->fail();
         } catch (NotSupportedException $e) {
             // Do nothing
         }
     }
 }
 protected static function closeDatabaseConnection()
 {
     if (RedBeanDatabase::isSetup()) {
         RedBeanDatabase::close();
         assert('!RedBeanDatabase::isSetup()');
     }
 }
 protected static function reconnectToDatabase()
 {
     RedBeanDatabase::close();
     RedBeanDatabase::setup(Yii::app()->db->connectionString, Yii::app()->db->username, Yii::app()->db->password);
 }
 public function handleEndRequest($event)
 {
     RedBeanDatabase::close();
     exit;
 }
 public function testToggleStar()
 {
     if (!RedBeanDatabase::isFrozen()) {
         StarredUtil::createStarredTables();
         $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
         $account = new Account();
         $account->owner = $super;
         $account->name = 'Test Account';
         $account->officePhone = '1234567890';
         $this->assertTrue($account->save());
         $this->setGetArray(array('modelClassName' => 'Account', 'modelId' => $account->id));
         $content = $this->runControllerWithNoExceptionsAndGetContent('zurmo/default/toggleStar');
         $this->assertEquals('icon-star starred', $content);
         $this->assertTrue(StarredUtil::isModelStarred($account));
         $content = $this->runControllerWithNoExceptionsAndGetContent('zurmo/default/toggleStar');
         $this->assertEquals('icon-star unstarred', $content);
         $this->assertFalse(StarredUtil::isModelStarred($account));
     }
 }
 protected static function decrementParentRolesCountsForAllSecurableItems($mungeTableName, Role $role)
 {
     assert('is_string($mungeTableName) && $mungeTableName != ""');
     if (!RedBeanDatabase::isFrozen() && $role->role->isSame($role)) {
         return;
     }
     if ($role->role->id > 0) {
         self::decrementCountForAllSecurableItems($mungeTableName, $role->role);
         self::decrementParentRolesCountsForAllSecurableItems($mungeTableName, $role->role);
     }
 }
 /**
  * @depends testGetGlobalSearchResultsByPartialTermUsingScope
  */
 public function testGetGlobalSearchResultsByPartialTermWithRegularUserAndElevationStepsForRegularUser()
 {
     //Unfrozen, there are too many attributes that have to be columns in the database at this point, so
     //now this is just a frozen test.
     if (RedBeanDatabase::isFrozen()) {
         $super = User::getByUsername('super');
         $jimmy = User::getByUsername('jimmy');
         Yii::app()->user->userModel = $super;
         //Jimmy does not have read access, so he should not be able to see any results.
         $this->assertEquals(Right::DENY, $jimmy->getEffectiveRight('AccountsModule', AccountsModule::RIGHT_ACCESS_ACCOUNTS));
         $this->assertEquals(Right::DENY, $jimmy->getEffectiveRight('ContactsModule', ContactsModule::RIGHT_ACCESS_CONTACTS));
         $this->assertEquals(Right::DENY, $jimmy->getEffectiveRight('OpportunitiesModule', OpportunitiesModule::RIGHT_ACCESS_OPPORTUNITIES));
         Yii::app()->user->userModel = $jimmy;
         $data = ModelAutoCompleteUtil::getGlobalSearchResultsByPartialTerm('animal', 5, Yii::app()->user->userModel);
         $this->assertEquals(array(array('href' => '', 'label' => 'No Results Found', 'iconClass' => '')), $data);
         //Give Jimmy access to the module, he still will not be able to see results.
         Yii::app()->user->userModel = $super;
         $jimmy->setRight('AccountsModule', AccountsModule::RIGHT_ACCESS_ACCOUNTS);
         $jimmy->setRight('ContactsModule', ContactsModule::RIGHT_ACCESS_CONTACTS);
         $jimmy->setRight('LeadsModule', LeadsModule::RIGHT_ACCESS_LEADS);
         $jimmy->setRight('OpportunitiesModule', OpportunitiesModule::RIGHT_ACCESS_OPPORTUNITIES);
         $this->assertTrue($jimmy->save());
         Yii::app()->user->userModel = $jimmy;
         $data = ModelAutoCompleteUtil::getGlobalSearchResultsByPartialTerm('animal', 5, Yii::app()->user->userModel);
         $this->assertEquals(array(array('href' => '', 'label' => 'No Results Found', 'iconClass' => '')), $data);
         //Give Jimmy read on 1 model.  The search then should pick up this model.
         Yii::app()->user->userModel = $super;
         $accounts = Account::getByName('The Zoo');
         $this->assertEquals(1, count($accounts));
         $account = $accounts[0];
         $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($jimmy));
         $account->addPermissions($jimmy, Permission::READ);
         $this->assertTrue($account->save());
         ReadPermissionsOptimizationUtil::securableItemGivenPermissionsForUser($account, $jimmy);
         Yii::app()->user->userModel = $jimmy;
         $data = ModelAutoCompleteUtil::getGlobalSearchResultsByPartialTerm('animal', 5, Yii::app()->user->userModel);
         $this->assertEquals(1, count($data));
         $this->assertEquals('The Zoo', $data[0]['label']);
         //Give Jimmy read on 2 more models.  The search then should pick up these models.
         Yii::app()->user->userModel = $super;
         $contacts = Contact::getByName('Big Elephant');
         $this->assertEquals(1, count($contacts));
         $contact = $contacts[0];
         $this->assertEquals(Permission::NONE, $contact->getEffectivePermissions($jimmy));
         $contact->addPermissions($jimmy, Permission::READ);
         $this->assertTrue($contact->save());
         ReadPermissionsOptimizationUtil::securableItemGivenPermissionsForUser($contact, $jimmy);
         $opportunities = Opportunity::getByName('Animal Crackers');
         $this->assertEquals(1, count($opportunities));
         $opportunity = $opportunities[0];
         $this->assertEquals(Permission::NONE, $opportunity->getEffectivePermissions($jimmy));
         $opportunity->addPermissions($jimmy, Permission::READ);
         $this->assertTrue($opportunity->save());
         ReadPermissionsOptimizationUtil::securableItemGivenPermissionsForUser($opportunity, $jimmy);
         Yii::app()->user->userModel = $jimmy;
         $data = ModelAutoCompleteUtil::getGlobalSearchResultsByPartialTerm('animal', 5, Yii::app()->user->userModel);
         $this->assertEquals(3, count($data));
         $this->assertEquals('The Zoo', $data[0]['label']);
         $this->assertEquals('Big Elephant', $data[1]['label']);
         $this->assertEquals('Animal Crackers', $data[2]['label']);
     }
 }
Exemple #24
0
 /**
  * Execute the action.
  * @param array command line parameters specific for this command
  */
 public function run($args)
 {
     set_time_limit('3600');
     if (!isset($args[0])) {
         $this->usageError('You must specify an action.');
     } else {
         $action = $args[0];
     }
     if (!isset($args[1])) {
         $this->usageError('You must specify a path to the file.');
     } else {
         $filePath = $args[1];
     }
     if (count($args) != 2 && count($args) != 8) {
         $this->usageError('Invalid number of arguments.');
     }
     if (count($args) == 8) {
         $databaseType = $args[2];
         $databaseHost = $args[3];
         $databaseName = $args[4];
         $databasePort = $args[5];
         $databaseUsername = $args[6];
         $databasePassword = $args[7];
     } else {
         $databaseConnectionInfo = RedBeanDatabase::getDatabaseInfoFromDsnString(Yii::app()->db->connectionString);
         $databaseType = $databaseConnectionInfo['databaseType'];
         $databaseHost = $databaseConnectionInfo['databaseHost'];
         $databaseName = $databaseConnectionInfo['databaseName'];
         $databasePort = $databaseConnectionInfo['databasePort'];
         $databaseUsername = Yii::app()->db->username;
         $databasePassword = Yii::app()->db->password;
     }
     if (!Yii::app()->isApplicationInMaintenanceMode()) {
         $this->usageError('Please set $maintenanceMode = true in the perInstance.php config file.');
     }
     if (!function_exists('exec')) {
         $this->usageError('exec() command is not available in PHP environment.');
     }
     try {
         $template = "{message}\n";
         $messageStreamer = new MessageStreamer($template);
         $messageStreamer->setExtraRenderBytes(0);
         $messageStreamer->add(' ');
         if ($action == 'backup') {
             $this->backupDatabase($filePath, $messageStreamer, $databaseType, $databaseHost, $databaseName, $databasePort, $databaseUsername, $databasePassword);
         } elseif ($action == 'restore') {
             $this->restoreDatabase($filePath, $messageStreamer, $databaseType, $databaseHost, $databaseName, $databasePort, $databaseUsername, $databasePassword);
         } else {
             $this->usageError('Invalid action. Valid values are "backup" and "restore".');
         }
     } catch (Exception $e) {
         $messageStreamer->add(Zurmo::t('Commands', 'An error occur during database backup/restore: {message}', array('{message}' => $e->getMessage())));
     }
 }
 public function testRun()
 {
     chdir(COMMON_ROOT . DIRECTORY_SEPARATOR . 'protected' . DIRECTORY_SEPARATOR . 'commands');
     $command = "php zurmocTest.php install {$this->temporaryDatabaseHostname} {$this->temporaryDatabaseName} ";
     $command .= "{$this->temporaryDatabaseUsername} {$this->temporaryDatabasePassword} {$this->temporaryDatabasePort} ";
     $command .= "{$this->superUserPassword} 'http://sampleHost' 'app/index.php' demodata 1";
     if (!IS_WINNT) {
         $command .= ' 2>&1';
     }
     exec($command, $output);
     $instanceRoot = INSTANCE_ROOT;
     $perInstanceConfigFile = "{$instanceRoot}/protected/config/perInstanceTest.php";
     $debugConfigFile = "{$instanceRoot}/protected/config/debugTest.php";
     $perInstanceConfiguration = file_get_contents($perInstanceConfigFile);
     $debugConfiguration = file_get_contents($debugConfigFile);
     //Check if config files is updated.
     $this->assertRegExp('/\\$connectionString = \'mysql:host=' . $this->temporaryDatabaseHostname . ';port=' . $this->temporaryDatabasePort . ';dbname=' . $this->temporaryDatabaseName . '\';/', $perInstanceConfiguration);
     $this->assertRegExp('/\\$username         = \'' . $this->temporaryDatabaseUsername . '\';/', $perInstanceConfiguration);
     $this->assertRegExp('/\\$password         = \'' . $this->temporaryDatabasePassword . '\';/', $perInstanceConfiguration);
     RedBeanDatabase::close();
     RedBeanDatabase::setup(Yii::app()->tempDb->connectionString, Yii::app()->tempDb->username, Yii::app()->tempDb->password, true);
     $count = R::getRow('select count(*) count from _user');
     $this->assertEquals(9, $count['count']);
 }
Exemple #26
0
 protected function linkBeans()
 {
     $baseModelClassName = null;
     $baseBean = null;
     foreach ($this->modelClassNameToBean as $modelClassName => $bean) {
         if ($baseBean !== null) {
             ZurmoRedBeanLinkManager::link($bean, $baseBean);
             if (!RedBeanDatabase::isFrozen()) {
                 $tableName = self::getTableName($modelClassName);
                 $columnName = self::getTableName($baseModelClassName) . '_id';
                 RedBeanColumnTypeOptimizer::optimize($tableName, $columnName, 'id');
             }
         }
         $baseModelClassName = $modelClassName;
         $baseBean = $bean;
     }
 }
 /**
  * @depends testAutoBuildDatabase
  */
 public function testAutoBuildUpgrade()
 {
     $this->unfreezeWhenDone = false;
     if (RedBeanDatabase::isFrozen()) {
         RedBeanDatabase::unfreeze();
         $this->unfreezeWhenDone = true;
     }
     // adding Text Field
     $metadata = Account::getMetadata();
     $metadata['Account']['members'][] = 'newField';
     $rules = array('newField', 'type', 'type' => 'string');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'string128';
     $rules = array('string128', 'type', 'type' => 'string');
     $metadata['Account']['rules'][] = $rules;
     $rules = array('string128', 'length', 'min' => 3, 'max' => 128);
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'string555';
     $rules = array('string555', 'type', 'type' => 'string');
     $metadata['Account']['rules'][] = $rules;
     $rules = array('string555', 'length', 'min' => 1, 'max' => 555);
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'string100000';
     $rules = array('string100000', 'type', 'type' => 'string');
     $metadata['Account']['rules'][] = $rules;
     $rules = array('string100000', 'length', 'min' => 1, 'max' => 100000);
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'textField';
     $rules = array('textField', 'type', 'type' => 'text');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'longTextField';
     $rules = array('longTextField', 'type', 'type' => 'longtext');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'dateField';
     $rules = array('dateField', 'type', 'type' => 'date');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'booleanField';
     $rules = array('booleanField', 'boolean');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'integerField';
     $rules = array('integerField', 'type', 'type' => 'integer');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'dateTimeField';
     $rules = array('dateTimeField', 'type', 'type' => 'datetime');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'urlField';
     $rules = array('urlField', 'url');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'floatField';
     $rules = array('floatField', 'type', 'type' => 'float');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'longTextField';
     $rules = array('longTextField', 'type', 'type' => 'longtext');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'blobField';
     $rules = array('blobField', 'type', 'type' => 'blob');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'longBlobField';
     $rules = array('longBlobField', 'type', 'type' => 'longblob');
     $metadata['Account']['rules'][] = $rules;
     Account::setMetadata($metadata);
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $messageLogger = new MessageLogger();
     $beforeRowCount = DatabaseCompatibilityUtil::getTableRowsCountTotal();
     InstallUtil::autoBuildDatabase($messageLogger);
     $afterRowCount = DatabaseCompatibilityUtil::getTableRowsCountTotal();
     $this->assertEquals($beforeRowCount, $afterRowCount);
     //Check Account fields
     $tableName = RedBeanModel::getTableName('Account');
     $columns = R::$writer->getColumns($tableName);
     $this->assertEquals('text', $columns['newfield']);
     $this->assertEquals('varchar(128)', $columns['string128']);
     $this->assertEquals('text', $columns['string555']);
     $this->assertEquals('longtext', $columns['string100000']);
     $this->assertEquals('text', $columns['textfield']);
     $this->assertEquals('date', $columns['datefield']);
     $this->assertEquals('tinyint(1)', $columns['booleanfield']);
     $this->assertEquals('int(11) unsigned', $columns['integerfield']);
     $this->assertEquals('datetime', $columns['datetimefield']);
     $this->assertEquals('varchar(255)', $columns['urlfield']);
     $this->assertEquals('double', $columns['floatfield']);
     $this->assertEquals('longtext', $columns['longtextfield']);
     $this->assertEquals('blob', $columns['blobfield']);
     $this->assertEquals('longblob', $columns['longblobfield']);
     $account = new Account();
     $account->name = 'Test Name';
     $account->owner = $super;
     $randomString = str_repeat("Aa", 64);
     $account->string128 = $randomString;
     $this->assertTrue($account->save());
     $metadata = Account::getMetadata();
     foreach ($metadata['Account']['rules'] as $key => $rule) {
         if ($rule[0] == 'string128' && $rule[1] == 'length') {
             $metadata['Account']['rules'][$key]['max'] = 64;
         }
     }
     Account::setMetadata($metadata);
     InstallUtil::autoBuildDatabase($messageLogger);
     RedBeanModel::forgetAll();
     $modifiedAccount = Account::getById($account->id);
     $this->assertEquals($randomString, $modifiedAccount->string128);
     //Check Account fields
     $tableName = RedBeanModel::getTableName('Account');
     $columns = R::$writer->getColumns($tableName);
     $this->assertEquals('varchar(128)', $columns['string128']);
 }
 public static function dropStoredFunctionsAndProcedures()
 {
     assert('RedBeanDatabase::isSetup()');
     if (RedBeanDatabase::getDatabaseType() == 'mysql') {
         try {
             $rows = ZurmoRedBean::getAll("select routine_name, routine_type from information_schema.routines;");
             foreach ($rows as $row) {
                 ZurmoRedBean::exec("drop {$row['routine_type']} if exists {$row['routine_name']}");
             }
         } catch (Exception $e) {
             if (isset($row)) {
                 echo "Failed to drop {$row['routine_type']} {$row['routine_name']}.\n";
             }
             throw $e;
         }
         if (YII_DEBUG) {
             ZurmoRedBean::exec("drop procedure if exists write_log");
         }
     } else {
         throw new NotSupportedException();
     }
 }
 public static function tearDownAfterClass()
 {
     if (self::$freeze) {
         RedBeanDatabase::freeze();
     }
     parent::tearDownAfterClass();
 }
 public static function checkServicesAfterInstallationAndGetResultsDataForDisplay()
 {
     $servicesToCheck = self::getServicesToCheckAfterInstallation();
     $form = new InstallSettingsForm();
     list(, $form->databaseHostname, $form->databasePort, $form->databaseName) = array_values(RedBeanDatabase::getDatabaseInfoFromDsnString(Yii::app()->db->connectionString));
     $form->databaseUsername = Yii::app()->db->username;
     $form->databasePassword = Yii::app()->db->password;
     return static::processServicesAndGetResultsData($servicesToCheck, $form);
 }