{@inheritdoc}

@see \Concrete\Core\Updater\Migrations\AbstractMigration::upgradeDatabase()
482340
public function upgradeDatabase()
    {
        $config = $this->getConfig();

        // In case public registrations have been enabled with manual approval,
        // the user needs to setup workflows manually to apply the same
        // functionality after the upgrade. It is safer to disable public
        // registrations for as long as it takes to setup the workflows.
        if ($config->get('concrete.user.registration.enabled') &&
            $config->get('concrete.user.registration.approval')
        ) {
            $config->save('concrete.user.registration.enabled', false);
            $config->save('concrete.user.registration.approval', null);
            $config->save('concrete.user.registration.type', 'disabled');
        }
    }
346693
protected function registerDatabaseUpgradeCommand($command)
    {
        $this->app->singleton($command, function ($app) {
            return new Database\Commands\DatabaseUpgradeCommand($app);
        });
    }
702695
public function upgradeDatabase()
    {
        // assign the page owner access entity to the page type category
        $pe = Type::getByHandle('page_owner');
        $category = Category::getByHandle('page_type');
        if (is_object($category) && is_object($pe)) {
            $category->associateAccessEntityType($pe);
        }
    }
623755
public function updateDatabase($verbose)
    {
        $em = $this->getEntityManager();
        $tool = new SchemaTool($em);
        if ($verbose) {
            print_r("Updating database.\n");
        }
        $classes = $this->getEntityMetaData($em);

        // Rebuild the schema
        if ($verbose) {
            print_r("Update existing schema.\nRunning:\n");
            foreach ($tool->getUpdateSchemaSql($classes) as $statement) {
                print_r($statement . "\n");
            }
        }
        $tool->updateSchema($classes, true);

        return "Database updated\n";
    }
1235761
public function to($version) {
        $this->out(sprintf('<success>Upgrading to %s...</success>', $version));

        $schema = sprintf('%s/Config/Schema/Upgrade/%s.sql', CakePlugin::path($this->plugin), $version);

        if (!file_exists($schema)) {
            $this->err(sprintf('<error>Upgrade schema %s does not exist</error>', basename($schema)));
            return false;
        }

        // Trigger any migration changes
        $method = 'to_' . preg_replace('/[^0-9]+/', '', $version);

        if (method_exists($this, $method)) {
            call_user_func(array($this, $method));
        }

        // Execute the schema
        if ($this->executeSchema($schema, false)) {
            $this->complete[] = $version;

            $this->out(sprintf('<success>Upgrade to %s complete</success>', $version));
            $this->versions();
        }

        return true;
    }
801733
public function upgradeDatabase()
    {
        $service = \Core::make('site');
        $site = $service->getDefault();
        $siteConfig = $site->getConfigRepository();
        $url = $siteConfig->get('seo.canonical_ssl_url');
        if ($url) {
            if ($siteConfig->get('seo.canonical_url')) {
                $siteConfig->save('seo.canonical_url_alternative', $url);
            } else {
                $siteConfig->save('seo.canonical_url', $url);
            }
            $siteConfig->save('seo.canonical_ssl_url', null);
        }
    }
893800
public function upgradeDatabase()
    {
        $job = Job::getByHandle('fill_thumbnails_table');
        if ($job === null) {
            Job::installByHandle('fill_thumbnails_table');
            $job = Job::getByHandle('fill_thumbnails_table');
            if ($job !== null) {
                $set = Set::getByName('Default');
                if ($set !== null) {
                    $set->addJob($job);
                }
            }
        }
        $sp = Page::getByPath('/dashboard/system/files/image_uploading');
        if (is_object($sp) && !$sp->isError()) {
            $sp->update([
                'cName' => 'Image Options',
            ]);
            if ($this->isAttributeHandleValid(PageCategory::class, 'meta_keywords')) {
                $sp->setAttribute('meta_keywords', 'uploading, upload, images, image, resizing, manager, exif, rotation, rotate, quality, compression, png, jpg, jpeg');
            }
        }
        $config = $this->app->make('config');
        $restrict_uploaded_image_sizes = $config->get('concrete.file_manager.restrict_uploaded_image_sizes');
        if ($restrict_uploaded_image_sizes !== null) {
            if (!$restrict_uploaded_image_sizes) {
                $config->save('concrete.file_manager.restrict_max_width', null);
                $config->save('concrete.file_manager.restrict_max_height', null);
            }
            $config->set('concrete.file_manager.restrict_uploaded_image_sizes', null);
            $config->save('concrete.file_manager.restrict_uploaded_image_sizes', null);
        }
    }
902075
public function upgradeDatabase()
    {
        $this->refreshEntities([
            Entity::class,
        ]);

        // Get all the entities ALL THE ENTITIES
        $entities = \Core::make('express')->getEntities(true)->findAll();
        foreach ($entities as $entity) {
            /* @var $entity \Concrete\Core\Entity\Express\Entity */
            $category = $entity->getAttributeKeyCategory();
            // Get all the attributes for the entity
            foreach ($entity->getAttributes() as $key) {
                // Refresh the column from the attribute's search index definition if we can
                // (we don't require this method in the interface yet)
                try {
                    $category->getSearchIndexer()->refreshRepositoryColumns($category, $key);
                } catch (\Exception $e) {
                }
            }
            // Get a list of the entities
            $list = new EntryList($entity);
            $entries = $list->getResults();
            foreach ($entries as $entry) {
                // Get the values for the entities
                $values = $category->getAttributeValues($entry);
                foreach ($values as $value) {
                    // Set the values in the search index to the values of the actual attribute
                    $category->getSearchIndexer()->indexEntry($category, $value, $entry);
                }
            }
        }
    }
592718
public function upgradeDatabase()
    {
        Page::getByPath('/dashboard/system/backup')->delete();
        Page::getByPath('/dashboard/system/backup/backup')->delete();
        Page::getByPath('/dashboard/system/backup/update')->delete();

        $this->createSinglePage('/dashboard/system/update', 'Update concrete5');

        $this->createSinglePage('/dashboard/system/update/update', 'Apply Update', ['meta_keywords' => 'upgrade, new version, update']);
    }
466084
protected function getTableMigrationNewDatabase($output, $new, $old)
    {
        if (empty($new['database'])) {
            return $output;
        }
        if ($this->neq($new, $old, ['database', 'default_character_set_name'])) {
            $output[] = $this->getAlterDatabaseCharset($new['database']['default_character_set_name']);
        }
        if ($this->neq($new, $old, ['database', 'default_collation_name'])) {
            $output[] = $this->getAlterDatabaseCollate($new['database']['default_collation_name']);
        }

        return $output;
    }
71287
public function update($table)
    {
        $query = new Query\UpdateQuery();

        if ($this->pdo) {
            $query->setPDO($this->pdo);
        }

        return $query->table($table);
    }
391438
public function up(Database $db)
    {
        $collection = $db->selectCollection($this->collection);
        $targetCollection = $db->selectCollection('Translation');

        $aggregate = [
            [
                '$match' => [
                    'isLocalized' => true,
                    'locale' => ['$ne' => 'en'],
                    'translated' => ['$ne' => null]
                ]
            ],
            [
                '$group' => [
                    '_id' => ['original' => '$original', 'locale' => '$locale'],
                    'translated' => ['$addToSet' => '$translated'],
                    'count' => ['$sum' => 1]
                ]
            ]
        ];

        foreach ($collection->aggregate($aggregate, ['cursor' => true]) as $translatable) {
            $original = $translatable['_id']['original'];
            $language = $translatable['_id']['locale'];
            $translation = $translatable['translated'][0];

            $rec = [
                'original' => $original,
                'language' => $language,
                'localized' => $translation
            ];

            try {
                $targetCollection->insert($rec);
            } catch (\Exception $e) {
                echo "Skipping already existing translation of original '${original}'".PHP_EOL;
            }
        }
    }
222642
private boolean upgradeDatabase(String name, String dbPath, boolean close) {
        Log.v(Log.TAG_DATABASE, "CouchbaseLite: Upgrading database (%s) at %s ...", name, dbPath);

        // if db with name already exists, not need to migrate. Simply remove old database
        Database db = getDatabase(name, false);
        if (!db.exists() && !name.equals("_replicator")) {

            // temporary database name for new db schema
            String tempName = name + ".tmp";

            // Create and open new CBLDatabase with temporary name:
            Database tmpDB = getDatabase(tempName, false);
            if (tmpDB == null) {
                Log.w(Log.TAG_DATABASE,
                        "Upgrade failed: Creating new db failed: %s", tempName);
                return false;
            }

            // upgradeDatabase() is called only if dbPath (old db version) exists. So presence of
            // temporary db indicates that previous upgrade crashed midway.
            if (tmpDB.exists()) {
                Log.v(Log.TAG_DATABASE, "Previous upgrade probably crashed midway. dbPath: " + dbPath);

                // rollback from temporary database to old database
                // NOTE: Deleting temporary db is not enough because `DatabaseUpgrade.importData()`
                //       move attachment files instead of copy files.
                DatabaseUpgrade upgrader = new DatabaseUpgrade(this, tmpDB, dbPath);
                upgrader.backOut();

                // temporary db is deleted by previous operation, reopen the temporary db.
                tmpDB = getDatabase(tempName, false);
                if (tmpDB == null) {
                    Log.w(Log.TAG_DATABASE, "Upgrade failed: Creating new db failed: %s", tempName);
                    return false;
                }
            }

            if (tmpDB.exists()) {
                // the temporary db should not exist. Just double check
                Log.w(Log.TAG_DATABASE,
                        "Upgrade failed: Failed to delete already existing db: %s", tempName);
                return false;
            }

            // Upgrade the old database into the new one:
            DatabaseUpgrade upgrader = new DatabaseUpgrade(this, tmpDB, dbPath);
            if (!upgrader.importData()) {
                upgrader.backOut();
                return false;
            }

            // close temporary database
            tmpDB.close();

            // rename temporary database name to new name
            File tmpPath = new File(pathForDatabaseNamed(tempName));
            File newPath = new File(pathForDatabaseNamed(name));
            if (!tmpPath.renameTo(newPath)) {
                Log.w(Log.TAG_DATABASE,
                        "Upgrade failed: Failed to rename db folder from temporary name: %s -> %s",
                        tmpPath, newPath);
                upgrader = new DatabaseUpgrade(this, getDatabase(tempName, false), dbPath);
                upgrader.backOut();
                return false;
            }

            // reopen db with name
            db = getDatabase(name, false);
            if (!db.exists()) {
                Log.w(Log.TAG_DATABASE,
                        "Upgrade failed: Failed to open the database after migrate: %s", name);
                return false;
            }
        }

        // close db if necessary
        if (close)
            db.close();

        // Remove old database file and its SQLite side files:
        moveSQLiteDbFiles(dbPath, null);

        if (dbPath.endsWith(kV1DBExtension)) {
            String oldAttachmentsName = FileDirUtils.getDatabaseNameFromPath(dbPath) + " attachments";
            File oldAttachmentsDir = new File(directoryFile, oldAttachmentsName);
            if (oldAttachmentsDir.exists())
                FileDirUtils.deleteRecursive(oldAttachmentsDir);
        }

        Log.v(Log.TAG_DATABASE, "    ...success!");
        return true;
    }
545044
public function upgradeDatabase()
    {
        // Find all files that have no FileVersions as these are invalid and are left over from a bug
        $query = 'SELECT F.fID FROM Files F WHERE F.fID NOT IN (SELECT FV.fID FROM FileVersions FV)';
        $orphan_files = $this->connection->executeQuery($query);
        while ($fID = $orphan_files->fetchColumn()) {
            $f = File::getByID($fID);
            if ($f !== null) {
                $f->delete();
            }
        }
    }
773973
protected function renameDatabaseTableField($table, $oldFieldName, $newFieldName)
    {
        $title = 'Renaming "' . $table . ':' . $oldFieldName . '" to "' . $table . ':' . $newFieldName . '": ';

        $currentTableFields = $this->databaseConnection->admin_get_fields($table);

        if ($currentTableFields[$newFieldName]) {
            $message = 'Field ' . $table . ':' . $newFieldName . ' already existing.';
            $status = FlashMessage::OK;
        } else {
            if (!$currentTableFields[$oldFieldName]) {
                $message = 'Field ' . $table . ':' . $oldFieldName . ' not existing';
                $status = FlashMessage::ERROR;
            } else {
                $sql = 'ALTER TABLE ' . $table . ' CHANGE COLUMN ' . $oldFieldName . ' ' . $newFieldName . ' ' .
                    $currentTableFields[$oldFieldName]['Type'];

                if ($this->databaseConnection->admin_query($sql) === false) {
                    $message = ' SQL ERROR: ' . $this->databaseConnection->sql_error();
                    $status = FlashMessage::ERROR;
                } else {
                    $message = 'OK!';
                    $status = FlashMessage::OK;
                }
            }
        }

        $this->addMessage($status, $title, $message);

        return $status;
    }
213913
public function upgradeDatabase()
    {
        if ($this->connection->getSchemaManager()->tablesExist('CalendarEventVersions')) {
            $events = (int) $this->connection->fetchColumn('select count(*) from CalendarEventVersions');
        } else {
            $events = null;
        }
        if ($events === null || $events === 0) {
            $this->migrateCalendar();
        }
    }
1182811
public function upgradeDatabase()
    {
        // image resizing options
        $this->createSinglePage('/dashboard/system/files/image_uploading', 'Image Uploading');

        // background size/position
        \Concrete\Core\Database\Schema\Schema::refreshCoreXMLSchema([
            'StyleCustomizerInlineStyleSets',
        ]);

        $this->refreshBlockType('image_slider');

        $this->refreshBlockType('youtube');

        $this->refreshBlockType('autonav');
    }