Generate appropriate SQL for RangeVariableDeclaration AST node

@param AST\RangeVariableDeclaration $rangeVariableDeclaration
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 . ')';
    }
855853
public function toQuery( $variableSet, $factVariableBinding )
	{
		if ( ! $this->substitutionGroups )
		{
			return null;
		}

		$clauses = array();

		if ( isset( $this->substitutionGroups['qnames'] ) && $this->substitutionGroups['qnames'] )
		foreach ( $this->substitutionGroups['qnames'] as $qname )
		{
			$name = qname( $qname );
			$clauses[] = $this->strict
				? "fn:QName('{$name->namespaceURI}','{$name->localName}') eq (xfi:concept-substitutions(fn:node-name(.)))[1]"
				: "fn:QName('{$name->namespaceURI}','{$name->localName}') = xfi:concept-substitutions(fn:node-name(.))";
		}

		if ( isset( $this->substitutionGroups['qnameExpressions'] ) && $this->substitutionGroups['qnameExpressions'] )
		foreach ( $this->substitutionGroups['qnameExpressions'] as $qnameExpression )
		{
			$clauses[] = $this->strict
				? "{$qnameExpression} eq (xfi:concept-substitutions(fn:node-name(.)))[1]"
				: "{$qnameExpression} = xfi:concept-substitutions(fn:node-name(.))";
		}

		return implode( " or ", $clauses );

	}
923822
protected void printDeadClassConstant(VariableDeclarationFragment fragment) {
    VariableElement var = fragment.getVariableElement();
    Object value = var.getConstantValue();
    assert value != null;
    String declType = getDeclarationType(var);
    declType += (declType.endsWith("*") ? "" : " ");
    String name = nameTable.getVariableShortName(var);
    if (ElementUtil.isPrimitiveConstant(var)) {
      printf("#define %s_%s %s\n", typeName, name, LiteralGenerator.generate(value));
    } else {
      println("FOUNDATION_EXPORT "
          + UnicodeUtils.format("%s%s_%s", declType, typeName, name) + ";");
    }
  }
1312019
StatementDMQL compileTriggerSetStatement(Table table,
            RangeVariable[] rangeVars) {

        read();

        Expression[]   updateExpressions;
        int[]          columnMap;
        OrderedHashSet colNames = new OrderedHashSet();
        HsqlArrayList  exprList = new HsqlArrayList();
        RangeVariable[] targetRangeVars = new RangeVariable[]{
            rangeVars[TriggerDef.NEW_ROW] };

        readSetClauseList(targetRangeVars, colNames, exprList);

        columnMap         = table.getColumnIndexes(colNames);
        updateExpressions = new Expression[exprList.size()];

        exprList.toArray(updateExpressions);
        resolveUpdateExpressions(table, rangeVars, columnMap,
                                 updateExpressions, RangeVariable.emptyArray);

        StatementDMQL cs = new StatementDML(session, table, rangeVars,
                                            columnMap, updateExpressions,
                                            compileContext);

        return cs;
    }
604453
public function toQuery( $variableSet, $factVariableBinding )
	{
		/**
		 * These are the arguments to the xfi:concept-relationships function
	     * #source
		 * #linkrole
		 * #arcrole
		 * #axis
		 * #generations
		 * #linkname
		 * #arcname
		 */

		$source = $this->variable
					? ( "fn:node-name(" . ( $this->variable['originalPrefix'] ? "\${$this->variable['originalPrefix']}:$this->variable['name']" : "\${$this->variable['name']}" ) . ")" )
					: ( $this->qnameExpression
							? $this->qnameExpression
							: "QName('" . qname($this->qname, $variableSet->nsMgr->getNamespaces())->namespaceURI . "', '" . qname($this->qname, $variableSet->nsMgr->getNamespaces())->localName . "')"
					  );

		$linkrole = $this->linkrole
					? "'{$this->linkrole}'"
					: ( $this->linkroleExpression
							? $this->linkroleExpression
							: "()"
					  );

		$arcrole = $this->arcrole
					? "'{$this->arcrole}'"
					: ( $this->arcroleExpression
							? $this->arcroleExpression
							: "()"
					  );

		$axis = "{$this->axis}";
		$generations = $this->generations ? $this->generations : "()";

		$linkname = $this->linkname
					? "'{$this->linkname}'"
					: ( $this->linknameExpression
							? $this->linknameExpression
							: "()"
					  );

		$arcname = $this->arcname
					? "'{$this->arcname}'"
					: ( $this->arcnameExpression
							? $this->arcnameExpression
							: "()"
					  );

		$test = $this->test
					? $this->test
					: "true()";

		// Alternative line end goes here (for query formatting)
		$le = "";

		$query = "( $le" .
				 "	( $le" .
				 "		some \$relationship in $le" .
				 "			xfi:concept-relationships( $le" .
				 "				$source, $le" .
				 "				$linkrole, $le" .
				 "				$arcrole, $le" .
				 "				" . str_replace( "-or-self", "", "'$axis'" ) . ",$le" .
		//		 "				fn:replace($axis,'-or-self',''), $le" .
				 "				$generations, $le" .
				 "				$linkname, $le" .
				 "				$arcname $le" .
				 "			) $le" .
				 "		satisfies $le" .
				 "			( $le" .
				 "				\$relationship[$test] and $le" .
				 "				(fn:node-name(.) eq $le" .
             	 "					( $le" .
             	 "						if (matches('$axis','ancestor|parent')) $le" .
              	 "						then xfi:relationship-from-concept(\$relationship) $le" .
              	 "						else xfi:relationship-to-concept(\$relationship) $le" .
              	 "					) $le" .
              	 "				) $le" .
              	 "			) $le" .
              	 "  ) $le";

		$clause1 = "" .
				 "	or $le" .
				 "	( $le" .
		//		 "		fn:starts-with($axis,'sibling') and $le" .
				 "		fn:empty( $le" .
				 "			xfi:concept-relationships( $source, $linkrole, $arcrole, 'parent', 1, $linkname, $arcname) $le" .
				 "		) and $le" .
				 "		fn:empty( $le" .
				 "			xfi:concept-relationships( fn:node-name(.), $linkrole, $arcrole, 'parent', 1, $linkname, $arcname) $le" .
				 "		) and $le" .
				 "		fn:exists( $le" .
				 "			xfi:concept-relationships( fn:node-name(.), $linkrole, $arcrole, 'child', 1, $linkname, $arcname) $le" .
				 "		) and $le" .
				 "		(fn:node-name(.) ne $source) $le" .
				 "	) $le";

		$clause2 = "" .
				 "	or $le" .
				 "	( $le" .
		//		 "		fn:ends-with($axis,'-or-self') $le" .
		//		 " 		and $le" .
		//		 "		( $le" .
				 "			if ( QName('http://www.xbrl.org/2008/function/instance','root') eq $source) $le" .
				 "			then $le" .
				 "			( $le" .
				 "				fn:empty( $le" .
				 "					xfi:concept-relationships( fn:node-name(.), $linkrole, $arcrole, 'parent', 1, $linkname, $arcname) $le" .
				 "				) and $le" .
				 "				fn:exists( $le" .
				 "					xfi:concept-relationships( fn:node-name(.), $linkrole, $arcrole, 'child', 1, $linkname, $arcname) $le" .
				 "				) $le" .
				 "			) $le" .
				 "			else $le" .
				 "			( $le" .
				 "				fn:node-name(.) eq $source $le" .
				 "			) $le" .
		//		 "		) $le" .
				 "  ) $le";

		$query = $query . ( \XBRL::startsWith( $axis, 'sibling' ) ? $clause1 : "" ) . ( \XBRL::endsWith( $axis, '-or-self' ) ? $clause2 : "" );
		$query .= ") $le";
		if ( empty( $le ) )
		{
			$query = preg_replace( "/\s\t+/", " ", $query );
		}
		echo $query;
		return $query;
	}
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);
    }
986132
private void setVariableRange(int start, int end) {
        if (start > end || start < 0 || end > 0xFFFF) {
            throw new IllegalIcuArgumentException("Invalid variable range " + start + ", " + end);
        }

        curData.variablesBase = (char) start; // first private use

        if (dataVector.size() == 0) {
            variableNext = (char) start;
            variableLimit = (char) (end + 1);
        }
    }
841773
public function walkSelectStatementWithRowNumber(SelectStatement $AST)
    {
        $hasOrderBy = false;
        $outerOrderBy = ' ORDER BY dctrn_minrownum ASC';
        $orderGroupBy = '';
        if ($AST->orderByClause instanceof OrderByClause) {
            $hasOrderBy = true;
            $this->rebuildOrderByForRowNumber($AST);
        }

        $innerSql = $this->getInnerSQL($AST);

        $sqlIdentifier = $this->getSQLIdentifier($AST);

        if ($hasOrderBy) {
            $orderGroupBy = ' GROUP BY ' . implode(', ', $sqlIdentifier);
            $sqlIdentifier[] = 'MIN(' . $this->walkResultVariable('dctrn_rownum') . ') AS dctrn_minrownum';
        }

        // Build the counter query
        $sql = sprintf(
            'SELECT DISTINCT %s FROM (%s) dctrn_result',
            implode(', ', $sqlIdentifier),
            $innerSql
        );

        if ($hasOrderBy) {
            $sql .= $orderGroupBy . $outerOrderBy;
        }

        // Apply the limit and offset.
        $sql = $this->platform->modifyLimitQuery(
            $sql,
            $this->maxResults,
            $this->firstResult
        );

        // Add the columns to the ResultSetMapping. It's not really nice but
        // it works. Preferably I'd clear the RSM or simply create a new one
        // but that is not possible from inside the output walker, so we dirty
        // up the one we have.
        foreach ($sqlIdentifier as $property => $alias) {
            $this->rsm->addScalarResult($alias, $property);
        }

        return $sql;
    }
101398
public function toQuery( $variableSet, $factVariableBinding )
	{
		// return "(true())";

		$clauses = array();

		$dimensionClause = "";
		if ( $this->dimension )
		{
			// $qname = qname( $this->dimension );
			$dimensionClause = "fn:QName('{$this->dimension['namespace']}','{$this->dimension['name']}')";
		}
		else if ( $this->dimensionExpression )
		{
			$dimensionClause = $this->dimensionExpression;
		}
		else
		{
			return "false()";
		}

		if ( $this->test )
		{
			return "( xfi:fact-has-typed-dimension(.,$dimensionClause) and xfi:fact-typed-dimension-value(.,$dimensionClause)[{$this->test}] )";
		}
		else
		{
			return "xfi:fact-has-typed-dimension(.,$dimensionClause)";
		}
	}
826585
public function toQuery( $variableSet, $factVariableBinding )
	{
		$clauses = array();

		// Include the qnames if being called as part of a boolean filter or there are qname expressions
		if ( $this->inBoolean || $this->qnameExpressions )
		foreach ( $this->qnames as $clark )
		{
			$qname = qname( $clark );
			$clauses[] = "(fn:node-name(.) eq fn:QName('{$qname->namespaceURI}','{$qname->localName}'))";
		}

		foreach ( $this->qnameExpressions as $qnameExpression )
		{
			$clauses[] = "(fn:node-name(.) eq $qnameExpression)";
		}

		if ( ! $clauses )
		{
			return null;
		}

		$query = implode( " or ", $clauses );
		return count( $clauses ) > 1 ? "($query)" : $query;
	}
590792
private function findConstants($withDefined = false)
    {
        $constants        = array();
        $expressionSolver = new NodeExpressionResolver($this);

        // constants can be only top-level nodes in the namespace, so we can scan them directly
        foreach ($this->namespaceNode->stmts as $namespaceLevelNode) {
            if ($namespaceLevelNode instanceof Const_) {
                $nodeConstants = $namespaceLevelNode->consts;
                if (!empty($nodeConstants)) {
                    foreach ($nodeConstants as $nodeConstant) {
                        $expressionSolver->process($nodeConstant->value);
                        $constants[$nodeConstant->name->toString()] = $expressionSolver->getValue();
                    }
                }
            }
        }

        if ($withDefined) {
            foreach ($this->namespaceNode->stmts as $namespaceLevelNode) {
                if ($namespaceLevelNode instanceof Expression
                    && $namespaceLevelNode->expr instanceof FuncCall
                    && $namespaceLevelNode->expr->name instanceof Name
                    && (string)$namespaceLevelNode->expr->name === 'define'
                ) {
                    $functionCallNode = $namespaceLevelNode->expr;
                    $expressionSolver->process($functionCallNode->args[0]->value);
                    $constantName = $expressionSolver->getValue();

                    // Ignore constants, for which name can't be determined.
                    if (strlen($constantName)) {
                        $expressionSolver->process($functionCallNode->args[1]->value);
                        $constantValue = $expressionSolver->getValue();

                        $constants[$constantName] = $constantValue;
                    }
                }
            }
        }

        return $constants;
    }
1324074
public static function computeCondition($strField, $strOperator, $varValue, $strTable = null)
    {
        $strOperator  = trim(strtolower($strOperator));
        $arrValues    = [];
        $strPattern   = '?';
        $blnAddQuotes = false;

        if ($strTable)
        {
            \Controller::loadDataContainer($strTable);

            $arrDca = &$GLOBALS['TL_DCA'][$strTable]['fields'][$strField];

            if (isset($arrDca['sql']) && stripos($arrDca['sql'], 'blob') !== false)
            {
                $blnAddQuotes = true;
            }
        }

        switch ($strOperator)
        {
            case static::OPERATOR_UNLIKE:
                $arrValues[] = '%' . ($blnAddQuotes ? '"' . $varValue . '"' : $varValue) . '%';
                break;
            case static::OPERATOR_EQUAL:
                $arrValues[] = $varValue;
                break;
            case static::OPERATOR_UNEQUAL:
            case '<>':
                $arrValues[] = $varValue;
                break;
            case static::OPERATOR_LOWER:
                $strPattern  = 'CAST(? AS DECIMAL)';
                $arrValues[] = $varValue;
                break;
            case static::OPERATOR_GREATER:
                $strPattern  = 'CAST(? AS DECIMAL)';
                $arrValues[] = $varValue;
                break;
            case static::OPERATOR_LOWER_EQUAL:
                $strPattern  = 'CAST(? AS DECIMAL)';
                $arrValues[] = $varValue;
                break;
            case static::OPERATOR_GREATER_EQUAL:
                $strPattern  = 'CAST(? AS DECIMAL)';
                $arrValues[] = $varValue;
                break;
            case static::OPERATOR_IN:
                $strPattern = '(' . implode(
                        ',',
                        array_map(
                            function ($value)
                            {
                                return '\'' . $value . '\'';
                            },
                            explode(',', $varValue)
                        )
                    ) . ')';
                break;
            case static::OPERATOR_NOT_IN:
                $strPattern = '(' . implode(
                        ',',
                        array_map(
                            function ($value)
                            {
                                return '\'' . $value . '\'';
                            },
                            explode(',', $varValue)
                        )
                    ) . ')';
                break;
            default:
                $arrValues[] = '%' . ($blnAddQuotes ? '"' . $varValue . '"' : $varValue) . '%';
                break;
        }

        $strOperator = static::transformVerboseOperator($strOperator);

        return ["$strField $strOperator $strPattern", $arrValues];
    }
502780
public function writeVariableValue(Variable $variable, $valueType = self::RW_VALUE)
    {
        switch ($valueType) {
            case self::RW_DEFAULTVALUE:
                $getterToCall = 'getDefaultValue';
                break;
                
            case self::RW_CORRECTRESPONSE:
                $getterToCall = 'getCorrectResponse';
                break;
                
            default:
                $getterToCall = 'getValue';
        }
        
        try {
            $value = call_user_func(array($variable, $getterToCall));
            $cardinality = $variable->getCardinality();
            $baseType = $variable->getBaseType();

            if (is_null($value) === true) {
                $this->writeBoolean(true);

                return;
            }

            // Non-null value.
            $this->writeBoolean(false);

            if ($cardinality === Cardinality::RECORD) {
                // is-scalar
                $this->writeBoolean(false);

                // count
                $this->writeShort(count($value));

                // content
                foreach ($value as $k => $v) {
                    $this->writeRecordField(array($k, $v), is_null($v));
                }
            } else {
                $toCall = 'write' . ucfirst(BaseType::getNameByConstant($baseType));

                if ($cardinality === Cardinality::SINGLE) {
                    // is-scalar
                    $this->writeBoolean(true);

                    // content
                    $this->$toCall(($value instanceof QtiScalar) ? $value->getValue() : $value);
                } else {
                    // is-scalar
                    $this->writeBoolean(false);

                    // count
                    $this->writeShort(count($value));

                    // MULTIPLE or ORDERED
                    foreach ($value as $v) {
                        if (is_null($v) === false) {
                            $this->writeBoolean(false);
                            $this->$toCall(($v instanceof QtiScalar) ? $v->getValue() : $v);
                        } else {
                            $this->writeBoolean(true);
                        }
                    }
                }
            }
        } catch (BinaryStreamAccessException $e) {
            $msg = "An error occured while writing a Variable value.";
            throw new QtiBinaryStreamAccessException($msg, $this, QtiBinaryStreamAccessException::VARIABLE, $e);
        }
    }
148784
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        if ($platform->getName() === 'mysql') {
            /** @var MySqlPlatform $platform */
            return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration)
                // . " CHARACTER SET utf8"
                . " " . $platform->getColumnCollationDeclarationSQL('utf8_bin')
                . " COMMENT '(DC2Type:binary_string)'"
                ;
        }

        return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration);
    }
579788
public function resolveVariableToNode($var)
    {
        $n = $var;
        // When a use is passed, start outside the closure to not return immediately
        // Use variable vs variable parsing?
        if ($var instanceof Node\UseVariableName) {
            $n = $var->getFirstAncestor(Node\Expression\AnonymousFunctionCreationExpression::class)->parent;
            $name = $var->getName();
        } else if ($var instanceof Node\Expression\Variable || $var instanceof Node\Parameter) {
            $name = $var->getName();
        } else {
            throw new \InvalidArgumentException('$var must be Variable, Param or ClosureUse, not ' . get_class($var));
        }
        if (empty($name)) {
            return null;
        }

        $shouldDescend = function ($nodeToDescand) {
            // Make sure not to decend into functions or classes (they represent a scope boundary)
            return !($nodeToDescand instanceof PhpParser\FunctionLike || $nodeToDescand instanceof PhpParser\ClassLike);
        };

        // Traverse the AST up
        do {
            // If a function is met, check the parameters and use statements
            if ($n instanceof PhpParser\FunctionLike) {
                if ($n->parameters !== null) {
                    foreach ($n->parameters->getElements() as $param) {
                        if ($param->getName() === $name) {
                            return $param;
                        }
                    }
                }
                // If it is a closure, also check use statements
                if ($n instanceof Node\Expression\AnonymousFunctionCreationExpression &&
                    $n->anonymousFunctionUseClause !== null &&
                    $n->anonymousFunctionUseClause->useVariableNameList !== null) {
                    foreach ($n->anonymousFunctionUseClause->useVariableNameList->getElements() as $use) {
                        if ($use->getName() === $name) {
                            return $use;
                        }
                    }
                }
                break;
            }

            // Check each previous sibling node and their descendents for a variable assignment to that variable
            // Each previous sibling could contain a declaration of the variable
            while (($prevSibling = $n->getPreviousSibling()) !== null && $n = $prevSibling) {

                // Check the sibling itself
                if (self::isVariableDeclaration($n, $name)) {
                    return $n;
                }

                // Check descendant of this sibling (e.g. the children of a previous if block)
                foreach ($n->getDescendantNodes($shouldDescend) as $descendant) {
                    if (self::isVariableDeclaration($descendant, $name)) {
                        return $descendant;
                    }
                }
            }
        } while (isset($n) && $n = $n->parent);
        // Return null if nothing was found
        return null;
    }
1276119
function checkForSemicolonForVariableDeclaration(node) {
				var ancestors = context.getAncestors(),
					parentIndex = ancestors.length - 1,
					parent = ancestors[parentIndex];

				if ((parent.type !== "ForStatement" || parent.init !== node) &&
					(!/^For(?:In|Of)Statement/.test(parent.type) || parent.left !== node)
				) {
					checkForSemicolon(node);
				}
			}
744111
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        $options = !array_key_exists('platformOptions', $fieldDeclaration) ?
            array() : $fieldDeclaration['platformOptions'];
        return $platform->getArrayTypeDeclarationSQL($fieldDeclaration, $options);
    }