Skip to content

Commit 9bdad65

Browse files
h4kunadg
authored andcommitted
SqlPreprocessor: throw exception if mode does not respond values (#175)
1 parent 9358712 commit 9bdad65

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

src/Database/SqlPreprocessor.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ class SqlPreprocessor
1919
{
2020
use Nette\SmartObject;
2121

22+
/** @var array */
23+
private const MODE_LIST = ['and', 'or', 'set', 'values', 'order'];
24+
2225
/** @var Connection */
2326
private $connection;
2427

@@ -162,6 +165,9 @@ private function formatValue($value, $mode = NULL)
162165

163166
if ($mode === 'values') { // (key, key, ...) VALUES (value, value, ...)
164167
if (array_key_exists(0, $value)) { // multi-insert
168+
if (!is_array($value[0])) {
169+
throw new Nette\InvalidArgumentException('Automaticaly detected multi-insert, but values aren\'t array. If you need try to change mode like "?[' . implode('|', self::MODE_LIST) . ']". Mode "' . $mode . '" was used.');
170+
}
165171
foreach ($value[0] as $k => $v) {
166172
$kx[] = $this->delimite($k);
167173
}
@@ -228,7 +234,7 @@ private function formatValue($value, $mode = NULL)
228234
throw new Nette\InvalidArgumentException("Unknown placeholder ?$mode.");
229235
}
230236

231-
} elseif (in_array($mode, ['and', 'or', 'set', 'values', 'order'], TRUE)) {
237+
} elseif (in_array($mode, self::MODE_LIST, TRUE)) {
232238
$type = gettype($value);
233239
throw new Nette\InvalidArgumentException("Placeholder ?$mode expects array or Traversable object, $type given.");
234240

tests/Database/SqlPreprocessor.phpt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,13 @@ test(function () use ($preprocessor) { // ?values
324324
});
325325

326326

327+
test(function () use ($preprocessor) { // automatic detection faild
328+
Assert::exception(function () use ($preprocessor) {
329+
$preprocessor->process(['INSERT INTO author (name) SELECT name FROM user WHERE id IN (?)', [11, 12]]);
330+
}, Nette\InvalidArgumentException::class, 'Automaticaly detected multi-insert, but values aren\'t array. If you need try to change mode like "?[and|or|set|values|order]". Mode "values" was used.');
331+
});
332+
333+
327334
test(function () use ($preprocessor) { // multi insert
328335
[$sql, $params] = $preprocessor->process(['INSERT INTO author', [
329336
['name' => 'Catelyn Stark', 'born' => new DateTime('2011-11-11')],

0 commit comments

Comments
 (0)