public function safeUp()
 {
     MigrationHelper::dropForeignKeyIfExists('market_lineitems', ['variantId']);
     $this->renameColumn('market_lineitems', 'variantId', 'purchasableId');
     $this->addForeignKey('market_lineitems', 'purchasableId', 'elements', 'id', 'SET NULL', 'CASCADE');
     return true;
 }
 public function safeUp()
 {
     $this->addColumnAfter('market_shippingmethods', 'default', ColumnType::Bool, 'enabled');
     MigrationHelper::dropForeignKeyIfExists('market_ordertypes', ['shippingMethodId']);
     $this->dropColumn('market_ordertypes', 'shippingMethodId');
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     Craft::log('Renaming `social_accounts` table to `social_login_accounts`', LogLevel::Info, true);
     MigrationHelper::renameTable('social_accounts', 'social_login_accounts');
     Craft::log('Done renaming `social_accounts` table to `social_login_accounts`', LogLevel::Info, true);
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     Craft::log('Renaming social_accounts `gateway` column by `providerHandle`', LogLevel::Info, true);
     MigrationHelper::renameColumn('social_accounts', 'gateway', 'providerHandle');
     Craft::log('Done renaming social_accounts `gateway` column by `providerHandle`', LogLevel::Info, true);
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     if (!craft()->db->columnExists('elements_i18n', 'slug')) {
         Craft::log('Creating an elements_i18n.slug column.', LogLevel::Info, true);
         $this->addColumnAfter('elements_i18n', 'slug', ColumnType::Varchar, 'locale');
     }
     if (craft()->db->tableExists('entries_i18n')) {
         Craft::log('Copying the slugs from entries_i18n into elements_i18n.', LogLevel::Info, true);
         $rows = craft()->db->createCommand()->select('entryId, locale, slug')->from('entries_i18n')->queryAll();
         foreach ($rows as $row) {
             $this->update('elements_i18n', array('slug' => $row['slug']), array('elementId' => $row['entryId'], 'locale' => $row['locale']));
         }
         Craft::log('Dropping the entries_i18n table.');
         $this->dropTable('entries_i18n');
     }
     if (!craft()->db->columnExists('elements_i18n', 'enabled')) {
         Craft::log('Creating an elements_i18n.enabled column.', LogLevel::Info, true);
         $this->addColumnAfter('elements_i18n', 'enabled', array('column' => ColumnType::Bool, 'default' => true), 'uri');
     }
     MigrationHelper::refresh();
     MigrationHelper::dropIndexIfExists('elements_i18n', array('slug', 'locale'));
     MigrationHelper::dropIndexIfExists('elements_i18n', array('enabled'));
     $this->createIndex('elements_i18n', 'slug,locale');
     $this->createIndex('elements_i18n', 'enabled');
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     // Rename the table to charges
     MigrationHelper::renameTable('charge_stripe', 'charges');
     // Make it an element type
     MigrationHelper::makeElemental('charges', 'Charge');
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     Craft::log('Interchanging social_users and social_accounts table names', LogLevel::Info, true);
     MigrationHelper::renameTable('social_users', 'social_accounts_temp');
     MigrationHelper::renameTable('social_accounts', 'social_users');
     MigrationHelper::renameTable('social_accounts_temp', 'social_accounts');
     Craft::log('Done interchanging social_users and social_accounts table names', LogLevel::Info, true);
     return true;
 }
 public function safeUp()
 {
     MigrationHelper::renameColumn('autoexpire', 'section', 'sectionId');
     MigrationHelper::renameColumn('autoexpire', 'entryType', 'entryTypeId');
     MigrationHelper::renameColumn('autoexpire', 'field', 'fieldHandle');
     MigrationHelper::renameColumn('autoexpire', 'expirationDate', 'dateTemplate');
     // MigrationHelper::renameColumn('autoexpire', 'allowOverwrite', 'allowOverwrite');
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     MigrationHelper::refresh();
     Craft::log('Dropping FK if it exists.', LogLevel::Info, true);
     MigrationHelper::dropForeignKeyIfExists('emailmessages', array('locale'));
     Craft::log('Adding FK to emailmessages table.', LogLevel::Info, true);
     $this->addForeignKey('emailmessages', 'locale', 'locales', 'locale', 'CASCADE', 'CASCADE');
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     Craft::log('Dropping FK if it exists.', LogLevel::Info, true);
     MigrationHelper::dropForeignKeyIfExists('charges', array('id', 'userId'));
     // This throws errors on some installs
     // It's not fully requried, so we'll avoid it for now, and update it in a future version
     //Craft::log('Adding FK to charges table.', LogLevel::Info, true);
     //$this->addForeignKey('charges', 'id', 'elements', 'id', 'CASCADE', 'CASCADE');
     //$this->addForeignKey('charges', 'userId', 'users', 'id', 'SET NULL');
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     // specify columns and AttributeType
     $locale = array('locale' => ColumnType::Char);
     SproutSeoPlugin::log('Dropping `entryId` index on the sproutseo_overrides table...', LogLevel::Info, true);
     MigrationHelper::dropIndexIfExists('sproutseo_overrides', 'entryId');
     SproutSeoPlugin::log('Done dropping `entryId` index on the sproutseo_overrides table.', LogLevel::Info, true);
     $this->_addColumnsAfter($locale, 'entryId');
     // return true and let craft know its done
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     if (craft()->db->columnExists('sections', 'defaultAuthorId')) {
         Craft::log('Dropping foreign key from sections to users table for default author.', LogLevel::Info, true);
         MigrationHelper::dropForeignKeyIfExists('sections', array('defaultAuthorId'));
         Craft::log('Removing defaultAuthorId column from sections table.', LogLevel::Info, true);
         $this->dropColumn('sections', 'defaultAuthorId');
     } else {
         Craft::log('defaultAuthorId does not exist in the sections, table.  All is well.', LogLevel::Info, true);
     }
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     if (!craft()->db->tableExists('tagsets')) {
         // Create the tagsets table
         craft()->db->createCommand()->createTable('tagsets', array('name' => array('maxLength' => 100, 'column' => ColumnType::Varchar, 'null' => false), 'handle' => array('maxLength' => 45, 'column' => ColumnType::Char, 'null' => false), 'fieldLayoutId' => array('column' => ColumnType::Int, 'length' => 10, 'unsigned' => false)));
         $this->createIndex('tagsets', 'name', true);
         $this->createIndex('tagsets', 'handle', true);
         // Create the Default tag group
         $this->insert('tagsets', array('name' => 'Default', 'handle' => 'default'));
         $tagSetId = craft()->db->getLastInsertID();
         // Rename the entrytags table
         MigrationHelper::renameTable('entrytags', 'tags');
         // Convert the tags to elements
         MigrationHelper::makeElemental('tags', 'Tag');
         // Make some tweaks on the tags table
         $this->alterColumn('tags', 'name', array('column' => ColumnType::Varchar, 'null' => false));
         $this->dropColumn('tags', 'count');
         $this->addColumnBefore('tags', 'setId', array('column' => ColumnType::Int, 'null' => false), 'name');
         $this->dropIndex('tags', 'name', true);
         // Place all current tags into the Default group
         $this->update('tags', array('setId' => $tagSetId));
         $this->createIndex('tags', 'setId, name', true);
         $this->addForeignKey('tags', 'setId', 'tagsets', 'id', 'CASCADE', null);
         // Create a new field group
         $this->insert('fieldgroups', array('name' => 'Tags (Auto-created)'));
         $groupId = craft()->db->getLastInsertID();
         // Create a new Tags field
         // Find a unique handle
         for ($i = 0; true; $i++) {
             $handle = 'tags' . ($i != 0 ? "-{$i}" : '');
             $totalFields = craft()->db->createCommand()->from('fields')->where(array('handle' => $handle))->count('id');
             if ($totalFields == 0) {
                 break;
             }
         }
         $this->insert('fields', array('groupId' => $groupId, 'name' => 'Tags', 'handle' => $handle, 'type' => 'Tags', 'settings' => JsonHelper::encode(array('source' => 'tagset:' . $tagSetId))));
         $fieldId = craft()->db->getLastInsertID();
         // Migrate entrytags_enrtries data into relations
         $tagRelations = craft()->db->createCommand()->select('entryId, tagId, dateCreated, dateUpdated, uid')->from('entrytags_entries')->queryAll(false);
         foreach ($tagRelations as &$relation) {
             array_unshift($relation, $fieldId);
         }
         $this->insertAll('relations', array('fieldId', 'parentId', 'childId', 'dateCreated', 'dateUpdated', 'uid'), $tagRelations, false);
         // Update the search indexes
         $this->update('searchindex', array('attribute' => 'field', 'fieldId' => $fieldId), array('attribute' => 'tags'), array(), false);
         // Drop the old entrytags_entries table
         $this->dropTable('entrytags_entries');
     } else {
         Craft::log('Tried to add the `tagsets` table, but it already exists.', LogLevel::Warning);
     }
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     /* -- Rename the column in  the retour_static_redirects column */
     MigrationHelper::renameColumn('retour_static_redirects', 'associatedEntryId', 'associatedElementId');
     /* -- Rename the column in  the retour_redirects column */
     MigrationHelper::renameColumn('retour_redirects', 'associatedEntryId', 'associatedElementId');
     /* -- Drop the old fk */
     MigrationHelper::dropForeignKeyIfExists('retour_redirects', array('associatedElementId'));
     /* -- Add the new foreign key */
     $this->addForeignKey('retour_redirects', 'associatedElementId', 'elements', 'id', 'CASCADE', 'CASCADE');
     // return true and let craft know its done
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     Craft::log('Making tag titles translatable...', LogLevel::Info, true);
     // Select all of the tag names
     $tags = craft()->db->createCommand()->select('id, name')->from('tags')->queryAll();
     foreach ($tags as $tag) {
         $this->update('content', array('title' => $tag['name']), array('elementId' => $tag['id']));
     }
     $this->createIndex('tags', 'groupId');
     MigrationHelper::dropIndexIfExists('tags', array('name', 'groupId'), true);
     MigrationHelper::dropIndexIfExists('tags', array('groupId', 'name'), true);
     $this->dropColumn('tags', 'name');
     Craft::log('Done making tag titles translatable.', LogLevel::Info, true);
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     $overridesTable = 'sproutseo_overrides';
     if (!craft()->db->columnExists($overridesTable, 'locale')) {
         $this->addColumnAfter($overridesTable, 'locale', array('column' => ColumnType::Locale, 'required' => true), 'entryId');
         SproutSeoPlugin::log("Created the column `locale` in `{$overridesTable}`.", LogLevel::Info, true);
     } else {
         SproutSeoPlugin::log("Column `locale` already existed in `{$overridesTable}`.", LogLevel::Info, true);
     }
     MigrationHelper::dropIndexIfExists($overridesTable, 'entryId');
     SproutSeoPlugin::log("Index `entryId` dropped from `{$overridesTable}`.", LogLevel::Info, true);
     craft()->db->createCommand()->createIndex($overridesTable, 'entryId, locale', array('entryId', 'locale'), true);
     SproutSeoPlugin::log("Composite index `localeAndEntryId` created on `{$overridesTable}`.", LogLevel::Info, true);
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     // Entry Versions
     Craft::log('Dropping foreign key for the `creatorId` column on the `entryversions` table.', LogLevel::Info, true);
     MigrationHelper::dropForeignKeyIfExists('entryversions', array('creatorId'));
     Craft::log('Making `creatorId` nullable on the table `entryversions`.', LogLevel::Info, true);
     $this->alterColumn('entryversions', 'creatorId', array('column' => ColumnType::Int, 'null' => true));
     Craft::log('Adding foreign key for the `creatorId` column on the `entryversions` table with a delete set to nullable.', LogLevel::Info, true);
     $this->addForeignKey('entryversions', 'creatorId', 'users', 'id', 'SET NULL');
     // Entry Drafts
     Craft::log('Dropping foreign key for the `creatorId` column on the `entrydrafts` table.', LogLevel::Info, true);
     MigrationHelper::dropForeignKeyIfExists('entrydrafts', array('creatorId'));
     Craft::log('Adding foreign key for the `creatorId` column on the `entrydrafts` table with a cascade delete set', LogLevel::Info, true);
     $this->addForeignKey('entrydrafts', 'creatorId', 'users', 'id', 'CASCADE');
     return true;
 }
 public function safeUp()
 {
     MigrationHelper::dropForeignKeyIfExists('market_orders', ['typeId']);
     MigrationHelper::dropIndexIfExists('market_orders', ['typeId']);
     $this->dropColumn('market_orders', 'typeId');
     // find everything that is not 'order'
     $ids = craft()->db->createCommand()->select('id')->from('market_ordertypes')->where("handle != 'order'")->queryColumn();
     // delete 'em
     $this->delete('market_ordertypes', array('in', 'id', $ids));
     $table = MigrationHelper::getTable('market_ordertypes');
     MigrationHelper::dropAllForeignKeysOnTable($table);
     $this->renameTable('market_ordertypes', 'market_ordersettings');
     $this->addForeignKey('market_ordersettings', 'fieldLayoutId', 'fieldlayouts', 'id', 'SET NULL');
     $orderSettings = craft()->db->createCommand()->select('*')->from('market_ordersettings')->where("handle = 'order'")->queryScalar();
     if (!$orderSettings) {
         craft()->db->createCommand()->insert('market_ordersettings', ['name' => 'Order', 'handle' => 'order', 'fieldLayoutId' => null]);
     }
     return true;
 }
    public function safeUp()
    {
        $all = <<<EOT
select
vv.id as idx,
vv.variantId as variantId,
v.productId as variantProductId,
p.typeId as productTypeId,
ot.handle as optionTypeName,
ov.id as optionValueId,
ov.name as optionValueName,
ov.displayName as optionValueDisplayName
from craft_market_variant_optionvalues vv
\tleft join craft_market_variants v
\t\ton vv.variantId = v.id
\tleft join craft_market_products p
\t\ton v.productId = p.id
\tleft join craft_market_optionvalues ov
\t\ton vv.optionValueId = ov.id
\tleft join craft_market_optiontypes ot
\t\ton ov.optionTypeId = ot.id
EOT;
        $allData = craft()->db->createCommand($all)->queryAll();
        if (!empty($allData)) {
            craft()->db->createCommand()->createTable('market_variantoptionvaluesbackup', ['idx' => ['column' => 'varchar', 'maxLength' => 255], 'variantId' => ['column' => 'varchar', 'maxLength' => 255], 'variantProductId' => ['column' => 'varchar', 'maxLength' => 255], 'productTypeId' => ['column' => 'varchar', 'maxLength' => 255], 'optionTypeName' => ['column' => 'varchar', 'maxLength' => 255], 'optionValueId' => ['column' => 'varchar', 'maxLength' => 255], 'optionValueName' => ['column' => 'varchar', 'maxLength' => 255], 'optionValueDisplayName' => ['column' => 'varchar', 'maxLength' => 255]], null, false);
            foreach ($allData as $row) {
                $this->insert('market_variantoptionvaluesbackup', $row);
            }
        }
        $market_optionvalues = MigrationHelper::getTable('market_optionvalues');
        $market_optiontypes = MigrationHelper::getTable('market_optiontypes');
        $market_product_optiontypes = MigrationHelper::getTable('market_product_optiontypes');
        $market_variant_optionvalues = MigrationHelper::getTable('market_variant_optionvalues');
        MigrationHelper::dropAllForeignKeysOnTable($market_optionvalues);
        MigrationHelper::dropAllForeignKeysOnTable($market_optiontypes);
        MigrationHelper::dropAllForeignKeysOnTable($market_product_optiontypes);
        MigrationHelper::dropAllForeignKeysOnTable($market_variant_optionvalues);
        $this->dropTable('market_optionvalues');
        $this->dropTable('market_optiontypes');
        $this->dropTable('market_product_optiontypes');
        $this->dropTable('market_variant_optionvalues');
        return true;
    }
 public function safeup()
 {
     // The Table you wish to add. 'craft_' prefix will be added automatically.
     $oldTableName = 'sproutseo_templates';
     $newTableName = 'sproutseo_defaults';
     if (!craft()->db->tableExists($newTableName)) {
         SproutSeoPlugin::log("New table `{$newTableName}` doesn't exist.", LogLevel::Info, true);
         if (craft()->db->tableExists($oldTableName)) {
             MigrationHelper::dropIndexIfExists('sproutseo_templates', array('name', 'handle'), true);
             SproutSeoPlugin::log("Old table `{$oldTableName}` does exist.", LogLevel::Info, true);
             SproutSeoPlugin::log("Renaming the `{$oldTableName}` table.", LogLevel::Info, true);
             // Rename table
             $this->renameTable($oldTableName, $newTableName);
             $this->createIndex('sproutseo_defaults', 'name,handle', true);
             SproutSeoPlugin::log("`{$oldTableName}` table has been renamed to `{$newTableName}`.", LogLevel::Info, true);
         }
     }
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     MigrationHelper::refresh();
     $addFkBack = false;
     if (craft()->db->tableExists('tagsets')) {
         // A couple people have had failed updates that resulted in tagsets *and* taggroups tables lying around
         // causing a MySQL error if trying to rename the tagsets table
         // so let's make sure it's gone first.
         if (craft()->db->tableExists('taggroups')) {
             MigrationHelper::dropForeignKeyIfExists('taggroups', array('fieldLayoutId'));
             if (craft()->db->columnExists('tags', 'groupId')) {
                 MigrationHelper::dropForeignKeyIfExists('tags', array('groupId'));
                 MigrationHelper::renameColumn('tags', 'groupId', 'setId');
                 $addFkBack = true;
             }
             $this->dropTable('taggroups');
             // ...and refresh the schema cache
             craft()->db->getSchema()->refresh();
         }
         Craft::log('Renaming the tagsets table to taggroups.', LogLevel::Info, true);
         MigrationHelper::renameTable('tagsets', 'taggroups');
     }
     if (craft()->db->columnExists('tags', 'setId')) {
         Craft::log('Renaming the tags.setId column to groupId.', LogLevel::Info, true);
         MigrationHelper::renameColumn('tags', 'setId', 'groupId');
     }
     if ($addFkBack) {
         $this->addForeignKey('tags', 'groupId', 'taggroups', 'id', null, 'CASCADE');
     }
     Craft::log('Updating the Tags fields\' settings.', LogLevel::Info, true);
     $fields = craft()->db->createCommand()->select('id, settings')->from('fields')->where('type="Tags"')->queryAll();
     foreach ($fields as $field) {
         $settings = JsonHelper::decode($field['settings']);
         if (isset($settings['source']) && strncmp($settings['source'], 'tagset:', 7) === 0) {
             $settings['source'] = 'taggroup:' . substr($settings['source'], 7);
             $this->update('fields', array('settings' => JsonHelper::encode($settings)), array('id' => $field['id']));
         }
     }
     return true;
 }
 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     $relationsTable = $this->dbConnection->schema->getTable('{{relations}}');
     if ($relationsTable) {
         Craft::log('Dropping foreign key for the `childId` column on the `relations` table.', LogLevel::Info, true);
         MigrationHelper::dropForeignKeyIfExists('relations', array('childId'));
         Craft::log('Dropping foreign key for the `parentId` column on the `relations` table.', LogLevel::Info, true);
         MigrationHelper::dropForeignKeyIfExists('relations', array('parentId'));
         Craft::log('Dropping foreign key for the `fieldId` column on the `relations` table.', LogLevel::Info, true);
         MigrationHelper::dropForeignKeyIfExists('relations', array('fieldId'));
         // Make sure there are no orphans before we re-add the FK's.
         $this->_murderOrphans();
         Craft::log('Adding foreign key for the `childId` column on the `relations` table.', LogLevel::Info, true);
         $this->addForeignKey('relations', 'childId', 'elements', 'id', 'CASCADE');
         Craft::log('Adding foreign key for the `parentId` column on the `relations` table.', LogLevel::Info, true);
         $this->addForeignKey('relations', 'parentId', 'elements', 'id', 'CASCADE');
         Craft::log('Adding foreign key for the `fieldId` column on the `relations` table.', LogLevel::Info, true);
         $this->addForeignKey('relations', 'fieldId', 'fields', 'id', 'CASCADE');
     } else {
         Craft::log('Could not find an `relations` table. Wut?', LogLevel::Error);
     }
 }
示例#23
0
$bootstrapPath = rtrim($craftPath, '/') . '/app/bootstrap.php';
if (!file_exists($bootstrapPath)) {
    throw new Exception('Could not locale a Craft bootstrap file. Make sure that `$craftPath` is set correctly.');
}
/** @var $app WebApp */
$app = (require $bootstrapPath);
$database = $app->config->get('database', ConfigFile::Db);
$tablePrefix = $app->config->get('tablePrefix', ConfigFile::Db);
$version = $app->getVersion() . '.' . $app->getBuild();
if ($tablePrefix) {
    throw new Exception('This tool requires Craft to be configured without a DB table prefix.');
}
$run = !empty($_POST['run']);
if ($run) {
    $fks = array();
    $tables = MigrationHelper::getTables();
    foreach ($tables as $tableName => $table) {
        if ($table->fks) {
            foreach ($table->fks as $fk) {
                $fks[] = array($fk->table->name, implode(',', $fk->columns), $fk->refTable, implode(',', $fk->refColumns), $fk->onDelete, $fk->onUpdate, $fk->name);
            }
        }
    }
    $output = JsonHelper::encode($fks);
    if (!file_exists('fks')) {
        mkdir('fks');
    }
    file_put_contents('fkdumps/' . $version . '.json', $output);
}
?>
示例#24
0
 /**
  * Drops the foreign keys from the model's table.
  *
  * @return null
  */
 public function dropForeignKeys()
 {
     $tableName = $this->getTableName();
     // Does the table exist?
     if (craft()->db->tableExists($tableName, true)) {
         $table = MigrationHelper::getTable($tableName);
         MigrationHelper::dropAllForeignKeysOnTable($table);
     }
 }
 public function safeUp()
 {
     MigrationHelper::makeElemental('market_variants', 'Market_Variant', true);
     return true;
 }
 public function safeUp()
 {
     MigrationHelper::dropForeignKeyIfExists('market_orderstatuses', ['orderTypeId']);
     $this->dropColumn('market_orderstatuses', 'orderTypeId');
     return true;
 }
示例#27
0
 /**
  * Saves a Matrix field's settings.
  *
  * @param MatrixSettingsModel $settings The settings model.
  * @param bool                $validate Whether the settings should be validated before being saved.
  *
  * @throws \Exception
  * @return bool Whether the settings saved successfully.
  */
 public function saveSettings(MatrixSettingsModel $settings, $validate = true)
 {
     if (!$validate || $this->validateFieldSettings($settings)) {
         $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
         try {
             $matrixField = $settings->getField();
             // Create the content table first since the block type fields will need it
             $oldContentTable = $this->getContentTableName($matrixField, true);
             $newContentTable = $this->getContentTableName($matrixField);
             // Do we need to create/rename the content table?
             if (!craft()->db->tableExists($newContentTable)) {
                 if ($oldContentTable && craft()->db->tableExists($oldContentTable)) {
                     MigrationHelper::renameTable($oldContentTable, $newContentTable);
                 } else {
                     $this->_createContentTable($newContentTable);
                 }
             }
             // Delete the old block types first, in case there's a handle conflict with one of the new ones
             $oldBlockTypes = $this->getBlockTypesByFieldId($matrixField->id);
             $oldBlockTypesById = array();
             foreach ($oldBlockTypes as $blockType) {
                 $oldBlockTypesById[$blockType->id] = $blockType;
             }
             foreach ($settings->getBlockTypes() as $blockType) {
                 if (!$blockType->isNew()) {
                     unset($oldBlockTypesById[$blockType->id]);
                 }
             }
             foreach ($oldBlockTypesById as $blockType) {
                 $this->deleteBlockType($blockType);
             }
             // Save the new ones
             $sortOrder = 0;
             $originalContentTable = craft()->content->contentTable;
             craft()->content->contentTable = $newContentTable;
             foreach ($settings->getBlockTypes() as $blockType) {
                 $sortOrder++;
                 $blockType->fieldId = $matrixField->id;
                 $blockType->sortOrder = $sortOrder;
                 $this->saveBlockType($blockType, false);
             }
             craft()->content->contentTable = $originalContentTable;
             if ($transaction !== null) {
                 $transaction->commit();
             }
             // Update our cache of this field's block types
             $this->_blockTypesByFieldId[$settings->getField()->id] = $settings->getBlockTypes();
             return true;
         } catch (\Exception $e) {
             if ($transaction !== null) {
                 $transaction->rollback();
             }
             throw $e;
         }
     } else {
         return false;
     }
 }
示例#28
0
        throw new Exception("Table {$tableName} doesn't exist");
    }
    $columns = explode(',', $columns);
    $refColumns = explode(',', $refColumns);
    if (count($columns) > 1 || count($refColumns) > 1) {
        throw new Exception('Foreign keys spanning multiple columns is not supported.');
    }
    $columnName = $columns[0];
    $refColumnName = $refColumns[0];
    $allowNull = $onDelete == 'SET NULL';
    // Find the invalid values for this FK
    $invalidValues = $app->db->createCommand()->selectDistinct("t.{$columnName}")->from("{$tableName} t")->leftJoin("{$refTableName} r", "t.{$columnName} = r.{$refColumnName}")->where(array('and', "t.{$columnName} is not null", "r.{$refColumnName} is null"))->queryColumn();
    if ($run) {
        // Drop the existing FK if it exists
        // Even if it does, we want to recreate it with the proper ON DELETE and ON UPDATE values
        MigrationHelper::dropForeignKeyIfExists($tableName, $columns);
        // Deal with any invalid values
        if ($invalidValues) {
            $condition = array('in', $columnName, $invalidValues);
            if ($allowNull) {
                $app->db->createCommand()->update($tableName, array($columnName => null), $condition, array(), false);
            } else {
                $app->db->createCommand()->delete($tableName, $condition);
            }
        }
        // Add the FK
        $app->db->createCommand()->addForeignKey($tableName, $columnName, $refTableName, $refColumnName, $onDelete, $onUpdate);
    }
    $report[] = array($tableName, $columnName, $refTableName, $refColumnName, $allowNull, $invalidValues);
}
?>
 /**
  * @param SproutForms_FormModel $form
  *
  * @throws \Exception
  * @return bool
  */
 public function saveForm(SproutForms_FormModel $form)
 {
     $formRecord = new SproutForms_FormRecord();
     $isNewForm = true;
     if ($form->id && !$form->saveAsNew) {
         $formRecord = SproutForms_FormRecord::model()->findById($form->id);
         if (!$formRecord) {
             throw new Exception(Craft::t('No form exists with the ID “{id}”', array('id' => $form->id)));
         }
         $oldForm = SproutForms_FormModel::populateModel($formRecord);
         $isNewForm = false;
         $hasLayout = count($form->getFieldLayout()->getFields()) > 0;
         // Add the oldHandle to our model so we can determine if we
         // need to rename the content table
         $form->oldHandle = $formRecord->getOldHandle();
     }
     // Create our new Form Record
     $formRecord->name = $form->name;
     $formRecord->handle = $form->handle;
     $formRecord->titleFormat = $form->titleFormat ? $form->titleFormat : "{dateCreated|date('D, d M Y H:i:s')}";
     $formRecord->displaySectionTitles = $form->displaySectionTitles;
     $formRecord->groupId = $form->groupId;
     $formRecord->redirectUri = $form->redirectUri;
     $formRecord->submitAction = $form->submitAction;
     $formRecord->submitButtonText = $form->submitButtonText;
     $formRecord->notificationEnabled = $form->notificationEnabled;
     $formRecord->notificationRecipients = $form->notificationRecipients;
     $formRecord->notificationSubject = $form->notificationSubject;
     $formRecord->notificationSenderName = $form->notificationSenderName;
     $formRecord->notificationSenderEmail = $form->notificationSenderEmail;
     $formRecord->notificationReplyToEmail = $form->notificationReplyToEmail;
     $formRecord->validate();
     $form->addErrors($formRecord->getErrors());
     if ($form->saveAsNew) {
         $form->name = $formRecord->name;
         $form->handle = $formRecord->handle;
     }
     if (!$form->hasErrors()) {
         $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
         try {
             // Set the field context
             craft()->content->fieldContext = $form->getFieldContext();
             craft()->content->contentTable = $form->getContentTable();
             if ($isNewForm) {
                 $fieldLayout = $form->getFieldLayout();
                 // Save the field layout
                 craft()->fields->saveLayout($fieldLayout);
                 // Assign our new layout id info to our form model and records
                 $form->fieldLayoutId = $fieldLayout->id;
                 $form->setFieldLayout($fieldLayout);
                 $formRecord->fieldLayoutId = $fieldLayout->id;
             } else {
                 // If we have a layout use it, otherwise
                 // since this is an existing form, grab the oldForm layout
                 if ($hasLayout) {
                     // Delete our previous record
                     craft()->fields->deleteLayoutById($oldForm->fieldLayoutId);
                     $fieldLayout = $form->getFieldLayout();
                     // Save the field layout
                     craft()->fields->saveLayout($fieldLayout);
                     // Assign our new layout id info to our
                     // form model and records
                     $form->fieldLayoutId = $fieldLayout->id;
                     $form->setFieldLayout($fieldLayout);
                     $formRecord->fieldLayoutId = $fieldLayout->id;
                 } else {
                     // We don't have a field layout right now
                     $form->fieldLayoutId = NULL;
                 }
             }
             // Create the content table first since the form will need it
             $oldContentTable = $this->getContentTableName($form, true);
             $newContentTable = $this->getContentTableName($form);
             // Do we need to create/rename the content table?
             if (!craft()->db->tableExists($newContentTable)) {
                 if ($oldContentTable && craft()->db->tableExists($oldContentTable)) {
                     MigrationHelper::renameTable($oldContentTable, $newContentTable);
                 } else {
                     $this->_createContentTable($newContentTable);
                 }
             }
             if (craft()->elements->saveElement($form)) {
                 // Create the new fields
                 if ($form->saveAsNew) {
                     // Duplicate the fields in the newContent Table also set the fields in the craft fields table
                     $newFields = array();
                     foreach ($form->getFields() as $key => $value) {
                         $field = new FieldModel();
                         $field->name = $value->name;
                         $field->handle = $value->handle;
                         $field->instructions = $value->instructions;
                         $field->required = $value->required;
                         $field->translatable = (bool) $value->translatable;
                         $field->type = $value->type;
                         if (isset($value->settings)) {
                             $field->settings = $value->settings;
                         }
                         craft()->content->fieldContext = $form->getFieldContext();
                         craft()->content->contentTable = $form->getContentTable();
                         craft()->fields->saveField($field);
                         array_push($newFields, $field);
                         SproutFormsPlugin::log('Saved field as new ' . $field->id);
                     }
                     // Update fieldId on layoutfields table
                     $fieldLayout = $form->getFieldLayout();
                     $fieldLayoutIds = FieldLayoutFieldRecord::model()->findAll("layoutId = {$fieldLayout->id}");
                     foreach ($fieldLayoutIds as $key => $layout) {
                         SproutFormsPlugin::log('Updated field layout  ' . $layout->id);
                         $model = FieldLayoutFieldRecord::model()->findByPk($layout->id);
                         $model->fieldId = $newFields[$key]->id;
                         $model->save();
                     }
                 }
                 // Now that we have an element ID, save it on the other stuff
                 if ($isNewForm) {
                     $formRecord->id = $form->id;
                 }
                 // Save our Form Settings
                 $formRecord->save(false);
                 if ($transaction !== null) {
                     $transaction->commit();
                 }
                 return true;
             }
         } catch (\Exception $e) {
             if ($transaction !== null) {
                 $transaction->rollback();
             }
             throw $e;
         }
     }
 }