1
0
mirror of https://github.com/dg/dibi.git synced 2025-08-02 12:21:06 +02:00

moved to namespace Dibi

added loader for old class names
This commit is contained in:
David Grudl
2015-10-08 02:13:22 +02:00
parent 6222e966c7
commit 2e09a559f2
75 changed files with 1173 additions and 954 deletions

View File

@@ -21,7 +21,8 @@
"dg/dibi": "self.version" "dg/dibi": "self.version"
}, },
"autoload": { "autoload": {
"classmap": ["src/"] "classmap": ["src/"],
"files": ["src/loader.php"]
}, },
"extra": { "extra": {
"branch-alias": { "branch-alias": {

View File

@@ -15,21 +15,21 @@ try {
'database' => 'data/sample.s3db', 'database' => 'data/sample.s3db',
]); ]);
echo 'OK'; echo 'OK';
} catch (DibiException $e) { } catch (Dibi\Exception $e) {
echo get_class($e), ': ', $e->getMessage(), "\n"; echo get_class($e), ': ', $e->getMessage(), "\n";
} }
echo "</p>\n"; echo "</p>\n";
// connects to SQlite using DibiConnection object // connects to SQlite using Dibi\Connection object
echo '<p>Connecting to Sqlite: '; echo '<p>Connecting to Sqlite: ';
try { try {
$connection = new DibiConnection([ $connection = new Dibi\Connection([
'driver' => 'sqlite3', 'driver' => 'sqlite3',
'database' => 'data/sample.s3db', 'database' => 'data/sample.s3db',
]); ]);
echo 'OK'; echo 'OK';
} catch (DibiException $e) { } catch (Dibi\Exception $e) {
echo get_class($e), ': ', $e->getMessage(), "\n"; echo get_class($e), ': ', $e->getMessage(), "\n";
} }
echo "</p>\n"; echo "</p>\n";
@@ -40,7 +40,7 @@ echo '<p>Connecting to MySQL: ';
try { try {
dibi::connect('driver=mysql&host=localhost&username=root&password=xxx&database=test&charset=cp1250'); dibi::connect('driver=mysql&host=localhost&username=root&password=xxx&database=test&charset=cp1250');
echo 'OK'; echo 'OK';
} catch (DibiException $e) { } catch (Dibi\Exception $e) {
echo get_class($e), ': ', $e->getMessage(), "\n"; echo get_class($e), ': ', $e->getMessage(), "\n";
} }
echo "</p>\n"; echo "</p>\n";
@@ -61,7 +61,7 @@ try {
'flags' => MYSQLI_CLIENT_COMPRESS, 'flags' => MYSQLI_CLIENT_COMPRESS,
]); ]);
echo 'OK'; echo 'OK';
} catch (DibiException $e) { } catch (Dibi\Exception $e) {
echo get_class($e), ': ', $e->getMessage(), "\n"; echo get_class($e), ': ', $e->getMessage(), "\n";
} }
echo "</p>\n"; echo "</p>\n";
@@ -77,7 +77,7 @@ try {
'dsn' => 'Driver={Microsoft Access Driver (*.mdb)};Dbq='.__DIR__.'/data/sample.mdb', 'dsn' => 'Driver={Microsoft Access Driver (*.mdb)};Dbq='.__DIR__.'/data/sample.mdb',
]); ]);
echo 'OK'; echo 'OK';
} catch (DibiException $e) { } catch (Dibi\Exception $e) {
echo get_class($e), ': ', $e->getMessage(), "\n"; echo get_class($e), ': ', $e->getMessage(), "\n";
} }
echo "</p>\n"; echo "</p>\n";
@@ -92,7 +92,7 @@ try {
'persistent' => TRUE, 'persistent' => TRUE,
]); ]);
echo 'OK'; echo 'OK';
} catch (DibiException $e) { } catch (Dibi\Exception $e) {
echo get_class($e), ': ', $e->getMessage(), "\n"; echo get_class($e), ': ', $e->getMessage(), "\n";
} }
echo "</p>\n"; echo "</p>\n";
@@ -106,7 +106,7 @@ try {
'dsn' => 'sqlite::memory:', 'dsn' => 'sqlite::memory:',
]); ]);
echo 'OK'; echo 'OK';
} catch (DibiException $e) { } catch (Dibi\Exception $e) {
echo get_class($e), ': ', $e->getMessage(), "\n"; echo get_class($e), ': ', $e->getMessage(), "\n";
} }
echo "</p>\n"; echo "</p>\n";
@@ -122,7 +122,7 @@ try {
'password' => 'xxx', 'password' => 'xxx',
]); ]);
echo 'OK'; echo 'OK';
} catch (DibiException $e) { } catch (Dibi\Exception $e) {
echo get_class($e), ': ', $e->getMessage(), "\n"; echo get_class($e), ': ', $e->getMessage(), "\n";
} }
echo "</p>\n"; echo "</p>\n";
@@ -139,7 +139,7 @@ try {
'database' => 'main', 'database' => 'main',
]); ]);
echo 'OK'; echo 'OK';
} catch (DibiException $e) { } catch (Dibi\Exception $e) {
echo get_class($e), ': ', $e->getMessage(), "\n"; echo get_class($e), ': ', $e->getMessage(), "\n";
} }
echo "</p>\n"; echo "</p>\n";
@@ -155,7 +155,7 @@ try {
'database' => 'db', 'database' => 'db',
]); ]);
echo 'OK'; echo 'OK';
} catch (DibiException $e) { } catch (Dibi\Exception $e) {
echo get_class($e), ': ', $e->getMessage(), "\n"; echo get_class($e), ': ', $e->getMessage(), "\n";
} }
echo "</p>\n"; echo "</p>\n";

View File

@@ -27,6 +27,6 @@ dibi::dump();
// dump result table // dump result table
echo '<h2>DibiResult::dump()</h2>'; echo '<h2>Dibi\Result::dump()</h2>';
$res->dump(); $res->dump();

View File

@@ -23,7 +23,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 DibiDateTime($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

View File

@@ -4,6 +4,8 @@
<?php <?php
use Dibi\Type;
if (@!include __DIR__ . '/../vendor/autoload.php') { if (@!include __DIR__ . '/../vendor/autoload.php') {
die('Install dependencies using `composer install --dev`'); die('Install dependencies using `composer install --dev`');
} }
@@ -22,14 +24,14 @@ dibi::connect([
// using manual hints // using manual hints
$res = dibi::query('SELECT * FROM [customers]'); $res = dibi::query('SELECT * FROM [customers]');
$res->setType('customer_id', DibiType::INTEGER) $res->setType('customer_id', Type::INTEGER)
->setType('added', DibiType::DATETIME) ->setType('added', Type::DATETIME)
->setFormat(DibiType::DATETIME, 'Y-m-d H:i:s'); ->setFormat(Type::DATETIME, 'Y-m-d H:i:s');
Tracy\Dumper::dump($res->fetch()); Tracy\Dumper::dump($res->fetch());
// outputs: // outputs:
// DibiRow(3) { // Dibi\Row(3) {
// customer_id => 1 // customer_id => 1
// name => "Dave Lister" (11) // name => "Dave Lister" (11)
// added => "2007-03-11 17:20:03" (19) // added => "2007-03-11 17:20:03" (19)
@@ -40,7 +42,7 @@ $res = dibi::query('SELECT * FROM [customers]');
Tracy\Dumper::dump($res->fetch()); Tracy\Dumper::dump($res->fetch());
// outputs: // outputs:
// DibiRow(3) { // Dibi\Row(3) {
// customer_id => 1 // customer_id => 1
// name => "Dave Lister" (11) // name => "Dave Lister" (11)
// added => "2007-03-11 17:20:03" (19) // added => "2007-03-11 17:20:03" (19)

View File

@@ -17,8 +17,8 @@ dibi::connect([
]); ]);
// using the "prototype" to add custom method to class DibiResult // using the "prototype" to add custom method to class Dibi\Result
DibiResult::extensionMethod('fetchShuffle', function (DibiResult $obj) { Dibi\Result::extensionMethod('fetchShuffle', function (Dibi\Result $obj) {
$all = $obj->fetchAll(); $all = $obj->fetchAll();
shuffle($all); shuffle($all);
return $all; return $all;

View File

@@ -26,7 +26,7 @@ try {
$res = dibi::query('SELECT * FROM [customers] WHERE [customer_id] < ?', 5); $res = dibi::query('SELECT * FROM [customers] WHERE [customer_id] < ?', 5);
$res = dibi::query('SELECT FROM [customers] WHERE [customer_id] < ?', 38); $res = dibi::query('SELECT FROM [customers] WHERE [customer_id] < ?', 38);
} catch (DibiException $e) { } catch (Dibi\Exception $e) {
echo '<p>', get_class($e), ': ', $e->getMessage(), '</p>'; echo '<p>', get_class($e), ': ', $e->getMessage(), '</p>';
} }

View File

@@ -5,11 +5,15 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Bridges\Nette;
use Nette;
/** /**
* Dibi extension for Nette Framework 2.1. Creates 'connection' service. * Dibi extension for Nette Framework 2.1. Creates 'connection' service.
*/ */
class DibiNette21Extension extends Nette\DI\CompilerExtension class DibiExtension21 extends Nette\DI\CompilerExtension
{ {
public function loadConfiguration() public function loadConfiguration()
@@ -32,14 +36,14 @@ class DibiNette21Extension extends Nette\DI\CompilerExtension
} }
$connection = $container->addDefinition($this->prefix('connection')) $connection = $container->addDefinition($this->prefix('connection'))
->setClass('DibiConnection', [$config]) ->setClass('Dibi\Connection', [$config])
->setAutowired(isset($config['autowired']) ? $config['autowired'] : TRUE); ->setAutowired(isset($config['autowired']) ? $config['autowired'] : TRUE);
if ($useProfiler) { if ($useProfiler) {
$panel = $container->addDefinition($this->prefix('panel')) $panel = $container->addDefinition($this->prefix('panel'))
->setClass('DibiNettePanel') ->setClass('Dibi\Bridges\Nette\Panel')
->addSetup('Nette\Diagnostics\Debugger::getBar()->addPanel(?)', ['@self']) ->addSetup('Nette\Diagnostics\Debugger::getBar()->addPanel(?)', ['@self'])
->addSetup('Nette\Diagnostics\Debugger::getBlueScreen()->addPanel(?)', ['DibiNettePanel::renderException']); ->addSetup('Nette\Diagnostics\Debugger::getBlueScreen()->addPanel(?)', ['Dibi\Bridges\Nette\Panel::renderException']);
$connection->addSetup('$service->onEvent[] = ?', [[$panel, 'logEvent']]); $connection->addSetup('$service->onEvent[] = ?', [[$panel, 'logEvent']]);
} }

View File

@@ -7,7 +7,6 @@
namespace Dibi\Bridges\Nette; namespace Dibi\Bridges\Nette;
use dibi;
use Nette; use Nette;
@@ -37,7 +36,7 @@ class DibiExtension22 extends Nette\DI\CompilerExtension
} }
$connection = $container->addDefinition($this->prefix('connection')) $connection = $container->addDefinition($this->prefix('connection'))
->setClass('DibiConnection', [$config]) ->setClass('Dibi\Connection', [$config])
->setAutowired(isset($config['autowired']) ? $config['autowired'] : TRUE); ->setAutowired(isset($config['autowired']) ? $config['autowired'] : TRUE);
if ($useProfiler) { if ($useProfiler) {

View File

@@ -5,15 +5,21 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Bridges\Nette;
use Dibi;
use Dibi\Event;
use Dibi\Helpers;
use Nette;
use Nette\Diagnostics\Debugger; use Nette\Diagnostics\Debugger;
/** /**
* Dibi panel for Nette\Diagnostics. * Dibi panel for Nette\Diagnostics.
*/ */
class DibiNettePanel implements Nette\Diagnostics\IBarPanel class Panel implements Nette\Diagnostics\IBarPanel
{ {
use DibiStrict; use Dibi\Strict;
/** @var int maximum SQL length */ /** @var int maximum SQL length */
public static $maxLength = 1000; public static $maxLength = 1000;
@@ -30,12 +36,12 @@ class DibiNettePanel implements Nette\Diagnostics\IBarPanel
public function __construct($explain = TRUE, $filter = NULL) public function __construct($explain = TRUE, $filter = NULL)
{ {
$this->filter = $filter ? (int) $filter : DibiEvent::QUERY; $this->filter = $filter ? (int) $filter : Event::QUERY;
$this->explain = $explain; $this->explain = $explain;
} }
public function register(DibiConnection $connection) public function register(Dibi\Connection $connection)
{ {
Debugger::getBar()->addPanel($this); Debugger::getBar()->addPanel($this);
Debugger::getBlueScreen()->addPanel([__CLASS__, 'renderException']); Debugger::getBlueScreen()->addPanel([__CLASS__, 'renderException']);
@@ -47,7 +53,7 @@ class DibiNettePanel implements Nette\Diagnostics\IBarPanel
* After event notification. * After event notification.
* @return void * @return void
*/ */
public function logEvent(DibiEvent $event) public function logEvent(Event $event)
{ {
if (($event->type & $this->filter) === 0) { if (($event->type & $this->filter) === 0) {
return; return;
@@ -62,10 +68,10 @@ class DibiNettePanel implements Nette\Diagnostics\IBarPanel
*/ */
public static function renderException($e) public static function renderException($e)
{ {
if ($e instanceof DibiException && $e->getSql()) { if ($e instanceof Dibi\Exception && $e->getSql()) {
return [ return [
'tab' => 'SQL', 'tab' => 'SQL',
'panel' => DibiHelpers::dump($e->getSql(), TRUE), 'panel' => Helpers::dump($e->getSql(), TRUE),
]; ];
} }
} }
@@ -99,15 +105,15 @@ class DibiNettePanel implements Nette\Diagnostics\IBarPanel
foreach ($this->events as $event) { foreach ($this->events as $event) {
$totalTime += $event->time; $totalTime += $event->time;
$explain = NULL; // EXPLAIN is called here to work SELECT FOUND_ROWS() $explain = NULL; // EXPLAIN is called here to work SELECT FOUND_ROWS()
if ($this->explain && $event->type === DibiEvent::SELECT) { if ($this->explain && $event->type === Event::SELECT) {
try { try {
$backup = [$event->connection->onEvent, dibi::$numOfQueries, dibi::$totalTime]; $backup = [$event->connection->onEvent, \dibi::$numOfQueries, \dibi::$totalTime];
$event->connection->onEvent = NULL; $event->connection->onEvent = NULL;
$cmd = is_string($this->explain) ? $this->explain : ($event->connection->getConfig('driver') === 'oracle' ? 'EXPLAIN PLAN FOR' : 'EXPLAIN'); $cmd = is_string($this->explain) ? $this->explain : ($event->connection->getConfig('driver') === 'oracle' ? 'EXPLAIN PLAN FOR' : 'EXPLAIN');
$explain = DibiHelpers::dump($event->connection->nativeQuery("$cmd $event->sql"), TRUE); $explain = Helpers::dump($event->connection->nativeQuery("$cmd $event->sql"), TRUE);
} catch (DibiException $e) { } catch (Dibi\Exception $e) {
} }
list($event->connection->onEvent, dibi::$numOfQueries, dibi::$totalTime) = $backup; list($event->connection->onEvent, \dibi::$numOfQueries, \dibi::$totalTime) = $backup;
} }
$s .= '<tr><td>' . sprintf('%0.3f', $event->time * 1000); $s .= '<tr><td>' . sprintf('%0.3f', $event->time * 1000);
@@ -117,7 +123,7 @@ class DibiNettePanel implements Nette\Diagnostics\IBarPanel
$s .= "<br /><a href='#nette-debug-DibiProfiler-row-$counter' class='nette-toggler nette-toggle-collapsed' rel='#nette-debug-DibiProfiler-row-$counter'>explain</a>"; $s .= "<br /><a href='#nette-debug-DibiProfiler-row-$counter' class='nette-toggler nette-toggle-collapsed' rel='#nette-debug-DibiProfiler-row-$counter'>explain</a>";
} }
$s .= '</td><td class="nette-DibiProfiler-sql">' . DibiHelpers::dump(strlen($event->sql) > self::$maxLength ? substr($event->sql, 0, self::$maxLength) . '...' : $event->sql, TRUE); $s .= '</td><td class="nette-DibiProfiler-sql">' . Helpers::dump(strlen($event->sql) > self::$maxLength ? substr($event->sql, 0, self::$maxLength) . '...' : $event->sql, TRUE);
if ($explain) { if ($explain) {
$s .= "<div id='nette-debug-DibiProfiler-row-$counter' class='nette-collapsed'>{$explain}</div>"; $s .= "<div id='nette-debug-DibiProfiler-row-$counter' class='nette-collapsed'>{$explain}</div>";
} }

View File

@@ -7,9 +7,10 @@
namespace Dibi\Bridges\Tracy; namespace Dibi\Bridges\Tracy;
use dibi; use Dibi;
use Dibi\Event;
use Dibi\Helpers;
use Tracy; use Tracy;
use DibiHelpers;
/** /**
@@ -17,7 +18,7 @@ use DibiHelpers;
*/ */
class Panel implements Tracy\IBarPanel class Panel implements Tracy\IBarPanel
{ {
use \DibiStrict; use Dibi\Strict;
/** @var int maximum SQL length */ /** @var int maximum SQL length */
public static $maxLength = 1000; public static $maxLength = 1000;
@@ -34,12 +35,12 @@ class Panel implements Tracy\IBarPanel
public function __construct($explain = TRUE, $filter = NULL) public function __construct($explain = TRUE, $filter = NULL)
{ {
$this->filter = $filter ? (int) $filter : \DibiEvent::QUERY; $this->filter = $filter ? (int) $filter : Event::QUERY;
$this->explain = $explain; $this->explain = $explain;
} }
public function register(\DibiConnection $connection) public function register(Dibi\Connection $connection)
{ {
Tracy\Debugger::getBar()->addPanel($this); Tracy\Debugger::getBar()->addPanel($this);
Tracy\Debugger::getBlueScreen()->addPanel([__CLASS__, 'renderException']); Tracy\Debugger::getBlueScreen()->addPanel([__CLASS__, 'renderException']);
@@ -51,7 +52,7 @@ class Panel implements Tracy\IBarPanel
* After event notification. * After event notification.
* @return void * @return void
*/ */
public function logEvent(\DibiEvent $event) public function logEvent(Event $event)
{ {
if (($event->type & $this->filter) === 0) { if (($event->type & $this->filter) === 0) {
return; return;
@@ -66,10 +67,10 @@ class Panel implements Tracy\IBarPanel
*/ */
public static function renderException($e) public static function renderException($e)
{ {
if ($e instanceof \DibiException && $e->getSql()) { if ($e instanceof Dibi\Exception && $e->getSql()) {
return [ return [
'tab' => 'SQL', 'tab' => 'SQL',
'panel' => DibiHelpers::dump($e->getSql(), TRUE), 'panel' => Helpers::dump($e->getSql(), TRUE),
]; ];
} }
} }
@@ -104,15 +105,15 @@ class Panel implements Tracy\IBarPanel
foreach ($this->events as $event) { foreach ($this->events as $event) {
$totalTime += $event->time; $totalTime += $event->time;
$explain = NULL; // EXPLAIN is called here to work SELECT FOUND_ROWS() $explain = NULL; // EXPLAIN is called here to work SELECT FOUND_ROWS()
if ($this->explain && $event->type === \DibiEvent::SELECT) { if ($this->explain && $event->type === Event::SELECT) {
try { try {
$backup = [$event->connection->onEvent, dibi::$numOfQueries, dibi::$totalTime]; $backup = [$event->connection->onEvent, \dibi::$numOfQueries, \dibi::$totalTime];
$event->connection->onEvent = NULL; $event->connection->onEvent = NULL;
$cmd = is_string($this->explain) ? $this->explain : ($event->connection->getConfig('driver') === 'oracle' ? 'EXPLAIN PLAN FOR' : 'EXPLAIN'); $cmd = is_string($this->explain) ? $this->explain : ($event->connection->getConfig('driver') === 'oracle' ? 'EXPLAIN PLAN FOR' : 'EXPLAIN');
$explain = DibiHelpers::dump($event->connection->nativeQuery("$cmd $event->sql"), TRUE); $explain = Helpers::dump($event->connection->nativeQuery("$cmd $event->sql"), TRUE);
} catch (\DibiException $e) { } catch (Dibi\Exception $e) {
} }
list($event->connection->onEvent, dibi::$numOfQueries, dibi::$totalTime) = $backup; list($event->connection->onEvent, \dibi::$numOfQueries, \dibi::$totalTime) = $backup;
} }
$s .= '<tr><td>' . sprintf('%0.3f', $event->time * 1000); $s .= '<tr><td>' . sprintf('%0.3f', $event->time * 1000);
@@ -122,7 +123,7 @@ class Panel implements Tracy\IBarPanel
$s .= "<br /><a href='#tracy-debug-DibiProfiler-row-$counter' class='tracy-toggle tracy-collapsed' rel='#tracy-debug-DibiProfiler-row-$counter'>explain</a>"; $s .= "<br /><a href='#tracy-debug-DibiProfiler-row-$counter' class='tracy-toggle tracy-collapsed' rel='#tracy-debug-DibiProfiler-row-$counter'>explain</a>";
} }
$s .= '</td><td class="tracy-DibiProfiler-sql">' . DibiHelpers::dump(strlen($event->sql) > self::$maxLength ? substr($event->sql, 0, self::$maxLength) . '...' : $event->sql, TRUE); $s .= '</td><td class="tracy-DibiProfiler-sql">' . Helpers::dump(strlen($event->sql) > self::$maxLength ? substr($event->sql, 0, self::$maxLength) . '...' : $event->sql, TRUE);
if ($explain) { if ($explain) {
$s .= "<div id='tracy-debug-DibiProfiler-row-$counter' class='tracy-collapsed'>{$explain}</div>"; $s .= "<div id='tracy-debug-DibiProfiler-row-$counter' class='tracy-collapsed'>{$explain}</div>";
} }

View File

@@ -5,6 +5,10 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi;
use Traversable;
/** /**
* dibi connection. * dibi connection.
@@ -12,26 +16,26 @@
* @property-read int $affectedRows * @property-read int $affectedRows
* @property-read int $insertId * @property-read int $insertId
*/ */
class DibiConnection class Connection
{ {
use DibiStrict; use Strict;
/** @var array of function (DibiEvent $event); Occurs after query is executed */ /** @var array of function (Event $event); Occurs after query is executed */
public $onEvent; public $onEvent;
/** @var array Current connection configuration */ /** @var array Current connection configuration */
private $config; private $config;
/** @var IDibiDriver */ /** @var Driver */
private $driver; private $driver;
/** @var DibiTranslator */ /** @var Translator */
private $translator; private $translator;
/** @var bool Is connected? */ /** @var bool Is connected? */
private $connected = FALSE; private $connected = FALSE;
/** @var DibiHashMap Substitutes for identifiers */ /** @var HashMap Substitutes for identifiers */
private $substitutes; private $substitutes;
@@ -47,7 +51,7 @@ class DibiConnection
* @param mixed connection parameters * @param mixed connection parameters
* @param string connection name * @param string connection name
* @throws DibiException * @throws Exception
*/ */
public function __construct($config, $name = NULL) public function __construct($config, $name = NULL)
{ {
@@ -62,7 +66,7 @@ class DibiConnection
$config = $tmp; $config = $tmp;
} elseif (!is_array($config)) { } elseif (!is_array($config)) {
throw new InvalidArgumentException('Configuration must be array, string or object.'); throw new \InvalidArgumentException('Configuration must be array, string or object.');
} }
self::alias($config, 'username', 'user'); self::alias($config, 'username', 'user');
@@ -72,19 +76,19 @@ class DibiConnection
self::alias($config, 'result|formatDateTime', 'resultDateTime'); self::alias($config, 'result|formatDateTime', 'resultDateTime');
if (!isset($config['driver'])) { if (!isset($config['driver'])) {
$config['driver'] = dibi::$defaultDriver; $config['driver'] = \dibi::$defaultDriver;
} }
$class = $tmp = preg_replace(['#\W#', '#sql#'], ['_', 'Sql'], ucfirst(strtolower($config['driver']))); $class = $tmp = preg_replace(['#\W#', '#sql#'], ['_', 'Sql'], ucfirst(strtolower($config['driver'])));
$class = "Dibi{$class}Driver"; $class = "Dibi\\Drivers\\{$class}Driver";
if (!class_exists($class)) { if (!class_exists($class)) {
throw new DibiException("Unable to create instance of dibi driver '$class'."); throw new Exception("Unable to create instance of dibi driver '$class'.");
} }
$config['name'] = $name; $config['name'] = $name;
$this->config = $config; $this->config = $config;
$this->driver = new $class; $this->driver = new $class;
$this->translator = new DibiTranslator($this); $this->translator = new Translator($this);
// profiler // profiler
$profilerCfg = & $config['profiler']; $profilerCfg = & $config['profiler'];
@@ -92,23 +96,23 @@ class DibiConnection
$profilerCfg = ['run' => (bool) $profilerCfg]; $profilerCfg = ['run' => (bool) $profilerCfg];
} }
if (!empty($profilerCfg['run'])) { if (!empty($profilerCfg['run'])) {
$filter = isset($profilerCfg['filter']) ? $profilerCfg['filter'] : DibiEvent::QUERY; $filter = isset($profilerCfg['filter']) ? $profilerCfg['filter'] : Event::QUERY;
if (isset($profilerCfg['file'])) { if (isset($profilerCfg['file'])) {
$this->onEvent[] = [new DibiFileLogger($profilerCfg['file'], $filter), 'logEvent']; $this->onEvent[] = [new Loggers\FileLogger($profilerCfg['file'], $filter), 'logEvent'];
} }
if (DibiFirePhpLogger::isAvailable()) { if (Loggers\FirePhpLogger::isAvailable()) {
$this->onEvent[] = [new DibiFirePhpLogger($filter), 'logEvent']; $this->onEvent[] = [new Loggers\FirePhpLogger($filter), 'logEvent'];
} }
if (!interface_exists('Tracy\IBarPanel') && interface_exists('Nette\Diagnostics\IBarPanel') && class_exists('DibiNettePanel')) { if (!interface_exists('Tracy\IBarPanel') && interface_exists('Nette\Diagnostics\IBarPanel') && class_exists('Dibi\Bridges\Nette\Panel')) {
$panel = new DibiNettePanel(isset($profilerCfg['explain']) ? $profilerCfg['explain'] : TRUE, $filter); $panel = new Bridges\Nette\Panel(isset($profilerCfg['explain']) ? $profilerCfg['explain'] : TRUE, $filter);
$panel->register($this); $panel->register($this);
} }
} }
$this->substitutes = new DibiHashMap(function ($expr) { return ":$expr:"; }); $this->substitutes = new HashMap(function ($expr) { return ":$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;
@@ -138,13 +142,13 @@ class DibiConnection
*/ */
final public function connect() final public function connect()
{ {
$event = $this->onEvent ? new DibiEvent($this, DibiEvent::CONNECT) : NULL; $event = $this->onEvent ? new Event($this, Event::CONNECT) : NULL;
try { try {
$this->driver->connect($this->config); $this->driver->connect($this->config);
$this->connected = TRUE; $this->connected = TRUE;
$event && $this->onEvent($event->done()); $event && $this->onEvent($event->done());
} catch (DibiException $e) { } catch (Exception $e) {
$event && $this->onEvent($event->done($e)); $event && $this->onEvent($event->done($e));
throw $e; throw $e;
} }
@@ -216,7 +220,7 @@ class DibiConnection
/** /**
* Returns the driver and connects to a database in lazy mode. * Returns the driver and connects to a database in lazy mode.
* @return IDibiDriver * @return Driver
*/ */
final public function getDriver() final public function getDriver()
{ {
@@ -228,8 +232,8 @@ class DibiConnection
/** /**
* Generates (translates) and executes SQL query. * Generates (translates) and executes SQL query.
* @param array|mixed one or more arguments * @param array|mixed one or more arguments
* @return DibiResult|int result set object (if any) * @return Result|int result set object (if any)
* @throws DibiException * @throws Exception
*/ */
final public function query($args) final public function query($args)
{ {
@@ -242,7 +246,7 @@ class DibiConnection
* Generates SQL query. * Generates SQL query.
* @param array|mixed one or more arguments * @param array|mixed one or more arguments
* @return string * @return string
* @throws DibiException * @throws Exception
*/ */
final public function translate($args) final public function translate($args)
{ {
@@ -260,12 +264,12 @@ class DibiConnection
{ {
$args = func_get_args(); $args = func_get_args();
try { try {
DibiHelpers::dump($this->translateArgs($args)); Helpers::dump($this->translateArgs($args));
return TRUE; return TRUE;
} catch (DibiException $e) { } catch (Exception $e) {
if ($e->getSql()) { if ($e->getSql()) {
DibiHelpers::dump($e->getSql()); Helpers::dump($e->getSql());
} else { } else {
echo get_class($e) . ': ' . $e->getMessage() . (PHP_SAPI === 'cli' ? "\n" : '<br>'); echo get_class($e) . ': ' . $e->getMessage() . (PHP_SAPI === 'cli' ? "\n" : '<br>');
} }
@@ -275,15 +279,15 @@ class DibiConnection
/** /**
* Generates (translates) and returns SQL query as DibiDataSource. * Generates (translates) and returns SQL query as DataSource.
* @param array|mixed one or more arguments * @param array|mixed one or more arguments
* @return DibiDataSource * @return DataSource
* @throws DibiException * @throws Exception
*/ */
final public function dataSource($args) final public function dataSource($args)
{ {
$args = func_get_args(); $args = func_get_args();
return new DibiDataSource($this->translateArgs($args), $this); return new DataSource($this->translateArgs($args), $this);
} }
@@ -302,19 +306,19 @@ class DibiConnection
/** /**
* Executes the SQL query. * Executes the SQL query.
* @param string SQL statement. * @param string SQL statement.
* @return DibiResult|int result set object (if any) * @return Result|int result set object (if any)
* @throws DibiException * @throws Exception
*/ */
final public function nativeQuery($sql) final public function nativeQuery($sql)
{ {
$this->connected || $this->connect(); $this->connected || $this->connect();
dibi::$sql = $sql; \dibi::$sql = $sql;
$event = $this->onEvent ? new DibiEvent($this, DibiEvent::QUERY, $sql) : NULL; $event = $this->onEvent ? new Event($this, Event::QUERY, $sql) : NULL;
try { try {
$res = $this->driver->query($sql); $res = $this->driver->query($sql);
} catch (DibiException $e) { } catch (Exception $e) {
$event && $this->onEvent($event->done($e)); $event && $this->onEvent($event->done($e));
throw $e; throw $e;
} }
@@ -333,14 +337,14 @@ class DibiConnection
/** /**
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query. * Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
* @return int number of rows * @return int number of rows
* @throws DibiException * @throws Exception
*/ */
public function getAffectedRows() public function getAffectedRows()
{ {
$this->connected || $this->connect(); $this->connected || $this->connect();
$rows = $this->driver->getAffectedRows(); $rows = $this->driver->getAffectedRows();
if (!is_int($rows) || $rows < 0) { if (!is_int($rows) || $rows < 0) {
throw new DibiException('Cannot retrieve number of affected rows.'); throw new Exception('Cannot retrieve number of affected rows.');
} }
return $rows; return $rows;
} }
@@ -349,7 +353,7 @@ class DibiConnection
/** /**
* Gets the number of affected rows. Alias for getAffectedRows(). * Gets the number of affected rows. Alias for getAffectedRows().
* @return int number of rows * @return int number of rows
* @throws DibiException * @throws Exception
*/ */
public function affectedRows() public function affectedRows()
{ {
@@ -361,14 +365,14 @@ class DibiConnection
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query. * Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
* @param string optional sequence name * @param string optional sequence name
* @return int * @return int
* @throws DibiException * @throws Exception
*/ */
public function getInsertId($sequence = NULL) public function getInsertId($sequence = NULL)
{ {
$this->connected || $this->connect(); $this->connected || $this->connect();
$id = $this->driver->getInsertId($sequence); $id = $this->driver->getInsertId($sequence);
if ($id < 1) { if ($id < 1) {
throw new DibiException('Cannot retrieve last generated ID.'); throw new Exception('Cannot retrieve last generated ID.');
} }
return (int) $id; return (int) $id;
} }
@@ -378,7 +382,7 @@ class DibiConnection
* Retrieves the ID generated for an AUTO_INCREMENT column. Alias for getInsertId(). * Retrieves the ID generated for an AUTO_INCREMENT column. Alias for getInsertId().
* @param string optional sequence name * @param string optional sequence name
* @return int * @return int
* @throws DibiException * @throws Exception
*/ */
public function insertId($sequence = NULL) public function insertId($sequence = NULL)
{ {
@@ -394,12 +398,12 @@ class DibiConnection
public function begin($savepoint = NULL) public function begin($savepoint = NULL)
{ {
$this->connected || $this->connect(); $this->connected || $this->connect();
$event = $this->onEvent ? new DibiEvent($this, DibiEvent::BEGIN, $savepoint) : NULL; $event = $this->onEvent ? new Event($this, Event::BEGIN, $savepoint) : NULL;
try { try {
$this->driver->begin($savepoint); $this->driver->begin($savepoint);
$event && $this->onEvent($event->done()); $event && $this->onEvent($event->done());
} catch (DibiException $e) { } catch (Exception $e) {
$event && $this->onEvent($event->done($e)); $event && $this->onEvent($event->done($e));
throw $e; throw $e;
} }
@@ -414,12 +418,12 @@ class DibiConnection
public function commit($savepoint = NULL) public function commit($savepoint = NULL)
{ {
$this->connected || $this->connect(); $this->connected || $this->connect();
$event = $this->onEvent ? new DibiEvent($this, DibiEvent::COMMIT, $savepoint) : NULL; $event = $this->onEvent ? new Event($this, Event::COMMIT, $savepoint) : NULL;
try { try {
$this->driver->commit($savepoint); $this->driver->commit($savepoint);
$event && $this->onEvent($event->done()); $event && $this->onEvent($event->done());
} catch (DibiException $e) { } catch (Exception $e) {
$event && $this->onEvent($event->done($e)); $event && $this->onEvent($event->done($e));
throw $e; throw $e;
} }
@@ -434,12 +438,12 @@ class DibiConnection
public function rollback($savepoint = NULL) public function rollback($savepoint = NULL)
{ {
$this->connected || $this->connect(); $this->connected || $this->connect();
$event = $this->onEvent ? new DibiEvent($this, DibiEvent::ROLLBACK, $savepoint) : NULL; $event = $this->onEvent ? new Event($this, Event::ROLLBACK, $savepoint) : NULL;
try { try {
$this->driver->rollback($savepoint); $this->driver->rollback($savepoint);
$event && $this->onEvent($event->done()); $event && $this->onEvent($event->done());
} catch (DibiException $e) { } catch (Exception $e) {
$event && $this->onEvent($event->done($e)); $event && $this->onEvent($event->done($e));
throw $e; throw $e;
} }
@@ -448,14 +452,14 @@ class DibiConnection
/** /**
* Result set factory. * Result set factory.
* @param IDibiResultDriver * @param ResultDriver
* @return DibiResult * @return Result
*/ */
public function createResultSet(IDibiResultDriver $resultDriver) public function createResultSet(ResultDriver $resultDriver)
{ {
$res = new DibiResult($resultDriver); $res = new Result($resultDriver);
return $res->setFormat(DibiType::DATE, $this->config['result']['formatDate']) return $res->setFormat(Type::DATE, $this->config['result']['formatDate'])
->setFormat(DibiType::DATETIME, $this->config['result']['formatDateTime']); ->setFormat(Type::DATETIME, $this->config['result']['formatDateTime']);
} }
@@ -463,17 +467,17 @@ class DibiConnection
/** /**
* @return DibiFluent * @return Fluent
*/ */
public function command() public function command()
{ {
return new DibiFluent($this); return new Fluent($this);
} }
/** /**
* @param string column name * @param string column name
* @return DibiFluent * @return Fluent
*/ */
public function select($args) public function select($args)
{ {
@@ -485,12 +489,12 @@ class DibiConnection
/** /**
* @param string table * @param string table
* @param array * @param array
* @return DibiFluent * @return Fluent
*/ */
public function update($table, $args) public function update($table, $args)
{ {
if (!(is_array($args) || $args instanceof Traversable)) { if (!(is_array($args) || $args instanceof Traversable)) {
throw new InvalidArgumentException('Arguments must be array or Traversable.'); throw new \InvalidArgumentException('Arguments must be array or Traversable.');
} }
return $this->command()->update('%n', $table)->set($args); return $this->command()->update('%n', $table)->set($args);
} }
@@ -499,14 +503,14 @@ class DibiConnection
/** /**
* @param string table * @param string table
* @param array * @param array
* @return DibiFluent * @return Fluent
*/ */
public function insert($table, $args) public function insert($table, $args)
{ {
if ($args instanceof Traversable) { if ($args instanceof Traversable) {
$args = iterator_to_array($args); $args = iterator_to_array($args);
} elseif (!is_array($args)) { } elseif (!is_array($args)) {
throw new InvalidArgumentException('Arguments must be array or Traversable.'); throw new \InvalidArgumentException('Arguments must be array or Traversable.');
} }
return $this->command()->insert() return $this->command()->insert()
->into('%n', $table, '(%n)', array_keys($args))->values('%l', $args); ->into('%n', $table, '(%n)', array_keys($args))->values('%l', $args);
@@ -515,7 +519,7 @@ class DibiConnection
/** /**
* @param string table * @param string table
* @return DibiFluent * @return Fluent
*/ */
public function delete($table) public function delete($table)
{ {
@@ -528,7 +532,7 @@ class DibiConnection
/** /**
* Returns substitution hashmap. * Returns substitution hashmap.
* @return DibiHashMap * @return HashMap
*/ */
public function getSubstitutes() public function getSubstitutes()
{ {
@@ -554,8 +558,8 @@ class DibiConnection
/** /**
* Executes SQL query and fetch result - shortcut for query() & fetch(). * Executes SQL query and fetch result - shortcut for query() & fetch().
* @param array|mixed one or more arguments * @param array|mixed one or more arguments
* @return DibiRow * @return Row
* @throws DibiException * @throws Exception
*/ */
public function fetch($args) public function fetch($args)
{ {
@@ -567,8 +571,8 @@ class DibiConnection
/** /**
* Executes SQL query and fetch results - shortcut for query() & fetchAll(). * Executes SQL query and fetch results - shortcut for query() & fetchAll().
* @param array|mixed one or more arguments * @param array|mixed one or more arguments
* @return DibiRow[] * @return Row[]
* @throws DibiException * @throws Exception
*/ */
public function fetchAll($args) public function fetchAll($args)
{ {
@@ -581,7 +585,7 @@ class DibiConnection
* Executes SQL query and fetch first column - shortcut for query() & fetchSingle(). * Executes SQL query and fetch first column - shortcut for query() & fetchSingle().
* @param array|mixed one or more arguments * @param array|mixed one or more arguments
* @return string * @return string
* @throws DibiException * @throws Exception
*/ */
public function fetchSingle($args) public function fetchSingle($args)
{ {
@@ -594,7 +598,7 @@ class DibiConnection
* Executes SQL query and fetch pairs - shortcut for query() & fetchPairs(). * Executes SQL query and fetch pairs - shortcut for query() & fetchPairs().
* @param array|mixed one or more arguments * @param array|mixed one or more arguments
* @return string * @return string
* @throws DibiException * @throws Exception
*/ */
public function fetchPairs($args) public function fetchPairs($args)
{ {
@@ -618,7 +622,7 @@ class DibiConnection
$handle = @fopen($file, 'r'); // intentionally @ $handle = @fopen($file, 'r'); // intentionally @
if (!$handle) { if (!$handle) {
throw new RuntimeException("Cannot open file '$file'."); throw new \RuntimeException("Cannot open file '$file'.");
} }
$count = 0; $count = 0;
@@ -650,12 +654,12 @@ class DibiConnection
/** /**
* Gets a information about the current database. * Gets a information about the current database.
* @return DibiDatabaseInfo * @return Reflection\Database
*/ */
public function getDatabaseInfo() public function getDatabaseInfo()
{ {
$this->connected || $this->connect(); $this->connected || $this->connect();
return new DibiDatabaseInfo($this->driver->getReflector(), isset($this->config['database']) ? $this->config['database'] : NULL); return new Reflection\Database($this->driver->getReflector(), isset($this->config['database']) ? $this->config['database'] : NULL);
} }
@@ -664,7 +668,7 @@ class DibiConnection
*/ */
public function __wakeup() public function __wakeup()
{ {
throw new DibiNotSupportedException('You cannot serialize or unserialize ' . get_class($this) . ' instances.'); throw new NotSupportedException('You cannot serialize or unserialize ' . get_class($this) . ' instances.');
} }
@@ -673,7 +677,7 @@ class DibiConnection
*/ */
public function __sleep() public function __sleep()
{ {
throw new DibiNotSupportedException('You cannot serialize or unserialize ' . get_class($this) . ' instances.'); throw new NotSupportedException('You cannot serialize or unserialize ' . get_class($this) . ' instances.');
} }

View File

@@ -5,22 +5,24 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi;
/** /**
* Default implementation of IDataSource for dibi. * Default implementation of IDataSource for dibi.
* *
*/ */
class DibiDataSource implements IDataSource class DataSource implements IDataSource
{ {
use DibiStrict; use Strict;
/** @var DibiConnection */ /** @var Connection */
private $connection; private $connection;
/** @var string */ /** @var string */
private $sql; private $sql;
/** @var DibiResult */ /** @var Result */
private $result; private $result;
/** @var int */ /** @var int */
@@ -47,9 +49,9 @@ class DibiDataSource implements IDataSource
/** /**
* @param string SQL command or table or view name, as data source * @param string SQL command or table or view name, as data source
* @param DibiConnection connection * @param Connection connection
*/ */
public function __construct($sql, DibiConnection $connection) public function __construct($sql, Connection $connection)
{ {
if (strpbrk($sql, " \t\r\n") === FALSE) { if (strpbrk($sql, " \t\r\n") === FALSE) {
$this->sql = $connection->getDriver()->escapeIdentifier($sql); // table name $this->sql = $connection->getDriver()->escapeIdentifier($sql); // table name
@@ -131,7 +133,7 @@ class DibiDataSource implements IDataSource
/** /**
* Returns the dibi connection. * Returns the dibi connection.
* @return DibiConnection * @return Connection
*/ */
final public function getConnection() final public function getConnection()
{ {
@@ -143,8 +145,8 @@ class DibiDataSource implements IDataSource
/** /**
* Returns (and queries) DibiResult. * Returns (and queries) Result.
* @return DibiResult * @return Result
*/ */
public function getResult() public function getResult()
{ {
@@ -156,7 +158,7 @@ class DibiDataSource implements IDataSource
/** /**
* @return DibiResultIterator * @return ResultIterator
*/ */
public function getIterator() public function getIterator()
{ {
@@ -166,7 +168,7 @@ class DibiDataSource implements IDataSource
/** /**
* Generates, executes SQL query and fetches the single row. * Generates, executes SQL query and fetches the single row.
* @return DibiRow|FALSE array on success, FALSE if no next record * @return Row|FALSE array on success, FALSE if no next record
*/ */
public function fetch() public function fetch()
{ {
@@ -231,8 +233,8 @@ class DibiDataSource implements IDataSource
/** /**
* Returns this data source wrapped in DibiFluent object. * Returns this data source wrapped in Fluent object.
* @return DibiFluent * @return Fluent
*/ */
public function toFluent() public function toFluent()
{ {
@@ -241,8 +243,8 @@ class DibiDataSource implements IDataSource
/** /**
* Returns this data source wrapped in DibiDataSource object. * Returns this data source wrapped in DataSource object.
* @return DibiDataSource * @return DataSource
*/ */
public function toDataSource() public function toDataSource()
{ {
@@ -264,7 +266,7 @@ FROM %SQL', $this->sql, '
%ex', $this->sorting ? ['ORDER BY %by', $this->sorting] : NULL, ' %ex', $this->sorting ? ['ORDER BY %by', $this->sorting] : NULL, '
%ofs %lmt', $this->offset, $this->limit %ofs %lmt', $this->offset, $this->limit
); );
} catch (Exception $e) { } catch (\Exception $e) {
trigger_error($e->getMessage(), E_USER_ERROR); trigger_error($e->getMessage(), E_USER_ERROR);
} }
} }

View File

@@ -5,19 +5,21 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi;
/** /**
* DateTime. * DateTime.
*/ */
class DibiDateTime extends DateTime class DateTime extends \DateTime
{ {
use DibiStrict; use Strict;
public function __construct($time = 'now', DateTimeZone $timezone = NULL) public function __construct($time = 'now', \DateTimeZone $timezone = NULL)
{ {
if (is_numeric($time)) { if (is_numeric($time)) {
parent::__construct('@' . $time); parent::__construct('@' . $time);
$this->setTimeZone($timezone ? $timezone : new DateTimeZone(date_default_timezone_get())); $this->setTimeZone($timezone ? $timezone : new \DateTimeZone(date_default_timezone_get()));
} elseif ($timezone === NULL) { } elseif ($timezone === NULL) {
parent::__construct($time); parent::__construct($time);
} else { } else {

View File

@@ -5,6 +5,10 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Drivers;
use Dibi;
/** /**
* The dibi driver for Firebird/InterBase database. * The dibi driver for Firebird/InterBase database.
@@ -16,11 +20,11 @@
* - charset => character encoding to set * - charset => character encoding to set
* - buffers (int) => buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default. * - buffers (int) => buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default.
* - resource (resource) => existing connection resource * - resource (resource) => existing connection resource
* - lazy, profiler, result, substitutes, ... => see DibiConnection options * - lazy, profiler, result, substitutes, ... => see Dibi\Connection options
*/ */
class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector class FirebirdDriver implements Dibi\Driver, Dibi\ResultDriver, Dibi\Reflector
{ {
use DibiStrict; use Dibi\Strict;
const ERROR_EXCEPTION_THROWN = -836; const ERROR_EXCEPTION_THROWN = -836;
@@ -41,12 +45,12 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
/** /**
* @throws DibiNotSupportedException * @throws Dibi\NotSupportedException
*/ */
public function __construct() public function __construct()
{ {
if (!extension_loaded('interbase')) { if (!extension_loaded('interbase')) {
throw new DibiNotSupportedException("PHP extension 'interbase' is not loaded."); throw new Dibi\NotSupportedException("PHP extension 'interbase' is not loaded.");
} }
} }
@@ -54,11 +58,11 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
/** /**
* Connects to a database. * Connects to a database.
* @return void * @return void
* @throws DibiException * @throws Dibi\Exception
*/ */
public function connect(array & $config) public function connect(array & $config)
{ {
DibiConnection::alias($config, 'database', 'db'); Dibi\Connection::alias($config, 'database', 'db');
if (isset($config['resource'])) { if (isset($config['resource'])) {
$this->connection = $config['resource']; $this->connection = $config['resource'];
@@ -73,18 +77,18 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
'buffers' => 0, 'buffers' => 0,
]; ];
DibiDriverException::tryError(); Dibi\DriverException::tryError();
if (empty($config['persistent'])) { if (empty($config['persistent'])) {
$this->connection = ibase_connect($config['database'], $config['username'], $config['password'], $config['charset'], $config['buffers']); // intentionally @ $this->connection = ibase_connect($config['database'], $config['username'], $config['password'], $config['charset'], $config['buffers']); // intentionally @
} else { } else {
$this->connection = ibase_pconnect($config['database'], $config['username'], $config['password'], $config['charset'], $config['buffers']); // intentionally @ $this->connection = ibase_pconnect($config['database'], $config['username'], $config['password'], $config['charset'], $config['buffers']); // intentionally @
} }
if (DibiDriverException::catchError($msg)) { if (Dibi\DriverException::catchError($msg)) {
throw new DibiDriverException($msg, ibase_errcode()); throw new Dibi\DriverException($msg, ibase_errcode());
} }
if (!is_resource($this->connection)) { if (!is_resource($this->connection)) {
throw new DibiDriverException(ibase_errmsg(), ibase_errcode()); throw new Dibi\DriverException(ibase_errmsg(), ibase_errcode());
} }
} }
} }
@@ -103,27 +107,27 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
/** /**
* Executes the SQL query. * Executes the SQL query.
* @param string SQL statement. * @param string SQL statement.
* @return IDibiResultDriver|NULL * @return Dibi\ResultDriver|NULL
* @throws DibiDriverException|DibiException * @throws Dibi\DriverException|Dibi\Exception
*/ */
public function query($sql) public function query($sql)
{ {
DibiDriverException::tryError(); Dibi\DriverException::tryError();
$resource = $this->inTransaction ? $this->transaction : $this->connection; $resource = $this->inTransaction ? $this->transaction : $this->connection;
$res = ibase_query($resource, $sql); $res = ibase_query($resource, $sql);
if (DibiDriverException::catchError($msg)) { if (Dibi\DriverException::catchError($msg)) {
if (ibase_errcode() == self::ERROR_EXCEPTION_THROWN) { if (ibase_errcode() == self::ERROR_EXCEPTION_THROWN) {
preg_match('/exception (\d+) (\w+) (.*)/i', ibase_errmsg(), $match); preg_match('/exception (\d+) (\w+) (.*)/i', ibase_errmsg(), $match);
throw new DibiProcedureException($match[3], $match[1], $match[2], dibi::$sql); throw new Dibi\ProcedureException($match[3], $match[1], $match[2], \dibi::$sql);
} else { } else {
throw new DibiDriverException(ibase_errmsg(), ibase_errcode(), dibi::$sql); throw new Dibi\DriverException(ibase_errmsg(), ibase_errcode(), \dibi::$sql);
} }
} }
if ($res === FALSE) { if ($res === FALSE) {
throw new DibiDriverException(ibase_errmsg(), ibase_errcode(), $sql); throw new Dibi\DriverException(ibase_errmsg(), ibase_errcode(), $sql);
} elseif (is_resource($res)) { } elseif (is_resource($res)) {
return $this->createResultDriver($res); return $this->createResultDriver($res);
@@ -156,12 +160,12 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
* Begins a transaction (if supported). * Begins a transaction (if supported).
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function begin($savepoint = NULL) public function begin($savepoint = NULL)
{ {
if ($savepoint !== NULL) { if ($savepoint !== NULL) {
throw new DibiNotSupportedException('Savepoints are not supported in Firebird/Interbase.'); throw new Dibi\NotSupportedException('Savepoints are not supported in Firebird/Interbase.');
} }
$this->transaction = ibase_trans($this->getResource()); $this->transaction = ibase_trans($this->getResource());
$this->inTransaction = TRUE; $this->inTransaction = TRUE;
@@ -172,16 +176,16 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
* Commits statements in a transaction. * Commits statements in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function commit($savepoint = NULL) public function commit($savepoint = NULL)
{ {
if ($savepoint !== NULL) { if ($savepoint !== NULL) {
throw new DibiNotSupportedException('Savepoints are not supported in Firebird/Interbase.'); throw new Dibi\NotSupportedException('Savepoints are not supported in Firebird/Interbase.');
} }
if (!ibase_commit($this->transaction)) { if (!ibase_commit($this->transaction)) {
throw new DibiDriverException('Unable to handle operation - failure when commiting transaction.'); throw new Dibi\DriverException('Unable to handle operation - failure when commiting transaction.');
} }
$this->inTransaction = FALSE; $this->inTransaction = FALSE;
@@ -192,16 +196,16 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
* Rollback changes in a transaction. * Rollback changes in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function rollback($savepoint = NULL) public function rollback($savepoint = NULL)
{ {
if ($savepoint !== NULL) { if ($savepoint !== NULL) {
throw new DibiNotSupportedException('Savepoints are not supported in Firebird/Interbase.'); throw new Dibi\NotSupportedException('Savepoints are not supported in Firebird/Interbase.');
} }
if (!ibase_rollback($this->transaction)) { if (!ibase_rollback($this->transaction)) {
throw new DibiDriverException('Unable to handle operation - failure when rolbacking transaction.'); throw new Dibi\DriverException('Unable to handle operation - failure when rolbacking transaction.');
} }
$this->inTransaction = FALSE; $this->inTransaction = FALSE;
@@ -230,7 +234,7 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
/** /**
* Returns the connection reflector. * Returns the connection reflector.
* @return IDibiReflector * @return Dibi\Reflector
*/ */
public function getReflector() public function getReflector()
{ {
@@ -241,7 +245,7 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
/** /**
* Result set driver factory. * Result set driver factory.
* @param resource * @param resource
* @return IDibiResultDriver * @return Dibi\ResultDriver
*/ */
public function createResultDriver($resource) public function createResultDriver($resource)
{ {
@@ -285,8 +289,8 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
public function escapeDate($value) public function escapeDate($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format("'Y-m-d'"); return $value->format("'Y-m-d'");
} }
@@ -294,8 +298,8 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
public function escapeDateTime($value) public function escapeDateTime($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format("'Y-m-d H:i:s'"); return $value->format("'Y-m-d H:i:s'");
} }
@@ -309,7 +313,7 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
*/ */
public function escapeLike($value, $pos) public function escapeLike($value, $pos)
{ {
throw new DibiNotImplementedException; throw new Dibi\NotImplementedException;
} }
@@ -327,7 +331,7 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
/** @deprecated */ /** @deprecated */
public function escape($value, $type) public function escape($value, $type)
{ {
return DibiHelpers::escape($this, $value, $type); return Dibi\Helpers::escape($this, $value, $type);
} }
@@ -363,7 +367,7 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
*/ */
public function getRowCount() public function getRowCount()
{ {
throw new DibiNotSupportedException('Firebird/Interbase do not support returning number of rows in result set.'); throw new Dibi\NotSupportedException('Firebird/Interbase do not support returning number of rows in result set.');
} }
@@ -374,16 +378,16 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
*/ */
public function fetch($assoc) public function fetch($assoc)
{ {
DibiDriverException::tryError(); Dibi\DriverException::tryError();
$result = $assoc ? ibase_fetch_assoc($this->resultSet, IBASE_TEXT) : ibase_fetch_row($this->resultSet, IBASE_TEXT); // intentionally @ $result = $assoc ? ibase_fetch_assoc($this->resultSet, IBASE_TEXT) : ibase_fetch_row($this->resultSet, IBASE_TEXT); // intentionally @
if (DibiDriverException::catchError($msg)) { if (Dibi\DriverException::catchError($msg)) {
if (ibase_errcode() == self::ERROR_EXCEPTION_THROWN) { if (ibase_errcode() == self::ERROR_EXCEPTION_THROWN) {
preg_match('/exception (\d+) (\w+) (.*)/is', ibase_errmsg(), $match); preg_match('/exception (\d+) (\w+) (.*)/is', ibase_errmsg(), $match);
throw new DibiProcedureException($match[3], $match[1], $match[2], dibi::$sql); throw new Dibi\ProcedureException($match[3], $match[1], $match[2], \dibi::$sql);
} else { } else {
throw new DibiDriverException($msg, ibase_errcode(), dibi::$sql); throw new Dibi\DriverException($msg, ibase_errcode(), \dibi::$sql);
} }
} }
@@ -395,11 +399,11 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
* Moves cursor position without fetching row. * Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to * @param int the 0-based cursor pos to seek to
* @return bool TRUE on success, FALSE if unable to seek to specified record * @return bool TRUE on success, FALSE if unable to seek to specified record
* @throws DibiException * @throws Dibi\Exception
*/ */
public function seek($row) public function seek($row)
{ {
throw new DibiNotSupportedException('Firebird/Interbase do not support seek in result set.'); throw new Dibi\NotSupportedException('Firebird/Interbase do not support seek in result set.');
} }
@@ -446,7 +450,7 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
} }
/********************* IDibiReflector ********************/ /********************* Dibi\Reflector ********************/
/** /**

View File

@@ -5,6 +5,11 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Drivers;
use Dibi;
use Dibi\Connection;
/** /**
* The dibi driver for MS SQL Driver 2005 database. * The dibi driver for MS SQL Driver 2005 database.
@@ -17,11 +22,11 @@
* - options (array) => connection options {@link https://msdn.microsoft.com/en-us/library/cc296161(SQL.90).aspx} * - options (array) => connection options {@link https://msdn.microsoft.com/en-us/library/cc296161(SQL.90).aspx}
* - charset => character encoding to set (default is UTF-8) * - charset => character encoding to set (default is UTF-8)
* - resource (resource) => existing connection resource * - resource (resource) => existing connection resource
* - lazy, profiler, result, substitutes, ... => see DibiConnection options * - lazy, profiler, result, substitutes, ... => see Dibi\Connection options
*/ */
class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver class MsSql2005Driver implements Dibi\Driver, Dibi\ResultDriver
{ {
use DibiStrict; use Dibi\Strict;
/** @var resource Connection resource */ /** @var resource Connection resource */
private $connection; private $connection;
@@ -37,12 +42,12 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
/** /**
* @throws DibiNotSupportedException * @throws Dibi\NotSupportedException
*/ */
public function __construct() public function __construct()
{ {
if (!extension_loaded('sqlsrv')) { if (!extension_loaded('sqlsrv')) {
throw new DibiNotSupportedException("PHP extension 'sqlsrv' is not loaded."); throw new Dibi\NotSupportedException("PHP extension 'sqlsrv' is not loaded.");
} }
} }
@@ -50,14 +55,14 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
/** /**
* Connects to a database. * Connects to a database.
* @return void * @return void
* @throws DibiException * @throws Dibi\Exception
*/ */
public function connect(array & $config) public function connect(array & $config)
{ {
DibiConnection::alias($config, 'options|UID', 'username'); Connection::alias($config, 'options|UID', 'username');
DibiConnection::alias($config, 'options|PWD', 'password'); Connection::alias($config, 'options|PWD', 'password');
DibiConnection::alias($config, 'options|Database', 'database'); Connection::alias($config, 'options|Database', 'database');
DibiConnection::alias($config, 'options|CharacterSet', 'charset'); Connection::alias($config, 'options|CharacterSet', 'charset');
if (isset($config['resource'])) { if (isset($config['resource'])) {
$this->connection = $config['resource']; $this->connection = $config['resource'];
@@ -73,7 +78,7 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
if (!is_resource($this->connection)) { if (!is_resource($this->connection)) {
$info = sqlsrv_errors(); $info = sqlsrv_errors();
throw new DibiDriverException($info[0]['message'], $info[0]['code']); throw new Dibi\DriverException($info[0]['message'], $info[0]['code']);
} }
} }
@@ -91,8 +96,8 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
/** /**
* Executes the SQL query. * Executes the SQL query.
* @param string SQL statement. * @param string SQL statement.
* @return IDibiResultDriver|NULL * @return Dibi\ResultDriver|NULL
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function query($sql) public function query($sql)
{ {
@@ -101,7 +106,7 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
if ($res === FALSE) { if ($res === FALSE) {
$info = sqlsrv_errors(); $info = sqlsrv_errors();
throw new DibiDriverException($info[0]['message'], $info[0]['code'], $sql); throw new Dibi\DriverException($info[0]['message'], $info[0]['code'], $sql);
} elseif (is_resource($res)) { } elseif (is_resource($res)) {
$this->affectedRows = sqlsrv_rows_affected($res); $this->affectedRows = sqlsrv_rows_affected($res);
@@ -139,7 +144,7 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
* Begins a transaction (if supported). * Begins a transaction (if supported).
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function begin($savepoint = NULL) public function begin($savepoint = NULL)
{ {
@@ -151,7 +156,7 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
* Commits statements in a transaction. * Commits statements in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function commit($savepoint = NULL) public function commit($savepoint = NULL)
{ {
@@ -163,7 +168,7 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
* Rollback changes in a transaction. * Rollback changes in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function rollback($savepoint = NULL) public function rollback($savepoint = NULL)
{ {
@@ -183,18 +188,18 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
/** /**
* Returns the connection reflector. * Returns the connection reflector.
* @return IDibiReflector * @return Dibi\Reflector
*/ */
public function getReflector() public function getReflector()
{ {
return new DibiMssql2005Reflector($this); return new Mssql2005Reflector($this);
} }
/** /**
* Result set driver factory. * Result set driver factory.
* @param resource * @param resource
* @return IDibiResultDriver * @return Dibi\ResultDriver
*/ */
public function createResultDriver($resource) public function createResultDriver($resource)
{ {
@@ -239,8 +244,8 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
public function escapeDate($value) public function escapeDate($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format("'Y-m-d'"); return $value->format("'Y-m-d'");
} }
@@ -248,14 +253,13 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
public function escapeDateTime($value) public function escapeDateTime($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format("'Y-m-d H:i:s'"); return $value->format("'Y-m-d H:i:s'");
} }
/** /**
* Encodes string for use in a LIKE statement. * Encodes string for use in a LIKE statement.
* @param string * @param string
@@ -283,7 +287,7 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
/** @deprecated */ /** @deprecated */
public function escape($value, $type) public function escape($value, $type)
{ {
return DibiHelpers::escape($this, $value, $type); return Dibi\Helpers::escape($this, $value, $type);
} }
@@ -299,7 +303,7 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
} }
if ($offset) { if ($offset) {
throw new DibiNotImplementedException('Offset is not implemented.'); throw new Dibi\NotImplementedException('Offset is not implemented.');
} }
} }
@@ -323,7 +327,7 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
*/ */
public function getRowCount() public function getRowCount()
{ {
throw new DibiNotSupportedException('Row count is not available for unbuffered queries.'); throw new Dibi\NotSupportedException('Row count is not available for unbuffered queries.');
} }
@@ -345,7 +349,7 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
*/ */
public function seek($row) public function seek($row)
{ {
throw new DibiNotSupportedException('Cannot seek an unbuffered result set.'); throw new Dibi\NotSupportedException('Cannot seek an unbuffered result set.');
} }

View File

@@ -5,20 +5,24 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Drivers;
use Dibi;
/** /**
* The dibi reflector for MSSQL2005 databases. * The dibi reflector for MSSQL2005 databases.
* @internal * @internal
*/ */
class DibiMsSql2005Reflector implements IDibiReflector class MsSql2005Reflector implements Dibi\Reflector
{ {
use DibiStrict; use Dibi\Strict;
/** @var IDibiDriver */ /** @var Dibi\Driver */
private $driver; private $driver;
public function __construct(IDibiDriver $driver) public function __construct(Dibi\Driver $driver)
{ {
$this->driver = $driver; $this->driver = $driver;
} }
@@ -126,7 +130,7 @@ class DibiMsSql2005Reflector implements IDibiReflector
*/ */
public function getForeignKeys($table) public function getForeignKeys($table)
{ {
throw new DibiNotImplementedException; throw new Dibi\NotImplementedException;
} }
} }

View File

@@ -5,6 +5,10 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Drivers;
use Dibi;
/** /**
* The dibi driver for MS SQL database. * The dibi driver for MS SQL database.
@@ -16,11 +20,11 @@
* - database => the database name to select * - database => the database name to select
* - persistent (bool) => try to find a persistent link? * - persistent (bool) => try to find a persistent link?
* - resource (resource) => existing connection resource * - resource (resource) => existing connection resource
* - lazy, profiler, result, substitutes, ... => see DibiConnection options * - lazy, profiler, result, substitutes, ... => see Dibi\Connection options
*/ */
class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver class MsSqlDriver implements Dibi\Driver, Dibi\ResultDriver
{ {
use DibiStrict; use Dibi\Strict;
/** @var resource Connection resource */ /** @var resource Connection resource */
private $connection; private $connection;
@@ -33,12 +37,12 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
/** /**
* @throws DibiNotSupportedException * @throws Dibi\NotSupportedException
*/ */
public function __construct() public function __construct()
{ {
if (!extension_loaded('mssql')) { if (!extension_loaded('mssql')) {
throw new DibiNotSupportedException("PHP extension 'mssql' is not loaded."); throw new Dibi\NotSupportedException("PHP extension 'mssql' is not loaded.");
} }
} }
@@ -46,7 +50,7 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
/** /**
* Connects to a database. * Connects to a database.
* @return void * @return void
* @throws DibiException * @throws Dibi\Exception
*/ */
public function connect(array & $config) public function connect(array & $config)
{ {
@@ -59,11 +63,11 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
} }
if (!is_resource($this->connection)) { if (!is_resource($this->connection)) {
throw new DibiDriverException("Can't connect to DB."); throw new Dibi\DriverException("Can't connect to DB.");
} }
if (isset($config['database']) && !@mssql_select_db($this->escapeIdentifier($config['database']), $this->connection)) { // intentionally @ if (isset($config['database']) && !@mssql_select_db($this->escapeIdentifier($config['database']), $this->connection)) { // intentionally @
throw new DibiDriverException("Can't select DB '$config[database]'."); throw new Dibi\DriverException("Can't select DB '$config[database]'.");
} }
} }
@@ -81,15 +85,15 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
/** /**
* Executes the SQL query. * Executes the SQL query.
* @param string SQL statement. * @param string SQL statement.
* @return IDibiResultDriver|NULL * @return Dibi\ResultDriver|NULL
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function query($sql) public function query($sql)
{ {
$res = @mssql_query($sql, $this->connection); // intentionally @ $res = @mssql_query($sql, $this->connection); // intentionally @
if ($res === FALSE) { if ($res === FALSE) {
throw new DibiDriverException(mssql_get_last_message(), 0, $sql); throw new Dibi\DriverException(mssql_get_last_message(), 0, $sql);
} elseif (is_resource($res)) { } elseif (is_resource($res)) {
return $this->createResultDriver($res); return $this->createResultDriver($res);
@@ -126,7 +130,7 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
* Begins a transaction (if supported). * Begins a transaction (if supported).
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function begin($savepoint = NULL) public function begin($savepoint = NULL)
{ {
@@ -138,7 +142,7 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
* Commits statements in a transaction. * Commits statements in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function commit($savepoint = NULL) public function commit($savepoint = NULL)
{ {
@@ -150,7 +154,7 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
* Rollback changes in a transaction. * Rollback changes in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function rollback($savepoint = NULL) public function rollback($savepoint = NULL)
{ {
@@ -170,18 +174,18 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
/** /**
* Returns the connection reflector. * Returns the connection reflector.
* @return IDibiReflector * @return Dibi\Reflector
*/ */
public function getReflector() public function getReflector()
{ {
return new DibiMsSqlReflector($this); return new MsSqlReflector($this);
} }
/** /**
* Result set driver factory. * Result set driver factory.
* @param resource * @param resource
* @return IDibiResultDriver * @return Dibi\ResultDriver
*/ */
public function createResultDriver($resource) public function createResultDriver($resource)
{ {
@@ -226,8 +230,8 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
public function escapeDate($value) public function escapeDate($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format("'Y-m-d'"); return $value->format("'Y-m-d'");
} }
@@ -235,8 +239,8 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
public function escapeDateTime($value) public function escapeDateTime($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format("'Y-m-d H:i:s'"); return $value->format("'Y-m-d H:i:s'");
} }
@@ -269,7 +273,7 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
/** @deprecated */ /** @deprecated */
public function escape($value, $type) public function escape($value, $type)
{ {
return DibiHelpers::escape($this, $value, $type); return Dibi\Helpers::escape($this, $value, $type);
} }
@@ -285,7 +289,7 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
} }
if ($offset) { if ($offset) {
throw new DibiNotImplementedException('Offset is not implemented.'); throw new Dibi\NotImplementedException('Offset is not implemented.');
} }
} }

View File

@@ -5,20 +5,24 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Drivers;
use Dibi;
/** /**
* The dibi reflector for MsSQL databases. * The dibi reflector for MsSQL databases.
* @internal * @internal
*/ */
class DibiMsSqlReflector implements IDibiReflector class MsSqlReflector implements Dibi\Reflector
{ {
use DibiStrict; use Dibi\Strict;
/** @var IDibiDriver */ /** @var Dibi\Driver */
private $driver; private $driver;
public function __construct(IDibiDriver $driver) public function __construct(Dibi\Driver $driver)
{ {
$this->driver = $driver; $this->driver = $driver;
} }

View File

@@ -5,6 +5,10 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Drivers;
use Dibi;
/** /**
* The dibi driver for MySQL database. * The dibi driver for MySQL database.
@@ -22,11 +26,11 @@
* - unbuffered (bool) => sends query without fetching and buffering the result rows automatically? * - unbuffered (bool) => sends query without fetching and buffering the result rows automatically?
* - sqlmode => see http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html * - sqlmode => see http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html
* - resource (resource) => existing connection resource * - resource (resource) => existing connection resource
* - lazy, profiler, result, substitutes, ... => see DibiConnection options * - lazy, profiler, result, substitutes, ... => see Dibi\Connection options
*/ */
class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver class MySqlDriver implements Dibi\Driver, Dibi\ResultDriver
{ {
use DibiStrict; use Dibi\Strict;
const ERROR_ACCESS_DENIED = 1045; const ERROR_ACCESS_DENIED = 1045;
const ERROR_DUPLICATE_ENTRY = 1062; const ERROR_DUPLICATE_ENTRY = 1062;
@@ -46,12 +50,12 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
/** /**
* @throws DibiNotSupportedException * @throws Dibi\NotSupportedException
*/ */
public function __construct() public function __construct()
{ {
if (!extension_loaded('mysql')) { if (!extension_loaded('mysql')) {
throw new DibiNotSupportedException("PHP extension 'mysql' is not loaded."); throw new Dibi\NotSupportedException("PHP extension 'mysql' is not loaded.");
} }
} }
@@ -59,7 +63,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
/** /**
* Connects to a database. * Connects to a database.
* @return void * @return void
* @throws DibiException * @throws Dibi\Exception
*/ */
public function connect(array & $config) public function connect(array & $config)
{ {
@@ -68,7 +72,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
} else { } else {
// default values // default values
DibiConnection::alias($config, 'flags', 'options'); Dibi\Connection::alias($config, 'flags', 'options');
$config += [ $config += [
'charset' => 'utf8', 'charset' => 'utf8',
'timezone' => date('P'), 'timezone' => date('P'),
@@ -102,7 +106,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
} }
if (!is_resource($this->connection)) { if (!is_resource($this->connection)) {
throw new DibiDriverException(mysql_error(), mysql_errno()); throw new Dibi\DriverException(mysql_error(), mysql_errno());
} }
if (isset($config['charset'])) { if (isset($config['charset'])) {
@@ -113,7 +117,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
if (isset($config['database'])) { if (isset($config['database'])) {
if (!@mysql_select_db($config['database'], $this->connection)) { // intentionally @ if (!@mysql_select_db($config['database'], $this->connection)) { // intentionally @
throw new DibiDriverException(mysql_error($this->connection), mysql_errno($this->connection)); throw new Dibi\DriverException(mysql_error($this->connection), mysql_errno($this->connection));
} }
} }
@@ -142,8 +146,8 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
/** /**
* Executes the SQL query. * Executes the SQL query.
* @param string SQL statement. * @param string SQL statement.
* @return IDibiResultDriver|NULL * @return Dibi\ResultDriver|NULL
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function query($sql) public function query($sql)
{ {
@@ -154,7 +158,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
} }
if (mysql_errno($this->connection)) { if (mysql_errno($this->connection)) {
throw new DibiDriverException(mysql_error($this->connection), mysql_errno($this->connection), $sql); throw new Dibi\DriverException(mysql_error($this->connection), mysql_errno($this->connection), $sql);
} elseif (is_resource($res)) { } elseif (is_resource($res)) {
return $this->createResultDriver($res); return $this->createResultDriver($res);
@@ -171,7 +175,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
$res = []; $res = [];
preg_match_all('#(.+?): +(\d+) *#', mysql_info($this->connection), $matches, PREG_SET_ORDER); preg_match_all('#(.+?): +(\d+) *#', mysql_info($this->connection), $matches, PREG_SET_ORDER);
if (preg_last_error()) { if (preg_last_error()) {
throw new DibiPcreException; throw new Dibi\PcreException;
} }
foreach ($matches as $m) { foreach ($matches as $m) {
@@ -205,7 +209,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
* Begins a transaction (if supported). * Begins a transaction (if supported).
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function begin($savepoint = NULL) public function begin($savepoint = NULL)
{ {
@@ -217,7 +221,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
* Commits statements in a transaction. * Commits statements in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function commit($savepoint = NULL) public function commit($savepoint = NULL)
{ {
@@ -229,7 +233,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
* Rollback changes in a transaction. * Rollback changes in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function rollback($savepoint = NULL) public function rollback($savepoint = NULL)
{ {
@@ -249,18 +253,18 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
/** /**
* Returns the connection reflector. * Returns the connection reflector.
* @return IDibiReflector * @return Dibi\Reflector
*/ */
public function getReflector() public function getReflector()
{ {
return new DibiMySqlReflector($this); return new MySqlReflector($this);
} }
/** /**
* Result set driver factory. * Result set driver factory.
* @param resource * @param resource
* @return IDibiResultDriver * @return Dibi\ResultDriver
*/ */
public function createResultDriver($resource) public function createResultDriver($resource)
{ {
@@ -311,8 +315,8 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
public function escapeDate($value) public function escapeDate($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format("'Y-m-d'"); return $value->format("'Y-m-d'");
} }
@@ -320,8 +324,8 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
public function escapeDateTime($value) public function escapeDateTime($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format("'Y-m-d H:i:s'"); return $value->format("'Y-m-d H:i:s'");
} }
@@ -354,7 +358,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
/** @deprecated */ /** @deprecated */
public function escape($value, $type) public function escape($value, $type)
{ {
return DibiHelpers::escape($this, $value, $type); return Dibi\Helpers::escape($this, $value, $type);
} }
@@ -392,7 +396,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
public function getRowCount() public function getRowCount()
{ {
if (!$this->buffered) { if (!$this->buffered) {
throw new DibiNotSupportedException('Row count is not available for unbuffered queries.'); throw new Dibi\NotSupportedException('Row count is not available for unbuffered queries.');
} }
return mysql_num_rows($this->resultSet); return mysql_num_rows($this->resultSet);
} }
@@ -413,12 +417,12 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
* Moves cursor position without fetching row. * Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to * @param int the 0-based cursor pos to seek to
* @return bool TRUE on success, FALSE if unable to seek to specified record * @return bool TRUE on success, FALSE if unable to seek to specified record
* @throws DibiException * @throws Dibi\Exception
*/ */
public function seek($row) public function seek($row)
{ {
if (!$this->buffered) { if (!$this->buffered) {
throw new DibiNotSupportedException('Cannot seek an unbuffered result set.'); throw new Dibi\NotSupportedException('Cannot seek an unbuffered result set.');
} }
return mysql_data_seek($this->resultSet, $row); return mysql_data_seek($this->resultSet, $row);

View File

@@ -5,20 +5,24 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Drivers;
use Dibi;
/** /**
* The dibi reflector for MySQL databases. * The dibi reflector for MySQL databases.
* @internal * @internal
*/ */
class DibiMySqlReflector implements IDibiReflector class MySqlReflector implements Dibi\Reflector
{ {
use DibiStrict; use Dibi\Strict;
/** @var IDibiDriver */ /** @var Dibi\Driver */
private $driver; private $driver;
public function __construct(IDibiDriver $driver) public function __construct(Dibi\Driver $driver)
{ {
$this->driver = $driver; $this->driver = $driver;
} }
@@ -110,13 +114,13 @@ class DibiMySqlReflector implements IDibiReflector
* Returns metadata for all foreign keys in a table. * Returns metadata for all foreign keys in a table.
* @param string * @param string
* @return array * @return array
* @throws DibiNotSupportedException * @throws Dibi\NotSupportedException
*/ */
public function getForeignKeys($table) public function getForeignKeys($table)
{ {
$data = $this->driver->query("SELECT `ENGINE` FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = {$this->driver->escapeText($table)}")->fetch(TRUE); $data = $this->driver->query("SELECT `ENGINE` FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = {$this->driver->escapeText($table)}")->fetch(TRUE);
if ($data['ENGINE'] !== 'InnoDB') { if ($data['ENGINE'] !== 'InnoDB') {
throw new DibiNotSupportedException("Foreign keys are not supported in {$data['ENGINE']} tables."); throw new Dibi\NotSupportedException("Foreign keys are not supported in {$data['ENGINE']} tables.");
} }
$res = $this->driver->query(" $res = $this->driver->query("

View File

@@ -5,6 +5,10 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Drivers;
use Dibi;
/** /**
* The dibi driver for MySQL database via improved extension. * The dibi driver for MySQL database via improved extension.
@@ -23,11 +27,11 @@
* - unbuffered (bool) => sends query without fetching and buffering the result rows automatically? * - unbuffered (bool) => sends query without fetching and buffering the result rows automatically?
* - sqlmode => see http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html * - sqlmode => see http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html
* - resource (mysqli) => existing connection resource * - resource (mysqli) => existing connection resource
* - lazy, profiler, result, substitutes, ... => see DibiConnection options * - lazy, profiler, result, substitutes, ... => see Dibi\Connection options
*/ */
class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver class MySqliDriver implements Dibi\Driver, Dibi\ResultDriver
{ {
use DibiStrict; use Dibi\Strict;
const ERROR_ACCESS_DENIED = 1045; const ERROR_ACCESS_DENIED = 1045;
const ERROR_DUPLICATE_ENTRY = 1062; const ERROR_DUPLICATE_ENTRY = 1062;
@@ -47,12 +51,12 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
/** /**
* @throws DibiNotSupportedException * @throws Dibi\NotSupportedException
*/ */
public function __construct() public function __construct()
{ {
if (!extension_loaded('mysqli')) { if (!extension_loaded('mysqli')) {
throw new DibiNotSupportedException("PHP extension 'mysqli' is not loaded."); throw new Dibi\NotSupportedException("PHP extension 'mysqli' is not loaded.");
} }
} }
@@ -60,7 +64,7 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
/** /**
* Connects to a database. * Connects to a database.
* @return void * @return void
* @throws DibiException * @throws Dibi\Exception
*/ */
public function connect(array & $config) public function connect(array & $config)
{ {
@@ -106,7 +110,7 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
@mysqli_real_connect($this->connection, (empty($config['persistent']) ? '' : 'p:') . $config['host'], $config['username'], $config['password'], $config['database'], $config['port'], $config['socket'], $config['flags']); // intentionally @ @mysqli_real_connect($this->connection, (empty($config['persistent']) ? '' : 'p:') . $config['host'], $config['username'], $config['password'], $config['database'], $config['port'], $config['socket'], $config['flags']); // intentionally @
if ($errno = mysqli_connect_errno()) { if ($errno = mysqli_connect_errno()) {
throw new DibiDriverException(mysqli_connect_error(), $errno); throw new Dibi\DriverException(mysqli_connect_error(), $errno);
} }
} }
@@ -141,15 +145,15 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
/** /**
* Executes the SQL query. * Executes the SQL query.
* @param string SQL statement. * @param string SQL statement.
* @return IDibiResultDriver|NULL * @return Dibi\ResultDriver|NULL
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function query($sql) public function query($sql)
{ {
$res = @mysqli_query($this->connection, $sql, $this->buffered ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT); // intentionally @ $res = @mysqli_query($this->connection, $sql, $this->buffered ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT); // intentionally @
if (mysqli_errno($this->connection)) { if (mysqli_errno($this->connection)) {
throw new DibiDriverException(mysqli_error($this->connection), mysqli_errno($this->connection), $sql); throw new Dibi\DriverException(mysqli_error($this->connection), mysqli_errno($this->connection), $sql);
} elseif (is_object($res)) { } elseif (is_object($res)) {
return $this->createResultDriver($res); return $this->createResultDriver($res);
@@ -166,7 +170,7 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
$res = []; $res = [];
preg_match_all('#(.+?): +(\d+) *#', mysqli_info($this->connection), $matches, PREG_SET_ORDER); preg_match_all('#(.+?): +(\d+) *#', mysqli_info($this->connection), $matches, PREG_SET_ORDER);
if (preg_last_error()) { if (preg_last_error()) {
throw new DibiPcreException; throw new Dibi\PcreException;
} }
foreach ($matches as $m) { foreach ($matches as $m) {
@@ -200,7 +204,7 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
* Begins a transaction (if supported). * Begins a transaction (if supported).
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function begin($savepoint = NULL) public function begin($savepoint = NULL)
{ {
@@ -212,7 +216,7 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
* Commits statements in a transaction. * Commits statements in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function commit($savepoint = NULL) public function commit($savepoint = NULL)
{ {
@@ -224,7 +228,7 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
* Rollback changes in a transaction. * Rollback changes in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function rollback($savepoint = NULL) public function rollback($savepoint = NULL)
{ {
@@ -244,20 +248,20 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
/** /**
* Returns the connection reflector. * Returns the connection reflector.
* @return IDibiReflector * @return Dibi\Reflector
*/ */
public function getReflector() public function getReflector()
{ {
return new DibiMySqlReflector($this); return new MySqlReflector($this);
} }
/** /**
* Result set driver factory. * Result set driver factory.
* @param mysqli_result * @param mysqli_result
* @return IDibiResultDriver * @return Dibi\ResultDriver
*/ */
public function createResultDriver(mysqli_result $resource) public function createResultDriver(\mysqli_result $resource)
{ {
$res = clone $this; $res = clone $this;
$res->resultSet = $resource; $res->resultSet = $resource;
@@ -299,8 +303,8 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
public function escapeDate($value) public function escapeDate($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format("'Y-m-d'"); return $value->format("'Y-m-d'");
} }
@@ -308,8 +312,8 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
public function escapeDateTime($value) public function escapeDateTime($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format("'Y-m-d H:i:s'"); return $value->format("'Y-m-d H:i:s'");
} }
@@ -342,7 +346,7 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
/** @deprecated */ /** @deprecated */
public function escape($value, $type) public function escape($value, $type)
{ {
return DibiHelpers::escape($this, $value, $type); return Dibi\Helpers::escape($this, $value, $type);
} }
@@ -380,7 +384,7 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
public function getRowCount() public function getRowCount()
{ {
if (!$this->buffered) { if (!$this->buffered) {
throw new DibiNotSupportedException('Row count is not available for unbuffered queries.'); throw new Dibi\NotSupportedException('Row count is not available for unbuffered queries.');
} }
return mysqli_num_rows($this->resultSet); return mysqli_num_rows($this->resultSet);
} }
@@ -401,12 +405,12 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
* Moves cursor position without fetching row. * Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to * @param int the 0-based cursor pos to seek to
* @return bool TRUE on success, FALSE if unable to seek to specified record * @return bool TRUE on success, FALSE if unable to seek to specified record
* @throws DibiException * @throws Dibi\Exception
*/ */
public function seek($row) public function seek($row)
{ {
if (!$this->buffered) { if (!$this->buffered) {
throw new DibiNotSupportedException('Cannot seek an unbuffered result set.'); throw new Dibi\NotSupportedException('Cannot seek an unbuffered result set.');
} }
return mysqli_data_seek($this->resultSet, $row); return mysqli_data_seek($this->resultSet, $row);
} }

View File

@@ -5,6 +5,10 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Drivers;
use Dibi;
/** /**
* The dibi driver interacting with databases via ODBC connections. * The dibi driver interacting with databases via ODBC connections.
@@ -15,11 +19,11 @@
* - password (or pass) * - password (or pass)
* - persistent (bool) => try to find a persistent link? * - persistent (bool) => try to find a persistent link?
* - resource (resource) => existing connection resource * - resource (resource) => existing connection resource
* - lazy, profiler, result, substitutes, ... => see DibiConnection options * - lazy, profiler, result, substitutes, ... => see Dibi\Connection options
*/ */
class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector class OdbcDriver implements Dibi\Driver, Dibi\ResultDriver, Dibi\Reflector
{ {
use DibiStrict; use Dibi\Strict;
/** @var resource Connection resource */ /** @var resource Connection resource */
private $connection; private $connection;
@@ -38,12 +42,12 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/** /**
* @throws DibiNotSupportedException * @throws Dibi\NotSupportedException
*/ */
public function __construct() public function __construct()
{ {
if (!extension_loaded('odbc')) { if (!extension_loaded('odbc')) {
throw new DibiNotSupportedException("PHP extension 'odbc' is not loaded."); throw new Dibi\NotSupportedException("PHP extension 'odbc' is not loaded.");
} }
} }
@@ -51,7 +55,7 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/** /**
* Connects to a database. * Connects to a database.
* @return void * @return void
* @throws DibiException * @throws Dibi\Exception
*/ */
public function connect(array & $config) public function connect(array & $config)
{ {
@@ -73,7 +77,7 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
} }
if (!is_resource($this->connection)) { if (!is_resource($this->connection)) {
throw new DibiDriverException(odbc_errormsg() . ' ' . odbc_error()); throw new Dibi\DriverException(odbc_errormsg() . ' ' . odbc_error());
} }
} }
@@ -91,8 +95,8 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/** /**
* Executes the SQL query. * Executes the SQL query.
* @param string SQL statement. * @param string SQL statement.
* @return IDibiResultDriver|NULL * @return Dibi\ResultDriver|NULL
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function query($sql) public function query($sql)
{ {
@@ -100,7 +104,7 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
$res = @odbc_exec($this->connection, $sql); // intentionally @ $res = @odbc_exec($this->connection, $sql); // intentionally @
if ($res === FALSE) { if ($res === FALSE) {
throw new DibiDriverException(odbc_errormsg($this->connection) . ' ' . odbc_error($this->connection), 0, $sql); throw new Dibi\DriverException(odbc_errormsg($this->connection) . ' ' . odbc_error($this->connection), 0, $sql);
} elseif (is_resource($res)) { } elseif (is_resource($res)) {
$this->affectedRows = odbc_num_rows($res); $this->affectedRows = odbc_num_rows($res);
@@ -125,7 +129,7 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
*/ */
public function getInsertId($sequence) public function getInsertId($sequence)
{ {
throw new DibiNotSupportedException('ODBC does not support autoincrementing.'); throw new Dibi\NotSupportedException('ODBC does not support autoincrementing.');
} }
@@ -133,12 +137,12 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
* Begins a transaction (if supported). * Begins a transaction (if supported).
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function begin($savepoint = NULL) public function begin($savepoint = NULL)
{ {
if (!odbc_autocommit($this->connection, FALSE)) { if (!odbc_autocommit($this->connection, FALSE)) {
throw new DibiDriverException(odbc_errormsg($this->connection) . ' ' . odbc_error($this->connection)); throw new Dibi\DriverException(odbc_errormsg($this->connection) . ' ' . odbc_error($this->connection));
} }
} }
@@ -147,12 +151,12 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
* Commits statements in a transaction. * Commits statements in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function commit($savepoint = NULL) public function commit($savepoint = NULL)
{ {
if (!odbc_commit($this->connection)) { if (!odbc_commit($this->connection)) {
throw new DibiDriverException(odbc_errormsg($this->connection) . ' ' . odbc_error($this->connection)); throw new Dibi\DriverException(odbc_errormsg($this->connection) . ' ' . odbc_error($this->connection));
} }
odbc_autocommit($this->connection, TRUE); odbc_autocommit($this->connection, TRUE);
} }
@@ -162,12 +166,12 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
* Rollback changes in a transaction. * Rollback changes in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function rollback($savepoint = NULL) public function rollback($savepoint = NULL)
{ {
if (!odbc_rollback($this->connection)) { if (!odbc_rollback($this->connection)) {
throw new DibiDriverException(odbc_errormsg($this->connection) . ' ' . odbc_error($this->connection)); throw new Dibi\DriverException(odbc_errormsg($this->connection) . ' ' . odbc_error($this->connection));
} }
odbc_autocommit($this->connection, TRUE); odbc_autocommit($this->connection, TRUE);
} }
@@ -195,7 +199,7 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/** /**
* Returns the connection reflector. * Returns the connection reflector.
* @return IDibiReflector * @return Dibi\Reflector
*/ */
public function getReflector() public function getReflector()
{ {
@@ -206,7 +210,7 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/** /**
* Result set driver factory. * Result set driver factory.
* @param resource * @param resource
* @return IDibiResultDriver * @return Dibi\ResultDriver
*/ */
public function createResultDriver($resource) public function createResultDriver($resource)
{ {
@@ -250,8 +254,8 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
public function escapeDate($value) public function escapeDate($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format("#m/d/Y#"); return $value->format("#m/d/Y#");
} }
@@ -259,8 +263,8 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
public function escapeDateTime($value) public function escapeDateTime($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format("#m/d/Y H:i:s#"); return $value->format("#m/d/Y H:i:s#");
} }
@@ -293,7 +297,7 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/** @deprecated */ /** @deprecated */
public function escape($value, $type) public function escape($value, $type)
{ {
return DibiHelpers::escape($this, $value, $type); return Dibi\Helpers::escape($this, $value, $type);
} }
@@ -309,7 +313,7 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
} }
if ($offset) { if ($offset) {
throw new DibiNotSupportedException('Offset is not implemented in driver odbc.'); throw new Dibi\NotSupportedException('Offset is not implemented in driver odbc.');
} }
} }
@@ -416,7 +420,7 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
} }
/********************* IDibiReflector ****************d*g**/ /********************* Dibi\Reflector ****************d*g**/
/** /**
@@ -473,7 +477,7 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
*/ */
public function getIndexes($table) public function getIndexes($table)
{ {
throw new DibiNotImplementedException; throw new Dibi\NotImplementedException;
} }
@@ -484,7 +488,7 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
*/ */
public function getForeignKeys($table) public function getForeignKeys($table)
{ {
throw new DibiNotImplementedException; throw new Dibi\NotImplementedException;
} }
} }

View File

@@ -5,6 +5,10 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Drivers;
use Dibi;
/** /**
* The dibi driver for Oracle database. * The dibi driver for Oracle database.
@@ -19,11 +23,11 @@
* - formatDateTime => how to format datetime in SQL (@see date) * - formatDateTime => how to format datetime in SQL (@see date)
* - resource (resource) => existing connection resource * - resource (resource) => existing connection resource
* - persistent => Creates persistent connections with oci_pconnect instead of oci_new_connect * - persistent => Creates persistent connections with oci_pconnect instead of oci_new_connect
* - lazy, profiler, result, substitutes, ... => see DibiConnection options * - lazy, profiler, result, substitutes, ... => see Dibi\Connection options
*/ */
class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector class OracleDriver implements Dibi\Driver, Dibi\ResultDriver, Dibi\Reflector
{ {
use DibiStrict; use Dibi\Strict;
/** @var resource Connection resource */ /** @var resource Connection resource */
private $connection; private $connection;
@@ -42,12 +46,12 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/** /**
* @throws DibiNotSupportedException * @throws Dibi\NotSupportedException
*/ */
public function __construct() public function __construct()
{ {
if (!extension_loaded('oci8')) { if (!extension_loaded('oci8')) {
throw new DibiNotSupportedException("PHP extension 'oci8' is not loaded."); throw new Dibi\NotSupportedException("PHP extension 'oci8' is not loaded.");
} }
} }
@@ -55,7 +59,7 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/** /**
* Connects to a database. * Connects to a database.
* @return void * @return void
* @throws DibiException * @throws Dibi\Exception
*/ */
public function connect(array & $config) public function connect(array & $config)
{ {
@@ -73,7 +77,7 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
if (!$this->connection) { if (!$this->connection) {
$err = oci_error(); $err = oci_error();
throw new DibiDriverException($err['message'], $err['code']); throw new Dibi\DriverException($err['message'], $err['code']);
} }
if (isset($config['schema'])) { if (isset($config['schema'])) {
@@ -95,8 +99,8 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/** /**
* Executes the SQL query. * Executes the SQL query.
* @param string SQL statement. * @param string SQL statement.
* @return IDibiResultDriver|NULL * @return Dibi\ResultDriver|NULL
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function query($sql) public function query($sql)
{ {
@@ -105,14 +109,14 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
@oci_execute($res, $this->autocommit ? OCI_COMMIT_ON_SUCCESS : OCI_DEFAULT); @oci_execute($res, $this->autocommit ? OCI_COMMIT_ON_SUCCESS : OCI_DEFAULT);
$err = oci_error($res); $err = oci_error($res);
if ($err) { if ($err) {
throw new DibiDriverException($err['message'], $err['code'], $sql); throw new Dibi\DriverException($err['message'], $err['code'], $sql);
} elseif (is_resource($res)) { } elseif (is_resource($res)) {
return $this->createResultDriver($res); return $this->createResultDriver($res);
} }
} else { } else {
$err = oci_error($this->connection); $err = oci_error($this->connection);
throw new DibiDriverException($err['message'], $err['code'], $sql); throw new Dibi\DriverException($err['message'], $err['code'], $sql);
} }
} }
@@ -123,7 +127,7 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
*/ */
public function getAffectedRows() public function getAffectedRows()
{ {
throw new DibiNotImplementedException; throw new Dibi\NotImplementedException;
} }
@@ -153,13 +157,13 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
* Commits statements in a transaction. * Commits statements in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function commit($savepoint = NULL) public function commit($savepoint = NULL)
{ {
if (!oci_commit($this->connection)) { if (!oci_commit($this->connection)) {
$err = oci_error($this->connection); $err = oci_error($this->connection);
throw new DibiDriverException($err['message'], $err['code']); throw new Dibi\DriverException($err['message'], $err['code']);
} }
$this->autocommit = TRUE; $this->autocommit = TRUE;
} }
@@ -169,13 +173,13 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
* Rollback changes in a transaction. * Rollback changes in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function rollback($savepoint = NULL) public function rollback($savepoint = NULL)
{ {
if (!oci_rollback($this->connection)) { if (!oci_rollback($this->connection)) {
$err = oci_error($this->connection); $err = oci_error($this->connection);
throw new DibiDriverException($err['message'], $err['code']); throw new Dibi\DriverException($err['message'], $err['code']);
} }
$this->autocommit = TRUE; $this->autocommit = TRUE;
} }
@@ -193,7 +197,7 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/** /**
* Returns the connection reflector. * Returns the connection reflector.
* @return IDibiReflector * @return Dibi\Reflector
*/ */
public function getReflector() public function getReflector()
{ {
@@ -204,7 +208,7 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/** /**
* Result set driver factory. * Result set driver factory.
* @param resource * @param resource
* @return IDibiResultDriver * @return Dibi\ResultDriver
*/ */
public function createResultDriver($resource) public function createResultDriver($resource)
{ {
@@ -249,8 +253,8 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
public function escapeDate($value) public function escapeDate($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format($this->fmtDate); return $value->format($this->fmtDate);
} }
@@ -258,8 +262,8 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
public function escapeDateTime($value) public function escapeDateTime($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format($this->fmtDateTime); return $value->format($this->fmtDateTime);
} }
@@ -293,7 +297,7 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/** @deprecated */ /** @deprecated */
public function escape($value, $type) public function escape($value, $type)
{ {
return DibiHelpers::escape($this, $value, $type); return Dibi\Helpers::escape($this, $value, $type);
} }
@@ -334,7 +338,7 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
*/ */
public function getRowCount() public function getRowCount()
{ {
throw new DibiNotSupportedException('Row count is not available for unbuffered queries.'); throw new Dibi\NotSupportedException('Row count is not available for unbuffered queries.');
} }
@@ -356,7 +360,7 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
*/ */
public function seek($row) public function seek($row)
{ {
throw new DibiNotImplementedException; throw new Dibi\NotImplementedException;
} }
@@ -403,7 +407,7 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
} }
/********************* IDibiReflector ****************d*g**/ /********************* Dibi\Reflector ****************d*g**/
/** /**
@@ -433,7 +437,7 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
*/ */
public function getColumns($table) public function getColumns($table)
{ {
throw new DibiNotImplementedException; throw new Dibi\NotImplementedException;
} }
@@ -444,7 +448,7 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
*/ */
public function getIndexes($table) public function getIndexes($table)
{ {
throw new DibiNotImplementedException; throw new Dibi\NotImplementedException;
} }
@@ -455,7 +459,7 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
*/ */
public function getForeignKeys($table) public function getForeignKeys($table)
{ {
throw new DibiNotImplementedException; throw new Dibi\NotImplementedException;
} }
} }

View File

@@ -5,6 +5,11 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Drivers;
use Dibi;
use PDO;
/** /**
* The dibi driver for PDO. * The dibi driver for PDO.
@@ -16,16 +21,16 @@
* - options (array) => driver specific options {@see PDO::__construct} * - options (array) => driver specific options {@see PDO::__construct}
* - resource (PDO) => existing connection * - resource (PDO) => existing connection
* - version * - version
* - lazy, profiler, result, substitutes, ... => see DibiConnection options * - lazy, profiler, result, substitutes, ... => see Dibi\Connection options
*/ */
class DibiPdoDriver implements IDibiDriver, IDibiResultDriver class PdoDriver implements Dibi\Driver, Dibi\ResultDriver
{ {
use DibiStrict; use Dibi\Strict;
/** @var PDO Connection resource */ /** @var PDO Connection resource */
private $connection; private $connection;
/** @var PDOStatement Resultset resource */ /** @var \PDOStatement Resultset resource */
private $resultSet; private $resultSet;
/** @var int|FALSE Affected rows */ /** @var int|FALSE Affected rows */
@@ -39,12 +44,12 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
/** /**
* @throws DibiNotSupportedException * @throws Dibi\NotSupportedException
*/ */
public function __construct() public function __construct()
{ {
if (!extension_loaded('pdo')) { if (!extension_loaded('pdo')) {
throw new DibiNotSupportedException("PHP extension 'pdo' is not loaded."); throw new Dibi\NotSupportedException("PHP extension 'pdo' is not loaded.");
} }
} }
@@ -52,13 +57,13 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
/** /**
* Connects to a database. * Connects to a database.
* @return void * @return void
* @throws DibiException * @throws Dibi\Exception
*/ */
public function connect(array & $config) public function connect(array & $config)
{ {
$foo = & $config['dsn']; $foo = & $config['dsn'];
$foo = & $config['options']; $foo = & $config['options'];
DibiConnection::alias($config, 'resource', 'pdo'); Dibi\Connection::alias($config, 'resource', 'pdo');
if ($config['resource'] instanceof PDO) { if ($config['resource'] instanceof PDO) {
$this->connection = $config['resource']; $this->connection = $config['resource'];
@@ -66,11 +71,11 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
} else { } else {
try { try {
$this->connection = new PDO($config['dsn'], $config['username'], $config['password'], $config['options']); $this->connection = new PDO($config['dsn'], $config['username'], $config['password'], $config['options']);
} catch (PDOException $e) { } catch (\PDOException $e) {
if ($e->getMessage() === 'could not find driver') { if ($e->getMessage() === 'could not find driver') {
throw new DibiNotSupportedException('PHP extension for PDO is not loaded.'); throw new Dibi\NotSupportedException('PHP extension for PDO is not loaded.');
} }
throw new DibiDriverException($e->getMessage(), $e->getCode()); throw new Dibi\DriverException($e->getMessage(), $e->getCode());
} }
} }
@@ -94,8 +99,8 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
/** /**
* Executes the SQL query. * Executes the SQL query.
* @param string SQL statement. * @param string SQL statement.
* @return IDibiResultDriver|NULL * @return Dibi\ResultDriver|NULL
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function query($sql) public function query($sql)
{ {
@@ -109,7 +114,7 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
if ($this->affectedRows === FALSE) { if ($this->affectedRows === FALSE) {
$err = $this->connection->errorInfo(); $err = $this->connection->errorInfo();
throw new DibiDriverException("SQLSTATE[$err[0]]: $err[2]", $err[1], $sql); throw new Dibi\DriverException("SQLSTATE[$err[0]]: $err[2]", $err[1], $sql);
} }
} else { } else {
@@ -117,7 +122,7 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
if ($res === FALSE) { if ($res === FALSE) {
$err = $this->connection->errorInfo(); $err = $this->connection->errorInfo();
throw new DibiDriverException("SQLSTATE[$err[0]]: $err[2]", $err[1], $sql); throw new Dibi\DriverException("SQLSTATE[$err[0]]: $err[2]", $err[1], $sql);
} else { } else {
return $this->createResultDriver($res); return $this->createResultDriver($res);
} }
@@ -149,13 +154,13 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
* Begins a transaction (if supported). * Begins a transaction (if supported).
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function begin($savepoint = NULL) public function begin($savepoint = NULL)
{ {
if (!$this->connection->beginTransaction()) { if (!$this->connection->beginTransaction()) {
$err = $this->connection->errorInfo(); $err = $this->connection->errorInfo();
throw new DibiDriverException("SQLSTATE[$err[0]]: $err[2]", $err[1]); throw new Dibi\DriverException("SQLSTATE[$err[0]]: $err[2]", $err[1]);
} }
} }
@@ -164,13 +169,13 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
* Commits statements in a transaction. * Commits statements in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function commit($savepoint = NULL) public function commit($savepoint = NULL)
{ {
if (!$this->connection->commit()) { if (!$this->connection->commit()) {
$err = $this->connection->errorInfo(); $err = $this->connection->errorInfo();
throw new DibiDriverException("SQLSTATE[$err[0]]: $err[2]", $err[1]); throw new Dibi\DriverException("SQLSTATE[$err[0]]: $err[2]", $err[1]);
} }
} }
@@ -179,13 +184,13 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
* Rollback changes in a transaction. * Rollback changes in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function rollback($savepoint = NULL) public function rollback($savepoint = NULL)
{ {
if (!$this->connection->rollBack()) { if (!$this->connection->rollBack()) {
$err = $this->connection->errorInfo(); $err = $this->connection->errorInfo();
throw new DibiDriverException("SQLSTATE[$err[0]]: $err[2]", $err[1]); throw new Dibi\DriverException("SQLSTATE[$err[0]]: $err[2]", $err[1]);
} }
} }
@@ -202,29 +207,29 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
/** /**
* Returns the connection reflector. * Returns the connection reflector.
* @return IDibiReflector * @return Dibi\Reflector
*/ */
public function getReflector() public function getReflector()
{ {
switch ($this->driverName) { switch ($this->driverName) {
case 'mysql': case 'mysql':
return new DibiMySqlReflector($this); return new MySqlReflector($this);
case 'sqlite': case 'sqlite':
return new DibiSqliteReflector($this); return new SqliteReflector($this);
default: default:
throw new DibiNotSupportedException; throw new Dibi\NotSupportedException;
} }
} }
/** /**
* Result set driver factory. * Result set driver factory.
* @param PDOStatement * @param \PDOStatement
* @return IDibiResultDriver * @return Dibi\ResultDriver
*/ */
public function createResultDriver(PDOStatement $resource) public function createResultDriver(\PDOStatement $resource)
{ {
$res = clone $this; $res = clone $this;
$res->resultSet = $resource; $res->resultSet = $resource;
@@ -299,8 +304,8 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
public function escapeDate($value) public function escapeDate($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format($this->driverName === 'odbc' ? '#m/d/Y#' : "'Y-m-d'"); return $value->format($this->driverName === 'odbc' ? '#m/d/Y#' : "'Y-m-d'");
} }
@@ -308,8 +313,8 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
public function escapeDateTime($value) public function escapeDateTime($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format($this->driverName === 'odbc' ? "#m/d/Y H:i:s#" : "'Y-m-d H:i:s'"); return $value->format($this->driverName === 'odbc' ? "#m/d/Y H:i:s#" : "'Y-m-d H:i:s'");
} }
@@ -370,7 +375,7 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
/** @deprecated */ /** @deprecated */
public function escape($value, $type) public function escape($value, $type)
{ {
return DibiHelpers::escape($this, $value, $type); return Dibi\Helpers::escape($this, $value, $type);
} }
@@ -433,7 +438,7 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
// intentionally break omitted // intentionally break omitted
default: default:
throw new DibiNotSupportedException('PDO or driver does not support applying limit or offset.'); throw new Dibi\NotSupportedException('PDO or driver does not support applying limit or offset.');
} }
} }
@@ -469,7 +474,7 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
*/ */
public function seek($row) public function seek($row)
{ {
throw new DibiNotSupportedException('Cannot seek an unbuffered result set.'); throw new Dibi\NotSupportedException('Cannot seek an unbuffered result set.');
} }
@@ -486,7 +491,7 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
/** /**
* Returns metadata for all columns in a result set. * Returns metadata for all columns in a result set.
* @return array * @return array
* @throws DibiException * @throws Dibi\Exception
*/ */
public function getResultColumns() public function getResultColumns()
{ {
@@ -495,7 +500,7 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
for ($i = 0; $i < $count; $i++) { for ($i = 0; $i < $count; $i++) {
$row = @$this->resultSet->getColumnMeta($i); // intentionally @ $row = @$this->resultSet->getColumnMeta($i); // intentionally @
if ($row === FALSE) { if ($row === FALSE) {
throw new DibiNotSupportedException('Driver does not support meta data.'); throw new Dibi\NotSupportedException('Driver does not support meta data.');
} }
$row = $row + [ $row = $row + [
'table' => NULL, 'table' => NULL,
@@ -516,7 +521,7 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
/** /**
* Returns the result set resource. * Returns the result set resource.
* @return PDOStatement * @return \PDOStatement
*/ */
public function getResultResource() public function getResultResource()
{ {

View File

@@ -5,6 +5,10 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Drivers;
use Dibi;
/** /**
* The dibi driver for PostgreSQL database. * The dibi driver for PostgreSQL database.
@@ -16,11 +20,11 @@
* - charset => character encoding to set (default is utf8) * - charset => character encoding to set (default is utf8)
* - persistent (bool) => try to find a persistent link? * - persistent (bool) => try to find a persistent link?
* - resource (resource) => existing connection resource * - resource (resource) => existing connection resource
* - lazy, profiler, result, substitutes, ... => see DibiConnection options * - lazy, profiler, result, substitutes, ... => see Dibi\Connection options
*/ */
class DibiPostgreDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector class PostgreDriver implements Dibi\Driver, Dibi\ResultDriver, Dibi\Reflector
{ {
use DibiStrict; use Dibi\Strict;
/** @var resource Connection resource */ /** @var resource Connection resource */
private $connection; private $connection;
@@ -36,12 +40,12 @@ class DibiPostgreDriver implements IDibiDriver, IDibiResultDriver, IDibiReflecto
/** /**
* @throws DibiNotSupportedException * @throws Dibi\NotSupportedException
*/ */
public function __construct() public function __construct()
{ {
if (!extension_loaded('pgsql')) { if (!extension_loaded('pgsql')) {
throw new DibiNotSupportedException("PHP extension 'pgsql' is not loaded."); throw new Dibi\NotSupportedException("PHP extension 'pgsql' is not loaded.");
} }
} }
@@ -49,7 +53,7 @@ class DibiPostgreDriver implements IDibiDriver, IDibiResultDriver, IDibiReflecto
/** /**
* Connects to a database. * Connects to a database.
* @return void * @return void
* @throws DibiException * @throws Dibi\Exception
*/ */
public function connect(array & $config) public function connect(array & $config)
{ {
@@ -64,8 +68,8 @@ class DibiPostgreDriver implements IDibiDriver, IDibiResultDriver, IDibiReflecto
$string = $config['string']; $string = $config['string'];
} else { } else {
$string = ''; $string = '';
DibiConnection::alias($config, 'user', 'username'); Dibi\Connection::alias($config, 'user', 'username');
DibiConnection::alias($config, 'dbname', 'database'); Dibi\Connection::alias($config, 'dbname', 'database');
foreach (['host', 'hostaddr', 'port', 'dbname', 'user', 'password', 'connect_timeout', 'options', 'sslmode', 'service'] as $key) { foreach (['host', 'hostaddr', 'port', 'dbname', 'user', 'password', 'connect_timeout', 'options', 'sslmode', 'service'] as $key) {
if (isset($config[$key])) { if (isset($config[$key])) {
$string .= $key . '=' . $config[$key] . ' '; $string .= $key . '=' . $config[$key] . ' ';
@@ -73,26 +77,26 @@ class DibiPostgreDriver implements IDibiDriver, IDibiResultDriver, IDibiReflecto
} }
} }
DibiDriverException::tryError(); Dibi\DriverException::tryError();
if (empty($config['persistent'])) { if (empty($config['persistent'])) {
$this->connection = pg_connect($string, PGSQL_CONNECT_FORCE_NEW); $this->connection = pg_connect($string, PGSQL_CONNECT_FORCE_NEW);
} else { } else {
$this->connection = pg_pconnect($string, PGSQL_CONNECT_FORCE_NEW); $this->connection = pg_pconnect($string, PGSQL_CONNECT_FORCE_NEW);
} }
if (DibiDriverException::catchError($msg)) { if (Dibi\DriverException::catchError($msg)) {
throw new DibiDriverException($msg, 0); throw new Dibi\DriverException($msg, 0);
} }
} }
if (!is_resource($this->connection)) { if (!is_resource($this->connection)) {
throw new DibiDriverException('Connecting error.'); throw new Dibi\DriverException('Connecting error.');
} }
if (isset($config['charset'])) { if (isset($config['charset'])) {
DibiDriverException::tryError(); Dibi\DriverException::tryError();
pg_set_client_encoding($this->connection, $config['charset']); pg_set_client_encoding($this->connection, $config['charset']);
if (DibiDriverException::catchError($msg)) { if (Dibi\DriverException::catchError($msg)) {
throw new DibiDriverException($msg, 0); throw new Dibi\DriverException($msg, 0);
} }
} }
@@ -125,8 +129,8 @@ class DibiPostgreDriver implements IDibiDriver, IDibiResultDriver, IDibiReflecto
/** /**
* Executes the SQL query. * Executes the SQL query.
* @param string SQL statement. * @param string SQL statement.
* @return IDibiResultDriver|NULL * @return Dibi\ResultDriver|NULL
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function query($sql) public function query($sql)
{ {
@@ -134,7 +138,7 @@ class DibiPostgreDriver implements IDibiDriver, IDibiResultDriver, IDibiReflecto
$res = @pg_query($this->connection, $sql); // intentionally @ $res = @pg_query($this->connection, $sql); // intentionally @
if ($res === FALSE) { if ($res === FALSE) {
throw new DibiDriverException(pg_last_error($this->connection), 0, $sql); throw new Dibi\DriverException(pg_last_error($this->connection), 0, $sql);
} elseif (is_resource($res)) { } elseif (is_resource($res)) {
$this->affectedRows = pg_affected_rows($res); $this->affectedRows = pg_affected_rows($res);
@@ -181,7 +185,7 @@ class DibiPostgreDriver implements IDibiDriver, IDibiResultDriver, IDibiReflecto
* Begins a transaction (if supported). * Begins a transaction (if supported).
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function begin($savepoint = NULL) public function begin($savepoint = NULL)
{ {
@@ -193,7 +197,7 @@ class DibiPostgreDriver implements IDibiDriver, IDibiResultDriver, IDibiReflecto
* Commits statements in a transaction. * Commits statements in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function commit($savepoint = NULL) public function commit($savepoint = NULL)
{ {
@@ -205,7 +209,7 @@ class DibiPostgreDriver implements IDibiDriver, IDibiResultDriver, IDibiReflecto
* Rollback changes in a transaction. * Rollback changes in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function rollback($savepoint = NULL) public function rollback($savepoint = NULL)
{ {
@@ -235,7 +239,7 @@ class DibiPostgreDriver implements IDibiDriver, IDibiResultDriver, IDibiReflecto
/** /**
* Returns the connection reflector. * Returns the connection reflector.
* @return IDibiReflector * @return Dibi\Reflector
*/ */
public function getReflector() public function getReflector()
{ {
@@ -246,7 +250,7 @@ class DibiPostgreDriver implements IDibiDriver, IDibiResultDriver, IDibiReflecto
/** /**
* Result set driver factory. * Result set driver factory.
* @param resource * @param resource
* @return IDibiResultDriver * @return Dibi\ResultDriver
*/ */
public function createResultDriver($resource) public function createResultDriver($resource)
{ {
@@ -297,8 +301,8 @@ class DibiPostgreDriver implements IDibiDriver, IDibiResultDriver, IDibiReflecto
public function escapeDate($value) public function escapeDate($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format("'Y-m-d'"); return $value->format("'Y-m-d'");
} }
@@ -306,8 +310,8 @@ class DibiPostgreDriver implements IDibiDriver, IDibiResultDriver, IDibiReflecto
public function escapeDateTime($value) public function escapeDateTime($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format("'Y-m-d H:i:s'"); return $value->format("'Y-m-d H:i:s'");
} }
@@ -342,7 +346,7 @@ class DibiPostgreDriver implements IDibiDriver, IDibiResultDriver, IDibiReflecto
/** @deprecated */ /** @deprecated */
public function escape($value, $type) public function escape($value, $type)
{ {
return DibiHelpers::escape($this, $value, $type); return Dibi\Helpers::escape($this, $value, $type);
} }
@@ -450,7 +454,7 @@ class DibiPostgreDriver implements IDibiDriver, IDibiResultDriver, IDibiReflecto
} }
/********************* IDibiReflector ****************d*g**/ /********************* Dibi\Reflector ****************d*g**/
/** /**
@@ -461,7 +465,7 @@ class DibiPostgreDriver implements IDibiDriver, IDibiResultDriver, IDibiReflecto
{ {
$version = pg_parameter_status($this->getResource(), 'server_version'); $version = pg_parameter_status($this->getResource(), 'server_version');
if ($version < 7.4) { if ($version < 7.4) {
throw new DibiDriverException('Reflection requires PostgreSQL 7.4 and newer.'); throw new Dibi\DriverException('Reflection requires PostgreSQL 7.4 and newer.');
} }
$query = " $query = "

View File

@@ -5,6 +5,11 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Drivers;
use Dibi;
use SQLite3;
/** /**
* The dibi driver for SQLite3 database. * The dibi driver for SQLite3 database.
@@ -16,16 +21,16 @@
* - dbcharset => database character encoding (will be converted to 'charset') * - dbcharset => database character encoding (will be converted to 'charset')
* - charset => character encoding to set (default is UTF-8) * - charset => character encoding to set (default is UTF-8)
* - resource (SQLite3) => existing connection resource * - resource (SQLite3) => existing connection resource
* - lazy, profiler, result, substitutes, ... => see DibiConnection options * - lazy, profiler, result, substitutes, ... => see Dibi\Connection options
*/ */
class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver class Sqlite3Driver implements Dibi\Driver, Dibi\ResultDriver
{ {
use DibiStrict; use Dibi\Strict;
/** @var SQLite3 Connection resource */ /** @var SQLite3 Connection resource */
private $connection; private $connection;
/** @var SQLite3Result Resultset resource */ /** @var \SQLite3Result Resultset resource */
private $resultSet; private $resultSet;
/** @var bool */ /** @var bool */
@@ -39,12 +44,12 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
/** /**
* @throws DibiNotSupportedException * @throws Dibi\NotSupportedException
*/ */
public function __construct() public function __construct()
{ {
if (!extension_loaded('sqlite3')) { if (!extension_loaded('sqlite3')) {
throw new DibiNotSupportedException("PHP extension 'sqlite3' is not loaded."); throw new Dibi\NotSupportedException("PHP extension 'sqlite3' is not loaded.");
} }
} }
@@ -52,11 +57,11 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
/** /**
* Connects to a database. * Connects to a database.
* @return void * @return void
* @throws DibiException * @throws Dibi\Exception
*/ */
public function connect(array & $config) public function connect(array & $config)
{ {
DibiConnection::alias($config, 'database', 'file'); Dibi\Connection::alias($config, 'database', 'file');
$this->fmtDate = isset($config['formatDate']) ? $config['formatDate'] : 'U'; $this->fmtDate = isset($config['formatDate']) ? $config['formatDate'] : 'U';
$this->fmtDateTime = isset($config['formatDateTime']) ? $config['formatDateTime'] : 'U'; $this->fmtDateTime = isset($config['formatDateTime']) ? $config['formatDateTime'] : 'U';
@@ -65,8 +70,8 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
} else { } else {
try { try {
$this->connection = new SQLite3($config['database']); $this->connection = new SQLite3($config['database']);
} catch (Exception $e) { } catch (\Exception $e) {
throw new DibiDriverException($e->getMessage(), $e->getCode()); throw new Dibi\DriverException($e->getMessage(), $e->getCode());
} }
} }
@@ -97,8 +102,8 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
/** /**
* Executes the SQL query. * Executes the SQL query.
* @param string SQL statement. * @param string SQL statement.
* @return IDibiResultDriver|NULL * @return Dibi\ResultDriver|NULL
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function query($sql) public function query($sql)
{ {
@@ -108,9 +113,9 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
$res = @$this->connection->query($sql); // intentionally @ $res = @$this->connection->query($sql); // intentionally @
if ($this->connection->lastErrorCode()) { if ($this->connection->lastErrorCode()) {
throw new DibiDriverException($this->connection->lastErrorMsg(), $this->connection->lastErrorCode(), $sql); throw new Dibi\DriverException($this->connection->lastErrorMsg(), $this->connection->lastErrorCode(), $sql);
} elseif ($res instanceof SQLite3Result) { } elseif ($res instanceof \SQLite3Result) {
return $this->createResultDriver($res); return $this->createResultDriver($res);
} }
} }
@@ -140,7 +145,7 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
* Begins a transaction (if supported). * Begins a transaction (if supported).
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function begin($savepoint = NULL) public function begin($savepoint = NULL)
{ {
@@ -152,7 +157,7 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
* Commits statements in a transaction. * Commits statements in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function commit($savepoint = NULL) public function commit($savepoint = NULL)
{ {
@@ -164,7 +169,7 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
* Rollback changes in a transaction. * Rollback changes in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws Dibi\DriverException
*/ */
public function rollback($savepoint = NULL) public function rollback($savepoint = NULL)
{ {
@@ -184,20 +189,20 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
/** /**
* Returns the connection reflector. * Returns the connection reflector.
* @return IDibiReflector * @return Dibi\Reflector
*/ */
public function getReflector() public function getReflector()
{ {
return new DibiSqliteReflector($this); return new SqliteReflector($this);
} }
/** /**
* Result set driver factory. * Result set driver factory.
* @param SQLite3Result * @param \SQLite3Result
* @return IDibiResultDriver * @return Dibi\ResultDriver
*/ */
public function createResultDriver(SQLite3Result $resource) public function createResultDriver(\SQLite3Result $resource)
{ {
$res = clone $this; $res = clone $this;
$res->resultSet = $resource; $res->resultSet = $resource;
@@ -239,8 +244,8 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
public function escapeDate($value) public function escapeDate($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format($this->fmtDate); return $value->format($this->fmtDate);
} }
@@ -248,8 +253,8 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
public function escapeDateTime($value) public function escapeDateTime($value)
{ {
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) { if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new DibiDateTime($value); $value = new Dibi\DateTime($value);
} }
return $value->format($this->fmtDateTime); return $value->format($this->fmtDateTime);
} }
@@ -282,7 +287,7 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
/** @deprecated */ /** @deprecated */
public function escape($value, $type) public function escape($value, $type)
{ {
return DibiHelpers::escape($this, $value, $type); return Dibi\Helpers::escape($this, $value, $type);
} }
@@ -314,11 +319,11 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
/** /**
* Returns the number of rows in a result set. * Returns the number of rows in a result set.
* @return int * @return int
* @throws DibiNotSupportedException * @throws Dibi\NotSupportedException
*/ */
public function getRowCount() public function getRowCount()
{ {
throw new DibiNotSupportedException('Row count is not available for unbuffered queries.'); throw new Dibi\NotSupportedException('Row count is not available for unbuffered queries.');
} }
@@ -349,11 +354,11 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
* Moves cursor position without fetching row. * Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to * @param int the 0-based cursor pos to seek to
* @return bool TRUE on success, FALSE if unable to seek to specified record * @return bool TRUE on success, FALSE if unable to seek to specified record
* @throws DibiNotSupportedException * @throws Dibi\NotSupportedException
*/ */
public function seek($row) public function seek($row)
{ {
throw new DibiNotSupportedException('Cannot seek an unbuffered result set.'); throw new Dibi\NotSupportedException('Cannot seek an unbuffered result set.');
} }

View File

@@ -5,20 +5,24 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Drivers;
use Dibi;
/** /**
* The dibi reflector for SQLite database. * The dibi reflector for SQLite database.
* @internal * @internal
*/ */
class DibiSqliteReflector implements IDibiReflector class SqliteReflector implements Dibi\Reflector
{ {
use DibiStrict; use Dibi\Strict;
/** @var IDibiDriver */ /** @var Dibi\Driver */
private $driver; private $driver;
public function __construct(IDibiDriver $driver) public function __construct(Dibi\Driver $driver)
{ {
$this->driver = $driver; $this->driver = $driver;
} }

View File

@@ -5,13 +5,15 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi;
/** /**
* Profiler & logger event. * Profiler & logger event.
*/ */
class DibiEvent class Event
{ {
use DibiStrict; use Strict;
/** event type */ /** event type */
const CONNECT = 1, const CONNECT = 1,
@@ -26,7 +28,7 @@ class DibiEvent
TRANSACTION = 448, // BEGIN | COMMIT | ROLLBACK TRANSACTION = 448, // BEGIN | COMMIT | ROLLBACK
ALL = 1023; ALL = 1023;
/** @var DibiConnection */ /** @var Connection */
public $connection; public $connection;
/** @var int */ /** @var int */
@@ -35,7 +37,7 @@ class DibiEvent
/** @var string */ /** @var string */
public $sql; public $sql;
/** @var DibiResult|DibiDriverException|NULL */ /** @var Result|DriverException|NULL */
public $result; public $result;
/** @var float */ /** @var float */
@@ -48,7 +50,7 @@ class DibiEvent
public $source; public $source;
public function __construct(DibiConnection $connection, $type, $sql = NULL) public function __construct(Connection $connection, $type, $sql = NULL)
{ {
$this->connection = $connection; $this->connection = $connection;
$this->type = $type; $this->type = $type;
@@ -63,7 +65,7 @@ class DibiEvent
$this->type = $types[strtoupper($matches[1])]; $this->type = $types[strtoupper($matches[1])];
} }
$rc = new ReflectionClass('dibi'); $rc = new \ReflectionClass('dibi');
$dibiDir = dirname($rc->getFileName()) . DIRECTORY_SEPARATOR; $dibiDir = dirname($rc->getFileName()) . DIRECTORY_SEPARATOR;
foreach (debug_backtrace(FALSE) as $row) { foreach (debug_backtrace(FALSE) as $row) {
if (isset($row['file']) && is_file($row['file']) && strpos($row['file'], $dibiDir) !== 0) { if (isset($row['file']) && is_file($row['file']) && strpos($row['file'], $dibiDir) !== 0) {
@@ -72,9 +74,9 @@ class DibiEvent
} }
} }
dibi::$elapsedTime = FALSE; \dibi::$elapsedTime = FALSE;
dibi::$numOfQueries++; \dibi::$numOfQueries++;
dibi::$sql = $sql; \dibi::$sql = $sql;
} }
@@ -82,14 +84,14 @@ class DibiEvent
{ {
$this->result = $result; $this->result = $result;
try { try {
$this->count = $result instanceof DibiResult ? count($result) : NULL; $this->count = $result instanceof Result ? count($result) : NULL;
} catch (DibiException $e) { } catch (Exception $e) {
$this->count = NULL; $this->count = NULL;
} }
$this->time += microtime(TRUE); $this->time += microtime(TRUE);
dibi::$elapsedTime = $this->time; \dibi::$elapsedTime = $this->time;
dibi::$totalTime += $this->time; \dibi::$totalTime += $this->time;
return $this; return $this;
} }

View File

@@ -5,25 +5,27 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi;
/** /**
* dibi SQL builder via fluent interfaces. EXPERIMENTAL! * dibi SQL builder via fluent interfaces. EXPERIMENTAL!
* *
* @method DibiFluent select($field) * @method Fluent select($field)
* @method DibiFluent distinct() * @method Fluent distinct()
* @method DibiFluent from($table) * @method Fluent from($table)
* @method DibiFluent where($cond) * @method Fluent where($cond)
* @method DibiFluent groupBy($field) * @method Fluent groupBy($field)
* @method DibiFluent having($cond) * @method Fluent having($cond)
* @method DibiFluent orderBy($field) * @method Fluent orderBy($field)
* @method DibiFluent limit(int $limit) * @method Fluent limit(int $limit)
* @method DibiFluent offset(int $offset) * @method Fluent offset(int $offset)
* @method DibiFluent leftJoin($table) * @method Fluent leftJoin($table)
* @method DibiFluent on($cond) * @method Fluent on($cond)
*/ */
class DibiFluent implements IDataSource class Fluent implements IDataSource
{ {
use DibiStrict; use Strict;
const REMOVE = FALSE; const REMOVE = FALSE;
@@ -72,7 +74,7 @@ class DibiFluent implements IDataSource
'RIGHT JOIN' => 'FROM', 'RIGHT JOIN' => 'FROM',
]; ];
/** @var DibiConnection */ /** @var Connection */
private $connection; private $connection;
/** @var array */ /** @var array */
@@ -90,19 +92,19 @@ class DibiFluent implements IDataSource
/** @var array */ /** @var array */
private $cursor; private $cursor;
/** @var DibiHashMap normalized clauses */ /** @var HashMap normalized clauses */
private static $normalizer; private static $normalizer;
/** /**
* @param DibiConnection * @param Connection
*/ */
public function __construct(DibiConnection $connection) public function __construct(Connection $connection)
{ {
$this->connection = $connection; $this->connection = $connection;
if (self::$normalizer === NULL) { if (self::$normalizer === NULL) {
self::$normalizer = new DibiHashMap([__CLASS__, '_formatClause']); self::$normalizer = new HashMap([__CLASS__, '_formatClause']);
} }
} }
@@ -175,7 +177,7 @@ class DibiFluent implements IDataSource
} elseif (is_string($arg) && preg_match('#^[a-z:_][a-z0-9_.:]*\z#i', $arg)) { // identifier } elseif (is_string($arg) && preg_match('#^[a-z:_][a-z0-9_.:]*\z#i', $arg)) { // identifier
$args = ['%n', $arg]; $args = ['%n', $arg];
} elseif (is_array($arg) || ($arg instanceof Traversable && !$arg instanceof self)) { // any array } elseif (is_array($arg) || ($arg instanceof \Traversable && !$arg instanceof self)) { // any array
if (isset(self::$modifiers[$clause])) { if (isset(self::$modifiers[$clause])) {
$args = [self::$modifiers[$clause], $arg]; $args = [self::$modifiers[$clause], $arg];
@@ -265,7 +267,7 @@ class DibiFluent implements IDataSource
/** /**
* Returns the dibi connection. * Returns the dibi connection.
* @return DibiConnection * @return Connection
*/ */
final public function getConnection() final public function getConnection()
{ {
@@ -274,7 +276,7 @@ class DibiFluent implements IDataSource
/** /**
* Adds DibiResult setup. * Adds Result setup.
* @param string method * @param string method
* @param mixed args * @param mixed args
* @return self * @return self
@@ -292,16 +294,16 @@ class DibiFluent implements IDataSource
/** /**
* Generates and executes SQL query. * Generates and executes SQL query.
* @param mixed what to return? * @param mixed what to return?
* @return DibiResult|int result set object (if any) * @return Result|int result set object (if any)
* @throws DibiException * @throws Exception
*/ */
public function execute($return = NULL) public function execute($return = NULL)
{ {
$res = $this->query($this->_export()); $res = $this->query($this->_export());
switch ($return) { switch ($return) {
case dibi::IDENTIFIER: case \dibi::IDENTIFIER:
return $this->connection->getInsertId(); return $this->connection->getInsertId();
case dibi::AFFECTED_ROWS: case \dibi::AFFECTED_ROWS:
return $this->connection->getAffectedRows(); return $this->connection->getAffectedRows();
default: default:
return $res; return $res;
@@ -311,7 +313,7 @@ class DibiFluent implements IDataSource
/** /**
* Generates, executes SQL query and fetches the single row. * Generates, executes SQL query and fetches the single row.
* @return DibiRow|FALSE array on success, FALSE if no next record * @return Row|FALSE array on success, FALSE if no next record
*/ */
public function fetch() public function fetch()
{ {
@@ -376,7 +378,7 @@ class DibiFluent implements IDataSource
* Required by the IteratorAggregate interface. * Required by the IteratorAggregate interface.
* @param int offset * @param int offset
* @param int limit * @param int limit
* @return DibiResultIterator * @return ResultIterator
*/ */
public function getIterator($offset = NULL, $limit = NULL) public function getIterator($offset = NULL, $limit = NULL)
{ {
@@ -407,7 +409,7 @@ class DibiFluent implements IDataSource
/** /**
* @return DibiResult * @return Result
*/ */
private function query($args) private function query($args)
{ {
@@ -423,11 +425,11 @@ class DibiFluent implements IDataSource
/** /**
* @return DibiDataSource * @return DataSource
*/ */
public function toDataSource() public function toDataSource()
{ {
return new DibiDataSource($this->connection->translate($this->_export()), $this->connection); return new DataSource($this->connection->translate($this->_export()), $this->connection);
} }
@@ -439,14 +441,14 @@ class DibiFluent implements IDataSource
{ {
try { try {
return $this->connection->translate($this->_export()); return $this->connection->translate($this->_export());
} catch (Exception $e) { } catch (\Exception $e) {
trigger_error($e->getMessage(), E_USER_ERROR); trigger_error($e->getMessage(), E_USER_ERROR);
} }
} }
/** /**
* Generates parameters for DibiTranslator. * Generates parameters for Translator.
* @param string clause name * @param string clause name
* @return array * @return array
*/ */

View File

@@ -5,12 +5,14 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi;
/** /**
* Lazy cached storage. * Lazy cached storage.
* @internal * @internal
*/ */
abstract class DibiHashMapBase abstract class HashMapBase
{ {
private $callback; private $callback;
@@ -25,7 +27,7 @@ abstract class DibiHashMapBase
{ {
if (!is_callable($callback)) { if (!is_callable($callback)) {
$able = is_callable($callback, TRUE, $textual); $able = is_callable($callback, TRUE, $textual);
throw new InvalidArgumentException("Handler '$textual' is not " . ($able ? 'callable.' : 'valid PHP callback.')); throw new \InvalidArgumentException("Handler '$textual' is not " . ($able ? 'callable.' : 'valid PHP callback.'));
} }
$this->callback = $callback; $this->callback = $callback;
} }
@@ -44,7 +46,7 @@ abstract class DibiHashMapBase
* *
* @internal * @internal
*/ */
final class DibiHashMap extends DibiHashMapBase final class HashMap extends HashMapBase
{ {
public function __set($nm, $val) public function __set($nm, $val)

View File

@@ -5,26 +5,28 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi;
class DibiHelpers
class Helpers
{ {
use DibiStrict; use Strict;
/** /**
* Prints out a syntax highlighted version of the SQL command or DibiResult. * Prints out a syntax highlighted version of the SQL command or Result.
* @param string|DibiResult * @param string|Result
* @param bool return output instead of printing it? * @param bool return output instead of printing it?
* @return string * @return string
*/ */
public static function dump($sql = NULL, $return = FALSE) public static function dump($sql = NULL, $return = FALSE)
{ {
ob_start(); ob_start();
if ($sql instanceof DibiResult) { if ($sql instanceof Result) {
$sql->dump(); $sql->dump();
} else { } else {
if ($sql === NULL) { if ($sql === NULL) {
$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'; 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';
@@ -113,12 +115,12 @@ class DibiHelpers
public static function escape($driver, $value, $type) public static function escape($driver, $value, $type)
{ {
static $types = [ static $types = [
DibiType::TEXT => 'text', Type::TEXT => 'text',
DibiType::BINARY => 'binary', Type::BINARY => 'binary',
DibiType::BOOL => 'bool', Type::BOOL => 'bool',
DibiType::DATE => 'date', Type::DATE => 'date',
DibiType::DATETIME => 'datetime', Type::DATETIME => 'datetime',
dibi::IDENTIFIER => 'identifier', \dibi::IDENTIFIER => 'identifier',
]; ];
if (isset($types[$type])) { if (isset($types[$type])) {
return $driver->{'escape' . $types[$type]}($value); return $driver->{'escape' . $types[$type]}($value);

View File

@@ -5,13 +5,15 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi;
/** /**
* SQL literal value. * SQL literal value.
*/ */
class DibiLiteral class Literal
{ {
use DibiStrict; use Strict;
/** @var string */ /** @var string */
private $value; private $value;

View File

@@ -5,13 +5,17 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Loggers;
use Dibi;
/** /**
* dibi file logger. * dibi file logger.
*/ */
class DibiFileLogger class FileLogger
{ {
use DibiStrict; use Dibi\Strict;
/** @var string Name of the file where SQL errors should be logged */ /** @var string Name of the file where SQL errors should be logged */
public $file; public $file;
@@ -23,7 +27,7 @@ class DibiFileLogger
public function __construct($file, $filter = NULL) public function __construct($file, $filter = NULL)
{ {
$this->file = $file; $this->file = $file;
$this->filter = $filter ? (int) $filter : DibiEvent::QUERY; $this->filter = $filter ? (int) $filter : Dibi\Event::QUERY;
} }
@@ -31,7 +35,7 @@ class DibiFileLogger
* After event notification. * After event notification.
* @return void * @return void
*/ */
public function logEvent(DibiEvent $event) public function logEvent(Dibi\Event $event)
{ {
if (($event->type & $this->filter) === 0) { if (($event->type & $this->filter) === 0) {
return; return;
@@ -43,7 +47,7 @@ class DibiFileLogger
} }
flock($handle, LOCK_EX); flock($handle, LOCK_EX);
if ($event->result instanceof Exception) { if ($event->result instanceof \Exception) {
$message = $event->result->getMessage(); $message = $event->result->getMessage();
if ($code = $event->result->getCode()) { if ($code = $event->result->getCode()) {
$message = "[$code] $message"; $message = "[$code] $message";

View File

@@ -5,13 +5,17 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Loggers;
use Dibi;
/** /**
* dibi FirePHP logger. * dibi FirePHP logger.
*/ */
class DibiFirePhpLogger class FirePhpLogger
{ {
use DibiStrict; use Dibi\Strict;
/** maximum number of rows */ /** maximum number of rows */
public static $maxQueries = 30; public static $maxQueries = 30;
@@ -46,7 +50,7 @@ class DibiFirePhpLogger
public function __construct($filter = NULL) public function __construct($filter = NULL)
{ {
$this->filter = $filter ? (int) $filter : DibiEvent::QUERY; $this->filter = $filter ? (int) $filter : Dibi\Event::QUERY;
} }
@@ -54,7 +58,7 @@ class DibiFirePhpLogger
* After event notification. * After event notification.
* @return void * @return void
*/ */
public function logEvent(DibiEvent $event) public function logEvent(Dibi\Event $event)
{ {
if (headers_sent() || ($event->type & $this->filter) === 0 || count(self::$fireTable) > self::$maxQueries) { if (headers_sent() || ($event->type & $this->filter) === 0 || count(self::$fireTable) > self::$maxQueries) {
return; return;
@@ -70,7 +74,7 @@ class DibiFirePhpLogger
self::$fireTable[] = [ self::$fireTable[] = [
sprintf('%0.3f', $event->time * 1000), sprintf('%0.3f', $event->time * 1000),
strlen($event->sql) > self::$maxLength ? substr($event->sql, 0, self::$maxLength) . '...' : $event->sql, strlen($event->sql) > self::$maxLength ? substr($event->sql, 0, self::$maxLength) . '...' : $event->sql,
$event->result instanceof Exception ? 'ERROR' : (string) $event->count, $event->result instanceof \Exception ? 'ERROR' : (string) $event->count,
$event->connection->getConfig('driver') . '/' . $event->connection->getConfig('name'), $event->connection->getConfig('driver') . '/' . $event->connection->getConfig('name'),
]; ];

View File

@@ -5,13 +5,18 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Reflection;
use Dibi;
use Dibi\Type;
/** /**
* Reflection metadata class for a table or result set column. * Reflection metadata class for a table or result set column.
* *
* @property-read string $name * @property-read string $name
* @property-read string $fullName * @property-read string $fullName
* @property-read DibiTableInfo $table * @property-read Table $table
* @property-read string $type * @property-read string $type
* @property-read mixed $nativeType * @property-read mixed $nativeType
* @property-read int $size * @property-read int $size
@@ -20,21 +25,21 @@
* @property-read bool $autoIncrement * @property-read bool $autoIncrement
* @property-read mixed $default * @property-read mixed $default
*/ */
class DibiColumnInfo class Column
{ {
use DibiStrict; use Dibi\Strict;
/** @var array */ /** @var array */
private static $types; private static $types;
/** @var IDibiReflector|NULL when created by DibiResultInfo */ /** @var Dibi\Reflector|NULL when created by Result */
private $reflector; private $reflector;
/** @var array (name, nativetype, [table], [fullname], [size], [nullable], [default], [autoincrement], [vendor]) */ /** @var array (name, nativetype, [table], [fullname], [size], [nullable], [default], [autoincrement], [vendor]) */
private $info; private $info;
public function __construct(IDibiReflector $reflector = NULL, array $info) public function __construct(Dibi\Reflector $reflector = NULL, array $info)
{ {
$this->reflector = $reflector; $this->reflector = $reflector;
$this->info = $info; $this->info = $info;
@@ -69,14 +74,14 @@ class DibiColumnInfo
/** /**
* @return DibiTableInfo * @return Table
*/ */
public function getTable() public function getTable()
{ {
if (empty($this->info['table']) || !$this->reflector) { if (empty($this->info['table']) || !$this->reflector) {
throw new DibiException("Table is unknown or not available."); throw new Dibi\Exception("Table is unknown or not available.");
} }
return new DibiTableInfo($this->reflector, ['name' => $this->info['table']]); return new Table($this->reflector, ['name' => $this->info['table']]);
} }
@@ -171,15 +176,15 @@ class DibiColumnInfo
public static function detectType($type) public static function detectType($type)
{ {
static $patterns = [ static $patterns = [
'^_' => DibiType::TEXT, // PostgreSQL arrays '^_' => Type::TEXT, // PostgreSQL arrays
'BYTEA|BLOB|BIN' => DibiType::BINARY, 'BYTEA|BLOB|BIN' => Type::BINARY,
'TEXT|CHAR|POINT|INTERVAL' => DibiType::TEXT, 'TEXT|CHAR|POINT|INTERVAL' => Type::TEXT,
'YEAR|BYTE|COUNTER|SERIAL|INT|LONG|SHORT' => DibiType::INTEGER, 'YEAR|BYTE|COUNTER|SERIAL|INT|LONG|SHORT' => Type::INTEGER,
'CURRENCY|REAL|MONEY|FLOAT|DOUBLE|DECIMAL|NUMERIC|NUMBER' => DibiType::FLOAT, 'CURRENCY|REAL|MONEY|FLOAT|DOUBLE|DECIMAL|NUMERIC|NUMBER' => Type::FLOAT,
'^TIME$' => DibiType::TIME, '^TIME$' => Type::TIME,
'TIME' => DibiType::DATETIME, // DATETIME, TIMESTAMP 'TIME' => Type::DATETIME, // DATETIME, TIMESTAMP
'DATE' => DibiType::DATE, 'DATE' => Type::DATE,
'BOOL' => DibiType::BOOL, 'BOOL' => Type::BOOL,
]; ];
foreach ($patterns as $s => $val) { foreach ($patterns as $s => $val) {
@@ -187,7 +192,7 @@ class DibiColumnInfo
return $val; return $val;
} }
} }
return DibiType::TEXT; return Type::TEXT;
} }
@@ -197,7 +202,7 @@ class DibiColumnInfo
public static function getTypeCache() public static function getTypeCache()
{ {
if (self::$types === NULL) { if (self::$types === NULL) {
self::$types = new DibiHashMap([__CLASS__, 'detectType']); self::$types = new Dibi\HashMap([__CLASS__, 'detectType']);
} }
return self::$types; return self::$types;
} }

View File

@@ -5,6 +5,10 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Reflection;
use Dibi;
/** /**
* Reflection metadata class for a database. * Reflection metadata class for a database.
@@ -13,11 +17,11 @@
* @property-read array $tables * @property-read array $tables
* @property-read array $tableNames * @property-read array $tableNames
*/ */
class DibiDatabaseInfo class Database
{ {
use DibiStrict; use Dibi\Strict;
/** @var IDibiReflector */ /** @var Dibi\Reflector */
private $reflector; private $reflector;
/** @var string */ /** @var string */
@@ -27,7 +31,7 @@ class DibiDatabaseInfo
private $tables; private $tables;
public function __construct(IDibiReflector $reflector, $name) public function __construct(Dibi\Reflector $reflector, $name)
{ {
$this->reflector = $reflector; $this->reflector = $reflector;
$this->name = $name; $this->name = $name;
@@ -44,7 +48,7 @@ class DibiDatabaseInfo
/** /**
* @return DibiTableInfo[] * @return Table[]
*/ */
public function getTables() public function getTables()
{ {
@@ -69,7 +73,7 @@ class DibiDatabaseInfo
/** /**
* @param string * @param string
* @return DibiTableInfo * @return Table
*/ */
public function getTable($name) public function getTable($name)
{ {
@@ -79,7 +83,7 @@ class DibiDatabaseInfo
return $this->tables[$l]; return $this->tables[$l];
} else { } else {
throw new DibiException("Database '$this->name' has no table '$name'."); throw new Dibi\Exception("Database '$this->name' has no table '$name'.");
} }
} }
@@ -103,7 +107,7 @@ class DibiDatabaseInfo
if ($this->tables === NULL) { if ($this->tables === NULL) {
$this->tables = []; $this->tables = [];
foreach ($this->reflector->getTables() as $info) { foreach ($this->reflector->getTables() as $info) {
$this->tables[strtolower($info['name'])] = new DibiTableInfo($this->reflector, $info); $this->tables[strtolower($info['name'])] = new Table($this->reflector, $info);
} }
} }
} }

View File

@@ -5,6 +5,10 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Reflection;
use Dibi;
/** /**
* Reflection metadata class for a foreign key. * Reflection metadata class for a foreign key.
@@ -12,9 +16,9 @@
* @property-read string $name * @property-read string $name
* @property-read array $references * @property-read array $references
*/ */
class DibiForeignKeyInfo class ForeignKey
{ {
use DibiStrict; use Dibi\Strict;
/** @var string */ /** @var string */
private $name; private $name;

View File

@@ -5,6 +5,10 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Reflection;
use Dibi;
/** /**
* Reflection metadata class for a index or primary key. * Reflection metadata class for a index or primary key.
@@ -14,9 +18,9 @@
* @property-read bool $unique * @property-read bool $unique
* @property-read bool $primary * @property-read bool $primary
*/ */
class DibiIndexInfo class Index
{ {
use DibiStrict; use Dibi\Strict;
/** @var array (name, columns, [unique], [primary]) */ /** @var array (name, columns, [unique], [primary]) */
private $info; private $info;

View File

@@ -5,6 +5,10 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Reflection;
use Dibi;
/** /**
* Reflection metadata class for a result set. * Reflection metadata class for a result set.
@@ -12,11 +16,11 @@
* @property-read array $columns * @property-read array $columns
* @property-read array $columnNames * @property-read array $columnNames
*/ */
class DibiResultInfo class Result
{ {
use DibiStrict; use Dibi\Strict;
/** @var IDibiResultDriver */ /** @var Dibi\ResultDriver */
private $driver; private $driver;
/** @var array */ /** @var array */
@@ -26,14 +30,14 @@ class DibiResultInfo
private $names; private $names;
public function __construct(IDibiResultDriver $driver) public function __construct(Dibi\ResultDriver $driver)
{ {
$this->driver = $driver; $this->driver = $driver;
} }
/** /**
* @return DibiColumnInfo[] * @return Column[]
*/ */
public function getColumns() public function getColumns()
{ {
@@ -59,7 +63,7 @@ class DibiResultInfo
/** /**
* @param string * @param string
* @return DibiColumnInfo * @return Column
*/ */
public function getColumn($name) public function getColumn($name)
{ {
@@ -69,7 +73,7 @@ class DibiResultInfo
return $this->names[$l]; return $this->names[$l];
} else { } else {
throw new DibiException("Result set has no column '$name'."); throw new Dibi\Exception("Result set has no column '$name'.");
} }
} }
@@ -92,9 +96,9 @@ class DibiResultInfo
{ {
if ($this->columns === NULL) { if ($this->columns === NULL) {
$this->columns = []; $this->columns = [];
$reflector = $this->driver instanceof IDibiReflector ? $this->driver : NULL; $reflector = $this->driver instanceof Dibi\Reflector ? $this->driver : NULL;
foreach ($this->driver->getResultColumns() as $info) { foreach ($this->driver->getResultColumns() as $info) {
$this->columns[] = $this->names[$info['name']] = new DibiColumnInfo($reflector, $info); $this->columns[] = $this->names[$info['name']] = new Column($reflector, $info);
} }
} }
} }

View File

@@ -5,6 +5,10 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi\Reflection;
use Dibi;
/** /**
* Reflection metadata class for a database table. * Reflection metadata class for a database table.
@@ -15,13 +19,13 @@
* @property-read array $columnNames * @property-read array $columnNames
* @property-read array $foreignKeys * @property-read array $foreignKeys
* @property-read array $indexes * @property-read array $indexes
* @property-read DibiIndexInfo $primaryKey * @property-read Index $primaryKey
*/ */
class DibiTableInfo class Table
{ {
use DibiStrict; use Dibi\Strict;
/** @var IDibiReflector */ /** @var Dibi\Reflector */
private $reflector; private $reflector;
/** @var string */ /** @var string */
@@ -39,11 +43,11 @@ class DibiTableInfo
/** @var array */ /** @var array */
private $indexes; private $indexes;
/** @var DibiIndexInfo */ /** @var Index */
private $primaryKey; private $primaryKey;
public function __construct(IDibiReflector $reflector, array $info) public function __construct(Dibi\Reflector $reflector, array $info)
{ {
$this->reflector = $reflector; $this->reflector = $reflector;
$this->name = $info['name']; $this->name = $info['name'];
@@ -70,7 +74,7 @@ class DibiTableInfo
/** /**
* @return DibiColumnInfo[] * @return Column[]
*/ */
public function getColumns() public function getColumns()
{ {
@@ -95,7 +99,7 @@ class DibiTableInfo
/** /**
* @param string * @param string
* @return DibiColumnInfo * @return Column
*/ */
public function getColumn($name) public function getColumn($name)
{ {
@@ -105,7 +109,7 @@ class DibiTableInfo
return $this->columns[$l]; return $this->columns[$l];
} else { } else {
throw new DibiException("Table '$this->name' has no column '$name'."); throw new Dibi\Exception("Table '$this->name' has no column '$name'.");
} }
} }
@@ -122,7 +126,7 @@ class DibiTableInfo
/** /**
* @return DibiForeignKeyInfo[] * @return ForeignKey[]
*/ */
public function getForeignKeys() public function getForeignKeys()
{ {
@@ -132,7 +136,7 @@ class DibiTableInfo
/** /**
* @return DibiIndexInfo[] * @return Index[]
*/ */
public function getIndexes() public function getIndexes()
{ {
@@ -142,7 +146,7 @@ class DibiTableInfo
/** /**
* @return DibiIndexInfo * @return Index
*/ */
public function getPrimaryKey() public function getPrimaryKey()
{ {
@@ -159,7 +163,7 @@ class DibiTableInfo
if ($this->columns === NULL) { if ($this->columns === NULL) {
$this->columns = []; $this->columns = [];
foreach ($this->reflector->getColumns($this->name) as $info) { foreach ($this->reflector->getColumns($this->name) as $info) {
$this->columns[strtolower($info['name'])] = new DibiColumnInfo($this->reflector, $info); $this->columns[strtolower($info['name'])] = new Column($this->reflector, $info);
} }
} }
} }
@@ -177,7 +181,7 @@ class DibiTableInfo
foreach ($info['columns'] as $key => $name) { foreach ($info['columns'] as $key => $name) {
$info['columns'][$key] = $this->columns[strtolower($name)]; $info['columns'][$key] = $this->columns[strtolower($name)];
} }
$this->indexes[strtolower($info['name'])] = new DibiIndexInfo($info); $this->indexes[strtolower($info['name'])] = new Index($info);
if (!empty($info['primary'])) { if (!empty($info['primary'])) {
$this->primaryKey = $this->indexes[strtolower($info['name'])]; $this->primaryKey = $this->indexes[strtolower($info['name'])];
} }
@@ -191,7 +195,7 @@ class DibiTableInfo
*/ */
protected function initForeignKeys() protected function initForeignKeys()
{ {
throw new DibiNotImplementedException; throw new Dibi\NotImplementedException;
} }
} }

View File

@@ -5,6 +5,8 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi;
/** /**
* dibi result set. * dibi result set.
@@ -24,26 +26,26 @@
* *
* @property-read int $rowCount * @property-read int $rowCount
*/ */
class DibiResult implements IDataSource class Result implements IDataSource
{ {
use DibiStrict; use Strict;
/** @var array IDibiResultDriver */ /** @var array ResultDriver */
private $driver; private $driver;
/** @var array Translate table */ /** @var array Translate table */
private $types = []; private $types = [];
/** @var DibiResultInfo */ /** @var Reflection\Result */
private $meta; private $meta;
/** @var bool Already fetched? Used for allowance for first seek(0) */ /** @var bool Already fetched? Used for allowance for first seek(0) */
private $fetched = FALSE; private $fetched = FALSE;
/** @var string returned object class */ /** @var string returned object class */
private $rowClass = 'DibiRow'; private $rowClass = 'Dibi\Row';
/** @var Callback returned object factory*/ /** @var callable returned object factory*/
private $rowFactory; private $rowFactory;
/** @var array format */ /** @var array format */
@@ -51,7 +53,7 @@ class DibiResult implements IDataSource
/** /**
* @param IDibiResultDriver * @param ResultDriver
*/ */
public function __construct($driver) public function __construct($driver)
{ {
@@ -84,13 +86,13 @@ class DibiResult implements IDataSource
/** /**
* Safe access to property $driver. * Safe access to property $driver.
* @return IDibiResultDriver * @return ResultDriver
* @throws RuntimeException * @throws \RuntimeException
*/ */
final public function getResultDriver() final public function getResultDriver()
{ {
if ($this->driver === NULL) { if ($this->driver === NULL) {
throw new RuntimeException('Result-set was released from memory.'); throw new \RuntimeException('Result-set was released from memory.');
} }
return $this->driver; return $this->driver;
@@ -104,7 +106,7 @@ class DibiResult implements IDataSource
* Moves cursor position without fetching row. * Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to * @param int the 0-based cursor pos to seek to
* @return bool TRUE on success, FALSE if unable to seek to specified record * @return bool TRUE on success, FALSE if unable to seek to specified record
* @throws DibiException * @throws Exception
*/ */
final public function seek($row) final public function seek($row)
{ {
@@ -134,11 +136,11 @@ class DibiResult implements IDataSource
/** /**
* Required by the IteratorAggregate interface. * Required by the IteratorAggregate interface.
* @return DibiResultIterator * @return ResultIterator
*/ */
final public function getIterator() final public function getIterator()
{ {
return new DibiResultIterator($this); return new ResultIterator($this);
} }
@@ -146,7 +148,7 @@ class DibiResult implements IDataSource
/** /**
* Set fetched object class. This class should extend the DibiRow class. * Set fetched object class. This class should extend the Row class.
* @param string * @param string
* @return self * @return self
*/ */
@@ -168,7 +170,7 @@ class DibiResult implements IDataSource
/** /**
* Set a factory to create fetched object instances. These should extend the DibiRow class. * Set a factory to create fetched object instances. These should extend the Row class.
* @param callback * @param callback
* @return self * @return self
*/ */
@@ -182,7 +184,7 @@ class DibiResult implements IDataSource
/** /**
* Fetches the row at current position, process optional type conversion. * Fetches the row at current position, process optional type conversion.
* and moves the internal cursor to the next position * and moves the internal cursor to the next position
* @return DibiRow|FALSE array on success, FALSE if no next record * @return Row|FALSE array on success, FALSE if no next record
*/ */
final public function fetch() final public function fetch()
{ {
@@ -221,7 +223,7 @@ class DibiResult implements IDataSource
* Fetches all records from table. * Fetches all records from table.
* @param int offset * @param int offset
* @param int limit * @param int limit
* @return DibiRow[] * @return Row[]
*/ */
final public function fetchAll($offset = NULL, $limit = NULL) final public function fetchAll($offset = NULL, $limit = NULL)
{ {
@@ -253,8 +255,8 @@ class DibiResult implements IDataSource
* - associative descriptor: col1|col2->col3=col4 * - associative descriptor: col1|col2->col3=col4
* builds a tree: $tree[$val1][$val2]->col3[$val3] = val4 * builds a tree: $tree[$val1][$val2]->col3[$val3] = val4
* @param string associative descriptor * @param string associative descriptor
* @return DibiRow * @return Row
* @throws InvalidArgumentException * @throws \InvalidArgumentException
*/ */
final public function fetchAssoc($assoc) final public function fetchAssoc($assoc)
{ {
@@ -275,7 +277,7 @@ class DibiResult implements IDataSource
foreach ($assoc as $as) { foreach ($assoc as $as) {
// offsetExists ignores NULL in PHP 5.2.1, isset() surprisingly NULL accepts // offsetExists ignores NULL in PHP 5.2.1, isset() surprisingly NULL accepts
if ($as !== '[]' && $as !== '=' && $as !== '->' && $as !== '|' && !property_exists($row, $as)) { if ($as !== '[]' && $as !== '=' && $as !== '->' && $as !== '|' && !property_exists($row, $as)) {
throw new InvalidArgumentException("Unknown column '$as' in associative descriptor."); throw new \InvalidArgumentException("Unknown column '$as' in associative descriptor.");
} }
} }
@@ -403,7 +405,7 @@ class DibiResult implements IDataSource
* @param string associative key * @param string associative key
* @param string value * @param string value
* @return array * @return array
* @throws InvalidArgumentException * @throws \InvalidArgumentException
*/ */
final public function fetchPairs($key = NULL, $value = NULL) final public function fetchPairs($key = NULL, $value = NULL)
{ {
@@ -417,7 +419,7 @@ class DibiResult implements IDataSource
if ($value === NULL) { if ($value === NULL) {
if ($key !== NULL) { if ($key !== NULL) {
throw new InvalidArgumentException('Either none or both columns must be specified.'); throw new \InvalidArgumentException('Either none or both columns must be specified.');
} }
// autodetect // autodetect
@@ -434,7 +436,7 @@ class DibiResult implements IDataSource
} else { } else {
if (!property_exists($row, $value)) { if (!property_exists($row, $value)) {
throw new InvalidArgumentException("Unknown value column '$value'."); throw new \InvalidArgumentException("Unknown value column '$value'.");
} }
if ($key === NULL) { // indexed-array if ($key === NULL) { // indexed-array
@@ -445,7 +447,7 @@ class DibiResult implements IDataSource
} }
if (!property_exists($row, $key)) { if (!property_exists($row, $key)) {
throw new InvalidArgumentException("Unknown key column '$key'."); throw new \InvalidArgumentException("Unknown key column '$key'.");
} }
} }
@@ -466,12 +468,12 @@ class DibiResult implements IDataSource
*/ */
private function detectTypes() private function detectTypes()
{ {
$cache = DibiColumnInfo::getTypeCache(); $cache = Reflection\Column::getTypeCache();
try { try {
foreach ($this->getResultDriver()->getResultColumns() as $col) { foreach ($this->getResultDriver()->getResultColumns() as $col) {
$this->types[$col['name']] = $cache->{$col['nativetype']}; $this->types[$col['name']] = $cache->{$col['nativetype']};
} }
} catch (DibiNotSupportedException $e) { } catch (NotSupportedException $e) {
} }
} }
@@ -488,24 +490,24 @@ class DibiResult implements IDataSource
continue; continue;
} }
$value = $row[$key]; $value = $row[$key];
if ($value === FALSE || $type === DibiType::TEXT) { if ($value === FALSE || $type === Type::TEXT) {
} elseif ($type === DibiType::INTEGER) { } elseif ($type === Type::INTEGER) {
$row[$key] = is_float($tmp = $value * 1) ? $value : $tmp; $row[$key] = is_float($tmp = $value * 1) ? $value : $tmp;
} elseif ($type === DibiType::FLOAT) { } elseif ($type === Type::FLOAT) {
$row[$key] = str_replace(',', '.', ltrim((string) ($tmp = (float) $value), '0')) === ltrim(rtrim(rtrim($value, '0'), '.'), '0') ? $tmp : $value; $row[$key] = str_replace(',', '.', ltrim((string) ($tmp = (float) $value), '0')) === ltrim(rtrim(rtrim($value, '0'), '.'), '0') ? $tmp : $value;
} elseif ($type === DibiType::BOOL) { } elseif ($type === Type::BOOL) {
$row[$key] = ((bool) $value) && $value !== 'f' && $value !== 'F'; $row[$key] = ((bool) $value) && $value !== 'f' && $value !== 'F';
} elseif ($type === DibiType::DATE || $type === DibiType::DATETIME) { } elseif ($type === Type::DATE || $type === Type::DATETIME) {
if ((int) $value !== 0 || substr((string) $value, 0, 3) === '00:') { // '', NULL, FALSE, '0000-00-00', ... if ((int) $value !== 0 || substr((string) $value, 0, 3) === '00:') { // '', NULL, FALSE, '0000-00-00', ...
$value = new DibiDateTime($value); $value = new DateTime($value);
$row[$key] = empty($this->formats[$type]) ? $value : $value->format($this->formats[$type]); $row[$key] = empty($this->formats[$type]) ? $value : $value->format($this->formats[$type]);
} }
} elseif ($type === DibiType::BINARY) { } elseif ($type === Type::BINARY) {
$row[$key] = $this->getResultDriver()->unescapeBinary($value); $row[$key] = $this->getResultDriver()->unescapeBinary($value);
} }
} }
@@ -515,7 +517,7 @@ class DibiResult implements IDataSource
/** /**
* Define column type. * Define column type.
* @param string column * @param string column
* @param string type (use constant DibiType::*) * @param string type (use constant Type::*)
* @return self * @return self
*/ */
final public function setType($col, $type) final public function setType($col, $type)
@@ -537,7 +539,7 @@ class DibiResult implements IDataSource
/** /**
* Sets data format. * Sets data format.
* @param string type (use constant DibiType::*) * @param string type (use constant Type::*)
* @param string format * @param string format
* @return self * @return self
*/ */
@@ -563,12 +565,12 @@ class DibiResult implements IDataSource
/** /**
* Returns a meta information about the current result set. * Returns a meta information about the current result set.
* @return DibiResultInfo * @return Reflection\Result
*/ */
public function getInfo() public function getInfo()
{ {
if ($this->meta === NULL) { if ($this->meta === NULL) {
$this->meta = new DibiResultInfo($this->getResultDriver()); $this->meta = new Reflection\Result($this->getResultDriver());
} }
return $this->meta; return $this->meta;
} }

View File

@@ -5,11 +5,13 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi;
/** /**
* External result set iterator. * External result set iterator.
* *
* This can be returned by DibiResult::getIterator() method or using foreach * This can be returned by Result::getIterator() method or using foreach
* <code> * <code>
* $result = dibi::query('SELECT * FROM table'); * $result = dibi::query('SELECT * FROM table');
* foreach ($result as $row) { * foreach ($result as $row) {
@@ -18,11 +20,11 @@
* unset($result); * unset($result);
* </code> * </code>
*/ */
class DibiResultIterator implements Iterator, Countable class ResultIterator implements \Iterator, \Countable
{ {
use DibiStrict; use Strict;
/** @var DibiResult */ /** @var Result */
private $result; private $result;
/** @var int */ /** @var int */
@@ -33,9 +35,9 @@ class DibiResultIterator implements Iterator, Countable
/** /**
* @param DibiResult * @param Result
*/ */
public function __construct(DibiResult $result) public function __construct(Result $result)
{ {
$this->result = $result; $this->result = $result;
} }

View File

@@ -5,11 +5,13 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi;
/** /**
* Result set single row. * Result set single row.
*/ */
class DibiRow implements ArrayAccess, IteratorAggregate, Countable class Row implements \ArrayAccess, \IteratorAggregate, \Countable
{ {
public function __construct($arr) public function __construct($arr)
@@ -30,16 +32,16 @@ class DibiRow implements ArrayAccess, IteratorAggregate, Countable
* Converts value to DateTime object. * Converts value to DateTime object.
* @param string key * @param string key
* @param string format * @param string format
* @return DateTime * @return \DateTime
*/ */
public function asDateTime($key, $format = NULL) public function asDateTime($key, $format = NULL)
{ {
$time = $this[$key]; $time = $this[$key];
if (!$time instanceof DibiDateTime) { if (!$time instanceof DateTime) {
if ((int) $time === 0 && substr((string) $time, 0, 3) !== '00:') { // '', NULL, FALSE, '0000-00-00', ... if ((int) $time === 0 && substr((string) $time, 0, 3) !== '00:') { // '', NULL, FALSE, '0000-00-00', ...
return NULL; return NULL;
} }
$time = new DibiDateTime($time); $time = new DateTime($time);
} }
return $format === NULL ? $time : $time->format($format); return $format === NULL ? $time : $time->format($format);
} }
@@ -47,7 +49,7 @@ class DibiRow implements ArrayAccess, IteratorAggregate, Countable
public function __get($key) public function __get($key)
{ {
$hint = DibiHelpers::getSuggestion(array_keys((array) $this), $key); $hint = Helpers::getSuggestion(array_keys((array) $this), $key);
trigger_error("Attempt to read missing column '$key'" . ($hint ? ", did you mean '$hint'?" : '.'), E_USER_NOTICE); trigger_error("Attempt to read missing column '$key'" . ($hint ? ", did you mean '$hint'?" : '.'), E_USER_NOTICE);
} }
@@ -63,7 +65,7 @@ class DibiRow implements ArrayAccess, IteratorAggregate, Countable
final public function getIterator() final public function getIterator()
{ {
return new ArrayIterator($this); return new \ArrayIterator($this);
} }

View File

@@ -5,11 +5,17 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi;
use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
/** /**
* Better OOP experience. * Better OOP experience.
*/ */
trait DibiStrict trait Strict
{ {
/** @var array [method => [type => callback]] */ /** @var array [method => [type => callback]] */
private static $extMethods; private static $extMethods;
@@ -17,7 +23,7 @@ trait DibiStrict
/** /**
* Call to undefined method. * Call to undefined method.
* @throws LogicException * @throws \LogicException
*/ */
public function __call($name, $args) public function __call($name, $args)
{ {
@@ -27,27 +33,27 @@ trait DibiStrict
} }
$class = method_exists($this, $name) ? 'parent' : get_class($this); $class = method_exists($this, $name) ? 'parent' : get_class($this);
$items = (new ReflectionClass($this))->getMethods(ReflectionMethod::IS_PUBLIC); $items = (new ReflectionClass($this))->getMethods(ReflectionMethod::IS_PUBLIC);
$hint = ($t = DibiHelpers::getSuggestion($items, $name)) ? ", did you mean $t()?" : '.'; $hint = ($t = Helpers::getSuggestion($items, $name)) ? ", did you mean $t()?" : '.';
throw new LogicException("Call to undefined method $class::$name()$hint"); throw new \LogicException("Call to undefined method $class::$name()$hint");
} }
/** /**
* Call to undefined static method. * Call to undefined static method.
* @throws LogicException * @throws \LogicException
*/ */
public static function __callStatic($name, $args) public static function __callStatic($name, $args)
{ {
$rc = new ReflectionClass(get_called_class()); $rc = new ReflectionClass(get_called_class());
$items = array_intersect($rc->getMethods(ReflectionMethod::IS_PUBLIC), $rc->getMethods(ReflectionMethod::IS_STATIC)); $items = array_intersect($rc->getMethods(ReflectionMethod::IS_PUBLIC), $rc->getMethods(ReflectionMethod::IS_STATIC));
$hint = ($t = DibiHelpers::getSuggestion($items, $name)) ? ", did you mean $t()?" : '.'; $hint = ($t = Helpers::getSuggestion($items, $name)) ? ", did you mean $t()?" : '.';
throw new LogicException("Call to undefined static method {$rc->getName()}::$name()$hint"); throw new \LogicException("Call to undefined static method {$rc->getName()}::$name()$hint");
} }
/** /**
* Access to undeclared property. * Access to undeclared property.
* @throws LogicException * @throws \LogicException
*/ */
public function &__get($name) public function &__get($name)
{ {
@@ -59,21 +65,21 @@ trait DibiStrict
} }
$rc = new ReflectionClass($this); $rc = new ReflectionClass($this);
$items = array_diff($rc->getProperties(ReflectionProperty::IS_PUBLIC), $rc->getProperties(ReflectionProperty::IS_STATIC)); $items = array_diff($rc->getProperties(ReflectionProperty::IS_PUBLIC), $rc->getProperties(ReflectionProperty::IS_STATIC));
$hint = ($t = DibiHelpers::getSuggestion($items, $name)) ? ", did you mean $$t?" : '.'; $hint = ($t = Helpers::getSuggestion($items, $name)) ? ", did you mean $$t?" : '.';
throw new LogicException("Attempt to read undeclared property {$rc->getName()}::$$name$hint"); throw new \LogicException("Attempt to read undeclared property {$rc->getName()}::$$name$hint");
} }
/** /**
* Access to undeclared property. * Access to undeclared property.
* @throws LogicException * @throws \LogicException
*/ */
public function __set($name, $value) public function __set($name, $value)
{ {
$rc = new ReflectionClass($this); $rc = new ReflectionClass($this);
$items = array_diff($rc->getProperties(ReflectionProperty::IS_PUBLIC), $rc->getProperties(ReflectionProperty::IS_STATIC)); $items = array_diff($rc->getProperties(ReflectionProperty::IS_PUBLIC), $rc->getProperties(ReflectionProperty::IS_STATIC));
$hint = ($t = DibiHelpers::getSuggestion($items, $name)) ? ", did you mean $$t?" : '.'; $hint = ($t = Helpers::getSuggestion($items, $name)) ? ", did you mean $$t?" : '.';
throw new LogicException("Attempt to write to undeclared property {$rc->getName()}::$$name$hint"); throw new \LogicException("Attempt to write to undeclared property {$rc->getName()}::$$name$hint");
} }
@@ -88,12 +94,12 @@ trait DibiStrict
/** /**
* Access to undeclared property. * Access to undeclared property.
* @throws LogicException * @throws \LogicException
*/ */
public function __unset($name) public function __unset($name)
{ {
$class = get_class($this); $class = get_class($this);
throw new LogicException("Attempt to unset undeclared property $class::$$name."); throw new \LogicException("Attempt to unset undeclared property $class::$$name.");
} }
@@ -108,7 +114,7 @@ trait DibiStrict
$class = get_called_class(); $class = get_called_class();
} else { } else {
list($class, $name) = explode('::', $name); list($class, $name) = explode('::', $name);
$class = (new \ReflectionClass($class))->getName(); $class = (new ReflectionClass($class))->getName();
} }
$list = & self::$extMethods[strtolower($name)]; $list = & self::$extMethods[strtolower($name)];
if ($callback === NULL) { // getter if ($callback === NULL) { // getter

View File

@@ -5,18 +5,20 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi;
/** /**
* dibi SQL translator. * dibi SQL translator.
*/ */
final class DibiTranslator final class Translator
{ {
use DibiStrict; use Strict;
/** @var DibiConnection */ /** @var Connection */
private $connection; private $connection;
/** @var IDibiDriver */ /** @var Driver */
private $driver; private $driver;
/** @var int */ /** @var int */
@@ -43,14 +45,14 @@ final class DibiTranslator
/** @var int */ /** @var int */
private $offset; private $offset;
/** @var DibiHashMap */ /** @var HashMap */
private $identifiers; private $identifiers;
public function __construct(DibiConnection $connection) public function __construct(Connection $connection)
{ {
$this->connection = $connection; $this->connection = $connection;
$this->identifiers = new DibiHashMap([$this, 'delimite']); $this->identifiers = new HashMap([$this, 'delimite']);
} }
@@ -58,7 +60,7 @@ final class DibiTranslator
* Generates SQL. * Generates SQL.
* @param array * @param array
* @return string * @return string
* @throws DibiException * @throws Exception
*/ */
public function translate(array $args) public function translate(array $args)
{ {
@@ -120,7 +122,7 @@ final class DibiTranslator
substr($arg, $toSkip) substr($arg, $toSkip)
); );
if (preg_last_error()) { if (preg_last_error()) {
throw new DibiPcreException; throw new PcreException;
} }
} }
continue; continue;
@@ -131,7 +133,7 @@ final class DibiTranslator
continue; continue;
} }
if ($arg instanceof Traversable) { if ($arg instanceof \Traversable) {
$arg = iterator_to_array($arg); $arg = iterator_to_array($arg);
} }
@@ -165,7 +167,7 @@ final class DibiTranslator
$sql = implode(' ', $sql); $sql = implode(' ', $sql);
if ($this->hasError) { if ($this->hasError) {
throw new DibiException('SQL translate error', 0, $sql); throw new Exception('SQL translate error', 0, $sql);
} }
// apply limit // apply limit
@@ -194,7 +196,7 @@ final class DibiTranslator
} }
// array processing (with or without modifier) // array processing (with or without modifier)
if ($value instanceof Traversable) { if ($value instanceof \Traversable) {
$value = iterator_to_array($value); $value = iterator_to_array($value);
} }
@@ -332,7 +334,7 @@ final class DibiTranslator
// with modifier procession // with modifier procession
if ($modifier) { if ($modifier) {
if ($value !== NULL && !is_scalar($value) && !$value instanceof DateTime && !$value instanceof DateTimeInterface) { // array is already processed if ($value !== NULL && !is_scalar($value) && !$value instanceof \DateTime && !$value instanceof \DateTimeInterface) { // array is already processed
$this->hasError = TRUE; $this->hasError = TRUE;
return '**Unexpected type ' . gettype($value) . '**'; return '**Unexpected type ' . gettype($value) . '**';
} }
@@ -405,7 +407,7 @@ final class DibiTranslator
substr($value, $toSkip) substr($value, $toSkip)
); );
if (preg_last_error()) { if (preg_last_error()) {
throw new DibiPcreException; throw new PcreException;
} }
} }
return $value; return $value;
@@ -453,10 +455,10 @@ final class DibiTranslator
} elseif ($value === NULL) { } elseif ($value === NULL) {
return 'NULL'; return 'NULL';
} elseif ($value instanceof DateTime || $value instanceof DateTimeInterface) { } elseif ($value instanceof \DateTime || $value instanceof \DateTimeInterface) {
return $this->driver->escapeDateTime($value); return $this->driver->escapeDateTime($value);
} elseif ($value instanceof DibiLiteral) { } elseif ($value instanceof Literal) {
return (string) $value; return (string) $value;
} else { } else {

View File

@@ -5,11 +5,13 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi;
/** /**
* Data types. * Data types.
*/ */
class DibiType class Type
{ {
const const
TEXT = 's', // as 'string' TEXT = 's', // as 'string'
@@ -23,7 +25,7 @@ class DibiType
final public function __construct() final public function __construct()
{ {
throw new LogicException('Cannot instantiate static class ' . __CLASS__); throw new \LogicException('Cannot instantiate static class ' . __CLASS__);
} }
} }

View File

@@ -5,6 +5,8 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
use Dibi\Type;
/** /**
* This class is static container class for creating DB objects and * This class is static container class for creating DB objects and
@@ -12,7 +14,7 @@
*/ */
class dibi class dibi
{ {
use DibiStrict; use Dibi\Strict;
const const
AFFECTED_ROWS = 'a', AFFECTED_ROWS = 'a',
@@ -30,27 +32,27 @@ class dibi
/** @deprecated */ /** @deprecated */
const const
TEXT = DibiType::TEXT, TEXT = Type::TEXT,
BINARY = DibiType::BINARY, BINARY = Type::BINARY,
BOOL = DibiType::BOOL, BOOL = Type::BOOL,
INTEGER = DibiType::INTEGER, INTEGER = Type::INTEGER,
FLOAT = DibiType::FLOAT, FLOAT = Type::FLOAT,
DATE = DibiType::DATE, DATE = Type::DATE,
DATETIME = DibiType::DATETIME, DATETIME = Type::DATETIME,
TIME = DibiType::TIME, TIME = Type::TIME,
FIELD_TEXT = DibiType::TEXT, FIELD_TEXT = Type::TEXT,
FIELD_BINARY = DibiType::BINARY, FIELD_BINARY = Type::BINARY,
FIELD_BOOL = DibiType::BOOL, FIELD_BOOL = Type::BOOL,
FIELD_INTEGER = DibiType::INTEGER, FIELD_INTEGER = Type::INTEGER,
FIELD_FLOAT = DibiType::FLOAT, FIELD_FLOAT = Type::FLOAT,
FIELD_DATE = DibiType::DATE, FIELD_DATE = Type::DATE,
FIELD_DATETIME = DibiType::DATETIME, FIELD_DATETIME = Type::DATETIME,
FIELD_TIME = DibiType::TIME; FIELD_TIME = Type::TIME;
/** @var DibiConnection[] Connection registry storage for DibiConnection objects */ /** @var Dibi\Connection[] Connection registry storage for DibiConnection objects */
private static $registry = []; private static $registry = [];
/** @var DibiConnection Current connection */ /** @var Dibi\Connection Current connection */
private static $connection; private static $connection;
/** @var string Last SQL command @see dibi::query() */ /** @var string Last SQL command @see dibi::query() */
@@ -82,20 +84,20 @@ class dibi
/** /**
* Creates a new DibiConnection object and connects it to specified database. * Creates a new Connection object and connects it to specified database.
* @param mixed connection parameters * @param mixed connection parameters
* @param string connection name * @param string connection name
* @return DibiConnection * @return Dibi\Connection
* @throws DibiException * @throws Dibi\Exception
*/ */
public static function connect($config = [], $name = 0) public static function connect($config = [], $name = 0)
{ {
return self::$connection = self::$registry[$name] = new DibiConnection($config, $name); return self::$connection = self::$registry[$name] = new Dibi\Connection($config, $name);
} }
/** /**
* Disconnects from database (doesn't destroy DibiConnection object). * Disconnects from database (doesn't destroy Connection object).
* @return void * @return void
*/ */
public static function disconnect() public static function disconnect()
@@ -117,21 +119,21 @@ class dibi
/** /**
* Retrieve active connection. * Retrieve active connection.
* @param string connection registy name * @param string connection registy name
* @return DibiConnection * @return Dibi\Connection
* @throws DibiException * @throws Dibi\Exception
*/ */
public static function getConnection($name = NULL) public static function getConnection($name = NULL)
{ {
if ($name === NULL) { if ($name === NULL) {
if (self::$connection === NULL) { if (self::$connection === NULL) {
throw new DibiException('Dibi is not connected to database.'); throw new Dibi\Exception('Dibi is not connected to database.');
} }
return self::$connection; return self::$connection;
} }
if (!isset(self::$registry[$name])) { if (!isset(self::$registry[$name])) {
throw new DibiException("There is no connection named '$name'."); throw new Dibi\Exception("There is no connection named '$name'.");
} }
return self::$registry[$name]; return self::$registry[$name];
@@ -140,10 +142,10 @@ class dibi
/** /**
* Sets connection. * Sets connection.
* @param DibiConnection * @param Dibi\Connection
* @return DibiConnection * @return Dibi\Connection
*/ */
public static function setConnection(DibiConnection $connection) public static function setConnection(Dibi\Connection $connection)
{ {
return self::$connection = $connection; return self::$connection = $connection;
} }
@@ -163,10 +165,10 @@ class dibi
/** /**
* Generates and executes SQL query - Monostate for DibiConnection::query(). * Generates and executes SQL query - Monostate for Dibi\Connection::query().
* @param array|mixed one or more arguments * @param array|mixed one or more arguments
* @return DibiResult|int result set object (if any) * @return Dibi\Result|int result set object (if any)
* @throws DibiException * @throws Dibi\Exception
*/ */
public static function query($args) public static function query($args)
{ {
@@ -176,9 +178,9 @@ class dibi
/** /**
* Executes the SQL query - Monostate for DibiConnection::nativeQuery(). * Executes the SQL query - Monostate for Dibi\Connection::nativeQuery().
* @param string SQL statement. * @param string SQL statement.
* @return DibiResult|int result set object (if any) * @return Dibi\Result|int result set object (if any)
*/ */
public static function nativeQuery($sql) public static function nativeQuery($sql)
{ {
@@ -187,7 +189,7 @@ class dibi
/** /**
* Generates and prints SQL query - Monostate for DibiConnection::test(). * Generates and prints SQL query - Monostate for Dibi\Connection::test().
* @param array|mixed one or more arguments * @param array|mixed one or more arguments
* @return bool * @return bool
*/ */
@@ -199,9 +201,9 @@ class dibi
/** /**
* Generates and returns SQL query as DibiDataSource - Monostate for DibiConnection::test(). * Generates and returns SQL query as DataSource - Monostate for Dibi\Connection::test().
* @param array|mixed one or more arguments * @param array|mixed one or more arguments
* @return DibiDataSource * @return Dibi\DataSource
*/ */
public static function dataSource($args) public static function dataSource($args)
{ {
@@ -211,10 +213,10 @@ class dibi
/** /**
* Executes SQL query and fetch result - Monostate for DibiConnection::query() & fetch(). * Executes SQL query and fetch result - Monostate for Dibi\Connection::query() & fetch().
* @param array|mixed one or more arguments * @param array|mixed one or more arguments
* @return DibiRow * @return Dibi\Row
* @throws DibiException * @throws Dibi\Exception
*/ */
public static function fetch($args) public static function fetch($args)
{ {
@@ -224,10 +226,10 @@ class dibi
/** /**
* Executes SQL query and fetch results - Monostate for DibiConnection::query() & fetchAll(). * Executes SQL query and fetch results - Monostate for Dibi\Connection::query() & fetchAll().
* @param array|mixed one or more arguments * @param array|mixed one or more arguments
* @return DibiRow[] * @return Dibi\Row[]
* @throws DibiException * @throws Dibi\Exception
*/ */
public static function fetchAll($args) public static function fetchAll($args)
{ {
@@ -237,10 +239,10 @@ class dibi
/** /**
* Executes SQL query and fetch first column - Monostate for DibiConnection::query() & fetchSingle(). * Executes SQL query and fetch first column - Monostate for Dibi\Connection::query() & fetchSingle().
* @param array|mixed one or more arguments * @param array|mixed one or more arguments
* @return string * @return string
* @throws DibiException * @throws Dibi\Exception
*/ */
public static function fetchSingle($args) public static function fetchSingle($args)
{ {
@@ -250,10 +252,10 @@ class dibi
/** /**
* Executes SQL query and fetch pairs - Monostate for DibiConnection::query() & fetchPairs(). * Executes SQL query and fetch pairs - Monostate for Dibi\Connection::query() & fetchPairs().
* @param array|mixed one or more arguments * @param array|mixed one or more arguments
* @return string * @return string
* @throws DibiException * @throws Dibi\Exception
*/ */
public static function fetchPairs($args) public static function fetchPairs($args)
{ {
@@ -264,9 +266,9 @@ class dibi
/** /**
* Gets the number of affected rows. * Gets the number of affected rows.
* Monostate for DibiConnection::getAffectedRows() * Monostate for Dibi\Connection::getAffectedRows()
* @return int number of rows * @return int number of rows
* @throws DibiException * @throws Dibi\Exception
*/ */
public static function getAffectedRows() public static function getAffectedRows()
{ {
@@ -277,7 +279,7 @@ class dibi
/** /**
* Gets the number of affected rows. Alias for getAffectedRows(). * Gets the number of affected rows. Alias for getAffectedRows().
* @return int number of rows * @return int number of rows
* @throws DibiException * @throws Dibi\Exception
*/ */
public static function affectedRows() public static function affectedRows()
{ {
@@ -287,10 +289,10 @@ class dibi
/** /**
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query. * Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
* Monostate for DibiConnection::getInsertId() * Monostate for Dibi\Connection::getInsertId()
* @param string optional sequence name * @param string optional sequence name
* @return int * @return int
* @throws DibiException * @throws Dibi\Exception
*/ */
public static function getInsertId($sequence = NULL) public static function getInsertId($sequence = NULL)
{ {
@@ -302,7 +304,7 @@ class dibi
* Retrieves the ID generated for an AUTO_INCREMENT column. Alias for getInsertId(). * Retrieves the ID generated for an AUTO_INCREMENT column. Alias for getInsertId().
* @param string optional sequence name * @param string optional sequence name
* @return int * @return int
* @throws DibiException * @throws Dibi\Exception
*/ */
public static function insertId($sequence = NULL) public static function insertId($sequence = NULL)
{ {
@@ -311,10 +313,10 @@ class dibi
/** /**
* Begins a transaction - Monostate for DibiConnection::begin(). * Begins a transaction - Monostate for Dibi\Connection::begin().
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiException * @throws Dibi\Exception
*/ */
public static function begin($savepoint = NULL) public static function begin($savepoint = NULL)
{ {
@@ -323,10 +325,10 @@ class dibi
/** /**
* Commits statements in a transaction - Monostate for DibiConnection::commit($savepoint = NULL). * Commits statements in a transaction - Monostate for Dibi\Connection::commit($savepoint = NULL).
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiException * @throws Dibi\Exception
*/ */
public static function commit($savepoint = NULL) public static function commit($savepoint = NULL)
{ {
@@ -335,10 +337,10 @@ class dibi
/** /**
* Rollback changes in a transaction - Monostate for DibiConnection::rollback(). * Rollback changes in a transaction - Monostate for Dibi\Connection::rollback().
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiException * @throws Dibi\Exception
*/ */
public static function rollback($savepoint = NULL) public static function rollback($savepoint = NULL)
{ {
@@ -347,8 +349,8 @@ class dibi
/** /**
* Gets a information about the current database - Monostate for DibiConnection::getDatabaseInfo(). * Gets a information about the current database - Monostate for Dibi\Connection::getDatabaseInfo().
* @return DibiDatabaseInfo * @return Dibi\Reflection\Database
*/ */
public static function getDatabaseInfo() public static function getDatabaseInfo()
{ {
@@ -383,7 +385,7 @@ class dibi
/** /**
* @return DibiFluent * @return Dibi\Fluent
*/ */
public static function command() public static function command()
{ {
@@ -393,7 +395,7 @@ class dibi
/** /**
* @param string column name * @param string column name
* @return DibiFluent * @return Dibi\Fluent
*/ */
public static function select($args) public static function select($args)
{ {
@@ -405,7 +407,7 @@ class dibi
/** /**
* @param string table * @param string table
* @param array * @param array
* @return DibiFluent * @return Dibi\Fluent
*/ */
public static function update($table, $args) public static function update($table, $args)
{ {
@@ -416,7 +418,7 @@ class dibi
/** /**
* @param string table * @param string table
* @param array * @param array
* @return DibiFluent * @return Dibi\Fluent
*/ */
public static function insert($table, $args) public static function insert($table, $args)
{ {
@@ -426,7 +428,7 @@ class dibi
/** /**
* @param string table * @param string table
* @return DibiFluent * @return Dibi\Fluent
*/ */
public static function delete($table) public static function delete($table)
{ {
@@ -438,8 +440,8 @@ class dibi
/** /**
* Returns substitution hashmap - Monostate for DibiConnection::getSubstitutes(). * Returns substitution hashmap - Monostate for Dibi\Connection::getSubstitutes().
* @return DibiHashMap * @return Dibi\HashMap
*/ */
public static function getSubstitutes() public static function getSubstitutes()
{ {
@@ -451,14 +453,14 @@ class dibi
/** /**
* Prints out a syntax highlighted version of the SQL command or DibiResult. * Prints out a syntax highlighted version of the SQL command or Result.
* @param string|DibiResult * @param string|Result
* @param bool return output instead of printing it? * @param bool return output instead of printing it?
* @return string * @return string
*/ */
public static function dump($sql = NULL, $return = FALSE) public static function dump($sql = NULL, $return = FALSE)
{ {
return DibiHelpers::dump($sql, $return); return Dibi\Helpers::dump($sql, $return);
} }
} }

View File

@@ -5,13 +5,15 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi;
/** /**
* dibi common exception. * dibi common exception.
*/ */
class DibiException extends Exception class Exception extends \Exception
{ {
use DibiStrict; use Strict;
/** @var string */ /** @var string */
private $sql; private $sql;
@@ -53,7 +55,7 @@ class DibiException extends Exception
/** /**
* database server exception. * database server exception.
*/ */
class DibiDriverException extends DibiException class DriverException extends Exception
{ {
/********************* error catching ****************d*g**/ /********************* error catching ****************d*g**/
@@ -110,9 +112,9 @@ class DibiDriverException extends DibiException
/** /**
* PCRE exception. * PCRE exception.
*/ */
class DibiPcreException extends Exception class PcreException extends \Exception
{ {
use DibiStrict; use Strict;
public function __construct($message = '%msg.') public function __construct($message = '%msg.')
{ {
@@ -129,18 +131,18 @@ class DibiPcreException extends Exception
} }
class DibiNotImplementedException extends DibiException class NotImplementedException extends Exception
{} {}
class DibiNotSupportedException extends DibiException class NotSupportedException extends Exception
{} {}
/** /**
* Database procedure exception. * Database procedure exception.
*/ */
class DibiProcedureException extends DibiException class ProcedureException extends Exception
{ {
/** @var string */ /** @var string */
protected $severity; protected $severity;

View File

@@ -5,43 +5,45 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com) * Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/ */
namespace Dibi;
/** /**
* Provides an interface between a dataset and data-aware components. * Provides an interface between a dataset and data-aware components.
*/ */
interface IDataSource extends Countable, IteratorAggregate interface IDataSource extends \Countable, \IteratorAggregate
{ {
//function IteratorAggregate::getIterator(); //function \IteratorAggregate::getIterator();
//function Countable::count(); //function \Countable::count();
} }
/** /**
* dibi driver interface. * dibi driver interface.
*/ */
interface IDibiDriver interface Driver
{ {
/** /**
* Connects to a database. * Connects to a database.
* @param array * @param array
* @return void * @return void
* @throws DibiException * @throws Exception
*/ */
function connect(array & $config); function connect(array & $config);
/** /**
* Disconnects from a database. * Disconnects from a database.
* @return void * @return void
* @throws DibiException * @throws Exception
*/ */
function disconnect(); function disconnect();
/** /**
* Internal: Executes the SQL query. * Internal: Executes the SQL query.
* @param string SQL statement. * @param string SQL statement.
* @return IDibiResultDriver|NULL * @return ResultDriver|NULL
* @throws DibiDriverException * @throws DriverException
*/ */
function query($sql); function query($sql);
@@ -61,7 +63,7 @@ interface IDibiDriver
* Begins a transaction (if supported). * Begins a transaction (if supported).
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws DriverException
*/ */
function begin($savepoint = NULL); function begin($savepoint = NULL);
@@ -69,7 +71,7 @@ interface IDibiDriver
* Commits statements in a transaction. * Commits statements in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws DriverException
*/ */
function commit($savepoint = NULL); function commit($savepoint = NULL);
@@ -77,7 +79,7 @@ interface IDibiDriver
* Rollback changes in a transaction. * Rollback changes in a transaction.
* @param string optional savepoint name * @param string optional savepoint name
* @return void * @return void
* @throws DibiDriverException * @throws DriverException
*/ */
function rollback($savepoint = NULL); function rollback($savepoint = NULL);
@@ -89,7 +91,7 @@ interface IDibiDriver
/** /**
* Returns the connection reflector. * Returns the connection reflector.
* @return IDibiReflector * @return Reflector
*/ */
function getReflector(); function getReflector();
@@ -130,7 +132,7 @@ interface IDibiDriver
/** /**
* dibi result set driver interface. * dibi result set driver interface.
*/ */
interface IDibiResultDriver interface ResultDriver
{ {
/** /**
@@ -143,7 +145,7 @@ interface IDibiResultDriver
* Moves cursor position without fetching row. * Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to * @param int the 0-based cursor pos to seek to
* @return boolean TRUE on success, FALSE if unable to seek to specified record * @return boolean TRUE on success, FALSE if unable to seek to specified record
* @throws DibiException * @throws Exception
*/ */
function seek($row); function seek($row);
@@ -187,7 +189,7 @@ interface IDibiResultDriver
/** /**
* dibi driver reflection. * dibi driver reflection.
*/ */
interface IDibiReflector interface Reflector
{ {
/** /**

View File

@@ -14,60 +14,129 @@ if (PHP_VERSION_ID < 50404) {
spl_autoload_register(function ($class) { spl_autoload_register(function ($class) {
static $map = [ static $map = [
'dibi' => 'dibi.php', 'dibi' => 'dibi.php',
'Dibi' => 'dibi.php',
'Dibi\Bridges\Nette\DibiExtension22' => 'Bridges/Nette/DibiExtension22.php', 'Dibi\Bridges\Nette\DibiExtension22' => 'Bridges/Nette/DibiExtension22.php',
'Dibi\Bridges\Nette\DibiExtension21' => 'Bridges/Nette/DibiExtension21.php',
'Dibi\Bridges\Nette\Panel' => 'Bridges/Nette/Panel.php',
'Dibi\Bridges\Tracy\Panel' => 'Bridges/Tracy/Panel.php', 'Dibi\Bridges\Tracy\Panel' => 'Bridges/Tracy/Panel.php',
'DibiColumnInfo' => 'Reflection/Column.php', 'Dibi\Connection' => 'Connection.php',
'DibiConnection' => 'Connection.php', 'Dibi\DataSource' => 'DataSource.php',
'DibiDatabaseInfo' => 'Reflection/Database.php', 'Dibi\DateTime' => 'DateTime.php',
'DibiDataSource' => 'DataSource.php', 'Dibi\Driver' => 'interfaces.php',
'DibiDateTime' => 'DateTime.php', 'Dibi\DriverException' => 'exceptions.php',
'DibiDriverException' => 'exceptions.php', 'Dibi\Drivers\FirebirdDriver' => 'Drivers/FirebirdDriver.php',
'DibiEvent' => 'Event.php', 'Dibi\Drivers\MsSql2005Driver' => 'Drivers/MsSql2005Driver.php',
'DibiException' => 'exceptions.php', 'Dibi\Drivers\MsSql2005Reflector' => 'Drivers/MsSql2005Reflector.php',
'DibiFileLogger' => 'Loggers/FileLogger.php', 'Dibi\Drivers\MsSqlDriver' => 'Drivers/MsSqlDriver.php',
'DibiFirebirdDriver' => 'Drivers/FirebirdDriver.php', 'Dibi\Drivers\MsSqlReflector' => 'Drivers/MsSqlReflector.php',
'DibiFirePhpLogger' => 'Loggers/FirePhpLogger.php', 'Dibi\Drivers\MySqlDriver' => 'Drivers/MySqlDriver.php',
'DibiFluent' => 'Fluent.php', 'Dibi\Drivers\MySqliDriver' => 'Drivers/MySqliDriver.php',
'DibiForeignKeyInfo' => 'Reflection/ForeignKey.php', 'Dibi\Drivers\MySqlReflector' => 'Drivers/MySqlReflector.php',
'DibiHashMap' => 'HashMap.php', 'Dibi\Drivers\OdbcDriver' => 'Drivers/OdbcDriver.php',
'DibiHashMapBase' => 'HashMap.php', 'Dibi\Drivers\OracleDriver' => 'Drivers/OracleDriver.php',
'DibiHelpers' => 'Helpers.php', 'Dibi\Drivers\PdoDriver' => 'Drivers/PdoDriver.php',
'DibiIndexInfo' => 'Reflection/Index.php', 'Dibi\Drivers\PostgreDriver' => 'Drivers/PostgreDriver.php',
'DibiLiteral' => 'Literal.php', 'Dibi\Drivers\Sqlite3Driver' => 'Drivers/Sqlite3Driver.php',
'DibiMsSql2005Driver' => 'Drivers/MsSql2005Driver.php', 'Dibi\Drivers\SqliteReflector' => 'Drivers/SqliteReflector.php',
'DibiMsSql2005Reflector' => 'Drivers/MsSql2005Reflector.php', 'Dibi\Event' => 'Event.php',
'DibiMsSqlDriver' => 'Drivers/MsSqlDriver.php', 'Dibi\Exception' => 'exceptions.php',
'DibiMsSqlReflector' => 'Drivers/MsSqlReflector.php', 'Dibi\Fluent' => 'Fluent.php',
'DibiMySqlDriver' => 'Drivers/MySqlDriver.php', 'Dibi\HashMap' => 'HashMap.php',
'DibiMySqliDriver' => 'Drivers/MySqliDriver.php', 'Dibi\HashMapBase' => 'HashMap.php',
'DibiMySqlReflector' => 'Drivers/MySqlReflector.php', 'Dibi\Helpers' => 'Helpers.php',
'DibiNette21Extension' => 'Bridges/Nette/DibiExtension21.php', 'Dibi\IDataSource' => 'interfaces.php',
'DibiNettePanel' => 'Bridges/Nette/Panel.php', 'Dibi\Literal' => 'Literal.php',
'DibiNotImplementedException' => 'exceptions.php', 'Dibi\Loggers\FileLogger' => 'Loggers/FileLogger.php',
'DibiNotSupportedException' => 'exceptions.php', 'Dibi\Loggers\FirePhpLogger' => 'Loggers/FirePhpLogger.php',
'DibiStrict' => 'Strict.php', 'Dibi\NotImplementedException' => 'exceptions.php',
'DibiOdbcDriver' => 'Drivers/OdbcDriver.php', 'Dibi\NotSupportedException' => 'exceptions.php',
'DibiOracleDriver' => 'Drivers/OracleDriver.php', 'Dibi\PcreException' => 'exceptions.php',
'DibiPcreException' => 'exceptions.php', 'Dibi\ProcedureException' => 'exceptions.php',
'DibiPdoDriver' => 'Drivers/PdoDriver.php', 'Dibi\Reflection\Column' => 'Reflection/Column.php',
'DibiPostgreDriver' => 'Drivers/PostgreDriver.php', 'Dibi\Reflection\Database' => 'Reflection/Database.php',
'DibiProcedureException' => 'exceptions.php', 'Dibi\Reflection\ForeignKey' => 'Reflection/ForeignKey.php',
'DibiResult' => 'Result.php', 'Dibi\Reflection\Index' => 'Reflection/Index.php',
'DibiResultInfo' => 'Reflection/Result.php', 'Dibi\Reflection\Result' => 'Reflection/Result.php',
'DibiResultIterator' => 'ResultIterator.php', 'Dibi\Reflection\Table' => 'Reflection/Table.php',
'DibiRow' => 'Row.php', 'Dibi\Reflector' => 'interfaces.php',
'DibiSqlite3Driver' => 'Drivers/Sqlite3Driver.php', 'Dibi\Result' => 'Result.php',
'DibiSqliteReflector' => 'Drivers/SqliteReflector.php', 'Dibi\ResultDriver' => 'interfaces.php',
'DibiTableInfo' => 'Reflection/Table.php', 'Dibi\ResultIterator' => 'ResultIterator.php',
'DibiTranslator' => 'Translator.php', 'Dibi\Row' => 'Row.php',
'DibiType' => 'Type.php', 'Dibi\Strict' => 'Strict.php',
'IDataSource' => 'interfaces.php', 'Dibi\Translator' => 'Translator.php',
'IDibiDriver' => 'interfaces.php', 'Dibi\Type' => 'Type.php',
'IDibiReflector' => 'interfaces.php', ], $old2new = [
'IDibiResultDriver' => 'interfaces.php', 'Dibi' => 'dibi.php',
'DibiColumnInfo' => 'Dibi\Reflection\Column',
'DibiConnection' => 'Dibi\Connection',
'DibiDatabaseInfo' => 'Dibi\Reflection\Database',
'DibiDataSource' => 'Dibi\DataSource',
'DibiDateTime' => 'Dibi\DateTime',
'DibiDriverException' => 'Dibi\DriverException',
'DibiEvent' => 'Dibi\Event',
'DibiException' => 'Dibi\Exception',
'DibiFileLogger' => 'Dibi\Loggers\FileLogger',
'DibiFirebirdDriver' => 'Dibi\Drivers\FirebirdDriver',
'DibiFirePhpLogger' => 'Dibi\Loggers\FirePhpLogger',
'DibiFluent' => 'Dibi\Fluent',
'DibiForeignKeyInfo' => 'Dibi\Reflection\ForeignKey',
'DibiHashMap' => 'Dibi\HashMap',
'DibiHashMapBase' => 'Dibi\HashMapBase',
'DibiIndexInfo' => 'Dibi\Reflection\Index',
'DibiLiteral' => 'Dibi\Literal',
'DibiMsSql2005Driver' => 'Dibi\Drivers\MsSql2005Driver',
'DibiMsSql2005Reflector' => 'Dibi\Drivers\MsSql2005Reflector',
'DibiMsSqlDriver' => 'Dibi\Drivers\MsSqlDriver',
'DibiMsSqlReflector' => 'Dibi\Drivers\MsSqlReflector',
'DibiMySqlDriver' => 'Dibi\Drivers\MySqlDriver',
'DibiMySqliDriver' => 'Dibi\Drivers\MySqliDriver',
'DibiMySqlReflector' => 'Dibi\Drivers\MySqlReflector',
'DibiNette21Extension' => 'Dibi\Bridges\Nette\DibiExtension21',
'DibiNettePanel' => 'Dibi\Bridges\Nette\Panel',
'DibiNotImplementedException' => 'Dibi\NotImplementedException',
'DibiNotSupportedException' => 'Dibi\NotSupportedException',
'DibiOdbcDriver' => 'Dibi\Drivers\OdbcDriver',
'DibiOracleDriver' => 'Dibi\Drivers\OracleDriver',
'DibiPcreException' => 'Dibi\PcreException',
'DibiPdoDriver' => 'Dibi\Drivers\PdoDriver',
'DibiPostgreDriver' => 'Dibi\Drivers\PostgreDriver',
'DibiProcedureException' => 'Dibi\ProcedureException',
'DibiResult' => 'Dibi\Result',
'DibiResultInfo' => 'Dibi\Reflection\Result',
'DibiResultIterator' => 'Dibi\ResultIterator',
'DibiRow' => 'Dibi\Row',
'DibiSqlite3Driver' => 'Dibi\Drivers\Sqlite3Driver',
'DibiSqliteReflector' => 'Dibi\Drivers\SqliteReflector',
'DibiTableInfo' => 'Dibi\Reflection\Table',
'DibiTranslator' => 'Dibi\Translator',
'IDataSource' => 'Dibi\IDataSource',
'IDibiDriver' => 'Dibi\Driver',
'IDibiReflector' => 'Dibi\Reflector',
'IDibiResultDriver' => 'Dibi\ResultDriver',
]; ];
if (isset($map[$class])) { if (isset($map[$class])) {
require __DIR__ . '/Dibi/' . $map[$class]; require __DIR__ . '/Dibi/' . $map[$class];
} elseif (isset($old2new[$class])) {
class_alias($old2new[$class], $class);
} }
}); });
// preload for compatiblity
array_map('class_exists', [
'DibiConnection',
'DibiDateTime',
'DibiDriverException',
'DibiEvent',
'DibiException',
'DibiFluent',
'DibiLiteral',
'DibiNotImplementedException',
'DibiNotSupportedException',
'DibiPcreException',
'DibiProcedureException',
'DibiResult',
'DibiRow',
'IDataSource',
'IDibiDriver',
]);

View File

@@ -8,7 +8,7 @@ use Tester\Assert;
require __DIR__ . '/bootstrap.php'; require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql"); $conn->loadFile(__DIR__ . "/data/$config[system].sql");

View File

@@ -5,12 +5,13 @@
*/ */
use Tester\Assert; use Tester\Assert;
use Dibi\Connection;
require __DIR__ . '/bootstrap.php'; require __DIR__ . '/bootstrap.php';
test(function () use ($config) { test(function () use ($config) {
$conn = new DibiConnection($config); $conn = new Connection($config);
Assert::true($conn->isConnected()); Assert::true($conn->isConnected());
$conn->disconnect(); $conn->disconnect();
@@ -19,7 +20,7 @@ test(function () use ($config) {
test(function () use ($config) { // lazy test(function () use ($config) { // lazy
$conn = new DibiConnection($config + ['lazy' => TRUE]); $conn = new Connection($config + ['lazy' => TRUE]);
Assert::false($conn->isConnected()); Assert::false($conn->isConnected());
$conn->query('SELECT 1'); $conn->query('SELECT 1');
@@ -28,10 +29,10 @@ test(function () use ($config) { // lazy
test(function () use ($config) { // query string test(function () use ($config) { // query string
$conn = new DibiConnection(http_build_query($config, NULL, '&')); $conn = new Connection(http_build_query($config, NULL, '&'));
Assert::true($conn->isConnected()); Assert::true($conn->isConnected());
Assert::null($conn->getConfig('lazy')); Assert::null($conn->getConfig('lazy'));
Assert::same($config['driver'], $conn->getConfig('driver')); Assert::same($config['driver'], $conn->getConfig('driver'));
Assert::type('IDibiDriver', $conn->getDriver()); Assert::type('Dibi\Driver', $conn->getDriver());
}); });

View File

@@ -5,10 +5,11 @@
*/ */
use Tester\Assert; use Tester\Assert;
use Dibi\Row;
require __DIR__ . '/bootstrap.php'; require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql"); $conn->loadFile(__DIR__ . "/data/$config[system].sql");
@@ -30,9 +31,9 @@ Assert::same('Chair', $res->fetchSingle());
// fetch complete result set // fetch complete result set
$res = $conn->query('SELECT * FROM [products] ORDER BY product_id'); $res = $conn->query('SELECT * FROM [products] ORDER BY product_id');
Assert::equal([ Assert::equal([
new DibiRow(['product_id' => num(1), 'title' => 'Chair']), new Row(['product_id' => num(1), 'title' => 'Chair']),
new DibiRow(['product_id' => num(2), 'title' => 'Table']), new Row(['product_id' => num(2), 'title' => 'Table']),
new DibiRow(['product_id' => num(3), 'title' => 'Computer']), new Row(['product_id' => num(3), 'title' => 'Computer']),
], $res->fetchAll()); ], $res->fetchAll());
@@ -53,18 +54,18 @@ Assert::same(
// fetch row by row // fetch row by row
$res = $conn->query('SELECT * FROM [products] ORDER BY product_id'); $res = $conn->query('SELECT * FROM [products] ORDER BY product_id');
Assert::equal([ Assert::equal([
new DibiRow(['product_id' => num(1), 'title' => 'Chair']), new Row(['product_id' => num(1), 'title' => 'Chair']),
new DibiRow(['product_id' => num(2), 'title' => 'Table']), new Row(['product_id' => num(2), 'title' => 'Table']),
new DibiRow(['product_id' => num(3), 'title' => 'Computer']), new Row(['product_id' => num(3), 'title' => 'Computer']),
], iterator_to_array($res)); ], iterator_to_array($res));
// fetch complete result set like association array // fetch complete result set like association array
$res = $conn->query('SELECT * FROM [products] ORDER BY product_id'); $res = $conn->query('SELECT * FROM [products] ORDER BY product_id');
Assert::equal([ Assert::equal([
'Chair' => new DibiRow(['product_id' => num(1), 'title' => 'Chair']), 'Chair' => new Row(['product_id' => num(1), 'title' => 'Chair']),
'Table' => new DibiRow(['product_id' => num(2), 'title' => 'Table']), 'Table' => new Row(['product_id' => num(2), 'title' => 'Table']),
'Computer' => new DibiRow(['product_id' => num(3), 'title' => 'Computer']), 'Computer' => new Row(['product_id' => num(3), 'title' => 'Computer']),
], $res->fetchAssoc('title')); ], $res->fetchAssoc('title'));
@@ -90,14 +91,14 @@ function query($conn) {
Assert::equal([ Assert::equal([
'Arnold Rimmer' => [ 'Arnold Rimmer' => [
'Chair' => new DibiRow(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]), 'Chair' => new Row(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]),
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]),
], ],
'Dave Lister' => [ 'Dave Lister' => [
'Table' => new DibiRow(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]), 'Table' => new Row(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]),
], ],
'Kristine Kochanski' => [ 'Kristine Kochanski' => [
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]),
], ],
], query($conn)->fetchAssoc('name,title')); ], query($conn)->fetchAssoc('name,title'));
@@ -105,20 +106,20 @@ Assert::equal([
Assert::equal([ Assert::equal([
'Arnold Rimmer' => [ 'Arnold Rimmer' => [
[ [
'Chair' => new DibiRow(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]), 'Chair' => new Row(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]),
], ],
[ [
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]),
], ],
], ],
'Dave Lister' => [ 'Dave Lister' => [
[ [
'Table' => new DibiRow(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]), 'Table' => new Row(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]),
], ],
], ],
'Kristine Kochanski' => [ 'Kristine Kochanski' => [
[ [
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]),
], ],
], ],
], query($conn)->fetchAssoc('name,#,title')); ], query($conn)->fetchAssoc('name,#,title'));
@@ -127,22 +128,22 @@ Assert::equal([
Assert::equal([ Assert::equal([
'Arnold Rimmer' => [ 'Arnold Rimmer' => [
'title' => [ 'title' => [
'Chair' => new DibiRow(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]), 'Chair' => new Row(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]),
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]),
], ],
'name' => 'Arnold Rimmer', 'name' => 'Arnold Rimmer',
'amount' => num(7.0), 'amount' => num(7.0),
], ],
'Dave Lister' => [ 'Dave Lister' => [
'title' => [ 'title' => [
'Table' => new DibiRow(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]), 'Table' => new Row(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]),
], ],
'name' => 'Dave Lister', 'name' => 'Dave Lister',
'amount' => num(3.0), 'amount' => num(3.0),
], ],
'Kristine Kochanski' => [ 'Kristine Kochanski' => [
'title' => [ 'title' => [
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]),
], ],
'name' => 'Kristine Kochanski', 'name' => 'Kristine Kochanski',
'amount' => num(5.0), 'amount' => num(5.0),
@@ -151,24 +152,24 @@ Assert::equal([
Assert::equal([ Assert::equal([
'Arnold Rimmer' => new DibiRow([ 'Arnold Rimmer' => new Row([
'title' => [ 'title' => [
'Chair' => new DibiRow(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]), 'Chair' => new Row(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]),
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]),
], ],
'name' => 'Arnold Rimmer', 'name' => 'Arnold Rimmer',
'amount' => num(7.0), 'amount' => num(7.0),
]), ]),
'Dave Lister' => new DibiRow([ 'Dave Lister' => new Row([
'title' => [ 'title' => [
'Table' => new DibiRow(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]), 'Table' => new Row(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]),
], ],
'name' => 'Dave Lister', 'name' => 'Dave Lister',
'amount' => num(3.0), 'amount' => num(3.0),
]), ]),
'Kristine Kochanski' => new DibiRow([ 'Kristine Kochanski' => new Row([
'title' => [ 'title' => [
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]),
], ],
'name' => 'Kristine Kochanski', 'name' => 'Kristine Kochanski',
'amount' => num(5.0), 'amount' => num(5.0),
@@ -177,12 +178,12 @@ Assert::equal([
Assert::equal([ Assert::equal([
new DibiRow(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]), new Row(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]),
new DibiRow([ new Row([
'title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]), 'title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]),
new DibiRow([ new Row([
'title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]), 'title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]),
new DibiRow([ new Row([
'title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]), 'title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]),
], query($conn)->fetchAssoc('@,=')); ], query($conn)->fetchAssoc('@,='));
@@ -190,22 +191,22 @@ Assert::equal([
Assert::equal([ Assert::equal([
'Arnold Rimmer' => [ 'Arnold Rimmer' => [
'title' => [ 'title' => [
'Chair' => new DibiRow(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]), 'Chair' => new Row(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]),
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]),
], ],
'name' => 'Arnold Rimmer', 'name' => 'Arnold Rimmer',
'amount' => num(7.0), 'amount' => num(7.0),
], ],
'Dave Lister' => [ 'Dave Lister' => [
'title' => [ 'title' => [
'Table' => new DibiRow(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]), 'Table' => new Row(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]),
], ],
'name' => 'Dave Lister', 'name' => 'Dave Lister',
'amount' => num(3.0), 'amount' => num(3.0),
], ],
'Kristine Kochanski' => [ 'Kristine Kochanski' => [
'title' => [ 'title' => [
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]),
], ],
'name' => 'Kristine Kochanski', 'name' => 'Kristine Kochanski',
'amount' => num(5.0), 'amount' => num(5.0),
@@ -216,14 +217,14 @@ Assert::equal([
// old syntax // old syntax
Assert::equal([ Assert::equal([
'Arnold Rimmer' => [ 'Arnold Rimmer' => [
'Chair' => new DibiRow(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]), 'Chair' => new Row(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]),
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]),
], ],
'Dave Lister' => [ 'Dave Lister' => [
'Table' => new DibiRow(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]), 'Table' => new Row(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]),
], ],
'Kristine Kochanski' => [ 'Kristine Kochanski' => [
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]),
], ],
], query($conn)->fetchAssoc('name|title')); ], query($conn)->fetchAssoc('name|title'));
@@ -231,44 +232,44 @@ Assert::equal([
Assert::equal([ Assert::equal([
'Arnold Rimmer' => [ 'Arnold Rimmer' => [
[ [
'Chair' => new DibiRow(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]), 'Chair' => new Row(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]),
], ],
[ [
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]),
], ],
], ],
'Dave Lister' => [ 'Dave Lister' => [
[ [
'Table' => new DibiRow(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]), 'Table' => new Row(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]),
], ],
], ],
'Kristine Kochanski' => [ 'Kristine Kochanski' => [
[ [
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]),
], ],
], ],
], query($conn)->fetchAssoc('name[]title')); ], query($conn)->fetchAssoc('name[]title'));
Assert::equal([ Assert::equal([
'Arnold Rimmer' => new DibiRow([ 'Arnold Rimmer' => new Row([
'title' => [ 'title' => [
'Chair' => new DibiRow(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]), 'Chair' => new Row(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]),
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]),
], ],
'name' => 'Arnold Rimmer', 'name' => 'Arnold Rimmer',
'amount' => num(7.0), 'amount' => num(7.0),
]), ]),
'Dave Lister' => new DibiRow([ 'Dave Lister' => new Row([
'title' => [ 'title' => [
'Table' => new DibiRow(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]), 'Table' => new Row(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]),
], ],
'name' => 'Dave Lister', 'name' => 'Dave Lister',
'amount' => num(3.0), 'amount' => num(3.0),
]), ]),
'Kristine Kochanski' => new DibiRow([ 'Kristine Kochanski' => new Row([
'title' => [ 'title' => [
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]),
], ],
'name' => 'Kristine Kochanski', 'name' => 'Kristine Kochanski',
'amount' => num(5.0), 'amount' => num(5.0),
@@ -277,17 +278,17 @@ Assert::equal([
Assert::equal([ Assert::equal([
'Arnold Rimmer' => new DibiRow([ 'Arnold Rimmer' => new Row([
'title' => ['Chair' => 'Arnold Rimmer', 'Computer' => 'Arnold Rimmer'], 'title' => ['Chair' => 'Arnold Rimmer', 'Computer' => 'Arnold Rimmer'],
'name' => 'Arnold Rimmer', 'name' => 'Arnold Rimmer',
'amount' => num(7.0), 'amount' => num(7.0),
]), ]),
'Dave Lister' => new DibiRow([ 'Dave Lister' => new Row([
'title' => ['Table' => 'Dave Lister'], 'title' => ['Table' => 'Dave Lister'],
'name' => 'Dave Lister', 'name' => 'Dave Lister',
'amount' => num(3.0), 'amount' => num(3.0),
]), ]),
'Kristine Kochanski' => new DibiRow([ 'Kristine Kochanski' => new Row([
'title' => ['Computer' => 'Kristine Kochanski'], 'title' => ['Computer' => 'Kristine Kochanski'],
'name' => 'Kristine Kochanski', 'name' => 'Kristine Kochanski',
'amount' => num(5.0), 'amount' => num(5.0),
@@ -296,32 +297,32 @@ Assert::equal([
Assert::equal([ Assert::equal([
new DibiRow(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]), new Row(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]),
new DibiRow(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]), new Row(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]),
new DibiRow(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]), new Row(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]),
new DibiRow(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]), new Row(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]),
], query($conn)->fetchAssoc('[]')); ], query($conn)->fetchAssoc('[]'));
Assert::equal([ Assert::equal([
'Arnold Rimmer' => new DibiRow([ 'Arnold Rimmer' => new Row([
'title' => [ 'title' => [
'Chair' => new DibiRow(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]), 'Chair' => new Row(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]),
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]),
], ],
'name' => 'Arnold Rimmer', 'name' => 'Arnold Rimmer',
'amount' => num(7.0), 'amount' => num(7.0),
]), ]),
'Dave Lister' => new DibiRow([ 'Dave Lister' => new Row([
'title' => [ 'title' => [
'Table' => new DibiRow(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]), 'Table' => new Row(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]),
], ],
'name' => 'Dave Lister', 'name' => 'Dave Lister',
'amount' => num(3.0), 'amount' => num(3.0),
]), ]),
'Kristine Kochanski' => new DibiRow([ 'Kristine Kochanski' => new Row([
'title' => [ 'title' => [
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]),
], ],
'name' => 'Kristine Kochanski', 'name' => 'Kristine Kochanski',
'amount' => num(5.0), 'amount' => num(5.0),

View File

@@ -5,7 +5,7 @@ use Tester\Assert;
require __DIR__ . '/bootstrap.php'; require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
// create new substitution :blog: ==> wp_ // create new substitution :blog: ==> wp_
$conn->getSubstitutes()->blog = 'wp_'; $conn->getSubstitutes()->blog = 'wp_';

View File

@@ -9,22 +9,22 @@ use Tester\Assert;
require __DIR__ . '/bootstrap.php'; require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql"); $conn->loadFile(__DIR__ . "/data/$config[system].sql");
/*Assert::exception(function () use ($conn) { /*Assert::exception(function () use ($conn) {
$conn->rollback(); $conn->rollback();
}, 'DibiException'); }, 'Dibi\Exception');
Assert::exception(function () use ($conn) { Assert::exception(function () use ($conn) {
$conn->commit(); $conn->commit();
}, 'DibiException'); }, 'Dibi\Exception');
$conn->begin(); $conn->begin();
Assert::exception(function () use ($conn) { Assert::exception(function () use ($conn) {
$conn->begin(); $conn->begin();
}, 'DibiException'); }, 'Dibi\Exception');
*/ */

View File

@@ -1,11 +1,12 @@
<?php <?php
use Tester\Assert; use Tester\Assert;
use Dibi\Row;
require __DIR__ . '/bootstrap.php'; require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql"); $conn->loadFile(__DIR__ . "/data/$config[system].sql");
@@ -80,7 +81,7 @@ Assert::same(1, $ds->toDataSource()->count());
Assert::equal([ Assert::equal([
new DibiRow([ new Row([
'product_id' => 1, 'product_id' => 1,
]), ]),
], iterator_to_array($ds)); ], iterator_to_array($ds));
@@ -117,7 +118,7 @@ FROM (SELECT [title] FROM [products]) t'),
(string) $ds (string) $ds
); );
Assert::equal(new DibiRow([ Assert::equal(new Row([
'product_id' => 1, 'product_id' => 1,
'title' => 'Chair', 'title' => 'Chair',
]), $conn->dataSource('SELECT * FROM products ORDER BY product_id')->fetch()); ]), $conn->dataSource('SELECT * FROM products ORDER BY product_id')->fetch());
@@ -130,22 +131,22 @@ Assert::same(
); );
Assert::equal([ Assert::equal([
1 => new DibiRow([ 1 => new Row([
'product_id' => 1, 'product_id' => 1,
'title' => 'Chair', 'title' => 'Chair',
]), ]),
new DibiRow([ new Row([
'product_id' => 2, 'product_id' => 2,
'title' => 'Table', 'title' => 'Table',
]), ]),
new DibiRow([ new Row([
'product_id' => 3, 'product_id' => 3,
'title' => 'Computer', 'title' => 'Computer',
]), ]),
], $conn->dataSource('SELECT * FROM products ORDER BY product_id')->fetchAssoc('product_id')); ], $conn->dataSource('SELECT * FROM products ORDER BY product_id')->fetchAssoc('product_id'));
$ds = new DibiDataSource('products', $conn); $ds = new Dibi\DataSource('products', $conn);
Assert::match( Assert::match(
reformat(' reformat('

View File

@@ -1,13 +1,14 @@
<?php <?php
use Tester\Assert; use Tester\Assert;
use Dibi\Fluent;
require __DIR__ . '/bootstrap.php'; require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
$fluent = new DibiFluent($conn); $fluent = new Fluent($conn);
$fluent->select('*')->from('table')->where('x=1'); $fluent->select('*')->from('table')->where('x=1');
$dolly = clone $fluent; $dolly = clone $fluent;
$dolly->where('y=1'); $dolly->where('y=1');
@@ -17,7 +18,7 @@ Assert::same(reformat('SELECT * FROM [table] WHERE x=1'), (string) $fluent);
Assert::same(reformat('SELECT * FROM [table] WHERE x=1 AND y=1 FOO'), (string) $dolly); Assert::same(reformat('SELECT * FROM [table] WHERE x=1 AND y=1 FOO'), (string) $dolly);
$fluent = new DibiFluent($conn); $fluent = new Fluent($conn);
$fluent->select('id')->from('table')->where('id = %i', 1); $fluent->select('id')->from('table')->where('id = %i', 1);
$dolly = clone $fluent; $dolly = clone $fluent;
$dolly->where('cd = %i', 5); $dolly->where('cd = %i', 5);
@@ -26,7 +27,7 @@ Assert::same(reformat('SELECT [id] FROM [table] WHERE id = 1'), (string) $fluent
Assert::same(reformat('SELECT [id] FROM [table] WHERE id = 1 AND cd = 5'), (string) $dolly); Assert::same(reformat('SELECT [id] FROM [table] WHERE id = 1 AND cd = 5'), (string) $dolly);
$fluent = new DibiFluent($conn); $fluent = new Fluent($conn);
$fluent->select('*')->from('table'); $fluent->select('*')->from('table');
$dolly = clone $fluent; $dolly = clone $fluent;
$dolly->removeClause('select')->select('count(*)'); $dolly->removeClause('select')->select('count(*)');

View File

@@ -5,7 +5,7 @@ use Tester\Assert;
require __DIR__ . '/bootstrap.php'; require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
$fluent = $conn->delete('table')->as('bAlias') $fluent = $conn->delete('table')->as('bAlias')

View File

@@ -5,10 +5,11 @@
*/ */
use Tester\Assert; use Tester\Assert;
use Dibi\Row;
require __DIR__ . '/bootstrap.php'; require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql"); $conn->loadFile(__DIR__ . "/data/$config[system].sql");
@@ -30,9 +31,9 @@ Assert::equal('Chair', $res->fetchSingle());
// fetch complete result set // fetch complete result set
$res = $conn->select('*')->from('products')->orderBy('product_id'); $res = $conn->select('*')->from('products')->orderBy('product_id');
Assert::equal([ Assert::equal([
new DibiRow(['product_id' => num(1), 'title' => 'Chair']), new Row(['product_id' => num(1), 'title' => 'Chair']),
new DibiRow(['product_id' => num(2), 'title' => 'Table']), new Row(['product_id' => num(2), 'title' => 'Table']),
new DibiRow(['product_id' => num(3), 'title' => 'Computer']), new Row(['product_id' => num(3), 'title' => 'Computer']),
], $res->fetchAll()); ], $res->fetchAll());
@@ -46,14 +47,14 @@ if ($config['system'] !== 'odbc') {
Assert::equal([ Assert::equal([
'Arnold Rimmer' => [ 'Arnold Rimmer' => [
'Chair' => new DibiRow(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]), 'Chair' => new Row(['title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0)]),
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0)]),
], ],
'Dave Lister' => [ 'Dave Lister' => [
'Table' => new DibiRow(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]), 'Table' => new Row(['title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0)]),
], ],
'Kristine Kochanski' => [ 'Kristine Kochanski' => [
'Computer' => new DibiRow(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]), 'Computer' => new Row(['title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0)]),
], ],
], $res->fetchAssoc('name,title')); ], $res->fetchAssoc('name,title'));
} }

View File

@@ -5,7 +5,7 @@ use Tester\Assert;
require __DIR__ . '/bootstrap.php'; require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
$arr = [ $arr = [

View File

@@ -5,7 +5,7 @@ use Tester\Assert;
require __DIR__ . '/bootstrap.php'; require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
$max = 10; $max = 10;
@@ -68,7 +68,7 @@ Assert::same(
(string) $fluent (string) $fluent
); );
$fluent->orderBy(DibiFluent::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)'),

View File

@@ -5,7 +5,7 @@ use Tester\Assert;
require __DIR__ . '/bootstrap.php'; require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
$arr = [ $arr = [

View File

@@ -76,5 +76,5 @@ $tests = function ($conn) {
} }
}; };
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
$tests($conn); $tests($conn);

View File

@@ -25,7 +25,7 @@ $tests = function ($conn) {
Assert::true($conn->query("SELECT 'AA\\BB' LIKE %~like~", 'A\\B')->fetchSingle()); Assert::true($conn->query("SELECT 'AA\\BB' LIKE %~like~", 'A\\B')->fetchSingle());
}; };
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
$conn->query('SET escape_string_warning = off'); // do not log warnings $conn->query('SET escape_string_warning = off'); // do not log warnings
$conn->query('SET standard_conforming_strings = on'); $conn->query('SET standard_conforming_strings = on');

View File

@@ -12,7 +12,7 @@ if ($config['system'] === 'odbc') {
Tester\Environment::skip('Not supported.'); Tester\Environment::skip('Not supported.');
} }
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql"); $conn->loadFile(__DIR__ . "/data/$config[system].sql");
$info = $conn->query(' $info = $conn->query('

View File

@@ -4,15 +4,15 @@ use Tester\Assert;
require __DIR__ . '/bootstrap.php'; require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql"); $conn->loadFile(__DIR__ . "/data/$config[system].sql");
$res = $conn->query('SELECT * FROM [customers]'); $res = $conn->query('SELECT * FROM [customers]');
// auto-converts this column to integer // auto-converts this column to integer
$res->setType('customer_id', DibiType::DATETIME, 'H:i j.n.Y'); $res->setType('customer_id', Dibi\Type::DATETIME, 'H:i j.n.Y');
Assert::equal(new DibiRow([ Assert::equal(new Dibi\Row([
'customer_id' => new DibiDateTime('1970-01-01 01:00:01'), 'customer_id' => new Dibi\DateTime('1970-01-01 01:00:01'),
'name' => 'Dave Lister', 'name' => 'Dave Lister',
]), $res->fetch()); ]), $res->fetch());

View File

@@ -8,7 +8,7 @@ use Tester\Assert;
require __DIR__ . '/bootstrap.php'; require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql"); $conn->loadFile(__DIR__ . "/data/$config[system].sql");

View File

@@ -7,7 +7,7 @@ require __DIR__ . '/bootstrap.php';
class TestClass class TestClass
{ {
use DibiStrict; use Dibi\Strict;
public $public; public $public;

View File

@@ -8,8 +8,8 @@ use Tester\Assert;
require __DIR__ . '/bootstrap.php'; require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
$translator = new DibiTranslator($conn); $translator = new Dibi\Translator($conn);
$datetime = new DateTime('1978-01-23 00:00:00'); $datetime = new DateTime('1978-01-23 00:00:00');

View File

@@ -8,7 +8,7 @@ use Tester\Assert;
require __DIR__ . '/bootstrap.php'; require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
// if & end // if & end

View File

@@ -8,7 +8,7 @@ use Tester\Assert;
require __DIR__ . '/bootstrap.php'; require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
Assert::same( Assert::same(

View File

@@ -5,10 +5,11 @@
*/ */
use Tester\Assert; use Tester\Assert;
use Dibi\DateTime;
require __DIR__ . '/bootstrap.php'; require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config + ['formatDateTime' => "'Y-m-d H:i:s'", 'formatDate' => "'Y-m-d'"]); $conn = new Dibi\Connection($config + ['formatDateTime' => "'Y-m-d H:i:s'", 'formatDate' => "'Y-m-d'"]);
// dibi detects INSERT or REPLACE command & booleans // dibi detects INSERT or REPLACE command & booleans
@@ -76,7 +77,7 @@ Assert::same(
// invalid input // invalid input
$e = Assert::exception(function () use ($conn) { $e = Assert::exception(function () use ($conn) {
$conn->translate('SELECT %s', (object) [123], ', %m', 123); $conn->translate('SELECT %s', (object) [123], ', %m', 123);
}, 'DibiException', 'SQL translate error'); }, 'Dibi\Exception', 'SQL translate error');
Assert::same('SELECT **Unexpected type object** , **Unknown or invalid modifier %m**', $e->getSql()); Assert::same('SELECT **Unexpected type object** , **Unknown or invalid modifier %m**', $e->getSql());
Assert::same( Assert::same(
@@ -148,7 +149,7 @@ Assert::same(
if ($config['system'] === 'odbc') { if ($config['system'] === 'odbc') {
Assert::exception(function () use ($conn) { Assert::exception(function () use ($conn) {
$conn->translate('SELECT * FROM [products] %lmt %ofs', 2, 1); $conn->translate('SELECT * FROM [products] %lmt %ofs', 2, 1);
}, 'DibiException'); }, 'Dibi\Exception');
} else { } else {
// with limit = 2, offset = 1 // with limit = 2, offset = 1
Assert::same( Assert::same(
@@ -176,8 +177,8 @@ Assert::same(
"INSERT INTO test ([a2], [a4], [b1], [b2], [b3], [b4], [b5], [b6], [b7], [b8], [b9]) VALUES ('1212-09-26 00:00:00', '1969-12-31 22:13:20', '1212-09-26', '1212-09-26 00:00:00', '1969-12-31', '1969-12-31 22:13:20', '1212-09-26 00:00:00', '1212-09-26', '1212-09-26 00:00:00', NULL, NULL)", "INSERT INTO test ([a2], [a4], [b1], [b2], [b3], [b4], [b5], [b6], [b7], [b8], [b9]) VALUES ('1212-09-26 00:00:00', '1969-12-31 22:13:20', '1212-09-26', '1212-09-26 00:00:00', '1969-12-31', '1969-12-31 22:13:20', '1212-09-26 00:00:00', '1212-09-26', '1212-09-26 00:00:00', NULL, NULL)",
]), ]),
$conn->translate('INSERT INTO test', [ $conn->translate('INSERT INTO test', [
'a2' => new DibiDateTime('1212-09-26'), 'a2' => new DateTime('1212-09-26'),
'a4' => new DibiDateTime(-10000), 'a4' => new DateTime(-10000),
'b1%d' => '1212-09-26', 'b1%d' => '1212-09-26',
'b2%t' => '1212-09-26', 'b2%t' => '1212-09-26',
'b3%d' => -10000, 'b3%d' => -10000,
@@ -227,7 +228,7 @@ if ($config['system'] === 'pgsql') {
$e = Assert::exception(function () use ($conn) { $e = Assert::exception(function () use ($conn) {
$conn->translate("SELECT '"); $conn->translate("SELECT '");
}, 'DibiException', 'SQL translate error'); }, 'Dibi\Exception', 'SQL translate error');
Assert::same('SELECT **Alone quote**', $e->getSql()); Assert::same('SELECT **Alone quote**', $e->getSql());
Assert::match( Assert::match(
@@ -273,7 +274,7 @@ $array3 = [
$array4 = [ $array4 = [
'a' => 12, 'a' => 12,
'b' => NULL, 'b' => NULL,
'c' => new DibiDateTime('12.3.2007'), 'c' => new DateTime('12.3.2007'),
'd' => 'any string', 'd' => 'any string',
]; ];
@@ -472,7 +473,7 @@ $e = Assert::exception(function () use ($conn) {
'num%i' => ['1', ''], 'num%i' => ['1', ''],
]; ];
$conn->translate('INSERT INTO test %m', $array6); $conn->translate('INSERT INTO test %m', $array6);
}, 'DibiException', 'SQL translate error'); }, 'Dibi\Exception', 'SQL translate error');
Assert::same('INSERT INTO test **Multi-insert array "num%i" is different.**', $e->getSql()); Assert::same('INSERT INTO test **Multi-insert array "num%i" is different.**', $e->getSql());
$array6 = [ $array6 = [

View File

@@ -37,13 +37,13 @@ if ($config['system'] === 'odbc') {
try { try {
new DibiConnection($config); new Dibi\Connection($config);
} catch (DibiNotSupportedException $e) { } catch (Dibi\NotSupportedException $e) {
Tester\Environment::skip($e->getMessage()); Tester\Environment::skip($e->getMessage());
} }
function test(\Closure $function) function test(Closure $function)
{ {
$function(); $function();
} }

View File

@@ -12,7 +12,7 @@ if ($config['system'] === 'odbc' || $config['driver'] === 'pdo') {
Tester\Environment::skip('Not supported.'); Tester\Environment::skip('Not supported.');
} }
$conn = new DibiConnection($config); $conn = new Dibi\Connection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql"); $conn->loadFile(__DIR__ . "/data/$config[system].sql");