public function getSafeDown()
 {
     if (count($this->getMigrations()) == 0) {
         return $this->space . '$this->dropTable("' . $this->_model->tableName() . '");';
     } else {
         $lines = [];
         $deleted = [];
         $fields = $this->getFields();
         $lastMigrationFields = $this->getLastMigration();
         foreach ($lastMigrationFields as $name => $field) {
             if (array_key_exists($name, $fields) === false) {
                 $added[$name] = $field;
             }
         }
         foreach ($fields as $name => $field) {
             if (array_key_exists($name, $lastMigrationFields) === false) {
                 $deleted[$name] = $field;
                 continue;
             }
             if ($field['hash'] == $lastMigrationFields[$name]['hash']) {
                 continue;
             }
             if ($field['sqlType'] != $lastMigrationFields[$name]['sqlType']) {
                 $lines[] = $this->space . '$this->alterColumn("' . $this->_model->tableName() . '", "' . $name . '", "' . $lastMigrationFields[$name]['sqlType'] . '");';
             } elseif ($field['sqlType'] == $lastMigrationFields[$name]['sqlType'] && $fields['length'] != $lastMigrationFields[$name]['length']) {
                 $lines[] = $this->space . '$this->alterColumn("' . $this->_model->tableName() . '", "' . $name . '", "' . $lastMigrationFields[$name]['sqlType'] . '");';
             }
         }
         foreach ($deleted as $name => $field) {
             $lines[] = $this->space . '$this->dropColumn("' . $this->_model->tableName() . '", "' . $name . '");';
         }
         return implode("\n", $lines);
     }
 }
 /**
  * Truncate table
  * @return int
  * @throws \Mindy\Query\Exception
  */
 public function truncate()
 {
     return $this->createCommand()->truncateTable($this->model->tableName())->execute();
 }
Exemple #3
0
 /**
  * @param $model \Mindy\Orm\Model
  */
 public function createIndexes(Model $model)
 {
     $command = $this->db->createCommand();
     try {
         // checkIntegrity is not supported by SQLite
         // $command->checkIntegrity(false)->execute();
     } catch (NotSupportedException $e) {
     }
     foreach ($model->getFields() as $name => $field) {
         if (is_a($field, '\\Mindy\\Orm\\Fields\\ForeignField')) {
             /* @var $modelClass \Mindy\Orm\Model */
             /* @var $field \Mindy\Orm\Fields\ForeignField */
             $modelClass = $field->modelClass;
             $fkModel = new $modelClass();
             $command->addForeignKey("fk_{$name}", $model->tableName(), [$name . '_id'], $modelClass::tableName(), [$fkModel->getPkName()], $delete = $field->getOnDelete(), $update = $field->getOnUpdate());
             $command->execute();
         }
     }
     try {
         // checkIntegrity is not supported by SQLite
         // $command->checkIntegrity(true)->execute();
     } catch (NotSupportedException $e) {
     }
 }