1
0
mirror of https://github.com/dg/dibi.git synced 2025-07-31 19:30:30 +02:00

coding style

This commit is contained in:
David Grudl
2021-03-01 17:55:56 +01:00
parent b6ead80202
commit d1a3362321
46 changed files with 592 additions and 496 deletions

View File

@@ -31,7 +31,7 @@ $name = $cond1 ? 'K%' : null;
$dibi->test(' $dibi->test('
SELECT * SELECT *
FROM customers FROM customers
%if', isset($name), 'WHERE name LIKE ?', $name, '%end' %if', isset($name), 'WHERE name LIKE ?', $name, '%end',
); );
// -> SELECT * FROM customers WHERE name LIKE 'K%' // -> SELECT * FROM customers WHERE name LIKE 'K%'
@@ -54,7 +54,7 @@ $dibi->test('
WHERE WHERE
%if', isset($name), 'name LIKE ?', $name, ' %if', isset($name), 'name LIKE ?', $name, '
%if', $cond2, 'AND admin=1 %end %if', $cond2, 'AND admin=1 %end
%else 1 LIMIT 10 %end' %else 1 LIMIT 10 %end',
); );
// -> SELECT * FROM customers WHERE LIMIT 10 // -> SELECT * FROM customers WHERE LIMIT 10

View File

@@ -28,7 +28,7 @@ $dibi->test('
SELECT COUNT(*) as [count] SELECT COUNT(*) as [count]
FROM [comments] FROM [comments]
WHERE [ip] LIKE ?', $ipMask, ' WHERE [ip] LIKE ?', $ipMask, '
AND [date] > ', new Dibi\DateTime($timestamp) AND [date] > ', new Dibi\DateTime($timestamp),
); );
// -> SELECT COUNT(*) as [count] FROM [comments] WHERE [ip] LIKE '192.168.%' AND [date] > 876693600 // -> SELECT COUNT(*) as [count] FROM [comments] WHERE [ip] LIKE '192.168.%' AND [date] > 876693600
@@ -69,7 +69,7 @@ $array = [1, 2, 3];
$dibi->test(' $dibi->test('
SELECT * SELECT *
FROM people FROM people
WHERE id IN (?)', $array WHERE id IN (?)', $array,
); );
// -> SELECT * FROM people WHERE id IN ( 1, 2, 3 ) // -> SELECT * FROM people WHERE id IN ( 1, 2, 3 )

View File

@@ -29,6 +29,6 @@ $dibi->test('
'id' => 123, 'id' => 123,
'date' => new DateTime('12.3.2007'), 'date' => new DateTime('12.3.2007'),
'stamp' => new DateTime('23.1.2007 10:23'), 'stamp' => new DateTime('23.1.2007 10:23'),
] ],
); );
// -> INSERT INTO [mytable] ([id], [date], [stamp]) VALUES (123, '2007-03-12', '2007-01-23 10-23-00') // -> INSERT INTO [mytable] ([id], [date], [stamp]) VALUES (123, '2007-03-12', '2007-01-23 10-23-00')

View File

@@ -54,6 +54,6 @@ define('SUBST_ACTIVE', 7);
$dibi->test(" $dibi->test("
UPDATE :account:user UPDATE :account:user
SET name='John Doe', status=:active: SET name='John Doe', status=:active:
WHERE id=", 7 WHERE id=", 7,
); );
// -> UPDATE eshop_user SET name='John Doe', status=7 WHERE id= 7 // -> UPDATE eshop_user SET name='John Doe', status=7 WHERE id= 7

View File

@@ -66,7 +66,7 @@ class DibiExtension22 extends Nette\DI\CompilerExtension
if (class_exists(Tracy\Debugger::class)) { if (class_exists(Tracy\Debugger::class)) {
$connection->addSetup( $connection->addSetup(
[new Nette\DI\Statement('Tracy\Debugger::getBlueScreen'), 'addPanel'], [new Nette\DI\Statement('Tracy\Debugger::getBlueScreen'), 'addPanel'],
[[Dibi\Bridges\Tracy\Panel::class, 'renderException']] [[Dibi\Bridges\Tracy\Panel::class, 'renderException']],
); );
} }

View File

@@ -174,7 +174,7 @@ class Panel implements Tracy\IBarPanel
private function getConnectionName(Dibi\Connection $connection): string private function getConnectionName(Dibi\Connection $connection): string
{ {
$driver = $connection->getConfig('driver'); $driver = $connection->getConfig('driver');
return (is_object($driver) ? get_class($driver) : $driver) return (is_object($driver) ? $driver::class : $driver)
. ($connection->getConfig('name') ? '/' . $connection->getConfig('name') : '') . ($connection->getConfig('name') ? '/' . $connection->getConfig('name') : '')
. ($connection->getConfig('host') ? "\u{202f}@\u{202f}" . $connection->getConfig('host') : ''); . ($connection->getConfig('host') ? "\u{202f}@\u{202f}" . $connection->getConfig('host') : '');
} }

View File

@@ -75,7 +75,7 @@ class Connection implements IConnection
Helpers::alias($config, 'host', 'hostname'); Helpers::alias($config, 'host', 'hostname');
Helpers::alias($config, 'result|formatDate', 'resultDate'); Helpers::alias($config, 'result|formatDate', 'resultDate');
Helpers::alias($config, 'result|formatDateTime', 'resultDateTime'); Helpers::alias($config, 'result|formatDateTime', 'resultDateTime');
$config['driver'] = $config['driver'] ?? 'mysqli'; $config['driver'] ??= 'mysqli';
$config['name'] = $name; $config['name'] = $name;
$this->config = $config; $this->config = $config;
@@ -93,7 +93,7 @@ class Connection implements IConnection
$this->onEvent[] = [new Loggers\FileLogger($config['profiler']['file'], $filter, $errorsOnly), 'logEvent']; $this->onEvent[] = [new Loggers\FileLogger($config['profiler']['file'], $filter, $errorsOnly), 'logEvent'];
} }
$this->substitutes = new HashMap(function (string $expr) { return ":$expr:"; }); $this->substitutes = new HashMap(fn(string $expr) => ":$expr:");
if (!empty($config['substitutes'])) { if (!empty($config['substitutes'])) {
foreach ($config['substitutes'] as $key => $value) { foreach ($config['substitutes'] as $key => $value) {
$this->substitutes->$key = $value; $this->substitutes->$key = $value;
@@ -253,7 +253,7 @@ class Connection implements IConnection
if ($e->getSql()) { if ($e->getSql()) {
Helpers::dump($e->getSql()); Helpers::dump($e->getSql());
} else { } else {
echo get_class($e) . ': ' . $e->getMessage() . (PHP_SAPI === 'cli' ? "\n" : '<br>'); echo $e::class . ': ' . $e->getMessage() . (PHP_SAPI === 'cli' ? "\n" : '<br>');
} }
return false; return false;
@@ -529,7 +529,7 @@ class Connection implements IConnection
{ {
return strpos($value, ':') === false return strpos($value, ':') === false
? $value ? $value
: preg_replace_callback('#:([^:\s]*):#', function (array $m) { return $this->substitutes->{$m[1]}; }, $value); : preg_replace_callback('#:([^:\s]*):#', fn(array $m) => $this->substitutes->{$m[1]}, $value);
} }

View File

@@ -241,7 +241,7 @@ class DataSource implements IDataSource
$this->sorting ? ['ORDER BY %by', $this->sorting] : null, $this->sorting ? ['ORDER BY %by', $this->sorting] : null,
"\n%ofs %lmt", "\n%ofs %lmt",
$this->offset, $this->offset,
$this->limit $this->limit,
); );
} catch (\Throwable $e) { } catch (\Throwable $e) {
trigger_error($e->getMessage(), E_USER_ERROR); trigger_error($e->getMessage(), E_USER_ERROR);
@@ -261,7 +261,7 @@ class DataSource implements IDataSource
if ($this->count === null) { if ($this->count === null) {
$this->count = $this->conds || $this->offset || $this->limit $this->count = $this->conds || $this->offset || $this->limit
? Helpers::intVal($this->connection->nativeQuery( ? Helpers::intVal($this->connection->nativeQuery(
'SELECT COUNT(*) FROM (' . $this->__toString() . ') t' 'SELECT COUNT(*) FROM (' . $this->__toString() . ') t',
)->fetchSingle()) )->fetchSingle())
: $this->getTotalCount(); : $this->getTotalCount();
} }
@@ -277,7 +277,7 @@ class DataSource implements IDataSource
{ {
if ($this->totalCount === null) { if ($this->totalCount === null) {
$this->totalCount = Helpers::intVal($this->connection->nativeQuery( $this->totalCount = Helpers::intVal($this->connection->nativeQuery(
'SELECT COUNT(*) FROM ' . $this->sql 'SELECT COUNT(*) FROM ' . $this->sql,
)->fetchSingle()); )->fetchSingle());
} }

View File

@@ -242,7 +242,7 @@ class FirebirdReflector implements Dibi\Reflector
END AS TRIGGER_ENABLED END AS TRIGGER_ENABLED
FROM RDB\$TRIGGERS FROM RDB\$TRIGGERS
WHERE RDB\$SYSTEM_FLAG = 0" WHERE RDB\$SYSTEM_FLAG = 0"
. ($table === null ? ';' : " AND RDB\$RELATION_NAME = UPPER('$table');") . ($table === null ? ';' : " AND RDB\$RELATION_NAME = UPPER('$table');"),
); );
$triggers = []; $triggers = [];
while ($row = $res->fetch(true)) { while ($row = $res->fetch(true)) {

View File

@@ -96,7 +96,7 @@ class MySqliDriver implements Dibi\Driver
$config['database'] ?? '', $config['database'] ?? '',
$config['port'] ?? 0, $config['port'] ?? 0,
$config['socket'], $config['socket'],
$config['flags'] ?? 0 $config['flags'] ?? 0,
); );
if ($this->connection->connect_errno) { if ($this->connection->connect_errno) {

View File

@@ -291,7 +291,7 @@ class SqliteDriver implements Dibi\Driver
string $name, string $name,
callable $rowCallback, callable $rowCallback,
callable $agrCallback, callable $agrCallback,
int $numArgs = -1 int $numArgs = -1,
): void ): void
{ {
$this->connection->createAggregate($name, $rowCallback, $agrCallback, $numArgs); $this->connection->createAggregate($name, $rowCallback, $agrCallback, $numArgs);

View File

@@ -76,7 +76,7 @@ class SqliteResult implements Dibi\ResultDriver
{ {
$count = $this->resultSet->numColumns(); $count = $this->resultSet->numColumns();
$columns = []; $columns = [];
static $types = [SQLITE3_INTEGER => 'int', SQLITE3_FLOAT => 'float', SQLITE3_TEXT => 'text', SQLITE3_BLOB => 'blob', SQLITE3_NULL => 'null']; $types = [SQLITE3_INTEGER => 'int', SQLITE3_FLOAT => 'float', SQLITE3_TEXT => 'text', SQLITE3_BLOB => 'blob', SQLITE3_NULL => 'null'];
for ($i = 0; $i < $count; $i++) { for ($i = 0; $i < $count; $i++) {
$columns[] = [ $columns[] = [
'name' => $this->resultSet->columnName($i), 'name' => $this->resultSet->columnName($i),

View File

@@ -60,7 +60,7 @@ class SqlsrvDriver implements Dibi\Driver
$options = $config['options']; $options = $config['options'];
// Default values // Default values
$options['CharacterSet'] = $options['CharacterSet'] ?? 'UTF-8'; $options['CharacterSet'] ??= 'UTF-8';
$options['PWD'] = (string) $options['PWD']; $options['PWD'] = (string) $options['PWD'];
$options['UID'] = (string) $options['UID']; $options['UID'] = (string) $options['UID'];
$options['Database'] = (string) $options['Database']; $options['Database'] = (string) $options['Database'];

View File

@@ -61,7 +61,7 @@ class Event
$this->time = -microtime(true); $this->time = -microtime(true);
if ($type === self::QUERY && preg_match('#\(?\s*(SELECT|UPDATE|INSERT|DELETE)#iA', $this->sql, $matches)) { if ($type === self::QUERY && preg_match('#\(?\s*(SELECT|UPDATE|INSERT|DELETE)#iA', $this->sql, $matches)) {
static $types = [ $types = [
'SELECT' => self::SELECT, 'UPDATE' => self::UPDATE, 'SELECT' => self::SELECT, 'UPDATE' => self::UPDATE,
'INSERT' => self::INSERT, 'DELETE' => self::DELETE, 'INSERT' => self::INSERT, 'DELETE' => self::DELETE,
]; ];

View File

@@ -75,8 +75,8 @@ class Helpers
$sql = \dibi::$sql; $sql = \dibi::$sql;
} }
static $keywords1 = 'SELECT|(?:ON\s+DUPLICATE\s+KEY)?UPDATE|INSERT(?:\s+INTO)?|REPLACE(?:\s+INTO)?|DELETE|CALL|UNION|FROM|WHERE|HAVING|GROUP\s+BY|ORDER\s+BY|LIMIT|OFFSET|FETCH\s+NEXT|SET|VALUES|LEFT\s+JOIN|INNER\s+JOIN|TRUNCATE|START\s+TRANSACTION|BEGIN|COMMIT|ROLLBACK(?:\s+TO\s+SAVEPOINT)?|(?:RELEASE\s+)?SAVEPOINT'; $keywords1 = 'SELECT|(?:ON\s+DUPLICATE\s+KEY)?UPDATE|INSERT(?:\s+INTO)?|REPLACE(?:\s+INTO)?|DELETE|CALL|UNION|FROM|WHERE|HAVING|GROUP\s+BY|ORDER\s+BY|LIMIT|OFFSET|FETCH\s+NEXT|SET|VALUES|LEFT\s+JOIN|INNER\s+JOIN|TRUNCATE|START\s+TRANSACTION|BEGIN|COMMIT|ROLLBACK(?:\s+TO\s+SAVEPOINT)?|(?:RELEASE\s+)?SAVEPOINT';
static $keywords2 = 'ALL|DISTINCT|DISTINCTROW|IGNORE|AS|USING|ON|AND|OR|IN|IS|NOT|NULL|LIKE|RLIKE|REGEXP|TRUE|FALSE'; $keywords2 = 'ALL|DISTINCT|DISTINCTROW|IGNORE|AS|USING|ON|AND|OR|IN|IS|NOT|NULL|LIKE|RLIKE|REGEXP|TRUE|FALSE';
// insert new lines // insert new lines
$sql = " $sql "; $sql = " $sql ";
@@ -162,7 +162,7 @@ class Helpers
/** @internal */ /** @internal */
public static function escape(Driver $driver, $value, string $type): string public static function escape(Driver $driver, $value, string $type): string
{ {
static $types = [ $types = [
Type::TEXT => 'text', Type::TEXT => 'text',
Type::BINARY => 'binary', Type::BINARY => 'binary',
Type::BOOL => 'bool', Type::BOOL => 'bool',
@@ -184,7 +184,7 @@ class Helpers
*/ */
public static function detectType(string $type): ?string public static function detectType(string $type): ?string
{ {
static $patterns = [ $patterns = [
'^_' => Type::TEXT, // PostgreSQL arrays '^_' => Type::TEXT, // PostgreSQL arrays
'RANGE$' => Type::TEXT, // PostgreSQL range types 'RANGE$' => Type::TEXT, // PostgreSQL range types
'BYTEA|BLOB|BIN' => Type::BINARY, 'BYTEA|BLOB|BIN' => Type::BINARY,

View File

@@ -58,7 +58,7 @@ class FileLogger
$this->writeToFile( $this->writeToFile(
$event, $event,
"ERROR: $message" "ERROR: $message"
. "\n-- SQL: " . $event->sql . "\n-- SQL: " . $event->sql,
); );
} else { } else {
$this->writeToFile( $this->writeToFile(
@@ -66,7 +66,7 @@ class FileLogger
'OK: ' . $event->sql 'OK: ' . $event->sql
. ($event->count ? ";\n-- rows: " . $event->count : '') . ($event->count ? ";\n-- rows: " . $event->count : '')
. "\n-- takes: " . sprintf('%0.3f ms', $event->time * 1000) . "\n-- takes: " . sprintf('%0.3f ms', $event->time * 1000)
. "\n-- source: " . implode(':', $event->source) . "\n-- source: " . implode(':', $event->source),
); );
} }
} }
@@ -76,7 +76,7 @@ class FileLogger
{ {
$driver = $event->connection->getConfig('driver'); $driver = $event->connection->getConfig('driver');
$message .= $message .=
"\n-- driver: " . (is_object($driver) ? get_class($driver) : $driver) . '/' . $event->connection->getConfig('name') "\n-- driver: " . (is_object($driver) ? $driver::class : $driver) . '/' . $event->connection->getConfig('name')
. "\n-- " . date('Y-m-d H:i:s') . "\n-- " . date('Y-m-d H:i:s')
. "\n\n"; . "\n\n";
file_put_contents($this->file, $message, FILE_APPEND | LOCK_EX); file_put_contents($this->file, $message, FILE_APPEND | LOCK_EX);

View File

@@ -206,7 +206,7 @@ class Result implements IDataSource
*/ */
final public function fetchAll(?int $offset = null, ?int $limit = null): array final public function fetchAll(?int $offset = null, ?int $limit = null): array
{ {
$limit = $limit ?? -1; $limit ??= -1;
$this->seek($offset ?: 0); $this->seek($offset ?: 0);
$row = $this->fetch(); $row = $this->fetch();
if (!$row) { if (!$row) {

View File

@@ -31,7 +31,7 @@ trait Strict
{ {
$class = method_exists($this, $name) ? 'parent' : static::class; $class = method_exists($this, $name) ? 'parent' : static::class;
$items = (new ReflectionClass($this))->getMethods(ReflectionMethod::IS_PUBLIC); $items = (new ReflectionClass($this))->getMethods(ReflectionMethod::IS_PUBLIC);
$items = array_map(function ($item) { return $item->getName(); }, $items); $items = array_map(fn($item) => $item->getName(), $items);
$hint = ($t = Helpers::getSuggestion($items, $name)) $hint = ($t = Helpers::getSuggestion($items, $name))
? ", did you mean $t()?" ? ", did you mean $t()?"
: '.'; : '.';
@@ -46,8 +46,8 @@ trait Strict
public static function __callStatic(string $name, array $args) public static function __callStatic(string $name, array $args)
{ {
$rc = new ReflectionClass(static::class); $rc = new ReflectionClass(static::class);
$items = array_filter($rc->getMethods(\ReflectionMethod::IS_STATIC), function ($m) { return $m->isPublic(); }); $items = array_filter($rc->getMethods(\ReflectionMethod::IS_STATIC), fn($m) => $m->isPublic());
$items = array_map(function ($item) { return $item->getName(); }, $items); $items = array_map(fn($item) => $item->getName(), $items);
$hint = ($t = Helpers::getSuggestion($items, $name)) $hint = ($t = Helpers::getSuggestion($items, $name))
? ", did you mean $t()?" ? ", did you mean $t()?"
: '.'; : '.';
@@ -69,8 +69,8 @@ trait Strict
} }
$rc = new ReflectionClass($this); $rc = new ReflectionClass($this);
$items = array_filter($rc->getProperties(ReflectionProperty::IS_PUBLIC), function ($p) { return !$p->isStatic(); }); $items = array_filter($rc->getProperties(ReflectionProperty::IS_PUBLIC), fn($p) => !$p->isStatic());
$items = array_map(function ($item) { return $item->getName(); }, $items); $items = array_map(fn($item) => $item->getName(), $items);
$hint = ($t = Helpers::getSuggestion($items, $name)) $hint = ($t = Helpers::getSuggestion($items, $name))
? ", did you mean $$t?" ? ", did you mean $$t?"
: '.'; : '.';
@@ -85,8 +85,8 @@ trait Strict
public function __set(string $name, $value) public function __set(string $name, $value)
{ {
$rc = new ReflectionClass($this); $rc = new ReflectionClass($this);
$items = array_filter($rc->getProperties(ReflectionProperty::IS_PUBLIC), function ($p) { return !$p->isStatic(); }); $items = array_filter($rc->getProperties(ReflectionProperty::IS_PUBLIC), fn($p) => !$p->isStatic());
$items = array_map(function ($item) { return $item->getName(); }, $items); $items = array_map(fn($item) => $item->getName(), $items);
$hint = ($t = Helpers::getSuggestion($items, $name)) $hint = ($t = Helpers::getSuggestion($items, $name))
? ", did you mean $$t?" ? ", did you mean $$t?"
: '.'; : '.';

View File

@@ -96,22 +96,21 @@ final class Translator
// note: this can change $this->args & $this->cursor & ... // note: this can change $this->args & $this->cursor & ...
. preg_replace_callback( . preg_replace_callback(
<<<'XX' <<<'XX'
/ /
(?=[`['":%?]) ## speed-up (?=[`['":%?]) ## speed-up
(?: (?:
`(.+?)`| ## 1) `identifier` `(.+?)`| ## 1) `identifier`
\[(.+?)\]| ## 2) [identifier] \[(.+?)\]| ## 2) [identifier]
(')((?:''|[^'])*)'| ## 3,4) string (')((?:''|[^'])*)'| ## 3,4) string
(")((?:""|[^"])*)"| ## 5,6) "string" (")((?:""|[^"])*)"| ## 5,6) "string"
('|")| ## 7) lone quote ('|")| ## 7) lone quote
:(\S*?:)([a-zA-Z0-9._]?)| ## 8,9) :substitution: :(\S*?:)([a-zA-Z0-9._]?)| ## 8,9) :substitution:
%([a-zA-Z~][a-zA-Z0-9~]{0,5})| ## 10) modifier %([a-zA-Z~][a-zA-Z0-9~]{0,5})| ## 10) modifier
(\?) ## 11) placeholder (\?) ## 11) placeholder
)/xs )/xs
XX XX,
,
[$this, 'cb'], [$this, 'cb'],
substr($arg, $toSkip) substr($arg, $toSkip),
); );
if (preg_last_error()) { if (preg_last_error()) {
throw new PcreException; throw new PcreException;
@@ -280,7 +279,7 @@ XX
$proto = array_keys($v); $proto = array_keys($v);
} }
} else { } else {
return $this->errors[] = '**Unexpected type ' . (is_object($v) ? get_class($v) : gettype($v)) . '**'; return $this->errors[] = '**Unexpected type ' . (is_object($v) ? $v::class : gettype($v)) . '**';
} }
$pair = explode('%', $k, 2); // split into identifier & modifier $pair = explode('%', $k, 2); // split into identifier & modifier
@@ -349,7 +348,7 @@ XX
) { ) {
// continue // continue
} else { } else {
$type = is_object($value) ? get_class($value) : gettype($value); $type = is_object($value) ? $value::class : gettype($value);
return $this->errors[] = "**Invalid combination of type $type and modifier %$modifier**"; return $this->errors[] = "**Invalid combination of type $type and modifier %$modifier**";
} }
} }
@@ -437,20 +436,19 @@ XX
$value = substr($value, 0, $toSkip) $value = substr($value, 0, $toSkip)
. preg_replace_callback( . preg_replace_callback(
<<<'XX' <<<'XX'
/ /
(?=[`['":]) (?=[`['":])
(?: (?:
`(.+?)`| `(.+?)`|
\[(.+?)\]| \[(.+?)]|
(')((?:''|[^'])*)'| (')((?:''|[^'])*)'|
(")((?:""|[^"])*)"| (")((?:""|[^"])*)"|
('|")| (['"])|
:(\S*?:)([a-zA-Z0-9._]?) :(\S*?:)([a-zA-Z0-9._]?)
)/sx )/sx
XX XX,
,
[$this, 'cb'], [$this, 'cb'],
substr($value, $toSkip) substr($value, $toSkip),
); );
if (preg_last_error()) { if (preg_last_error()) {
throw new PcreException; throw new PcreException;
@@ -516,7 +514,7 @@ XX
return $this->connection->translate(...$value->getValues()); return $this->connection->translate(...$value->getValues());
} else { } else {
$type = is_object($value) ? get_class($value) : gettype($value); $type = is_object($value) ? $value::class : gettype($value);
return $this->errors[] = "**Unexpected $type**"; return $this->errors[] = "**Unexpected $type**";
} }
} }

View File

@@ -164,7 +164,7 @@ class dibi
*/ */
public static function stripMicroseconds(DateTimeInterface $dt): DateTimeInterface public static function stripMicroseconds(DateTimeInterface $dt): DateTimeInterface
{ {
$class = get_class($dt); $class = $dt::class;
return new $class($dt->format('Y-m-d H:i:s'), $dt->getTimezone()); return new $class($dt->format('Y-m-d H:i:s'), $dt->getTimezone());
} }
} }

View File

@@ -73,24 +73,29 @@ test('', function () use ($config) {
test('', function () use ($config) { test('', function () use ($config) {
Assert::exception(function () use ($config) { Assert::exception(
new Connection($config + ['onConnect' => '']); fn() => new Connection($config + ['onConnect' => '']),
}, InvalidArgumentException::class, "Configuration option 'onConnect' must be array."); InvalidArgumentException::class,
"Configuration option 'onConnect' must be array.",
);
$e = Assert::exception(function () use ($config) { $e = Assert::exception(
new Connection($config + ['onConnect' => ['STOP']]); fn() => new Connection($config + ['onConnect' => ['STOP']]),
}, Dibi\DriverException::class); Dibi\DriverException::class,
);
Assert::same('STOP', $e->getSql()); Assert::same('STOP', $e->getSql());
$e = Assert::exception(function () use ($config) { $e = Assert::exception(
new Connection($config + ['onConnect' => [['STOP %i', 123]]]); fn() => new Connection($config + ['onConnect' => [['STOP %i', 123]]]),
}, Dibi\DriverException::class); Dibi\DriverException::class,
);
Assert::same('STOP 123', $e->getSql()); Assert::same('STOP 123', $e->getSql());
// lazy // lazy
$conn = new Connection($config + ['lazy' => true, 'onConnect' => ['STOP']]); $conn = new Connection($config + ['lazy' => true, 'onConnect' => ['STOP']]);
$e = Assert::exception(function () use ($conn) { $e = Assert::exception(
$conn->query('SELECT 1'); fn() => $conn->query('SELECT 1'),
}, Dibi\DriverException::class); Dibi\DriverException::class,
);
Assert::same('STOP', $e->getSql()); Assert::same('STOP', $e->getSql());
}); });

View File

@@ -33,13 +33,13 @@ Assert::equal([
$res = $conn->query('SELECT * FROM [products] ORDER BY product_id'); $res = $conn->query('SELECT * FROM [products] ORDER BY product_id');
Assert::same( Assert::same(
[1 => 'Chair', 'Table', 'Computer'], [1 => 'Chair', 'Table', 'Computer'],
$res->fetchPairs('product_id', 'title') $res->fetchPairs('product_id', 'title'),
); );
$res = $conn->query('SELECT * FROM [products] ORDER BY product_id'); $res = $conn->query('SELECT * FROM [products] ORDER BY product_id');
Assert::same( Assert::same(
[1 => 'Chair', 'Table', 'Computer'], [1 => 'Chair', 'Table', 'Computer'],
$res->fetchPairs() $res->fetchPairs(),
); );

View File

@@ -14,27 +14,27 @@ $conn->getSubstitutes()->blog = 'wp_';
Assert::same( Assert::same(
reformat('UPDATE wp_items SET [val]=1'), reformat('UPDATE wp_items SET [val]=1'),
$conn->translate('UPDATE :blog:items SET [val]=1') $conn->translate('UPDATE :blog:items SET [val]=1'),
); );
Assert::same( Assert::same(
reformat('UPDATE [wp_items] SET [val]=1'), reformat('UPDATE [wp_items] SET [val]=1'),
$conn->translate('UPDATE [:blog:items] SET [val]=1') $conn->translate('UPDATE [:blog:items] SET [val]=1'),
); );
Assert::same( Assert::same(
reformat("UPDATE 'wp_' SET [val]=1"), reformat("UPDATE 'wp_' SET [val]=1"),
$conn->translate('UPDATE :blog: SET [val]=1') $conn->translate('UPDATE :blog: SET [val]=1'),
); );
Assert::same( Assert::same(
reformat("UPDATE ':blg:' SET [val]=1"), reformat("UPDATE ':blg:' SET [val]=1"),
$conn->translate('UPDATE :blg: SET [val]=1') $conn->translate('UPDATE :blg: SET [val]=1'),
); );
Assert::same( Assert::same(
reformat("UPDATE table SET [text]=':blog:a'"), reformat("UPDATE table SET [text]=':blog:a'"),
$conn->translate("UPDATE table SET [text]=':blog:a'") $conn->translate("UPDATE table SET [text]=':blog:a'"),
); );
@@ -43,16 +43,14 @@ $conn->getSubstitutes()->{''} = 'my_';
Assert::same( Assert::same(
reformat('UPDATE my_table SET [val]=1'), reformat('UPDATE my_table SET [val]=1'),
$conn->translate('UPDATE ::table SET [val]=1') $conn->translate('UPDATE ::table SET [val]=1'),
); );
// create substitutions using fallback callback // create substitutions using fallback callback
$conn->getSubstitutes()->setCallback(function ($expr) { $conn->getSubstitutes()->setCallback(fn($expr) => '_' . $expr . '_');
return '_' . $expr . '_';
});
Assert::same( Assert::same(
reformat('UPDATE _account_user SET [val]=1'), reformat('UPDATE _account_user SET [val]=1'),
$conn->translate('UPDATE :account:user SET [val]=1') $conn->translate('UPDATE :account:user SET [val]=1'),
); );

View File

@@ -15,18 +15,22 @@ $conn = new Dibi\Connection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql"); $conn->loadFile(__DIR__ . "/data/$config[system].sql");
/*Assert::exception(function () use ($conn) { /*
$conn->rollback(); Assert::exception(
}, Dibi\Exception::class); fn() => $conn->rollback(),
Dibi\Exception::class,
);
Assert::exception(function () use ($conn) { Assert::exception(
$conn->commit(); fn() => $conn->commit(),
}, Dibi\Exception::class); Dibi\Exception::class,
);
$conn->begin(); $conn->begin();
Assert::exception(function () use ($conn) { Assert::exception(
$conn->begin(); fn() => $conn->begin(),
}, Dibi\Exception::class); Dibi\Exception::class,
);
*/ */
@@ -53,14 +57,16 @@ test('begin() & commit()', function () use ($conn) {
test('transaction() fail', function () use ($conn) { test('transaction() fail', function () use ($conn) {
Assert::exception(function () use ($conn) { Assert::exception(
$conn->transaction(function (Dibi\Connection $connection) { fn() => $conn->transaction(function (Dibi\Connection $connection) {
$connection->query('INSERT INTO [products]', [ $connection->query('INSERT INTO [products]', [
'title' => 'Test product', 'title' => 'Test product',
]); ]);
throw new Exception('my exception'); throw new Exception('my exception');
}); }),
}, Throwable::class, 'my exception'); Throwable::class,
'my exception',
);
Assert::same(4, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle()); Assert::same(4, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());
}); });
@@ -76,8 +82,8 @@ test('transaction() success', function () use ($conn) {
test('nested transaction() call fail', function () use ($conn) { test('nested transaction() call fail', function () use ($conn) {
Assert::exception(function () use ($conn) { Assert::exception(
$conn->transaction(function (Dibi\Connection $connection) { fn() => $conn->transaction(function (Dibi\Connection $connection) {
$connection->query('INSERT INTO [products]', [ $connection->query('INSERT INTO [products]', [
'title' => 'Test product', 'title' => 'Test product',
]); ]);
@@ -88,8 +94,10 @@ test('nested transaction() call fail', function () use ($conn) {
]); ]);
throw new Exception('my exception'); throw new Exception('my exception');
}); });
}); }),
}, Throwable::class, 'my exception'); Throwable::class,
'my exception',
);
Assert::same(5, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle()); Assert::same(5, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());
}); });
@@ -111,21 +119,27 @@ test('nested transaction() call success', function () use ($conn) {
test('begin(), commit() & rollback() calls are forbidden in transaction()', function () use ($conn) { test('begin(), commit() & rollback() calls are forbidden in transaction()', function () use ($conn) {
Assert::exception(function () use ($conn) { Assert::exception(
$conn->transaction(function (Dibi\Connection $connection) { fn() => $conn->transaction(function (Dibi\Connection $connection) {
$connection->begin(); $connection->begin();
}); }),
}, LogicException::class, Dibi\Connection::class . '::begin() call is forbidden inside a transaction() callback'); LogicException::class,
Dibi\Connection::class . '::begin() call is forbidden inside a transaction() callback',
);
Assert::exception(function () use ($conn) { Assert::exception(
$conn->transaction(function (Dibi\Connection $connection) { fn() => $conn->transaction(function (Dibi\Connection $connection) {
$connection->commit(); $connection->commit();
}); }),
}, LogicException::class, Dibi\Connection::class . '::commit() call is forbidden inside a transaction() callback'); LogicException::class,
Dibi\Connection::class . '::commit() call is forbidden inside a transaction() callback',
);
Assert::exception(function () use ($conn) { Assert::exception(
$conn->transaction(function (Dibi\Connection $connection) { fn() => $conn->transaction(function (Dibi\Connection $connection) {
$connection->rollback(); $connection->rollback();
}); }),
}, LogicException::class, Dibi\Connection::class . '::rollback() call is forbidden inside a transaction() callback'); LogicException::class,
Dibi\Connection::class . '::rollback() call is forbidden inside a transaction() callback',
);
}); });

View File

@@ -17,7 +17,7 @@ Assert::match(
reformat(' reformat('
SELECT * SELECT *
FROM (SELECT * FROM products) t'), FROM (SELECT * FROM products) t'),
(string) $ds (string) $ds,
); );
@@ -25,7 +25,7 @@ Assert::same(3, $ds->count());
Assert::same(3, $ds->getTotalCount()); Assert::same(3, $ds->getTotalCount());
Assert::same( Assert::same(
reformat('SELECT COUNT(*) FROM (SELECT * FROM products) t'), reformat('SELECT COUNT(*) FROM (SELECT * FROM products) t'),
dibi::$sql dibi::$sql,
); );
@@ -39,7 +39,7 @@ FROM (SELECT * FROM products) t
WHERE (title like '%a%') WHERE (title like '%a%')
ORDER BY [title] DESC ORDER BY [title] DESC
"), "),
(string) $ds (string) $ds,
); );
@@ -53,7 +53,7 @@ FROM (SELECT * FROM products) t
WHERE (title like '%a%') AND (product_id = 1) WHERE (title like '%a%') AND (product_id = 1)
ORDER BY [title] DESC, [product_id] ASC ORDER BY [title] DESC, [product_id] ASC
"), "),
(string) $ds (string) $ds,
); );
@@ -67,7 +67,7 @@ FROM (SELECT * FROM products) t
WHERE (title like '%a%') AND (product_id = 1) AND (product_id = 1) WHERE (title like '%a%') AND (product_id = 1) AND (product_id = 1)
ORDER BY [product_id] ASC ORDER BY [product_id] ASC
"), "),
(string) $ds (string) $ds,
); );
@@ -95,7 +95,7 @@ FROM (SELECT * FROM products) t
WHERE (title like '%a%') AND (product_id = 1) AND (product_id = 1) WHERE (title like '%a%') AND (product_id = 1) AND (product_id = 1)
ORDER BY [product_id] ASC ORDER BY [product_id] ASC
"), "),
dibi::$sql dibi::$sql,
); );
@@ -108,7 +108,7 @@ FROM (SELECT * FROM products) t
WHERE (title like '%a%') AND (product_id = 1) AND (product_id = 1) WHERE (title like '%a%') AND (product_id = 1) AND (product_id = 1)
ORDER BY [product_id] ASC ORDER BY [product_id] ASC
) t"), ) t"),
(string) $fluent (string) $fluent,
); );
@@ -117,7 +117,7 @@ Assert::match(
reformat(' reformat('
SELECT * SELECT *
FROM (SELECT [title] FROM [products]) t'), FROM (SELECT [title] FROM [products]) t'),
(string) $ds (string) $ds,
); );
Assert::equal(new Row([ Assert::equal(new Row([
@@ -129,7 +129,7 @@ Assert::same(1, $conn->dataSource('SELECT * FROM products ORDER BY product_id')-
Assert::same( Assert::same(
[1 => 'Chair', 'Table', 'Computer'], [1 => 'Chair', 'Table', 'Computer'],
$conn->dataSource('SELECT * FROM products ORDER BY product_id')->fetchPairs() $conn->dataSource('SELECT * FROM products ORDER BY product_id')->fetchPairs(),
); );
Assert::equal([ Assert::equal([
@@ -154,7 +154,7 @@ Assert::match(
reformat(' reformat('
SELECT * SELECT *
FROM [products]'), FROM [products]'),
(string) $ds (string) $ds,
); );
Assert::same(3, $ds->count()); Assert::same(3, $ds->count());

View File

@@ -10,10 +10,10 @@ require __DIR__ . '/bootstrap.php';
date_default_timezone_set('Europe/Prague'); date_default_timezone_set('Europe/Prague');
Assert::same('1978-01-23 11:40:00.000000', (string) new DateTime(254400000)); Assert::same('1978-01-23 11:40:00.000000', (string) new DateTime(254_400_000));
Assert::same('1978-01-23 11:40:00.000000', (string) (new DateTime)->setTimestamp(254400000)); Assert::same('1978-01-23 11:40:00.000000', (string) (new DateTime)->setTimestamp(254_400_000));
Assert::same(254400000, (new DateTime(254400000))->getTimestamp()); Assert::same(254_400_000, (new DateTime(254_400_000))->getTimestamp());
Assert::same(is_int(2544000000) ? 2544000000 : '2544000000', (new DateTime(2544000000))->getTimestamp()); // 64 bit Assert::same(is_int(2_544_000_000) ? 2_544_000_000 : '2544000000', (new DateTime(2_544_000_000))->getTimestamp()); // 64 bit
Assert::same('1978-05-05 00:00:00.000000', (string) new DateTime('1978-05-05')); Assert::same('1978-05-05 00:00:00.000000', (string) new DateTime('1978-05-05'));

View File

@@ -15,33 +15,33 @@ $fluent = $conn->delete('table')->as('bAlias')
Assert::same( Assert::same(
reformat('DELETE IGNORE FROM [table] AS [bAlias]'), reformat('DELETE IGNORE FROM [table] AS [bAlias]'),
(string) $fluent (string) $fluent,
); );
$fluent->removeClause('from')->from('anotherTable'); $fluent->removeClause('from')->from('anotherTable');
Assert::same( Assert::same(
reformat('DELETE IGNORE FROM [anotherTable]'), reformat('DELETE IGNORE FROM [anotherTable]'),
(string) $fluent (string) $fluent,
); );
$fluent->using('thirdTable'); $fluent->using('thirdTable');
Assert::same( Assert::same(
reformat('DELETE IGNORE FROM [anotherTable] USING [thirdTable]'), reformat('DELETE IGNORE FROM [anotherTable] USING [thirdTable]'),
(string) $fluent (string) $fluent,
); );
$fluent->setFlag('IGNORE', false); $fluent->setFlag('IGNORE', false);
Assert::same( Assert::same(
reformat('DELETE FROM [anotherTable] USING [thirdTable]'), reformat('DELETE FROM [anotherTable] USING [thirdTable]'),
(string) $fluent (string) $fluent,
); );
$fluent->limit(10); $fluent->limit(10);
Assert::same( Assert::same(
reformat('DELETE FROM [anotherTable] USING [thirdTable] LIMIT 10'), reformat('DELETE FROM [anotherTable] USING [thirdTable] LIMIT 10'),
(string) $fluent (string) $fluent,
); );

View File

@@ -58,28 +58,28 @@ $fluent = $conn->select('*')
Assert::same( Assert::same(
reformat('SELECT TOP (1) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t'), reformat('SELECT TOP (1) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t'),
(string) $fluent (string) $fluent,
); );
$fluent->fetch(); $fluent->fetch();
Assert::same( Assert::same(
'SELECT TOP (1) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t', 'SELECT TOP (1) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t',
dibi::$sql dibi::$sql,
); );
$fluent->fetchSingle(); $fluent->fetchSingle();
Assert::same( Assert::same(
reformat('SELECT TOP (1) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t'), reformat('SELECT TOP (1) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t'),
dibi::$sql dibi::$sql,
); );
$fluent->fetchAll(0, 3); $fluent->fetchAll(0, 3);
Assert::same( Assert::same(
reformat('SELECT TOP (3) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t'), reformat('SELECT TOP (3) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t'),
dibi::$sql dibi::$sql,
); );
Assert::same( Assert::same(
reformat('SELECT TOP (1) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t'), reformat('SELECT TOP (1) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t'),
(string) $fluent (string) $fluent,
); );
@@ -87,16 +87,16 @@ $fluent->limit(0);
$fluent->fetch(); $fluent->fetch();
Assert::same( Assert::same(
reformat('SELECT TOP (0) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t'), reformat('SELECT TOP (0) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t'),
dibi::$sql dibi::$sql,
); );
$fluent->fetchSingle(); $fluent->fetchSingle();
Assert::same( Assert::same(
reformat('SELECT TOP (0) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t'), reformat('SELECT TOP (0) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t'),
dibi::$sql dibi::$sql,
); );
Assert::same( Assert::same(
reformat('SELECT TOP (0) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t'), reformat('SELECT TOP (0) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t'),
(string) $fluent (string) $fluent,
); );
@@ -105,14 +105,14 @@ $fluent->removeClause('offset');
$fluent->fetch(); $fluent->fetch();
Assert::same( Assert::same(
reformat('SELECT TOP (1) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t'), reformat('SELECT TOP (1) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t'),
dibi::$sql dibi::$sql,
); );
$fluent->fetchSingle(); $fluent->fetchSingle();
Assert::same( Assert::same(
reformat('SELECT TOP (1) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t'), reformat('SELECT TOP (1) * FROM (SELECT * FROM [customers] ORDER BY [customer_id]) t'),
dibi::$sql dibi::$sql,
); );
Assert::same( Assert::same(
reformat('SELECT * FROM [customers] ORDER BY [customer_id]'), reformat('SELECT * FROM [customers] ORDER BY [customer_id]'),
(string) $fluent (string) $fluent,
); );

View File

@@ -23,28 +23,28 @@ $fluent = $conn->select('*')
Assert::same( Assert::same(
reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 1 OFFSET 3'), reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 1 OFFSET 3'),
(string) $fluent (string) $fluent,
); );
$fluent->fetch(); $fluent->fetch();
Assert::same( Assert::same(
reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 1 OFFSET 3'), reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 1 OFFSET 3'),
dibi::$sql dibi::$sql,
); );
$fluent->fetchSingle(); $fluent->fetchSingle();
Assert::same( Assert::same(
reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 1 OFFSET 3'), reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 1 OFFSET 3'),
dibi::$sql dibi::$sql,
); );
$fluent->fetchAll(2, 3); $fluent->fetchAll(2, 3);
Assert::same( Assert::same(
reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 3 OFFSET 2'), reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 3 OFFSET 2'),
dibi::$sql dibi::$sql,
); );
Assert::same( Assert::same(
reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 1 OFFSET 3'), reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 1 OFFSET 3'),
(string) $fluent (string) $fluent,
); );
@@ -52,16 +52,16 @@ $fluent->limit(0);
$fluent->fetch(); $fluent->fetch();
Assert::same( Assert::same(
reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 0 OFFSET 3'), reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 0 OFFSET 3'),
dibi::$sql dibi::$sql,
); );
$fluent->fetchSingle(); $fluent->fetchSingle();
Assert::same( Assert::same(
reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 0 OFFSET 3'), reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 0 OFFSET 3'),
dibi::$sql dibi::$sql,
); );
Assert::same( Assert::same(
reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 0 OFFSET 3'), reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 0 OFFSET 3'),
(string) $fluent (string) $fluent,
); );
@@ -69,16 +69,16 @@ $fluent->removeClause('limit');
$fluent->fetch(); $fluent->fetch();
Assert::same( Assert::same(
reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 1 OFFSET 3'), reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 1 OFFSET 3'),
dibi::$sql dibi::$sql,
); );
$fluent->fetchSingle(); $fluent->fetchSingle();
Assert::same( Assert::same(
reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 1 OFFSET 3'), reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 1 OFFSET 3'),
dibi::$sql dibi::$sql,
); );
Assert::same( Assert::same(
reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 18446744073709551615 OFFSET 3'), reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 18446744073709551615 OFFSET 3'),
(string) $fluent (string) $fluent,
); );
@@ -86,14 +86,14 @@ $fluent->removeClause('offset');
$fluent->fetch(); $fluent->fetch();
Assert::same( Assert::same(
reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 1'), reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 1'),
dibi::$sql dibi::$sql,
); );
$fluent->fetchSingle(); $fluent->fetchSingle();
Assert::same( Assert::same(
reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 1'), reformat('SELECT * FROM [customers] ORDER BY [customer_id] LIMIT 1'),
dibi::$sql dibi::$sql,
); );
Assert::same( Assert::same(
reformat('SELECT * FROM [customers] ORDER BY [customer_id]'), reformat('SELECT * FROM [customers] ORDER BY [customer_id]'),
(string) $fluent (string) $fluent,
); );

View File

@@ -21,40 +21,40 @@ $fluent = $conn->insert('table', $arr)
Assert::same( Assert::same(
reformat('INSERT IGNORE DELAYED INTO [table] ([title], [price], [brand]) VALUES (\'Super Product\', 12, NULL)'), reformat('INSERT IGNORE DELAYED INTO [table] ([title], [price], [brand]) VALUES (\'Super Product\', 12, NULL)'),
(string) $fluent (string) $fluent,
); );
$fluent->setFlag('IGNORE', false); $fluent->setFlag('IGNORE', false);
Assert::same( Assert::same(
reformat('INSERT DELAYED INTO [table] ([title], [price], [brand]) VALUES (\'Super Product\', 12, NULL)'), reformat('INSERT DELAYED INTO [table] ([title], [price], [brand]) VALUES (\'Super Product\', 12, NULL)'),
(string) $fluent (string) $fluent,
); );
$fluent->setFlag('HIGH_priority'); $fluent->setFlag('HIGH_priority');
Assert::same( Assert::same(
reformat('INSERT DELAYED HIGH_PRIORITY INTO [table] ([title], [price], [brand]) VALUES (\'Super Product\', 12, NULL)'), reformat('INSERT DELAYED HIGH_PRIORITY INTO [table] ([title], [price], [brand]) VALUES (\'Super Product\', 12, NULL)'),
(string) $fluent (string) $fluent,
); );
$fluent->into('anotherTable'); $fluent->into('anotherTable');
Assert::same( Assert::same(
reformat('INSERT DELAYED HIGH_PRIORITY INTO [anotherTable] VALUES (\'Super Product\', 12, NULL)'), reformat('INSERT DELAYED HIGH_PRIORITY INTO [anotherTable] VALUES (\'Super Product\', 12, NULL)'),
(string) $fluent (string) $fluent,
); );
$fluent->values('%l', $arr); $fluent->values('%l', $arr);
Assert::same( Assert::same(
reformat('INSERT DELAYED HIGH_PRIORITY INTO [anotherTable] VALUES (\'Super Product\', 12, NULL) , (\'Super Product\', 12, NULL)'), reformat('INSERT DELAYED HIGH_PRIORITY INTO [anotherTable] VALUES (\'Super Product\', 12, NULL) , (\'Super Product\', 12, NULL)'),
(string) $fluent (string) $fluent,
); );
$fluent->values($arr); $fluent->values($arr);
Assert::same( Assert::same(
reformat('INSERT DELAYED HIGH_PRIORITY INTO [anotherTable] VALUES (\'Super Product\', 12, NULL) , (\'Super Product\', 12, NULL) , (\'Super Product\', 12, NULL)'), reformat('INSERT DELAYED HIGH_PRIORITY INTO [anotherTable] VALUES (\'Super Product\', 12, NULL) , (\'Super Product\', 12, NULL) , (\'Super Product\', 12, NULL)'),
(string) $fluent (string) $fluent,
); );

View File

@@ -25,7 +25,7 @@ $fluent = $conn->select('*')
Assert::same( Assert::same(
reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d]'), reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d]'),
(string) $fluent (string) $fluent,
); );
$fluent->from('table')->as('table.Alias') $fluent->from('table')->as('table.Alias')
@@ -34,21 +34,21 @@ $fluent->from('table')->as('table.Alias')
Assert::same( Assert::same(
reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d] FROM [table] AS [table.Alias] INNER JOIN [table1] ON table.col = table1.col INNER JOIN [table2] ON table.col = table2.col'), reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d] FROM [table] AS [table.Alias] INNER JOIN [table1] ON table.col = table1.col INNER JOIN [table2] ON table.col = table2.col'),
(string) $fluent (string) $fluent,
); );
$fluent->from('anotherTable'); $fluent->from('anotherTable');
Assert::same( Assert::same(
reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d] FROM [table] AS [table.Alias] INNER JOIN [table1] ON table.col = table1.col INNER JOIN [table2] ON table.col = table2.col , [anotherTable]'), reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d] FROM [table] AS [table.Alias] INNER JOIN [table1] ON table.col = table1.col INNER JOIN [table2] ON table.col = table2.col , [anotherTable]'),
(string) $fluent (string) $fluent,
); );
$fluent->removeClause('from')->from('anotherTable'); $fluent->removeClause('from')->from('anotherTable');
Assert::same( Assert::same(
reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d] FROM [anotherTable]'), reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d] FROM [anotherTable]'),
(string) $fluent (string) $fluent,
); );
$fluent->as('anotherAlias') $fluent->as('anotherAlias')
@@ -58,7 +58,7 @@ $fluent->as('anotherAlias')
Assert::same( Assert::same(
reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d] FROM [anotherTable] AS [anotherAlias] INNER JOIN [table3] ON table.col = table3.col'), reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d] FROM [anotherTable] AS [anotherAlias] INNER JOIN [table3] ON table.col = table3.col'),
(string) $fluent (string) $fluent,
); );
$fluent->where('col > %i', $max) $fluent->where('col > %i', $max)
@@ -71,14 +71,14 @@ $fluent->where('col > %i', $max)
Assert::same( Assert::same(
reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d] FROM [anotherTable] AS [anotherAlias] INNER JOIN [table3] ON table.col = table3.col WHERE col > 10 OR col < 5 AND active = 1 AND [col] IN (1, 2, 3) ORDER BY [val] ASC , [val2] DESC , [val3] DESC'), reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d] FROM [anotherTable] AS [anotherAlias] INNER JOIN [table3] ON table.col = table3.col WHERE col > 10 OR col < 5 AND active = 1 AND [col] IN (1, 2, 3) ORDER BY [val] ASC , [val2] DESC , [val3] DESC'),
(string) $fluent (string) $fluent,
); );
$fluent->orderBy(Dibi\Fluent::REMOVE); $fluent->orderBy(Dibi\Fluent::REMOVE);
Assert::same( Assert::same(
reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d] FROM [anotherTable] AS [anotherAlias] INNER JOIN [table3] ON table.col = table3.col WHERE col > 10 OR col < 5 AND active = 1 AND [col] IN (1, 2, 3)'), reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d] FROM [anotherTable] AS [anotherAlias] INNER JOIN [table3] ON table.col = table3.col WHERE col > 10 OR col < 5 AND active = 1 AND [col] IN (1, 2, 3)'),
(string) $fluent (string) $fluent,
); );
@@ -86,7 +86,7 @@ $fluent = $conn->select('*')
->select( ->select(
$conn->select('count(*)') $conn->select('count(*)')
->from('precteni')->as('P') ->from('precteni')->as('P')
->where('P.id_clanku', '=', 'C.id_clanku') ->where('P.id_clanku', '=', 'C.id_clanku'),
) )
->from('clanky')->as('C') ->from('clanky')->as('C')
->where('id_clanku=%i', 123) ->where('id_clanku=%i', 123)
@@ -99,7 +99,7 @@ Assert::same(
'sqlsrv' => 'SELECT * , (SELECT count(*) FROM [precteni] AS [P] WHERE P.id_clanku = C.id_clanku) FROM [clanky] AS [C] WHERE id_clanku=123 OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY', 'sqlsrv' => 'SELECT * , (SELECT count(*) FROM [precteni] AS [P] WHERE P.id_clanku = C.id_clanku) FROM [clanky] AS [C] WHERE id_clanku=123 OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY',
'SELECT * , (SELECT count(*) FROM [precteni] AS [P] WHERE P.id_clanku = C.id_clanku) FROM [clanky] AS [C] WHERE id_clanku=123 LIMIT 1', 'SELECT * , (SELECT count(*) FROM [precteni] AS [P] WHERE P.id_clanku = C.id_clanku) FROM [clanky] AS [C] WHERE id_clanku=123 LIMIT 1',
]), ]),
(string) $fluent (string) $fluent,
); );
@@ -112,7 +112,7 @@ $fluent = $conn->select('*')
Assert::same( Assert::same(
reformat('SELECT * , [x] AS [xAlias] FROM [products] INNER JOIN [orders] USING (product_id) INNER JOIN [customers] USING ([customer_id]) INNER JOIN [items] USING ([customer_id], [order_id])'), reformat('SELECT * , [x] AS [xAlias] FROM [products] INNER JOIN [orders] USING (product_id) INNER JOIN [customers] USING ([customer_id]) INNER JOIN [items] USING ([customer_id], [order_id])'),
(string) $fluent (string) $fluent,
); );
@@ -124,7 +124,7 @@ $fluent = $conn->command()->select()
Assert::same( Assert::same(
reformat('SELECT * FROM [products] INNER JOIN [orders] USING (product_id)'), reformat('SELECT * FROM [products] INNER JOIN [orders] USING (product_id)'),
(string) $fluent (string) $fluent,
); );
@@ -138,7 +138,7 @@ Assert::same(
'sqlsrv' => "SELECT * FROM [me] AS [t] WHERE col > 10 AND ([x] = N'a') AND (b) AND (c)", 'sqlsrv' => "SELECT * FROM [me] AS [t] WHERE col > 10 AND ([x] = N'a') AND (b) AND (c)",
"SELECT * FROM [me] AS [t] WHERE col > 10 AND ([x] = 'a') AND (b) AND (c)", "SELECT * FROM [me] AS [t] WHERE col > 10 AND ([x] = 'a') AND (b) AND (c)",
]), ]),
(string) $fluent (string) $fluent,
); );
@@ -158,5 +158,5 @@ $fluent = $conn->select('*')->from('abc')
Assert::same( Assert::same(
reformat('SELECT * FROM [abc] WHERE x IN ((SELECT [id] FROM [xyz]))'), reformat('SELECT * FROM [abc] WHERE x IN ((SELECT [id] FROM [xyz]))'),
(string) $fluent (string) $fluent,
); );

View File

@@ -21,14 +21,14 @@ $fluent = $conn->update('table', $arr)
Assert::same( Assert::same(
reformat('UPDATE IGNORE DELAYED [table] SET [title]=\'Super Product\', [price]=12, [brand]=NULL'), reformat('UPDATE IGNORE DELAYED [table] SET [title]=\'Super Product\', [price]=12, [brand]=NULL'),
(string) $fluent (string) $fluent,
); );
$fluent->set(['another' => 123]); $fluent->set(['another' => 123]);
Assert::same( Assert::same(
reformat('UPDATE IGNORE DELAYED [table] SET [title]=\'Super Product\', [price]=12, [brand]=NULL , [another]=123'), reformat('UPDATE IGNORE DELAYED [table] SET [title]=\'Super Product\', [price]=12, [brand]=NULL , [another]=123'),
(string) $fluent (string) $fluent,
); );
@@ -40,5 +40,5 @@ $arr = [
$fluent = $conn->update(['table1', 'table2'], $arr); $fluent = $conn->update(['table1', 'table2'], $arr);
Assert::same( Assert::same(
reformat('UPDATE [table1], [table2] SET [table1].[title]=\'Super Product\', [table2].[price]=12, [table2].[brand]=NULL'), reformat('UPDATE [table1], [table2] SET [table1].[title]=\'Super Product\', [table2].[price]=12, [table2].[brand]=NULL'),
(string) $fluent (string) $fluent,
); );

View File

@@ -6,9 +6,7 @@ use Tester\Assert;
require __DIR__ . '/bootstrap.php'; require __DIR__ . '/bootstrap.php';
$hash = new Dibi\HashMap(function ($v) { $hash = new Dibi\HashMap(fn($v) => "b-$v-e");
return "b-$v-e";
});
Assert::same('b-X-e', $hash->{'X'}); Assert::same('b-X-e', $hash->{'X'});
Assert::same('b--e', $hash->{''}); Assert::same('b--e', $hash->{''});

View File

@@ -12,22 +12,32 @@ Assert::same(0, Helpers::intVal(0));
Assert::same(0, Helpers::intVal('0')); Assert::same(0, Helpers::intVal('0'));
Assert::same(-10, Helpers::intVal('-10')); Assert::same(-10, Helpers::intVal('-10'));
Assert::exception(function () { Assert::exception(
Helpers::intVal('12345678901234567890123456879'); fn() => Helpers::intVal('12345678901234567890123456879'),
}, Dibi\Exception::class, 'Number 12345678901234567890123456879 is greater than integer.'); Dibi\Exception::class,
'Number 12345678901234567890123456879 is greater than integer.',
);
Assert::exception(function () { Assert::exception(
Helpers::intVal('-12345678901234567890123456879'); fn() => Helpers::intVal('-12345678901234567890123456879'),
}, Dibi\Exception::class, 'Number -12345678901234567890123456879 is greater than integer.'); Dibi\Exception::class,
'Number -12345678901234567890123456879 is greater than integer.',
);
Assert::exception(function () { Assert::exception(
Helpers::intVal(''); fn() => Helpers::intVal(''),
}, Dibi\Exception::class, "Expected number, '' given."); Dibi\Exception::class,
"Expected number, '' given.",
);
Assert::exception(function () { Assert::exception(
Helpers::intVal('not number'); fn() => Helpers::intVal('not number'),
}, Dibi\Exception::class, "Expected number, 'not number' given."); Dibi\Exception::class,
"Expected number, 'not number' given.",
);
Assert::exception(function () { Assert::exception(
Helpers::intVal(null); fn() => Helpers::intVal(null),
}, Dibi\Exception::class, "Expected number, '' given."); Dibi\Exception::class,
"Expected number, '' given.",
);

View File

@@ -19,17 +19,22 @@ function buildPdoDriver(?int $errorMode)
// PDO error mode: exception // PDO error mode: exception
Assert::exception(function () { Assert::exception(
buildPdoDriver(PDO::ERRMODE_EXCEPTION); fn() => buildPdoDriver(PDO::ERRMODE_EXCEPTION),
}, Dibi\DriverException::class, 'PDO connection in exception or warning error mode is not supported.'); Dibi\DriverException::class,
'PDO connection in exception or warning error mode is not supported.',
);
// PDO error mode: warning // PDO error mode: warning
Assert::exception(function () { Assert::exception(
buildPdoDriver(PDO::ERRMODE_WARNING); fn() => buildPdoDriver(PDO::ERRMODE_WARNING),
}, Dibi\DriverException::class, 'PDO connection in exception or warning error mode is not supported.'); Dibi\DriverException::class,
'PDO connection in exception or warning error mode is not supported.',
);
test('PDO error mode: explicitly set silent', function () { test(
buildPdoDriver(PDO::ERRMODE_SILENT); 'PDO error mode: explicitly set silent',
}); fn() => buildPdoDriver(PDO::ERRMODE_SILENT)
);

View File

@@ -28,14 +28,14 @@ Assert::same(4, $res->getColumnCount());
Assert::same( Assert::same(
['product_id', 'order_id', 'name', 'xXx'], ['product_id', 'order_id', 'name', 'xXx'],
$info->getColumnNames() $info->getColumnNames(),
); );
if (!in_array($config['driver'], ['sqlite', 'sqlite3', 'pdo', 'sqlsrv'], true)) { if (!in_array($config['driver'], ['sqlite', 'sqlite3', 'pdo', 'sqlsrv'], true)) {
Assert::same( Assert::same(
['products.product_id', 'orders.order_id', 'customers.name', 'xXx'], ['products.product_id', 'orders.order_id', 'customers.name', 'xXx'],
$info->getColumnNames(true) $info->getColumnNames(true),
); );
} }

View File

@@ -162,9 +162,10 @@ test('', function () {
if (PHP_VERSION_ID < 80000) { if (PHP_VERSION_ID < 80000) {
Assert::same(['col' => 0], @$result->test(['col' => ''])); // triggers warning since PHP 7.1 Assert::same(['col' => 0], @$result->test(['col' => ''])); // triggers warning since PHP 7.1
} else { } else {
Assert::exception(function () use ($result) { Assert::exception(
Assert::same(['col' => 0], $result->test(['col' => ''])); fn() => Assert::same(['col' => 0], $result->test(['col' => ''])),
}, TypeError::class); TypeError::class,
);
} }
Assert::same(['col' => 0], $result->test(['col' => '0'])); Assert::same(['col' => 0], $result->test(['col' => '0']));
@@ -189,9 +190,10 @@ test('', function () {
$result->setType('col', Type::DATETIME); $result->setType('col', Type::DATETIME);
Assert::same(['col' => null], $result->test(['col' => null])); Assert::same(['col' => null], $result->test(['col' => null]));
Assert::exception(function () use ($result) { Assert::exception(
$result->test(['col' => true]); fn() => $result->test(['col' => true]),
}, TypeError::class); TypeError::class,
);
Assert::same(['col' => null], $result->test(['col' => false])); Assert::same(['col' => null], $result->test(['col' => false]));
Assert::same(['col' => null], $result->test(['col' => ''])); Assert::same(['col' => null], $result->test(['col' => '']));
@@ -208,9 +210,10 @@ test('', function () {
$result->setFormat(Type::DATETIME, 'Y-m-d H:i:s'); $result->setFormat(Type::DATETIME, 'Y-m-d H:i:s');
Assert::same(['col' => null], $result->test(['col' => null])); Assert::same(['col' => null], $result->test(['col' => null]));
Assert::exception(function () use ($result) { Assert::exception(
$result->test(['col' => true]); fn() => $result->test(['col' => true]),
}, TypeError::class); TypeError::class,
);
Assert::same(['col' => null], $result->test(['col' => false])); Assert::same(['col' => null], $result->test(['col' => false]));
Assert::same(['col' => null], $result->test(['col' => ''])); Assert::same(['col' => null], $result->test(['col' => '']));
@@ -226,9 +229,10 @@ test('', function () {
$result->setType('col', Type::DATE); $result->setType('col', Type::DATE);
Assert::same(['col' => null], $result->test(['col' => null])); Assert::same(['col' => null], $result->test(['col' => null]));
Assert::exception(function () use ($result) { Assert::exception(
$result->test(['col' => true]); fn() => $result->test(['col' => true]),
}, TypeError::class); TypeError::class,
);
Assert::same(['col' => null], $result->test(['col' => false])); Assert::same(['col' => null], $result->test(['col' => false]));
Assert::same(['col' => null], $result->test(['col' => ''])); Assert::same(['col' => null], $result->test(['col' => '']));
@@ -242,9 +246,10 @@ test('', function () {
$result->setType('col', Type::TIME); $result->setType('col', Type::TIME);
Assert::same(['col' => null], $result->test(['col' => null])); Assert::same(['col' => null], $result->test(['col' => null]));
Assert::exception(function () use ($result) { Assert::exception(
$result->test(['col' => true]); fn() => $result->test(['col' => true]),
}, TypeError::class); TypeError::class,
);
Assert::same(['col' => null], $result->test(['col' => false])); Assert::same(['col' => null], $result->test(['col' => false]));
Assert::same(['col' => null], $result->test(['col' => ''])); Assert::same(['col' => null], $result->test(['col' => '']));

View File

@@ -25,7 +25,7 @@ $conn->query(
'CREATE TRIGGER %n ON %n AFTER INSERT AS INSERT INTO %n DEFAULT VALUES', 'CREATE TRIGGER %n ON %n AFTER INSERT AS INSERT INTO %n DEFAULT VALUES',
'UpdAAB', 'UpdAAB',
'aab', 'aab',
'aaa' 'aaa',
); );
$conn->query('INSERT INTO %n DEFAULT VALUES', 'aab'); $conn->query('INSERT INTO %n DEFAULT VALUES', 'aab');

View File

@@ -21,19 +21,19 @@ $tests = function ($conn) {
// Limit and offset // Limit and offset
Assert::same( Assert::same(
'SELECT 1 OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY', 'SELECT 1 OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY',
$conn->translate('SELECT 1 %ofs %lmt', 10, 10) $conn->translate('SELECT 1 %ofs %lmt', 10, 10),
); );
// Limit only // Limit only
Assert::same( Assert::same(
'SELECT 1 OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY', 'SELECT 1 OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY',
$conn->translate('SELECT 1 %lmt', 10) $conn->translate('SELECT 1 %lmt', 10),
); );
// Offset only // Offset only
Assert::same( Assert::same(
'SELECT 1 OFFSET 10 ROWS', 'SELECT 1 OFFSET 10 ROWS',
$conn->translate('SELECT 1 %ofs', 10) $conn->translate('SELECT 1 %ofs', 10),
); );
// Offset invalid // Offset invalid
@@ -42,7 +42,7 @@ $tests = function ($conn) {
$conn->translate('SELECT 1 %ofs', -10); $conn->translate('SELECT 1 %ofs', -10);
}, },
Dibi\NotSupportedException::class, Dibi\NotSupportedException::class,
'Negative offset or limit.' 'Negative offset or limit.',
); );
// Limit invalid // Limit invalid
@@ -51,7 +51,7 @@ $tests = function ($conn) {
$conn->translate('SELECT 1 %lmt', -10); $conn->translate('SELECT 1 %lmt', -10);
}, },
Dibi\NotSupportedException::class, Dibi\NotSupportedException::class,
'Negative offset or limit.' 'Negative offset or limit.',
); );
// Limit invalid, offset valid // Limit invalid, offset valid
@@ -60,7 +60,7 @@ $tests = function ($conn) {
$conn->translate('SELECT 1 %ofs %lmt', 10, -10); $conn->translate('SELECT 1 %ofs %lmt', 10, -10);
}, },
Dibi\NotSupportedException::class, Dibi\NotSupportedException::class,
'Negative offset or limit.' 'Negative offset or limit.',
); );
// Limit valid, offset invalid // Limit valid, offset invalid
@@ -69,22 +69,23 @@ $tests = function ($conn) {
$conn->translate('SELECT 1 %ofs %lmt', -10, 10); $conn->translate('SELECT 1 %ofs %lmt', -10, 10);
}, },
Dibi\NotSupportedException::class, Dibi\NotSupportedException::class,
'Negative offset or limit.' 'Negative offset or limit.',
); );
} else { } else {
Assert::same( Assert::same(
'SELECT TOP (1) * FROM (SELECT 1) t', 'SELECT TOP (1) * FROM (SELECT 1) t',
$conn->translate('SELECT 1 %lmt', 1) $conn->translate('SELECT 1 %lmt', 1),
); );
Assert::same( Assert::same(
'SELECT 1', 'SELECT 1',
$conn->translate('SELECT 1 %lmt', -10) $conn->translate('SELECT 1 %lmt', -10),
); );
Assert::exception(function () { Assert::exception(
$conn->translate('SELECT 1 %ofs %lmt', 10, 10); fn() => $conn->translate('SELECT 1 %ofs %lmt', 10, 10),
}, Dibi\NotSupportedException::class); Dibi\NotSupportedException::class,
);
} }
}; };

View File

@@ -13,13 +13,16 @@ switch ($config['system']) {
case 'mysql': case 'mysql':
Assert::equal('10:20:30.0', $translator->formatValue(new DateInterval('PT10H20M30S'), null)); Assert::equal('10:20:30.0', $translator->formatValue(new DateInterval('PT10H20M30S'), null));
Assert::equal('-1:00:00.0', $translator->formatValue(DateInterval::createFromDateString('-1 hour'), null)); Assert::equal('-1:00:00.0', $translator->formatValue(DateInterval::createFromDateString('-1 hour'), null));
Assert::exception(function () use ($translator) { Assert::exception(
$translator->formatValue(new DateInterval('P2Y4DT6H8M'), null); fn() => $translator->formatValue(new DateInterval('P2Y4DT6H8M'), null),
}, Dibi\NotSupportedException::class, 'Only time interval is supported.'); Dibi\NotSupportedException::class,
'Only time interval is supported.',
);
break; break;
default: default:
Assert::exception(function () use ($translator) { Assert::exception(
$translator->formatValue(new DateInterval('PT10H20M30S'), null); fn() => $translator->formatValue(new DateInterval('PT10H20M30S'), null),
}, Dibi\Exception::class); Dibi\Exception::class,
);
} }

View File

@@ -27,8 +27,8 @@ FROM [customers]
isset($name), isset($name),
'WHERE [name] LIKE %s', 'WHERE [name] LIKE %s',
'xxx', 'xxx',
'%end' '%end',
) ),
); );
@@ -42,8 +42,8 @@ FROM [customers] /* ... */'),
SELECT * SELECT *
FROM %if', FROM %if',
true, true,
'[customers] %else [products]' '[customers] %else [products]',
) ),
); );
@@ -62,7 +62,7 @@ FROM [people]
WHERE [id] > 0 WHERE [id] > 0
%if', false, 'AND [foo]=%i', 1, ' %if', false, 'AND [foo]=%i', 1, '
%else %if', true, 'AND [bar]=%i', 1, ' %else %if', true, 'AND [bar]=%i', 1, '
') '),
); );
@@ -97,8 +97,8 @@ WHERE
%if', %if',
false, false,
'AND [admin]=1 %end 'AND [admin]=1 %end
%else 1 LIMIT 10 %end' %else 1 LIMIT 10 %end',
) ),
); );
@@ -113,6 +113,6 @@ Assert::same(
3, 3,
'%ofs', '%ofs',
5, 5,
'%end' '%end',
) ),
); );

View File

@@ -15,35 +15,35 @@ $conn = new Dibi\Connection($config);
Assert::same( Assert::same(
reformat('SELECT * FROM where WHERE select < 2'), reformat('SELECT * FROM where WHERE select < 2'),
$conn->translate('SELECT * FROM where WHERE select < 2') $conn->translate('SELECT * FROM where WHERE select < 2'),
); );
Assert::same( Assert::same(
reformat('SELECT * FROM [where] WHERE where.select < 2'), reformat('SELECT * FROM [where] WHERE where.select < 2'),
$conn->translate('SELECT * FROM [where] WHERE where.select < 2') $conn->translate('SELECT * FROM [where] WHERE where.select < 2'),
); );
Assert::same( Assert::same(
reformat('SELECT * FROM [where] WHERE [where].[select] < 2'), reformat('SELECT * FROM [where] WHERE [where].[select] < 2'),
$conn->translate('SELECT * FROM [where] WHERE [where.select] < 2') $conn->translate('SELECT * FROM [where] WHERE [where.select] < 2'),
); );
Assert::same( Assert::same(
reformat('SELECT * FROM [where] as [temp] WHERE [temp].[select] < 2'), reformat('SELECT * FROM [where] as [temp] WHERE [temp].[select] < 2'),
$conn->translate('SELECT * FROM [where] as [temp] WHERE [temp.select] < 2') $conn->translate('SELECT * FROM [where] as [temp] WHERE [temp.select] < 2'),
); );
Assert::same( Assert::same(
reformat('SELECT * FROM [where] WHERE [quot\'n\' space] > 2'), reformat('SELECT * FROM [where] WHERE [quot\'n\' space] > 2'),
$conn->translate("SELECT * FROM [where] WHERE [quot'n' space] > 2") $conn->translate("SELECT * FROM [where] WHERE [quot'n' space] > 2"),
); );
Assert::same( Assert::same(
reformat('SELECT * FROM [where] WHERE [where].[quot\'n\' space] > 2'), reformat('SELECT * FROM [where] WHERE [where].[quot\'n\' space] > 2'),
$conn->translate("SELECT * FROM [where] WHERE [where.quot'n' space] > 2") $conn->translate("SELECT * FROM [where] WHERE [where.quot'n' space] > 2"),
); );

View File

@@ -23,7 +23,7 @@ Assert::same(
$conn->translate('REPLACE INTO [products]', [ $conn->translate('REPLACE INTO [products]', [
'title' => 'Drticka', 'title' => 'Drticka',
'price' => 318, 'price' => 318,
]) ]),
); );
@@ -38,7 +38,7 @@ Assert::same(
'sqlsrv' => "INSERT INTO [products] ([title], [price], [brand]) VALUES (N'Super Product', 12, NULL) , (N'Super Product', 12, NULL) , (N'Super Product', 12, NULL)", 'sqlsrv' => "INSERT INTO [products] ([title], [price], [brand]) VALUES (N'Super Product', 12, NULL) , (N'Super Product', 12, NULL) , (N'Super Product', 12, NULL)",
"INSERT INTO [products] ([title], [price], [brand]) VALUES ('Super Product', 12, NULL) , ('Super Product', 12, NULL) , ('Super Product', 12, NULL)", "INSERT INTO [products] ([title], [price], [brand]) VALUES ('Super Product', 12, NULL) , ('Super Product', 12, NULL) , ('Super Product', 12, NULL)",
]), ]),
$conn->translate('INSERT INTO [products]', $array, $array, $array) $conn->translate('INSERT INTO [products]', $array, $array, $array),
); );
@@ -53,7 +53,7 @@ Assert::same(
'sqlsrv' => "INSERT INTO [products] ([pole], [bit]) VALUES (N'hodnota1', 1) , (N'hodnota2', 1) , (N'hodnota3', 1)", 'sqlsrv' => "INSERT INTO [products] ([pole], [bit]) VALUES (N'hodnota1', 1) , (N'hodnota2', 1) , (N'hodnota3', 1)",
"INSERT INTO [products] ([pole], [bit]) VALUES ('hodnota1', 1) , ('hodnota2', 1) , ('hodnota3', 1)", "INSERT INTO [products] ([pole], [bit]) VALUES ('hodnota1', 1) , ('hodnota2', 1) , ('hodnota3', 1)",
]), ]),
$conn->translate('INSERT INTO [products] %ex', $array) $conn->translate('INSERT INTO [products] %ex', $array),
); );
@@ -66,7 +66,7 @@ Assert::same(
$conn->translate('UPDATE [colors] SET', [ $conn->translate('UPDATE [colors] SET', [
'color' => 'blue', 'color' => 'blue',
'order' => 12, 'order' => 12,
], 'WHERE [id]=%i', 123) ], 'WHERE [id]=%i', 123),
); );
@@ -74,26 +74,28 @@ Assert::same(
$array = [1, 2, 3]; $array = [1, 2, 3];
Assert::same( Assert::same(
reformat('SELECT * FROM [people] WHERE [id] IN ( 1, 2, 3 )'), reformat('SELECT * FROM [people] WHERE [id] IN ( 1, 2, 3 )'),
$conn->translate('SELECT * FROM [people] WHERE [id] IN (', $array, ')') $conn->translate('SELECT * FROM [people] WHERE [id] IN (', $array, ')'),
); );
// long numbers // long numbers
Assert::same( Assert::same(
reformat('SELECT -123456789123456789123456789'), reformat('SELECT -123456789123456789123456789'),
$conn->translate('SELECT %i', '-123456789123456789123456789') $conn->translate('SELECT %i', '-123456789123456789123456789'),
); );
// long float numbers // long float numbers
Assert::same( Assert::same(
reformat('SELECT -.12345678912345678912345678e10'), reformat('SELECT -.12345678912345678912345678e10'),
$conn->translate('SELECT %f', '-.12345678912345678912345678e10') $conn->translate('SELECT %f', '-.12345678912345678912345678e10'),
); );
// invalid input // invalid input
$e = Assert::exception(function () use ($conn) { $e = Assert::exception(
$conn->translate('SELECT %s', (object) [123], ', %m', 123); fn() => $conn->translate('SELECT %s', (object) [123], ', %m', 123),
}, Dibi\Exception::class, 'SQL translate error: Invalid combination of type stdClass and modifier %s'); Dibi\Exception::class,
'SQL translate error: Invalid combination of type stdClass and modifier %s',
);
Assert::same('SELECT **Invalid combination of type stdClass and modifier %s** , **Unknown or unexpected modifier %m**', $e->getSql()); Assert::same('SELECT **Invalid combination of type stdClass and modifier %s** , **Unknown or unexpected modifier %m**', $e->getSql());
Assert::same( Assert::same(
@@ -101,7 +103,7 @@ Assert::same(
'sqlsrv' => "SELECT * FROM [table] WHERE id=10 AND name=N'ahoj'", 'sqlsrv' => "SELECT * FROM [table] WHERE id=10 AND name=N'ahoj'",
"SELECT * FROM [table] WHERE id=10 AND name='ahoj'", "SELECT * FROM [table] WHERE id=10 AND name='ahoj'",
]), ]),
$conn->translate('SELECT * FROM [table] WHERE id=%i AND name=%s', 10, 'ahoj') $conn->translate('SELECT * FROM [table] WHERE id=%i AND name=%s', 10, 'ahoj'),
); );
Assert::same( Assert::same(
@@ -109,7 +111,7 @@ Assert::same(
'sqlsrv' => "TEST ([cond] > 2) OR ([cond2] = N'3') OR (cond3 < RAND())", 'sqlsrv' => "TEST ([cond] > 2) OR ([cond2] = N'3') OR (cond3 < RAND())",
"TEST ([cond] > 2) OR ([cond2] = '3') OR (cond3 < RAND())", "TEST ([cond] > 2) OR ([cond2] = '3') OR (cond3 < RAND())",
]), ]),
$conn->translate('TEST %or', ['[cond] > 2', '[cond2] = "3"', 'cond3 < RAND()']) $conn->translate('TEST %or', ['[cond] > 2', '[cond2] = "3"', 'cond3 < RAND()']),
); );
Assert::same( Assert::same(
@@ -117,7 +119,7 @@ Assert::same(
'sqlsrv' => "TEST ([cond] > 2) AND ([cond2] = N'3') AND (cond3 < RAND())", 'sqlsrv' => "TEST ([cond] > 2) AND ([cond2] = N'3') AND (cond3 < RAND())",
"TEST ([cond] > 2) AND ([cond2] = '3') AND (cond3 < RAND())", "TEST ([cond] > 2) AND ([cond2] = '3') AND (cond3 < RAND())",
]), ]),
$conn->translate('TEST %and', ['[cond] > 2', '[cond2] = "3"', 'cond3 < RAND()']) $conn->translate('TEST %and', ['[cond] > 2', '[cond2] = "3"', 'cond3 < RAND()']),
); );
@@ -126,7 +128,7 @@ $where[] = '[age] > 20';
$where[] = '[email] IS NOT NULL'; $where[] = '[email] IS NOT NULL';
Assert::same( Assert::same(
reformat('SELECT * FROM [table] WHERE ([age] > 20) AND ([email] IS NOT NULL)'), reformat('SELECT * FROM [table] WHERE ([age] > 20) AND ([email] IS NOT NULL)'),
$conn->translate('SELECT * FROM [table] WHERE %and', $where) $conn->translate('SELECT * FROM [table] WHERE %and', $where),
); );
@@ -139,14 +141,14 @@ Assert::same(
'sqlsrv' => "SELECT * FROM [table] WHERE ([age] IS NULL) AND ([email] = N'ahoj') AND ([id] IN (10, 20, 30))", 'sqlsrv' => "SELECT * FROM [table] WHERE ([age] IS NULL) AND ([email] = N'ahoj') AND ([id] IN (10, 20, 30))",
"SELECT * FROM [table] WHERE ([age] IS NULL) AND ([email] = 'ahoj') AND ([id] IN (10, 20, 30))", "SELECT * FROM [table] WHERE ([age] IS NULL) AND ([email] = 'ahoj') AND ([id] IN (10, 20, 30))",
]), ]),
$conn->translate('SELECT * FROM [table] WHERE %and', $where) $conn->translate('SELECT * FROM [table] WHERE %and', $where),
); );
$where = []; $where = [];
Assert::same( Assert::same(
reformat('SELECT * FROM [table] WHERE 1=1'), reformat('SELECT * FROM [table] WHERE 1=1'),
$conn->translate('SELECT * FROM [table] WHERE %and', $where) $conn->translate('SELECT * FROM [table] WHERE %and', $where),
); );
@@ -161,7 +163,7 @@ $order = [
]; ];
Assert::same( Assert::same(
reformat('SELECT * FROM [people] ORDER BY [field1] ASC, [field2] DESC, [field3] ASC, [field4] DESC, [field5] ASC, [field6] DESC'), reformat('SELECT * FROM [people] ORDER BY [field1] ASC, [field2] DESC, [field3] ASC, [field4] DESC, [field5] ASC, [field6] DESC'),
$conn->translate('SELECT * FROM [people] ORDER BY %by', $order) $conn->translate('SELECT * FROM [people] ORDER BY %by', $order),
); );
@@ -172,13 +174,14 @@ Assert::same(
'sqlsrv' => 'SELECT * FROM [products] OFFSET 0 ROWS FETCH NEXT 2 ROWS ONLY', 'sqlsrv' => 'SELECT * FROM [products] OFFSET 0 ROWS FETCH NEXT 2 ROWS ONLY',
'SELECT * FROM [products] LIMIT 2', 'SELECT * FROM [products] LIMIT 2',
]), ]),
$conn->translate('SELECT * FROM [products] %lmt', 2) $conn->translate('SELECT * FROM [products] %lmt', 2),
); );
if ($config['system'] === 'odbc') { if ($config['system'] === 'odbc') {
Assert::exception(function () use ($conn) { Assert::exception(
$conn->translate('SELECT * FROM [products] %lmt %ofs', 2, 1); fn() => $conn->translate('SELECT * FROM [products] %lmt %ofs', 2, 1),
}, Dibi\Exception::class); Dibi\Exception::class,
);
} else { } else {
// with limit = 2, offset = 1 // with limit = 2, offset = 1
Assert::same( Assert::same(
@@ -186,7 +189,7 @@ if ($config['system'] === 'odbc') {
'sqlsrv' => 'SELECT * FROM [products] OFFSET 1 ROWS FETCH NEXT 2 ROWS ONLY', 'sqlsrv' => 'SELECT * FROM [products] OFFSET 1 ROWS FETCH NEXT 2 ROWS ONLY',
'SELECT * FROM [products] LIMIT 2 OFFSET 1', 'SELECT * FROM [products] LIMIT 2 OFFSET 1',
]), ]),
$conn->translate('SELECT * FROM [products] %lmt %ofs', 2, 1) $conn->translate('SELECT * FROM [products] %lmt %ofs', 2, 1),
); );
// with offset = 50 // with offset = 50
@@ -197,7 +200,7 @@ if ($config['system'] === 'odbc') {
'sqlsrv' => 'SELECT * FROM [products] OFFSET 50 ROWS', 'sqlsrv' => 'SELECT * FROM [products] OFFSET 50 ROWS',
'SELECT * FROM [products] LIMIT -1 OFFSET 50', 'SELECT * FROM [products] LIMIT -1 OFFSET 50',
]), ]),
$conn->translate('SELECT * FROM [products] %ofs', 50) $conn->translate('SELECT * FROM [products] %ofs', 50),
); );
} }
@@ -223,12 +226,14 @@ Assert::same(
'b8%d' => null, 'b8%d' => null,
'b9%t' => null, 'b9%t' => null,
'c1%t' => new DateTime('1212-09-26 16:51:34.0124'), 'c1%t' => new DateTime('1212-09-26 16:51:34.0124'),
]) ]),
); );
Assert::exception(function () use ($conn) { Assert::exception(
$conn->translate('SELECT %s', new DateTime('1212-09-26')); fn() => $conn->translate('SELECT %s', new DateTime('1212-09-26')),
}, Dibi\Exception::class, 'SQL translate error: Invalid combination of type Dibi\DateTime and modifier %s'); Dibi\Exception::class,
'SQL translate error: Invalid combination of type Dibi\DateTime and modifier %s',
);
@@ -247,13 +252,13 @@ if ($config['system'] === 'postgre') {
$conn->query('SET standard_conforming_strings = off'); $conn->query('SET standard_conforming_strings = off');
Assert::same( Assert::same(
"SELECT * FROM products WHERE (title LIKE 'C%' AND title LIKE '%r') OR title LIKE '%a\n\\\\%\\\\_\\\\\\\\''\"%'", "SELECT * FROM products WHERE (title LIKE 'C%' AND title LIKE '%r') OR title LIKE '%a\n\\\\%\\\\_\\\\\\\\''\"%'",
$conn->translate($args[0], $args[1], $args[2], $args[3]) $conn->translate($args[0], $args[1], $args[2], $args[3]),
); );
$conn->query('SET standard_conforming_strings = on'); $conn->query('SET standard_conforming_strings = on');
Assert::same( Assert::same(
"SELECT * FROM products WHERE (title LIKE 'C%' AND title LIKE '%r') OR title LIKE '%a\n\\%\\_\\\\''\"%'", "SELECT * FROM products WHERE (title LIKE 'C%' AND title LIKE '%r') OR title LIKE '%a\n\\%\\_\\\\''\"%'",
$conn->translate($args[0], $args[1], $args[2], $args[3]) $conn->translate($args[0], $args[1], $args[2], $args[3]),
); );
} elseif ($config['driver'] !== 'sqlite') { // sqlite2 } elseif ($config['driver'] !== 'sqlite') { // sqlite2
Assert::same( Assert::same(
@@ -263,49 +268,56 @@ if ($config['system'] === 'postgre') {
'sqlsrv' => "SELECT * FROM products WHERE (title LIKE 'C%' AND title LIKE '%r') OR title LIKE '%a\n[%][_]\\''\"%'", 'sqlsrv' => "SELECT * FROM products WHERE (title LIKE 'C%' AND title LIKE '%r') OR title LIKE '%a\n[%][_]\\''\"%'",
"SELECT * FROM products WHERE (title LIKE 'C%' AND title LIKE '%r') OR title LIKE '%a\\n\\%\\_\\\\\\\\\\'\"%'", "SELECT * FROM products WHERE (title LIKE 'C%' AND title LIKE '%r') OR title LIKE '%a\\n\\%\\_\\\\\\\\\\'\"%'",
]), ]),
$conn->translate($args[0], $args[1], $args[2], $args[3]) $conn->translate($args[0], $args[1], $args[2], $args[3]),
); );
} }
$e = Assert::exception(function () use ($conn) { $e = Assert::exception(
$conn->translate("SELECT '"); fn() => $conn->translate("SELECT '"),
}, Dibi\Exception::class, 'SQL translate error: Alone quote'); Dibi\Exception::class,
'SQL translate error: Alone quote',
);
Assert::same('SELECT **Alone quote**', $e->getSql()); Assert::same('SELECT **Alone quote**', $e->getSql());
Assert::match( Assert::match(
reformat([ pattern: reformat([
'mysql' => "SELECT DISTINCT HIGH_PRIORITY SQL_BUFFER_RESULT 'mysql' => <<<'XX'
CONCAT(last_name, ', ', first_name) AS full_name SELECT DISTINCT HIGH_PRIORITY SQL_BUFFER_RESULT
GROUP BY `user` CONCAT(last_name, ', ', first_name) AS full_name
HAVING MAX(salary) > %i 123 GROUP BY `user`
INTO OUTFILE '/tmp/result\\'.txt' HAVING MAX(salary) > %i 123
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\\\"' INTO OUTFILE '/tmp/result\'.txt'
LINES TERMINATED BY '\\\\n' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'
", LINES TERMINATED BY '\\n'
'sqlsrv' => "SELECT DISTINCT HIGH_PRIORITY SQL_BUFFER_RESULT XX,
CONCAT(last_name, N', ', first_name) AS full_name 'sqlsrv' => <<<'XX'
GROUP BY [user] SELECT DISTINCT HIGH_PRIORITY SQL_BUFFER_RESULT
HAVING MAX(salary) > %i 123 CONCAT(last_name, N', ', first_name) AS full_name
INTO OUTFILE N'/tmp/result''.txt' GROUP BY [user]
FIELDS TERMINATED BY N',' OPTIONALLY ENCLOSED BY N'\"' HAVING MAX(salary) > %i 123
LINES TERMINATED BY N'\\n'", "SELECT DISTINCT HIGH_PRIORITY SQL_BUFFER_RESULT INTO OUTFILE N'/tmp/result''.txt'
CONCAT(last_name, ', ', first_name) AS full_name FIELDS TERMINATED BY N',' OPTIONALLY ENCLOSED BY N'"'
GROUP BY [user] LINES TERMINATED BY N'\n'
HAVING MAX(salary) > %i 123 XX,
INTO OUTFILE '/tmp/result''.txt' <<<'XX'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' SELECT DISTINCT HIGH_PRIORITY SQL_BUFFER_RESULT
LINES TERMINATED BY '\\n' CONCAT(last_name, ', ', first_name) AS full_name
", GROUP BY [user]
HAVING MAX(salary) > %i 123
INTO OUTFILE '/tmp/result''.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
XX,
]), ]),
$conn->translate('%sql', 'SELECT DISTINCT HIGH_PRIORITY SQL_BUFFER_RESULT actual: $conn->translate('%sql', 'SELECT DISTINCT HIGH_PRIORITY SQL_BUFFER_RESULT
CONCAT(last_name, ", ", first_name) AS full_name CONCAT(last_name, ", ", first_name) AS full_name
GROUP BY [user] GROUP BY [user]
HAVING MAX(salary) > %i', 123, " HAVING MAX(salary) > %i', 123, "
INTO OUTFILE '/tmp/result''.txt' INTO OUTFILE '/tmp/result''.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\\n' LINES TERMINATED BY '\\n'
") "),
); );
@@ -330,114 +342,124 @@ $array5 = ['RAND()', '[col1] > [col2]'];
Assert::match( Assert::match(
reformat([ pattern: reformat([
'mysql' => "SELECT * 'mysql' => <<<'XX'
FROM `db`.`table` SELECT *
WHERE (`test`.`a` LIKE '1995-03-01' FROM `db`.`table`
OR `b1` IN ( 1, 2, 3 ) WHERE (`test`.`a` LIKE '1995-03-01'
OR `b2` IN ('1', '2', '3' ) OR `b1` IN ( 1, 2, 3 )
OR `b3` IN ( ) OR `b2` IN ('1', '2', '3' )
OR `b4` IN ( 'one', 'two', 'three' ) OR `b3` IN ( )
OR `b5` IN (`col1` AS `one`, `col2` AS `two`, `col3` AS `thr.ee` ) OR `b4` IN ( 'one', 'two', 'three' )
OR `b6` IN ('one', 'two', 'thr.ee') OR `b5` IN (`col1` AS `one`, `col2` AS `two`, `col3` AS `thr.ee` )
OR `b7` IN (NULL) OR `b6` IN ('one', 'two', 'thr.ee')
OR `b8` IN (RAND() `col1` > `col2` ) OR `b7` IN (NULL)
OR `b9` IN (RAND(), [col1] > [col2] ) OR `b8` IN (RAND() `col1` > `col2` )
OR `b10` IN ( ) OR `b9` IN (RAND(), [col1] > [col2] )
AND `c` = 'embedded \\' string' OR `b10` IN ( )
OR `d`=10 AND `c` = 'embedded \' string'
OR `e`=NULL OR `d`=10
OR `true`= 1 OR `e`=NULL
OR `false`= 0 OR `true`= 1
OR `str_null`=NULL OR `false`= 0
OR `str_not_null`='hello' OR `str_null`=NULL
LIMIT 10", OR `str_not_null`='hello'
'sqlsrv' => "SELECT * LIMIT 10
FROM [db].[table] XX,
WHERE ([test].[a] LIKE '1995-03-01' 'sqlsrv' => <<<'XX'
OR [b1] IN ( 1, 2, 3 ) SELECT *
OR [b2] IN (N'1', N'2', N'3' ) FROM [db].[table]
OR [b3] IN ( ) WHERE ([test].[a] LIKE '1995-03-01'
OR [b4] IN ( N'one', N'two', N'three' ) OR [b1] IN ( 1, 2, 3 )
OR [b5] IN ([col1] AS [one], [col2] AS [two], [col3] AS [thr.ee] ) OR [b2] IN (N'1', N'2', N'3' )
OR [b6] IN (N'one', N'two', N'thr.ee') OR [b3] IN ( )
OR [b7] IN (NULL) OR [b4] IN ( N'one', N'two', N'three' )
OR [b8] IN (RAND() [col1] > [col2] ) OR [b5] IN ([col1] AS [one], [col2] AS [two], [col3] AS [thr.ee] )
OR [b9] IN (RAND(), [col1] > [col2] ) OR [b6] IN (N'one', N'two', N'thr.ee')
OR [b10] IN ( ) OR [b7] IN (NULL)
AND [c] = N'embedded '' string' OR [b8] IN (RAND() [col1] > [col2] )
OR [d]=10 OR [b9] IN (RAND(), [col1] > [col2] )
OR [e]=NULL OR [b10] IN ( )
OR [true]= 1 AND [c] = N'embedded '' string'
OR [false]= 0 OR [d]=10
OR [str_null]=NULL OR [e]=NULL
OR [str_not_null]=N'hello' OR [true]= 1
LIMIT 10", OR [false]= 0
'postgre' => 'SELECT * OR [str_null]=NULL
FROM "db"."table" OR [str_not_null]=N'hello'
WHERE ("test"."a" LIKE \'1995-03-01\' LIMIT 10
OR "b1" IN ( 1, 2, 3 ) XX,
OR "b2" IN (\'1\', \'2\', \'3\' ) 'postgre' => <<<'XX'
OR "b3" IN ( ) SELECT *
OR "b4" IN ( \'one\', \'two\', \'three\' ) FROM "db"."table"
OR "b5" IN ("col1" AS "one", "col2" AS "two", "col3" AS "thr.ee" ) WHERE ("test"."a" LIKE '1995-03-01'
OR "b6" IN (\'one\', \'two\', \'thr.ee\') OR "b1" IN ( 1, 2, 3 )
OR "b7" IN (NULL) OR "b2" IN ('1', '2', '3' )
OR "b8" IN (RAND() "col1" > "col2" ) OR "b3" IN ( )
OR "b9" IN (RAND(), [col1] > [col2] ) OR "b4" IN ( 'one', 'two', 'three' )
OR "b10" IN ( ) OR "b5" IN ("col1" AS "one", "col2" AS "two", "col3" AS "thr.ee" )
AND "c" = \'embedded \'\' string\' OR "b6" IN ('one', 'two', 'thr.ee')
OR "d"=10 OR "b7" IN (NULL)
OR "e"=NULL OR "b8" IN (RAND() "col1" > "col2" )
OR "true"= TRUE OR "b9" IN (RAND(), [col1] > [col2] )
OR "false"= FALSE OR "b10" IN ( )
OR "str_null"=NULL AND "c" = 'embedded '' string'
OR "str_not_null"=\'hello\' OR "d"=10
LIMIT 10', OR "e"=NULL
'odbc' => "SELECT * OR "true"= TRUE
FROM [db].[table] OR "false"= FALSE
WHERE ([test].[a] LIKE #03/01/1995# OR "str_null"=NULL
OR [b1] IN ( 1, 2, 3 ) OR "str_not_null"='hello'
OR [b2] IN ('1', '2', '3' ) LIMIT 10
OR [b3] IN ( ) XX,
OR [b4] IN ( 'one', 'two', 'three' ) 'odbc' => <<<'XX'
OR [b5] IN ([col1] AS [one], [col2] AS [two], [col3] AS [thr.ee] ) SELECT *
OR [b6] IN ('one', 'two', 'thr.ee') FROM [db].[table]
OR [b7] IN (NULL) WHERE ([test].[a] LIKE #03/01/1995#
OR [b8] IN (RAND() [col1] > [col2] ) OR [b1] IN ( 1, 2, 3 )
OR [b9] IN (RAND(), [col1] > [col2] ) OR [b2] IN ('1', '2', '3' )
OR [b10] IN ( ) OR [b3] IN ( )
AND [c] = 'embedded '' string' OR [b4] IN ( 'one', 'two', 'three' )
OR [d]=10 OR [b5] IN ([col1] AS [one], [col2] AS [two], [col3] AS [thr.ee] )
OR [e]=NULL OR [b6] IN ('one', 'two', 'thr.ee')
OR [true]= 1 OR [b7] IN (NULL)
OR [false]= 0 OR [b8] IN (RAND() [col1] > [col2] )
OR [str_null]=NULL OR [b9] IN (RAND(), [col1] > [col2] )
OR [str_not_null]='hello' OR [b10] IN ( )
LIMIT 10", AND [c] = 'embedded '' string'
"SELECT * OR [d]=10
FROM [db].[table] OR [e]=NULL
WHERE ([test].[a] LIKE '1995-03-01' OR [true]= 1
OR [b1] IN ( 1, 2, 3 ) OR [false]= 0
OR [b2] IN ('1', '2', '3' ) OR [str_null]=NULL
OR [b3] IN ( ) OR [str_not_null]='hello'
OR [b4] IN ( 'one', 'two', 'three' ) LIMIT 10
OR [b5] IN ([col1] AS [one], [col2] AS [two], [col3] AS [thr.ee] ) XX,
OR [b6] IN ('one', 'two', 'thr.ee') <<<'XX'
OR [b7] IN (NULL) SELECT *
OR [b8] IN (RAND() [col1] > [col2] ) FROM [db].[table]
OR [b9] IN (RAND(), [col1] > [col2] ) WHERE ([test].[a] LIKE '1995-03-01'
OR [b10] IN ( ) OR [b1] IN ( 1, 2, 3 )
AND [c] = 'embedded '' string' OR [b2] IN ('1', '2', '3' )
OR [d]=10 OR [b3] IN ( )
OR [e]=NULL OR [b4] IN ( 'one', 'two', 'three' )
OR [true]= 1 OR [b5] IN ([col1] AS [one], [col2] AS [two], [col3] AS [thr.ee] )
OR [false]= 0 OR [b6] IN ('one', 'two', 'thr.ee')
OR [str_null]=NULL OR [b7] IN (NULL)
OR [str_not_null]='hello' OR [b8] IN (RAND() [col1] > [col2] )
LIMIT 10", OR [b9] IN (RAND(), [col1] > [col2] )
OR [b10] IN ( )
AND [c] = 'embedded '' string'
OR [d]=10
OR [e]=NULL
OR [true]= 1
OR [false]= 0
OR [str_null]=NULL
OR [str_not_null]='hello'
LIMIT 10
XX,
]), ]),
$conn->translate('SELECT * actual: $conn->translate('SELECT *
FROM [db.table] FROM [db.table]
WHERE ([test.a] LIKE %d', '1995-03-01', ' WHERE ([test.a] LIKE %d', '1995-03-01', '
OR [b1] IN (', $array1, ') OR [b1] IN (', $array1, ')
@@ -457,7 +479,7 @@ WHERE ([test.a] LIKE %d', '1995-03-01', '
OR [false]=', false, ' OR [false]=', false, '
OR [str_null]=%sn', '', ' OR [str_null]=%sn', '', '
OR [str_not_null]=%sn', 'hello', ' OR [str_not_null]=%sn', 'hello', '
LIMIT 10') LIMIT 10'),
); );
@@ -466,19 +488,19 @@ Assert::same(
'sqlsrv' => "TEST [cond] > 2 [cond2] = N'3' cond3 < RAND() 123", 'sqlsrv' => "TEST [cond] > 2 [cond2] = N'3' cond3 < RAND() 123",
"TEST [cond] > 2 [cond2] = '3' cond3 < RAND() 123", "TEST [cond] > 2 [cond2] = '3' cond3 < RAND() 123",
]), ]),
$conn->translate('TEST %ex', ['[cond] > 2', '[cond2] = "3"', 'cond3 < RAND()'], 123) $conn->translate('TEST %ex', ['[cond] > 2', '[cond2] = "3"', 'cond3 < RAND()'], 123),
); );
Assert::same( Assert::same(
reformat('TEST ([cond] > 2) OR ([cond2] > 3) OR ([cond3] = 10 + 1)'), reformat('TEST ([cond] > 2) OR ([cond2] > 3) OR ([cond3] = 10 + 1)'),
$conn->translate('TEST %or', ['`cond` > 2', ['[cond2] > %i', '3'], 'cond3%sql' => ['10 + 1']]) $conn->translate('TEST %or', ['`cond` > 2', ['[cond2] > %i', '3'], 'cond3%sql' => ['10 + 1']]),
); );
Assert::same( Assert::same(
reformat('TEST ([cond] = 2) OR ([cond3] = RAND())'), reformat('TEST ([cond] = 2) OR ([cond3] = RAND())'),
$conn->translate('TEST %or', ['cond' => 2, 'cond3%sql' => 'RAND()']) $conn->translate('TEST %or', ['cond' => 2, 'cond3%sql' => 'RAND()']),
); );
@@ -487,7 +509,7 @@ Assert::same(
'sqlsrv' => "TEST ([cond1] 3) OR ([cond2] RAND()) OR ([cond3] LIKE N'string')", 'sqlsrv' => "TEST ([cond1] 3) OR ([cond2] RAND()) OR ([cond3] LIKE N'string')",
"TEST ([cond1] 3) OR ([cond2] RAND()) OR ([cond3] LIKE 'string')", "TEST ([cond1] 3) OR ([cond2] RAND()) OR ([cond3] LIKE 'string')",
]), ]),
$conn->translate('TEST %or', ['cond1%ex' => 3, 'cond2%ex' => 'RAND()', 'cond3%ex' => ['LIKE %s', 'string']]) $conn->translate('TEST %or', ['cond1%ex' => 3, 'cond2%ex' => 'RAND()', 'cond3%ex' => ['LIKE %s', 'string']]),
); );
@@ -497,7 +519,7 @@ Assert::same(
'sqlsrv' => 'SELECT * FROM [test] WHERE [id] LIKE N\'%d%t\' OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY', 'sqlsrv' => 'SELECT * FROM [test] WHERE [id] LIKE N\'%d%t\' OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY',
'SELECT * FROM [test] WHERE [id] LIKE \'%d%t\' LIMIT 10', 'SELECT * FROM [test] WHERE [id] LIKE \'%d%t\' LIMIT 10',
]), ]),
$conn->translate("SELECT * FROM [test] WHERE %n LIKE '%d%t' %lmt", 'id', 10) $conn->translate("SELECT * FROM [test] WHERE %n LIKE '%d%t' %lmt", 'id', 10),
); );
@@ -506,13 +528,13 @@ $where = [
]; ];
Assert::same( Assert::same(
reformat('SELECT * FROM [tablename] WHERE ([tablename].[column] = 1)'), reformat('SELECT * FROM [tablename] WHERE ([tablename].[column] = 1)'),
$conn->translate('SELECT * FROM [tablename] WHERE %and', $where) $conn->translate('SELECT * FROM [tablename] WHERE %and', $where),
); );
Assert::same( Assert::same(
reformat('SELECT FROM ...'), reformat('SELECT FROM ...'),
$conn->translate('SELECT FROM ... %lmt', null) $conn->translate('SELECT FROM ... %lmt', null),
); );
Assert::same( Assert::same(
@@ -520,7 +542,7 @@ Assert::same(
'sqlsrv' => "SELECT N'%i'", 'sqlsrv' => "SELECT N'%i'",
"SELECT '%i'", "SELECT '%i'",
]), ]),
$conn->translate("SELECT '%i'") $conn->translate("SELECT '%i'"),
); );
Assert::same( Assert::same(
@@ -528,7 +550,7 @@ Assert::same(
'sqlsrv' => "SELECT N'%i'", 'sqlsrv' => "SELECT N'%i'",
"SELECT '%i'", "SELECT '%i'",
]), ]),
$conn->translate('SELECT "%i"') $conn->translate('SELECT "%i"'),
); );
@@ -543,7 +565,7 @@ Assert::same(
], [ ], [
'product_id' => 1, 'product_id' => 1,
'title' => new Dibi\Expression('SHA1(%s)', 'Test product'), 'title' => new Dibi\Expression('SHA1(%s)', 'Test product'),
]) ]),
); );
Assert::same( Assert::same(
@@ -554,7 +576,7 @@ Assert::same(
$conn->translate('UPDATE [products]', [ $conn->translate('UPDATE [products]', [
'product_id' => 1, 'product_id' => 1,
'title' => new Dibi\Expression('SHA1(%s)', 'Test product'), 'title' => new Dibi\Expression('SHA1(%s)', 'Test product'),
]) ]),
); );
Assert::same( Assert::same(
@@ -565,7 +587,7 @@ Assert::same(
$conn->translate('UPDATE [products]', [ $conn->translate('UPDATE [products]', [
'product_id' => 1, 'product_id' => 1,
'title' => new Dibi\Expression('SHA1(%s)', 'Test product'), 'title' => new Dibi\Expression('SHA1(%s)', 'Test product'),
]) ]),
); );
Assert::same( Assert::same(
@@ -576,7 +598,7 @@ Assert::same(
$conn->translate('SELECT * FROM [products] WHERE', [ $conn->translate('SELECT * FROM [products] WHERE', [
'product_id' => 1, 'product_id' => 1,
'title' => new Dibi\Expression('SHA1(%s)', 'Test product'), 'title' => new Dibi\Expression('SHA1(%s)', 'Test product'),
]) ]),
); );
@@ -588,7 +610,7 @@ Assert::same(
'top' => 2, 'top' => 2,
]), ]),
new Dibi\Expression('number < %i', 100), new Dibi\Expression('number < %i', 100),
]) ]),
); );
@@ -613,7 +635,7 @@ Assert::same(
'sqlsrv' => "INSERT INTO test ([id], [text], [num]) VALUES (1, N'ahoj', 1), (2, N'jak', -1), (3, N'se', 10), (4, SUM(5), 1)", 'sqlsrv' => "INSERT INTO test ([id], [text], [num]) VALUES (1, N'ahoj', 1), (2, N'jak', -1), (3, N'se', 10), (4, SUM(5), 1)",
"INSERT INTO test ([id], [text], [num]) VALUES (1, 'ahoj', 1), (2, 'jak', -1), (3, 'se', 10), (4, SUM(5), 1)", "INSERT INTO test ([id], [text], [num]) VALUES (1, 'ahoj', 1), (2, 'jak', -1), (3, 'se', 10), (4, SUM(5), 1)",
]), ]),
$conn->translate('INSERT INTO test %m', $array6) $conn->translate('INSERT INTO test %m', $array6),
); );
@@ -624,42 +646,46 @@ $by = [
Assert::same( Assert::same(
reformat('SELECT * FROM table ORDER BY funkce(nazev_pole) ASC, [jine_pole] DESC'), reformat('SELECT * FROM table ORDER BY funkce(nazev_pole) ASC, [jine_pole] DESC'),
$conn->translate('SELECT * FROM table ORDER BY %by', $by) $conn->translate('SELECT * FROM table ORDER BY %by', $by),
); );
Assert::same( Assert::same(
reformat('INSERT INTO [test].*'), reformat('INSERT INTO [test].*'),
$conn->translate('INSERT INTO [test.*]') $conn->translate('INSERT INTO [test.*]'),
); );
Assert::exception(function () use ($conn) { Assert::exception(
$conn->translate('INSERT INTO %i', 'ahoj'); fn() => $conn->translate('INSERT INTO %i', 'ahoj'),
}, Dibi\Exception::class, "Expected number, 'ahoj' given."); Dibi\Exception::class,
"Expected number, 'ahoj' given.",
);
Assert::exception(function () use ($conn) { Assert::exception(
$conn->translate('INSERT INTO %f', 'ahoj'); fn() => $conn->translate('INSERT INTO %f', 'ahoj'),
}, Dibi\Exception::class, "Expected number, 'ahoj' given."); Dibi\Exception::class,
"Expected number, 'ahoj' given.",
);
Assert::same( Assert::same(
reformat('SELECT * FROM table'), reformat('SELECT * FROM table'),
$conn->translate('SELECT', new Dibi\Literal('* FROM table')) $conn->translate('SELECT', new Dibi\Literal('* FROM table')),
); );
Assert::same( Assert::same(
reformat('SELECT * FROM table'), reformat('SELECT * FROM table'),
$conn->translate('SELECT %SQL', new Dibi\Literal('* FROM table')) $conn->translate('SELECT %SQL', new Dibi\Literal('* FROM table')),
); );
Assert::same( Assert::same(
reformat('SELECT * FROM table'), reformat('SELECT * FROM table'),
$conn->translate(new Dibi\Literal('SELECT * FROM table')) $conn->translate(new Dibi\Literal('SELECT * FROM table')),
); );
Assert::same( Assert::same(
reformat('SELECT [a].[b] AS [c.d]'), reformat('SELECT [a].[b] AS [c.d]'),
$conn->translate('SELECT %n AS %N', 'a.b', 'c.d') $conn->translate('SELECT %n AS %N', 'a.b', 'c.d'),
); );
@@ -677,5 +703,5 @@ Assert::same(
'spec2%f' => 1000.00, 'spec2%f' => 1000.00,
'spec3%i' => 10000, 'spec3%i' => 10000,
'spec4' => 10000, 'spec4' => 10000,
], 'WHERE [price]=%f', 123.5) ], 'WHERE [price]=%f', 123.5),
); );

View File

@@ -15,41 +15,54 @@ $conn = new Dibi\Connection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql"); $conn->loadFile(__DIR__ . "/data/$config[system].sql");
$e = Assert::exception(function () use ($conn) { $e = Assert::exception(
new Dibi\Connection([ fn() => new Dibi\Connection([
'driver' => 'mysqli', 'driver' => 'mysqli',
'host' => 'localhost', 'host' => 'localhost',
'username' => 'unknown', 'username' => 'unknown',
'password' => 'unknown', 'password' => 'unknown',
]); ]),
}, Dibi\DriverException::class); Dibi\DriverException::class,
);
Assert::null($e->getSql()); Assert::null($e->getSql());
$e = Assert::exception(function () use ($conn) { $e = Assert::exception(
$conn->query('SELECT'); fn() => $conn->query('SELECT'),
}, Dibi\DriverException::class, '%a% error in your SQL syntax;%a%', 1064); Dibi\DriverException::class,
'%a% error in your SQL syntax;%a%',
1064,
);
Assert::same('SELECT', $e->getSql()); Assert::same('SELECT', $e->getSql());
$e = Assert::exception(function () use ($conn) { $e = Assert::exception(
$conn->query('INSERT INTO products (product_id, title) VALUES (1, "New")'); fn() => $conn->query('INSERT INTO products (product_id, title) VALUES (1, "New")'),
}, Dibi\UniqueConstraintViolationException::class, "%a?%Duplicate entry '1' for key '%a?%PRIMARY'", 1062); Dibi\UniqueConstraintViolationException::class,
"%a?%Duplicate entry '1' for key '%a?%PRIMARY'",
1062,
);
Assert::same("INSERT INTO products (product_id, title) VALUES (1, 'New')", $e->getSql()); Assert::same("INSERT INTO products (product_id, title) VALUES (1, 'New')", $e->getSql());
$e = Assert::exception(function () use ($conn) { $e = Assert::exception(
$conn->query('INSERT INTO products (title) VALUES (NULL)'); fn() => $conn->query('INSERT INTO products (title) VALUES (NULL)'),
}, Dibi\NotNullConstraintViolationException::class, "%a?%Column 'title' cannot be null", 1048); Dibi\NotNullConstraintViolationException::class,
"%a?%Column 'title' cannot be null",
1048,
);
Assert::same('INSERT INTO products (title) VALUES (NULL)', $e->getSql()); Assert::same('INSERT INTO products (title) VALUES (NULL)', $e->getSql());
$e = Assert::exception(function () use ($conn) { $e = Assert::exception(
$conn->query('INSERT INTO orders (customer_id, product_id, amount) VALUES (100, 1, 1)'); fn() => $conn->query('INSERT INTO orders (customer_id, product_id, amount) VALUES (100, 1, 1)'),
}, Dibi\ForeignKeyConstraintViolationException::class, '%a% a foreign key constraint fails %a%', 1452); Dibi\ForeignKeyConstraintViolationException::class,
'%a% a foreign key constraint fails %a%',
1452,
);
Assert::same('INSERT INTO orders (customer_id, product_id, amount) VALUES (100, 1, 1)', $e->getSql()); Assert::same('INSERT INTO orders (customer_id, product_id, amount) VALUES (100, 1, 1)', $e->getSql());

View File

@@ -15,29 +15,40 @@ $conn = new Dibi\Connection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql"); $conn->loadFile(__DIR__ . "/data/$config[system].sql");
$e = Assert::exception(function () use ($conn) { $e = Assert::exception(
$conn->query('SELECT INTO'); fn() => $conn->query('SELECT INTO'),
}, Dibi\DriverException::class, '%a?%syntax error %A%'); Dibi\DriverException::class,
'%a?%syntax error %A%',
);
Assert::same('SELECT INTO', $e->getSql()); Assert::same('SELECT INTO', $e->getSql());
$e = Assert::exception(function () use ($conn) { $e = Assert::exception(
$conn->query('INSERT INTO products (product_id, title) VALUES (1, "New")'); fn() => $conn->query('INSERT INTO products (product_id, title) VALUES (1, "New")'),
}, Dibi\UniqueConstraintViolationException::class, '%a% violates unique constraint %A%', '23505'); Dibi\UniqueConstraintViolationException::class,
'%a% violates unique constraint %A%',
'23505',
);
Assert::same("INSERT INTO products (product_id, title) VALUES (1, 'New')", $e->getSql()); Assert::same("INSERT INTO products (product_id, title) VALUES (1, 'New')", $e->getSql());
$e = Assert::exception(function () use ($conn) { $e = Assert::exception(
$conn->query('INSERT INTO products (title) VALUES (NULL)'); fn() => $conn->query('INSERT INTO products (title) VALUES (NULL)'),
}, Dibi\NotNullConstraintViolationException::class, '%a?%null value in column "title"%a%violates not-null constraint%A?%', '23502'); Dibi\NotNullConstraintViolationException::class,
'%a?%null value in column "title"%a%violates not-null constraint%A?%',
'23502',
);
Assert::same('INSERT INTO products (title) VALUES (NULL)', $e->getSql()); Assert::same('INSERT INTO products (title) VALUES (NULL)', $e->getSql());
$e = Assert::exception(function () use ($conn) { $e = Assert::exception(
$conn->query('INSERT INTO orders (customer_id, product_id, amount) VALUES (100, 1, 1)'); fn() => $conn->query('INSERT INTO orders (customer_id, product_id, amount) VALUES (100, 1, 1)'),
}, Dibi\ForeignKeyConstraintViolationException::class, '%a% violates foreign key constraint %A%', '23503'); Dibi\ForeignKeyConstraintViolationException::class,
'%a% violates foreign key constraint %A%',
'23503',
);
Assert::same('INSERT INTO orders (customer_id, product_id, amount) VALUES (100, 1, 1)', $e->getSql()); Assert::same('INSERT INTO orders (customer_id, product_id, amount) VALUES (100, 1, 1)', $e->getSql());

View File

@@ -15,23 +15,32 @@ $conn = new Dibi\Connection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql"); $conn->loadFile(__DIR__ . "/data/$config[system].sql");
$e = Assert::exception(function () use ($conn) { $e = Assert::exception(
$conn->query('SELECT'); fn() => $conn->query('SELECT'),
}, Dibi\DriverException::class, '%a%', 1); Dibi\DriverException::class,
'%a%',
1,
);
Assert::same('SELECT', $e->getSql()); Assert::same('SELECT', $e->getSql());
$e = Assert::exception(function () use ($conn) { $e = Assert::exception(
$conn->query('INSERT INTO products (product_id, title) VALUES (1, "New")'); fn() => $conn->query('INSERT INTO products (product_id, title) VALUES (1, "New")'),
}, Dibi\UniqueConstraintViolationException::class, null, 19); Dibi\UniqueConstraintViolationException::class,
null,
19,
);
Assert::same("INSERT INTO products (product_id, title) VALUES (1, 'New')", $e->getSql()); Assert::same("INSERT INTO products (product_id, title) VALUES (1, 'New')", $e->getSql());
$e = Assert::exception(function () use ($conn) { $e = Assert::exception(
$conn->query('INSERT INTO products (title) VALUES (NULL)'); fn() => $conn->query('INSERT INTO products (title) VALUES (NULL)'),
}, Dibi\NotNullConstraintViolationException::class, null, 19); Dibi\NotNullConstraintViolationException::class,
null,
19,
);
Assert::same('INSERT INTO products (title) VALUES (NULL)', $e->getSql()); Assert::same('INSERT INTO products (title) VALUES (NULL)', $e->getSql());