From ea0bc14a524e2af722c9859398beaedea0f2ce4f Mon Sep 17 00:00:00 2001 From: Simon Mundy Date: Tue, 13 Oct 2026 17:04:16 +1100 Subject: [PATCH 1/2] Quote ORDER BY names as identifiers where fragment quoting breaks them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Select::processOrder() fragment-quoted each order name, so names such as x-y, my col, a"b or café rendered as several quoted pieces. Such names are now quoted whole as an identifier chain split only on '.'. Names whose parts between '*' and '.' already render as one identifier each, such as t.col and price*qty, render byte-for-byte as before. --- src/Sql/Select.php | 34 ++++- test/unit/Sql/SelectOrderNameTest.php | 142 ++++++++++++++++++ .../TestAsset/HyphenWordSql92Platform.php | 15 ++ 3 files changed, 190 insertions(+), 1 deletion(-) create mode 100644 test/unit/Sql/SelectOrderNameTest.php create mode 100644 test/unit/TestAsset/HyphenWordSql92Platform.php diff --git a/src/Sql/Select.php b/src/Sql/Select.php index 183750be9..7348393f1 100644 --- a/src/Sql/Select.php +++ b/src/Sql/Select.php @@ -12,9 +12,11 @@ use function array_key_exists; use function array_key_first; +use function array_map; use function count; use function explode; use function gettype; +use function implode; use function is_array; use function is_int; use function is_numeric; @@ -23,6 +25,7 @@ use function key; use function method_exists; use function preg_split; +use function str_replace; use function strcasecmp; use function stripos; use function strtolower; @@ -604,7 +607,7 @@ protected function processOrder( } $orders[] = [ - $platform->quoteIdentifierInFragment($k), + $this->quoteOrderIdentifier($k, $platform), strcasecmp(trim($v), self::ORDER_DESCENDING) === 0 ? self::ORDER_DESCENDING : self::ORDER_ASCENDING, @@ -770,6 +773,35 @@ private function prefixFromTable(?string $fromTable, PlatformInterface $platform : ''; } + /** + * Quote an order name, keeping fragment quoting only where it renders each part as a single identifier + * + * Fragment quoting splits on every non-word character, so a name such as `x-y` or `my col` would render + * as several quoted pieces. Such a name is quoted whole as an identifier chain instead, split only on + * the table qualifier dot. Names whose parts between `*` and `.` already quote whole, such as `t.col` + * or `price*qty`, render exactly as before. + */ + private function quoteOrderIdentifier(string $name, PlatformInterface $platform): string + { + foreach (explode('.', str_replace(self::SQL_STAR, replace: '.', subject: $name)) as $segment) { + $segment = trim($segment, characters: ' '); + $quoted = $platform->quoteIdentifierInFragment($segment); + if ($quoted !== $segment && $quoted !== $platform->quoteIdentifier($segment)) { + return implode( + $platform->getIdentifierSeparator(), + array_map( + static fn(string $part): string => self::SQL_STAR === $part + ? $part + : $platform->quoteIdentifier($part), + explode('.', $name), + ), + ); + } + } + + return $platform->quoteIdentifierInFragment($name); + } + /** * @param Select|TableReference|null $table * @return array{0: string|null, 1: string} diff --git a/test/unit/Sql/SelectOrderNameTest.php b/test/unit/Sql/SelectOrderNameTest.php new file mode 100644 index 000000000..d400142b0 --- /dev/null +++ b/test/unit/Sql/SelectOrderNameTest.php @@ -0,0 +1,142 @@ +|string, string}> + */ + public static function brokenOrderProvider(): array + { + return [ + 'hyphen' => ['x-y', '"x-y" ASC'], + 'hyphen descending' => ['x-y DESC', '"x-y" DESC'], + 'dotted hyphen' => ['t-1.x-y DESC', '"t-1"."x-y" DESC'], + 'quote character' => ['a"b DESC', '"a\'b" DESC'], + 'non-ascii' => ['café DESC', '"café" DESC'], + 'hyphen in comma list' => ['x-y DESC, b', '"x-y" DESC, "b" ASC'], + 'arithmetic with hyphen' => ['price*x-y DESC', '"price*x-y" DESC'], + 'hyphen array key' => [['x-y' => 'DESC'], '"x-y" DESC'], + 'space array key' => [['my col' => 'DESC'], '"my col" DESC'], + 'dotted space array key' => [['t.my col' => 'ASC'], '"t"."my col" ASC'], + 'quote character array key' => [['a"b' => 'DESC'], '"a\'b" DESC'], + 'non-ascii array key' => [['café' => 'DESC'], '"café" DESC'], + 'hyphen array list' => [['x-y DESC', 'b'], '"x-y" DESC, "b" ASC'], + 'hyphen qualified star' => ['x-y.* DESC', '"x-y".* DESC'], + ]; + } + + /** + * @return array + */ + public static function platformOrderProvider(): array + { + return [ + 'hyphen word character' => [new HyphenWordSql92Platform(), 'x-y DESC', '"x-y" DESC'], + 'hyphen word character arithmetic' => [ + new HyphenWordSql92Platform(), + 'price*x-y DESC', + '"price"*"x-y" DESC', + ], + 'hyphen word character with plus' => [new HyphenWordSql92Platform(), 'x+y DESC', '"x+y" DESC'], + 'identifier quoting off' => [ + new TestSql92Platform(quoteIdentifiers: false), + 'x-y DESC', + 'x-y DESC', + ], + 'identifier quoting off arithmetic' => [ + new TestSql92Platform(quoteIdentifiers: false), + 'price*qty DESC', + 'price*qty DESC', + ], + ]; + } + + /** + * @return array|string, string}> + */ + public static function validOrderProvider(): array + { + return [ + 'plain' => ['a', '"a" ASC'], + 'plain descending' => ['a DESC', '"a" DESC'], + 'lower case descending' => ['a desc', '"a" DESC'], + 'dotted' => ['t.col DESC', '"t"."col" DESC'], + 'comma list' => ['a DESC, b', '"a" DESC, "b" ASC'], + 'arithmetic' => ['price*qty DESC', '"price"*"qty" DESC'], + 'string with space' => ['my col DESC', '"my" ASC'], + 'array key' => [['a' => 'DESC'], '"a" DESC'], + 'array key unknown direction' => [['a' => 'sideways'], '"a" ASC'], + 'spaced arithmetic key' => [['price * qty' => 'DESC'], '"price" * "qty" DESC'], + 'dotted arithmetic key' => [['t.price*t.qty' => 'DESC'], '"t"."price"*"t"."qty" DESC'], + 'trailing space key' => [['a ' => 'DESC'], '"a" DESC'], + 'safe word part' => [['t.as' => 'DESC'], '"t".as DESC'], + 'array list' => [['a DESC', 'b'], '"a" DESC, "b" ASC'], + 'expression' => [new Expression('RAND()'), 'RAND()'], + 'expression in array' => [['a', new Expression('RAND()')], '"a" ASC, RAND()'], + ]; + } + + #[Test] + #[DataProvider('platformOrderProvider')] + public function followsThePlatformFragmentRulesForOrderNames( + PlatformInterface $platform, + string $order, + string $expected, + ): void { + $select = (new Select('foo'))->order($order); + + self::assertStringEndsWith(" ORDER BY {$expected}", $select->getSqlString($platform)); + } + + /** + * @param ExpressionInterface|array|string $order + */ + #[Test] + #[DataProvider('brokenOrderProvider')] + public function quotesOrderNameAsIdentifierChainWhenFragmentQuotingWouldBreakIt( + ExpressionInterface|array|string $order, + string $expected, + ): void { + self::assertSame("SELECT \"foo\".* FROM \"foo\" ORDER BY {$expected}", $this->render($order)); + } + + /** + * @param ExpressionInterface|array|string $order + */ + #[Test] + #[DataProvider('validOrderProvider')] + public function rendersValidOrderUnchanged(ExpressionInterface|array|string $order, string $expected): void + { + self::assertSame("SELECT \"foo\".* FROM \"foo\" ORDER BY {$expected}", $this->render($order)); + } + + /** + * @param ExpressionInterface|array|string $order + */ + private function render(ExpressionInterface|array|string $order): string + { + return (new Select('foo'))->order($order) + ->getSqlString(new TrustingSql92Platform()); + } +} diff --git a/test/unit/TestAsset/HyphenWordSql92Platform.php b/test/unit/TestAsset/HyphenWordSql92Platform.php new file mode 100644 index 000000000..224cbe48c --- /dev/null +++ b/test/unit/TestAsset/HyphenWordSql92Platform.php @@ -0,0 +1,15 @@ + Date: Wed, 4 Nov 2026 16:24:41 +1100 Subject: [PATCH 2/2] Quote ORDER BY names through the shared IdentifierQuoter Replace quoteOrderIdentifier() with IdentifierQuoter::quote(), so ORDER BY names follow the same rule as columns: "t"."as" rather than the invalid "t".as, and arithmetic mixed with a hyphenated name, such as price*x-y, now throws instead of becoming one identifier. The tests use the shared TrustingHyphenWordPlatform, replacing HyphenWordSql92Platform. --- src/Sql/Select.php | 34 +-------------- test/unit/Sql/SelectOrderNameTest.php | 43 +++++++++++++++---- .../TestAsset/HyphenWordSql92Platform.php | 15 ------- 3 files changed, 36 insertions(+), 56 deletions(-) delete mode 100644 test/unit/TestAsset/HyphenWordSql92Platform.php diff --git a/src/Sql/Select.php b/src/Sql/Select.php index d7079628a..a8ffb0437 100644 --- a/src/Sql/Select.php +++ b/src/Sql/Select.php @@ -13,11 +13,9 @@ use function array_key_exists; use function array_key_first; -use function array_map; use function count; use function explode; use function gettype; -use function implode; use function is_array; use function is_int; use function is_numeric; @@ -26,7 +24,6 @@ use function key; use function method_exists; use function preg_split; -use function str_replace; use function strcasecmp; use function stripos; use function strtolower; @@ -610,7 +607,7 @@ protected function processOrder( } $orders[] = [ - $this->quoteOrderIdentifier($k, $platform), + IdentifierQuoter::quote($k, $platform), strcasecmp(trim($v), self::ORDER_DESCENDING) === 0 ? self::ORDER_DESCENDING : self::ORDER_ASCENDING, @@ -797,35 +794,6 @@ private function prefixFromTable(?string $fromTable, PlatformInterface $platform : ''; } - /** - * Quote an order name, keeping fragment quoting only where it renders each part as a single identifier - * - * Fragment quoting splits on every non-word character, so a name such as `x-y` or `my col` would render - * as several quoted pieces. Such a name is quoted whole as an identifier chain instead, split only on - * the table qualifier dot. Names whose parts between `*` and `.` already quote whole, such as `t.col` - * or `price*qty`, render exactly as before. - */ - private function quoteOrderIdentifier(string $name, PlatformInterface $platform): string - { - foreach (explode('.', str_replace(self::SQL_STAR, replace: '.', subject: $name)) as $segment) { - $segment = trim($segment, characters: ' '); - $quoted = $platform->quoteIdentifierInFragment($segment); - if ($quoted !== $segment && $quoted !== $platform->quoteIdentifier($segment)) { - return implode( - $platform->getIdentifierSeparator(), - array_map( - static fn(string $part): string => self::SQL_STAR === $part - ? $part - : $platform->quoteIdentifier($part), - explode('.', $name), - ), - ); - } - } - - return $platform->quoteIdentifierInFragment($name); - } - /** * @param Select|TableReference|null $table * @return array{0: string|null, 1: string} diff --git a/test/unit/Sql/SelectOrderNameTest.php b/test/unit/Sql/SelectOrderNameTest.php index d400142b0..1a9200eaa 100644 --- a/test/unit/Sql/SelectOrderNameTest.php +++ b/test/unit/Sql/SelectOrderNameTest.php @@ -5,11 +5,12 @@ namespace PhpDbTest\Sql; use PhpDb\Adapter\Platform\PlatformInterface; +use PhpDb\Sql\Exception\InvalidArgumentException; use PhpDb\Sql\Expression; use PhpDb\Sql\ExpressionInterface; use PhpDb\Sql\Select; -use PhpDbTest\TestAsset\HyphenWordSql92Platform; use PhpDbTest\TestAsset\TestSql92Platform; +use PhpDbTest\TestAsset\TrustingHyphenWordPlatform; use PhpDbTest\TestAsset\TrustingSql92Platform; use PHPUnit\Framework\Attributes\CoversMethod; use PHPUnit\Framework\Attributes\DataProvider; @@ -20,7 +21,6 @@ #[Group('unit')] #[CoversMethod(Select::class, 'order')] #[CoversMethod(Select::class, 'processOrder')] -#[CoversMethod(Select::class, 'quoteOrderIdentifier')] final class SelectOrderNameTest extends TestCase { /** @@ -35,7 +35,6 @@ public static function brokenOrderProvider(): array 'quote character' => ['a"b DESC', '"a\'b" DESC'], 'non-ascii' => ['café DESC', '"café" DESC'], 'hyphen in comma list' => ['x-y DESC, b', '"x-y" DESC, "b" ASC'], - 'arithmetic with hyphen' => ['price*x-y DESC', '"price*x-y" DESC'], 'hyphen array key' => [['x-y' => 'DESC'], '"x-y" DESC'], 'space array key' => [['my col' => 'DESC'], '"my col" DESC'], 'dotted space array key' => [['t.my col' => 'ASC'], '"t"."my col" ASC'], @@ -43,6 +42,7 @@ public static function brokenOrderProvider(): array 'non-ascii array key' => [['café' => 'DESC'], '"café" DESC'], 'hyphen array list' => [['x-y DESC', 'b'], '"x-y" DESC, "b" ASC'], 'hyphen qualified star' => ['x-y.* DESC', '"x-y".* DESC'], + 'as after qualifier' => [['t.as' => 'DESC'], '"t"."as" DESC'], ]; } @@ -52,13 +52,12 @@ public static function brokenOrderProvider(): array public static function platformOrderProvider(): array { return [ - 'hyphen word character' => [new HyphenWordSql92Platform(), 'x-y DESC', '"x-y" DESC'], + 'hyphen word character' => [new TrustingHyphenWordPlatform(), 'x-y DESC', '`x-y` DESC'], 'hyphen word character arithmetic' => [ - new HyphenWordSql92Platform(), + new TrustingHyphenWordPlatform(), 'price*x-y DESC', - '"price"*"x-y" DESC', + '`price`*`x-y` DESC', ], - 'hyphen word character with plus' => [new HyphenWordSql92Platform(), 'x+y DESC', '"x+y" DESC'], 'identifier quoting off' => [ new TestSql92Platform(quoteIdentifiers: false), 'x-y DESC', @@ -72,6 +71,18 @@ public static function platformOrderProvider(): array ]; } + /** + * @return array|string, string}> + */ + public static function unquotableOrderProvider(): array + { + return [ + 'arithmetic with hyphen' => [new TrustingSql92Platform(), 'price*x-y DESC', 'price*x-y'], + 'function call' => [new TrustingSql92Platform(), ['COUNT(id)' => 'DESC'], 'COUNT(id)'], + 'plus on hyphen platform' => [new TrustingHyphenWordPlatform(), 'x+y DESC', 'x+y'], + ]; + } + /** * @return array|string, string}> */ @@ -90,7 +101,6 @@ public static function validOrderProvider(): array 'spaced arithmetic key' => [['price * qty' => 'DESC'], '"price" * "qty" DESC'], 'dotted arithmetic key' => [['t.price*t.qty' => 'DESC'], '"t"."price"*"t"."qty" DESC'], 'trailing space key' => [['a ' => 'DESC'], '"a" DESC'], - 'safe word part' => [['t.as' => 'DESC'], '"t".as DESC'], 'array list' => [['a DESC', 'b'], '"a" DESC, "b" ASC'], 'expression' => [new Expression('RAND()'), 'RAND()'], 'expression in array' => [['a', new Expression('RAND()')], '"a" ASC, RAND()'], @@ -121,6 +131,23 @@ public function quotesOrderNameAsIdentifierChainWhenFragmentQuotingWouldBreakIt( self::assertSame("SELECT \"foo\".* FROM \"foo\" ORDER BY {$expected}", $this->render($order)); } + /** + * @param array|string $order + */ + #[Test] + #[DataProvider('unquotableOrderProvider')] + public function rejectsOrderNamesHoldingExpressionSyntax( + PlatformInterface $platform, + array|string $order, + string $name, + ): void { + $select = (new Select('foo'))->order($order); + + $this->expectExceptionObject(InvalidArgumentException::forUnquotableIdentifier($name)); + + $select->getSqlString($platform); + } + /** * @param ExpressionInterface|array|string $order */ diff --git a/test/unit/TestAsset/HyphenWordSql92Platform.php b/test/unit/TestAsset/HyphenWordSql92Platform.php deleted file mode 100644 index 224cbe48c..000000000 --- a/test/unit/TestAsset/HyphenWordSql92Platform.php +++ /dev/null @@ -1,15 +0,0 @@ -