Updates the database if necessary

@author Benjamin Butschell <bb@webprofil.at>
@return array
344415
public function updateDatabase()
    {
        $storageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('MASK\\Mask\\Domain\\Repository\\StorageRepository');
        $json = $storageRepository->load();
        $sqlStatements = $this->getSqlByConfiguration($json);
        if (count($sqlStatements) > 0) {
            $response = $this->performDbUpdates($sqlStatements);
        }
        return $response;
    }
52511
public function upgradeDatabase()
    {
        \Concrete\Core\Database\Schema\Schema::refreshCoreXMLSchema([
            'ConversationPermissionAddMessageAccessList',
            'ConversationSubscriptions',
            'Conversations',
        ]);

        // Subscribe admin to conversations by default, if we have no subscriptions
        $users = \Conversation::getDefaultSubscribedUsers();
        if (count($users) == 0) {
            $admin = \UserInfo::getByID(USER_SUPER_ID);
            if (is_object($admin)) {
                $users = [$admin];
                \Conversation::setDefaultSubscribedUsers($users);
            }
        }

        $db = \Database::get();
        $db->Execute('DROP TABLE IF EXISTS PageStatistics');

        $this->refreshBlockType('page_list');

        $this->refreshBlockType('page_title');

        $this->refreshBlockType('form');

        $c = \Page::getByPath('/dashboard/system/seo/urls');
        if (is_object($c) && !$c->isError()) {
            $c->update(['cName' => 'URLs and Redirection']);
        }

        $this->createSinglePage('/dashboard/system/environment/entities', 'Database Entities', ['meta_keywords' => 'database, entities, doctrine, orm']);

        $pkx = Category::getByHandle('multilingual_section');
        if (!is_object($pkx)) {
            $pkx = Category::add('multilingual_section');
        }
        $pkx->associateAccessEntityType(Type::getByHandle('group'));
        $pkx->associateAccessEntityType(Type::getByHandle('user'));
        $pkx->associateAccessEntityType(Type::getByHandle('group_combination'));

        $db->Execute('alter table QueueMessages modify column body longtext not null');

        $this->updatePermissionDurationObjects();

        $key = Key::getByHandle('add_conversation_message');
        if (is_object($key) && !$key->permissionKeyHasCustomClass()) {
            $key->setPermissionKeyHasCustomClass(true);
        }

        $this->installMaintenanceModePermission();

        $db = \Database::get();
        if ($this->updateSectionPlurals) {
            $rs = $db->Execute('select cID, msLanguage, msCountry from MultilingualSections');
            while ($row = $rs->FetchRow()) {
                $locale = $row['msLanguage'];
                if ($row['msCountry']) {
                    $locale .= '_' . $row['msCountry'];
                }
                $localeInfo = \Gettext\Languages\Language::getById($locale);
                if ($localeInfo) {
                    $pluralCases = [];
                    foreach ($localeInfo->categories as $category) {
                        $pluralCases[] = $category->id . '@' . $category->examples;
                    }
                    $db->update(
                        'MultilingualSections',
                        [
                            'msNumPlurals' => count($localeInfo->categories),
                            'msPluralRule' => $localeInfo->formula,
                            'msPluralCases' => implode("\n", $pluralCases),
                        ],
                        ['cID' => $row['cID']]
                        );
                }
            }
        }
        if ($this->updateMultilingualTranslations) {
            $db->Execute("UPDATE MultilingualTranslations SET comments = REPLACE(comments, ':', '\\n') WHERE comments IS NOT NULL");
        }
    }
749615
public function updateTable()
	{
		//get the instance of the FileInfo class
		$file_info = FileInfo::Create($this->table_file_path);

		//this file already exists
		if($file_info->isFile())
		{
			//load the clas into momeory
			include $file_info->getPathname();

			$class_name = substr($file_info->getFilename(), 0,-4);

			//get the database table class
			$table_object = new $class_name();

			//get the table columns, create SQL and execute
			$this->getColumns($table_object)->updateSQL()->executeUpdate();

			//echo "{$this->query_string}";exit(0);

		}

		//this file has not been created yet
		else
		{


		}

	}
933092
public function getAllForInsertUpdate()
    {
        $data = [];
        foreach ($this->_values as $key => $value) {
            if ($key === '_id' || $key === '_rev') {
                continue;
            }

            if ($key === '_key' && $value === null) {
                // key value not yet set
                continue;
            }
            $data[$key] = $value;
        }
        if ($this->_key !== null) {
            $data['_key'] = $this->_key;
        }

        return $data;
    }
1085405
function update() {
		$db=$this->db;
		$now=microtime(TRUE);
		$data=&$db->read($this->file);
		if (isset($this->trigger['beforeupdate']) &&
			\Base::instance()->call($this->trigger['beforeupdate'],
				[$this,['_id'=>$this->id]])===FALSE)
			return $this->document;
		$data[$this->id]=$this->document;
		$db->write($this->file,$data);
		$db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
			$this->file.' [update] '.json_encode($this->document));
		if (isset($this->trigger['afterupdate']))
			\Base::instance()->call($this->trigger['afterupdate'],
				[$this,['_id'=>$this->id]]);
		return $this->document;
	}
287697
public function update() {
        $this->isNewRecord = false;
        if ($this->usesTimestamps()) {
            $this->updateTimestamps();
        }
        $this->invoke(self::BEFORE_UPDATE, [$this]);
        if (!$this->validate()) {
            return false;
        }
        $query = $this->getPrimaryKeyQuery();
        if (empty($query)) {
            $this->setError('pk', 'ERROR PK!');
            return false;
        }
        $data = $this->_getRealFields();
        if (empty($data)) {
            return true;
        }
        $row = $query
            ->update($data);
        if (!empty($row)) {
            $this->setOldAttribute();
        } else {
            $this->setError('data', 'Data is not change!');
        }
        $this->invoke(self::AFTER_UPDATE, [$this]);
        return $row;
    }
484466
protected function getUpdateQueries()
    {
        $schema = new SchemaTool($this->em);

        $metadatas = $this->em->getMetadataFactory()->getAllMetadata();

        // Insure the name of altered tables are quoted according to the platform
        $this->em->getEventManager()->addEventListener(Events::onSchemaAlterTable, $this);

        $sqls = $schema->getUpdateSchemaSql($metadatas, true);

        return $sqls;
    }
721420
public function update($db=''){
		if ( empty($db) ){
			$db = $this->db->current;
		}
		if ( bbn\str::check_name($db) ){

      $this->db->clear_all_cache();

			$change = $this->db->current === $db ? false : $this->db->current;
			if ( $change ){
				$this->db->change($db);
			}
			$schema = $this->db->modelize();
			if ( $change ){
				$this->db->change($change);
			}
      /*
			$projects = [];
			$r1 = $this->db->query("SELECT *
			FROM `{$this->admin_db}`.`{$this->prefix}projects`
			WHERE `db` LIKE '$db'");
			while ( $d1 = $r1->get_row() ){
				$projects[$d1['id']] = $d1;
				$projects[$d1['id']]['forms'] = [];
				$r2 = $this->db->query("
					SELECT id
					FROM `{$this->admin_db}`.`{$this->prefix}forms`
					WHERE `id_project` = ?",
					$d1['id']);
				while ( $d2 = $r2->get_row() ){
					$projects[$d1['id']]['forms'][$d2['id']] = $this->get_form_config();
				}
			}
			*/
			$this->db->insert_ignore($this->admin_db.'.'.$this->prefix.'dbs',[
        'id' => $db,
        'db' => $db,
        'host' => $this->db->host
      ]);
      $tab_history = false;
      if ( bbn\appui\history::$is_used && isset($schema[bbn\appui\history::$htable]) ){
        $tab_history = 1;
      }
      if ( !\is_array($schema) ){

        die(var_dump("THIS IS NOT AN ARRAY", $schema));
      }

			foreach ( $schema as $t => $vars ){
        $col_history = $tab_history;
				if ( isset($vars['fields']) ){
          $tmp = explode(".", $t);
          $db = $tmp[0];
          $table = $tmp[1];
					$this->db->insert_update($this->admin_db.'.'.$this->prefix.'tables',[
						'id' => $t,
						'db' => $db,
						'table' => $table
					]);
          if ( $col_history && !array_key_exists(bbn\appui\history::$hcol, $vars['fields']) ){
            $col_history = false;
          }
          foreach ( $vars['fields'] as $col => $f ){
    				$config = new \stdClass();
						if ( $col_history && ($col !== bbn\appui\history::$hcol) ){
							$config->history = 1;
						}
						if ( !empty($f['extra']) ){
							$config->extra = $f['extra'];
						}
						if ( isset($f['signed']) && $f['signed'] == 1 ){
							$config->signed = 1;
						}
						if ( isset($f['null']) && $f['null'] == '1' ){
							$config->null = 1;
						}
						if ( isset($f['maxlength']) && $f['maxlength'] > 0 ){
							$config->maxlength = (int)$f['maxlength'];
						}
						if ( isset($f['keys']) ){
							$config->keys = [];
							foreach ( $f['keys'] as $key ){
								$config->keys[$key] = $vars['keys'][$key];
							}
						}
						$this->db->insert_update($this->admin_db.'.'.$this->prefix.'columns',[
							'id' => $t.'.'.$col,
							'table' => $t,
							'column' => $col,
							'position' => $f['position'],
							'type' => $f['type'],
							'null' => $f['null'],
              'key' => $f['key'],
              'default' => $f['default'],
							'config' => json_encode($config)
						]);
					}
				}
			}
      foreach ( $schema as $t => $vars ){
        if ( isset($vars['keys']) && \is_array($vars['keys']) ){
          foreach ( $vars['keys'] as $k => $arr ){
            $pos = 1;
            foreach ( $arr['columns'] as $c ){
              $this->db->insert_update($this->admin_db.'.'.$this->prefix.'keys', [
                'id' => $t.'.'.$k,
                'key' => $k,
                'table' => $t,
                'column' => $t.'.'.$c,
                'position' => $pos,
                'ref_column' => \is_null($arr['ref_column']) ? null : $arr['ref_db'].'.'.$arr['ref_table'].'.'.$arr['ref_column'],
                'unique' => $arr['unique']
              ]);
              $pos++;
            }
          }
        }
      }
      /*
			foreach ( $projects as $i => $p ){
				$this->db->insert($this->admin_db.'.'.$this->prefix.'projects',[
					'id' => $i,
					'id_client' => $p['id_client'],
					'db' => $p['db'],
					'name' => $p['name'],
					'config' => $p['config']]);
				foreach ( $p['forms'] as $j => $form ){
					$this->db->insert($this->admin_db.'.'.$this->prefix.'forms',[
						'id' => $j,
						'id_project' => $i
					]);
					foreach ( $form as $field ){
						$this->db->insert_ignore($this->admin_db.'.'.$this->prefix.'fields',[
							'id' => $field['id'],
							'id_form' => $j,
							'column' => $field['column'],
							'title' => $field['title'],
							'position' => $field['position'],
							'configuration' => json_encode($field['configuration'])
						]);
					}
				}
			}
       * 
       */
      $this->db->enable_keys();
		}
	}
890010
private function update()
    {
        $db = new Db();

        //Insert into article table
        $row = $db->query('UPDATE article
                            SET   category = :category,
                                  author = :author,
                                  pubdate = :pubdate,
                                  editdate = :editdate,
                                  tags = :tags,
                                  status = :status,
                                  title = :title,
                                  media = :media,
                                  resume = :resume
                            WHERE id = :id',

                        [':id'=>$this->id,
                         ':category' => $this->category,
                         ':author' => $this->author,
                         ':pubdate' => $this->pubdate,
                         ':editdate' => $this->editdate,
                         ':tags' => $this->tags,
                         ':status' => $this->status,
                         ':title' => $this->title,
                         ':media' => $this->media,
                         ':resume' => $this->resume
                        ]);
        //check update
        if (!$row) {
            return false;
        }

        //Insert into content table
        $row = $db->query('UPDATE articlecontent
                            SET   editdate = :editdate,
                                  content = :content
                            WHERE article = :article',
                            
                        [':article' => $this->id,
                         ':editdate' => $this->editdate,
                         ':content' => $this->content]);
        return $row;

        
        $cols = '';
        $vals = [];
        foreach ($this as $k => $v) {
            if ($k == 'table' || $k == 'where') {
                continue;
            }echo '<br><b>'.$k.': </b>'.$v;
            if ($k !== 'id') {
                $cols .= $k.' = :'.$k.',';
            }
            $vals[':'.$k] = $v;
        }
        
        $cols = substr($cols, 0, -1); //tirando a ultima vírgula

        $where = ' WHERE id = :id ';
        if ($this->where != null) {
            $where .= ' and '.$this->where;
        }

        $db = new Db();
        return $db->query('UPDATE '.$this->table.' SET '.$cols.$where, $vals);
    }
855446
public function getAllUpdates()
	{
		$update =  !empty($_SESSION[$this->_app->name]['update']) ? $_SESSION[$this->_app->name]['update'] : false;

		// Clean em all!
		$this->cleanUpdate();

		return $update;
	}
18816
public function upgradeDatabase()
    {
        $this->connection->Execute('set foreign_key_checks = 0');
        $this->prepareInvalidForeignKeys();
        $this->fixMultilingualPageRelations();
        $this->renameProblematicTables();
        $this->updateDoctrineXmlTables();
        $this->prepareProblematicEntityTables();
        $this->installEntities(['Concrete\Core\Entity\File\File', 'Concrete\Core\Entity\File\Version', 'Concrete\Core\Entity\File\Image\Thumbnail\Type\Type']);
        $this->installOtherEntities();
        $this->installSite();
        $this->importAttributeTypes();
        $this->migrateOldPermissions();
        $this->addPermissions();
        $this->importAttributeKeys();
        $this->deleteInvalidAttributeValuesForeignKeys();
        $this->addDashboard();
        $this->updateFileManager();
        $this->migrateFileManagerPermissions();
        $this->addBlockTypes();
        $this->updateTopics();
        $this->updateWorkflows();
        $this->addTreeNodeTypes();
        $this->installDesktops();
        $this->updateJobs();
        $this->setupSinglePages();
        $this->addNotifications();
        $this->splittedTrackingCode();
        $this->cleanupOldPermissions();
        $this->installLocales();
        $this->fixStacks();
        $this->nullifyInvalidForeignKeys();
        $this->connection->Execute('set foreign_key_checks = 1');
        $this->migrateDrafts();
    }
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);
        }
    }
1059870
function update() {
		$args=[];
		$ctr=0;
		$pairs='';
		$filter='';
		$pkeys=[];
		foreach ($this->fields as $key=>$field)
			if ($field['pkey'])
				$pkeys[$key]=$field['previous'];
		if (isset($this->trigger['beforeupdate']) &&
			\Base::instance()->call($this->trigger['beforeupdate'],
				[$this,$pkeys])===FALSE)
			return $this;
		foreach ($this->fields as $key=>$field)
			if ($field['changed']) {
				$pairs.=($pairs?',':'').$this->db->quotekey($key).'=?';
				$args[++$ctr]=[$field['value'],$field['pdo_type']];
			}
		foreach ($this->fields as $key=>$field)
			if ($field['pkey']) {
				$filter.=($filter?' AND ':' WHERE ').
					$this->db->quotekey($key).'=?';
				$args[++$ctr]=[$field['previous'],$field['pdo_type']];
			}
		if ($pairs) {
			$sql='UPDATE '.$this->table.' SET '.$pairs.$filter;
			$this->db->exec($sql,$args);
		}
		if (isset($this->trigger['afterupdate']))
			\Base::instance()->call($this->trigger['afterupdate'],
				[$this,$pkeys]);
		// reset changed flag after calling afterupdate
		foreach ($this->fields as $key=>&$field) {
				$field['changed']=FALSE;
				$field['initial']=$field['value'];
				unset($field);
			}
		return $this;
	}
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);
        }
    }
648692
public function update_by()
    {
        $args = func_get_args();
        $data = array_pop($args);

        $data = $this->trigger('before_update', $data);

        if ($this->validate($data) !== FALSE)
        {
            $this->_set_where($args);
            $result = $this->_database->set($data)
                               ->update($this->_table);
            $this->trigger('after_update', array($data, $result));

            return $result;
        }
        else
        {
            return FALSE;
        }
    }
1186872
public function save()
    {
        $array = $this->toArrayWithoutEmptyValues();

        $query = $this->createQuery();

        $now = (new \DateTime())->format('Y-m-d H:i:s');

        if ($this->{$this->getTableKey()}) {
            $query->setAction('update');
            $query->where($query->buildAndSet([
                [$this->getTableKey(), "=", $this->id],
            ]));

            foreach ($array as $key => $value) {
                $query->addValue($key, $value);
            }

            // Since it's an update, add updated_at if the model implements it
            if (property_exists($this, 'updated_at')) {
                $query->addValue('updated_at', $now);
                $this->updated_at = $now;
            }
        } else {
            $query->setAction('insert');

            foreach ($array as $key => $value) {
                if ($key !== $this->tableKey) {
                    $query->addValue($key, $value);
                }
            }

            // Since it's an insert, add created_at if the model implements it
            if (property_exists($this, 'created_at')) {
                $query->addValue('created_at', $now);
                $this->created_at = $now;
            }
        }
        $result = $this->database->query($query);
        if ($result && $query->getAction() === 'insert') {
            $this->id = $this->database->getInstance()->lastInsertId();
        }
        return $result ? true : false;
    }
646885
public function update() {
    $task = $this->taskDrush()
      ->stopOnFail()
      // Execute db updates.
      // This must happen before features are imported or configuration is
      // imported. For instance, if you add a dependency on a new extension to
      // an existing configuration file, you must enable that extension via an
      // update hook before attempting to import the configuration.
      // If a db update relies on updated configuration, you should import the
      // necessary configuration file(s) as part of the db update.
      ->drush("updb");

    $result = $task->run();
    if (!$result->wasSuccessful()) {
      throw new BltException("Failed to execute database updates!");
    }

    $this->invokeCommands(['drupal:config:import', 'drupal:toggle:modules']);
  }