Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/Statements/CreateStatement.php
Original file line number Diff line number Diff line change
Expand Up @@ -462,11 +462,22 @@ public function build(): string
$builtStatement = $this->with->build();
}

$body = TokensList::buildFromArray($this->body);
// Body tokens (e.g. trailing `UNION ALL (SELECT ...)` after the
// primary SELECT) are concatenated raw, so without a separator
// the rebuilt SQL collides with the SELECT's last token —
// `WHERE 3 = 3union all` instead of `WHERE 3 = 3 union all`.
// Only insert a space when neither side already has one to
// avoid double-spacing the WITH...AS path.
$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() ?? '');
}

Expand Down
25 changes: 25 additions & 0 deletions tests/Builder/CreateStatementTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -897,4 +897,29 @@ public function testBuildCreateTableComplexIndexes(): void
$stmt->build(),
);
}

/**
* Regression for #655: `CREATE VIEW ... AS SELECT ... WHERE ... UNION ALL (...)`
* used to lose the whitespace between the SELECT body and the trailing
* UNION clause, producing invalid SQL like `WHERE 3 = 3union all (...)`.
*/
public function testBuilderViewWithUnionPreservesWhitespace(): void
{
$sql = "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 = new Parser($sql);
$built = $parser->statements[0]->build();

$this->assertStringNotContainsString(
'3union all',
$built,
'rebuilt CREATE VIEW must keep the space between WHERE clause and UNION',
);
$this->assertStringContainsString(
'3 union all',
// case-insensitive match: builder may upper-case the keyword
preg_replace('/UNION\s+ALL/i', 'union all', $built),
);
}
}