Skip to content

Commit 8b240cd

Browse files
authored
Merge pull request #244 from simon-mundy/fix/predicate-identifier
Quote predicate names as identifiers where fragment quoting renders broken SQL
2 parents f0a6b96 + 3c3e19c commit 8b240cd

2 files changed

Lines changed: 357 additions & 2 deletions

File tree

‎src/Sql/AbstractSql.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ protected function processExpression(
255255
$parameterContainer,
256256
)
257257
: $platform->quoteValue((string) $argument->getValue()),
258-
$argument instanceof Identifier => $platform->quoteIdentifierInFragment($argument->getValue()),
258+
$argument instanceof Identifier => IdentifierQuoter::quote($argument->getValue(), $platform),
259259
$argument instanceof Literal => $argument->getValue(),
260260
$argument instanceof Identifiers => $this->processIdentifiersArgument($argument, $platform),
261261
$argument instanceof SelectArgument => $this->processExpressionOrSelect(
@@ -338,7 +338,7 @@ protected function processIdentifiersArgument(
338338
$processedIdentifiers = [];
339339

340340
foreach ($identifiers as $identifier) {
341-
$processedIdentifiers[] = $platform->quoteIdentifierInFragment($identifier);
341+
$processedIdentifiers[] = IdentifierQuoter::quote($identifier, $platform);
342342
}
343343

344344
return implode(', ', $processedIdentifiers);
Lines changed: 355 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,355 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace PhpDbTest\Sql;
6+
7+
use Closure;
8+
use PhpDb\Adapter\Platform\PlatformInterface;
9+
use PhpDb\Sql\AbstractSql;
10+
use PhpDb\Sql\Argument;
11+
use PhpDb\Sql\Delete;
12+
use PhpDb\Sql\Exception\InvalidArgumentException;
13+
use PhpDb\Sql\Predicate\Expression;
14+
use PhpDb\Sql\Predicate\Literal;
15+
use PhpDb\Sql\Predicate\Predicate;
16+
use PhpDb\Sql\Select;
17+
use PhpDb\Sql\Update;
18+
use PhpDbTest\TestAsset\TrustingHyphenWordPlatform;
19+
use PhpDbTest\TestAsset\TrustingSql92Platform;
20+
use PHPUnit\Framework\Attributes\CoversMethod;
21+
use PHPUnit\Framework\Attributes\DataProvider;
22+
use PHPUnit\Framework\Attributes\Group;
23+
use PHPUnit\Framework\Attributes\Test;
24+
use PHPUnit\Framework\TestCase;
25+
26+
use function sprintf;
27+
28+
#[Group('unit')]
29+
#[CoversMethod(AbstractSql::class, 'processExpression')]
30+
#[CoversMethod(AbstractSql::class, 'processIdentifiersArgument')]
31+
final class PredicateIdentifierNameTest extends TestCase
32+
{
33+
/**
34+
* Names whose fragment quoting renders adjacent quoted pieces, and their single-identifier rendering
35+
*
36+
* @return array<string, array{string, string}>
37+
*/
38+
public static function brokenNameProvider(): array
39+
{
40+
return [
41+
'hyphen' => ['x-y', '"x-y"'],
42+
'space' => ['my col', '"my col"'],
43+
'quote character' => ['a"b', '"a\'b"'],
44+
'non-ascii' => ['nâme', '"nâme"'],
45+
'tab' => ["a\tb", "\"a\tb\""],
46+
'dotted hyphen' => ['t-1.x-y', '"t-1"."x-y"'],
47+
'dotted space' => ['t.my col', '"t"."my col"'],
48+
'hyphen qualified star' => ['t-1.*', '"t-1".*'],
49+
];
50+
}
51+
52+
/**
53+
* @return iterable<string, array{Closure(Predicate, string): Predicate, string, string, string}>
54+
*/
55+
public static function brokenPredicateProvider(): iterable
56+
{
57+
foreach (self::predicateMethodProvider() as $method => [$apply, $template]) {
58+
foreach (self::brokenNameProvider() as $case => [$name, $quoted]) {
59+
yield "{$method} {$case}" => [$apply, $template, $name, $quoted];
60+
}
61+
}
62+
}
63+
64+
/**
65+
* @return array<string, array{string, string}>
66+
*/
67+
public static function hyphenWordPlatformProvider(): array
68+
{
69+
return [
70+
'hyphen' => ['x-y', '`x-y`'],
71+
'hyphen arithmetic' => ['a-b * c', '`a-b` * `c`'],
72+
'dotted hyphen' => ['t-1.x-y', '`t-1`.`x-y`'],
73+
'space' => ['my col', '`my col`'],
74+
'quote character' => ['a`b', '`a``b`'],
75+
];
76+
}
77+
78+
/**
79+
* @return array<string, array{Closure(Predicate, string): Predicate, string}>
80+
*/
81+
public static function predicateMethodProvider(): array
82+
{
83+
return [
84+
'equalTo' => [static fn(Predicate $p, string $n): Predicate => $p->equalTo($n, 1), "%s = '1'"],
85+
'notEqualTo' => [static fn(Predicate $p, string $n): Predicate => $p->notEqualTo($n, 1), "%s != '1'"],
86+
'lessThan' => [static fn(Predicate $p, string $n): Predicate => $p->lessThan($n, 1), "%s < '1'"],
87+
'greaterThan' => [static fn(Predicate $p, string $n): Predicate => $p->greaterThan($n, 1), "%s > '1'"],
88+
'like' => [static fn(Predicate $p, string $n): Predicate => $p->like($n, 'a%'), "%s LIKE 'a%%'"],
89+
'in' => [static fn(Predicate $p, string $n): Predicate => $p->in($n, [1, 2]), "%s IN ('1', '2')"],
90+
'between' => [
91+
static fn(Predicate $p, string $n): Predicate => $p->between($n, 1, 2),
92+
"%s BETWEEN '1' AND '2'",
93+
],
94+
'isNull' => [static fn(Predicate $p, string $n): Predicate => $p->isNull($n), '%s IS NULL'],
95+
];
96+
}
97+
98+
/**
99+
* @return array<string, array{PlatformInterface, string, InvalidArgumentException}>
100+
*/
101+
public static function rejectedNameProvider(): array
102+
{
103+
return [
104+
'function call' => [
105+
new TrustingSql92Platform(),
106+
'COUNT(id)',
107+
InvalidArgumentException::forUnquotableIdentifier('COUNT(id)'),
108+
],
109+
'spaced minus' => [
110+
new TrustingSql92Platform(),
111+
'a - b',
112+
InvalidArgumentException::forUnquotableIdentifier('a - b'),
113+
],
114+
'arithmetic with hyphen' => [
115+
new TrustingSql92Platform(),
116+
'x-y * 2',
117+
InvalidArgumentException::forUnquotableIdentifier('x-y * 2'),
118+
],
119+
'plus on hyphen platform' => [
120+
new TrustingHyphenWordPlatform(),
121+
'a+b',
122+
InvalidArgumentException::forUnquotableIdentifier('a+b'),
123+
],
124+
'empty' => [
125+
new TrustingSql92Platform(),
126+
'',
127+
InvalidArgumentException::forEmptyIdentifierPart(''),
128+
],
129+
'empty qualifier part' => [
130+
new TrustingSql92Platform(),
131+
'a..b',
132+
InvalidArgumentException::forEmptyIdentifierPart('a..b'),
133+
],
134+
];
135+
}
136+
137+
/**
138+
* Names whose fragment quoting renders valid SQL, and that rendering
139+
*
140+
* @return array<string, array{string, string}>
141+
*/
142+
public static function unchangedNameProvider(): array
143+
{
144+
return [
145+
'plain' => ['col', '"col"'],
146+
'dotted' => ['t.col', '"t"."col"'],
147+
'qualified star' => ['t.*', '"t".*'],
148+
'arithmetic' => ['price*qty', '"price"*"qty"'],
149+
'spaced arithmetic' => ['a * b', '"a" * "b"'],
150+
'dotted arithmetic' => ['t.a * t.b', '"t"."a" * "t"."b"'],
151+
'inline alias' => ['x as y', '"x" as "y"'],
152+
'inline alias upper' => ['x AS y', '"x" AS "y"'],
153+
'comma' => ['a,b', '"a,b"'],
154+
];
155+
}
156+
157+
/**
158+
* @return iterable<string, array{Closure(Predicate, string): Predicate, string, string, string}>
159+
*/
160+
public static function unchangedPredicateProvider(): iterable
161+
{
162+
foreach (self::predicateMethodProvider() as $method => [$apply, $template]) {
163+
foreach (self::unchangedNameProvider() as $case => [$name, $quoted]) {
164+
yield "{$method} {$case}" => [$apply, $template, $name, $quoted];
165+
}
166+
}
167+
}
168+
169+
#[Test]
170+
#[DataProvider('hyphenWordPlatformProvider')]
171+
public function followsThePlatformFragmentPatternForWordCharacters(string $name, string $quoted): void
172+
{
173+
$select = new Select('foo');
174+
$select->where->equalTo($name, 1);
175+
176+
self::assertSame(
177+
"SELECT `foo`.* FROM `foo` WHERE {$quoted} = '1'",
178+
$select->getSqlString(new TrustingHyphenWordPlatform()),
179+
);
180+
}
181+
182+
/**
183+
* @param Closure(Predicate, string): Predicate $apply
184+
*/
185+
#[Test]
186+
#[DataProvider('unchangedPredicateProvider')]
187+
public function keepsValidWhereNameRenderingUnchanged(
188+
Closure $apply,
189+
string $template,
190+
string $name,
191+
string $quoted,
192+
): void {
193+
$select = new Select('foo');
194+
$apply($select->where, $name);
195+
196+
self::assertSame(
197+
sprintf("SELECT \"foo\".* FROM \"foo\" WHERE {$template}", $quoted),
198+
$select->getSqlString(new TrustingSql92Platform()),
199+
);
200+
}
201+
202+
#[Test]
203+
public function leavesExpressionWhereUnchanged(): void
204+
{
205+
$select = new Select('foo');
206+
$select->where(new Expression('x-y = ?', [1]));
207+
208+
self::assertSame(
209+
"SELECT \"foo\".* FROM \"foo\" WHERE x-y = '1'",
210+
$select->getSqlString(new TrustingSql92Platform()),
211+
);
212+
}
213+
214+
#[Test]
215+
public function leavesLiteralWhereUnchanged(): void
216+
{
217+
$select = new Select('foo');
218+
$select->where(new Literal('x-y = 1'));
219+
220+
self::assertSame(
221+
'SELECT "foo".* FROM "foo" WHERE x-y = 1',
222+
$select->getSqlString(new TrustingSql92Platform()),
223+
);
224+
}
225+
226+
#[Test]
227+
public function leavesStringWhereUnchanged(): void
228+
{
229+
$select = new Select('foo');
230+
$select->where('x-y = 1');
231+
232+
self::assertSame(
233+
'SELECT "foo".* FROM "foo" WHERE x-y = 1',
234+
$select->getSqlString(new TrustingSql92Platform()),
235+
);
236+
}
237+
238+
#[Test]
239+
#[DataProvider('brokenNameProvider')]
240+
#[DataProvider('unchangedNameProvider')]
241+
public function quotesDeleteWhereName(string $name, string $quoted): void
242+
{
243+
$delete = new Delete('foo');
244+
$delete->where->equalTo($name, 1);
245+
246+
self::assertSame(
247+
"DELETE FROM \"foo\" WHERE {$quoted} = '1'",
248+
$delete->getSqlString(new TrustingSql92Platform()),
249+
);
250+
}
251+
252+
#[Test]
253+
public function quotesEachNameOfAnIdentifiersArgument(): void
254+
{
255+
$select = new Select('foo');
256+
$select->where(new Expression('(?) IN (SELECT 1)', [Argument::identifiers(['x-y', 't.col', 'a * b'])]));
257+
258+
self::assertSame(
259+
'SELECT "foo".* FROM "foo" WHERE ("x-y", "t"."col", "a" * "b") IN (SELECT 1)',
260+
$select->getSqlString(new TrustingSql92Platform()),
261+
);
262+
}
263+
264+
#[Test]
265+
#[DataProvider('brokenNameProvider')]
266+
#[DataProvider('unchangedNameProvider')]
267+
public function quotesHavingName(string $name, string $quoted): void
268+
{
269+
$select = new Select('foo');
270+
$select->having->greaterThan($name, 1);
271+
272+
self::assertSame(
273+
"SELECT \"foo\".* FROM \"foo\" HAVING {$quoted} > '1'",
274+
$select->getSqlString(new TrustingSql92Platform()),
275+
);
276+
}
277+
278+
/**
279+
* @param Closure(Predicate, string): Predicate $apply
280+
*/
281+
#[Test]
282+
#[DataProvider('brokenPredicateProvider')]
283+
public function quotesPreviouslyBrokenWhereNameAsOneIdentifier(
284+
Closure $apply,
285+
string $template,
286+
string $name,
287+
string $quoted,
288+
): void {
289+
$select = new Select('foo');
290+
$apply($select->where, $name);
291+
292+
self::assertSame(
293+
sprintf("SELECT \"foo\".* FROM \"foo\" WHERE {$template}", $quoted),
294+
$select->getSqlString(new TrustingSql92Platform()),
295+
);
296+
}
297+
298+
#[Test]
299+
#[DataProvider('brokenNameProvider')]
300+
#[DataProvider('unchangedNameProvider')]
301+
public function quotesUpdateWhereName(string $name, string $quoted): void
302+
{
303+
$update = new Update('foo');
304+
$update->set(['bar' => 2]);
305+
$update->where->equalTo($name, 1);
306+
307+
self::assertSame(
308+
"UPDATE \"foo\" SET \"bar\" = '2' WHERE {$quoted} = '1'",
309+
$update->getSqlString(new TrustingSql92Platform()),
310+
);
311+
}
312+
313+
#[Test]
314+
#[DataProvider('brokenNameProvider')]
315+
#[DataProvider('unchangedNameProvider')]
316+
public function quotesWhereArrayKeyAsPredicateName(string $name, string $quoted): void
317+
{
318+
$select = new Select('foo');
319+
$select->where([$name => 1]);
320+
321+
self::assertSame(
322+
"SELECT \"foo\".* FROM \"foo\" WHERE {$quoted} = '1'",
323+
$select->getSqlString(new TrustingSql92Platform()),
324+
);
325+
}
326+
327+
#[Test]
328+
#[DataProvider('brokenNameProvider')]
329+
#[DataProvider('unchangedNameProvider')]
330+
public function quotesWhereArrayKeyWithNullAsIsNullName(string $name, string $quoted): void
331+
{
332+
$select = new Select('foo');
333+
$select->where([$name => null]);
334+
335+
self::assertSame(
336+
"SELECT \"foo\".* FROM \"foo\" WHERE {$quoted} IS NULL",
337+
$select->getSqlString(new TrustingSql92Platform()),
338+
);
339+
}
340+
341+
#[Test]
342+
#[DataProvider('rejectedNameProvider')]
343+
public function rejectsWhereNamesThatCannotBeQuotedAsWritten(
344+
PlatformInterface $platform,
345+
string $name,
346+
InvalidArgumentException $expected,
347+
): void {
348+
$select = new Select('foo');
349+
$select->where->equalTo($name, 1);
350+
351+
$this->expectExceptionObject($expected);
352+
353+
$select->getSqlString($platform);
354+
}
355+
}

0 commit comments

Comments
 (0)