Processes TABLE defintion

Takes also care of set alias definition.

@throws QueryBuilderException
335728
private function processTableDefinition()
    {
        // Table setting in scheme always (!) overrides manual set table definition
        if (! empty($this->scheme['table'])) {
            $this->table = $this->scheme['table'];
        }
        
        // Look for table name when there was none set by a scheme
        if (empty($this->table) && ! empty($this->definition['table'])) {
            $this->table = $this->definition['table'];
        }
        
        // Still no table? Time to complain about it with an exception
        if (empty($this->table)) {
            Throw new QueryBuilderException('QueryBuilder needs a table name. Provide tablename by setting "table" element in your query definition or provide a Scheme with a set table element.<br><br><small>Send QueryBuilder definition:</small><pre>' . print_r($this->definition, true) . '</pre>');
        }
        
        // Is our table an array, which means that it is a QueryBuilder definition?
        if (is_array($this->table)) {
            
            // Build this sql string
            $this->table = $this->checkSubquery($this->table);
        }
        
        // Alias setting in scheme always (!) overrides manual set alias definition
        if (! empty($this->scheme['alias'])) {
            $this->alias = $this->scheme['alias'];
        }
        
        // No alias until here but set in definition?
        if (empty($this->alias) && ! empty($this->definition['alias'])) {
            $this->alias = $this->definition['alias'];
        }
    }
415093
protected function processStatements(array $statements, string $prefix = ''): void
    {
        $uses = [];

        foreach ($statements as $statement) {
            if ($statement instanceof Namespace_) {
                $this->processStatements($statement->stmts, (string)$statement->name);

                return;
            }

            if ($statement instanceof Use_) {
                foreach ($statement->uses as $use) {
                    /** @var Identifier $aliasIdentifier */
                    $aliasIdentifier = $use->alias;
                    if (empty($aliasIdentifier->name)) {
                        $parts = $use->name->parts;
                        $alias = (string)end($parts);
                    } else {
                        $alias = $aliasIdentifier->name;
                    }

                    $uses[$alias] = $use->name->toString();
                }
            }

            if ($statement instanceof Class_) {
                $this->processClassStatement($statement, $prefix, $uses);
            }
        }
    }
1201754
private void processPredecessors() throws SQLException
   {
      List<Row> rows = getRows("select * from " + m_schema + "taskpred where proj_id=? and delete_date is null", m_projectID);
      m_reader.processPredecessors(rows);
   }
335721
protected function processQueries()
    {
        if (! \function_exists('dbDelta')) {
            throw WPDatabaseUpdateFunctionsNotFoundException::dbDeltaIsNotExist();   
        }

        $queries = '';

        foreach ($this->getQueries() as $index => $query) {
            $queries .= \trim($query);
        }

        \dbDelta($queries); 
    }
1101404
protected void prepareQuery(Query queryObject) {
		if (isCacheQueries()) {
			queryObject.setCacheable(true);
			if (getQueryCacheRegion() != null) {
				queryObject.setCacheRegion(getQueryCacheRegion());
			}
		}
		if (getFetchSize() > 0) {
			queryObject.setFetchSize(getFetchSize());
		}
		if (getMaxResults() > 0) {
			queryObject.setMaxResults(getMaxResults());
		}

		if (getFirstResult() > 0) {
			queryObject.setFirstResult(getFirstResult());
		}

	}
99305
private function processDataDefinition()
    {
        // Autodetection of method when none is set e.g. SELECT is set
        if ($this->method == 'SELECT') {
            
            // Try to get name of primary field from provided scheme. A scheme always is preferred to qb definitions
            $primary = ! empty($this->scheme['primary']) ? $this->scheme['primary'] : false;
            
            // No primary from scheme? Check for a primary set in definition.
            if ($primary == false && ! empty($this->definition['primary'])) {
                $primary = $this->definition['primary'];
            }
            
            // Set method to UPDATE when primary exists and has a value. Otherwise we INSERT a new record
            $this->method = ($primary !== false && ! empty($this->definition['data'][$primary])) ? 'UPDATE' : 'INSERT';
        }
        
        // Check for allowed querymethods
        $allowed_methods = [
            'UPDATE',
            'INSERT',
            'REPLACE'
        ];
        
        if (! in_array($this->method, $allowed_methods)) {
            Throw new QueryBuilderException('QueryBuilder can only process querymethods of type "update", "insert" or "replace".');
        }
        
        foreach ($this->definition['data'] as $field_name => $value) {
            
            // Field is flagged as serialized?
            if (! empty($this->scheme['serialize'][$field_name])) {
                $value = serialize($value);
            }
            
            // Handle fields flagged as primary
            if (isset($primary) && $field_name == $primary) {
                
                // Different modes need different handlings
                switch ($this->method) {
                    
                    // Ignore field when mode is insert
                    case 'INSERT':
                        continue;
                        break;
                    
                    // Use field as filter on update
                    case 'UPDATE':
                        $this->definition['filter'] = $field_name . ' = :__primary_' . $field_name;
                        $this->definition['params'][':__primary_' . $field_name] = $value;
                        break;
                    
                    // Add field to fieldlist on replace
                    case 'REPLACE':
                    default:
                        $this->definition['fields'][] = $field_name;
                        $this->definition['params'][':' . $field_name] = $value;
                        break;
                }
            } else {
                
                // Simple field and value
                $this->definition['fields'][] = $field_name;
                $this->definition['params'][':' . $field_name] = $value;
            }
        }
    }
345994
public function process(QueryInterface $query)
    {
        if (!$query instanceof ShowQuery || $query->getObject() !== ShowQuery::EXPRESSION_TABLES) {
            return null;
        }

        $tablet = $this->tablet->getTablet();
        $command = new GetSchema($tablet->getAlias());
        /* @var $vtCtldResult GetSchemaResult */
        $vtCtldResult = $this->client->executeCommand($command);

        return new Tables($vtCtldResult);
    }
1049497
public function compileResequenceQuery(QueryBuilder $queryBuilder, ResequenceOrderIndexColumn $query) : \Dms\Core\Persistence\Db\Platform\CompiledQuery
    {
        $platform         = $queryBuilder->getConnection()->getDatabasePlatform();
        $tableName        = $platform->quoteSingleIdentifier($query->getTable()->getName());
        $subSelectTable   = $platform->quoteSingleIdentifier($query->getTable()->getName() . '__inner');
        $orderIndexColumn = $platform->quoteSingleIdentifier($query->getColumn()->getName());

        $subSelect = $queryBuilder->getConnection()->createQueryBuilder();
        $subSelect
                ->from($tableName, $subSelectTable)
                ->select('COUNT(*) AS row_number')
                ->where($queryBuilder->expr()->lte(
                        $subSelectTable . '.' . $orderIndexColumn,
                        $tableName . '.' . $orderIndexColumn
                ));

        if ($query->hasGroupingColumn()) {
            $groupingColumn = $platform->quoteSingleIdentifier($query->getGroupingColumn()->getName());

            $subSelect->andWhere($queryBuilder->expr()->eq(
                    $subSelectTable . '.' . $groupingColumn,
                    $tableName . '.' . $groupingColumn
            ));
        }

        $queryBuilder
                ->update($tableName)
                ->set($orderIndexColumn, '(' . $subSelect->getSQL() . ')');

        if ($query->hasWhereCondition()) {
            $queryBuilder->where(
                    $this->expressionCompiler->compileExpression($queryBuilder, $query->getWhereCondition())
            );
        }

        return new CompiledQuery($queryBuilder->getSQL(), $queryBuilder->getParameters());
    }
636286
public function execute()
        {
            $values = ($this->getQuery() instanceof QueryInterface) ? $this->getQuery()->getValues() : array();
            if (Core::isDebugMode()) {
                if (Core::isDebugLoggingEnabled() && class_exists('\\caspar\\core\\Logging')) {
                    \caspar\core\Logging::log('executing PDO query (' . Core::getSQLCount() . ') - ' . (($this->getQuery() instanceof Criteria) ? $this->getQuery()->getAction() : 'unknown'), 'B2DB');
                }

                $previous_time = Core::getDebugTime();
            }

            $res = $this->statement->execute($values);

            if (!$res) {
                $error = $this->statement->errorInfo();
                if (Core::isDebugMode()) {
                    Core::sqlHit($this, $previous_time);
                }
                throw new Exception($error[2], $this->printSQL());
            }
            if (Core::isDebugLoggingEnabled() && class_exists('\\caspar\\core\\Logging')) {
                \caspar\core\Logging::log('done', 'B2DB');
            }

            if ($this->getQuery() instanceof Query && $this->getQuery()->isInsert()) {
                if (Core::getDriver() == Core::DRIVER_MYSQL) {
                    $this->insert_id = Core::getDBLink()->lastInsertId();
                } elseif (Core::getDriver() == Core::DRIVER_POSTGRES) {
                    $this->insert_id = Core::getDBLink()->lastInsertId(Core::getTablePrefix() . $this->getQuery()->getTable()->getB2DBName() . '_id_seq');
                    if (Core::isDebugLoggingEnabled() && class_exists('\\caspar\\core\\Logging')) {
                        \caspar\core\Logging::log('sequence: ' . Core::getTablePrefix() . $this->getQuery()->getTable()->getB2DBName() . '_id_seq', 'b2db');
                        \caspar\core\Logging::log('id is: ' . $this->insert_id, 'b2db');
                    }
                }
            }

            $return_value = new Resultset($this);

            if (Core::isDebugMode()) {
                Core::sqlHit($this, $previous_time);
            }

            if (!$this->getQuery() || $this->getQuery()->isSelect()) {
                $this->statement->closeCursor();
            }

            return $return_value;
        }
829660
public void configureExecutionQuery(AbstractQuery query) {
    configureQuery(query);
    CompositePermissionCheck permissionCheck = new PermissionCheckBuilder()
        .disjunctive()
        .atomicCheck(PROCESS_INSTANCE, "RES.PROC_INST_ID_", READ)
        .atomicCheck(PROCESS_DEFINITION, "P.KEY_", READ_INSTANCE)
        .build();
    addPermissionCheck(query.getAuthCheck(), permissionCheck);
  }
1231852
private function updateQueryTranslations(Query $query, array $translationsData): void
    {
        $mainLocale = $query->getMainLocale();

        foreach ($query->getAvailableLocales() as $locale) {
            if ($locale === $mainLocale) {
                continue;
            }

            if (!array_key_exists($locale, $translationsData)) {
                throw new RuntimeException(
                    sprintf('Could not find locale "%s" in the given query data', $locale)
                );
            }

            $this->updateQueryTranslation($query, $translationsData[$locale], $locale);
        }
    }
1026663
public function apply(Builder $query, string $tableAlias = null, string $customName = null)
    {
        if ($this->hasBeenApplied()) {
            return;
        }

        $name = $this->buildDbName($tableAlias, $customName);

        $query->orderBy($name, $this->direction);
        $this->setApplied(true);
    }
511899
public <T> T executeQuery(@NotNull ResultSetProcessor<T> processor, @NotNull SqlQuery query) {
        return withCurrentTransaction(query, tx -> {
            logQuery(query);

            try (PreparedStatement ps = tx.getConnection().prepareStatement(query.getSql())) {
                prepareStatementFromQuery(ps, query);

                long startTime = currentTimeMillis();
                try (ResultSet resultSet = ps.executeQuery()) {
                    logQueryExecution(query, currentTimeMillis() - startTime);
                    return processor.process(resultSet);
                }
            }
        });
    }
20321
public QueryBuilder<T, ID> queryBuilder() throws SQLException {
		if (statementBuilder instanceof QueryBuilder) {
			return (QueryBuilder<T, ID>) statementBuilder;
		} else {
			throw new SQLException("Cannot cast " + statementBuilder.getType() + " to QueryBuilder");
		}
	}
818678
public function execute() {
		
		// build the query
		$this->buildQuery();

		// prepare the statement
		$this->Prepared = \Polyfony\Database::handle()->prepare($this->Query);
		
		// marker start (after preparation, otherwise we would not be able to read the query, it wouldn't exist yet!)
		$id_marker = Profiler::setMarker(null, 'database', ['Query'=>$this]);

		// if prepare failed
		if(!$this->Prepared) {
			// throw an exception
			$this->throwExceptionOn('prepare');
		}
		
		// execute the statement
		$this->Success = $this->Prepared->execute($this->Values);
		
		// if execution failed
		if($this->Success === false) {
			// throw an exception
			$this->throwExceptionOn('execute');
		}

		// if a forced type of object has been defined
		$this->Object = $this->Object && $this->Object != 'Record' ? 
			'\Models\\'.$this->Object : 
			'\Models\\'.$this->Table;

		// temporary fix, if we don't have an object class at all
		if($this->Object == '\Models\\') {
			$this->Object = '\Polyfony\\Record';
		}

		// tweak for Microsoft SQL Server and MySQL
		$this->Object = str_replace('"','', $this->Object);
		
		// fetch all results as objects
		$this->Result = $this->Prepared->fetchAll(PDO::FETCH_CLASS, $this->Object);

		// format the result
		$this->formatSelectResult();
		$this->formatUpdateOrDeleteResult();
		$this->formatInsertResult();

		// marker end, release after all manipulation has been done
		Profiler::releaseMarker($id_marker);

		// return whatever result we got
		return $this->Result;
	}
97386
public function init()
    {
        if (!$this->getQuery()) {
            throw new \RuntimeException('Uninitialized QueryBuilder');
        }

        $this->resetIterator();
        $this->setNbResults($this->computeNbResult());

        if (0 == $this->getPage() || 0 == $this->getMaxPerPage() || 0 == $this->getNbResults()) {
            $this->setLastPage(0);
            $this->getQuery()->setFirstResult(0);
            $this->getQuery()->setMaxResults(0);
        } else {
            $offset = ($this->getPage() - 1) * $this->getMaxPerPage();
            $this->setLastPage(ceil($this->getNbResults() / $this->getMaxPerPage()));
            $this->getQuery()->setFirstResult($offset);
            $this->getQuery()->setMaxResults($this->getMaxPerPage());
        }
    }
1241163
protected function process()
    {

        // initialize the URL key and array for the categories
        $urlKey = null;
        $categories = array();

        // query whether or not the URL key column has a value
        if ($this->hasValue(ColumnKeys::URL_KEY)) {
            $urlKey = $this->getValue(ColumnKeys::URL_KEY);
        } else {
            $this->setValue(
                ColumnKeys::URL_KEY,
                $urlKey = $this->convertNameToUrlKey($this->getValue(ColumnKeys::NAME))
            );
        }

        // explode the path into the category names
        if ($categories = $this->explode($this->getValue(ColumnKeys::PATH), '/')) {
            // initialize the category with the actual category's URL key
            $categoryPaths = array($urlKey);
            // prepare the store view code
            $this->prepareStoreViewCode();
            // load ID of the actual store view
            $storeId = $this->getRowStoreId(StoreViewCodes::ADMIN);

            // iterate over the category names and try to load the category therefore
            for ($i = sizeof($categories) - 1; $i > 1; $i--) {
                try {
                    // prepare the expected category name
                    $categoryPath = implode('/', array_slice($categories, 0, $i));
                    // load the existing category and prepend the URL key the array with the category URL keys
                    $existingCategory = $this->getCategoryByPkAndStoreId($this->mapPath($categoryPath), $storeId);
                    // query whether or not an URL key is available or not
                    if (isset($existingCategory[MemberNames::URL_KEY])) {
                        array_unshift($categoryPaths, $existingCategory[MemberNames::URL_KEY]);
                    } else {
                        $this->getSystemLogger()->debug(sprintf('Can\'t find URL key for category %s', $categoryPath));
                    }
                } catch (\Exception $e) {
                    $this->getSystemLogger()->debug(sprintf('Can\'t load parent category %s', $categoryPath));
                }
            }

            // create the header for the URL path
            if (!$this->hasHeader(ColumnKeys::URL_PATH)) {
                $this->addHeader(ColumnKeys::URL_PATH);
            }

            // set the URL path
            $this->setValue(ColumnKeys::URL_PATH, implode('/', $categoryPaths));
        }
    }