1
0
mirror of https://github.com/dg/dibi.git synced 2025-09-01 10:02:53 +02:00

Compare commits

..

1 Commits
v4.2.2 ... v4.1

Author SHA1 Message Date
David Grudl
49f2bf867f SqlsrvDriver: workaround for "Driver's SQLSetConnectAttr failed on ODBC <=13" bug 2021-03-10 16:42:45 +01:00
16 changed files with 80 additions and 241 deletions

View File

@@ -1,5 +1,6 @@
language: php
php:
- 7.1
- 7.2
- 7.3
- 7.4

View File

@@ -15,17 +15,17 @@ init:
- SET ANSICON=121x90 (121x90)
install:
# Install PHP 7.2
# Install PHP 7.1
- IF EXIST c:\php7 (SET PHP=0) ELSE (SET PHP=1)
- IF %PHP%==1 mkdir c:\php7
- IF %PHP%==1 cd c:\php7
- IF %PHP%==1 curl https://windows.php.net/downloads/releases/archives/php-7.2.18-Win32-VC15-x64.zip --output php.zip
- IF %PHP%==1 curl https://windows.php.net/downloads/releases/archives/php-7.1.5-Win32-VC14-x64.zip --output php.zip
- IF %PHP%==1 7z x php.zip >nul
- IF %PHP%==1 echo extension_dir=ext >> php.ini
- IF %PHP%==1 echo extension=php_openssl.dll >> php.ini
- IF %PHP%==1 curl https://github.com/microsoft/msphpsql/releases/download/v5.8.0/Windows-7.2.zip -L --output sqlsrv.zip
- IF %PHP%==1 7z x sqlsrv.zip >nul
- IF %PHP%==1 copy Windows-7.2\x64\php_sqlsrv_72_ts.dll ext\php_sqlsrv_ts.dll
- IF %PHP%==1 appveyor DownloadFile https://files.nette.org/misc/php-sqlsrv.zip
- IF %PHP%==1 7z x php-sqlsrv.zip >nul
- IF %PHP%==1 copy SQLSRV\php_sqlsrv_71_ts.dll ext\php_sqlsrv_71_ts.dll
- IF %PHP%==1 del /Q *.zip
# Install Microsoft Access Database Engine x64

View File

@@ -11,7 +11,7 @@
}
],
"require": {
"php": ">=7.2"
"php": ">=7.1"
},
"require-dev": {
"tracy/tracy": "~2.2",
@@ -31,7 +31,7 @@
},
"extra": {
"branch-alias": {
"dev-master": "4.2-dev"
"dev-master": "4.1-dev"
}
}
}

View File

@@ -15,14 +15,12 @@ Database access functions in PHP are not standardised. This library
hides the differences between them, and above all, it gives you a very handy interface.
Support Me
----------
Support Project
---------------
Do you like Dibi? Are you looking forward to the new features?
[![Buy me a coffee](https://files.nette.org/icons/donation-3.svg)](https://github.com/sponsors/dg)
Thank you!
[![Donate](https://files.nette.org/icons/donation-1.svg?)](https://nette.org/make-donation?to=dibi)
Installation
@@ -34,7 +32,7 @@ Install Dibi via Composer:
composer require dibi/dibi
```
The Dibi 4.2 requires PHP version 7.2 and supports PHP up to 8.0.
The Dibi 4.1 requires PHP version 7.1 and supports PHP up to 8.0.
Usage

View File

@@ -28,9 +28,6 @@ class Connection implements IConnection
/** @var array Current connection configuration */
private $config;
/** @var string[] resultset formats */
private $formats;
/** @var Driver|null */
private $driver;
@@ -40,26 +37,17 @@ class Connection implements IConnection
/** @var HashMap Substitutes for identifiers */
private $substitutes;
private $transactionDepth = 0;
/**
* Connection options: (see driver-specific options too)
* - lazy (bool) => if true, connection will be established only when required
* - result (array) => result set options
* - normalize => normalizes result fields (default: true)
* - formatDateTime => date-time format
* empty for decoding as Dibi\DateTime (default)
* "..." formatted according to given format, see https://www.php.net/manual/en/datetime.format.php
* "native" for leaving value as is
* - formatTimeInterval => time-interval format
* empty for decoding as DateInterval (default)
* "..." formatted according to given format, see https://www.php.net/manual/en/dateinterval.format.php
* "native" for leaving value as is
* - formatJson => json format
* "array" for decoding json as an array (default)
* "object" for decoding json as \stdClass
* "native" for leaving value as is
* - formatDateTime => date-time format (if empty, DateTime objects will be returned)
* - formatJson => json format (
* "string" for leaving value as is,
* "object" for decoding json as \stdClass,
* "array" for decoding json as an array - default
* )
* - profiler (array)
* - run (bool) => enable profiler?
* - file => file to log
@@ -77,15 +65,9 @@ class Connection implements IConnection
Helpers::alias($config, 'result|formatDateTime', 'resultDateTime');
$config['driver'] = $config['driver'] ?? 'mysqli';
$config['name'] = $name;
$config['result']['formatJson'] = $config['result']['formatJson'] ?? 'array';
$this->config = $config;
$this->formats = [
Type::DATE => $this->config['result']['formatDate'],
Type::DATETIME => $this->config['result']['formatDateTime'],
Type::JSON => $this->config['result']['formatJson'] ?? 'array',
Type::TIME_INTERVAL => $this->config['result']['formatTimeInterval'] ?? null,
];
// profiler
if (isset($config['profiler']['file']) && (!isset($config['profiler']['run']) || $config['profiler']['run'])) {
$filter = $config['profiler']['filter'] ?? Event::QUERY;
@@ -218,7 +200,7 @@ class Connection implements IConnection
*/
final public function query(...$args): Result
{
return $this->nativeQuery($this->translate(...$args));
return $this->nativeQuery($this->translateArgs($args));
}
@@ -229,10 +211,7 @@ class Connection implements IConnection
*/
final public function translate(...$args): string
{
if (!$this->driver) {
$this->connect();
}
return (clone $this->translator)->translate($args);
return $this->translateArgs($args);
}
@@ -243,7 +222,7 @@ class Connection implements IConnection
final public function test(...$args): bool
{
try {
Helpers::dump($this->translate(...$args));
Helpers::dump($this->translateArgs($args));
return true;
} catch (Exception $e) {
@@ -264,7 +243,19 @@ class Connection implements IConnection
*/
final public function dataSource(...$args): DataSource
{
return new DataSource($this->translate(...$args), $this);
return new DataSource($this->translateArgs($args), $this);
}
/**
* Generates SQL query.
*/
protected function translateArgs(array $args): string
{
if (!$this->driver) {
$this->connect();
}
return (clone $this->translator)->translate($args);
}
@@ -337,10 +328,6 @@ class Connection implements IConnection
*/
public function begin(string $savepoint = null): void
{
if ($this->transactionDepth !== 0) {
throw new \LogicException(__METHOD__ . '() call is forbidden inside a transaction() callback');
}
if (!$this->driver) {
$this->connect();
}
@@ -365,10 +352,6 @@ class Connection implements IConnection
*/
public function commit(string $savepoint = null): void
{
if ($this->transactionDepth !== 0) {
throw new \LogicException(__METHOD__ . '() call is forbidden inside a transaction() callback');
}
if (!$this->driver) {
$this->connect();
}
@@ -393,10 +376,6 @@ class Connection implements IConnection
*/
public function rollback(string $savepoint = null): void
{
if ($this->transactionDepth !== 0) {
throw new \LogicException(__METHOD__ . '() call is forbidden inside a transaction() callback');
}
if (!$this->driver) {
$this->connect();
}
@@ -416,42 +395,15 @@ class Connection implements IConnection
}
/**
* @return mixed
*/
public function transaction(callable $callback)
{
if ($this->transactionDepth === 0) {
$this->begin();
}
$this->transactionDepth++;
try {
$res = $callback($this);
} catch (\Throwable $e) {
$this->transactionDepth--;
if ($this->transactionDepth === 0) {
$this->rollback();
}
throw $e;
}
$this->transactionDepth--;
if ($this->transactionDepth === 0) {
$this->commit();
}
return $res;
}
/**
* Result set factory.
*/
public function createResultSet(ResultDriver $resultDriver): Result
{
return (new Result($resultDriver, $this->config['result']['normalize'] ?? true))
->setFormats($this->formats);
$res = new Result($resultDriver);
return $res->setFormat(Type::DATE, $this->config['result']['formatDate'])
->setFormat(Type::DATETIME, $this->config['result']['formatDateTime'])
->setFormat(Type::JSON, $this->config['result']['formatJson']);
}

View File

@@ -188,7 +188,7 @@ class PostgreDriver implements Dibi\Driver
*/
public function begin(string $savepoint = null): void
{
$this->query($savepoint ? "SAVEPOINT {$this->escapeIdentifier($savepoint)}" : 'START TRANSACTION');
$this->query($savepoint ? "SAVEPOINT $savepoint" : 'START TRANSACTION');
}
@@ -198,7 +198,7 @@ class PostgreDriver implements Dibi\Driver
*/
public function commit(string $savepoint = null): void
{
$this->query($savepoint ? "RELEASE SAVEPOINT {$this->escapeIdentifier($savepoint)}" : 'COMMIT');
$this->query($savepoint ? "RELEASE SAVEPOINT $savepoint" : 'COMMIT');
}
@@ -208,7 +208,7 @@ class PostgreDriver implements Dibi\Driver
*/
public function rollback(string $savepoint = null): void
{
$this->query($savepoint ? "ROLLBACK TO SAVEPOINT {$this->escapeIdentifier($savepoint)}" : 'ROLLBACK');
$this->query($savepoint ? "ROLLBACK TO SAVEPOINT $savepoint" : 'ROLLBACK');
}

View File

@@ -28,6 +28,9 @@ class PostgreReflector implements Dibi\Reflector
public function __construct(Dibi\Driver $driver, string $version)
{
if ($version < 7.4) {
throw new Dibi\DriverException('Reflection requires PostgreSQL 7.4 and newer.');
}
$this->driver = $driver;
$this->version = $version;
}

View File

@@ -41,12 +41,10 @@ class Result implements IDataSource
private $formats = [];
public function __construct(ResultDriver $driver, bool $normalize = true)
public function __construct(ResultDriver $driver)
{
$this->driver = $driver;
if ($normalize) {
$this->detectTypes();
}
$this->detectTypes();
}
@@ -456,12 +454,8 @@ class Result implements IDataSource
continue;
}
$value = $row[$key];
$format = $this->formats[$type] ?? null;
if ($type === null || $format === 'native') {
$row[$key] = $value;
} elseif ($type === Type::TEXT) {
if ($type === Type::TEXT) {
$row[$key] = (string) $value;
} elseif ($type === Type::INTEGER) {
@@ -491,16 +485,17 @@ class Result implements IDataSource
} elseif ($type === Type::DATETIME || $type === Type::DATE || $type === Type::TIME) {
if ($value && substr((string) $value, 0, 3) !== '000') { // '', null, false, '0000-00-00', ...
$value = new DateTime($value);
$row[$key] = $format ? $value->format($format) : $value;
$row[$key] = empty($this->formats[$type])
? $value
: $value->format($this->formats[$type]);
} else {
$row[$key] = null;
}
} elseif ($type === Type::TIME_INTERVAL) {
preg_match('#^(-?)(\d+)\D(\d+)\D(\d+)\z#', $value, $m);
$value = new \DateInterval("PT$m[2]H$m[3]M$m[4]S");
$value->invert = (int) (bool) $m[1];
$row[$key] = $format ? $value->format($format) : $value;
$row[$key] = new \DateInterval("PT$m[2]H$m[3]M$m[4]S");
$row[$key]->invert = (int) (bool) $m[1];
} elseif ($type === Type::BINARY) {
$row[$key] = is_string($value)
@@ -508,12 +503,15 @@ class Result implements IDataSource
: $value;
} elseif ($type === Type::JSON) {
if ($format === 'string') { // back compatibility with 'native'
if ($this->formats[$type] === 'string') {
$row[$key] = $value;
} else {
$row[$key] = json_decode($value, $format === 'array');
$row[$key] = json_decode($value, $this->formats[$type] === 'array');
}
} elseif ($type === null) {
$row[$key] = $value;
} else {
throw new \RuntimeException('Unexpected type ' . $type);
}
@@ -551,7 +549,7 @@ class Result implements IDataSource
/**
* Sets type format.
* Sets date format.
*/
final public function setFormat(string $type, ?string $format): self
{
@@ -560,16 +558,6 @@ class Result implements IDataSource
}
/**
* Sets type formats.
*/
final public function setFormats(array $formats): self
{
$this->formats = $formats;
return $this;
}
/**
* Returns data format.
*/

View File

@@ -53,12 +53,6 @@ class Row implements \ArrayAccess, \IteratorAggregate, \Countable
}
public function __isset(string $key): bool
{
return false;
}
/********************* interfaces ArrayAccess, Countable & IteratorAggregate ****************d*g**/

View File

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

View File

@@ -25,7 +25,6 @@ declare(strict_types=1);
* @method static void begin(string $savepoint = null)
* @method static void commit(string $savepoint = null)
* @method static void rollback(string $savepoint = null)
* @method static mixed transaction(callable $callback)
* @method static Dibi\Reflection\Database getDatabaseInfo()
* @method static Dibi\Fluent command()
* @method static Dibi\Fluent select(...$args)
@@ -45,7 +44,7 @@ class dibi
/** version */
public const
VERSION = '4.2.2';
VERSION = '4.1.3';
/** sorting order */
public const

View File

@@ -30,102 +30,21 @@ Assert::exception(function () use ($conn) {
*/
test('begin() & rollback()', function () use ($conn) {
$conn->begin();
Assert::same(3, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());
$conn->query('INSERT INTO [products]', [
'title' => 'Test product',
]);
Assert::same(4, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());
$conn->rollback();
Assert::same(3, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());
});
$conn->begin();
Assert::same(3, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());
$conn->query('INSERT INTO [products]', [
'title' => 'Test product',
]);
Assert::same(4, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());
$conn->rollback();
Assert::same(3, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());
test('begin() & commit()', function () use ($conn) {
$conn->begin();
$conn->query('INSERT INTO [products]', [
'title' => 'Test product',
]);
$conn->commit();
Assert::same(4, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());
});
test('transaction() fail', function () use ($conn) {
Assert::exception(function () use ($conn) {
$conn->transaction(function (Dibi\Connection $connection) {
$connection->query('INSERT INTO [products]', [
'title' => 'Test product',
]);
throw new Exception('my exception');
});
}, \Throwable::class, 'my exception');
Assert::same(4, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());
});
test('transaction() success', function () use ($conn) {
$conn->transaction(function (Dibi\Connection $connection) {
$connection->query('INSERT INTO [products]', [
'title' => 'Test product',
]);
});
Assert::same(5, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());
});
test('nested transaction() call fail', function () use ($conn) {
Assert::exception(function () use ($conn) {
$conn->transaction(function (Dibi\Connection $connection) {
$connection->query('INSERT INTO [products]', [
'title' => 'Test product',
]);
$connection->transaction(function (Dibi\Connection $connection2) {
$connection2->query('INSERT INTO [products]', [
'title' => 'Test product',
]);
throw new Exception('my exception');
});
});
}, \Throwable::class, 'my exception');
Assert::same(5, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());
});
test('nested transaction() call success', function () use ($conn) {
$conn->transaction(function (Dibi\Connection $connection) {
$connection->query('INSERT INTO [products]', [
'title' => 'Test product',
]);
$connection->transaction(function (Dibi\Connection $connection2) {
$connection2->query('INSERT INTO [products]', [
'title' => 'Test product',
]);
});
});
Assert::same(7, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());
});
test('begin(), commit() & rollback() calls are forbidden in transaction()', function () use ($conn) {
Assert::exception(function () use ($conn) {
$conn->transaction(function (Dibi\Connection $connection) {
$connection->begin();
});
}, \LogicException::class, Dibi\Connection::class . '::begin() call is forbidden inside a transaction() callback');
Assert::exception(function () use ($conn) {
$conn->transaction(function (Dibi\Connection $connection) {
$connection->commit();
});
}, \LogicException::class, Dibi\Connection::class . '::commit() call is forbidden inside a transaction() callback');
Assert::exception(function () use ($conn) {
$conn->transaction(function (Dibi\Connection $connection) {
$connection->rollback();
});
}, \LogicException::class, Dibi\Connection::class . '::rollback() call is forbidden inside a transaction() callback');
});
$conn->begin();
$conn->query('INSERT INTO [products]', [
'title' => 'Test product',
]);
$conn->commit();
Assert::same(4, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());

View File

@@ -32,7 +32,7 @@ Assert::same(
);
if (!in_array($config['driver'], ['sqlite', 'sqlite3', 'pdo', 'sqlsrv'], true)) {
if (!in_array($config['driver'], ['sqlite', 'pdo', 'sqlsrv'], true)) {
Assert::same(
['products.product_id', 'orders.order_id', 'customers.name', 'xXx'],
$info->getColumnNames(true)
@@ -43,7 +43,7 @@ if (!in_array($config['driver'], ['sqlite', 'sqlite3', 'pdo', 'sqlsrv'], true))
$columns = $info->getColumns();
Assert::same('product_id', $columns[0]->getName());
if (!in_array($config['driver'], ['sqlite', 'sqlite3', 'pdo', 'sqlsrv'], true)) {
if (!in_array($config['driver'], ['sqlite', 'pdo', 'sqlsrv'], true)) {
Assert::same('products', $columns[0]->getTableName());
}
Assert::null($columns[0]->getVendorInfo('xxx'));

View File

@@ -24,17 +24,6 @@ class MockResult extends Dibi\Result
}
test('', function () {
$result = new MockResult;
$result->setType('col', Type::TEXT);
$result->setFormat(Type::TEXT, 'native');
Assert::same(['col' => null], $result->test(['col' => null]));
Assert::same(['col' => true], $result->test(['col' => true]));
Assert::same(['col' => false], $result->test(['col' => false]));
});
test('', function () {
$result = new MockResult;
$result->setType('col', Type::BOOL);

View File

@@ -35,10 +35,6 @@ Assert::error(function () use ($row) {
Assert::false(isset($row->missing));
Assert::false(isset($row['missing']));
// ??
Assert::same(123, $row->missing ?? 123);
Assert::same(123, $row['missing'] ?? 123);
// suggestions
Assert::error(function () use ($row) {

View File

@@ -12,5 +12,5 @@ extension=php_pdo_pgsql.dll
extension=php_pdo_sqlite.dll
extension=php_pgsql.dll
extension=php_sqlite3.dll
extension=php_sqlsrv_ts.dll
extension=php_sqlsrv_71_ts.dll
extension=php_odbc.dll