RangeVariableDeclaration ::= AbstractSchemaName ["AS"] AliasIdentificationVariable

@return AST\RangeVariableDeclaration

@throws QueryException
555137
public function RangeVariableDeclaration()
    {
        if ($this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS) && $this->lexer->glimpse()['type'] === Lexer::T_SELECT) {
            $this->semanticalError('Subquery is not supported here', $this->lexer->token);
        }

        $abstractSchemaName = $this->AbstractSchemaName();

        $this->validateAbstractSchemaName($abstractSchemaName);

        if ($this->lexer->isNextToken(Lexer::T_AS)) {
            $this->match(Lexer::T_AS);
        }

        $token                       = $this->lexer->lookahead;
        $aliasIdentificationVariable = $this->AliasIdentificationVariable();
        $classMetadata               = $this->em->getClassMetadata($abstractSchemaName);

        // Building queryComponent
        $queryComponent = [
            'metadata'     => $classMetadata,
            'parent'       => null,
            'relation'     => null,
            'map'          => null,
            'nestingLevel' => $this->nestingLevel,
            'token'        => $token,
        ];

        $this->queryComponents[$aliasIdentificationVariable] = $queryComponent;

        return new AST\RangeVariableDeclaration($abstractSchemaName, $aliasIdentificationVariable);
    }
475553
public function getQuery()
    {
        if (count($this->parts['select']) === 0) {
            throw new QueryException('Missing "select" parts to generate query.');
        }

        $sql = 'SELECT ';

        if ($this->distinct) {
            $sql .= 'DISTINCT ';
        }

        $sql .= implode(', ', $this->parts['select']) . ' FROM';

        if (count($this->parts['from']) === 0) {
            throw new QueryException('Missing "from" parts to generate query.');
        }

        $renderedFromBefore = false;

        foreach ($this->parts['from'] as $fromPart) {
            if ($fromPart['type'] === 'FROM') {
                if ($renderedFromBefore === true) {
                    $sql .= ',';
                }

                $sql .= ' ' . $fromPart['table'];
                $renderedFromBefore = true;
            } else {
                $sql .= ' ' . $fromPart['type'] . ' JOIN ' . $fromPart['table'];

                if ($fromPart['condition']) {
                    $sql .= ' ON ' . $fromPart['condition'];
                }
            }
        }

        if (count($this->parts['where']) > 0) {
            $sql .= ' WHERE ' . implode(' AND ', $this->parts['where']);
        }

        if (count($this->parts['groupBy']) > 0) {
            $sql .= ' GROUP BY ' . implode(', ', $this->parts['groupBy']);
        }

        if (count($this->parts['having']) > 0) {
            $sql .= ' HAVING ' . implode(' AND ', $this->parts['having']);
        }

        if (count($this->parts['orderBy']) > 0) {
            $sql .= ' ORDER BY ' . implode(', ', $this->parts['orderBy']);
        }

        if ($this->limit || $this->offset) {
            $sql = $this->connection->getDatabasePlatform()->modifyLimitQuery(
                $sql,
                $this->limit,
                $this->offset
            );
        }

        return $sql;
    }
404611
public function JoinAssociationPathExpression()
    {
        $identVariable = $this->IdentificationVariable();

        if ( ! isset($this->queryComponents[$identVariable])) {
            $this->semanticalError(
                'Identification Variable ' . $identVariable .' used in join path expression but was not defined before.'
            );
        }

        $this->match(Lexer::T_DOT);
        $this->match(Lexer::T_IDENTIFIER);

        $field = $this->lexer->token['value'];

        // Validate association field
        $qComp = $this->queryComponents[$identVariable];
        $class = $qComp['metadata'];

        if ( ! $class->hasAssociation($field)) {
            $this->semanticalError('Class ' . $class->name . ' has no association named ' . $field);
        }

        return new AST\JoinAssociationPathExpression($identVariable, $field);
    }
134041
public function walkRangeVariableDeclaration($rangeVariableDeclaration)
    {
        $class    = $this->em->getClassMetadata($rangeVariableDeclaration->abstractSchemaName);
        $dqlAlias = $rangeVariableDeclaration->aliasIdentificationVariable;

        if ($rangeVariableDeclaration->isRoot) {
            $this->rootAliases[] = $dqlAlias;
        }

        $sql = $this->platform->appendLockHint(
            $this->quoteStrategy->getTableName($class, $this->platform) . ' ' .
            $this->getSQLTableAlias($class->getTableName(), $dqlAlias),
            $this->query->getHint(Query::HINT_LOCK_MODE)
        );

        if ($class->isInheritanceTypeJoined()) {
            $sql .= $this->_generateClassTableInheritanceJoins($class, $dqlAlias);
        }

        return $sql;
    }
817244
StatementDMQL compileCallStatement(RangeVariable[] outerRanges,
                                       boolean isStrictlyProcedure) {

        read();

        if (isIdentifier()) {
            checkValidCatalogName(token.namePrePrefix);

            RoutineSchema routineSchema =
                (RoutineSchema) database.schemaManager.findSchemaObject(
                    token.tokenString,
                    session.getSchemaName(token.namePrefix),
                    SchemaObject.PROCEDURE);

            if (routineSchema != null) {
                read();

                HsqlArrayList list = new HsqlArrayList();

                readThis(Tokens.OPENBRACKET);

                if (token.tokenType == Tokens.CLOSEBRACKET) {
                    read();
                } else {
                    while (true) {
                        Expression e = XreadValueExpression();

                        list.add(e);

                        if (token.tokenType == Tokens.COMMA) {
                            read();
                        } else {
                            readThis(Tokens.CLOSEBRACKET);

                            break;
                        }
                    }
                }

                Expression[] arguments = new Expression[list.size()];

                list.toArray(arguments);

                Routine routine =
                    routineSchema.getSpecificRoutine(arguments.length);
                HsqlList unresolved = null;

                for (int i = 0; i < arguments.length; i++) {
                    Expression e = arguments[i];

                    if (e.isParam()) {
                        e.setAttributesAsColumn(
                            routine.getParameter(i),
                            routine.getParameter(i).isWriteable());
                    } else {
                        int paramMode =
                            routine.getParameter(i).getParameterMode();

                        unresolved =
                            arguments[i].resolveColumnReferences(outerRanges,
                                unresolved);

                        if (paramMode
                                != SchemaObject.ParameterModes.PARAM_IN) {
                            if (e.getType() != OpTypes.VARIABLE) {
                                throw Error.error(ErrorCode.X_42603);
                            }
                        }
                    }
                }

                ExpressionColumn.checkColumnsResolved(unresolved);

                for (int i = 0; i < arguments.length; i++) {
                    arguments[i].resolveTypes(session, null);
                }

                StatementDMQL cs = new StatementProcedure(session, routine,
                    arguments, compileContext);

                return cs;
            }
        }

        if (isStrictlyProcedure) {
            throw Error.error(ErrorCode.X_42501, token.tokenString);
        }

        Expression expression = this.XreadValueExpression();
        HsqlList unresolved = expression.resolveColumnReferences(outerRanges,
            null);

        ExpressionColumn.checkColumnsResolved(unresolved);
        expression.resolveTypes(session, null);

//        expression.paramMode = PARAM_OUT;
        StatementDMQL cs = new StatementProcedure(session, expression,
            compileContext);

        return cs;
    }
427357
public static QueryColumn toQueryColumn(Object o, PageContext pc) throws PageException {
	if (o instanceof QueryColumn) return (QueryColumn) o;
	if (o instanceof String) {
	    o = VariableInterpreter.getVariableAsCollection(pc, (String) o);
	    if (o instanceof QueryColumn) return (QueryColumn) o;
	}

	throw new CasterException(o, "querycolumn");
    }
950891
public function process()
    {
        $operands = $this->getOperands();

        if ($operands->containsNull() === true) {
            return null;
        }

        if ($operands->exclusivelySingle() === false) {
            $msg = "The Equal operator only accepts operands with a single cardinality.";
            throw new OperatorProcessingException($msg, $this, OperatorProcessingException::WRONG_CARDINALITY);
        }

        if ($operands->exclusivelyNumeric() === false) {
            $msg = "The Equal operator only accepts operands with an integer or float baseType";
            throw new OperatorProcessingException($msg, $this, OperatorProcessingException::WRONG_BASETYPE);
        }

        $operand1 = $operands[0];
        $operand2 = $operands[1];
        $expression = $this->getExpression();

        if ($expression->getToleranceMode() === ToleranceMode::EXACT) {
            return new QtiBoolean($operand1->getValue() == $operand2->getValue());
        } else {
            $tolerance = $expression->getTolerance();

            if (gettype($tolerance[0]) === 'string') {
                $strTolerance = $tolerance;
                $tolerance = array();

                // variableRef to handle.
                $state = $this->getState();
                $tolerance0Name = Utils::sanitizeVariableRef($strTolerance[0]);
                $varValue = $state[$tolerance0Name];

                if (is_null($varValue)) {
                    $msg = "The variable with name '${tolerance0Name}' could not be resolved.";
                    throw new OperatorProcessingException($msg, $this, OperatorProcessingException::NONEXISTENT_VARIABLE);
                } elseif (!$varValue instanceof QtiFloat) {
                    $msg = "The variable with name '${tolerance0Name}' is not a float.";
                    throw new OperatorProcessingException($msg, $this, OperatorProcessingException::WRONG_VARIABLE_BASETYPE);
                }

                $tolerance[] = $varValue->getValue();

                if (isset($strTolerance[1]) && gettype($strTolerance[1]) === 'string') {
                    // A second variableRef to handle.
                    $tolerance1Name = Utils::sanitizeVariableRef($strTolerance[1]);

                    if (($varValue = $state[$tolerance1Name]) !== null && $varValue instanceof QtiFloat) {
                        $tolerance[] = $varValue->getValue();
                    }
                }
            }

            if ($expression->getToleranceMode() === ToleranceMode::ABSOLUTE) {

                $t0 = $operand1->getValue() - $tolerance[0];
                $t1 = $operand1->getValue() + ((isset($tolerance[1])) ? $tolerance[1] : $tolerance[0]);

                $moreThanLower = ($expression->doesIncludeLowerBound()) ? $operand2->getValue() >= $t0 : $operand2->getValue() > $t0;
                $lessThanUpper = ($expression->doesIncludeUpperBound()) ? $operand2->getValue() <= $t1 : $operand2->getValue() < $t1;

                return new QtiBoolean($moreThanLower && $lessThanUpper);
            } else {
                // Tolerance mode RELATIVE
                $tolerance = $expression->getTolerance();
                $t0 = $operand1->getValue() * (1 - $tolerance[0] / 100);
                $t1 = $operand1->getValue() * (1 + ((isset($tolerance[1])) ? $tolerance[1] : $tolerance[0]) / 100);

                $moreThanLower = ($expression->doesIncludeLowerBound()) ? $operand2->getValue() >= $t0 : $operand2->getValue() > $t0;
                $lessThanUpper = ($expression->doesIncludeUpperBound()) ? $operand2->getValue() <= $t1 : $operand2->getValue() < $t1;

                return new QtiBoolean($moreThanLower && $lessThanUpper);
            }
        }
    }
945597
protected function queryVars()
    {
        $resultColumns = $this->dataRecord->getDataSingleton()->getSearchFields();
        $columns = [];
        foreach ($resultColumns as $field) {
            $columns[$field->getName()] = '';
        }

        $arr = array_merge(
            $columns,
            [
                'action_doRegistryFilter' => 'Filter',
                'Sort' => '',
                'Dir' => ''
            ]
        );

        foreach ($arr as $key => $val) {
            if (isset($_GET[$key])) {
                $arr[$key] = $_GET[$key];
            }
        }

        return $arr;
    }
381686
StatementDMQL compileMigrateStatement(RangeVariable[] outerRanges) {

        final Expression condition;
        assert token.tokenType == Tokens.MIGRATE;
        read();
        readThis(Tokens.FROM);

        RangeVariable[] rangeVariables = { readSimpleRangeVariable(StatementTypes.MIGRATE_WHERE) };
        Table table     = rangeVariables[0].getTable();

        if (token.tokenType == Tokens.WHERE) {
            read();

            condition = XreadBooleanValueExpression();

            HsqlList unresolved =
                    condition.resolveColumnReferences(outerRanges, null);

            unresolved = Expression.resolveColumnSet(rangeVariables,
                    unresolved, null);

            ExpressionColumn.checkColumnsResolved(unresolved);
            condition.resolveTypes(session, null);

            if (condition.isParam()) {
                condition.dataType = Type.SQL_BOOLEAN;
            }

            if (condition.getDataType() != Type.SQL_BOOLEAN) {
                throw Error.error(ErrorCode.X_42568);
            }
        } else {
            throw Error.error(ErrorCode.X_47000);
        }
        // check WHERE condition
        RangeVariableResolver resolver =
                new RangeVariableResolver(rangeVariables, condition,
                        compileContext);
        resolver.processConditions();

        rangeVariables = resolver.rangeVariables;

        return new StatementDML(session, table, rangeVariables, compileContext);
    }
35749
public function range($range = null)
    {
        if (!func_num_args()) {
            return $this->_start . '-' . ($this->_limit ? $this->_start + $this->_limit : '');
        }
        $values = explode('-', $range);
        $this->_start = (int) $values[0];
        $this->_limit = $values[1] !== '' ? $values[1] - $values[0] : null;
        return $this;
    }
61964
private function getSQLIdentifier(SelectStatement $AST)
    {
        // Find out the SQL alias of the identifier column of the root entity.
        // It may be possible to make this work with multiple root entities but that
        // would probably require issuing multiple queries or doing a UNION SELECT.
        // So for now, it's not supported.

        // Get the root entity and alias from the AST fromClause.
        $from = $AST->fromClause->identificationVariableDeclarations;
        if (count($from) !== 1) {
            throw new \RuntimeException('Cannot count query which selects two FROM components, cannot make distinction');
        }

        $fromRoot       = reset($from);
        $rootAlias      = $fromRoot->rangeVariableDeclaration->aliasIdentificationVariable;
        $rootClass      = $this->queryComponents[$rootAlias]['metadata'];
        $rootIdentifier = $rootClass->identifier;

        // For every identifier, find out the SQL alias by combing through the ResultSetMapping
        $sqlIdentifier = [];
        foreach ($rootIdentifier as $property) {
            if (isset($rootClass->fieldMappings[$property])) {
                foreach (array_keys($this->rsm->fieldMappings, $property) as $alias) {
                    if ($this->rsm->columnOwnerMap[$alias] == $rootAlias) {
                        $sqlIdentifier[$property] = $alias;
                    }
                }
            }

            if (isset($rootClass->associationMappings[$property])) {
                $joinColumn = $rootClass->associationMappings[$property]['joinColumns'][0]['name'];

                foreach (array_keys($this->rsm->metaMappings, $joinColumn) as $alias) {
                    if ($this->rsm->columnOwnerMap[$alias] == $rootAlias) {
                        $sqlIdentifier[$property] = $alias;
                    }
                }
            }
        }

        if (count($sqlIdentifier) === 0) {
            throw new \RuntimeException('The Paginator does not support Queries which only yield ScalarResults.');
        }

        if (count($rootIdentifier) != count($sqlIdentifier)) {
            throw new \RuntimeException(sprintf(
                'Not all identifier properties can be found in the ResultSetMapping: %s',
                implode(', ', array_diff($rootIdentifier, array_keys($sqlIdentifier)))
            ));
        }

        return $sqlIdentifier;
    }
1021845
public function getVariableQName()
	{
		// Use the cached name if there is one.
		if ( ! $this->qname )
		{
			if ( ! property_exists( $this, 'variable' ) ) return null;
			$this->qname = $qname = new QName( $this->variable['originalPrefix'], $this->variable['namespace'], $this->variable['name'] );
		}

		return $this->qname;
	}
752590
public function GetSelect() {
      // Close off any open query elements.
      $this->_EndQuery();
      
      $Sql = (!$this->_Distinct) ? 'select ' : 'select distinct ';

      // Don't escape the field if it is numeric or an asterisk (all columns)
      $Selects = array();
      foreach($this->_Selects as $Key => $Expr) {
         $Field = $Expr['Field'];
         $Function = $Expr['Function'];
         $Alias = $Expr['Alias'];
         $CaseOptions = ArrayValue('CaseOptions', $Expr);
         if ($Field != '*' && !is_numeric($Field))
            $Field = $this->EscapeIdentifier($Field);

         if ($Alias == '' && $Function != '')
            $Alias = $Field;

         // if (in_array(strtolower($Function), array('max', 'min', 'avg', 'sum', 'count')))
         if ($Function != '') {
				if(strpos($Function, '%s') !== FALSE)
					$Field = sprintf($Function, $Field);
				else
					$Field = $Function.'('.$Field.')';
			}

         if ($CaseOptions !== FALSE)
            $Field = 'case ' . $Field . $CaseOptions . ' end';

         if ($Alias != '')
            $Field .= ' as '.$this->QuoteIdentifier($Alias);

         if ($Field != '')
            $Selects[] = $Field;
      }
      $Sql .= (count($Selects) == 0) ? '*' : implode(', ', $Selects);

      if (count($this->_Froms) > 0)
         $Sql .= "\nfrom ".$this->_FromTables($this->_Froms);

      if (count($this->_Joins) > 0) {
         $Sql .= "\n";
         $Sql .= implode("\n", $this->_Joins);
      }

      if (count($this->_Wheres) > 0)
         $Sql .= "\nwhere ";

      $Sql .= implode("\n", $this->_Wheres);

      // Close any where groups that were left open.
      for ($i = 0; $i < $this->_OpenWhereGroupCount; ++$i) {
         $Sql .= ')';
      }
      $this->_OpenWhereGroupCount = 0;

      if (count($this->_GroupBys) > 0) {
         $Sql .= "\ngroup by ";

         // special consideration for table aliases
         if (count($this->_AliasMap) > 0 && $this->Database->DatabasePrefix)
            $Sql .= implode(', ', $this->_FilterTableAliases($this->_GroupBys));
         else
            $Sql .= implode(', ', $this->_GroupBys);
      }

      if (count($this->_Havings) > 0)
         $Sql .= "\nhaving ".implode("\n", $this->_Havings);

      if (count($this->_OrderBys) > 0)
         $Sql .= "\norder by ".implode(', ', $this->_OrderBys);

      if (is_numeric($this->_Limit)) {
         $Sql .= "\n";
         $Sql = $this->GetLimit($Sql, $this->_Limit, $this->_Offset);
      }

      return $Sql;
   }
422530
private function generateRangeVariableDeclarationSQL($rangeVariableDeclaration, bool $buildNestedJoins) : string
    {
        $class    = $this->em->getClassMetadata($rangeVariableDeclaration->abstractSchemaName);
        $dqlAlias = $rangeVariableDeclaration->aliasIdentificationVariable;

        if ($rangeVariableDeclaration->isRoot) {
            $this->rootAliases[] = $dqlAlias;
        }

        $tableName  = $class->table->getQuotedQualifiedName($this->platform);
        $tableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);

        $sql = $this->platform->appendLockHint(
            $tableName . ' ' . $tableAlias,
            $this->query->getHint(Query::HINT_LOCK_MODE)
        );

        if ($class->inheritanceType !== InheritanceType::JOINED) {
            return $sql;
        }

        $classTableInheritanceJoins = $this->generateClassTableInheritanceJoins($class, $dqlAlias);

        if (! $buildNestedJoins) {
            return $sql . $classTableInheritanceJoins;
        }

        return $classTableInheritanceJoins === '' ? $sql : '(' . $sql . $classTableInheritanceJoins . ')';
    }
672754
private function processDeferredIdentificationVariables()
    {
        foreach ($this->deferredIdentificationVariables as $deferredItem) {
            $identVariable = $deferredItem['expression'];

            // Check if IdentificationVariable exists in queryComponents
            if ( ! isset($this->queryComponents[$identVariable])) {
                $this->semanticalError(
                    "'$identVariable' is not defined.", $deferredItem['token']
                );
            }

            $qComp = $this->queryComponents[$identVariable];

            // Check if queryComponent points to an AbstractSchemaName or a ResultVariable
            if ( ! isset($qComp['metadata'])) {
                $this->semanticalError(
                    "'$identVariable' does not point to a Class.", $deferredItem['token']
                );
            }

            // Validate if identification variable nesting level is lower or equal than the current one
            if ($qComp['nestingLevel'] > $deferredItem['nestingLevel']) {
                $this->semanticalError(
                    "'$identVariable' is used outside the scope of its declaration.", $deferredItem['token']
                );
            }
        }
    }
1354812
public function query()
    {
        $filters = [];
        $queries = [];

        foreach ($this->identity->getComps() as $comp) {
            if ($comp['value'] === null || (is_array($comp['value']) && empty($comp['value']))) {
                continue;
            }
            if ($comp['operator'] === Consts::WILDCARD) {
                $queries['bool']['must'][][Consts::WILDCARD][$comp['name']] = $comp['value'];
            } else {
                if ($comp['name'] === 'geo_distance') {
                    $filters[$comp['operator']][][$this->getTerm($comp['value'])] = $comp['value'];
                } else {
                    $filters[$comp['operator']][][$this->getTerm($comp['value'])][$comp['name']] = $comp['value'];
                }
            }
        }

        if (empty($queries)) {
            $queries = [
                'match_all' => [],
            ];
        }

        $result = $this->prepareType() + [
            'from'  => $this->offset($this->identity),
            'size'  => $this->limit($this->identity),
            'body'  => [
                'query' => [
                    'filtered' => [
                        'query' => $queries,
                        'filter' => [
                            'bool' => $filters,
                        ],
                    ],
                ],
                'sort' => $this->orderBy(),
            ]
        ];

        $groupBy = $this->groupBy();
        if (count($groupBy) > 0) {
            $result['body']['aggs'] = $groupBy;
            $result['size'] = 0;
        }

        return $result;
    }
421360
public function matchExpr() : QueryExpr
    {
        $expr = new QueryExpr($this->dm);
        $expr->setClassMetadata($this->class);

        return $expr;
    }