From 8703a8e5de729caae5f0dd940e7c1d96efe495ad Mon Sep 17 00:00:00 2001 From: upstream Date: Thu, 3 Sep 2026 13:30:28 +0200 Subject: [PATCH] Upstream doctrine/orm state of the touched files before 64718e1f43 --- src/Query/Parser.php | 3534 +++++++++++++++++ .../ORM/Query/SelectSqlGenerationTest.php | 2208 ++++++++++ 2 files changed, 5742 insertions(+) create mode 100644 src/Query/Parser.php create mode 100644 tests/Tests/ORM/Query/SelectSqlGenerationTest.php diff --git a/src/Query/Parser.php b/src/Query/Parser.php new file mode 100644 index 0000000..e666d1b --- /dev/null +++ b/src/Query/Parser.php @@ -0,0 +1,3534 @@ + + * @phpstan-type QueryComponent = array{ + * metadata?: ClassMetadata, + * parent?: string|null, + * relation?: AssociationMapping|null, + * map?: string|null, + * resultVariable?: AST\Node|string, + * nestingLevel: int, + * token: DqlToken, + * } + */ +final class Parser +{ + /** + * @readonly Maps BUILT-IN string function names to AST class names. + * @var array> + */ + private static array $stringFunctions = [ + 'concat' => Functions\ConcatFunction::class, + 'substring' => Functions\SubstringFunction::class, + 'trim' => Functions\TrimFunction::class, + 'lower' => Functions\LowerFunction::class, + 'upper' => Functions\UpperFunction::class, + 'identity' => Functions\IdentityFunction::class, + ]; + + /** + * @readonly Maps BUILT-IN numeric function names to AST class names. + * @var array> + */ + private static array $numericFunctions = [ + 'length' => Functions\LengthFunction::class, + 'locate' => Functions\LocateFunction::class, + 'abs' => Functions\AbsFunction::class, + 'sqrt' => Functions\SqrtFunction::class, + 'mod' => Functions\ModFunction::class, + 'size' => Functions\SizeFunction::class, + 'date_diff' => Functions\DateDiffFunction::class, + 'bit_and' => Functions\BitAndFunction::class, + 'bit_or' => Functions\BitOrFunction::class, + + // Aggregate functions + 'min' => Functions\MinFunction::class, + 'max' => Functions\MaxFunction::class, + 'avg' => Functions\AvgFunction::class, + 'sum' => Functions\SumFunction::class, + 'count' => Functions\CountFunction::class, + ]; + + /** + * @readonly Maps BUILT-IN datetime function names to AST class names. + * @var array> + */ + private static array $datetimeFunctions = [ + 'current_date' => Functions\CurrentDateFunction::class, + 'current_time' => Functions\CurrentTimeFunction::class, + 'current_timestamp' => Functions\CurrentTimestampFunction::class, + 'date_add' => Functions\DateAddFunction::class, + 'date_sub' => Functions\DateSubFunction::class, + ]; + + /* + * Expressions that were encountered during parsing of identifiers and expressions + * and still need to be validated. + */ + + /** @phpstan-var list */ + private array $deferredIdentificationVariables = []; + + /** @phpstan-var list */ + private array $deferredPartialObjectExpressions = []; + + /** @phpstan-var list */ + private array $deferredPathExpressions = []; + + /** @phpstan-var list */ + private array $deferredResultVariables = []; + + /** @phpstan-var list */ + private array $deferredNewObjectExpressions = []; + + /** + * The lexer. + */ + private readonly Lexer $lexer; + + /** + * The parser result. + */ + private readonly ParserResult $parserResult; + + /** + * The EntityManager. + */ + private readonly EntityManagerInterface $em; + + /** + * Map of declared query components in the parsed query. + * + * @phpstan-var array + */ + private array $queryComponents = []; + + /** + * Keeps the nesting level of defined ResultVariables. + */ + private int $nestingLevel = 0; + + /** + * Keeps the nesting level of subqueries in JOIN WITH conditions. + */ + private int $withJoinConditionNestingLevel = 0; + + /** + * Any additional custom tree walkers that modify the AST. + * + * @var list> + */ + private array $customTreeWalkers = []; + + /** + * The custom last tree walker, if any, that is responsible for producing the output. + * + * @var class-string|null + */ + private $customOutputWalker; + + /** @phpstan-var array */ + private array $identVariableExpressions = []; + + /** + * Creates a new query parser object. + * + * @param Query $query The Query to parse. + */ + public function __construct(private readonly Query $query) + { + $this->em = $query->getEntityManager(); + $this->lexer = new Lexer((string) $query->getDQL()); + $this->parserResult = new ParserResult(); + } + + /** + * Sets a custom tree walker that produces output. + * This tree walker will be run last over the AST, after any other walkers. + * + * @param class-string $className + */ + public function setCustomOutputTreeWalker(string $className): void + { + Deprecation::trigger( + 'doctrine/orm', + 'https://github.com/doctrine/orm/pull/11641', + '%s is deprecated, set the output walker class with the \Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER query hint instead', + __METHOD__, + ); + + $this->customOutputWalker = $className; + } + + /** + * Adds a custom tree walker for modifying the AST. + * + * @param class-string $className + */ + public function addCustomTreeWalker(string $className): void + { + $this->customTreeWalkers[] = $className; + } + + /** + * Gets the lexer used by the parser. + */ + public function getLexer(): Lexer + { + return $this->lexer; + } + + /** + * Gets the ParserResult that is being filled with information during parsing. + */ + public function getParserResult(): ParserResult + { + return $this->parserResult; + } + + /** + * Gets the EntityManager used by the parser. + */ + public function getEntityManager(): EntityManagerInterface + { + return $this->em; + } + + /** + * Parses and builds AST for the given Query. + */ + public function getAST(): AST\SelectStatement|AST\UpdateStatement|AST\DeleteStatement + { + // Parse & build AST + $AST = $this->QueryLanguage(); + + // Process any deferred validations of some nodes in the AST. + // This also allows post-processing of the AST for modification purposes. + $this->processDeferredIdentificationVariables(); + + if ($this->deferredPartialObjectExpressions) { + $this->processDeferredPartialObjectExpressions(); + } + + if ($this->deferredPathExpressions) { + $this->processDeferredPathExpressions(); + } + + if ($this->deferredResultVariables) { + $this->processDeferredResultVariables(); + } + + if ($this->deferredNewObjectExpressions) { + $this->processDeferredNewObjectExpressions($AST); + } + + $this->processRootEntityAliasSelected(); + + // TODO: Is there a way to remove this? It may impact the mixed hydration resultset a lot! + $this->fixIdentificationVariableOrder($AST); + + return $AST; + } + + /** + * Attempts to match the given token with the current lookahead token. + * + * If they match, updates the lookahead token; otherwise raises a syntax + * error. + * + * @throws QueryException If the tokens don't match. + */ + public function match(TokenType $token): void + { + $lookaheadType = $this->lexer->lookahead->type ?? null; + + // Short-circuit on first condition, usually types match + if ($lookaheadType === $token) { + $this->lexer->moveNext(); + + return; + } + + // If parameter is not identifier (1-99) must be exact match + if ($token->value < TokenType::T_IDENTIFIER->value) { + $this->syntaxError($this->lexer->getLiteral($token)); + } + + // If parameter is keyword (200+) must be exact match + if ($token->value > TokenType::T_IDENTIFIER->value) { + $this->syntaxError($this->lexer->getLiteral($token)); + } + + // If parameter is T_IDENTIFIER, then matches T_IDENTIFIER (100) and keywords (200+) + if ($token->value === TokenType::T_IDENTIFIER->value && $lookaheadType->value < TokenType::T_IDENTIFIER->value) { + $this->syntaxError($this->lexer->getLiteral($token)); + } + + $this->lexer->moveNext(); + } + + /** + * Frees this parser, enabling it to be reused. + * + * @param bool $deep Whether to clean peek and reset errors. + * @param int $position Position to reset. + */ + public function free(bool $deep = false, int $position = 0): void + { + // WARNING! Use this method with care. It resets the scanner! + $this->lexer->resetPosition($position); + + // Deep = true cleans peek and also any previously defined errors + if ($deep) { + $this->lexer->resetPeek(); + } + + $this->lexer->token = null; + $this->lexer->lookahead = null; + } + + /** + * Parses a query string. + */ + public function parse(): ParserResult + { + $AST = $this->getAST(); + + $customWalkers = $this->query->getHint(Query::HINT_CUSTOM_TREE_WALKERS); + if ($customWalkers !== false) { + $this->customTreeWalkers = $customWalkers; + } + + $customOutputWalker = $this->query->getHint(Query::HINT_CUSTOM_OUTPUT_WALKER); + if ($customOutputWalker !== false) { + $this->customOutputWalker = $customOutputWalker; + } + + // Run any custom tree walkers over the AST + if ($this->customTreeWalkers) { + $treeWalkerChain = new TreeWalkerChain($this->query, $this->parserResult, $this->queryComponents); + + foreach ($this->customTreeWalkers as $walker) { + $treeWalkerChain->addTreeWalker($walker); + } + + match (true) { + $AST instanceof AST\UpdateStatement => $treeWalkerChain->walkUpdateStatement($AST), + $AST instanceof AST\DeleteStatement => $treeWalkerChain->walkDeleteStatement($AST), + $AST instanceof AST\SelectStatement => $treeWalkerChain->walkSelectStatement($AST), + }; + + $this->queryComponents = $treeWalkerChain->getQueryComponents(); + } + + $outputWalkerClass = $this->customOutputWalker ?: SqlOutputWalker::class; + $outputWalker = new $outputWalkerClass($this->query, $this->parserResult, $this->queryComponents); + + if ($outputWalker instanceof OutputWalker) { + $finalizer = $outputWalker->getFinalizer($AST); + $this->parserResult->setSqlFinalizer($finalizer); + } else { + Deprecation::trigger( + 'doctrine/orm', + 'https://github.com/doctrine/orm/pull/11188/', + 'Your output walker class %s should implement %s in order to provide a %s. This also means the output walker should not use the query firstResult/maxResult values, which should be read from the query by the SqlFinalizer only.', + $outputWalkerClass, + OutputWalker::class, + SqlFinalizer::class, + ); + // @phpstan-ignore method.deprecated + $executor = $outputWalker->getExecutor($AST); + // @phpstan-ignore method.deprecated + $this->parserResult->setSqlExecutor($executor); + } + + return $this->parserResult; + } + + /** + * Fixes order of identification variables. + * + * They have to appear in the select clause in the same order as the + * declarations (from ... x join ... y join ... z ...) appear in the query + * as the hydration process relies on that order for proper operation. + */ + private function fixIdentificationVariableOrder(AST\SelectStatement|AST\DeleteStatement|AST\UpdateStatement $AST): void + { + if (count($this->identVariableExpressions) <= 1) { + return; + } + + assert($AST instanceof AST\SelectStatement); + + foreach ($this->queryComponents as $dqlAlias => $qComp) { + if (! isset($this->identVariableExpressions[$dqlAlias])) { + continue; + } + + $expr = $this->identVariableExpressions[$dqlAlias]; + $key = array_search($expr, $AST->selectClause->selectExpressions, true); + + unset($AST->selectClause->selectExpressions[$key]); + + $AST->selectClause->selectExpressions[] = $expr; + } + } + + /** + * Generates a new syntax error. + * + * @param string $expected Expected string. + * @param DqlToken|null $token Got token. + * + * @throws QueryException + */ + public function syntaxError(string $expected = '', Token|null $token = null): never + { + if ($token === null) { + $token = $this->lexer->lookahead; + } + + $tokenPos = $token->position ?? '-1'; + + $message = sprintf('line 0, col %d: Error: ', $tokenPos); + $message .= $expected !== '' ? sprintf('Expected %s, got ', $expected) : 'Unexpected '; + $message .= $this->lexer->lookahead === null ? 'end of string.' : sprintf("'%s'", $token->value); + + throw QueryException::syntaxError($message, QueryException::dqlError($this->query->getDQL() ?? '')); + } + + /** + * Generates a new semantical error. + * + * @param string $message Optional message. + * @phpstan-param DqlToken|null $token + * + * @throws QueryException + */ + public function semanticalError(string $message = '', Token|null $token = null): never + { + if ($token === null) { + $token = $this->lexer->lookahead ?? new Token('fake token', 42, 0); + } + + // Minimum exposed chars ahead of token + $distance = 12; + + // Find a position of a final word to display in error string + $dql = $this->query->getDQL(); + $length = strlen($dql); + $pos = $token->position + $distance; + $pos = strpos($dql, ' ', $length > $pos ? $pos : $length); + $length = $pos !== false ? $pos - $token->position : $distance; + + $tokenPos = $token->position > 0 ? $token->position : '-1'; + $tokenStr = substr($dql, $token->position, $length); + + // Building informative message + $message = 'line 0, col ' . $tokenPos . " near '" . $tokenStr . "': Error: " . $message; + + throw QueryException::semanticalError($message, QueryException::dqlError($this->query->getDQL())); + } + + /** + * Peeks beyond the matched closing parenthesis and returns the first token after that one. + * + * @param bool $resetPeek Reset peek after finding the closing parenthesis. + * + * @phpstan-return DqlToken|null + */ + private function peekBeyondClosingParenthesis(bool $resetPeek = true): Token|null + { + $token = $this->lexer->peek(); + $numUnmatched = 1; + + while ($numUnmatched > 0 && $token !== null) { + switch ($token->type) { + case TokenType::T_OPEN_PARENTHESIS: + ++$numUnmatched; + break; + + case TokenType::T_CLOSE_PARENTHESIS: + --$numUnmatched; + break; + + default: + // Do nothing + } + + $token = $this->lexer->peek(); + } + + if ($resetPeek) { + $this->lexer->resetPeek(); + } + + return $token; + } + + /** + * Checks if the given token indicates a mathematical operator. + * + * @phpstan-param DqlToken|null $token + */ + private function isMathOperator(Token|null $token): bool + { + return $token !== null && in_array($token->type, [TokenType::T_PLUS, TokenType::T_MINUS, TokenType::T_DIVIDE, TokenType::T_MULTIPLY], true); + } + + /** + * Checks if the next-next (after lookahead) token starts a function. + * + * @return bool TRUE if the next-next tokens start a function, FALSE otherwise. + */ + private function isFunction(): bool + { + assert($this->lexer->lookahead !== null); + $lookaheadType = $this->lexer->lookahead->type; + $peek = $this->lexer->peek(); + + $this->lexer->resetPeek(); + + return $lookaheadType->value >= TokenType::T_IDENTIFIER->value && $peek !== null && $peek->type === TokenType::T_OPEN_PARENTHESIS; + } + + /** + * Checks whether the given token type indicates an aggregate function. + * + * @return bool TRUE if the token type is an aggregate function, FALSE otherwise. + */ + private function isAggregateFunction(TokenType $tokenType): bool + { + return in_array( + $tokenType, + [TokenType::T_AVG, TokenType::T_MIN, TokenType::T_MAX, TokenType::T_SUM, TokenType::T_COUNT], + true, + ); + } + + /** + * Checks whether the current lookahead token of the lexer has the type T_ALL, T_ANY or T_SOME. + */ + private function isNextAllAnySome(): bool + { + assert($this->lexer->lookahead !== null); + + return in_array( + $this->lexer->lookahead->type, + [TokenType::T_ALL, TokenType::T_ANY, TokenType::T_SOME], + true, + ); + } + + /** + * Validates that the given IdentificationVariable is semantically correct. + * It must exist in query components list. + */ + private function processDeferredIdentificationVariables(): void + { + foreach ($this->deferredIdentificationVariables as $deferredItem) { + $identVariable = $deferredItem['expression']; + + // Check if IdentificationVariable exists in queryComponents + if (! isset($this->queryComponents[$identVariable])) { + $this->semanticalError( + sprintf("'%s' is not defined.", $identVariable), + $deferredItem['token'], + ); + } + + $qComp = $this->queryComponents[$identVariable]; + + // Check if queryComponent points to an AbstractSchemaName or a ResultVariable + if (! isset($qComp['metadata'])) { + $this->semanticalError( + sprintf("'%s' does not point to a Class.", $identVariable), + $deferredItem['token'], + ); + } + + // Validate if identification variable nesting level is lower or equal than the current one + if ($qComp['nestingLevel'] > $deferredItem['nestingLevel']) { + $this->semanticalError( + sprintf("'%s' is used outside the scope of its declaration.", $identVariable), + $deferredItem['token'], + ); + } + } + } + + /** + * Validates that the given NewObjectExpression. + */ + private function processDeferredNewObjectExpressions(AST\SelectStatement $AST): void + { + foreach ($this->deferredNewObjectExpressions as $deferredItem) { + $expression = $deferredItem['expression']; + $token = $deferredItem['token']; + $className = $expression->className; + $args = $expression->args; + $fromClassName = $AST->fromClause->identificationVariableDeclarations[0]->rangeVariableDeclaration->abstractSchemaName ?? null; + + // If the namespace is not given then assumes the first FROM entity namespace + if (! str_contains($className, '\\') && ! class_exists($className) && is_string($fromClassName) && str_contains($fromClassName, '\\')) { + $namespace = substr($fromClassName, 0, strrpos($fromClassName, '\\')); + $fqcn = $namespace . '\\' . $className; + + if (class_exists($fqcn)) { + $expression->className = $fqcn; + $className = $fqcn; + } + } + + if (! class_exists($className)) { + $this->semanticalError(sprintf('Class "%s" is not defined.', $className), $token); + } + + $class = new ReflectionClass($className); + + if (! $class->isInstantiable()) { + $this->semanticalError(sprintf('Class "%s" can not be instantiated.', $className), $token); + } + + if ($class->getConstructor() === null) { + $this->semanticalError(sprintf('Class "%s" has not a valid constructor.', $className), $token); + } + + if ($class->getConstructor()->getNumberOfRequiredParameters() > count($args)) { + $this->semanticalError(sprintf('Number of arguments does not match with "%s" constructor declaration.', $className), $token); + } + } + } + + /** + * Validates that the given PartialObjectExpression is semantically correct. + * It must exist in query components list. + */ + private function processDeferredPartialObjectExpressions(): void + { + foreach ($this->deferredPartialObjectExpressions as $deferredItem) { + $expr = $deferredItem['expression']; + $class = $this->getMetadataForDqlAlias($expr->identificationVariable); + + foreach ($expr->partialFieldSet as $field) { + if (isset($class->fieldMappings[$field])) { + continue; + } + + if ( + isset($class->associationMappings[$field]) && + $class->associationMappings[$field]->isToOneOwningSide() + ) { + continue; + } + + $this->semanticalError(sprintf( + "There is no mapped field named '%s' on class %s.", + $field, + $class->name, + ), $deferredItem['token']); + } + + if (array_intersect($class->identifier, $expr->partialFieldSet) !== $class->identifier) { + $this->semanticalError( + 'The partial field selection of class ' . $class->name . ' must contain the identifier.', + $deferredItem['token'], + ); + } + } + } + + /** + * Validates that the given ResultVariable is semantically correct. + * It must exist in query components list. + */ + private function processDeferredResultVariables(): void + { + foreach ($this->deferredResultVariables as $deferredItem) { + $resultVariable = $deferredItem['expression']; + + // Check if ResultVariable exists in queryComponents + if (! isset($this->queryComponents[$resultVariable])) { + $this->semanticalError( + sprintf("'%s' is not defined.", $resultVariable), + $deferredItem['token'], + ); + } + + $qComp = $this->queryComponents[$resultVariable]; + + // Check if queryComponent points to an AbstractSchemaName or a ResultVariable + if (! isset($qComp['resultVariable'])) { + $this->semanticalError( + sprintf("'%s' does not point to a ResultVariable.", $resultVariable), + $deferredItem['token'], + ); + } + + // Validate if identification variable nesting level is lower or equal than the current one + if ($qComp['nestingLevel'] > $deferredItem['nestingLevel']) { + $this->semanticalError( + sprintf("'%s' is used outside the scope of its declaration.", $resultVariable), + $deferredItem['token'], + ); + } + } + } + + /** + * Validates that the given PathExpression is semantically correct for grammar rules: + * + * AssociationPathExpression ::= CollectionValuedPathExpression | SingleValuedAssociationPathExpression + * SingleValuedPathExpression ::= StateFieldPathExpression | SingleValuedAssociationPathExpression + * StateFieldPathExpression ::= IdentificationVariable "." StateField + * SingleValuedAssociationPathExpression ::= IdentificationVariable "." SingleValuedAssociationField + * CollectionValuedPathExpression ::= IdentificationVariable "." CollectionValuedAssociationField + */ + private function processDeferredPathExpressions(): void + { + foreach ($this->deferredPathExpressions as $deferredItem) { + $pathExpression = $deferredItem['expression']; + + $class = $this->getMetadataForDqlAlias($pathExpression->identificationVariable); + + $field = $pathExpression->field; + if ($field === null) { + $field = $pathExpression->field = $class->identifier[0]; + } + + // Check if field or association exists + if (! isset($class->associationMappings[$field]) && ! isset($class->fieldMappings[$field])) { + $this->semanticalError( + 'Class ' . $class->name . ' has no field or association named ' . $field, + $deferredItem['token'], + ); + } + + $fieldType = AST\PathExpression::TYPE_STATE_FIELD; + + if (isset($class->associationMappings[$field])) { + $assoc = $class->associationMappings[$field]; + + $fieldType = $assoc->isToOne() + ? AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION + : AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION; + } + + // Validate if PathExpression is one of the expected types + $expectedType = $pathExpression->expectedType; + + if (! ($expectedType & $fieldType)) { + // We need to recognize which was expected type(s) + $expectedStringTypes = []; + + // Validate state field type + if ($expectedType & AST\PathExpression::TYPE_STATE_FIELD) { + $expectedStringTypes[] = 'StateFieldPathExpression'; + } + + // Validate single valued association (*-to-one) + if ($expectedType & AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION) { + $expectedStringTypes[] = 'SingleValuedAssociationField'; + } + + // Validate single valued association (*-to-many) + if ($expectedType & AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION) { + $expectedStringTypes[] = 'CollectionValuedAssociationField'; + } + + // Build the error message + $semanticalError = 'Invalid PathExpression. '; + $semanticalError .= count($expectedStringTypes) === 1 + ? 'Must be a ' . $expectedStringTypes[0] . '.' + : implode(' or ', $expectedStringTypes) . ' expected.'; + + $this->semanticalError($semanticalError, $deferredItem['token']); + } + + // We need to force the type in PathExpression + $pathExpression->type = $fieldType; + } + } + + private function processRootEntityAliasSelected(): void + { + if (! count($this->identVariableExpressions)) { + return; + } + + foreach ($this->identVariableExpressions as $dqlAlias => $expr) { + if (isset($this->queryComponents[$dqlAlias]) && ! isset($this->queryComponents[$dqlAlias]['parent'])) { + return; + } + } + + $this->semanticalError('Cannot select entity through identification variables without choosing at least one root entity alias.'); + } + + /** + * QueryLanguage ::= SelectStatement | UpdateStatement | DeleteStatement + */ + public function QueryLanguage(): AST\SelectStatement|AST\UpdateStatement|AST\DeleteStatement + { + $statement = null; + + $this->lexer->moveNext(); + + switch ($this->lexer->lookahead->type ?? null) { + case TokenType::T_SELECT: + $statement = $this->SelectStatement(); + break; + + case TokenType::T_UPDATE: + $statement = $this->UpdateStatement(); + break; + + case TokenType::T_DELETE: + $statement = $this->DeleteStatement(); + break; + + default: + $this->syntaxError('SELECT, UPDATE or DELETE'); + break; + } + + // Check for end of string + if ($this->lexer->lookahead !== null) { + $this->syntaxError('end of string'); + } + + return $statement; + } + + /** + * SelectStatement ::= SelectClause FromClause [WhereClause] [GroupByClause] [HavingClause] [OrderByClause] + */ + public function SelectStatement(): AST\SelectStatement + { + $selectStatement = new AST\SelectStatement($this->SelectClause(), $this->FromClause()); + + $selectStatement->whereClause = $this->lexer->isNextToken(TokenType::T_WHERE) ? $this->WhereClause() : null; + $selectStatement->groupByClause = $this->lexer->isNextToken(TokenType::T_GROUP) ? $this->GroupByClause() : null; + $selectStatement->havingClause = $this->lexer->isNextToken(TokenType::T_HAVING) ? $this->HavingClause() : null; + $selectStatement->orderByClause = $this->lexer->isNextToken(TokenType::T_ORDER) ? $this->OrderByClause() : null; + + return $selectStatement; + } + + /** + * UpdateStatement ::= UpdateClause [WhereClause] + */ + public function UpdateStatement(): AST\UpdateStatement + { + $updateStatement = new AST\UpdateStatement($this->UpdateClause()); + + $updateStatement->whereClause = $this->lexer->isNextToken(TokenType::T_WHERE) ? $this->WhereClause() : null; + + return $updateStatement; + } + + /** + * DeleteStatement ::= DeleteClause [WhereClause] + */ + public function DeleteStatement(): AST\DeleteStatement + { + $deleteStatement = new AST\DeleteStatement($this->DeleteClause()); + + $deleteStatement->whereClause = $this->lexer->isNextToken(TokenType::T_WHERE) ? $this->WhereClause() : null; + + return $deleteStatement; + } + + /** + * IdentificationVariable ::= identifier + */ + public function IdentificationVariable(): string + { + $this->match(TokenType::T_IDENTIFIER); + + assert($this->lexer->token !== null); + $identVariable = $this->lexer->token->value; + + $this->deferredIdentificationVariables[] = [ + 'expression' => $identVariable, + 'nestingLevel' => $this->nestingLevel, + 'token' => $this->lexer->token, + ]; + + return $identVariable; + } + + /** + * AliasIdentificationVariable = identifier + */ + public function AliasIdentificationVariable(): string + { + $this->match(TokenType::T_IDENTIFIER); + + assert($this->lexer->token !== null); + $aliasIdentVariable = $this->lexer->token->value; + $exists = isset($this->queryComponents[$aliasIdentVariable]); + + if ($exists) { + $this->semanticalError( + sprintf("'%s' is already defined.", $aliasIdentVariable), + $this->lexer->token, + ); + } + + return $aliasIdentVariable; + } + + /** + * AbstractSchemaName ::= fully_qualified_name | identifier + */ + public function AbstractSchemaName(): string + { + if ($this->lexer->isNextToken(TokenType::T_FULLY_QUALIFIED_NAME)) { + $this->match(TokenType::T_FULLY_QUALIFIED_NAME); + assert($this->lexer->token !== null); + + return $this->lexer->token->value; + } + + $this->match(TokenType::T_IDENTIFIER); + assert($this->lexer->token !== null); + + return $this->lexer->token->value; + } + + /** + * Validates an AbstractSchemaName, making sure the class exists. + * + * @param string $schemaName The name to validate. + * + * @throws QueryException if the name does not exist. + */ + private function validateAbstractSchemaName(string $schemaName): void + { + assert($this->lexer->token !== null); + if (! (class_exists($schemaName, true) || interface_exists($schemaName, true))) { + $this->semanticalError( + sprintf("Class '%s' is not defined.", $schemaName), + $this->lexer->token, + ); + } + } + + /** + * AliasResultVariable ::= identifier + */ + public function AliasResultVariable(): string + { + $this->match(TokenType::T_IDENTIFIER); + + assert($this->lexer->token !== null); + $resultVariable = $this->lexer->token->value; + $exists = isset($this->queryComponents[$resultVariable]); + + if ($exists) { + $this->semanticalError( + sprintf("'%s' is already defined.", $resultVariable), + $this->lexer->token, + ); + } + + return $resultVariable; + } + + /** + * ResultVariable ::= identifier + */ + public function ResultVariable(): string + { + $this->match(TokenType::T_IDENTIFIER); + + assert($this->lexer->token !== null); + $resultVariable = $this->lexer->token->value; + + // Defer ResultVariable validation + $this->deferredResultVariables[] = [ + 'expression' => $resultVariable, + 'nestingLevel' => $this->nestingLevel, + 'token' => $this->lexer->token, + ]; + + return $resultVariable; + } + + /** + * JoinAssociationPathExpression ::= IdentificationVariable "." (CollectionValuedAssociationField | SingleValuedAssociationField) + */ + public function JoinAssociationPathExpression(): AST\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(TokenType::T_DOT); + $this->match(TokenType::T_IDENTIFIER); + + assert($this->lexer->token !== null); + $field = $this->lexer->token->value; + + // Validate association field + $class = $this->getMetadataForDqlAlias($identVariable); + + if (! $class->hasAssociation($field)) { + $this->semanticalError('Class ' . $class->name . ' has no association named ' . $field); + } + + return new AST\JoinAssociationPathExpression($identVariable, $field); + } + + /** + * Parses an arbitrary path expression and defers semantical validation + * based on expected types. + * + * PathExpression ::= IdentificationVariable {"." identifier}* + * + * @phpstan-param int-mask-of $expectedTypes + */ + public function PathExpression(int $expectedTypes): AST\PathExpression + { + $identVariable = $this->IdentificationVariable(); + $field = null; + + assert($this->lexer->token !== null); + if ($this->lexer->isNextToken(TokenType::T_DOT)) { + $this->match(TokenType::T_DOT); + $this->match(TokenType::T_IDENTIFIER); + + $field = $this->lexer->token->value; + + while ($this->lexer->isNextToken(TokenType::T_DOT)) { + $this->match(TokenType::T_DOT); + $this->match(TokenType::T_IDENTIFIER); + $field .= '.' . $this->lexer->token->value; + } + } + + // Creating AST node + $pathExpr = new AST\PathExpression($expectedTypes, $identVariable, $field); + + // Defer PathExpression validation if requested to be deferred + $this->deferredPathExpressions[] = [ + 'expression' => $pathExpr, + 'nestingLevel' => $this->nestingLevel, + 'token' => $this->lexer->token, + ]; + + return $pathExpr; + } + + /** + * AssociationPathExpression ::= CollectionValuedPathExpression | SingleValuedAssociationPathExpression + */ + public function AssociationPathExpression(): AST\PathExpression + { + return $this->PathExpression( + AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION | + AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION, + ); + } + + /** + * SingleValuedPathExpression ::= StateFieldPathExpression | SingleValuedAssociationPathExpression + */ + public function SingleValuedPathExpression(): AST\PathExpression + { + return $this->PathExpression( + AST\PathExpression::TYPE_STATE_FIELD | + AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, + ); + } + + /** + * StateFieldPathExpression ::= IdentificationVariable "." StateField + */ + public function StateFieldPathExpression(): AST\PathExpression + { + return $this->PathExpression(AST\PathExpression::TYPE_STATE_FIELD); + } + + /** + * SingleValuedAssociationPathExpression ::= IdentificationVariable "." SingleValuedAssociationField + */ + public function SingleValuedAssociationPathExpression(): AST\PathExpression + { + return $this->PathExpression(AST\PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION); + } + + /** + * CollectionValuedPathExpression ::= IdentificationVariable "." CollectionValuedAssociationField + */ + public function CollectionValuedPathExpression(): AST\PathExpression + { + return $this->PathExpression(AST\PathExpression::TYPE_COLLECTION_VALUED_ASSOCIATION); + } + + /** + * EntityAsDtoArgumentExpression ::= IdentificationVariable + */ + public function EntityAsDtoArgumentExpression(): AST\EntityAsDtoArgumentExpression + { + assert($this->lexer->lookahead !== null); + $expression = null; + $identVariable = null; + $peek = $this->lexer->glimpse(); + $lookaheadType = $this->lexer->lookahead->type; + assert($peek !== null); + + assert($lookaheadType === TokenType::T_IDENTIFIER); + assert($peek->type !== TokenType::T_DOT); + assert($peek->type !== TokenType::T_OPEN_PARENTHESIS); + + $expression = $identVariable = $this->IdentificationVariable(); + + // [["AS"] AliasResultVariable] + $mustHaveAliasResultVariable = false; + + if ($this->lexer->isNextToken(TokenType::T_AS)) { + $this->match(TokenType::T_AS); + + $mustHaveAliasResultVariable = true; + } + + $aliasResultVariable = null; + + if ($mustHaveAliasResultVariable || $this->lexer->isNextToken(TokenType::T_IDENTIFIER)) { + $token = $this->lexer->lookahead; + $aliasResultVariable = $this->AliasResultVariable(); + + // Include AliasResultVariable in query components. + $this->queryComponents[$aliasResultVariable] = [ + 'resultVariable' => $expression, + 'nestingLevel' => $this->nestingLevel, + 'token' => $token, + ]; + } + + return new AST\EntityAsDtoArgumentExpression($expression, $identVariable, $aliasResultVariable); + } + + /** + * SelectClause ::= "SELECT" ["DISTINCT"] SelectExpression {"," SelectExpression} + */ + public function SelectClause(): AST\SelectClause + { + $isDistinct = false; + $this->match(TokenType::T_SELECT); + + // Check for DISTINCT + if ($this->lexer->isNextToken(TokenType::T_DISTINCT)) { + $this->match(TokenType::T_DISTINCT); + + $isDistinct = true; + } + + // Process SelectExpressions (1..N) + $selectExpressions = []; + $selectExpressions[] = $this->SelectExpression(); + + while ($this->lexer->isNextToken(TokenType::T_COMMA)) { + $this->match(TokenType::T_COMMA); + + $selectExpressions[] = $this->SelectExpression(); + } + + return new AST\SelectClause($selectExpressions, $isDistinct); + } + + /** + * SimpleSelectClause ::= "SELECT" ["DISTINCT"] SimpleSelectExpression + */ + public function SimpleSelectClause(): AST\SimpleSelectClause + { + $isDistinct = false; + $this->match(TokenType::T_SELECT); + + if ($this->lexer->isNextToken(TokenType::T_DISTINCT)) { + $this->match(TokenType::T_DISTINCT); + + $isDistinct = true; + } + + return new AST\SimpleSelectClause($this->SimpleSelectExpression(), $isDistinct); + } + + /** + * UpdateClause ::= "UPDATE" AbstractSchemaName ["AS"] AliasIdentificationVariable "SET" UpdateItem {"," UpdateItem}* + */ + public function UpdateClause(): AST\UpdateClause + { + $this->match(TokenType::T_UPDATE); + assert($this->lexer->lookahead !== null); + + $token = $this->lexer->lookahead; + $abstractSchemaName = $this->AbstractSchemaName(); + + $this->validateAbstractSchemaName($abstractSchemaName); + + if ($this->lexer->isNextToken(TokenType::T_AS)) { + $this->match(TokenType::T_AS); + } + + $aliasIdentificationVariable = $this->AliasIdentificationVariable(); + + $class = $this->em->getClassMetadata($abstractSchemaName); + + // Building queryComponent + $queryComponent = [ + 'metadata' => $class, + 'parent' => null, + 'relation' => null, + 'map' => null, + 'nestingLevel' => $this->nestingLevel, + 'token' => $token, + ]; + + $this->queryComponents[$aliasIdentificationVariable] = $queryComponent; + + $this->match(TokenType::T_SET); + + $updateItems = []; + $updateItems[] = $this->UpdateItem(); + + while ($this->lexer->isNextToken(TokenType::T_COMMA)) { + $this->match(TokenType::T_COMMA); + + $updateItems[] = $this->UpdateItem(); + } + + $updateClause = new AST\UpdateClause($abstractSchemaName, $updateItems); + $updateClause->aliasIdentificationVariable = $aliasIdentificationVariable; + + return $updateClause; + } + + /** + * DeleteClause ::= "DELETE" ["FROM"] AbstractSchemaName ["AS"] AliasIdentificationVariable + */ + public function DeleteClause(): AST\DeleteClause + { + $this->match(TokenType::T_DELETE); + + if ($this->lexer->isNextToken(TokenType::T_FROM)) { + $this->match(TokenType::T_FROM); + } + + assert($this->lexer->lookahead !== null); + $token = $this->lexer->lookahead; + $abstractSchemaName = $this->AbstractSchemaName(); + + $this->validateAbstractSchemaName($abstractSchemaName); + + $deleteClause = new AST\DeleteClause($abstractSchemaName); + + if ($this->lexer->isNextToken(TokenType::T_AS)) { + $this->match(TokenType::T_AS); + } + + $aliasIdentificationVariable = $this->lexer->isNextToken(TokenType::T_IDENTIFIER) + ? $this->AliasIdentificationVariable() + : 'alias_should_have_been_set'; + + $deleteClause->aliasIdentificationVariable = $aliasIdentificationVariable; + $class = $this->em->getClassMetadata($deleteClause->abstractSchemaName); + + // Building queryComponent + $queryComponent = [ + 'metadata' => $class, + 'parent' => null, + 'relation' => null, + 'map' => null, + 'nestingLevel' => $this->nestingLevel, + 'token' => $token, + ]; + + $this->queryComponents[$aliasIdentificationVariable] = $queryComponent; + + return $deleteClause; + } + + /** + * FromClause ::= "FROM" IdentificationVariableDeclaration {"," IdentificationVariableDeclaration}* + */ + public function FromClause(): AST\FromClause + { + $this->match(TokenType::T_FROM); + + $identificationVariableDeclarations = []; + $identificationVariableDeclarations[] = $this->IdentificationVariableDeclaration(); + + while ($this->lexer->isNextToken(TokenType::T_COMMA)) { + $this->match(TokenType::T_COMMA); + + $identificationVariableDeclarations[] = $this->IdentificationVariableDeclaration(); + } + + return new AST\FromClause($identificationVariableDeclarations); + } + + /** + * SubselectFromClause ::= "FROM" SubselectIdentificationVariableDeclaration {"," SubselectIdentificationVariableDeclaration}* + */ + public function SubselectFromClause(): AST\SubselectFromClause + { + $this->match(TokenType::T_FROM); + + $identificationVariables = []; + $identificationVariables[] = $this->SubselectIdentificationVariableDeclaration(); + + while ($this->lexer->isNextToken(TokenType::T_COMMA)) { + $this->match(TokenType::T_COMMA); + + $identificationVariables[] = $this->SubselectIdentificationVariableDeclaration(); + } + + return new AST\SubselectFromClause($identificationVariables); + } + + /** + * WhereClause ::= "WHERE" ConditionalExpression + */ + public function WhereClause(): AST\WhereClause + { + $this->match(TokenType::T_WHERE); + + return new AST\WhereClause($this->ConditionalExpression()); + } + + /** + * HavingClause ::= "HAVING" ConditionalExpression + */ + public function HavingClause(): AST\HavingClause + { + $this->match(TokenType::T_HAVING); + + return new AST\HavingClause($this->ConditionalExpression()); + } + + /** + * GroupByClause ::= "GROUP" "BY" GroupByItem {"," GroupByItem}* + */ + public function GroupByClause(): AST\GroupByClause + { + $this->match(TokenType::T_GROUP); + $this->match(TokenType::T_BY); + + $groupByItems = [$this->GroupByItem()]; + + while ($this->lexer->isNextToken(TokenType::T_COMMA)) { + $this->match(TokenType::T_COMMA); + + $groupByItems[] = $this->GroupByItem(); + } + + return new AST\GroupByClause($groupByItems); + } + + /** + * OrderByClause ::= "ORDER" "BY" OrderByItem {"," OrderByItem}* + */ + public function OrderByClause(): AST\OrderByClause + { + $this->match(TokenType::T_ORDER); + $this->match(TokenType::T_BY); + + $orderByItems = []; + $orderByItems[] = $this->OrderByItem(); + + while ($this->lexer->isNextToken(TokenType::T_COMMA)) { + $this->match(TokenType::T_COMMA); + + $orderByItems[] = $this->OrderByItem(); + } + + return new AST\OrderByClause($orderByItems, $this->withJoinConditionNestingLevel === 0); + } + + /** + * Subselect ::= SimpleSelectClause SubselectFromClause [WhereClause] [GroupByClause] [HavingClause] [OrderByClause] + */ + public function Subselect(): AST\Subselect + { + // Increase query nesting level + $this->nestingLevel++; + + $subselect = new AST\Subselect($this->SimpleSelectClause(), $this->SubselectFromClause()); + + $subselect->whereClause = $this->lexer->isNextToken(TokenType::T_WHERE) ? $this->WhereClause() : null; + $subselect->groupByClause = $this->lexer->isNextToken(TokenType::T_GROUP) ? $this->GroupByClause() : null; + $subselect->havingClause = $this->lexer->isNextToken(TokenType::T_HAVING) ? $this->HavingClause() : null; + $subselect->orderByClause = $this->lexer->isNextToken(TokenType::T_ORDER) ? $this->OrderByClause() : null; + + // Decrease query nesting level + $this->nestingLevel--; + + return $subselect; + } + + /** + * UpdateItem ::= SingleValuedPathExpression "=" NewValue + */ + public function UpdateItem(): AST\UpdateItem + { + $pathExpr = $this->SingleValuedPathExpression(); + + $this->match(TokenType::T_EQUALS); + + return new AST\UpdateItem($pathExpr, $this->NewValue()); + } + + /** + * GroupByItem ::= IdentificationVariable | ResultVariable | SingleValuedPathExpression + */ + public function GroupByItem(): string|AST\PathExpression + { + // We need to check if we are in a IdentificationVariable or SingleValuedPathExpression + $glimpse = $this->lexer->glimpse(); + + if ($glimpse !== null && $glimpse->type === TokenType::T_DOT) { + return $this->SingleValuedPathExpression(); + } + + assert($this->lexer->lookahead !== null); + // Still need to decide between IdentificationVariable or ResultVariable + $lookaheadValue = $this->lexer->lookahead->value; + + if (! isset($this->queryComponents[$lookaheadValue])) { + $this->semanticalError('Cannot group by undefined identification or result variable.'); + } + + return isset($this->queryComponents[$lookaheadValue]['metadata']) + ? $this->IdentificationVariable() + : $this->ResultVariable(); + } + + /** + * OrderByItem ::= ( + * SimpleArithmeticExpression | SingleValuedPathExpression | CaseExpression | + * ScalarExpression | ResultVariable | FunctionDeclaration + * ) ["ASC" | "DESC"] + */ + public function OrderByItem(): AST\OrderByItem + { + $this->lexer->peek(); // lookahead => '.' + $this->lexer->peek(); // lookahead => token after '.' + + $peek = $this->lexer->peek(); // lookahead => token after the token after the '.' + + $this->lexer->resetPeek(); + + $glimpse = $this->lexer->glimpse(); + + assert($this->lexer->lookahead !== null); + $expr = match (true) { + $this->isMathOperator($peek) || $this->isMathOperator($glimpse) => $this->SimpleArithmeticExpression(), + $glimpse !== null && $glimpse->type === TokenType::T_DOT => $this->SingleValuedPathExpression(), + $this->lexer->peek() && $this->isMathOperator($this->peekBeyondClosingParenthesis()) => $this->ScalarExpression(), + $this->lexer->lookahead->type === TokenType::T_CASE => $this->CaseExpression(), + $this->isFunction() => $this->FunctionDeclaration(), + default => $this->ResultVariable(), + }; + + $type = 'ASC'; + $item = new AST\OrderByItem($expr); + + switch (true) { + case $this->lexer->isNextToken(TokenType::T_DESC): + $this->match(TokenType::T_DESC); + $type = 'DESC'; + break; + + case $this->lexer->isNextToken(TokenType::T_ASC): + $this->match(TokenType::T_ASC); + break; + + default: + // Do nothing + } + + $item->type = $type; + + return $item; + } + + /** + * NewValue ::= SimpleArithmeticExpression | StringPrimary | DatetimePrimary | BooleanPrimary | + * EnumPrimary | SimpleEntityExpression | "NULL" + * + * NOTE: Since it is not possible to correctly recognize individual types, here is the full + * grammar that needs to be supported: + * + * NewValue ::= SimpleArithmeticExpression | "NULL" + * + * SimpleArithmeticExpression covers all *Primary grammar rules and also SimpleEntityExpression + */ + public function NewValue(): AST\ArithmeticExpression|AST\InputParameter|null + { + if ($this->lexer->isNextToken(TokenType::T_NULL)) { + $this->match(TokenType::T_NULL); + + return null; + } + + if ($this->lexer->isNextToken(TokenType::T_INPUT_PARAMETER)) { + $this->match(TokenType::T_INPUT_PARAMETER); + assert($this->lexer->token !== null); + + return new AST\InputParameter($this->lexer->token->value); + } + + return $this->ArithmeticExpression(); + } + + /** + * IdentificationVariableDeclaration ::= RangeVariableDeclaration [IndexBy] {Join}* + */ + public function IdentificationVariableDeclaration(): AST\IdentificationVariableDeclaration + { + $joins = []; + $rangeVariableDeclaration = $this->RangeVariableDeclaration(); + $indexBy = $this->lexer->isNextToken(TokenType::T_INDEX) + ? $this->IndexBy() + : null; + + $rangeVariableDeclaration->isRoot = true; + + while ( + $this->lexer->isNextToken(TokenType::T_LEFT) || + $this->lexer->isNextToken(TokenType::T_INNER) || + $this->lexer->isNextToken(TokenType::T_JOIN) + ) { + $joins[] = $this->Join(); + } + + return new AST\IdentificationVariableDeclaration( + $rangeVariableDeclaration, + $indexBy, + $joins, + ); + } + + /** + * SubselectIdentificationVariableDeclaration ::= IdentificationVariableDeclaration + * + * {Internal note: WARNING: Solution is harder than a bare implementation. + * Desired EBNF support: + * + * SubselectIdentificationVariableDeclaration ::= IdentificationVariableDeclaration | (AssociationPathExpression ["AS"] AliasIdentificationVariable) + * + * It demands that entire SQL generation to become programmatical. This is + * needed because association based subselect requires "WHERE" conditional + * expressions to be injected, but there is no scope to do that. Only scope + * accessible is "FROM", prohibiting an easy implementation without larger + * changes.} + */ + public function SubselectIdentificationVariableDeclaration(): AST\IdentificationVariableDeclaration + { + /* + NOT YET IMPLEMENTED! + + $glimpse = $this->lexer->glimpse(); + + if ($glimpse->type == TokenType::T_DOT) { + $associationPathExpression = $this->AssociationPathExpression(); + + if ($this->lexer->isNextToken(TokenType::T_AS)) { + $this->match(TokenType::T_AS); + } + + $aliasIdentificationVariable = $this->AliasIdentificationVariable(); + $identificationVariable = $associationPathExpression->identificationVariable; + $field = $associationPathExpression->associationField; + + $class = $this->queryComponents[$identificationVariable]['metadata']; + $targetClass = $this->em->getClassMetadata($class->associationMappings[$field]['targetEntity']); + + // Building queryComponent + $joinQueryComponent = array( + 'metadata' => $targetClass, + 'parent' => $identificationVariable, + 'relation' => $class->getAssociationMapping($field), + 'map' => null, + 'nestingLevel' => $this->nestingLevel, + 'token' => $this->lexer->lookahead + ); + + $this->queryComponents[$aliasIdentificationVariable] = $joinQueryComponent; + + return new AST\SubselectIdentificationVariableDeclaration( + $associationPathExpression, $aliasIdentificationVariable + ); + } + */ + + return $this->IdentificationVariableDeclaration(); + } + + /** + * Join ::= ["LEFT" ["OUTER"] | "INNER"] "JOIN" + * (JoinAssociationDeclaration ["WITH" ConditionalExpression] | RangeVariableDeclaration [("ON" | "WITH") ConditionalExpression]) + */ + public function Join(): AST\Join + { + // Check Join type + $joinType = AST\Join::JOIN_TYPE_INNER; + + switch (true) { + case $this->lexer->isNextToken(TokenType::T_LEFT): + $this->match(TokenType::T_LEFT); + + $joinType = AST\Join::JOIN_TYPE_LEFT; + + // Possible LEFT OUTER join + if ($this->lexer->isNextToken(TokenType::T_OUTER)) { + $this->match(TokenType::T_OUTER); + + $joinType = AST\Join::JOIN_TYPE_LEFTOUTER; + } + + break; + + case $this->lexer->isNextToken(TokenType::T_INNER): + $this->match(TokenType::T_INNER); + break; + + default: + // Do nothing + } + + $this->match(TokenType::T_JOIN); + + $next = $this->lexer->glimpse(); + assert($next !== null); + $conditionalExpression = null; + + if ($next->type === TokenType::T_DOT) { + $joinDeclaration = $this->JoinAssociationDeclaration(); + + if ($this->lexer->isNextToken(TokenType::T_WITH)) { + $this->match(TokenType::T_WITH); + + try { + $this->withJoinConditionNestingLevel++; + + $conditionalExpression = $this->ConditionalExpression(); + } finally { + $this->withJoinConditionNestingLevel--; + } + } + } else { + $joinDeclaration = $this->RangeVariableDeclaration(); + $joinDeclaration->isRoot = false; + + if ($this->lexer->isNextToken(TokenType::T_ON)) { + $this->match(TokenType::T_ON); + $conditionalExpression = $this->ConditionalExpression(); + } elseif ($this->lexer->isNextToken(TokenType::T_WITH)) { + $this->match(TokenType::T_WITH); + $conditionalExpression = $this->ConditionalExpression(); + Deprecation::trigger('doctrine/orm', 'https://github.com/doctrine/orm/issues/12192', 'Using WITH for the join condition of arbitrary joins is deprecated. Use ON instead.'); + } + } + + $join = new AST\Join($joinType, $joinDeclaration); + $join->conditionalExpression = $conditionalExpression; + + return $join; + } + + /** + * RangeVariableDeclaration ::= AbstractSchemaName ["AS"] AliasIdentificationVariable + * + * @throws QueryException + */ + public function RangeVariableDeclaration(): AST\RangeVariableDeclaration + { + if ($this->lexer->isNextToken(TokenType::T_OPEN_PARENTHESIS) && $this->lexer->glimpse()->type === TokenType::T_SELECT) { + $this->semanticalError('Subquery is not supported here', $this->lexer->token); + } + + $abstractSchemaName = $this->AbstractSchemaName(); + + $this->validateAbstractSchemaName($abstractSchemaName); + + if ($this->lexer->isNextToken(TokenType::T_AS)) { + $this->match(TokenType::T_AS); + } + + assert($this->lexer->lookahead !== null); + $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); + } + + /** + * JoinAssociationDeclaration ::= JoinAssociationPathExpression ["AS"] AliasIdentificationVariable [IndexBy] + */ + public function JoinAssociationDeclaration(): AST\JoinAssociationDeclaration + { + $joinAssociationPathExpression = $this->JoinAssociationPathExpression(); + + if ($this->lexer->isNextToken(TokenType::T_AS)) { + $this->match(TokenType::T_AS); + } + + assert($this->lexer->lookahead !== null); + + $aliasIdentificationVariable = $this->AliasIdentificationVariable(); + $indexBy = $this->lexer->isNextToken(TokenType::T_INDEX) ? $this->IndexBy() : null; + + $identificationVariable = $joinAssociationPathExpression->identificationVariable; + $field = $joinAssociationPathExpression->associationField; + + $class = $this->getMetadataForDqlAlias($identificationVariable); + $targetClass = $this->em->getClassMetadata($class->associationMappings[$field]->targetEntity); + + // Building queryComponent + $joinQueryComponent = [ + 'metadata' => $targetClass, + 'parent' => $joinAssociationPathExpression->identificationVariable, + 'relation' => $class->getAssociationMapping($field), + 'map' => null, + 'nestingLevel' => $this->nestingLevel, + 'token' => $this->lexer->lookahead, + ]; + + $this->queryComponents[$aliasIdentificationVariable] = $joinQueryComponent; + + return new AST\JoinAssociationDeclaration($joinAssociationPathExpression, $aliasIdentificationVariable, $indexBy); + } + + /** + * PartialObjectExpression ::= "PARTIAL" IdentificationVariable "." PartialFieldSet + * PartialFieldSet ::= "{" SimpleStateField {"," SimpleStateField}* "}" + */ + public function PartialObjectExpression(): AST\PartialObjectExpression + { + $this->match(TokenType::T_PARTIAL); + + $partialFieldSet = []; + + $identificationVariable = $this->IdentificationVariable(); + + $this->match(TokenType::T_DOT); + $this->match(TokenType::T_OPEN_CURLY_BRACE); + $this->match(TokenType::T_IDENTIFIER); + + assert($this->lexer->token !== null); + $field = $this->lexer->token->value; + + // First field in partial expression might be embeddable property + while ($this->lexer->isNextToken(TokenType::T_DOT)) { + $this->match(TokenType::T_DOT); + $this->match(TokenType::T_IDENTIFIER); + $field .= '.' . $this->lexer->token->value; + } + + $partialFieldSet[] = $field; + + while ($this->lexer->isNextToken(TokenType::T_COMMA)) { + $this->match(TokenType::T_COMMA); + $this->match(TokenType::T_IDENTIFIER); + + $field = $this->lexer->token->value; + + while ($this->lexer->isNextToken(TokenType::T_DOT)) { + $this->match(TokenType::T_DOT); + $this->match(TokenType::T_IDENTIFIER); + $field .= '.' . $this->lexer->token->value; + } + + $partialFieldSet[] = $field; + } + + $this->match(TokenType::T_CLOSE_CURLY_BRACE); + + $partialObjectExpression = new AST\PartialObjectExpression($identificationVariable, $partialFieldSet); + + // Defer PartialObjectExpression validation + $this->deferredPartialObjectExpressions[] = [ + 'expression' => $partialObjectExpression, + 'nestingLevel' => $this->nestingLevel, + 'token' => $this->lexer->token, + ]; + + return $partialObjectExpression; + } + + /** + * NewObjectExpression ::= "NEW" AbstractSchemaName "(" NewObjectArg {"," NewObjectArg}* ")" + */ + public function NewObjectExpression(): AST\NewObjectExpression + { + $useNamedArguments = false; + $args = []; + $argFieldAlias = []; + $this->match(TokenType::T_NEW); + + if ($this->lexer->isNextToken(TokenType::T_NAMED)) { + $this->match(TokenType::T_NAMED); + $useNamedArguments = true; + } + + /** @var class-string $className */ + $className = $this->AbstractSchemaName(); // note that this is not yet validated + $token = $this->lexer->token; + + $this->match(TokenType::T_OPEN_PARENTHESIS); + + $this->addArgument($args, $useNamedArguments); + + while ($this->lexer->isNextToken(TokenType::T_COMMA)) { + $this->match(TokenType::T_COMMA); + $this->addArgument($args, $useNamedArguments); + } + + $this->match(TokenType::T_CLOSE_PARENTHESIS); + + $expression = new AST\NewObjectExpression($className, $args); + + // Defer NewObjectExpression validation + $this->deferredNewObjectExpressions[] = [ + 'token' => $token, + 'expression' => $expression, + 'nestingLevel' => $this->nestingLevel, + ]; + + return $expression; + } + + /** @param array $args */ + public function addArgument(array &$args, bool $useNamedArguments): void + { + $fieldAlias = null; + + if ($useNamedArguments) { + $startToken = $this->lexer->lookahead?->position ?? 0; + + $newArg = $this->NewObjectArg($fieldAlias); + + $key = $fieldAlias ?? $newArg->field ?? null; + + if ($key === null) { + throw NoMatchingPropertyException::create(trim(substr( + ($this->query->getDQL() ?? ''), + $startToken, + ($this->lexer->lookahead->position ?? 0) - $startToken, + ))); + } + + if (array_key_exists($key, $args)) { + throw DuplicateFieldException::create($key, trim(substr( + ($this->query->getDQL() ?? ''), + $startToken, + ($this->lexer->lookahead->position ?? 0) - $startToken, + ))); + } + + $args[$key] = $newArg; + } else { + $args[] = $this->NewObjectArg($fieldAlias); + } + } + + /** + * NewObjectArg ::= (ScalarExpression | "(" Subselect ")" | NewObjectExpression) ["AS" AliasResultVariable] + */ + public function NewObjectArg(string|null &$fieldAlias = null): mixed + { + $fieldAlias = null; + + assert($this->lexer->lookahead !== null); + $token = $this->lexer->lookahead; + $peek = $this->lexer->glimpse(); + + assert($peek !== null); + + $expression = null; + + if ($token->type === TokenType::T_OPEN_PARENTHESIS && $peek->type === TokenType::T_SELECT) { + $this->match(TokenType::T_OPEN_PARENTHESIS); + $expression = $this->Subselect(); + $this->match(TokenType::T_CLOSE_PARENTHESIS); + } elseif ($token->type === TokenType::T_NEW) { + $expression = $this->NewObjectExpression(); + } elseif ($token->type === TokenType::T_IDENTIFIER && $peek->type !== TokenType::T_DOT && $peek->type !== TokenType::T_OPEN_PARENTHESIS) { + $expression = $this->EntityAsDtoArgumentExpression(); + $fieldAlias = $expression->aliasVariable; + } else { + $expression = $this->ScalarExpression(); + } + + if ($this->lexer->isNextToken(TokenType::T_AS)) { + $this->match(TokenType::T_AS); + $this->match(TokenType::T_IDENTIFIER); + + assert($this->lexer->token !== null); + + $fieldAlias = $this->lexer->token->value; + } + + return $expression; + } + + /** + * IndexBy ::= "INDEX" "BY" SingleValuedPathExpression + */ + public function IndexBy(): AST\IndexBy + { + $this->match(TokenType::T_INDEX); + $this->match(TokenType::T_BY); + $pathExpr = $this->SingleValuedPathExpression(); + + // Add the INDEX BY info to the query component + $this->queryComponents[$pathExpr->identificationVariable]['map'] = $pathExpr->field; + + return new AST\IndexBy($pathExpr); + } + + /** + * ScalarExpression ::= SimpleArithmeticExpression | StringPrimary | DatetimePrimary | + * StateFieldPathExpression | BooleanPrimary | CaseExpression | + * InstanceOfExpression + * + * @return mixed One of the possible expressions or subexpressions. + */ + public function ScalarExpression(): mixed + { + assert($this->lexer->token !== null); + assert($this->lexer->lookahead !== null); + $lookahead = $this->lexer->lookahead->type; + $peek = $this->lexer->glimpse(); + + switch (true) { + case $lookahead === TokenType::T_INTEGER: + case $lookahead === TokenType::T_FLOAT: + // SimpleArithmeticExpression : (- u.value ) or ( + u.value ) or ( - 1 ) or ( + 1 ) + case $lookahead === TokenType::T_MINUS: + case $lookahead === TokenType::T_PLUS: + return $this->SimpleArithmeticExpression(); + + case $lookahead === TokenType::T_STRING: + return $this->StringPrimary(); + + case $lookahead === TokenType::T_TRUE: + case $lookahead === TokenType::T_FALSE: + $this->match($lookahead); + + return new AST\Literal(AST\Literal::BOOLEAN, $this->lexer->token->value); + + case $lookahead === TokenType::T_INPUT_PARAMETER: + return match (true) { + $this->isMathOperator($peek) => $this->SimpleArithmeticExpression(), + default => $this->InputParameter(), + }; + + case $lookahead === TokenType::T_CASE: + case $lookahead === TokenType::T_COALESCE: + case $lookahead === TokenType::T_NULLIF: + // Since NULLIF and COALESCE can be identified as a function, + // we need to check these before checking for FunctionDeclaration + return $this->CaseExpression(); + + case $lookahead === TokenType::T_OPEN_PARENTHESIS: + return $this->SimpleArithmeticExpression(); + + // this check must be done before checking for a filed path expression + case $this->isFunction(): + $this->lexer->peek(); + + return match (true) { + $this->isMathOperator($this->peekBeyondClosingParenthesis()) => $this->SimpleArithmeticExpression(), + default => $this->FunctionDeclaration(), + }; + + // it is no function, so it must be a field path + case $lookahead === TokenType::T_IDENTIFIER: + $this->lexer->peek(); // lookahead => '.' + $this->lexer->peek(); // lookahead => token after '.' + $peek = $this->lexer->peek(); // lookahead => token after the token after the '.' + $this->lexer->resetPeek(); + + if ($this->isMathOperator($peek)) { + return $this->SimpleArithmeticExpression(); + } + + return $this->StateFieldPathExpression(); + + default: + $this->syntaxError(); + } + } + + /** + * CaseExpression ::= GeneralCaseExpression | SimpleCaseExpression | CoalesceExpression | NullIfExpression + * GeneralCaseExpression ::= "CASE" WhenClause {WhenClause}* "ELSE" ScalarExpression "END" + * WhenClause ::= "WHEN" ConditionalExpression "THEN" ScalarExpression + * SimpleCaseExpression ::= "CASE" CaseOperand SimpleWhenClause {SimpleWhenClause}* "ELSE" ScalarExpression "END" + * CaseOperand ::= StateFieldPathExpression + * SimpleWhenClause ::= "WHEN" ScalarExpression "THEN" ScalarExpression + * CoalesceExpression ::= "COALESCE" "(" ScalarExpression {"," ScalarExpression}* ")" + * NullIfExpression ::= "NULLIF" "(" ScalarExpression "," ScalarExpression ")" + * + * @return mixed One of the possible expressions or subexpressions. + */ + public function CaseExpression(): mixed + { + assert($this->lexer->lookahead !== null); + $lookahead = $this->lexer->lookahead->type; + + switch ($lookahead) { + case TokenType::T_NULLIF: + return $this->NullIfExpression(); + + case TokenType::T_COALESCE: + return $this->CoalesceExpression(); + + case TokenType::T_CASE: + $this->lexer->resetPeek(); + $peek = $this->lexer->peek(); + + assert($peek !== null); + if ($peek->type === TokenType::T_WHEN) { + return $this->GeneralCaseExpression(); + } + + return $this->SimpleCaseExpression(); + + default: + // Do nothing + break; + } + + $this->syntaxError(); + } + + /** + * CoalesceExpression ::= "COALESCE" "(" ScalarExpression {"," ScalarExpression}* ")" + */ + public function CoalesceExpression(): AST\CoalesceExpression + { + $this->match(TokenType::T_COALESCE); + $this->match(TokenType::T_OPEN_PARENTHESIS); + + // Process ScalarExpressions (1..N) + $scalarExpressions = []; + $scalarExpressions[] = $this->ScalarExpression(); + + while ($this->lexer->isNextToken(TokenType::T_COMMA)) { + $this->match(TokenType::T_COMMA); + + $scalarExpressions[] = $this->ScalarExpression(); + } + + $this->match(TokenType::T_CLOSE_PARENTHESIS); + + return new AST\CoalesceExpression($scalarExpressions); + } + + /** + * NullIfExpression ::= "NULLIF" "(" ScalarExpression "," ScalarExpression ")" + */ + public function NullIfExpression(): AST\NullIfExpression + { + $this->match(TokenType::T_NULLIF); + $this->match(TokenType::T_OPEN_PARENTHESIS); + + $firstExpression = $this->ScalarExpression(); + $this->match(TokenType::T_COMMA); + $secondExpression = $this->ScalarExpression(); + + $this->match(TokenType::T_CLOSE_PARENTHESIS); + + return new AST\NullIfExpression($firstExpression, $secondExpression); + } + + /** + * GeneralCaseExpression ::= "CASE" WhenClause {WhenClause}* "ELSE" ScalarExpression "END" + */ + public function GeneralCaseExpression(): AST\GeneralCaseExpression + { + $this->match(TokenType::T_CASE); + + // Process WhenClause (1..N) + $whenClauses = []; + + do { + $whenClauses[] = $this->WhenClause(); + } while ($this->lexer->isNextToken(TokenType::T_WHEN)); + + $this->match(TokenType::T_ELSE); + $scalarExpression = $this->ScalarExpression(); + $this->match(TokenType::T_END); + + return new AST\GeneralCaseExpression($whenClauses, $scalarExpression); + } + + /** + * SimpleCaseExpression ::= "CASE" CaseOperand SimpleWhenClause {SimpleWhenClause}* "ELSE" ScalarExpression "END" + * CaseOperand ::= StateFieldPathExpression + */ + public function SimpleCaseExpression(): AST\SimpleCaseExpression + { + $this->match(TokenType::T_CASE); + $caseOperand = $this->StateFieldPathExpression(); + + // Process SimpleWhenClause (1..N) + $simpleWhenClauses = []; + + do { + $simpleWhenClauses[] = $this->SimpleWhenClause(); + } while ($this->lexer->isNextToken(TokenType::T_WHEN)); + + $this->match(TokenType::T_ELSE); + $scalarExpression = $this->ScalarExpression(); + $this->match(TokenType::T_END); + + return new AST\SimpleCaseExpression($caseOperand, $simpleWhenClauses, $scalarExpression); + } + + /** + * WhenClause ::= "WHEN" ConditionalExpression "THEN" ScalarExpression + */ + public function WhenClause(): AST\WhenClause + { + $this->match(TokenType::T_WHEN); + $conditionalExpression = $this->ConditionalExpression(); + $this->match(TokenType::T_THEN); + + return new AST\WhenClause($conditionalExpression, $this->ScalarExpression()); + } + + /** + * SimpleWhenClause ::= "WHEN" ScalarExpression "THEN" ScalarExpression + */ + public function SimpleWhenClause(): AST\SimpleWhenClause + { + $this->match(TokenType::T_WHEN); + $conditionalExpression = $this->ScalarExpression(); + $this->match(TokenType::T_THEN); + + return new AST\SimpleWhenClause($conditionalExpression, $this->ScalarExpression()); + } + + /** + * SelectExpression ::= ( + * IdentificationVariable | ScalarExpression | AggregateExpression | FunctionDeclaration | + * PartialObjectExpression | "(" Subselect ")" | CaseExpression | NewObjectExpression + * ) [["AS"] ["HIDDEN"] AliasResultVariable] + */ + public function SelectExpression(): AST\SelectExpression + { + assert($this->lexer->lookahead !== null); + $expression = null; + $identVariable = null; + $peek = $this->lexer->glimpse(); + $lookaheadType = $this->lexer->lookahead->type; + assert($peek !== null); + + switch (true) { + // ScalarExpression (u.name) + case $lookaheadType === TokenType::T_IDENTIFIER && $peek->type === TokenType::T_DOT: + $expression = $this->ScalarExpression(); + break; + + // IdentificationVariable (u) + case $lookaheadType === TokenType::T_IDENTIFIER && $peek->type !== TokenType::T_OPEN_PARENTHESIS: + $expression = $identVariable = $this->IdentificationVariable(); + break; + + // CaseExpression (CASE ... or NULLIF(...) or COALESCE(...)) + case $lookaheadType === TokenType::T_CASE: + case $lookaheadType === TokenType::T_COALESCE: + case $lookaheadType === TokenType::T_NULLIF: + $expression = $this->CaseExpression(); + break; + + // DQL Function (SUM(u.value) or SUM(u.value) + 1) + case $this->isFunction(): + $this->lexer->peek(); // "(" + + $expression = match (true) { + $this->isMathOperator($this->peekBeyondClosingParenthesis()) => $this->ScalarExpression(), + default => $this->FunctionDeclaration(), + }; + + break; + + // PartialObjectExpression (PARTIAL u.{id, name}) + case $lookaheadType === TokenType::T_PARTIAL: + $expression = $this->PartialObjectExpression(); + $identVariable = $expression->identificationVariable; + break; + + // Subselect + case $lookaheadType === TokenType::T_OPEN_PARENTHESIS && $peek->type === TokenType::T_SELECT: + $this->match(TokenType::T_OPEN_PARENTHESIS); + $expression = $this->Subselect(); + $this->match(TokenType::T_CLOSE_PARENTHESIS); + break; + + // Shortcut: ScalarExpression => SimpleArithmeticExpression + case $lookaheadType === TokenType::T_OPEN_PARENTHESIS: + case $lookaheadType === TokenType::T_INTEGER: + case $lookaheadType === TokenType::T_STRING: + case $lookaheadType === TokenType::T_FLOAT: + // SimpleArithmeticExpression : (- u.value ) or ( + u.value ) + case $lookaheadType === TokenType::T_MINUS: + case $lookaheadType === TokenType::T_PLUS: + $expression = $this->SimpleArithmeticExpression(); + break; + + // NewObjectExpression (New ClassName(id, name)) + case $lookaheadType === TokenType::T_NEW: + $expression = $this->NewObjectExpression(); + break; + + default: + $this->syntaxError( + 'IdentificationVariable | ScalarExpression | AggregateExpression | FunctionDeclaration | PartialObjectExpression | "(" Subselect ")" | CaseExpression', + $this->lexer->lookahead, + ); + } + + // [["AS"] ["HIDDEN"] AliasResultVariable] + $mustHaveAliasResultVariable = false; + + if ($this->lexer->isNextToken(TokenType::T_AS)) { + $this->match(TokenType::T_AS); + + $mustHaveAliasResultVariable = true; + } + + $hiddenAliasResultVariable = false; + + if ($this->lexer->isNextToken(TokenType::T_HIDDEN)) { + $this->match(TokenType::T_HIDDEN); + + $hiddenAliasResultVariable = true; + } + + $aliasResultVariable = null; + + if ($mustHaveAliasResultVariable || $this->lexer->isNextToken(TokenType::T_IDENTIFIER)) { + assert($expression instanceof AST\Node || is_string($expression)); + $token = $this->lexer->lookahead; + $aliasResultVariable = $this->AliasResultVariable(); + + // Include AliasResultVariable in query components. + $this->queryComponents[$aliasResultVariable] = [ + 'resultVariable' => $expression, + 'nestingLevel' => $this->nestingLevel, + 'token' => $token, + ]; + } + + // AST + + $expr = new AST\SelectExpression($expression, $aliasResultVariable, $hiddenAliasResultVariable); + + if ($identVariable) { + $this->identVariableExpressions[$identVariable] = $expr; + } + + return $expr; + } + + /** + * SimpleSelectExpression ::= ( + * StateFieldPathExpression | IdentificationVariable | FunctionDeclaration | + * AggregateExpression | "(" Subselect ")" | ScalarExpression + * ) [["AS"] AliasResultVariable] + */ + public function SimpleSelectExpression(): AST\SimpleSelectExpression + { + assert($this->lexer->lookahead !== null); + $peek = $this->lexer->glimpse(); + assert($peek !== null); + + switch ($this->lexer->lookahead->type) { + case TokenType::T_IDENTIFIER: + switch (true) { + case $peek->type === TokenType::T_DOT: + $expression = $this->StateFieldPathExpression(); + + return new AST\SimpleSelectExpression($expression); + + case $peek->type !== TokenType::T_OPEN_PARENTHESIS: + $expression = $this->IdentificationVariable(); + + return new AST\SimpleSelectExpression($expression); + + case $this->isFunction(): + // SUM(u.id) + COUNT(u.id) + if ($this->isMathOperator($this->peekBeyondClosingParenthesis())) { + return new AST\SimpleSelectExpression($this->ScalarExpression()); + } + + // COUNT(u.id) + if ($this->isAggregateFunction($this->lexer->lookahead->type)) { + return new AST\SimpleSelectExpression($this->AggregateExpression()); + } + + // IDENTITY(u) + return new AST\SimpleSelectExpression($this->FunctionDeclaration()); + + default: + // Do nothing + } + + break; + + case TokenType::T_OPEN_PARENTHESIS: + if ($peek->type !== TokenType::T_SELECT) { + // Shortcut: ScalarExpression => SimpleArithmeticExpression + $expression = $this->SimpleArithmeticExpression(); + + return new AST\SimpleSelectExpression($expression); + } + + // Subselect + $this->match(TokenType::T_OPEN_PARENTHESIS); + $expression = $this->Subselect(); + $this->match(TokenType::T_CLOSE_PARENTHESIS); + + return new AST\SimpleSelectExpression($expression); + + default: + // Do nothing + } + + $this->lexer->peek(); + + $expression = $this->ScalarExpression(); + $expr = new AST\SimpleSelectExpression($expression); + + if ($this->lexer->isNextToken(TokenType::T_AS)) { + $this->match(TokenType::T_AS); + } + + if ($this->lexer->isNextToken(TokenType::T_IDENTIFIER)) { + $token = $this->lexer->lookahead; + $resultVariable = $this->AliasResultVariable(); + $expr->fieldIdentificationVariable = $resultVariable; + + // Include AliasResultVariable in query components. + $this->queryComponents[$resultVariable] = [ + 'resultvariable' => $expr, + 'nestingLevel' => $this->nestingLevel, + 'token' => $token, + ]; + } + + return $expr; + } + + /** + * ConditionalExpression ::= ConditionalTerm {"OR" ConditionalTerm}* + */ + public function ConditionalExpression(): AST\ConditionalExpression|AST\ConditionalFactor|AST\ConditionalPrimary|AST\ConditionalTerm + { + $conditionalTerms = []; + $conditionalTerms[] = $this->ConditionalTerm(); + + while ($this->lexer->isNextToken(TokenType::T_OR)) { + $this->match(TokenType::T_OR); + + $conditionalTerms[] = $this->ConditionalTerm(); + } + + // Phase 1 AST optimization: Prevent AST\ConditionalExpression + // if only one AST\ConditionalTerm is defined + if (count($conditionalTerms) === 1) { + return $conditionalTerms[0]; + } + + return new AST\ConditionalExpression($conditionalTerms); + } + + /** + * ConditionalTerm ::= ConditionalFactor {"AND" ConditionalFactor}* + */ + public function ConditionalTerm(): AST\ConditionalFactor|AST\ConditionalPrimary|AST\ConditionalTerm + { + $conditionalFactors = []; + $conditionalFactors[] = $this->ConditionalFactor(); + + while ($this->lexer->isNextToken(TokenType::T_AND)) { + $this->match(TokenType::T_AND); + + $conditionalFactors[] = $this->ConditionalFactor(); + } + + // Phase 1 AST optimization: Prevent AST\ConditionalTerm + // if only one AST\ConditionalFactor is defined + if (count($conditionalFactors) === 1) { + return $conditionalFactors[0]; + } + + return new AST\ConditionalTerm($conditionalFactors); + } + + /** + * ConditionalFactor ::= ["NOT"] ConditionalPrimary + */ + public function ConditionalFactor(): AST\ConditionalFactor|AST\ConditionalPrimary + { + $not = false; + + if ($this->lexer->isNextToken(TokenType::T_NOT)) { + $this->match(TokenType::T_NOT); + + $not = true; + } + + $conditionalPrimary = $this->ConditionalPrimary(); + + // Phase 1 AST optimization: Prevent AST\ConditionalFactor + // if only one AST\ConditionalPrimary is defined + if (! $not) { + return $conditionalPrimary; + } + + return new AST\ConditionalFactor($conditionalPrimary, $not); + } + + /** + * ConditionalPrimary ::= SimpleConditionalExpression | "(" ConditionalExpression ")" + */ + public function ConditionalPrimary(): AST\ConditionalPrimary + { + $condPrimary = new AST\ConditionalPrimary(); + + if (! $this->lexer->isNextToken(TokenType::T_OPEN_PARENTHESIS)) { + $condPrimary->simpleConditionalExpression = $this->SimpleConditionalExpression(); + + return $condPrimary; + } + + // Peek beyond the matching closing parenthesis ')' + $peek = $this->peekBeyondClosingParenthesis(); + + if ( + $peek !== null && ( + in_array($peek->value, ['=', '<', '<=', '<>', '>', '>=', '!='], true) || + in_array($peek->type, [TokenType::T_NOT, TokenType::T_BETWEEN, TokenType::T_LIKE, TokenType::T_IN, TokenType::T_IS, TokenType::T_EXISTS], true) || + $this->isMathOperator($peek) + ) + ) { + $condPrimary->simpleConditionalExpression = $this->SimpleConditionalExpression(); + + return $condPrimary; + } + + $this->match(TokenType::T_OPEN_PARENTHESIS); + $condPrimary->conditionalExpression = $this->ConditionalExpression(); + $this->match(TokenType::T_CLOSE_PARENTHESIS); + + return $condPrimary; + } + + /** + * SimpleConditionalExpression ::= + * ComparisonExpression | BetweenExpression | LikeExpression | + * InExpression | NullComparisonExpression | ExistsExpression | + * EmptyCollectionComparisonExpression | CollectionMemberExpression | + * InstanceOfExpression + */ + public function SimpleConditionalExpression(): AST\ExistsExpression|AST\BetweenExpression|AST\LikeExpression|AST\InListExpression|AST\InSubselectExpression|AST\InstanceOfExpression|AST\CollectionMemberExpression|AST\NullComparisonExpression|AST\EmptyCollectionComparisonExpression|AST\ComparisonExpression + { + assert($this->lexer->lookahead !== null); + if ($this->lexer->isNextToken(TokenType::T_EXISTS)) { + return $this->ExistsExpression(); + } + + $token = $this->lexer->lookahead; + $peek = $this->lexer->glimpse(); + $lookahead = $token; + + if ($this->lexer->isNextToken(TokenType::T_NOT)) { + $token = $this->lexer->glimpse(); + } + + assert($token !== null); + assert($peek !== null); + if ($token->type === TokenType::T_IDENTIFIER || $token->type === TokenType::T_INPUT_PARAMETER || $this->isFunction()) { + // Peek beyond the matching closing parenthesis. + $beyond = $this->lexer->peek(); + + switch ($peek->value) { + case '(': + // Peeks beyond the matched closing parenthesis. + $token = $this->peekBeyondClosingParenthesis(false); + assert($token !== null); + + if ($token->type === TokenType::T_NOT) { + $token = $this->lexer->peek(); + assert($token !== null); + } + + if ($token->type === TokenType::T_IS) { + $lookahead = $this->lexer->peek(); + } + + break; + + default: + // Peek beyond the PathExpression or InputParameter. + $token = $beyond; + + while ($token->value === '.') { + $this->lexer->peek(); + + $token = $this->lexer->peek(); + assert($token !== null); + } + + // Also peek beyond a NOT if there is one. + assert($token !== null); + if ($token->type === TokenType::T_NOT) { + $token = $this->lexer->peek(); + assert($token !== null); + } + + // We need to go even further in case of IS (differentiate between NULL and EMPTY) + $lookahead = $this->lexer->peek(); + } + + assert($lookahead !== null); + // Also peek beyond a NOT if there is one. + if ($lookahead->type === TokenType::T_NOT) { + $lookahead = $this->lexer->peek(); + } + + $this->lexer->resetPeek(); + } + + if ($token->type === TokenType::T_BETWEEN) { + return $this->BetweenExpression(); + } + + if ($token->type === TokenType::T_LIKE) { + return $this->LikeExpression(); + } + + if ($token->type === TokenType::T_IN) { + return $this->InExpression(); + } + + if ($token->type === TokenType::T_INSTANCE) { + return $this->InstanceOfExpression(); + } + + if ($token->type === TokenType::T_MEMBER) { + return $this->CollectionMemberExpression(); + } + + assert($lookahead !== null); + if ($token->type === TokenType::T_IS && $lookahead->type === TokenType::T_NULL) { + return $this->NullComparisonExpression(); + } + + if ($token->type === TokenType::T_IS && $lookahead->type === TokenType::T_EMPTY) { + return $this->EmptyCollectionComparisonExpression(); + } + + return $this->ComparisonExpression(); + } + + /** + * EmptyCollectionComparisonExpression ::= CollectionValuedPathExpression "IS" ["NOT"] "EMPTY" + */ + public function EmptyCollectionComparisonExpression(): AST\EmptyCollectionComparisonExpression + { + $pathExpression = $this->CollectionValuedPathExpression(); + $this->match(TokenType::T_IS); + + $not = false; + if ($this->lexer->isNextToken(TokenType::T_NOT)) { + $this->match(TokenType::T_NOT); + $not = true; + } + + $this->match(TokenType::T_EMPTY); + + return new AST\EmptyCollectionComparisonExpression( + $pathExpression, + $not, + ); + } + + /** + * CollectionMemberExpression ::= EntityExpression ["NOT"] "MEMBER" ["OF"] CollectionValuedPathExpression + * + * EntityExpression ::= SingleValuedAssociationPathExpression | SimpleEntityExpression + * SimpleEntityExpression ::= IdentificationVariable | InputParameter + */ + public function CollectionMemberExpression(): AST\CollectionMemberExpression + { + $not = false; + $entityExpr = $this->EntityExpression(); + + if ($this->lexer->isNextToken(TokenType::T_NOT)) { + $this->match(TokenType::T_NOT); + + $not = true; + } + + $this->match(TokenType::T_MEMBER); + + if ($this->lexer->isNextToken(TokenType::T_OF)) { + $this->match(TokenType::T_OF); + } + + return new AST\CollectionMemberExpression( + $entityExpr, + $this->CollectionValuedPathExpression(), + $not, + ); + } + + /** + * Literal ::= string | char | integer | float | boolean + */ + public function Literal(): AST\Literal + { + assert($this->lexer->lookahead !== null); + assert($this->lexer->token !== null); + switch ($this->lexer->lookahead->type) { + case TokenType::T_STRING: + $this->match(TokenType::T_STRING); + + return new AST\Literal(AST\Literal::STRING, $this->lexer->token->value); + + case TokenType::T_INTEGER: + case TokenType::T_FLOAT: + $this->match( + $this->lexer->isNextToken(TokenType::T_INTEGER) ? TokenType::T_INTEGER : TokenType::T_FLOAT, + ); + + return new AST\Literal(AST\Literal::NUMERIC, $this->lexer->token->value); + + case TokenType::T_TRUE: + case TokenType::T_FALSE: + $this->match( + $this->lexer->isNextToken(TokenType::T_TRUE) ? TokenType::T_TRUE : TokenType::T_FALSE, + ); + + return new AST\Literal(AST\Literal::BOOLEAN, $this->lexer->token->value); + + default: + $this->syntaxError('Literal'); + } + } + + /** + * InParameter ::= ArithmeticExpression | InputParameter + */ + public function InParameter(): AST\InputParameter|AST\ArithmeticExpression + { + assert($this->lexer->lookahead !== null); + if ($this->lexer->lookahead->type === TokenType::T_INPUT_PARAMETER) { + return $this->InputParameter(); + } + + return $this->ArithmeticExpression(); + } + + /** + * InputParameter ::= PositionalParameter | NamedParameter + */ + public function InputParameter(): AST\InputParameter + { + $this->match(TokenType::T_INPUT_PARAMETER); + assert($this->lexer->token !== null); + + return new AST\InputParameter($this->lexer->token->value); + } + + /** + * ArithmeticExpression ::= SimpleArithmeticExpression | "(" Subselect ")" + */ + public function ArithmeticExpression(): AST\ArithmeticExpression + { + $expr = new AST\ArithmeticExpression(); + + if ($this->lexer->isNextToken(TokenType::T_OPEN_PARENTHESIS)) { + $peek = $this->lexer->glimpse(); + assert($peek !== null); + + if ($peek->type === TokenType::T_SELECT) { + $this->match(TokenType::T_OPEN_PARENTHESIS); + $expr->subselect = $this->Subselect(); + $this->match(TokenType::T_CLOSE_PARENTHESIS); + + return $expr; + } + } + + $expr->simpleArithmeticExpression = $this->SimpleArithmeticExpression(); + + return $expr; + } + + /** + * SimpleArithmeticExpression ::= ArithmeticTerm {("+" | "-") ArithmeticTerm}* + */ + public function SimpleArithmeticExpression(): AST\Node|string + { + $terms = []; + $terms[] = $this->ArithmeticTerm(); + + while (($isPlus = $this->lexer->isNextToken(TokenType::T_PLUS)) || $this->lexer->isNextToken(TokenType::T_MINUS)) { + $this->match($isPlus ? TokenType::T_PLUS : TokenType::T_MINUS); + + assert($this->lexer->token !== null); + $terms[] = $this->lexer->token->value; + $terms[] = $this->ArithmeticTerm(); + } + + // Phase 1 AST optimization: Prevent AST\SimpleArithmeticExpression + // if only one AST\ArithmeticTerm is defined + if (count($terms) === 1) { + return $terms[0]; + } + + return new AST\SimpleArithmeticExpression($terms); + } + + /** + * ArithmeticTerm ::= ArithmeticFactor {("*" | "/") ArithmeticFactor}* + */ + public function ArithmeticTerm(): AST\Node|string + { + $factors = []; + $factors[] = $this->ArithmeticFactor(); + + while (($isMult = $this->lexer->isNextToken(TokenType::T_MULTIPLY)) || $this->lexer->isNextToken(TokenType::T_DIVIDE)) { + $this->match($isMult ? TokenType::T_MULTIPLY : TokenType::T_DIVIDE); + + assert($this->lexer->token !== null); + $factors[] = $this->lexer->token->value; + $factors[] = $this->ArithmeticFactor(); + } + + // Phase 1 AST optimization: Prevent AST\ArithmeticTerm + // if only one AST\ArithmeticFactor is defined + if (count($factors) === 1) { + return $factors[0]; + } + + return new AST\ArithmeticTerm($factors); + } + + /** + * ArithmeticFactor ::= [("+" | "-")] ArithmeticPrimary + */ + public function ArithmeticFactor(): AST\Node|string|AST\ArithmeticFactor + { + $sign = null; + + $isPlus = $this->lexer->isNextToken(TokenType::T_PLUS); + if ($isPlus || $this->lexer->isNextToken(TokenType::T_MINUS)) { + $this->match($isPlus ? TokenType::T_PLUS : TokenType::T_MINUS); + $sign = $isPlus; + } + + $primary = $this->ArithmeticPrimary(); + + // Phase 1 AST optimization: Prevent AST\ArithmeticFactor + // if only one AST\ArithmeticPrimary is defined + if ($sign === null) { + return $primary; + } + + return new AST\ArithmeticFactor($primary, $sign); + } + + /** + * ArithmeticPrimary ::= SingleValuedPathExpression | Literal | ParenthesisExpression + * | FunctionsReturningNumerics | AggregateExpression | FunctionsReturningStrings + * | FunctionsReturningDatetime | IdentificationVariable | ResultVariable + * | InputParameter | CaseExpression + */ + public function ArithmeticPrimary(): AST\Node|string + { + if ($this->lexer->isNextToken(TokenType::T_OPEN_PARENTHESIS)) { + $this->match(TokenType::T_OPEN_PARENTHESIS); + + $expr = $this->SimpleArithmeticExpression(); + + $this->match(TokenType::T_CLOSE_PARENTHESIS); + + return new AST\ParenthesisExpression($expr); + } + + if ($this->lexer->lookahead === null) { + $this->syntaxError('ArithmeticPrimary'); + } + + switch ($this->lexer->lookahead->type) { + case TokenType::T_COALESCE: + case TokenType::T_NULLIF: + case TokenType::T_CASE: + return $this->CaseExpression(); + + case TokenType::T_IDENTIFIER: + $peek = $this->lexer->glimpse(); + + if ($peek !== null && $peek->value === '(') { + return $this->FunctionDeclaration(); + } + + if ($peek !== null && $peek->value === '.') { + return $this->SingleValuedPathExpression(); + } + + if (isset($this->queryComponents[$this->lexer->lookahead->value]['resultVariable'])) { + return $this->ResultVariable(); + } + + return $this->StateFieldPathExpression(); + + case TokenType::T_INPUT_PARAMETER: + return $this->InputParameter(); + + default: + $peek = $this->lexer->glimpse(); + + if ($peek !== null && $peek->value === '(') { + return $this->FunctionDeclaration(); + } + + return $this->Literal(); + } + } + + /** + * StringExpression ::= StringPrimary | ResultVariable | "(" Subselect ")" + */ + public function StringExpression(): AST\Subselect|AST\Node|string + { + $peek = $this->lexer->glimpse(); + assert($peek !== null); + + // Subselect + if ($this->lexer->isNextToken(TokenType::T_OPEN_PARENTHESIS) && $peek->type === TokenType::T_SELECT) { + $this->match(TokenType::T_OPEN_PARENTHESIS); + $expr = $this->Subselect(); + $this->match(TokenType::T_CLOSE_PARENTHESIS); + + return $expr; + } + + assert($this->lexer->lookahead !== null); + // ResultVariable (string) + if ( + $this->lexer->isNextToken(TokenType::T_IDENTIFIER) && + isset($this->queryComponents[$this->lexer->lookahead->value]['resultVariable']) + ) { + return $this->ResultVariable(); + } + + return $this->StringPrimary(); + } + + /** + * StringPrimary ::= StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression | CaseExpression + */ + public function StringPrimary(): AST\Node + { + assert($this->lexer->lookahead !== null); + $lookaheadType = $this->lexer->lookahead->type; + + switch ($lookaheadType) { + case TokenType::T_IDENTIFIER: + $peek = $this->lexer->glimpse(); + assert($peek !== null); + + if ($peek->value === '.') { + return $this->StateFieldPathExpression(); + } + + if ($peek->value === '(') { + // do NOT directly go to FunctionsReturningString() because it doesn't check for custom functions. + return $this->FunctionDeclaration(); + } + + $this->syntaxError("'.' or '('"); + break; + + case TokenType::T_STRING: + $this->match(TokenType::T_STRING); + assert($this->lexer->token !== null); + + return new AST\Literal(AST\Literal::STRING, $this->lexer->token->value); + + case TokenType::T_INPUT_PARAMETER: + return $this->InputParameter(); + + case TokenType::T_CASE: + case TokenType::T_COALESCE: + case TokenType::T_NULLIF: + return $this->CaseExpression(); + + default: + assert($lookaheadType !== null); + if ($this->isAggregateFunction($lookaheadType)) { + return $this->AggregateExpression(); + } + } + + $this->syntaxError( + 'StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression', + ); + } + + /** + * EntityExpression ::= SingleValuedAssociationPathExpression | SimpleEntityExpression + */ + public function EntityExpression(): AST\InputParameter|AST\PathExpression + { + $glimpse = $this->lexer->glimpse(); + assert($glimpse !== null); + + if ($this->lexer->isNextToken(TokenType::T_IDENTIFIER) && $glimpse->value === '.') { + return $this->SingleValuedAssociationPathExpression(); + } + + return $this->SimpleEntityExpression(); + } + + /** + * SimpleEntityExpression ::= IdentificationVariable | InputParameter + */ + public function SimpleEntityExpression(): AST\InputParameter|AST\PathExpression + { + if ($this->lexer->isNextToken(TokenType::T_INPUT_PARAMETER)) { + return $this->InputParameter(); + } + + return $this->StateFieldPathExpression(); + } + + /** + * AggregateExpression ::= + * ("AVG" | "MAX" | "MIN" | "SUM" | "COUNT") "(" ["DISTINCT"] SimpleArithmeticExpression ")" + */ + public function AggregateExpression(): AST\AggregateExpression + { + assert($this->lexer->lookahead !== null); + $lookaheadType = $this->lexer->lookahead->type; + $isDistinct = false; + + if (! in_array($lookaheadType, [TokenType::T_COUNT, TokenType::T_AVG, TokenType::T_MAX, TokenType::T_MIN, TokenType::T_SUM], true)) { + $this->syntaxError('One of: MAX, MIN, AVG, SUM, COUNT'); + } + + $this->match($lookaheadType); + assert($this->lexer->token !== null); + $functionName = $this->lexer->token->value; + $this->match(TokenType::T_OPEN_PARENTHESIS); + + if ($this->lexer->isNextToken(TokenType::T_DISTINCT)) { + $this->match(TokenType::T_DISTINCT); + $isDistinct = true; + } + + $pathExp = $this->SimpleArithmeticExpression(); + + $this->match(TokenType::T_CLOSE_PARENTHESIS); + + return new AST\AggregateExpression($functionName, $pathExp, $isDistinct); + } + + /** + * QuantifiedExpression ::= ("ALL" | "ANY" | "SOME") "(" Subselect ")" + */ + public function QuantifiedExpression(): AST\QuantifiedExpression + { + assert($this->lexer->lookahead !== null); + $lookaheadType = $this->lexer->lookahead->type; + $value = $this->lexer->lookahead->value; + + if (! in_array($lookaheadType, [TokenType::T_ALL, TokenType::T_ANY, TokenType::T_SOME], true)) { + $this->syntaxError('ALL, ANY or SOME'); + } + + $this->match($lookaheadType); + $this->match(TokenType::T_OPEN_PARENTHESIS); + + $qExpr = new AST\QuantifiedExpression($this->Subselect()); + $qExpr->type = $value; + + $this->match(TokenType::T_CLOSE_PARENTHESIS); + + return $qExpr; + } + + /** + * BetweenExpression ::= ArithmeticExpression ["NOT"] "BETWEEN" ArithmeticExpression "AND" ArithmeticExpression + */ + public function BetweenExpression(): AST\BetweenExpression + { + $not = false; + $arithExpr1 = $this->ArithmeticExpression(); + + if ($this->lexer->isNextToken(TokenType::T_NOT)) { + $this->match(TokenType::T_NOT); + $not = true; + } + + $this->match(TokenType::T_BETWEEN); + $arithExpr2 = $this->ArithmeticExpression(); + $this->match(TokenType::T_AND); + $arithExpr3 = $this->ArithmeticExpression(); + + return new AST\BetweenExpression($arithExpr1, $arithExpr2, $arithExpr3, $not); + } + + /** + * ComparisonExpression ::= ArithmeticExpression ComparisonOperator ( QuantifiedExpression | ArithmeticExpression ) + */ + public function ComparisonExpression(): AST\ComparisonExpression + { + $this->lexer->glimpse(); + + $leftExpr = $this->ArithmeticExpression(); + $operator = $this->ComparisonOperator(); + $rightExpr = $this->isNextAllAnySome() + ? $this->QuantifiedExpression() + : $this->ArithmeticExpression(); + + return new AST\ComparisonExpression($leftExpr, $operator, $rightExpr); + } + + /** + * InExpression ::= SingleValuedPathExpression ["NOT"] "IN" "(" (InParameter {"," InParameter}* | Subselect) ")" + */ + public function InExpression(): AST\InListExpression|AST\InSubselectExpression + { + $expression = $this->ArithmeticExpression(); + + $not = false; + if ($this->lexer->isNextToken(TokenType::T_NOT)) { + $this->match(TokenType::T_NOT); + $not = true; + } + + $this->match(TokenType::T_IN); + $this->match(TokenType::T_OPEN_PARENTHESIS); + + if ($this->lexer->isNextToken(TokenType::T_SELECT)) { + $inExpression = new AST\InSubselectExpression( + $expression, + $this->Subselect(), + $not, + ); + } else { + $literals = [$this->InParameter()]; + + while ($this->lexer->isNextToken(TokenType::T_COMMA)) { + $this->match(TokenType::T_COMMA); + $literals[] = $this->InParameter(); + } + + $inExpression = new AST\InListExpression( + $expression, + $literals, + $not, + ); + } + + $this->match(TokenType::T_CLOSE_PARENTHESIS); + + return $inExpression; + } + + /** + * InstanceOfExpression ::= IdentificationVariable ["NOT"] "INSTANCE" ["OF"] (InstanceOfParameter | "(" InstanceOfParameter {"," InstanceOfParameter}* ")") + */ + public function InstanceOfExpression(): AST\InstanceOfExpression + { + $identificationVariable = $this->IdentificationVariable(); + + $not = false; + if ($this->lexer->isNextToken(TokenType::T_NOT)) { + $this->match(TokenType::T_NOT); + $not = true; + } + + $this->match(TokenType::T_INSTANCE); + $this->match(TokenType::T_OF); + + $exprValues = $this->lexer->isNextToken(TokenType::T_OPEN_PARENTHESIS) + ? $this->InstanceOfParameterList() + : [$this->InstanceOfParameter()]; + + return new AST\InstanceOfExpression( + $identificationVariable, + $exprValues, + $not, + ); + } + + /** @return non-empty-list */ + public function InstanceOfParameterList(): array + { + $this->match(TokenType::T_OPEN_PARENTHESIS); + + $exprValues = [$this->InstanceOfParameter()]; + + while ($this->lexer->isNextToken(TokenType::T_COMMA)) { + $this->match(TokenType::T_COMMA); + + $exprValues[] = $this->InstanceOfParameter(); + } + + $this->match(TokenType::T_CLOSE_PARENTHESIS); + + return $exprValues; + } + + /** + * InstanceOfParameter ::= AbstractSchemaName | InputParameter + */ + public function InstanceOfParameter(): AST\InputParameter|string + { + if ($this->lexer->isNextToken(TokenType::T_INPUT_PARAMETER)) { + $this->match(TokenType::T_INPUT_PARAMETER); + assert($this->lexer->token !== null); + + return new AST\InputParameter($this->lexer->token->value); + } + + $abstractSchemaName = $this->AbstractSchemaName(); + + $this->validateAbstractSchemaName($abstractSchemaName); + + return $abstractSchemaName; + } + + /** + * LikeExpression ::= StringExpression ["NOT"] "LIKE" StringPrimary ["ESCAPE" char] + */ + public function LikeExpression(): AST\LikeExpression + { + $stringExpr = $this->StringExpression(); + $not = false; + + if ($this->lexer->isNextToken(TokenType::T_NOT)) { + $this->match(TokenType::T_NOT); + $not = true; + } + + $this->match(TokenType::T_LIKE); + + if ($this->lexer->isNextToken(TokenType::T_INPUT_PARAMETER)) { + $this->match(TokenType::T_INPUT_PARAMETER); + assert($this->lexer->token !== null); + $stringPattern = new AST\InputParameter($this->lexer->token->value); + } else { + $stringPattern = $this->StringPrimary(); + } + + $escapeChar = null; + + if ($this->lexer->lookahead !== null && $this->lexer->lookahead->type === TokenType::T_ESCAPE) { + $this->match(TokenType::T_ESCAPE); + $this->match(TokenType::T_STRING); + assert($this->lexer->token !== null); + + $escapeChar = new AST\Literal(AST\Literal::STRING, $this->lexer->token->value); + } + + return new AST\LikeExpression($stringExpr, $stringPattern, $escapeChar, $not); + } + + /** + * NullComparisonExpression ::= (InputParameter | NullIfExpression | CoalesceExpression | AggregateExpression | FunctionDeclaration | IdentificationVariable | SingleValuedPathExpression | ResultVariable) "IS" ["NOT"] "NULL" + */ + public function NullComparisonExpression(): AST\NullComparisonExpression + { + switch (true) { + case $this->lexer->isNextToken(TokenType::T_INPUT_PARAMETER): + $this->match(TokenType::T_INPUT_PARAMETER); + assert($this->lexer->token !== null); + + $expr = new AST\InputParameter($this->lexer->token->value); + break; + + case $this->lexer->isNextToken(TokenType::T_NULLIF): + $expr = $this->NullIfExpression(); + break; + + case $this->lexer->isNextToken(TokenType::T_COALESCE): + $expr = $this->CoalesceExpression(); + break; + + case $this->isFunction(): + $expr = $this->FunctionDeclaration(); + break; + + default: + // We need to check if we are in a IdentificationVariable or SingleValuedPathExpression + $glimpse = $this->lexer->glimpse(); + assert($glimpse !== null); + + if ($glimpse->type === TokenType::T_DOT) { + $expr = $this->SingleValuedPathExpression(); + + // Leave switch statement + break; + } + + assert($this->lexer->lookahead !== null); + $lookaheadValue = $this->lexer->lookahead->value; + + // Validate existing component + if (! isset($this->queryComponents[$lookaheadValue])) { + $this->semanticalError('Cannot add having condition on undefined result variable.'); + } + + // Validate SingleValuedPathExpression (ie.: "product") + if (isset($this->queryComponents[$lookaheadValue]['metadata'])) { + $expr = $this->SingleValuedPathExpression(); + break; + } + + // Validating ResultVariable + if (! isset($this->queryComponents[$lookaheadValue]['resultVariable'])) { + $this->semanticalError('Cannot add having condition on a non result variable.'); + } + + $expr = $this->ResultVariable(); + break; + } + + $this->match(TokenType::T_IS); + + $not = false; + if ($this->lexer->isNextToken(TokenType::T_NOT)) { + $this->match(TokenType::T_NOT); + + $not = true; + } + + $this->match(TokenType::T_NULL); + + return new AST\NullComparisonExpression($expr, $not); + } + + /** + * ExistsExpression ::= ["NOT"] "EXISTS" "(" Subselect ")" + */ + public function ExistsExpression(): AST\ExistsExpression + { + $not = false; + + if ($this->lexer->isNextToken(TokenType::T_NOT)) { + $this->match(TokenType::T_NOT); + $not = true; + } + + $this->match(TokenType::T_EXISTS); + $this->match(TokenType::T_OPEN_PARENTHESIS); + + $subselect = $this->Subselect(); + + $this->match(TokenType::T_CLOSE_PARENTHESIS); + + return new AST\ExistsExpression($subselect, $not); + } + + /** + * ComparisonOperator ::= "=" | "<" | "<=" | "<>" | ">" | ">=" | "!=" + */ + public function ComparisonOperator(): string + { + assert($this->lexer->lookahead !== null); + switch ($this->lexer->lookahead->value) { + case '=': + $this->match(TokenType::T_EQUALS); + + return '='; + + case '<': + $this->match(TokenType::T_LOWER_THAN); + $operator = '<'; + + if ($this->lexer->isNextToken(TokenType::T_EQUALS)) { + $this->match(TokenType::T_EQUALS); + $operator .= '='; + } elseif ($this->lexer->isNextToken(TokenType::T_GREATER_THAN)) { + $this->match(TokenType::T_GREATER_THAN); + $operator .= '>'; + } + + return $operator; + + case '>': + $this->match(TokenType::T_GREATER_THAN); + $operator = '>'; + + if ($this->lexer->isNextToken(TokenType::T_EQUALS)) { + $this->match(TokenType::T_EQUALS); + $operator .= '='; + } + + return $operator; + + case '!': + $this->match(TokenType::T_NEGATE); + $this->match(TokenType::T_EQUALS); + + return '<>'; + + default: + $this->syntaxError('=, <, <=, <>, >, >=, !='); + } + } + + /** + * FunctionDeclaration ::= FunctionsReturningStrings | FunctionsReturningNumerics | FunctionsReturningDatetime + */ + public function FunctionDeclaration(): Functions\FunctionNode + { + assert($this->lexer->lookahead !== null); + $token = $this->lexer->lookahead; + $funcName = strtolower($token->value); + + $customFunctionDeclaration = $this->CustomFunctionDeclaration(); + + // Check for custom functions functions first! + switch (true) { + case $customFunctionDeclaration !== null: + return $customFunctionDeclaration; + + case isset(self::$stringFunctions[$funcName]): + return $this->FunctionsReturningStrings(); + + case isset(self::$numericFunctions[$funcName]): + return $this->FunctionsReturningNumerics(); + + case isset(self::$datetimeFunctions[$funcName]): + return $this->FunctionsReturningDatetime(); + + default: + $this->syntaxError('known function', $token); + } + } + + /** + * Helper function for FunctionDeclaration grammar rule. + */ + private function CustomFunctionDeclaration(): Functions\FunctionNode|null + { + assert($this->lexer->lookahead !== null); + $token = $this->lexer->lookahead; + $funcName = strtolower($token->value); + + // Check for custom functions afterwards + $config = $this->em->getConfiguration(); + + return match (true) { + $config->getCustomStringFunction($funcName) !== null => $this->CustomFunctionsReturningStrings(), + $config->getCustomNumericFunction($funcName) !== null => $this->CustomFunctionsReturningNumerics(), + $config->getCustomDatetimeFunction($funcName) !== null => $this->CustomFunctionsReturningDatetime(), + default => null, + }; + } + + /** + * FunctionsReturningNumerics ::= + * "LENGTH" "(" StringPrimary ")" | + * "LOCATE" "(" StringPrimary "," StringPrimary ["," SimpleArithmeticExpression]")" | + * "ABS" "(" SimpleArithmeticExpression ")" | + * "SQRT" "(" SimpleArithmeticExpression ")" | + * "MOD" "(" SimpleArithmeticExpression "," SimpleArithmeticExpression ")" | + * "SIZE" "(" CollectionValuedPathExpression ")" | + * "DATE_DIFF" "(" ArithmeticPrimary "," ArithmeticPrimary ")" | + * "BIT_AND" "(" ArithmeticPrimary "," ArithmeticPrimary ")" | + * "BIT_OR" "(" ArithmeticPrimary "," ArithmeticPrimary ")" + */ + public function FunctionsReturningNumerics(): AST\Functions\FunctionNode + { + assert($this->lexer->lookahead !== null); + $funcNameLower = strtolower($this->lexer->lookahead->value); + $funcClass = self::$numericFunctions[$funcNameLower]; + + $function = new $funcClass($funcNameLower); + $function->parse($this); + + return $function; + } + + public function CustomFunctionsReturningNumerics(): AST\Functions\FunctionNode + { + assert($this->lexer->lookahead !== null); + // getCustomNumericFunction is case-insensitive + $functionName = strtolower($this->lexer->lookahead->value); + $functionClass = $this->em->getConfiguration()->getCustomNumericFunction($functionName); + + assert($functionClass !== null); + + if (is_string($functionClass)) { + $function = new $functionClass($functionName); + assert($function instanceof AST\Functions\FunctionNode); + } else { + $function = $functionClass($functionName); + } + + $function->parse($this); + + return $function; + } + + /** + * FunctionsReturningDatetime ::= + * "CURRENT_DATE" | + * "CURRENT_TIME" | + * "CURRENT_TIMESTAMP" | + * "DATE_ADD" "(" ArithmeticPrimary "," ArithmeticPrimary "," StringPrimary ")" | + * "DATE_SUB" "(" ArithmeticPrimary "," ArithmeticPrimary "," StringPrimary ")" + */ + public function FunctionsReturningDatetime(): AST\Functions\FunctionNode + { + assert($this->lexer->lookahead !== null); + $funcNameLower = strtolower($this->lexer->lookahead->value); + $funcClass = self::$datetimeFunctions[$funcNameLower]; + + $function = new $funcClass($funcNameLower); + $function->parse($this); + + return $function; + } + + public function CustomFunctionsReturningDatetime(): AST\Functions\FunctionNode + { + assert($this->lexer->lookahead !== null); + // getCustomDatetimeFunction is case-insensitive + $functionName = $this->lexer->lookahead->value; + $functionClass = $this->em->getConfiguration()->getCustomDatetimeFunction($functionName); + + assert($functionClass !== null); + + $function = is_string($functionClass) + ? new $functionClass($functionName) + : $functionClass($functionName); + + $function->parse($this); + + return $function; + } + + /** + * FunctionsReturningStrings ::= + * "CONCAT" "(" StringPrimary "," StringPrimary {"," StringPrimary}* ")" | + * "SUBSTRING" "(" StringPrimary "," SimpleArithmeticExpression "," SimpleArithmeticExpression ")" | + * "TRIM" "(" [["LEADING" | "TRAILING" | "BOTH"] [char] "FROM"] StringPrimary ")" | + * "LOWER" "(" StringPrimary ")" | + * "UPPER" "(" StringPrimary ")" | + * "IDENTITY" "(" SingleValuedAssociationPathExpression {"," string} ")" + */ + public function FunctionsReturningStrings(): AST\Functions\FunctionNode + { + assert($this->lexer->lookahead !== null); + $funcNameLower = strtolower($this->lexer->lookahead->value); + $funcClass = self::$stringFunctions[$funcNameLower]; + + $function = new $funcClass($funcNameLower); + $function->parse($this); + + return $function; + } + + public function CustomFunctionsReturningStrings(): Functions\FunctionNode + { + assert($this->lexer->lookahead !== null); + // getCustomStringFunction is case-insensitive + $functionName = $this->lexer->lookahead->value; + $functionClass = $this->em->getConfiguration()->getCustomStringFunction($functionName); + + assert($functionClass !== null); + + $function = is_string($functionClass) + ? new $functionClass($functionName) + : $functionClass($functionName); + + $function->parse($this); + + return $function; + } + + private function getMetadataForDqlAlias(string $dqlAlias): ClassMetadata + { + if (! isset($this->queryComponents[$dqlAlias]['metadata'])) { + throw new LogicException(sprintf('No metadata for DQL alias: %s', $dqlAlias)); + } + + return $this->queryComponents[$dqlAlias]['metadata']; + } +} diff --git a/tests/Tests/ORM/Query/SelectSqlGenerationTest.php b/tests/Tests/ORM/Query/SelectSqlGenerationTest.php new file mode 100644 index 0000000..0678fc5 --- /dev/null +++ b/tests/Tests/ORM/Query/SelectSqlGenerationTest.php @@ -0,0 +1,2208 @@ +entityManager = $this->getTestEntityManager(); + } + + /** + * Assert a valid SQL generation. + */ + public function assertSqlGeneration( + string $dqlToBeTested, + string $sqlToBeConfirmed, + array $queryHints = [], + array $queryParams = [], + ): void { + $query = $this->entityManager->createQuery($dqlToBeTested); + $query->setHydrationMode($this->hydrationMode); + + foreach ($queryParams as $name => $value) { + $query->setParameter($name, $value); + } + + $query->useQueryCache(false); + + foreach ($queryHints as $name => $value) { + $query->setHint($name, $value); + } + + $sqlGenerated = $query->getSQL(); + + parent::assertEquals( + $sqlToBeConfirmed, + $sqlGenerated, + ); + + $query->free(); + } + + /** + * Asser an invalid SQL generation. + */ + public function assertInvalidSqlGeneration( + string $dqlToBeTested, + string $expectedException, + array $queryHints = [], + array $queryParams = [], + ): void { + $this->expectException($expectedException); + + $query = $this->entityManager->createQuery($dqlToBeTested); + + foreach ($queryParams as $name => $value) { + $query->setParameter($name, $value); + } + + $query->useQueryCache(false); + + foreach ($queryHints as $name => $value) { + $query->setHint($name, $value); + } + + $sql = $query->getSql(); + $query->free(); + + // If we reached here, test failed + self::fail($sql); + } + + #[Group('DDC-3697')] + public function testJoinWithRangeVariablePutsConditionIntoSqlWhereClause(): void + { + $this->assertSqlGeneration( + 'SELECT c.id FROM Doctrine\Tests\Models\Company\CompanyPerson c JOIN Doctrine\Tests\Models\Company\CompanyPerson r WHERE c.spouse = r AND r.id = 42', + 'SELECT c0_.id AS id_0 FROM company_persons c0_ LEFT JOIN company_managers c1_ ON c0_.id = c1_.id LEFT JOIN company_employees c2_ ON c0_.id = c2_.id INNER JOIN company_persons c3_ LEFT JOIN company_managers c4_ ON c3_.id = c4_.id LEFT JOIN company_employees c5_ ON c3_.id = c5_.id WHERE c0_.spouse_id = c3_.id AND c3_.id = 42', + ); + } + + #[Group('DDC-3697')] + public function testJoinWithRangeVariableAndInheritancePutsConditionIntoSqlWhereClause(): void + { + /* + * Basically like the previous test, but this time load data for the inherited objects as well. + * The important thing is that the ON clauses in LEFT JOINs only contain the conditions necessary to join the appropriate inheritance table + * whereas the filtering condition must remain in the SQL WHERE clause. + */ + $this->assertSqlGeneration( + 'SELECT c.id FROM Doctrine\Tests\Models\Company\CompanyPerson c JOIN Doctrine\Tests\Models\Company\CompanyPerson r WHERE c.spouse = r AND r.id = 42', + 'SELECT c0_.id AS id_0 FROM company_persons c0_ LEFT JOIN company_managers c1_ ON c0_.id = c1_.id LEFT JOIN company_employees c2_ ON c0_.id = c2_.id INNER JOIN company_persons c3_ LEFT JOIN company_managers c4_ ON c3_.id = c4_.id LEFT JOIN company_employees c5_ ON c3_.id = c5_.id WHERE c0_.spouse_id = c3_.id AND c3_.id = 42', + ); + } + + public function testSupportsSelectForAllFields(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_', + ); + } + + public function testSupportsSelectForOneField(): void + { + $this->assertSqlGeneration( + 'SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u', + 'SELECT c0_.id AS id_0 FROM cms_users c0_', + ); + } + + public function testSupportsSelectForOneNestedField(): void + { + $this->assertSqlGeneration( + 'SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsArticle a JOIN a.user u', + 'SELECT c0_.id AS id_0 FROM cms_articles c1_ INNER JOIN cms_users c0_ ON c1_.user_id = c0_.id', + ); + } + + public function testSupportsSelectForAllNestedField(): void + { + $this->assertSqlGeneration( + 'SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a JOIN a.user u ORDER BY u.name ASC', + 'SELECT c0_.id AS id_0, c0_.topic AS topic_1, c0_.text AS text_2, c0_.version AS version_3, c0_.user_id AS user_id_4 FROM cms_articles c0_ INNER JOIN cms_users c1_ ON c0_.user_id = c1_.id ORDER BY c1_.name ASC', + ); + } + + public function testNotExistsExpression(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE NOT EXISTS (SELECT p.phonenumber FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.phonenumber = 1234)', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE NOT EXISTS (SELECT c1_.phonenumber FROM cms_phonenumbers c1_ WHERE c1_.phonenumber = 1234)', + ); + } + + public function testSupportsSelectForMultipleColumnsOfASingleComponent(): void + { + $this->assertSqlGeneration( + 'SELECT u.username, u.name FROM Doctrine\Tests\Models\CMS\CmsUser u', + 'SELECT c0_.username AS username_0, c0_.name AS name_1 FROM cms_users c0_', + ); + } + + public function testSupportsSelectUsingMultipleFromComponents(): void + { + $this->assertSqlGeneration( + 'SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE u = p.user', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c1_.phonenumber AS phonenumber_4, c0_.email_id AS email_id_5, c1_.user_id AS user_id_6 FROM cms_users c0_, cms_phonenumbers c1_ WHERE c0_.id = c1_.user_id', + ); + } + + public function testSupportsJoinOnMultipleComponents(): void + { + $this->assertSqlGeneration( + 'SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN Doctrine\Tests\Models\CMS\CmsPhonenumber p ON u = p.user', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c1_.phonenumber AS phonenumber_4, c0_.email_id AS email_id_5, c1_.user_id AS user_id_6 FROM cms_users c0_ INNER JOIN cms_phonenumbers c1_ ON (c0_.id = c1_.user_id)', + ); + } + + public function testSupportsJoinOnMultipleComponentsWithJoinedInheritanceType(): void + { + $this->assertSqlGeneration( + 'SELECT e FROM Doctrine\Tests\Models\Company\CompanyEmployee e JOIN Doctrine\Tests\Models\Company\CompanyManager m ON e.id = m.id', + 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c2_.title AS title_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c2_.car_id AS car_id_8 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id LEFT JOIN company_managers c2_ ON c1_.id = c2_.id INNER JOIN (company_managers c3_ INNER JOIN company_employees c5_ ON c3_.id = c5_.id INNER JOIN company_persons c4_ ON c3_.id = c4_.id) ON (c0_.id = c4_.id)', + ); + + $this->assertSqlGeneration( + 'SELECT e FROM Doctrine\Tests\Models\Company\CompanyEmployee e LEFT JOIN Doctrine\Tests\Models\Company\CompanyManager m ON e.id = m.id', + 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c2_.title AS title_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c2_.car_id AS car_id_8 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id LEFT JOIN company_managers c2_ ON c1_.id = c2_.id LEFT JOIN (company_managers c3_ INNER JOIN company_employees c5_ ON c3_.id = c5_.id INNER JOIN company_persons c4_ ON c3_.id = c4_.id) ON (c0_.id = c4_.id)', + ); + + $this->assertSqlGeneration( + 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c JOIN c.salesPerson s LEFT JOIN Doctrine\Tests\Models\Company\CompanyEvent e ON s.id = e.id', + "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6, c0_.salesPerson_id AS salesPerson_id_7 FROM company_contracts c0_ INNER JOIN company_employees c1_ ON c0_.salesPerson_id = c1_.id LEFT JOIN company_persons c2_ ON c1_.id = c2_.id LEFT JOIN company_managers c3_ ON c1_.id = c3_.id LEFT JOIN (company_events c4_ LEFT JOIN company_auctions c5_ ON c4_.id = c5_.id LEFT JOIN company_raffles c6_ ON c4_.id = c6_.id) ON (c2_.id = c4_.id) WHERE c0_.discr IN ('fix', 'flexible', 'flexultra')", + ); + } + + public function testSupportsSelectWithCollectionAssociationJoin(): void + { + $this->assertSqlGeneration( + 'SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.phonenumbers p', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c1_.phonenumber AS phonenumber_4, c0_.email_id AS email_id_5, c1_.user_id AS user_id_6 FROM cms_users c0_ INNER JOIN cms_phonenumbers c1_ ON c0_.id = c1_.user_id', + ); + } + + public function testSupportsSelectWithSingleValuedAssociationJoin(): void + { + $this->assertSqlGeneration( + 'SELECT u, a FROM Doctrine\Tests\Models\Forum\ForumUser u JOIN u.avatar a', + 'SELECT f0_.id AS id_0, f0_.username AS username_1, f1_.id AS id_2, f0_.avatar_id AS avatar_id_3 FROM forum_users f0_ INNER JOIN forum_avatars f1_ ON f0_.avatar_id = f1_.id', + ); + } + + public function testSelectCorrelatedSubqueryComplexMathematicalExpression(): void + { + $this->assertSqlGeneration( + 'SELECT (SELECT (count(p.phonenumber)+5)*10 FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p JOIN p.user ui WHERE ui.id = u.id) AS c FROM Doctrine\Tests\Models\CMS\CmsUser u', + 'SELECT (SELECT (count(c0_.phonenumber) + 5) * 10 AS sclr_1 FROM cms_phonenumbers c0_ INNER JOIN cms_users c1_ ON c0_.user_id = c1_.id WHERE c1_.id = c2_.id) AS sclr_0 FROM cms_users c2_', + ); + } + + public function testSelectComplexMathematicalExpression(): void + { + $this->assertSqlGeneration( + 'SELECT (count(p.phonenumber)+5)*10 FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p JOIN p.user ui WHERE ui.id = ?1', + 'SELECT (count(c0_.phonenumber) + 5) * 10 AS sclr_0 FROM cms_phonenumbers c0_ INNER JOIN cms_users c1_ ON c0_.user_id = c1_.id WHERE c1_.id = ?', + ); + } + + public function testSingleAssociationPathExpressionInSubselect(): void + { + // Can be supported if SimpleSelectExpression supports SingleValuedPathExpression instead of StateFieldPathExpression. + self::markTestSkipped('Not yet supported.'); + + $this->assertSqlGeneration( + 'SELECT (SELECT p.user FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.user = u) user_id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1', + 'SELECT (SELECT c0_.user_id FROM cms_phonenumbers c0_ WHERE c0_.user_id = c1_.id) AS sclr_0 FROM cms_users c1_ WHERE c1_.id = ?', + ); + } + + #[Group('DDC-1077')] + public function testConstantValueInSelect(): void + { + $this->assertSqlGeneration( + "SELECT u.name, 'foo' AS bar FROM Doctrine\Tests\Models\CMS\CmsUser u", + "SELECT c0_.name AS name_0, 'foo' AS sclr_1 FROM cms_users c0_", + ); + } + + public function testSupportsOrderByWithAscAsDefault(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u ORDER BY u.id', + 'SELECT f0_.id AS id_0, f0_.username AS username_1, f0_.avatar_id AS avatar_id_2 FROM forum_users f0_ ORDER BY f0_.id ASC', + ); + } + + public function testSupportsOrderByAsc(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u ORDER BY u.id asc', + 'SELECT f0_.id AS id_0, f0_.username AS username_1, f0_.avatar_id AS avatar_id_2 FROM forum_users f0_ ORDER BY f0_.id ASC', + ); + } + + public function testSupportsOrderByDesc(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u ORDER BY u.id desc', + 'SELECT f0_.id AS id_0, f0_.username AS username_1, f0_.avatar_id AS avatar_id_2 FROM forum_users f0_ ORDER BY f0_.id DESC', + ); + } + + public function testSupportsOrderByWithSimpleArithmeticExpression(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u ORDER BY LENGTH(u.username) + LENGTH(u.username) asc', + 'SELECT f0_.id AS id_0, f0_.username AS username_1, f0_.avatar_id AS avatar_id_2 FROM forum_users f0_ ORDER BY LENGTH(f0_.username) + LENGTH(f0_.username) ASC', + ); + } + + public function testSupportsSelectDistinct(): void + { + $this->assertSqlGeneration( + 'SELECT DISTINCT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u', + 'SELECT DISTINCT c0_.name AS name_0 FROM cms_users c0_', + ); + } + + public function testSupportsAggregateFunctionInSelectedFields(): void + { + $this->assertSqlGeneration( + 'SELECT COUNT(u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY u.id', + 'SELECT COUNT(c0_.id) AS sclr_0 FROM cms_users c0_ GROUP BY c0_.id', + ); + } + + public function testSupportsAggregateFunctionWithSimpleArithmetic(): void + { + $this->assertSqlGeneration( + 'SELECT MAX(u.id + 4) * 2 FROM Doctrine\Tests\Models\CMS\CmsUser u', + 'SELECT MAX(c0_.id + 4) * 2 AS sclr_0 FROM cms_users c0_', + ); + } + + #[Group('DDC-3276')] + public function testSupportsAggregateCountFunctionWithSimpleArithmetic(): void + { + $this->entityManager = $this->createTestEntityManagerWithPlatform(new MySQLPlatform()); + + $this->assertSqlGeneration( + 'SELECT COUNT(CONCAT(u.id, u.name)) FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY u.id', + 'SELECT COUNT(CONCAT(c0_.id, c0_.name)) AS sclr_0 FROM cms_users c0_ GROUP BY c0_.id', + ); + } + + public function testSupportsWhereClauseWithPositionalParameter(): void + { + $this->assertSqlGeneration( + 'select u from Doctrine\Tests\Models\Forum\ForumUser u where u.id = ?1', + 'SELECT f0_.id AS id_0, f0_.username AS username_1, f0_.avatar_id AS avatar_id_2 FROM forum_users f0_ WHERE f0_.id = ?', + ); + } + + public function testSupportsWhereClauseWithNamedParameter(): void + { + $this->assertSqlGeneration( + 'select u from Doctrine\Tests\Models\Forum\ForumUser u where u.username = :name', + 'SELECT f0_.id AS id_0, f0_.username AS username_1, f0_.avatar_id AS avatar_id_2 FROM forum_users f0_ WHERE f0_.username = ?', + ); + } + + public function testSupportsWhereAndClauseWithNamedParameters(): void + { + $this->assertSqlGeneration( + 'select u from Doctrine\Tests\Models\Forum\ForumUser u where u.username = :name and u.username = :name2', + 'SELECT f0_.id AS id_0, f0_.username AS username_1, f0_.avatar_id AS avatar_id_2 FROM forum_users f0_ WHERE f0_.username = ? AND f0_.username = ?', + ); + } + + public function testSupportsCombinedWhereClauseWithNamedParameter(): void + { + $this->assertSqlGeneration( + 'select u from Doctrine\Tests\Models\Forum\ForumUser u where (u.username = :name OR u.username = :name2) AND u.id = :id', + 'SELECT f0_.id AS id_0, f0_.username AS username_1, f0_.avatar_id AS avatar_id_2 FROM forum_users f0_ WHERE (f0_.username = ? OR f0_.username = ?) AND f0_.id = ?', + ); + } + + public function testSupportsAggregateFunctionInASelectDistinct(): void + { + $this->assertSqlGeneration( + 'SELECT COUNT(DISTINCT u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u', + 'SELECT COUNT(DISTINCT c0_.name) AS sclr_0 FROM cms_users c0_', + ); + } + + /** Ticket #668 */ + public function testSupportsASqlKeywordInAStringLiteralParam(): void + { + $this->assertSqlGeneration( + "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name LIKE '%foo OR bar%'", + "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE c0_.name LIKE '%foo OR bar%'", + ); + } + + public function testSupportsArithmeticExpressionsInWherePart(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE ((u.id + 5000) * u.id + 3) < 10000000', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE ((c0_.id + 5000) * c0_.id + 3) < 10000000', + ); + } + + public function testSupportsMultipleEntitiesInFromClause(): void + { + $this->assertSqlGeneration( + 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsArticle a JOIN a.user u2 WHERE u.id = u2.id', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c1_.id AS id_4, c1_.topic AS topic_5, c1_.text AS text_6, c1_.version AS version_7, c0_.email_id AS email_id_8, c1_.user_id AS user_id_9 FROM cms_users c0_, cms_articles c1_ INNER JOIN cms_users c2_ ON c1_.user_id = c2_.id WHERE c0_.id = c2_.id', + ); + } + + public function testSupportsMultipleEntitiesInFromClauseUsingPathExpression(): void + { + $this->assertSqlGeneration( + 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsArticle a WHERE u.id = a.user', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c1_.id AS id_4, c1_.topic AS topic_5, c1_.text AS text_6, c1_.version AS version_7, c0_.email_id AS email_id_8, c1_.user_id AS user_id_9 FROM cms_users c0_, cms_articles c1_ WHERE c0_.id = c1_.user_id', + ); + } + + public function testSupportsPlainJoinWithoutClause(): void + { + $this->assertSqlGeneration( + 'SELECT u.id, a.id from Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a', + 'SELECT c0_.id AS id_0, c1_.id AS id_1 FROM cms_users c0_ LEFT JOIN cms_articles c1_ ON c0_.id = c1_.user_id', + ); + $this->assertSqlGeneration( + 'SELECT u.id, a.id from Doctrine\Tests\Models\CMS\CmsUser u JOIN u.articles a', + 'SELECT c0_.id AS id_0, c1_.id AS id_1 FROM cms_users c0_ INNER JOIN cms_articles c1_ ON c0_.id = c1_.user_id', + ); + } + + #[Group('DDC-135')] + public function testSupportsJoinAndWithClauseRestriction(): void + { + $this->assertSqlGeneration( + "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a WITH a.topic LIKE '%foo%'", + "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ LEFT JOIN cms_articles c1_ ON c0_.id = c1_.user_id AND (c1_.topic LIKE '%foo%')", + ); + $this->assertSqlGeneration( + "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles a WITH a.topic LIKE '%foo%'", + "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ INNER JOIN cms_articles c1_ ON c0_.id = c1_.user_id AND (c1_.topic LIKE '%foo%')", + ); + } + + #[Group('DDC-135')] + #[Group('DDC-177')] + public function testJoinOnClauseNotYetSupportedThrowsException(): void + { + $this->expectException(QueryException::class); + + $sql = $this->entityManager->createQuery( + "SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a ON a.topic LIKE '%foo%'", + )->getSql(); + } + + public function testSupportsMultipleJoins(): void + { + $this->assertSqlGeneration( + 'SELECT u.id, a.id, p.phonenumber, c.id from Doctrine\Tests\Models\CMS\CmsUser u JOIN u.articles a JOIN u.phonenumbers p JOIN a.comments c', + 'SELECT c0_.id AS id_0, c1_.id AS id_1, c2_.phonenumber AS phonenumber_2, c3_.id AS id_3 FROM cms_users c0_ INNER JOIN cms_articles c1_ ON c0_.id = c1_.user_id INNER JOIN cms_phonenumbers c2_ ON c0_.id = c2_.user_id INNER JOIN cms_comments c3_ ON c1_.id = c3_.article_id', + ); + } + + public function testSupportsTrimFunction(): void + { + $this->entityManager = $this->createTestEntityManagerWithPlatform(new MySQLPlatform()); + + $this->assertSqlGeneration( + "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE TRIM(TRAILING ' ' FROM u.name) = 'someone'", + "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE TRIM(TRAILING ' ' FROM c0_.name) = 'someone'", + ); + } + + #[Group('DDC-2668')] + public function testSupportsTrimLeadingZeroString(): void + { + $this->entityManager = $this->createTestEntityManagerWithPlatform(new MySQLPlatform()); + + $this->assertSqlGeneration( + "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE TRIM(TRAILING '0' FROM u.name) != ''", + "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE TRIM(TRAILING '0' FROM c0_.name) <> ''", + ); + } + + /** Ticket 894 */ + public function testSupportsBetweenClauseWithPositionalParameters(): void + { + $this->assertSqlGeneration( + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id BETWEEN ?1 AND ?2', + 'SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE c0_.id BETWEEN ? AND ?', + ); + } + + #[Group('DDC-1802')] + public function testSupportsNotBetweenForSizeFunction(): void + { + $this->assertSqlGeneration( + 'SELECT m.name FROM Doctrine\Tests\Models\StockExchange\Market m WHERE SIZE(m.stocks) NOT BETWEEN ?1 AND ?2', + 'SELECT e0_.name AS name_0 FROM exchange_markets e0_ WHERE (SELECT COUNT(*) FROM exchange_stocks e1_ WHERE e1_.market_id = e0_.id) NOT BETWEEN ? AND ?', + ); + } + + public function testSupportsFunctionalExpressionsInWherePart(): void + { + $this->assertSqlGeneration( + "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE TRIM(u.name) = 'someone'", + // String quoting in the SQL usually depends on the database platform. + // This test works with a mock connection which uses ' for string quoting. + "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE TRIM(c0_.name) = 'someone'", + ); + } + + public function testSupportsInstanceOfExpressionsInWherePart(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF Doctrine\Tests\Models\Company\CompanyEmployee', + "SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.title AS title_2, c2_.salary AS salary_3, c2_.department AS department_4, c2_.startDate AS startDate_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c1_.car_id AS car_id_8 FROM company_persons c0_ LEFT JOIN company_managers c1_ ON c0_.id = c1_.id LEFT JOIN company_employees c2_ ON c0_.id = c2_.id WHERE c0_.discr IN ('manager', 'employee')", + ); + } + + public function testSupportsInstanceOfExpressionInWherePartWithMultipleValues(): void + { + // This also uses FQCNs starting with or without a backslash in the INSTANCE OF parameter + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF (Doctrine\Tests\Models\Company\CompanyEmployee, \Doctrine\Tests\Models\Company\CompanyManager)', + "SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.title AS title_2, c2_.salary AS salary_3, c2_.department AS department_4, c2_.startDate AS startDate_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c1_.car_id AS car_id_8 FROM company_persons c0_ LEFT JOIN company_managers c1_ ON c0_.id = c1_.id LEFT JOIN company_employees c2_ ON c0_.id = c2_.id WHERE c0_.discr IN ('manager', 'employee')", + ); + } + + #[Group('DDC-1194')] + public function testSupportsInstanceOfExpressionsInWherePartPrefixedSlash(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF \Doctrine\Tests\Models\Company\CompanyEmployee', + "SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.title AS title_2, c2_.salary AS salary_3, c2_.department AS department_4, c2_.startDate AS startDate_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c1_.car_id AS car_id_8 FROM company_persons c0_ LEFT JOIN company_managers c1_ ON c0_.id = c1_.id LEFT JOIN company_employees c2_ ON c0_.id = c2_.id WHERE c0_.discr IN ('manager', 'employee')", + ); + } + + #[Group('DDC-1194')] + public function testSupportsInstanceOfExpressionsInWherePartWithUnrelatedClass(): void + { + $this->assertInvalidSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF \Doctrine\Tests\Models\CMS\CmsUser', + QueryException::class, + ); + } + + public function testSupportsInstanceOfExpressionsInWherePartInDeeperLevel(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyEmployee u WHERE u INSTANCE OF Doctrine\Tests\Models\Company\CompanyManager', + "SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c2_.title AS title_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c2_.car_id AS car_id_8 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id LEFT JOIN company_managers c2_ ON c1_.id = c2_.id WHERE c0_.discr IN ('manager')", + ); + } + + public function testSupportsInstanceOfExpressionsInWherePartInDeepestLevel(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyManager u WHERE u INSTANCE OF Doctrine\Tests\Models\Company\CompanyManager', + "SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c2_.title AS title_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c2_.car_id AS car_id_8 FROM company_managers c2_ INNER JOIN company_employees c1_ ON c2_.id = c1_.id INNER JOIN company_persons c0_ ON c2_.id = c0_.id WHERE c0_.discr IN ('manager')", + ); + } + + public function testSupportsInstanceOfExpressionsUsingInputParameterInWherePart(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF ?1', + 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.title AS title_2, c2_.salary AS salary_3, c2_.department AS department_4, c2_.startDate AS startDate_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c1_.car_id AS car_id_8 FROM company_persons c0_ LEFT JOIN company_managers c1_ ON c0_.id = c1_.id LEFT JOIN company_employees c2_ ON c0_.id = c2_.id WHERE c0_.discr IN (?)', + [], + [1 => $this->entityManager->getClassMetadata(CompanyEmployee::class)], + ); + } + + /** Ticket #973 */ + public function testSupportsSingleValuedInExpressionWithoutSpacesInWherePart(): void + { + $this->assertSqlGeneration( + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE IDENTITY(u.email) IN(46)', + 'SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE c0_.email_id IN (46)', + ); + } + + public function testSupportsMultipleValuedInExpressionInWherePart(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id IN (1, 2)', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE c0_.id IN (1, 2)', + ); + } + + public function testSupportsNotInExpressionInWherePart(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE :id NOT IN (1)', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE ? NOT IN (1)', + ); + } + + #[Group('DDC-1802')] + public function testSupportsNotInExpressionForModFunction(): void + { + $this->entityManager = $this->createTestEntityManagerWithPlatform(new MySQLPlatform()); + + $this->assertSqlGeneration( + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE MOD(u.id, 5) NOT IN(1,3,4)', + 'SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE MOD(c0_.id, 5) NOT IN (1, 3, 4)', + ); + } + + public function testInExpressionWithSingleValuedAssociationPathExpressionInWherePart(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u WHERE u.avatar IN (?1, ?2)', + 'SELECT f0_.id AS id_0, f0_.username AS username_1, f0_.avatar_id AS avatar_id_2 FROM forum_users f0_ WHERE f0_.avatar_id IN (?, ?)', + ); + } + + public function testInvalidInExpressionWithSingleValuedAssociationPathExpressionOnInverseSide(): void + { + // We do not support SingleValuedAssociationPathExpression on inverse side + $this->assertInvalidSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.address IN (?1, ?2)', + QueryException::class, + ); + } + + public function testInExpressionWithArithmeticExpression(): void + { + $this->entityManager->getConfiguration()->addCustomStringFunction('FOO', MyAbsFunction::class); + + $this->assertSqlGeneration( + "SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u WHERE u.username IN (FOO('Lo'), 'Lo', :name)", + "SELECT f0_.id AS id_0, f0_.username AS username_1, f0_.avatar_id AS avatar_id_2 FROM forum_users f0_ WHERE f0_.username IN (ABS('Lo'), 'Lo', ?)", + ); + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\Forum\ForumUser u WHERE u.id IN (1 + 1)', + 'SELECT f0_.id AS id_0, f0_.username AS username_1, f0_.avatar_id AS avatar_id_2 FROM forum_users f0_ WHERE f0_.id IN (1 + 1)', + ); + } + + public function testSupportsConcatFunctionForMysqlAndPostgresql(): void + { + $this->entityManager = $this->createTestEntityManagerWithPlatform(new MySQLPlatform()); + + $this->assertSqlGeneration( + "SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CONCAT(u.name, 's') = ?1", + "SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE CONCAT(c0_.name, 's') = ?", + ); + $this->assertSqlGeneration( + 'SELECT CONCAT(u.id, u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1', + 'SELECT CONCAT(c0_.id, c0_.name) AS sclr_0 FROM cms_users c0_ WHERE c0_.id = ?', + ); + + $this->entityManager = $this->createTestEntityManagerWithPlatform(new PostgreSQLPlatform()); + $this->assertSqlGeneration( + "SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CONCAT(u.name, 's') = ?1", + "SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE c0_.name || 's' = ?", + ); + $this->assertSqlGeneration( + 'SELECT CONCAT(u.id, u.name) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1', + 'SELECT c0_.id || c0_.name AS sclr_0 FROM cms_users c0_ WHERE c0_.id = ?', + ); + } + + public function testSupportsExistsExpressionInWherePartWithCorrelatedSubquery(): void + { + $this->assertSqlGeneration( + 'SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE EXISTS (SELECT p.phonenumber FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.phonenumber = u.id)', + 'SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE EXISTS (SELECT c1_.phonenumber FROM cms_phonenumbers c1_ WHERE c1_.phonenumber = c0_.id)', + ); + } + + #[Group('DDC-593')] + public function testSubqueriesInComparisonExpression(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE (u.id >= (SELECT u2.id FROM Doctrine\Tests\Models\CMS\CmsUser u2 WHERE u2.name = :name)) AND (u.id <= (SELECT u3.id FROM Doctrine\Tests\Models\CMS\CmsUser u3 WHERE u3.name = :name))', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE (c0_.id >= (SELECT c1_.id FROM cms_users c1_ WHERE c1_.name = ?)) AND (c0_.id <= (SELECT c2_.id FROM cms_users c2_ WHERE c2_.name = ?))', + ); + } + + public function testSupportsMemberOfExpressionOneToMany(): void + { + // "Get all users who have $phone as a phonenumber." (*cough* doesnt really make sense...) + $q = $this->entityManager->createQuery('SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE :param MEMBER OF u.phonenumbers'); + + $phone = new CmsPhonenumber(); + $phone->phonenumber = 101; + $q->setParameter('param', $phone); + + self::assertEquals( + 'SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE EXISTS (SELECT 1 FROM cms_phonenumbers c1_ WHERE c0_.id = c1_.user_id AND c1_.phonenumber = ?)', + $q->getSql(), + ); + } + + public function testSupportsMemberOfExpressionManyToMany(): void + { + // "Get all users who are members of $group." + $q = $this->entityManager->createQuery('SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE :param MEMBER OF u.groups'); + + $group = new CmsGroup(); + $group->id = 101; + $q->setParameter('param', $group); + + self::assertEquals( + 'SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE EXISTS (SELECT 1 FROM cms_users_groups c1_ WHERE c1_.user_id = c0_.id AND c1_.group_id IN (?))', + $q->getSql(), + ); + } + + public function testSupportsMemberOfExpressionManyToManyParameterArray(): void + { + $q = $this->entityManager->createQuery('SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE :param MEMBER OF u.groups'); + + $group = new CmsGroup(); + $group->id = 101; + $group2 = new CmsGroup(); + $group2->id = 105; + $q->setParameter('param', [$group, $group2]); + + self::assertEquals( + 'SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE EXISTS (SELECT 1 FROM cms_users_groups c1_ WHERE c1_.user_id = c0_.id AND c1_.group_id IN (?))', + $q->getSql(), + ); + } + + public function testSupportsMemberOfExpressionSelfReferencing(): void + { + // "Get all persons who have $person as a friend." + // Tough one: Many-many self-referencing ("friends") with class table inheritance + $q = $this->entityManager->createQuery('SELECT p FROM Doctrine\Tests\Models\Company\CompanyPerson p WHERE :param MEMBER OF p.friends'); + $person = new CompanyPerson(); + $this->entityManager->getClassMetadata($person::class)->setIdentifierValues($person, ['id' => 101]); + $q->setParameter('param', $person); + self::assertEquals( + 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.title AS title_2, c2_.salary AS salary_3, c2_.department AS department_4, c2_.startDate AS startDate_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c1_.car_id AS car_id_8 FROM company_persons c0_ LEFT JOIN company_managers c1_ ON c0_.id = c1_.id LEFT JOIN company_employees c2_ ON c0_.id = c2_.id WHERE EXISTS (SELECT 1 FROM company_persons_friends c3_ WHERE c3_.person_id = c0_.id AND c3_.friend_id IN (?))', + $q->getSql(), + ); + } + + public function testSupportsMemberOfWithSingleValuedAssociation(): void + { + // Impossible example, but it illustrates the purpose + $q = $this->entityManager->createQuery('SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.email MEMBER OF u.groups'); + + self::assertEquals( + 'SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE EXISTS (SELECT 1 FROM cms_users_groups c1_ WHERE c1_.user_id = c0_.id AND c1_.group_id IN (c0_.email_id))', + $q->getSql(), + ); + } + + public function testSupportsMemberOfWithIdentificationVariable(): void + { + // Impossible example, but it illustrates the purpose + $q = $this->entityManager->createQuery('SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u MEMBER OF u.groups'); + + self::assertEquals( + 'SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE EXISTS (SELECT 1 FROM cms_users_groups c1_ WHERE c1_.user_id = c0_.id AND c1_.group_id IN (c0_.id))', + $q->getSql(), + ); + } + + public function testSupportsCurrentDateFunction(): void + { + $q = $this->entityManager->createQuery('SELECT d.id FROM Doctrine\Tests\Models\Generic\DateTimeModel d WHERE d.datetime > current_date()'); + self::assertEquals('SELECT d0_.id AS id_0 FROM date_time_model d0_ WHERE d0_.col_datetime > CURRENT_DATE', $q->getSql()); + } + + public function testSupportsCurrentTimeFunction(): void + { + $q = $this->entityManager->createQuery('SELECT d.id FROM Doctrine\Tests\Models\Generic\DateTimeModel d WHERE d.time > current_time()'); + self::assertEquals('SELECT d0_.id AS id_0 FROM date_time_model d0_ WHERE d0_.col_time > CURRENT_TIME', $q->getSql()); + } + + public function testSupportsCurrentTimestampFunction(): void + { + $q = $this->entityManager->createQuery('SELECT d.id FROM Doctrine\Tests\Models\Generic\DateTimeModel d WHERE d.datetime > current_timestamp()'); + self::assertEquals('SELECT d0_.id AS id_0 FROM date_time_model d0_ WHERE d0_.col_datetime > CURRENT_TIMESTAMP', $q->getSql()); + } + + public function testExistsExpressionInWhereCorrelatedSubqueryAssocCondition(): void + { + $this->assertSqlGeneration( + // DQL + // The result of this query consists of all employees whose spouses are also employees. + 'SELECT DISTINCT emp FROM Doctrine\Tests\Models\CMS\CmsEmployee emp + WHERE EXISTS ( + SELECT spouseEmp + FROM Doctrine\Tests\Models\CMS\CmsEmployee spouseEmp + WHERE spouseEmp = emp.spouse)', + // SQL + 'SELECT DISTINCT c0_.id AS id_0, c0_.name AS name_1, c0_.spouse_id AS spouse_id_2 FROM cms_employees c0_ WHERE EXISTS (SELECT c1_.id FROM cms_employees c1_ WHERE c1_.id = c0_.spouse_id)', + ); + } + + public function testExistsExpressionWithSimpleSelectReturningScalar(): void + { + $this->assertSqlGeneration( + // DQL + // The result of this query consists of all employees whose spouses are also employees. + 'SELECT DISTINCT emp FROM Doctrine\Tests\Models\CMS\CmsEmployee emp + WHERE EXISTS ( + SELECT 1 + FROM Doctrine\Tests\Models\CMS\CmsEmployee spouseEmp + WHERE spouseEmp = emp.spouse)', + // SQL + 'SELECT DISTINCT c0_.id AS id_0, c0_.name AS name_1, c0_.spouse_id AS spouse_id_2 FROM cms_employees c0_ WHERE EXISTS (SELECT 1 AS sclr_3 FROM cms_employees c1_ WHERE c1_.id = c0_.spouse_id)', + ); + } + + public function testLimitFromQueryClass(): void + { + $q = $this->entityManager + ->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u') + ->setMaxResults(10); + + self::assertEquals('SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ LIMIT 10', $q->getSql()); + } + + public function testLimitAndOffsetFromQueryClass(): void + { + $q = $this->entityManager + ->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u') + ->setMaxResults(10) + ->setFirstResult(0); + + // DBAL 2.8+ doesn't add OFFSET part when offset is 0 + self::assertThat( + $q->getSql(), + self::logicalOr( + self::identicalTo('SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ LIMIT 10'), + self::identicalTo('SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ LIMIT 10 OFFSET 0'), + ), + ); + } + + public function testSizeFunction(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE SIZE(u.phonenumbers) > 1', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE (SELECT COUNT(*) FROM cms_phonenumbers c1_ WHERE c1_.user_id = c0_.id) > 1', + ); + } + + public function testSizeFunctionSupportsManyToMany(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE SIZE(u.groups) > 1', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE (SELECT COUNT(*) FROM cms_users_groups c1_ WHERE c1_.user_id = c0_.id) > 1', + ); + } + + public function testEmptyCollectionComparisonExpression(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.phonenumbers IS EMPTY', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE (SELECT COUNT(*) FROM cms_phonenumbers c1_ WHERE c1_.user_id = c0_.id) = 0', + ); + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.phonenumbers IS NOT EMPTY', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE (SELECT COUNT(*) FROM cms_phonenumbers c1_ WHERE c1_.user_id = c0_.id) > 0', + ); + } + + public function testNestedExpressions(): void + { + $this->assertSqlGeneration( + 'select u from Doctrine\Tests\Models\CMS\CmsUser u where u.id > 10 and u.id < 42 and ((u.id * 2) > 5)', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE c0_.id > 10 AND c0_.id < 42 AND ((c0_.id * 2) > 5)', + ); + } + + public function testNestedExpressions2(): void + { + $this->assertSqlGeneration( + 'select u from Doctrine\Tests\Models\CMS\CmsUser u where (u.id > 10) and (u.id < 42 and ((u.id * 2) > 5)) or u.id <> 42', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE (c0_.id > 10) AND (c0_.id < 42 AND ((c0_.id * 2) > 5)) OR c0_.id <> 42', + ); + } + + public function testNestedExpressions3(): void + { + $this->assertSqlGeneration( + 'select u from Doctrine\Tests\Models\CMS\CmsUser u where (u.id > 10) and (u.id between 1 and 10 or u.id in (1, 2, 3, 4, 5))', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE (c0_.id > 10) AND (c0_.id BETWEEN 1 AND 10 OR c0_.id IN (1, 2, 3, 4, 5))', + ); + } + + public function testOrderByCollectionAssociationSize(): void + { + $this->assertSqlGeneration( + 'select u, size(u.articles) as numArticles from Doctrine\Tests\Models\CMS\CmsUser u order by numArticles', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, (SELECT COUNT(*) FROM cms_articles c1_ WHERE c1_.user_id = c0_.id) AS sclr_4, c0_.email_id AS email_id_5 FROM cms_users c0_ ORDER BY sclr_4 ASC', + ); + } + + public function testOrderBySupportsSingleValuedPathExpressionOwningSide(): void + { + $this->assertSqlGeneration( + 'select a from Doctrine\Tests\Models\CMS\CmsArticle a order by a.user', + 'SELECT c0_.id AS id_0, c0_.topic AS topic_1, c0_.text AS text_2, c0_.version AS version_3, c0_.user_id AS user_id_4 FROM cms_articles c0_ ORDER BY c0_.user_id ASC', + ); + } + + public function testOrderBySupportsSingleValuedPathExpressionInverseSide(): void + { + $this->expectException(QueryException::class); + $q = $this->entityManager->createQuery('select u from Doctrine\Tests\Models\CMS\CmsUser u order by u.address'); + $q->getSQL(); + } + + public function testBooleanLiteralInWhereOnSqlite(): void + { + $this->entityManager = $this->createTestEntityManagerWithPlatform(new SQLitePlatform()); + $this->assertSqlGeneration( + 'SELECT b FROM Doctrine\Tests\Models\Generic\BooleanModel b WHERE b.booleanField = true', + 'SELECT b0_.id AS id_0, b0_.booleanField AS booleanField_1 FROM boolean_model b0_ WHERE b0_.booleanField = 1', + ); + + $this->assertSqlGeneration( + 'SELECT b FROM Doctrine\Tests\Models\Generic\BooleanModel b WHERE b.booleanField = false', + 'SELECT b0_.id AS id_0, b0_.booleanField AS booleanField_1 FROM boolean_model b0_ WHERE b0_.booleanField = 0', + ); + } + + public function testBooleanLiteralInWhereOnPostgres(): void + { + $this->entityManager = $this->createTestEntityManagerWithPlatform(new PostgreSQLPlatform()); + $this->assertSqlGeneration( + 'SELECT b FROM Doctrine\Tests\Models\Generic\BooleanModel b WHERE b.booleanField = true', + 'SELECT b0_.id AS id_0, b0_.booleanField AS booleanfield_1 FROM boolean_model b0_ WHERE b0_.booleanField = true', + ); + + $this->assertSqlGeneration( + 'SELECT b FROM Doctrine\Tests\Models\Generic\BooleanModel b WHERE b.booleanField = false', + 'SELECT b0_.id AS id_0, b0_.booleanField AS booleanfield_1 FROM boolean_model b0_ WHERE b0_.booleanField = false', + ); + } + + public function testSingleValuedAssociationFieldInWhere(): void + { + $this->assertSqlGeneration( + 'SELECT p FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.user = ?1', + 'SELECT c0_.phonenumber AS phonenumber_0, c0_.user_id AS user_id_1 FROM cms_phonenumbers c0_ WHERE c0_.user_id = ?', + ); + } + + public function testSingleValuedAssociationNullCheckOnOwningSide(): void + { + $this->assertSqlGeneration( + 'SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a WHERE a.user IS NULL', + 'SELECT c0_.id AS id_0, c0_.country AS country_1, c0_.zip AS zip_2, c0_.city AS city_3, c0_.user_id AS user_id_4 FROM cms_addresses c0_ WHERE c0_.user_id IS NULL', + ); + } + + /** + * Null check on inverse side has to happen through explicit JOIN. + * "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.address IS NULL" + * where the CmsUser is the inverse side is not supported. + */ + public function testSingleValuedAssociationNullCheckOnInverseSide(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.address a WHERE a.id IS NULL', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ LEFT JOIN cms_addresses c1_ ON c0_.id = c1_.user_id WHERE c1_.id IS NULL', + ); + } + + #[Group('DDC-339')] + #[Group('DDC-1572')] + public function testStringFunctionLikeExpression(): void + { + $this->assertSqlGeneration( + "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE LOWER(u.name) LIKE '%foo OR bar%'", + "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE LOWER(c0_.name) LIKE '%foo OR bar%'", + ); + $this->assertSqlGeneration( + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE LOWER(u.name) LIKE :str', + 'SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE LOWER(c0_.name) LIKE ?', + ); + $this->assertSqlGeneration( + "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CONCAT(UPPER(u.name), '_moo') LIKE :str", + "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE UPPER(c0_.name) || '_moo' LIKE ?", + ); + + // DDC-1572 + $this->assertSqlGeneration( + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE UPPER(u.name) LIKE UPPER(:str)', + 'SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE UPPER(c0_.name) LIKE UPPER(?)', + ); + $this->assertSqlGeneration( + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE UPPER(LOWER(u.name)) LIKE UPPER(LOWER(:str))', + 'SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE UPPER(LOWER(c0_.name)) LIKE UPPER(LOWER(?))', + ); + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a WITH a.topic LIKE u.name', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ LEFT JOIN cms_articles c1_ ON c0_.id = c1_.user_id AND (c1_.topic LIKE c0_.name)', + ); + } + + #[Group('DDC-1802')] + public function testStringFunctionNotLikeExpression(): void + { + $this->assertSqlGeneration( + "SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE LOWER(u.name) NOT LIKE '%foo OR bar%'", + "SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE LOWER(c0_.name) NOT LIKE '%foo OR bar%'", + ); + + $this->assertSqlGeneration( + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE UPPER(LOWER(u.name)) NOT LIKE UPPER(LOWER(:str))', + 'SELECT c0_.name AS name_0 FROM cms_users c0_ WHERE UPPER(LOWER(c0_.name)) NOT LIKE UPPER(LOWER(?))', + ); + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a WITH a.topic NOT LIKE u.name', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ LEFT JOIN cms_articles c1_ ON c0_.id = c1_.user_id AND (c1_.topic NOT LIKE c0_.name)', + ); + } + + #[Group('DDC-338')] + public function testOrderedCollectionFetchJoined(): void + { + $this->assertSqlGeneration( + 'SELECT r, l FROM Doctrine\Tests\Models\Routing\RoutingRoute r JOIN r.legs l', + 'SELECT r0_.id AS id_0, r1_.id AS id_1, r1_.departureDate AS departureDate_2, r1_.arrivalDate AS arrivalDate_3, r1_.from_id AS from_id_4, r1_.to_id AS to_id_5 FROM RoutingRoute r0_ INNER JOIN RoutingRouteLegs r2_ ON r0_.id = r2_.route_id INNER JOIN RoutingLeg r1_ ON r1_.id = r2_.leg_id ORDER BY r1_.departureDate ASC', + ); + } + + public function testSubselectInSelect(): void + { + $this->assertSqlGeneration( + "SELECT u.name, (SELECT COUNT(p.phonenumber) FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.phonenumber = 1234) pcount FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = 'jon'", + "SELECT c0_.name AS name_0, (SELECT COUNT(c1_.phonenumber) AS sclr_2 FROM cms_phonenumbers c1_ WHERE c1_.phonenumber = 1234) AS sclr_1 FROM cms_users c0_ WHERE c0_.name = 'jon'", + ); + } + + #[Group('locking')] + #[Group('DDC-178')] + public function testPessimisticWriteLockQueryHint(): void + { + if ($this->entityManager->getConnection()->getDatabasePlatform() instanceof SQLitePlatform) { + self::markTestSkipped('SqLite does not support Row locking at all.'); + } + + $this->assertSqlGeneration( + "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 'gblanco'", + "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE c0_.username = 'gblanco' FOR UPDATE", + [ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_WRITE], + ); + } + + #[Group('locking')] + #[Group('DDC-178')] + public function testPessimisticReadLockQueryHintPostgreSql(): void + { + $this->entityManager = $this->createTestEntityManagerWithPlatform(new PostgreSQLPlatform()); + + $this->assertSqlGeneration( + "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 'gblanco'", + "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE c0_.username = 'gblanco' FOR SHARE", + [ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_READ], + ); + } + + #[Group('DDC-1693')] + #[Group('locking')] + public function testLockModeNoneQueryHint(): void + { + $this->assertSqlGeneration( + "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 'gblanco'", + "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE c0_.username = 'gblanco'", + [ORMQuery::HINT_LOCK_MODE => LockMode::NONE], + ); + } + + #[Group('DDC-430')] + public function testSupportSelectWithMoreThan10InputParameters(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1 OR u.id = ?2 OR u.id = ?3 OR u.id = ?4 OR u.id = ?5 OR u.id = ?6 OR u.id = ?7 OR u.id = ?8 OR u.id = ?9 OR u.id = ?10 OR u.id = ?11', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE c0_.id = ? OR c0_.id = ? OR c0_.id = ? OR c0_.id = ? OR c0_.id = ? OR c0_.id = ? OR c0_.id = ? OR c0_.id = ? OR c0_.id = ? OR c0_.id = ? OR c0_.id = ?', + ); + } + + #[Group('locking')] + #[Group('DDC-178')] + public function testPessimisticReadLockQueryHintMySql(): void + { + $this->entityManager = $this->createTestEntityManagerWithPlatform(new MySQLPlatform()); + + $this->assertSqlGeneration( + "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 'gblanco'", + "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE c0_.username = 'gblanco' LOCK IN SHARE MODE", + [ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_READ], + ); + } + + #[Group('locking')] + #[Group('DDC-178')] + public function testPessimisticReadLockQueryHintOracle(): void + { + $this->entityManager = $this->createTestEntityManagerWithPlatform(new OraclePlatform()); + + $this->assertSqlGeneration( + "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 'gblanco'", + "SELECT c0_.id AS ID_0, c0_.status AS STATUS_1, c0_.username AS USERNAME_2, c0_.name AS NAME_3, c0_.email_id AS EMAIL_ID_4 FROM cms_users c0_ WHERE c0_.username = 'gblanco' FOR UPDATE", + [ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_READ], + ); + } + + #[Group('DDC-431')] + public function testSupportToCustomDQLFunctions(): void + { + $config = $this->entityManager->getConfiguration(); + $config->addCustomNumericFunction('MYABS', MyAbsFunction::class); + + $this->assertSqlGeneration( + 'SELECT MYABS(p.phonenumber) FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p', + 'SELECT ABS(c0_.phonenumber) AS sclr_0 FROM cms_phonenumbers c0_', + ); + + $config->setCustomNumericFunctions([]); + } + + #[Group('DDC-826')] + public function testMappedSuperclassAssociationJoin(): void + { + $this->assertSqlGeneration( + 'SELECT f FROM Doctrine\Tests\Models\DirectoryTree\File f JOIN f.parentDirectory d WHERE f.id = ?1', + 'SELECT f0_.id AS id_0, f0_.name AS name_1, f0_.extension AS extension_2, f0_.parentDirectory_id AS parentDirectory_id_3 FROM "file" f0_ INNER JOIN Directory d1_ ON f0_.parentDirectory_id = d1_.id WHERE f0_.id = ?', + ); + } + + #[Group('DDC-1053')] + public function testGroupBy(): void + { + $this->assertSqlGeneration( + 'SELECT g.id, count(u.id) FROM Doctrine\Tests\Models\CMS\CmsGroup g JOIN g.users u GROUP BY g.id', + 'SELECT c0_.id AS id_0, count(c1_.id) AS sclr_1 FROM cms_groups c0_ INNER JOIN cms_users_groups c2_ ON c0_.id = c2_.group_id INNER JOIN cms_users c1_ ON c1_.id = c2_.user_id GROUP BY c0_.id', + ); + } + + #[Group('DDC-1053')] + public function testGroupByIdentificationVariable(): void + { + $this->assertSqlGeneration( + 'SELECT g, count(u.id) FROM Doctrine\Tests\Models\CMS\CmsGroup g JOIN g.users u GROUP BY g', + 'SELECT c0_.id AS id_0, c0_.name AS name_1, count(c1_.id) AS sclr_2 FROM cms_groups c0_ INNER JOIN cms_users_groups c2_ ON c0_.id = c2_.group_id INNER JOIN cms_users c1_ ON c1_.id = c2_.user_id GROUP BY c0_.id, c0_.name', + ); + } + + public function testCaseContainingNullIf(): void + { + $this->assertSqlGeneration( + 'SELECT NULLIF(g.id, g.name) AS NullIfEqual FROM Doctrine\Tests\Models\CMS\CmsGroup g', + 'SELECT NULLIF(c0_.id, c0_.name) AS sclr_0 FROM cms_groups c0_', + ); + } + + public function testCaseContainingCoalesce(): void + { + $this->assertSqlGeneration( + "SELECT COALESCE(NULLIF(u.name, ''), u.username) as Display FROM Doctrine\Tests\Models\CMS\CmsUser u", + "SELECT COALESCE(NULLIF(c0_.name, ''), c0_.username) AS sclr_0 FROM cms_users c0_", + ); + } + + /** + * Test that the right discriminator data is inserted in a subquery. + */ + public function testSubSelectDiscriminator(): void + { + $this->assertSqlGeneration( + 'SELECT u.name, (SELECT COUNT(cfc.id) total FROM Doctrine\Tests\Models\Company\CompanyFixContract cfc) as cfc_count FROM Doctrine\Tests\Models\CMS\CmsUser u', + "SELECT c0_.name AS name_0, (SELECT COUNT(c1_.id) AS sclr_2 FROM company_contracts c1_ WHERE c1_.discr IN ('fix')) AS sclr_1 FROM cms_users c0_", + ); + } + + public function testIdVariableResultVariableReuse(): void + { + $exceptionThrown = false; + try { + $query = $this->entityManager->createQuery('SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IN (SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u)'); + + $query->getSql(); + $query->free(); + } catch (Exception) { + $exceptionThrown = true; + } + + self::assertTrue($exceptionThrown); + } + + public function testSubSelectAliasesFromOuterQuery(): void + { + $this->assertSqlGeneration( + 'SELECT uo, (SELECT ui.name FROM Doctrine\Tests\Models\CMS\CmsUser ui WHERE ui.id = uo.id) AS bar FROM Doctrine\Tests\Models\CMS\CmsUser uo', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, (SELECT c1_.name FROM cms_users c1_ WHERE c1_.id = c0_.id) AS sclr_4, c0_.email_id AS email_id_5 FROM cms_users c0_', + ); + } + + public function testSubSelectAliasesFromOuterQueryWithSubquery(): void + { + $this->assertSqlGeneration( + 'SELECT uo, (SELECT ui.name FROM Doctrine\Tests\Models\CMS\CmsUser ui WHERE ui.id = uo.id AND ui.name IN (SELECT uii.name FROM Doctrine\Tests\Models\CMS\CmsUser uii)) AS bar FROM Doctrine\Tests\Models\CMS\CmsUser uo', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, (SELECT c1_.name FROM cms_users c1_ WHERE c1_.id = c0_.id AND c1_.name IN (SELECT c2_.name FROM cms_users c2_)) AS sclr_4, c0_.email_id AS email_id_5 FROM cms_users c0_', + ); + } + + public function testSubSelectAliasesFromOuterQueryReuseInWhereClause(): void + { + $this->assertSqlGeneration( + 'SELECT uo, (SELECT ui.name FROM Doctrine\Tests\Models\CMS\CmsUser ui WHERE ui.id = uo.id) AS bar FROM Doctrine\Tests\Models\CMS\CmsUser uo WHERE bar = ?0', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, (SELECT c1_.name FROM cms_users c1_ WHERE c1_.id = c0_.id) AS sclr_4, c0_.email_id AS email_id_5 FROM cms_users c0_ WHERE sclr_4 = ?', + ); + } + + #[Group('DDC-1298')] + public function testSelectForeignKeyPKWithoutFields(): void + { + $this->assertSqlGeneration( + 'SELECT t, s, l FROM Doctrine\Tests\Models\DDC117\DDC117Link l INNER JOIN l.target t INNER JOIN l.source s', + 'SELECT d0_.article_id AS article_id_0, d0_.title AS title_1, d1_.article_id AS article_id_2, d1_.title AS title_3, d2_.source_id AS source_id_4, d2_.target_id AS target_id_5 FROM DDC117Link d2_ INNER JOIN DDC117Article d0_ ON d2_.target_id = d0_.article_id INNER JOIN DDC117Article d1_ ON d2_.source_id = d1_.article_id', + ); + } + + public function testGeneralCaseWithSingleWhenClause(): void + { + $this->assertSqlGeneration( + 'SELECT g.id, CASE WHEN ((g.id / 2) > 18) THEN 1 ELSE 0 END AS test FROM Doctrine\Tests\Models\CMS\CmsGroup g', + 'SELECT c0_.id AS id_0, CASE WHEN ((c0_.id / 2) > 18) THEN 1 ELSE 0 END AS sclr_1 FROM cms_groups c0_', + ); + } + + public function testGeneralCaseWithMultipleWhenClause(): void + { + $this->assertSqlGeneration( + 'SELECT g.id, CASE WHEN (g.id / 2 < 10) THEN 2 WHEN ((g.id / 2) > 20) THEN 1 ELSE 0 END AS test FROM Doctrine\Tests\Models\CMS\CmsGroup g', + 'SELECT c0_.id AS id_0, CASE WHEN (c0_.id / 2 < 10) THEN 2 WHEN ((c0_.id / 2) > 20) THEN 1 ELSE 0 END AS sclr_1 FROM cms_groups c0_', + ); + } + + public function testSimpleCaseWithSingleWhenClause(): void + { + $this->assertSqlGeneration( + "SELECT g FROM Doctrine\Tests\Models\CMS\CmsGroup g WHERE g.id = CASE g.name WHEN 'admin' THEN 1 ELSE 2 END", + "SELECT c0_.id AS id_0, c0_.name AS name_1 FROM cms_groups c0_ WHERE c0_.id = CASE c0_.name WHEN 'admin' THEN 1 ELSE 2 END", + ); + } + + public function testSimpleCaseWithMultipleWhenClause(): void + { + $this->assertSqlGeneration( + "SELECT g FROM Doctrine\Tests\Models\CMS\CmsGroup g WHERE g.id = (CASE g.name WHEN 'admin' THEN 1 WHEN 'moderator' THEN 2 ELSE 3 END)", + "SELECT c0_.id AS id_0, c0_.name AS name_1 FROM cms_groups c0_ WHERE c0_.id = (CASE c0_.name WHEN 'admin' THEN 1 WHEN 'moderator' THEN 2 ELSE 3 END)", + ); + } + + public function testGeneralCaseWithSingleWhenClauseInSubselect(): void + { + $this->assertSqlGeneration( + 'SELECT g FROM Doctrine\Tests\Models\CMS\CmsGroup g WHERE g.id IN (SELECT CASE WHEN ((g2.id / 2) > 18) THEN 2 ELSE 1 END FROM Doctrine\Tests\Models\CMS\CmsGroup g2)', + 'SELECT c0_.id AS id_0, c0_.name AS name_1 FROM cms_groups c0_ WHERE c0_.id IN (SELECT CASE WHEN ((c1_.id / 2) > 18) THEN 2 ELSE 1 END AS sclr_2 FROM cms_groups c1_)', + ); + } + + public function testGeneralCaseWithMultipleWhenClauseInSubselect(): void + { + $this->assertSqlGeneration( + 'SELECT g FROM Doctrine\Tests\Models\CMS\CmsGroup g WHERE g.id IN (SELECT CASE WHEN (g.id / 2 < 10) THEN 3 WHEN ((g.id / 2) > 20) THEN 2 ELSE 1 END FROM Doctrine\Tests\Models\CMS\CmsGroup g2)', + 'SELECT c0_.id AS id_0, c0_.name AS name_1 FROM cms_groups c0_ WHERE c0_.id IN (SELECT CASE WHEN (c0_.id / 2 < 10) THEN 3 WHEN ((c0_.id / 2) > 20) THEN 2 ELSE 1 END AS sclr_2 FROM cms_groups c1_)', + ); + } + + public function testSimpleCaseWithSingleWhenClauseInSubselect(): void + { + $this->assertSqlGeneration( + "SELECT g FROM Doctrine\Tests\Models\CMS\CmsGroup g WHERE g.id IN (SELECT CASE g2.name WHEN 'admin' THEN 1 ELSE 2 END FROM Doctrine\Tests\Models\CMS\CmsGroup g2)", + "SELECT c0_.id AS id_0, c0_.name AS name_1 FROM cms_groups c0_ WHERE c0_.id IN (SELECT CASE c1_.name WHEN 'admin' THEN 1 ELSE 2 END AS sclr_2 FROM cms_groups c1_)", + ); + } + + public function testSimpleCaseWithMultipleWhenClauseInSubselect(): void + { + $this->assertSqlGeneration( + "SELECT g FROM Doctrine\Tests\Models\CMS\CmsGroup g WHERE g.id IN (SELECT CASE g2.name WHEN 'admin' THEN 1 WHEN 'moderator' THEN 2 ELSE 3 END FROM Doctrine\Tests\Models\CMS\CmsGroup g2)", + "SELECT c0_.id AS id_0, c0_.name AS name_1 FROM cms_groups c0_ WHERE c0_.id IN (SELECT CASE c1_.name WHEN 'admin' THEN 1 WHEN 'moderator' THEN 2 ELSE 3 END AS sclr_2 FROM cms_groups c1_)", + ); + } + + #[Group('DDC-1696')] + public function testSimpleCaseWithStringPrimary(): void + { + $this->assertSqlGeneration( + "SELECT g.id, CASE WHEN ((g.id / 2) > 18) THEN 'Foo' ELSE 'Bar' END AS test FROM Doctrine\Tests\Models\CMS\CmsGroup g", + "SELECT c0_.id AS id_0, CASE WHEN ((c0_.id / 2) > 18) THEN 'Foo' ELSE 'Bar' END AS sclr_1 FROM cms_groups c0_", + ); + } + + #[Group('DDC-2205')] + public function testCaseNegativeValuesInThenExpression(): void + { + $this->assertSqlGeneration( + "SELECT CASE g.name WHEN 'admin' THEN - 1 ELSE - 2 END FROM Doctrine\Tests\Models\CMS\CmsGroup g", + "SELECT CASE c0_.name WHEN 'admin' THEN -1 ELSE -2 END AS sclr_0 FROM cms_groups c0_", + ); + + $this->assertSqlGeneration( + "SELECT CASE g.name WHEN 'admin' THEN - 2 WHEN 'guest' THEN - 1 ELSE 0 END FROM Doctrine\Tests\Models\CMS\CmsGroup g", + "SELECT CASE c0_.name WHEN 'admin' THEN -2 WHEN 'guest' THEN -1 ELSE 0 END AS sclr_0 FROM cms_groups c0_", + ); + + $this->assertSqlGeneration( + "SELECT CASE g.name WHEN 'admin' THEN (- 1) ELSE (- 2) END FROM Doctrine\Tests\Models\CMS\CmsGroup g", + "SELECT CASE c0_.name WHEN 'admin' THEN (-1) ELSE (-2) END AS sclr_0 FROM cms_groups c0_", + ); + + $this->assertSqlGeneration( + "SELECT CASE g.name WHEN 'admin' THEN ( - :value) ELSE ( + :value) END FROM Doctrine\Tests\Models\CMS\CmsGroup g", + "SELECT CASE c0_.name WHEN 'admin' THEN (-?) ELSE (+?) END AS sclr_0 FROM cms_groups c0_", + ); + + $this->assertSqlGeneration( + "SELECT CASE g.name WHEN 'admin' THEN ( - g.id) ELSE ( + g.id) END FROM Doctrine\Tests\Models\CMS\CmsGroup g", + "SELECT CASE c0_.name WHEN 'admin' THEN (-c0_.id) ELSE (+c0_.id) END AS sclr_0 FROM cms_groups c0_", + ); + } + + public function testIdentityFunctionWithCompositePrimaryKey(): void + { + $this->assertSqlGeneration( + "SELECT IDENTITY(p.poi, 'long') AS long FROM Doctrine\Tests\Models\Navigation\NavPhotos p", + 'SELECT n0_.poi_long AS sclr_0 FROM navigation_photos n0_', + ); + + $this->assertSqlGeneration( + "SELECT IDENTITY(p.poi, 'lat') AS lat FROM Doctrine\Tests\Models\Navigation\NavPhotos p", + 'SELECT n0_.poi_lat AS sclr_0 FROM navigation_photos n0_', + ); + + $this->assertSqlGeneration( + "SELECT IDENTITY(p.poi, 'long') AS long, IDENTITY(p.poi, 'lat') AS lat FROM Doctrine\Tests\Models\Navigation\NavPhotos p", + 'SELECT n0_.poi_long AS sclr_0, n0_.poi_lat AS sclr_1 FROM navigation_photos n0_', + ); + + $this->assertInvalidSqlGeneration( + "SELECT IDENTITY(p.poi, 'invalid') AS invalid FROM Doctrine\Tests\Models\Navigation\NavPhotos p", + QueryException::class, + ); + } + + #[Group('DDC-2519')] + public function testPartialWithAssociationIdentifier(): void + { + $this->assertSqlGeneration( + 'SELECT PARTIAL l.{_source, _target} FROM Doctrine\Tests\Models\Legacy\LegacyUserReference l', + 'SELECT l0_.iUserIdSource AS iUserIdSource_0, l0_.iUserIdTarget AS iUserIdTarget_1 FROM legacy_users_reference l0_', + ); + + $this->assertSqlGeneration( + 'SELECT PARTIAL l.{_description, _source, _target} FROM Doctrine\Tests\Models\Legacy\LegacyUserReference l', + 'SELECT l0_.description AS description_0, l0_.iUserIdSource AS iUserIdSource_1, l0_.iUserIdTarget AS iUserIdTarget_2 FROM legacy_users_reference l0_', + ); + } + + #[Group('DDC-1339')] + public function testIdentityFunctionInSelectClause(): void + { + $this->assertSqlGeneration( + 'SELECT IDENTITY(u.email) as email_id FROM Doctrine\Tests\Models\CMS\CmsUser u', + 'SELECT c0_.email_id AS sclr_0 FROM cms_users c0_', + ); + } + + public function testIdentityFunctionInJoinedSubclass(): void + { + //relation is in the subclass (CompanyManager) we are querying + $this->assertSqlGeneration( + 'SELECT m, IDENTITY(m.car) as car_id FROM Doctrine\Tests\Models\Company\CompanyManager m', + 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c2_.title AS title_5, c2_.car_id AS sclr_6, c0_.discr AS discr_7, c0_.spouse_id AS spouse_id_8, c2_.car_id AS car_id_9 FROM company_managers c2_ INNER JOIN company_employees c1_ ON c2_.id = c1_.id INNER JOIN company_persons c0_ ON c2_.id = c0_.id', + ); + + //relation is in the base class (CompanyPerson). + $this->assertSqlGeneration( + 'SELECT m, IDENTITY(m.spouse) as spouse_id FROM Doctrine\Tests\Models\Company\CompanyManager m', + 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c2_.title AS title_5, c0_.spouse_id AS sclr_6, c0_.discr AS discr_7, c0_.spouse_id AS spouse_id_8, c2_.car_id AS car_id_9 FROM company_managers c2_ INNER JOIN company_employees c1_ ON c2_.id = c1_.id INNER JOIN company_persons c0_ ON c2_.id = c0_.id', + ); + } + + #[Group('DDC-1339')] + public function testIdentityFunctionDoesNotAcceptStateField(): void + { + $this->assertInvalidSqlGeneration( + 'SELECT IDENTITY(u.name) as name FROM Doctrine\Tests\Models\CMS\CmsUser u', + QueryException::class, + ); + } + + #[Group('DDC-1389')] + public function testInheritanceTypeJoinInRootClassWithDisabledForcePartialLoad(): void + { + $this->assertSqlGeneration( + 'SELECT p FROM Doctrine\Tests\Models\Company\CompanyPerson p', + 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.title AS title_2, c2_.salary AS salary_3, c2_.department AS department_4, c2_.startDate AS startDate_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c1_.car_id AS car_id_8 FROM company_persons c0_ LEFT JOIN company_managers c1_ ON c0_.id = c1_.id LEFT JOIN company_employees c2_ ON c0_.id = c2_.id', + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false], + ); + } + + #[Group('DDC-1389')] + public function testInheritanceTypeJoinInRootClassWithEnabledForcePartialLoad(): void + { + $this->assertSqlGeneration( + 'SELECT p FROM Doctrine\Tests\Models\Company\CompanyPerson p', + 'SELECT c0_.id AS id_0, c0_.name AS name_1, c0_.discr AS discr_2 FROM company_persons c0_', + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true], + ); + } + + #[Group('DDC-1389')] + public function testInheritanceTypeJoinInChildClassWithDisabledForcePartialLoad(): void + { + $this->assertSqlGeneration( + 'SELECT e FROM Doctrine\Tests\Models\Company\CompanyEmployee e', + 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c2_.title AS title_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c2_.car_id AS car_id_8 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id LEFT JOIN company_managers c2_ ON c1_.id = c2_.id', + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false], + ); + } + + #[Group('DDC-1389')] + public function testInheritanceTypeJoinInChildClassWithEnabledForcePartialLoad(): void + { + $this->assertSqlGeneration( + 'SELECT e FROM Doctrine\Tests\Models\Company\CompanyEmployee e', + 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c0_.discr AS discr_5 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id', + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true], + ); + } + + #[Group('DDC-1389')] + public function testInheritanceTypeJoinInLeafClassWithDisabledForcePartialLoad(): void + { + $this->assertSqlGeneration( + 'SELECT m FROM Doctrine\Tests\Models\Company\CompanyManager m', + 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c2_.title AS title_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c2_.car_id AS car_id_8 FROM company_managers c2_ INNER JOIN company_employees c1_ ON c2_.id = c1_.id INNER JOIN company_persons c0_ ON c2_.id = c0_.id', + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false], + ); + } + + #[Group('DDC-1389')] + public function testInheritanceTypeJoinInLeafClassWithEnabledForcePartialLoad(): void + { + $this->assertSqlGeneration( + 'SELECT m FROM Doctrine\Tests\Models\Company\CompanyManager m', + 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c2_.title AS title_5, c0_.discr AS discr_6 FROM company_managers c2_ INNER JOIN company_employees c1_ ON c2_.id = c1_.id INNER JOIN company_persons c0_ ON c2_.id = c0_.id', + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true], + ); + } + + #[Group('DDC-1389')] + public function testInheritanceTypeSingleTableInRootClassWithDisabledForcePartialLoad(): void + { + $this->assertSqlGeneration( + 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c', + "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6, c0_.salesPerson_id AS salesPerson_id_7 FROM company_contracts c0_ WHERE c0_.discr IN ('fix', 'flexible', 'flexultra')", + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false], + ); + } + + #[Group('DDC-1389')] + public function testInheritanceTypeSingleTableInRootClassWithEnabledForcePartialLoad(): void + { + $this->assertSqlGeneration( + 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c', + "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6 FROM company_contracts c0_ WHERE c0_.discr IN ('fix', 'flexible', 'flexultra')", + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true], + ); + } + + #[Group('DDC-1389')] + public function testInheritanceTypeSingleTableInChildClassWithDisabledForcePartialLoad(): void + { + $this->assertSqlGeneration( + 'SELECT fc FROM Doctrine\Tests\Models\Company\CompanyFlexContract fc', + "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.hoursWorked AS hoursWorked_2, c0_.pricePerHour AS pricePerHour_3, c0_.maxPrice AS maxPrice_4, c0_.discr AS discr_5, c0_.salesPerson_id AS salesPerson_id_6 FROM company_contracts c0_ WHERE c0_.discr IN ('flexible', 'flexultra')", + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false], + ); + } + + #[Group('DDC-1389')] + public function testInheritanceTypeSingleTableInChildClassWithEnabledForcePartialLoad(): void + { + $this->assertSqlGeneration( + 'SELECT fc FROM Doctrine\Tests\Models\Company\CompanyFlexContract fc', + "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.hoursWorked AS hoursWorked_2, c0_.pricePerHour AS pricePerHour_3, c0_.maxPrice AS maxPrice_4, c0_.discr AS discr_5 FROM company_contracts c0_ WHERE c0_.discr IN ('flexible', 'flexultra')", + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true], + ); + } + + #[Group('DDC-1389')] + public function testInheritanceTypeSingleTableInLeafClassWithDisabledForcePartialLoad(): void + { + $this->assertSqlGeneration( + 'SELECT fuc FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract fuc', + "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.hoursWorked AS hoursWorked_2, c0_.pricePerHour AS pricePerHour_3, c0_.maxPrice AS maxPrice_4, c0_.discr AS discr_5, c0_.salesPerson_id AS salesPerson_id_6 FROM company_contracts c0_ WHERE c0_.discr IN ('flexultra')", + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false], + ); + } + + #[Group('DDC-1389')] + public function testInheritanceTypeSingleTableInLeafClassWithEnabledForcePartialLoad(): void + { + $this->assertSqlGeneration( + 'SELECT fuc FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract fuc', + "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.hoursWorked AS hoursWorked_2, c0_.pricePerHour AS pricePerHour_3, c0_.maxPrice AS maxPrice_4, c0_.discr AS discr_5 FROM company_contracts c0_ WHERE c0_.discr IN ('flexultra')", + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true], + ); + } + + #[Group('DDC-1161')] + public function testSelfReferenceWithOneToOneDoesNotDuplicateAlias(): void + { + $this->assertSqlGeneration( + 'SELECT p, pp FROM Doctrine\Tests\Models\Company\CompanyPerson p JOIN p.spouse pp', + 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.title AS title_2, c2_.salary AS salary_3, c2_.department AS department_4, c2_.startDate AS startDate_5, c3_.id AS id_6, c3_.name AS name_7, c4_.title AS title_8, c5_.salary AS salary_9, c5_.department AS department_10, c5_.startDate AS startDate_11, c0_.discr AS discr_12, c0_.spouse_id AS spouse_id_13, c1_.car_id AS car_id_14, c3_.discr AS discr_15, c3_.spouse_id AS spouse_id_16, c4_.car_id AS car_id_17 FROM company_persons c0_ LEFT JOIN company_managers c1_ ON c0_.id = c1_.id LEFT JOIN company_employees c2_ ON c0_.id = c2_.id INNER JOIN company_persons c3_ ON c0_.spouse_id = c3_.id LEFT JOIN company_managers c4_ ON c3_.id = c4_.id LEFT JOIN company_employees c5_ ON c3_.id = c5_.id', + ); + } + + #[Group('DDC-1384')] + public function testAliasDoesNotExceedPlatformDefinedLength(): void + { + $this->assertSqlGeneration( + 'SELECT m FROM ' . __NAMESPACE__ . '\\DDC1384Model m', + 'SELECT d0_.aVeryLongIdentifierThatShouldBeShortenedByTheSQLWalkerFooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo AS ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo_0 FROM DDC1384Model d0_', + ); + } + + #[Group('DDC-331')] + #[Group('DDC-1384')] + public function testIssue331(): void + { + $this->assertSqlGeneration( + 'SELECT e.name FROM Doctrine\Tests\Models\Company\CompanyEmployee e', + 'SELECT c0_.name AS name_0 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id LEFT JOIN company_managers c2_ ON c1_.id = c2_.id', + ); + } + + #[Group('DDC-1435')] + public function testForeignKeyAsPrimaryKeySubselect(): void + { + $this->assertSqlGeneration( + 'SELECT s FROM Doctrine\Tests\Models\DDC117\DDC117Article s WHERE EXISTS (SELECT r FROM Doctrine\Tests\Models\DDC117\DDC117Reference r WHERE r.source = s)', + 'SELECT d0_.article_id AS article_id_0, d0_.title AS title_1 FROM DDC117Article d0_ WHERE EXISTS (SELECT d1_.source_id, d1_.target_id FROM DDC117Reference d1_ WHERE d1_.source_id = d0_.article_id)', + ); + } + + #[Group('DDC-1474')] + public function testSelectWithArithmeticExpressionBeforeField(): void + { + $this->assertSqlGeneration( + 'SELECT - e.value AS value, e.id FROM ' . __NAMESPACE__ . '\DDC1474Entity e', + 'SELECT -d0_.value AS sclr_0, d0_.id AS id_1 FROM DDC1474Entity d0_', + ); + + $this->assertSqlGeneration( + 'SELECT e.id, + e.value AS value FROM ' . __NAMESPACE__ . '\DDC1474Entity e', + 'SELECT d0_.id AS id_0, +d0_.value AS sclr_1 FROM DDC1474Entity d0_', + ); + } + + #[Group('DDC-1430')] + public function testGroupByAllFieldsWhenObjectHasForeignKeys(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY u', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ GROUP BY c0_.id, c0_.status, c0_.username, c0_.name, c0_.email_id', + ); + + $this->assertSqlGeneration( + 'SELECT e FROM Doctrine\Tests\Models\CMS\CmsEmployee e GROUP BY e', + 'SELECT c0_.id AS id_0, c0_.name AS name_1, c0_.spouse_id AS spouse_id_2 FROM cms_employees c0_ GROUP BY c0_.id, c0_.name, c0_.spouse_id', + ); + } + + #[Group('DDC-1236')] + public function testGroupBySupportsResultVariable(): void + { + $this->assertSqlGeneration( + 'SELECT u, u.status AS st FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY st', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.status AS status_4, c0_.email_id AS email_id_5 FROM cms_users c0_ GROUP BY c0_.status', + ); + } + + #[Group('DDC-1236')] + public function testGroupBySupportsIdentificationVariable(): void + { + $this->assertSqlGeneration( + 'SELECT u AS user FROM Doctrine\Tests\Models\CMS\CmsUser u GROUP BY user', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ GROUP BY id_0, status_1, username_2, name_3', + ); + } + + #[Group('DDC-1213')] + public function testSupportsBitComparison(): void + { + $this->assertSqlGeneration( + 'SELECT BIT_OR(4,2), BIT_AND(4,2), u FROM Doctrine\Tests\Models\CMS\CmsUser u', + 'SELECT (4 | 2) AS sclr_0, (4 & 2) AS sclr_1, c0_.id AS id_2, c0_.status AS status_3, c0_.username AS username_4, c0_.name AS name_5, c0_.email_id AS email_id_6 FROM cms_users c0_', + ); + $this->assertSqlGeneration( + 'SELECT BIT_OR(u.id,2), BIT_AND(u.id,2) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE BIT_OR(u.id,2) > 0', + 'SELECT (c0_.id | 2) AS sclr_0, (c0_.id & 2) AS sclr_1 FROM cms_users c0_ WHERE (c0_.id | 2) > 0', + ); + $this->assertSqlGeneration( + 'SELECT BIT_OR(u.id,2), BIT_AND(u.id,2) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE BIT_AND(u.id , 4) > 0', + 'SELECT (c0_.id | 2) AS sclr_0, (c0_.id & 2) AS sclr_1 FROM cms_users c0_ WHERE (c0_.id & 4) > 0', + ); + $this->assertSqlGeneration( + 'SELECT BIT_OR(u.id,2), BIT_AND(u.id,2) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE BIT_OR(u.id , 2) > 0 OR BIT_AND(u.id , 4) > 0', + 'SELECT (c0_.id | 2) AS sclr_0, (c0_.id & 2) AS sclr_1 FROM cms_users c0_ WHERE (c0_.id | 2) > 0 OR (c0_.id & 4) > 0', + ); + } + + #[Group('DDC-1539')] + public function testParenthesesOnTheLeftHandOfComparison(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u where ( (u.id + u.id) * u.id ) > 100', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE ((c0_.id + c0_.id) * c0_.id) > 100', + ); + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u where (u.id + u.id) * u.id > 100', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE (c0_.id + c0_.id) * c0_.id > 100', + ); + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u where 100 < (u.id + u.id) * u.id ', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE 100 < (c0_.id + c0_.id) * c0_.id', + ); + } + + public function testSupportsParenthesisExpressionInSubSelect(): void + { + $this->assertSqlGeneration( + 'SELECT u.id, (SELECT (1000*SUM(subU.id)/SUM(subU.id)) FROM Doctrine\Tests\Models\CMS\CmsUser subU where subU.id = u.id) AS subSelect FROM Doctrine\Tests\Models\CMS\CmsUser u', + 'SELECT c0_.id AS id_0, (SELECT (1000 * SUM(c1_.id) / SUM(c1_.id)) FROM cms_users c1_ WHERE c1_.id = c0_.id) AS sclr_1 FROM cms_users c0_', + ); + } + + #[Group('DDC-1557')] + public function testSupportsSubSqlFunction(): void + { + $this->assertSqlGeneration( + 'SELECT u1 FROM Doctrine\Tests\Models\CMS\CmsUser u1 WHERE u1.name IN ( SELECT TRIM(u2.name) FROM Doctrine\Tests\Models\CMS\CmsUser u2 )', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE c0_.name IN (SELECT TRIM(c1_.name) AS sclr_5 FROM cms_users c1_)', + ); + $this->assertSqlGeneration( + 'SELECT u1 FROM Doctrine\Tests\Models\CMS\CmsUser u1 WHERE u1.name IN ( SELECT TRIM(u2.name) FROM Doctrine\Tests\Models\CMS\CmsUser u2 WHERE LOWER(u2.name) LIKE \'%fabio%\')', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE c0_.name IN (SELECT TRIM(c1_.name) AS sclr_5 FROM cms_users c1_ WHERE LOWER(c1_.name) LIKE \'%fabio%\')', + ); + $this->assertSqlGeneration( + 'SELECT u1 FROM Doctrine\Tests\Models\CMS\CmsUser u1 WHERE u1.email IN ( SELECT TRIM(IDENTITY(u2.email)) FROM Doctrine\Tests\Models\CMS\CmsUser u2 )', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE c0_.email_id IN (SELECT TRIM(c1_.email_id) AS sclr_5 FROM cms_users c1_)', + ); + $this->assertSqlGeneration( + 'SELECT u1 FROM Doctrine\Tests\Models\CMS\CmsUser u1 WHERE u1.email IN ( SELECT IDENTITY(u2.email) FROM Doctrine\Tests\Models\CMS\CmsUser u2 )', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE c0_.email_id IN (SELECT c1_.email_id AS sclr_5 FROM cms_users c1_)', + ); + $this->assertSqlGeneration( + 'SELECT u1 FROM Doctrine\Tests\Models\CMS\CmsUser u1 WHERE COUNT(u1.id) = ( SELECT SUM(u2.id) FROM Doctrine\Tests\Models\CMS\CmsUser u2 )', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE COUNT(c0_.id) = (SELECT SUM(c1_.id) AS sclr_5 FROM cms_users c1_)', + ); + $this->assertSqlGeneration( + 'SELECT u1 FROM Doctrine\Tests\Models\CMS\CmsUser u1 WHERE COUNT(u1.id) <= ( SELECT SUM(u2.id) + COUNT(u2.email) FROM Doctrine\Tests\Models\CMS\CmsUser u2 )', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE COUNT(c0_.id) <= (SELECT SUM(c1_.id) + COUNT(c1_.email_id) AS sclr_5 FROM cms_users c1_)', + ); + } + + #[Group('DDC-1574')] + public function testSupportsNewOperator(): void + { + $this->assertSqlGeneration( + 'SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO(u.name, e.email, a.city) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e JOIN u.address a', + 'SELECT c0_.name AS sclr_0, c1_.email AS sclr_1, c2_.city AS sclr_2 FROM cms_users c0_ INNER JOIN cms_emails c1_ ON c0_.email_id = c1_.id INNER JOIN cms_addresses c2_ ON c0_.id = c2_.user_id', + ); + + $this->assertSqlGeneration( + 'SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO(u.name, e.email, a.id + u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e JOIN u.address a', + 'SELECT c0_.name AS sclr_0, c1_.email AS sclr_1, c2_.id + c0_.id AS sclr_2 FROM cms_users c0_ INNER JOIN cms_emails c1_ ON c0_.email_id = c1_.id INNER JOIN cms_addresses c2_ ON c0_.id = c2_.user_id', + ); + + $this->assertSqlGeneration( + 'SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO(u.name, e.email, a.city, COUNT(p)) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e JOIN u.address a JOIN u.phonenumbers p', + 'SELECT c0_.name AS sclr_0, c1_.email AS sclr_1, c2_.city AS sclr_2, COUNT(c3_.phonenumber) AS sclr_3 FROM cms_users c0_ INNER JOIN cms_emails c1_ ON c0_.email_id = c1_.id INNER JOIN cms_addresses c2_ ON c0_.id = c2_.user_id INNER JOIN cms_phonenumbers c3_ ON c0_.id = c3_.user_id', + ); + + $this->assertSqlGeneration( + 'SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO(u.name, e.email, a.city, COUNT(p) + u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e JOIN u.address a JOIN u.phonenumbers p', + 'SELECT c0_.name AS sclr_0, c1_.email AS sclr_1, c2_.city AS sclr_2, COUNT(c3_.phonenumber) + c0_.id AS sclr_3 FROM cms_users c0_ INNER JOIN cms_emails c1_ ON c0_.email_id = c1_.id INNER JOIN cms_addresses c2_ ON c0_.id = c2_.user_id INNER JOIN cms_phonenumbers c3_ ON c0_.id = c3_.user_id', + ); + + $this->assertSqlGeneration( + 'SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO(a.id, a.country, a.city), new Doctrine\Tests\Models\CMS\CmsAddressDTO(u.name, e.email) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e JOIN u.address a ORDER BY u.name', + 'SELECT c0_.id AS sclr_0, c0_.country AS sclr_1, c0_.city AS sclr_2, c1_.name AS sclr_3, c2_.email AS sclr_4 FROM cms_users c1_ INNER JOIN cms_emails c2_ ON c1_.email_id = c2_.id INNER JOIN cms_addresses c0_ ON c1_.id = c0_.user_id ORDER BY c1_.name ASC', + ); + + $this->assertSqlGeneration( + 'SELECT new Doctrine\Tests\Models\CMS\CmsUserDTO(a.id, (SELECT 1 FROM Doctrine\Tests\Models\CMS\CmsUser su), a.country, a.city), new Doctrine\Tests\Models\CMS\CmsAddressDTO(u.name, e.email) FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e JOIN u.address a ORDER BY u.name', + 'SELECT c0_.id AS sclr_0, (SELECT 1 AS sclr_2 FROM cms_users c1_) AS sclr_1, c0_.country AS sclr_3, c0_.city AS sclr_4, c2_.name AS sclr_5, c3_.email AS sclr_6 FROM cms_users c2_ INNER JOIN cms_emails c3_ ON c2_.email_id = c3_.id INNER JOIN cms_addresses c0_ ON c2_.id = c0_.user_id ORDER BY c2_.name ASC', + ); + } + + #[Group('DDC-2234')] + public function testWhereFunctionIsNullComparisonExpression(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE IDENTITY(u.email) IS NULL', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE c0_.email_id IS NULL', + ); + + $this->assertSqlGeneration( + "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE NULLIF(u.name, 'FabioBatSilva') IS NULL AND IDENTITY(u.email) IS NOT NULL", + "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE NULLIF(c0_.name, 'FabioBatSilva') IS NULL AND c0_.email_id IS NOT NULL", + ); + + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE IDENTITY(u.email) IS NOT NULL', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE c0_.email_id IS NOT NULL', + ); + + $this->assertSqlGeneration( + "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE NULLIF(u.name, 'FabioBatSilva') IS NOT NULL", + "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE NULLIF(c0_.name, 'FabioBatSilva') IS NOT NULL", + ); + + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE COALESCE(u.name, u.id) IS NOT NULL', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE COALESCE(c0_.name, c0_.id) IS NOT NULL', + ); + + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE COALESCE(u.id, IDENTITY(u.email)) IS NOT NULL', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE COALESCE(c0_.id, c0_.email_id) IS NOT NULL', + ); + + $this->assertSqlGeneration( + "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE COALESCE(IDENTITY(u.email), NULLIF(u.name, 'FabioBatSilva')) IS NOT NULL", + "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE COALESCE(c0_.email_id, NULLIF(c0_.name, 'FabioBatSilva')) IS NOT NULL", + ); + } + + public function testCustomTypeValueSql(): void + { + if (DBALType::hasType('negative_to_positive')) { + DBALType::overrideType('negative_to_positive', NegativeToPositiveType::class); + } else { + DBALType::addType('negative_to_positive', NegativeToPositiveType::class); + } + + $this->assertSqlGeneration( + 'SELECT p.customInteger FROM Doctrine\Tests\Models\CustomType\CustomTypeParent p WHERE p.id = 1', + 'SELECT -(c0_.customInteger) AS customInteger_0 FROM customtype_parents c0_ WHERE c0_.id = 1', + ); + } + + public function testCustomTypeValueSqlIgnoresIdentifierColumn(): void + { + if (DBALType::hasType('negative_to_positive')) { + DBALType::overrideType('negative_to_positive', NegativeToPositiveType::class); + } else { + DBALType::addType('negative_to_positive', NegativeToPositiveType::class); + } + + $this->assertSqlGeneration( + 'SELECT p.id FROM Doctrine\Tests\Models\CustomType\CustomTypeParent p WHERE p.id = 1', + 'SELECT c0_.id AS id_0 FROM customtype_parents c0_ WHERE c0_.id = 1', + ); + } + + public function testCustomTypeValueSqlForAllFields(): void + { + if (DBALType::hasType('negative_to_positive')) { + DBALType::overrideType('negative_to_positive', NegativeToPositiveType::class); + } else { + DBALType::addType('negative_to_positive', NegativeToPositiveType::class); + } + + $this->assertSqlGeneration( + 'SELECT p FROM Doctrine\Tests\Models\CustomType\CustomTypeParent p', + 'SELECT c0_.id AS id_0, -(c0_.customInteger) AS customInteger_1, c0_.child_id AS child_id_2 FROM customtype_parents c0_', + ); + } + + public function testCustomTypeValueSqlForPartialObject(): void + { + if (DBALType::hasType('negative_to_positive')) { + DBALType::overrideType('negative_to_positive', NegativeToPositiveType::class); + } else { + DBALType::addType('negative_to_positive', NegativeToPositiveType::class); + } + + $this->assertSqlGeneration( + 'SELECT partial p.{id, customInteger} FROM Doctrine\Tests\Models\CustomType\CustomTypeParent p', + 'SELECT c0_.id AS id_0, -(c0_.customInteger) AS customInteger_1, c0_.child_id AS child_id_2 FROM customtype_parents c0_', + ); + } + + #[Group('DDC-1529')] + public function testMultipleFromAndInheritanceCondition(): void + { + $this->assertSqlGeneration( + 'SELECT fix, flex FROM Doctrine\Tests\Models\Company\CompanyFixContract fix, Doctrine\Tests\Models\Company\CompanyFlexContract flex', + "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c1_.id AS id_3, c1_.completed AS completed_4, c1_.hoursWorked AS hoursWorked_5, c1_.pricePerHour AS pricePerHour_6, c1_.maxPrice AS maxPrice_7, c0_.discr AS discr_8, c0_.salesPerson_id AS salesPerson_id_9, c1_.discr AS discr_10, c1_.salesPerson_id AS salesPerson_id_11 FROM company_contracts c0_, company_contracts c1_ WHERE (c0_.discr IN ('fix') AND c1_.discr IN ('flexible', 'flexultra'))", + ); + } + + #[Group('DDC-775')] + public function testOrderByClauseSupportsSimpleArithmeticExpression(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.id + 1 ', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ ORDER BY c0_.id + 1 ASC', + ); + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY ( ( (u.id + 1) * (u.id - 1) ) / 2)', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ ORDER BY (((c0_.id + 1) * (c0_.id - 1)) / 2) ASC', + ); + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY ((u.id + 5000) * u.id + 3) ', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ ORDER BY ((c0_.id + 5000) * c0_.id + 3) ASC', + ); + } + + public function testOrderByClauseSupportsFunction(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY CONCAT(u.username, u.name) ', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ ORDER BY c0_.username || c0_.name ASC', + ); + } + + #[Group('DDC-1719')] + public function testStripNonAlphanumericCharactersFromAlias(): void + { + $this->assertSqlGeneration( + 'SELECT e FROM Doctrine\Tests\Models\Generic\NonAlphaColumnsEntity e', + 'SELECT n0_."simple-entity-id" AS simpleentityid_0, n0_."simple-entity-value" AS simpleentityvalue_1 FROM "not-a-simple-entity" n0_', + ); + + $this->assertSqlGeneration( + 'SELECT e.value FROM Doctrine\Tests\Models\Generic\NonAlphaColumnsEntity e ORDER BY e.value', + 'SELECT n0_."simple-entity-value" AS simpleentityvalue_0 FROM "not-a-simple-entity" n0_ ORDER BY n0_."simple-entity-value" ASC', + ); + + $this->assertSqlGeneration( + 'SELECT TRIM(e.value) FROM Doctrine\Tests\Models\Generic\NonAlphaColumnsEntity e ORDER BY e.value', + 'SELECT TRIM(n0_."simple-entity-value") AS sclr_0 FROM "not-a-simple-entity" n0_ ORDER BY n0_."simple-entity-value" ASC', + ); + } + + #[Group('DDC-2435')] + public function testColumnNameWithNumbersAndNonAlphanumericCharacters(): void + { + $this->assertSqlGeneration( + 'SELECT e FROM Doctrine\Tests\Models\Quote\NumericEntity e', + 'SELECT t0_."1:1" AS 11_0, t0_."2:2" AS 22_1 FROM table t0_', + ); + + $this->assertSqlGeneration( + 'SELECT e.value FROM Doctrine\Tests\Models\Quote\NumericEntity e', + 'SELECT t0_."2:2" AS 22_0 FROM table t0_', + ); + + $this->assertSqlGeneration( + 'SELECT TRIM(e.value) FROM Doctrine\Tests\Models\Quote\NumericEntity e', + 'SELECT TRIM(t0_."2:2") AS sclr_0 FROM table t0_', + ); + } + + #[Group('DDC-1845')] + public function testQuotedTableDeclaration(): void + { + $this->assertSqlGeneration( + 'SELECT u FROM Doctrine\Tests\Models\Quote\User u', + 'SELECT q0_."user-id" AS userid_0, q0_."user-name" AS username_1 FROM "quote-user" q0_', + ); + } + + #[Group('DDC-1845')] + public function testQuotedWalkJoinVariableDeclaration(): void + { + $this->assertSqlGeneration( + 'SELECT u, a FROM Doctrine\Tests\Models\Quote\User u JOIN u.address a', + <<<'SQL' +SELECT q0_."user-id" AS userid_0, q0_."user-name" AS username_1, q1_."address-id" AS addressid_2, q1_."address-zip" AS addresszip_3, q1_.type AS type_4, q1_."user-id" AS userid_5, q1_."city-id" AS cityid_6 FROM "quote-user" q0_ INNER JOIN "quote-address" q1_ ON q0_."user-id" = q1_."user-id" AND q1_.type IN ('simple', 'full') +SQL, + ); + + $this->assertSqlGeneration( + 'SELECT u, p FROM Doctrine\Tests\Models\Quote\User u JOIN u.phones p', + 'SELECT q0_."user-id" AS userid_0, q0_."user-name" AS username_1, q1_."phone-number" AS phonenumber_2, q1_."user-id" AS userid_3 FROM "quote-user" q0_ INNER JOIN "quote-phone" q1_ ON q0_."user-id" = q1_."user-id"', + ); + + $this->assertSqlGeneration( + 'SELECT u, g FROM Doctrine\Tests\Models\Quote\User u JOIN u.groups g', + 'SELECT q0_."user-id" AS userid_0, q0_."user-name" AS username_1, q1_."group-id" AS groupid_2, q1_."group-name" AS groupname_3, q1_."parent-id" AS parentid_4 FROM "quote-user" q0_ INNER JOIN "quote-users-groups" q2_ ON q0_."user-id" = q2_."user-id" INNER JOIN "quote-group" q1_ ON q1_."group-id" = q2_."group-id"', + ); + + $this->assertSqlGeneration( + 'SELECT a, u FROM Doctrine\Tests\Models\Quote\Address a JOIN a.user u', + 'SELECT q0_."address-id" AS addressid_0, q0_."address-zip" AS addresszip_1, q1_."user-id" AS userid_2, q1_."user-name" AS username_3, q0_.type AS type_4, q0_."user-id" AS userid_5, q0_."city-id" AS cityid_6 FROM "quote-address" q0_ INNER JOIN "quote-user" q1_ ON q0_."user-id" = q1_."user-id" WHERE q0_.type IN (\'simple\', \'full\')', + ); + + $this->assertSqlGeneration( + 'SELECT g, u FROM Doctrine\Tests\Models\Quote\Group g JOIN g.users u', + 'SELECT q0_."group-id" AS groupid_0, q0_."group-name" AS groupname_1, q1_."user-id" AS userid_2, q1_."user-name" AS username_3, q0_."parent-id" AS parentid_4 FROM "quote-group" q0_ INNER JOIN "quote-users-groups" q2_ ON q0_."group-id" = q2_."group-id" INNER JOIN "quote-user" q1_ ON q1_."user-id" = q2_."user-id"', + ); + + $this->assertSqlGeneration( + 'SELECT g, p FROM Doctrine\Tests\Models\Quote\Group g JOIN g.parent p', + 'SELECT q0_."group-id" AS groupid_0, q0_."group-name" AS groupname_1, q1_."group-id" AS groupid_2, q1_."group-name" AS groupname_3, q0_."parent-id" AS parentid_4, q1_."parent-id" AS parentid_5 FROM "quote-group" q0_ INNER JOIN "quote-group" q1_ ON q0_."parent-id" = q1_."group-id"', + ); + } + + #[Group('DDC-2208')] + public function testCaseThenParameterArithmeticExpression(): void + { + $this->assertSqlGeneration( + 'SELECT SUM(CASE WHEN e.salary <= :value THEN e.salary - :value WHEN e.salary >= :value THEN :value - e.salary ELSE 0 END) FROM Doctrine\Tests\Models\Company\CompanyEmployee e', + 'SELECT SUM(CASE WHEN c0_.salary <= ? THEN c0_.salary - ? WHEN c0_.salary >= ? THEN ? - c0_.salary ELSE 0 END) AS sclr_0 FROM company_employees c0_ INNER JOIN company_persons c1_ ON c0_.id = c1_.id LEFT JOIN company_managers c2_ ON c0_.id = c2_.id', + ); + + $this->assertSqlGeneration( + 'SELECT SUM(CASE WHEN e.salary <= :value THEN e.salary - :value WHEN e.salary >= :value THEN :value - e.salary ELSE e.salary + 0 END) FROM Doctrine\Tests\Models\Company\CompanyEmployee e', + 'SELECT SUM(CASE WHEN c0_.salary <= ? THEN c0_.salary - ? WHEN c0_.salary >= ? THEN ? - c0_.salary ELSE c0_.salary + 0 END) AS sclr_0 FROM company_employees c0_ INNER JOIN company_persons c1_ ON c0_.id = c1_.id LEFT JOIN company_managers c2_ ON c0_.id = c2_.id', + ); + + $this->assertSqlGeneration( + 'SELECT SUM(CASE WHEN e.salary <= :value THEN (e.salary - :value) WHEN e.salary >= :value THEN (:value - e.salary) ELSE (e.salary + :value) END) FROM Doctrine\Tests\Models\Company\CompanyEmployee e', + 'SELECT SUM(CASE WHEN c0_.salary <= ? THEN (c0_.salary - ?) WHEN c0_.salary >= ? THEN (? - c0_.salary) ELSE (c0_.salary + ?) END) AS sclr_0 FROM company_employees c0_ INNER JOIN company_persons c1_ ON c0_.id = c1_.id LEFT JOIN company_managers c2_ ON c0_.id = c2_.id', + ); + } + + #[Group('DDC-2268')] + public function testCaseThenFunction(): void + { + $this->entityManager = $this->createTestEntityManagerWithPlatform(new PostgreSQLPlatform()); + + $this->assertSqlGeneration( + 'SELECT CASE WHEN LENGTH(u.name) <> 0 THEN CONCAT(u.id, u.name) ELSE u.id END AS name FROM Doctrine\Tests\Models\CMS\CmsUser u', + 'SELECT CASE WHEN LENGTH(c0_.name) <> 0 THEN c0_.id || c0_.name ELSE c0_.id END AS sclr_0 FROM cms_users c0_', + ); + + $this->assertSqlGeneration( + 'SELECT CASE WHEN LENGTH(u.name) <> LENGTH(TRIM(u.name)) THEN TRIM(u.name) ELSE u.name END AS name FROM Doctrine\Tests\Models\CMS\CmsUser u', + 'SELECT CASE WHEN LENGTH(c0_.name) <> LENGTH(TRIM(c0_.name)) THEN TRIM(c0_.name) ELSE c0_.name END AS sclr_0 FROM cms_users c0_', + ); + + $this->assertSqlGeneration( + 'SELECT CASE WHEN LENGTH(u.name) > :value THEN SUBSTRING(u.name, 0, :value) ELSE TRIM(u.name) END AS name FROM Doctrine\Tests\Models\CMS\CmsUser u', + 'SELECT CASE WHEN LENGTH(c0_.name) > ? THEN SUBSTRING(c0_.name FROM 0 FOR ?) ELSE TRIM(c0_.name) END AS sclr_0 FROM cms_users c0_', + ); + } + + #[Group('DDC-2268')] + public function testSupportsMoreThanTwoParametersInConcatFunction(): void + { + $this->entityManager = $this->createTestEntityManagerWithPlatform(new MySQLPlatform()); + + $this->assertSqlGeneration( + "SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CONCAT(u.name, u.status, 's') = ?1", + "SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE CONCAT(c0_.name, c0_.status, 's') = ?", + ); + $this->assertSqlGeneration( + 'SELECT CONCAT(u.id, u.name, u.status) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1', + 'SELECT CONCAT(c0_.id, c0_.name, c0_.status) AS sclr_0 FROM cms_users c0_ WHERE c0_.id = ?', + ); + } + + #[Group('DDC-2188')] + public function testArithmeticPriority(): void + { + $this->assertSqlGeneration( + 'SELECT 100/(2*2) FROM Doctrine\Tests\Models\CMS\CmsUser u', + 'SELECT 100 / (2 * 2) AS sclr_0 FROM cms_users c0_', + ); + + $this->assertSqlGeneration( + 'SELECT (u.id / (u.id * 2)) FROM Doctrine\Tests\Models\CMS\CmsUser u', + 'SELECT (c0_.id / (c0_.id * 2)) AS sclr_0 FROM cms_users c0_', + ); + + $this->assertSqlGeneration( + 'SELECT 100/(2*2) + (u.id / (u.id * 2)) FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE (u.id / (u.id * 2)) > 0', + 'SELECT 100 / (2 * 2) + (c0_.id / (c0_.id * 2)) AS sclr_0 FROM cms_users c0_ WHERE (c0_.id / (c0_.id * 2)) > 0', + ); + } + + #[Group('DDC-2475')] + public function testOrderByClauseShouldReplaceOrderByRelationMapping(): void + { + $this->assertSqlGeneration( + 'SELECT r, b FROM Doctrine\Tests\Models\Routing\RoutingRoute r JOIN r.bookings b', + 'SELECT r0_.id AS id_0, r1_.id AS id_1, r1_.passengerName AS passengerName_2, r1_.route_id AS route_id_3 FROM RoutingRoute r0_ INNER JOIN RoutingRouteBooking r1_ ON r0_.id = r1_.route_id ORDER BY r1_.passengerName ASC', + ); + + $this->assertSqlGeneration( + 'SELECT r, b FROM Doctrine\Tests\Models\Routing\RoutingRoute r JOIN r.bookings b ORDER BY b.passengerName DESC', + 'SELECT r0_.id AS id_0, r1_.id AS id_1, r1_.passengerName AS passengerName_2, r1_.route_id AS route_id_3 FROM RoutingRoute r0_ INNER JOIN RoutingRouteBooking r1_ ON r0_.id = r1_.route_id ORDER BY r1_.passengerName DESC', + ); + } + + #[Group('DDC-1858')] + public function testHavingSupportIsNullExpression(): void + { + $this->assertSqlGeneration( + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING u.username IS NULL', + 'SELECT c0_.name AS name_0 FROM cms_users c0_ HAVING c0_.username IS NULL', + ); + + $this->assertSqlGeneration( + 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING MAX(u.name) IS NULL', + 'SELECT c0_.name AS name_0 FROM cms_users c0_ HAVING MAX(c0_.name) IS NULL', + ); + } + + #[Group('DDC-2506')] + public function testClassTableInheritanceJoinWithConditionAppliesToBaseTable(): void + { + $this->assertSqlGeneration( + 'SELECT e.id FROM Doctrine\Tests\Models\Company\CompanyOrganization o JOIN o.events e WITH e.id = ?1', + 'SELECT c0_.id AS id_0 FROM company_organizations c1_ INNER JOIN (company_events c0_ LEFT JOIN company_auctions c2_ ON c0_.id = c2_.id LEFT JOIN company_raffles c3_ ON c0_.id = c3_.id) ON c1_.id = c0_.org_id AND (c0_.id = ?)', + ); + } + + #[Group('DDC-2235')] + public function testSingleTableInheritanceLeftJoinWithCondition(): void + { + // Regression test for the bug + $this->assertSqlGeneration( + 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyEmployee e LEFT JOIN Doctrine\Tests\Models\Company\CompanyContract c ON c.salesPerson = e.id', + "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6, c0_.salesPerson_id AS salesPerson_id_7 FROM company_employees c1_ INNER JOIN company_persons c2_ ON c1_.id = c2_.id LEFT JOIN company_managers c3_ ON c1_.id = c3_.id LEFT JOIN company_contracts c0_ ON (c0_.salesPerson_id = c2_.id) AND c0_.discr IN ('fix', 'flexible', 'flexultra')", + ); + } + + #[Group('DDC-2235')] + public function testSingleTableInheritanceLeftJoinWithConditionAndWhere(): void + { + // Ensure other WHERE predicates are passed through to the main WHERE clause + $this->assertSqlGeneration( + 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyEmployee e LEFT JOIN Doctrine\Tests\Models\Company\CompanyContract c ON c.salesPerson = e.id WHERE e.salary > 1000', + "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6, c0_.salesPerson_id AS salesPerson_id_7 FROM company_employees c1_ INNER JOIN company_persons c2_ ON c1_.id = c2_.id LEFT JOIN company_managers c3_ ON c1_.id = c3_.id LEFT JOIN company_contracts c0_ ON (c0_.salesPerson_id = c2_.id) AND c0_.discr IN ('fix', 'flexible', 'flexultra') WHERE c1_.salary > 1000", + ); + } + + #[Group('DDC-2235')] + public function testSingleTableInheritanceInnerJoinWithCondition(): void + { + // Test inner joins too + $this->assertSqlGeneration( + 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyEmployee e INNER JOIN Doctrine\Tests\Models\Company\CompanyContract c ON c.salesPerson = e.id', + "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6, c0_.salesPerson_id AS salesPerson_id_7 FROM company_employees c1_ INNER JOIN company_persons c2_ ON c1_.id = c2_.id LEFT JOIN company_managers c3_ ON c1_.id = c3_.id INNER JOIN company_contracts c0_ ON (c0_.salesPerson_id = c2_.id) AND c0_.discr IN ('fix', 'flexible', 'flexultra')", + ); + } + + #[Group('DDC-2235')] + public function testSingleTableInheritanceLeftJoinNonAssociationWithConditionAndWhere(): void + { + // Test that the discriminator IN() predicate is still added into + // the where clause when not joining onto that table + $this->assertSqlGeneration( + 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c LEFT JOIN Doctrine\Tests\Models\Company\CompanyEmployee e ON e.id = c.salesPerson WHERE c.completed = true', + "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6, c0_.salesPerson_id AS salesPerson_id_7 FROM company_contracts c0_ LEFT JOIN (company_employees c1_ INNER JOIN company_persons c2_ ON c1_.id = c2_.id LEFT JOIN company_managers c3_ ON c1_.id = c3_.id) ON (c2_.id = c0_.salesPerson_id) WHERE (c0_.completed = 1) AND c0_.discr IN ('fix', 'flexible', 'flexultra')", + ); + } + + #[Group('DDC-2235')] + public function testSingleTableInheritanceJoinCreatesOnCondition(): void + { + // Test that the discriminator IN() predicate is still added + // into the where clause when not joining onto a single table inheritance entity + // via a join association + $this->assertSqlGeneration( + 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c JOIN c.salesPerson s WHERE c.completed = true', + "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6, c0_.salesPerson_id AS salesPerson_id_7 FROM company_contracts c0_ INNER JOIN company_employees c1_ ON c0_.salesPerson_id = c1_.id LEFT JOIN company_persons c2_ ON c1_.id = c2_.id LEFT JOIN company_managers c3_ ON c1_.id = c3_.id WHERE (c0_.completed = 1) AND c0_.discr IN ('fix', 'flexible', 'flexultra')", + ); + } + + #[Group('DDC-2235')] + public function testSingleTableInheritanceCreatesOnConditionAndWhere(): void + { + // Test that when joining onto an entity using single table inheritance via + // a join association that the discriminator IN() predicate is placed + // into the ON clause of the join + $this->assertSqlGeneration( + 'SELECT e, COUNT(c) FROM Doctrine\Tests\Models\Company\CompanyEmployee e JOIN e.contracts c WHERE e.department = :department', + "SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c2_.title AS title_5, COUNT(c3_.id) AS sclr_6, c0_.discr AS discr_7, c0_.spouse_id AS spouse_id_8, c2_.car_id AS car_id_9 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id LEFT JOIN company_managers c2_ ON c1_.id = c2_.id INNER JOIN company_contract_employees c4_ ON c1_.id = c4_.employee_id INNER JOIN company_contracts c3_ ON c3_.id = c4_.contract_id AND c3_.discr IN ('fix', 'flexible', 'flexultra') WHERE c1_.department = ?", + [], + ['department' => 'foobar'], + ); + } + + #[Group('DDC-1858')] + public function testHavingSupportResultVariableInExpression(): void + { + $this->assertSqlGeneration( + 'SELECT u.name AS foo FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING foo IN (?1)', + 'SELECT c0_.name AS name_0 FROM cms_users c0_ HAVING name_0 IN (?)', + ); + } + + #[Group('DDC-1858')] + public function testHavingSupportResultVariableLikeExpression(): void + { + $this->assertSqlGeneration( + "SELECT u.name AS foo FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING foo LIKE '3'", + "SELECT c0_.name AS name_0 FROM cms_users c0_ HAVING name_0 LIKE '3'", + ); + } + + #[Group('DDC-3085')] + public function testHavingSupportResultVariableNullComparisonExpression(): void + { + $this->assertSqlGeneration( + 'SELECT u AS user, SUM(a.id) AS score FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN Doctrine\Tests\Models\CMS\CmsAddress a ON a.user = u GROUP BY u HAVING score IS NOT NULL AND score >= 5', + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, SUM(c1_.id) AS sclr_4, c0_.email_id AS email_id_5 FROM cms_users c0_ LEFT JOIN cms_addresses c1_ ON (c1_.user_id = c0_.id) GROUP BY c0_.id, c0_.status, c0_.username, c0_.name, c0_.email_id HAVING sclr_4 IS NOT NULL AND sclr_4 >= 5', + ); + } + + #[Group('DDC-1858')] + public function testHavingSupportResultVariableInAggregateFunction(): void + { + $this->assertSqlGeneration( + 'SELECT COUNT(u.name) AS countName FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING countName IS NULL', + 'SELECT COUNT(c0_.name) AS sclr_0 FROM cms_users c0_ HAVING sclr_0 IS NULL', + ); + } + + /** + * GitHub issue #4764: https://github.com/doctrine/orm/issues/4764 + */ + #[DataProvider('mathematicOperatorsProvider')] + #[Group('DDC-3907')] + public function testHavingRegressionUsingVariableWithMathOperatorsExpression($operator): void + { + $this->assertSqlGeneration( + 'SELECT COUNT(u.name) AS countName FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING 1 ' . $operator . ' countName > 0', + 'SELECT COUNT(c0_.name) AS sclr_0 FROM cms_users c0_ HAVING 1 ' . $operator . ' sclr_0 > 0', + ); + } + + /** @phpstan-return list */ + public static function mathematicOperatorsProvider(): array + { + return [['+'], ['-'], ['*'], ['/']]; + } +} + +class MyAbsFunction extends FunctionNode +{ + /** @var SimpleArithmeticExpression */ + public $simpleArithmeticExpression; + + public function getSql(SqlWalker $sqlWalker): string + { + return 'ABS(' . $sqlWalker->walkSimpleArithmeticExpression($this->simpleArithmeticExpression) . ')'; + } + + public function parse(Parser $parser): void + { + $lexer = $parser->getLexer(); + + $parser->match(TokenType::T_IDENTIFIER); + $parser->match(TokenType::T_OPEN_PARENTHESIS); + + $this->simpleArithmeticExpression = $parser->SimpleArithmeticExpression(); + + $parser->match(TokenType::T_CLOSE_PARENTHESIS); + } +} +#[Entity] +class DDC1384Model +{ + /** @var int */ + #[Id] + #[Column(type: 'integer')] + #[GeneratedValue] + protected $aVeryLongIdentifierThatShouldBeShortenedByTheSQLWalkerFooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo; +} + + +#[Entity] +class DDC1474Entity +{ + /** @var int */ + #[Id] + #[Column(type: 'integer')] + #[GeneratedValue] + protected $id; + + public function __construct( + #[Column(type: 'float')] + private string $value, + ) { + } + + public function getId(): int + { + return $this->id; + } + + public function getValue(): float + { + return $this->value; + } + + public function setValue(float $value): void + { + $this->value = $value; + } +}