diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 0d6f646d..e0469592 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -1908,7 +1908,7 @@ parameters: - message: '#^Dynamic call to static method PHPUnit\\Framework\\Assert\:\:assertEquals\(\)\.$#' identifier: staticMethod.dynamicCall - count: 35 + count: 36 path: tests/Builder/CreateStatementTest.php - diff --git a/src/Statements/CreateStatement.php b/src/Statements/CreateStatement.php index 7b2b65a5..639b1a0a 100644 --- a/src/Statements/CreateStatement.php +++ b/src/Statements/CreateStatement.php @@ -27,6 +27,7 @@ use function is_array; use function str_replace; +use function substr; use function trim; /** @@ -462,11 +463,18 @@ public function build(): string $builtStatement = $this->with->build(); } + $body = TokensList::buildFromArray($this->body); + // Trailing body tokens (e.g. `UNION ALL ...`) need a space after the SELECT, + // unless one side already has it (the WITH ... AS path does). + $separator = $builtStatement !== '' && $body !== '' + && substr($builtStatement, -1) !== ' ' + && $body[0] !== ' ' ? ' ' : ''; + return 'CREATE ' . $this->options->build() . ' ' . $this->name->build() . ' ' . $fields . ' AS ' . $builtStatement - . TokensList::buildFromArray($this->body) . ' ' + . $separator . $body . ' ' . ($this->entityOptions?->build() ?? ''); } diff --git a/tests/Builder/CreateStatementTest.php b/tests/Builder/CreateStatementTest.php index 6c8fea6d..f81bda4c 100644 --- a/tests/Builder/CreateStatementTest.php +++ b/tests/Builder/CreateStatementTest.php @@ -919,4 +919,22 @@ public function testBuildCreateTableWithUppercaseHexDefault(): void $this->assertEmpty($parser->errors); $this->assertStringContainsString("DEFAULT X'FF'", $parser->statements[0]->build()); } + + /** + * Regression for #655: the UNION body used to be glued to the SELECT, + * producing invalid SQL like `WHERE 3 = 3union all (...)`. + */ + public function testBuilderViewWithUnionPreservesWhitespace(): void + { + $parser = new Parser( + 'CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER ' + . 'VIEW `v1` AS select 1 AS `a` where 3 = 3 union all (select 2 AS `a`)', + ); + + $this->assertEquals( + 'CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER ' + . 'VIEW `v1` AS SELECT 1 AS `a` WHERE 3 = 3 union all (select 2 AS `a`) ', + $parser->statements[0]->build(), + ); + } }