{@inheritdoc}

@see \Concrete\Core\Updater\Migrations\AbstractMigration::upgradeDatabase()
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();
            }
        }
    }
561387
public function up()
    {
        if (Schema::hasTable('service_type')) {
            $output = new \Symfony\Component\Console\Output\ConsoleOutput();
            $output->writeln('Scanning database for old sql_db service type...');
            $ids = DB::table('service')->where('type', 'sql_db')->pluck('id');
            if (!empty($ids)) {
                $configs = DB::table('sql_db_config')->whereIn('service_id', $ids)->get();
                $output->writeln('|--------------------------------------------------------------------');
                foreach ($configs as $entry) {
                    /** @type array $entry */
                    $entry = (array)$entry;
                    $newType = '';
                    $config = static::adaptConfig($entry, $newType);
                    $config = json_encode($config);
                    $id = array_get($entry, 'service_id');
                    $output->writeln('| Service ID: ' . $id . ' New Config: ' . $config);
                    DB::table('service')->where('id', $id)->update(['type' => $newType]);
                    DB::table('sql_db_config')->where('service_id', $id)->update(['connection' => $config]);
                }
                $output->writeln('|--------------------------------------------------------------------');
            }

            $output->writeln('Scanning database for old script service type...');
            $ids = DB::table('service')->where('type', 'script')->pluck('id');
            if (!empty($ids)) {
                $configs = DB::table('script_config')->whereIn('service_id', $ids)->pluck('type', 'service_id');
                $output->writeln('|--------------------------------------------------------------------');
                foreach ($configs as $id => $driver) {
                    $newType = $driver;
                    $output->writeln('| ID: ' . $id . ' New Type: ' . $newType);
                    DB::table('service')->where('id', $id)->update(['type' => $newType]);
                }
                $output->writeln('|--------------------------------------------------------------------');
            }
        }
    }
962296
public function upgradeDatabase()
    {
        $this->refreshEntities([
            ThumbnailTypeEntity::class,
            ThumbnailTypeFileSet::class,
        ]);

        $type = Type::getByHandle('file_manager_detail');
        if ($type) {
            /*
             * Fix issue where file manager detail thumbnails were being added without a height.
             *
             * @var \Concrete\Core\Entity\File\Image\Thumbnail\Type\Type $type
             */
            if (!$type->getHeight()) {
                $type->setHeight($type->getWidth());
                $em = $this->connection->getEntityManager();
                $em->persist($type);
                $em->flush();
            }
        }
    }
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;
    }
1260800
public function upgradeDatabase()
    {
        $all_tables = $this->connection->executeQuery('SHOW TABLES LIKE "%ExpressSearchIndexAttributes"')->fetchAll();
        $all_tables = array_map(function ($row) {
            return array_values($row)[0];
        }, $all_tables);

        $entity_tables = [];

        $entities = \Core::make('express')->getEntities(true)->findAll();
        foreach ($entities as $entity) {
            /* @var $entity \Concrete\Core\Entity\Express\Entity */
            $entity_tables[] = $entity->getAttributeKeyCategory()->getIndexedSearchTable();
        }

        $drop_tables = array_diff($all_tables, $entity_tables);

        foreach ($drop_tables as $table) {
            $this->connection->exec('DROP TABLE IF EXISTS ' . $table);
        }
    }
209913
public function upgradeDatabase()
    {
        $this->refreshEntities([
            'Concrete\Core\Entity\File\Image\Thumbnail\Type\Type',
        ]);
        $config = \Core::make('config');
        $type = Type::getByHandle($config->get('concrete.icons.file_manager_listing.handle'));
        /* @var \Concrete\Core\Entity\File\Image\Thumbnail\Type\Type $type */
        if ($type) {
            $type->setSizingMode($type::RESIZE_EXACT);
            $type->save();
        }
        $type = Type::getByHandle($config->get('concrete.icons.file_manager_detail.handle'));
        /* @var \Concrete\Core\Entity\File\Image\Thumbnail\Type\Type $type */
        if ($type) {
            $type->setSizingMode($type::RESIZE_EXACT);
            $type->save();
        }
    }
779033
public function upgradeDatabase()
    {
        $config = $this->app->make('config');
        $resolver = $this->app->make(Resolver::class);
        $error = null;
        try {
            list($characterSet, $collation) = $resolver
                ->setCharacterSet((string) $config->get('database.preferred_character_set'))
                ->setCollation((string) $config->get('database.preferred_collation'))
                ->resolveCharacterSetAndCollation($this->connection)
            ;
        } catch (CharacterSetCollationException $x) {
            try {
                list($characterSet, $collation) = $resolver
                    ->setCharacterSet((string) $config->get('database.fallback_character_set'))
                    ->setCollation((string) $config->get('database.fallback_collation'))
                    ->resolveCharacterSetAndCollation($this->connection)
                ;
            } catch (Exception $x) {
                $error = $x;
            }
        } catch (Throwable $x) {
            $error = $x;
        }
        if ($error !== null) {
            $this->output(t('Failed to resolve the database character set and collation: %s', $error->getMessage()));

            return;
        }
        $params = $this->connection->getParams();
        if (isset($params['character_set']) && $params['character_set'] === $characterSet && isset($params['collation']) && $params['collation'] === $collation) {
            return;
        }
        $manager = $this->app->make(Manager::class);
        try {
            $manager->apply(
                $characterSet,
                $collation,
                '',
                '',
                function ($message) {
                    $this->output($message);
                }
            );
        } catch (Exception $x) {
            $this->output(t('Failed to set character sets: %s', $x->getMessage()));
        } catch (Throwable $x) {
            $this->output(t('Failed to set character sets: %s', $x->getMessage()));
        }
    }
914610
public static function upgrade() {
		$sql = self::$sql;

		$sql::$logger->deactivate();
		try {
			$version = $sql->query(
				"SELECT version FROM meta LIMIT 1")['version'];
		} catch(SQLError $e) {
			$sql::$logger->activate();
			return self::upgrade_tables();
		}
		$sql::$logger->activate();

		if (0 <= version_compare($version, self::TABLE_VERSION))
			return self::$logger->debug(
				"Zapmin: Tables are up-to-date.");

		return self::upgrade_tables($version);
	}
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');
    }
963148
public function migrate()
    {
        // find migrations
        $folders = $this->app->pathfinder->search('dbupdates', '', 'path');
        // todo - sort files in folders
        foreach ($folders as $dir) {
            $files = scandir($dir);
            sort($files);
            foreach ($files as $name) {
                if (strtolower(substr($name, -4)) != '.sql') {
                    continue;
                }
                $q = $this->db->dsql()
                    ->table('_db_update')
                    ->where('name', strtolower($name))
                    ->field('status');
                if ($q->getOne() === 'ok') {
                    continue;
                }
                $migration = file_get_contents($dir.'/'.$name);
                $q->set('name', strtolower($name));
                try {
                    $this->db->dbh->exec($migration);
                    $q->set('status', 'ok')->replace();
                } catch (Exception $e) {
                    $q->set('status', 'fail')->replace();
                    if (!$e instanceof BaseException) {
                        $e = $this->exception()
                            ->addMoreInfo('Original error', $e->getMessage());
                    }
                    throw $e->addMoreInfo('file', $name);
                }
            }
        }

        return $this;
    }
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']);
    }
1166513
protected function prepareDatabase()
    {
        $this->migrator->setConnection($this->option('database'));

        if (!$this->migrator->repositoryExists()) {
            $this->call(
                'migrate:install', ['--database' => $this->option('database')]
            );
        }
    }
125028
public function update($object)
    {
        $id = $object->getId();

        $db = new DatabaseManager();
        $connection = $db->getDbh();

        $objectAsArrayForSqlInsert = DatatbaseUtility::objectToArrayLessId($object);
        $fields = array_keys($objectAsArrayForSqlInsert);
        $updateFieldList = DatatbaseUtility::fieldListToUpdateString($fields);

        $sql = 'UPDATE :table SET :updateFieldList WHERE id=:id';
        $sql = str_replace(':table', $this->tableName, $sql);
        $sql = str_replace(':updateFieldList', $updateFieldList, $sql);

        $statement = $connection->prepare($sql);

        // add 'id' to parameters array
        $objectAsArrayForSqlInsert['id'] = $id;

        $queryWasSuccessful = $statement->execute($objectAsArrayForSqlInsert);

        return $queryWasSuccessful;
    }
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);
        }
    }
702590
def db_upgrade(version=None):
    """"""
    v1 = get_db_version()
    migrate_api.upgrade(url=db_url, repository=db_repo, version=version)
    v2 = get_db_version()

    if v1 == v2:
        print 'Database already up-to-date.'
    else:
        print 'Upgraded: %s ... %s' % (v1, v2)
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);
        }
    }
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;
            }
        }
    }