Example #1
0
 public function actionUpdate()
 {
     $isSubmitted = false;
     $sql = false;
     $foreignKey = ForeignKey::model()->findBySql('SELECT * FROM KEY_COLUMN_USAGE ' . 'WHERE TABLE_SCHEMA = :tableSchema ' . 'AND TABLE_NAME = :tableName ' . 'AND COLUMN_NAME = :columnName ' . 'AND REFERENCED_TABLE_SCHEMA IS NOT NULL', array('tableSchema' => $this->schema, 'tableName' => $this->table, 'columnName' => $this->column));
     if (!$foreignKey) {
         $foreignKey = new ForeignKey();
         $foreignKey->TABLE_SCHEMA = $this->schema;
         $foreignKey->TABLE_NAME = $this->table;
         $foreignKey->COLUMN_NAME = $this->column;
     }
     if (isset($_POST['ForeignKey'])) {
         $foreignKey->attributes = $_POST['ForeignKey'];
         if ($foreignKey->getReferences() && ($sql = $foreignKey->save())) {
             $isSubmitted = true;
         } elseif (!$foreignKey->getReferences() && ($sql = $foreignKey->delete())) {
             $isSubmitted = true;
         }
     }
     CHtml::generateRandomIdPrefix();
     // Column data
     $columns = array('' => '');
     $tables = Table::model()->findAllByAttributes(array('TABLE_SCHEMA' => $this->schema));
     foreach ($tables as $table) {
         if (StorageEngine::check($table->ENGINE, StorageEngine::SUPPORTS_FOREIGN_KEYS)) {
             $columns[$table->TABLE_NAME] = array();
             foreach ($table->columns as $column) {
                 $columns[$table->TABLE_NAME][$this->schema . '.' . $table->TABLE_NAME . '.' . $column->COLUMN_NAME] = $column->COLUMN_NAME;
             }
         }
     }
     // "On-Actions"
     $onActions = array('' => '', 'CASCADE' => 'CASCADE', 'SET NULL' => 'SET NULL', 'NO ACTION' => 'NO ACTION', 'RESTRICT' => 'RESTRICT');
     $this->render('form', array('foreignKey' => $foreignKey, 'columns' => $columns, 'onActions' => $onActions, 'sql' => $sql, 'isSubmitted' => $isSubmitted));
 }
Example #2
0
 public function actionCreate()
 {
     $column = new Column();
     $column->TABLE_NAME = $this->table;
     $table = Table::model()->findByPk(array('TABLE_SCHEMA' => $this->schema, 'TABLE_NAME' => $this->table));
     if (isset($_POST['Column'])) {
         $column->attributes = $_POST['Column'];
         /*
          * Add index
          */
         $addIndices = array();
         if (isset($_POST['createIndexPrimary'])) {
             $column->createPrimaryKey = true;
         }
         if (isset($_POST['createIndex'])) {
             $addIndices['INDEX'] = $column->COLUMN_NAME;
         }
         if (isset($_POST['createIndexUnique'])) {
             $column->createUniqueKey = true;
         }
         if (isset($_POST['createIndexFulltext'])) {
             $addIndices['FULLTEXT'] = $column->COLUMN_NAME . (array_search($column->COLUMN_NAME, $addIndices) !== false ? '_fulltext' : '');
         }
         if ($sql = $column->save()) {
             $response = new AjaxResponse();
             $response->addNotification('success', Yii::t('core', 'successAddColumn', array('{col}' => $column->COLUMN_NAME)), null, $sql);
             $response->refresh = true;
             foreach ($addIndices as $type => $indexName) {
                 try {
                     $index = new Index();
                     $index->throwExceptions = true;
                     $index->TABLE_NAME = $this->table;
                     $index->TABLE_SCHEMA = $this->schema;
                     $index->INDEX_NAME = $indexName;
                     $index->setType($type);
                     $indexCol = new IndexColumn();
                     $indexCol->COLUMN_NAME = $column->COLUMN_NAME;
                     $index->columns = array($indexCol);
                     $sql = $index->save();
                     $response->addNotification('success', Yii::t('core', 'successCreateIndex', array('{index}' => $index->INDEX_NAME)), null, $sql);
                 } catch (DbException $ex) {
                     $response->addNotification('error', Yii::t('core', 'errorCreateIndex', array('{index}' => $index->INDEX_NAME)), $ex->getText(), $ex->getSql());
                 }
             }
             $this->sendJSON($response);
         }
     }
     $collations = Collation::model()->findAll(array('order' => 'COLLATION_NAME', 'select' => 'COLLATION_NAME, CHARACTER_SET_NAME AS collationGroup'));
     CHtml::generateRandomIdPrefix();
     $data = array('column' => $column, 'table' => $table, 'collations' => $collations);
     $data['formBody'] = $this->renderPartial('formBody', $data, true);
     $this->render('form', $data);
 }
Example #3
0
 /**
  * Checks what happens when deleting auto_increment primary key.
  *
  * @expectedException DbException
  */
 public function testDeleteAutoIncrement()
 {
     // Load table
     $table = Table::model()->findByPk(array('TABLE_SCHEMA' => 'indextest', 'TABLE_NAME' => 'table1'));
     // Delete key
     $index = $table->indices[0];
     $res = $index->delete();
     // Check result
     $this->assertEquals(false, $res);
     // Set throwExceptions and try again
     $index->throwExceptions = true;
     $index->delete();
 }
Example #4
0
 /**
  * Test dropping
  */
 public function testDrop()
 {
     // Load table definition
     $table = Table::model()->findByPk(array('TABLE_SCHEMA' => 'columntest', 'TABLE_NAME' => 'test'));
     // Save column count
     $columnCount = count($table->columns);
     // Drop first column
     $col = $table->columns[0];
     $col->throwExceptions = true;
     $this->assertType('string', $col->delete());
     // Load table definition
     $table = Table::model()->findByPk(array('TABLE_SCHEMA' => 'columntest', 'TABLE_NAME' => 'test'));
     // Check column count
     $this->assertEquals($columnCount - 1, count($table->columns));
 }
Example #5
0
 /**
  * @see		ActiveRecord::instantiate()
  */
 public function instantiate($attributes)
 {
     $res = parent::instantiate($attributes);
     $res->table = Table::model()->findByAttributes(array('TABLE_SCHEMA' => $attributes['TABLE_SCHEMA'], 'TABLE_NAME' => $attributes['TABLE_NAME']));
     $match = '/^\\s+constraint `' . $attributes['CONSTRAINT_NAME'] . '` .+?$/im';
     if (preg_match($match, $res->table->getShowCreateTable(), $result)) {
         if (preg_match('/on delete (CASCADE|NO ACTION|SET NULL|RESTRICT)/i', $result[0], $result2)) {
             $res->onDelete = $result2[1];
         }
         if (preg_match('/on update (CASCADE|NO ACTION|SET NULL|RESTRICT)/i', $result[0], $result2)) {
             $res->onUpdate = $result2[1];
         }
     }
     return $res;
 }
 public function loadModel($id)
 {
     if (($model = Table::model()->with(array('person', 'event'))->findByPk($id)) === null) {
         throw new CHttpException(404, 'Страница не найдена');
     }
     return $model;
 }
Example #7
0
 /**
  * Exports all tables of the given array and writes the dump to the output buffer.
  * @todo	constraints
  *
  * @param	array					list of tables
  */
 private function exportTables($tables)
 {
     // Get DbConnection object
     $db = Yii::app()->db;
     // Escape all table names
     $tableNames = array();
     foreach ($tables as $table) {
         $tableNames[] = Yii::app()->db->quoteValue($table);
     }
     // Find all tables
     $allTables = Table::model()->findAll('TABLE_SCHEMA = ' . Yii::app()->db->quoteValue($this->schema));
     if (count($tables) > 0) {
         $filteredTables = array();
         foreach ($allTables as $table) {
             if (in_array($table->TABLE_NAME, $tables)) {
                 $filteredTables[] = $table;
             }
         }
     } else {
         $filteredTables = $allTables;
     }
     foreach ($filteredTables as $table) {
         if ($this->settings['exportStructure']) {
             $this->exportTableStructure($table);
         }
         if ($this->settings['exportData']) {
             // Data
             $this->exportTableData($table);
         }
     }
 }
 public function actionCalculate($id, $code)
 {
     // Загрузка таблицы для блока
     $table = Table::model()->findByPK((int) $id);
     if ($table === null) {
         throw new CHttpException('404');
     }
     // Устанавливаем источники данных
     $person = null;
     $event = null;
     $personForm = new PersonForm();
     $eventForm = new EventForm();
     $this->performAjaxValidation(array($personForm, $eventForm), $code);
     if ($table->source_destiny_table == Table::SOURCE_FROM_USER && ($personFormData = Yii::app()->getRequest()->getPost('PersonForm')) !== null) {
         $personForm->setAttributes($personFormData);
         if ($personForm->validate()) {
             $person = new Person();
             $person->setAttributes(array('name' => $personForm->name, 'gender' => $personForm->gender, 'date' => $personForm->date, 'time' => $personForm->getTime(), 'city_id' => $personForm->city_id));
         }
     }
     if ($table->source_event_table == Table::SOURCE_FROM_USER && ($eventFormData = Yii::app()->getRequest()->getPost('EventForm')) !== null) {
         $eventForm->setAttributes($eventFormData);
         if ($eventForm->date != '' || $eventForm->city_id != '' || $eventForm->hour != '' || $eventForm->minute != '') {
             if ($eventForm->validate()) {
                 $event = new Event();
                 $event->setAttributes(array('date' => $eventForm->date, 'time' => $eventForm->getTime(), 'city_id' => $eventForm->city_id));
             }
         }
     }
     if (Yii::app()->request->isAjaxRequest) {
         if ($personForm->hasErrors() || $eventForm->hasErrors()) {
             $personForm->addErrors($eventForm->getErrors());
             Yii::app()->ajax->failure($personForm->getErrors());
         } else {
             $arr = explode('-', $code);
             $blockId = key_exists(0, $arr) ? (int) $arr[0] : '';
             $this->widget('application.modules.bazi.widgets.TableWidget', array('model_id' => $table->id, 'block_id' => $blockId, 'person' => $person, 'event' => $event));
         }
     }
     return false;
 }
Example #9
0
 /**
  * Lists all tables.
  */
 public function actionTables()
 {
     $schema = $this->loadSchema();
     // Criteria
     $criteria = new CDbCriteria();
     $criteria->condition = 'TABLE_SCHEMA = :schema AND TABLE_TYPE IN (\'BASE TABLE\', \'SYSTEM VIEW\')';
     $criteria->params = array(':schema' => $this->schema);
     if ($this->request->getParam('sideBar')) {
         $tables = array();
         foreach (Table::model()->findAll($criteria) as $table) {
             $tables[] = array('tableName' => $table->TABLE_NAME, 'rowCount' => $table->getRowCount(), 'rowCountText' => Yii::t('core', 'Xrows', array($table->getRowCount(), '{amount}' => $table->getRowCount())));
         }
         $this->sendJSON($tables);
     } else {
         // Pagination
         $pages = new Pagination(Table::model()->count($criteria));
         $pages->setupPageSize('pageSize', 'schema.tables');
         $pages->applyLimit($criteria);
         $pages->route = '#tables';
         // Sort
         $sort = new CSort('Table');
         $sort->attributes = array('name' => 'TABLE_NAME', 'rows' => 'TABLE_ROWS', 'collation' => 'TABLE_COLLATION', 'engine' => 'ENGINE', 'datalength' => 'DATA_LENGTH', 'datafree' => 'DATA_FREE');
         $sort->route = '#tables';
         $sort->applyOrder($criteria);
         // Load data
         $schema->tables = Table::model()->findAll($criteria);
         // Render
         $this->render('tables', array('schema' => $schema, 'tableCount' => count($schema->tables), 'pages' => $pages, 'sort' => $sort));
     }
 }
Example #10
0
 public function getTableList()
 {
     $models = Table::model()->findAll();
     return CHtml::listData($models, 'id', 'title');
 }
Example #11
0
 public function actionUpdate()
 {
     $index = Index::model()->findByAttributes(array('TABLE_SCHEMA' => $this->schema, 'TABLE_NAME' => $this->table, 'INDEX_NAME' => $this->index));
     if ($index == null) {
         $index = new Index();
         $index->TABLE_SCHEMA = $this->schema;
         $index->TABLE_NAME = $this->table;
         $index->INDEX_NAME = $this->index;
     }
     $table = Table::model()->findByPk(array('TABLE_SCHEMA' => $this->schema, 'TABLE_NAME' => $this->table));
     if (isset($_POST['Index'])) {
         $index->attributes = $_POST['Index'];
         $index->columns = $this->getColumnsFromRequest();
         if ($sql = $index->save()) {
             $response = new AjaxResponse();
             $response->addNotification('success', Yii::t('core', 'successAlterIndex', array('{index}' => $index->INDEX_NAME)), null, $sql);
             $response->refresh = true;
             $this->sendJSON($response);
         }
     }
     $indexTypes = $table->getSupportedIndexTypes();
     $this->render('form', array('index' => $index, 'indexTypes' => $indexTypes, 'addColumnData' => $this->getColumnSelect($table)));
 }
 /**
  * Запускаем отрисовку виджета
  *
  * @return void
  */
 public function run()
 {
     // Авторизован ли пользователь
     if (Yii::app()->user->isAuthenticated() === false) {
         return;
     }
     if (($user = Yii::app()->user->getProfile()) === null) {
         return;
     }
     // Загрузка таблицы для блока
     $table = Table::model()->with(array('descriptions'))->findByPK((int) $this->model_id);
     if ($table === null) {
         return;
     }
     // Устанавливаем источники данных
     $person = null;
     $event = null;
     $personForm = new PersonForm();
     $eventForm = new EventForm();
     $description = '';
     if ($table->source_destiny_table == Table::SOURCE_USER) {
         $person = new Person();
         $person->setAttributes(array('name' => $user->profile->name, 'gender' => $user->profile->gender, 'date' => $user->profile->birth_date, 'time' => $user->profile->birth_time, 'city_id' => $user->profile->city_id));
     } elseif ($table->source_destiny_table == Table::SOURCE_ADMIN) {
         $person = $table->person;
     } elseif ($table->source_destiny_table == Table::SOURCE_FROM_USER && ($personFormData = Yii::app()->getRequest()->getPost('PersonForm')) !== null) {
         $personForm->setAttributes($personFormData);
         if ($personForm->validate()) {
             $person = new Person();
             $person->setAttributes(array('name' => $personForm->name, 'gender' => $personForm->gender, 'date' => $personForm->date, 'time' => $personForm->getTime(), 'city_id' => $personForm->city_id));
         }
     }
     if ($table->source_event_table == Table::SOURCE_USER) {
         $event = new Event();
         $event->setAttributes(array('date' => date('Y-m-d'), 'time' => date('H:i'), 'city_id' => $user->profile->city_id));
     } elseif ($table->source_event_table == Table::SOURCE_ADMIN) {
         $event = $table->event;
     } elseif ($table->source_event_table == Table::SOURCE_FROM_USER && ($eventFormData = Yii::app()->getRequest()->getPost('EventForm')) !== null) {
         $eventForm->setAttributes($eventFormData);
         if ($eventForm->date != '' || $eventForm->city_id != '' || $eventForm->hour != '' || $eventForm->minute != '') {
             if ($eventForm->validate()) {
                 $event = new Event();
                 $event->setAttributes(array('date' => $eventForm->date, 'time' => $eventForm->getTime(), 'city_id' => $eventForm->city_id));
             }
         }
     }
     if ($person !== null) {
         $validateResult = $person->validate();
         $validateResult = $validateResult && ($event !== null ? $event->validate() : true);
     }
     if ($validateResult) {
         $calculator = new Calculator($person, $event);
         // Запуск расчета
         $calculator->run();
         if ($table->active_luck_pillar > 0) {
             $calculator->numCurrentLuckColumn = (int) $table->active_luck_pillar;
         }
         // Определяем описание
         $description = $table->description;
     } else {
         if ($person !== null) {
             $personForm->addErrors($person->getErrors());
         }
         if ($event !== null) {
             $eventForm->addErrors($event->getErrors());
         }
     }
     if (Yii::app()->request->isAjaxRequest) {
         $this->controller->renderPartial('//bazi/widgets/TableWidget/_chart', array('model' => $table, 'calculator' => $calculator, 'description' => $description), false, true);
     } else {
         $this->render($this->view, array('model' => $table, 'calculator' => $calculator, 'description' => $description, 'personForm' => $personForm, 'eventForm' => $eventForm));
     }
 }
Example #13
0
 /**
  * Запускаем отрисовку виджета
  *
  * @return void
  */
 public function run()
 {
     // Авторизован ли пользователь
     if (Yii::app()->user->isAuthenticated() === false) {
         return;
     }
     if (($user = Yii::app()->user->getProfile()) === null) {
         return;
     }
     // Загрузка таблицы для блока
     $table = Table::model()->with(array('markup'))->findByPK((int) $this->model_id);
     if ($table === null) {
         return;
     }
     // Генерируем уникальный код таблицы
     $tableCode = $this->block_id !== null ? $this->block_id . '-' : '';
     $tableCode .= $table->id . '-' . mt_rand(100000, 999999);
     // Устанавливаем источники данных
     $personForm = new PersonForm();
     $eventForm = new EventForm();
     $beforeDescription = '';
     $afterDescription = '';
     $useAltTable = false;
     // Если Персона не установлена
     if ($this->person === null) {
         // Если источник данных - данные пользователя,
         // то берем все данные из профиля пользователя
         if ($table->source_destiny_table == Table::SOURCE_USER) {
             $this->person = new Person();
             $this->person->setAttributes(array('name' => $user->profile->name, 'gender' => $user->profile->gender, 'date' => $user->profile->birth_date, 'time' => $user->profile->birth_time, 'city_id' => $user->profile->city_id));
         } elseif ($table->source_destiny_table == Table::SOURCE_ADMIN) {
             $this->person = $table->person;
         }
     }
     // Если Событие не установлено
     if ($this->event === null) {
         // Если источник данных - данные от администратора,
         // то берем данные из БД
         if ($table->source_event_table == Table::SOURCE_ADMIN) {
             $this->event = $table->event;
         }
     }
     // Проверка данных
     if ($this->person !== null) {
         $validateResult = $this->person->validate();
         $validateResult = $validateResult && ($this->event !== null ? $this->event->validate() : true);
     }
     // Если данные корректны
     if ($validateResult) {
         // Создаем калькулятор
         $calculator = new Calculator($this->person, $this->event);
         // Определяем активный столп
         if ($table->active_luck_pillar > 0) {
             $calculator->numCurrentLuckColumn = (int) $table->active_luck_pillar;
         }
         // Запуск расчета
         $calculator->run();
         // Если задана разметка, запускаем анализаторы
         if (!empty($table->markup)) {
             // Анализатор
             $analyzer = new Analyzer($calculator);
             // Запуск анализа
             $analyzer->run();
             $markupAnalyzer = new MarkupAnalyzer($table, $analyzer);
             $markupAnalyzer->run();
             //var_dump($markupAnalyzer->getFoundedMarkupItems());
             //exit();
             // Найденные элементы разметки
             $foundedMarkupItems = $markupAnalyzer->getFoundedMarkupItems();
             $useIndividualDescription = false;
             // Если не найден ни один элемент разметки
             if (empty($foundedMarkupItems)) {
                 // Если используется альтернативная таблица
                 if ($table->source_destiny_table == Table::SOURCE_USER && $table->use_alt_table) {
                     // Используем альтернативную таблицу
                     // Создаем калькулятор
                     $calculator = new Calculator($table->altTable, $this->event);
                     // Определяем активный столп
                     if ($table->active_luck_pillar > 0) {
                         $calculator->numCurrentLuckColumn = (int) $table->active_luck_pillar;
                     }
                     // Запуск расчета
                     $calculator->run();
                     // Анализатор
                     $analyzer = new Analyzer($calculator);
                     $analyzer->run();
                     $markupAnalyzer = new MarkupAnalyzer($table, $analyzer);
                     $markupAnalyzer->run();
                     // Альтернативное описание
                     if ($table->description_place == Table::DESCRIPTION_PLACE_BEFORE) {
                         $beforeDescription = $table->alt_description;
                     } elseif ($table->description_place == Table::DESCRIPTION_PLACE_AFTER) {
                         $afterDescription = $table->alt_description;
                     }
                     $useAltTable = true;
                 } else {
                     // В противном случае выводим основное описание
                     if ($table->description_place == Table::DESCRIPTION_PLACE_BEFORE) {
                         $beforeDescription = $table->description;
                     } elseif ($table->description_place == Table::DESCRIPTION_PLACE_AFTER) {
                         $afterDescription = $table->description;
                     }
                 }
             } else {
                 $useIndividualDescription = true;
             }
             if ($useIndividualDescription) {
                 // Формируем описания до таблиц и после для каждой найденной разметки
                 foreach ($foundedMarkupItems as $markupItem) {
                     if ($markupItem->description_place == TableMarkup::DESCRIPTION_PLACE_BEFORE) {
                         // Общее описание
                         $beforeDescription .= $markupItem->description;
                         // Описание для женщины
                         $beforeDescription .= $this->person->gender == Person::GENDER_FEMALE && $markupItem->description_f != '' ? $markupItem->description_f : '';
                         // Описание для мужчины
                         $beforeDescription .= $this->person->gender == Person::GENDER_MALE && $markupItem->description_m != '' ? $markupItem->description_m : '';
                     } elseif ($markupItem->description_place == TableMarkup::DESCRIPTION_PLACE_AFTER) {
                         // Общее описание
                         $afterDescription .= $markupItem->description;
                         // Описание для женщины
                         $afterDescription .= $this->person->gender == Person::GENDER_FEMALE && $markupItem->description_f != '' ? $markupItem->description_f : '';
                         // Описание для мужчины
                         $afterDescription .= $this->person->gender == Person::GENDER_MALE && $markupItem->description_m != '' ? $markupItem->description_m : '';
                     }
                 }
             }
         }
     } else {
         // Формируем список ошибок
         $errors = array();
         if ($this->person !== null) {
             foreach ($this->person->getErrors() as $key => $error) {
                 $errors['Person'][$key] = $error;
             }
         }
         if ($this->event !== null) {
             foreach ($this->event->getErrors() as $key => $error) {
                 $errors['Event'][$key] = $error;
             }
         }
     }
     //var_dump($beforeDescription);
     // Вывод в шаблон
     if (Yii::app()->request->isAjaxRequest) {
         // Если аякс-запрос, то перерисовываем только чарт
         $this->controller->renderPartial('//bazi/widgets/TableWidget/_chart', array('model' => $table, 'tableCode' => $tableCode, 'calculator' => $calculator, 'beforeDescription' => $beforeDescription, 'afterDescription' => $afterDescription, 'useAltTable' => $useAltTable, 'markupCells' => isset($markupAnalyzer) ? $markupAnalyzer->getMarkupCells() : array(), 'markupRelations' => isset($markupAnalyzer) ? $markupAnalyzer->getMarkupRelations() : array()));
     } else {
         $this->render($this->view, array('model' => $table, 'tableCode' => $tableCode, 'calculator' => $calculator, 'beforeDescription' => $beforeDescription, 'afterDescription' => $afterDescription, 'useAltTable' => $useAltTable, 'personForm' => $personForm, 'eventForm' => $eventForm, 'errors' => $errors, 'markupCells' => isset($markupAnalyzer) ? $markupAnalyzer->getMarkupCells() : array(), 'markupRelations' => isset($markupAnalyzer) ? $markupAnalyzer->getMarkupRelations() : array()));
     }
 }
Example #14
0
 /**
  * Record can't be inserted cause its not new
  *
  * @expectedException CDbException
  */
 public function testInsertException1()
 {
     $col2 = new Column();
     $col2->COLUMN_NAME = 'test2';
     $col2->setDataType('varchar');
     $col2->setCollation('utf8_general_ci');
     $col2->size = 250;
     $column = array($col2);
     $table = array('TABLE_SCHEMA' => 'tabletest', 'TABLE_NAME' => 'tabletest3');
     // Load column definition
     $ta = Table::model()->findByPk($table);
     $ta->insert($column);
 }
Example #15
0
File: Row.php Project: cebe/chive
 public function update($attributes = null)
 {
     if ($this->getIsNewRecord()) {
         throw new CDbException(Yii::t('core', 'The active record cannot be updated because it is new.'));
     }
     if (!$this->beforeSave()) {
         return false;
     }
     $sql = '';
     $table = Table::model()->findByPk(array('TABLE_NAME' => self::$table, 'TABLE_SCHEMA' => self::$schema));
     // Check if there has been changed any attribute
     $changedAttributes = array();
     foreach ($this->originalAttributes as $column => $value) {
         if ($this->getAttribute($column) !== $value || $this->getFunction($column)) {
             // SET datatype
             $changedAttributes[$column] = $this->getAttribute($column);
         }
     }
     $changedAttributesCount = count($changedAttributes);
     if ($changedAttributesCount > 0) {
         $sql = 'UPDATE ' . self::$db->quoteTableName(self::$table) . ' SET ' . "\n";
         foreach ($changedAttributes as $column => $value) {
             $columnInfo = $this->getColumnInfo($table, $column);
             $function = $this->getFunction($column);
             $sql .= "\t" . self::$db->quoteColumnName($column) . ' = ';
             if ($function !== null) {
                 $sql .= self::$functions[$function] . '(' . ($value === null ? 'NULL' : self::$db->quoteValue($value)) . ')';
             } elseif ($columnInfo->IS_NULLABLE === "YES" && is_null($value)) {
                 $sql .= 'NULL';
             } elseif ($this->isHex($column)) {
                 $sql .= $value;
             } elseif (is_array($value)) {
                 $sql .= self::$db->quoteValue(implode(",", $value));
             } elseif ($columnInfo->DATA_TYPE == "int") {
                 $sql .= (int) $value;
             } elseif ($columnInfo->DATA_TYPE == "bit") {
                 $sql .= (int) $value;
             } else {
                 $sql .= is_null($value) ? 'NULL' : self::$db->quoteValue($value);
             }
             $changedAttributesCount--;
             if ($changedAttributesCount > 0) {
                 $sql .= ',' . "\n";
             }
         }
         $sql .= "\n" . 'WHERE ' . "\n";
         $identifier = $this->getOriginalIdentifier();
         // Create find criteria
         $count = count($identifier);
         foreach ($identifier as $column => $value) {
             if (is_null($value)) {
                 $sql .= "\t" . self::$db->quoteColumnName($column) . ' IS NULL ';
             } else {
                 $sql .= "\t" . self::$db->quoteColumnName($column) . ' = ' . self::$db->quoteValue($this->originalAttributes[$column]) . ' ';
             }
             $count--;
             if ($count > 0) {
                 $sql .= 'AND ' . "\n";
             }
         }
         $sql .= "\n" . 'LIMIT 1;';
     }
     $cmd = new CDbCommand(self::$db, $sql);
     try {
         $cmd->prepare();
         $cmd->execute();
         $this->afterSave();
         return $sql;
     } catch (CDbException $ex) {
         throw new DbException($cmd);
     }
 }
Example #16
0
 /**
  * Exports all tables of the given array and writes the dump to the output buffer.
  *
  * @param	array					list of tables
  */
 private function exportTables($tables)
 {
     // Get DbConnection object
     $db = Yii::app()->db;
     // Escape all table names
     $tableNames = array();
     foreach ($tables as $table) {
         $tableNames[] = Yii::app()->db->quoteValue($table);
     }
     // Find all tables
     $tables = Table::model()->findAll('TABLE_NAME IN (' . implode(',', $tableNames) . ') ' . 'AND TABLE_SCHEMA = ' . Yii::app()->db->quoteValue($this->schema));
     foreach ($tables as $table) {
         $this->exportTableData($table);
     }
 }
Example #17
0
 /**
  * Loads the current table.
  *
  * @return	Table
  */
 public function loadTable()
 {
     if (is_null($this->_table)) {
         $pk = array('TABLE_SCHEMA' => $this->schema, 'TABLE_NAME' => $this->table);
         $this->_table = Table::model()->findByPk($pk);
         $this->_table->columns = Column::model()->findAllByAttributes($pk);
         if (is_null($this->_table)) {
             throw new CHttpException(500, 'The requested table does not exist.');
         }
     }
     return $this->_table;
 }
Example #18
0
 public function actionSearch()
 {
     $cmdBuilder = new CDbCommandBuilder(Yii::app()->db->getSchema());
     $criteria = new CDbCriteria();
     $criteria->condition = "TABLE_NAME LIKE :table OR TABLE_SCHEMA LIKE :schema";
     $criteria->params = array(":table" => "%" . Yii::app()->getRequest()->getParam('q') . "%", ":schema" => "%" . Yii::app()->getRequest()->getParam('q') . "%");
     $criteria->order = 'TABLE_SCHEMA, TABLE_NAME';
     $items = array();
     $lastSchemaName = '';
     foreach (Table::model()->findAll($criteria) as $table) {
         if ($table->TABLE_SCHEMA != $lastSchemaName) {
             $items[] = CJSON::encode(array('text' => '<span class="icon schema">' . Html::icon('database') . '<span>' . StringUtil::cutText($table->TABLE_SCHEMA, 30) . '</span></span>', 'target' => Yii::app()->createUrl('schema/' . $table->TABLE_SCHEMA), 'plain' => $table->TABLE_SCHEMA));
         }
         $lastSchemaName = $table->TABLE_SCHEMA;
         $items[] = CJSON::encode(array('text' => '<span class="icon table">' . Html::icon('table') . '<span>' . StringUtil::cutText($table->TABLE_NAME, 30) . '</span></span>', 'target' => Yii::app()->createUrl('schema/' . $table->TABLE_SCHEMA) . '#tables/' . $table->TABLE_NAME . '/browse', 'plain' => $table->TABLE_NAME));
     }
     Yii::app()->end(implode("\n", $items));
 }