1
0
mirror of https://github.com/dg/dibi.git synced 2025-07-31 11:20:25 +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"
},
"autoload": {
"classmap": ["src/"]
"classmap": ["src/"],
"files": ["src/loader.php"]
},
"extra": {
"branch-alias": {

View File

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

View File

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

View File

@@ -23,7 +23,7 @@ dibi::test('
SELECT COUNT(*) as [count]
FROM [comments]
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

View File

@@ -4,6 +4,8 @@
<?php
use Dibi\Type;
if (@!include __DIR__ . '/../vendor/autoload.php') {
die('Install dependencies using `composer install --dev`');
}
@@ -22,14 +24,14 @@ dibi::connect([
// using manual hints
$res = dibi::query('SELECT * FROM [customers]');
$res->setType('customer_id', DibiType::INTEGER)
->setType('added', DibiType::DATETIME)
->setFormat(DibiType::DATETIME, 'Y-m-d H:i:s');
$res->setType('customer_id', Type::INTEGER)
->setType('added', Type::DATETIME)
->setFormat(Type::DATETIME, 'Y-m-d H:i:s');
Tracy\Dumper::dump($res->fetch());
// outputs:
// DibiRow(3) {
// Dibi\Row(3) {
// customer_id => 1
// name => "Dave Lister" (11)
// added => "2007-03-11 17:20:03" (19)
@@ -40,7 +42,7 @@ $res = dibi::query('SELECT * FROM [customers]');
Tracy\Dumper::dump($res->fetch());
// outputs:
// DibiRow(3) {
// Dibi\Row(3) {
// customer_id => 1
// name => "Dave Lister" (11)
// 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
DibiResult::extensionMethod('fetchShuffle', function (DibiResult $obj) {
// using the "prototype" to add custom method to class Dibi\Result
Dibi\Result::extensionMethod('fetchShuffle', function (Dibi\Result $obj) {
$all = $obj->fetchAll();
shuffle($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] < ?', 38);
} catch (DibiException $e) {
} catch (Dibi\Exception $e) {
echo '<p>', get_class($e), ': ', $e->getMessage(), '</p>';
}

View File

@@ -5,11 +5,15 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/
namespace Dibi\Bridges\Nette;
use Nette;
/**
* 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()
@@ -32,14 +36,14 @@ class DibiNette21Extension extends Nette\DI\CompilerExtension
}
$connection = $container->addDefinition($this->prefix('connection'))
->setClass('DibiConnection', [$config])
->setClass('Dibi\Connection', [$config])
->setAutowired(isset($config['autowired']) ? $config['autowired'] : TRUE);
if ($useProfiler) {
$panel = $container->addDefinition($this->prefix('panel'))
->setClass('DibiNettePanel')
->setClass('Dibi\Bridges\Nette\Panel')
->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']]);
}

View File

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

View File

@@ -5,15 +5,21 @@
* 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;
/**
* 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 */
public static $maxLength = 1000;
@@ -30,12 +36,12 @@ class DibiNettePanel implements Nette\Diagnostics\IBarPanel
public function __construct($explain = TRUE, $filter = NULL)
{
$this->filter = $filter ? (int) $filter : DibiEvent::QUERY;
$this->filter = $filter ? (int) $filter : Event::QUERY;
$this->explain = $explain;
}
public function register(DibiConnection $connection)
public function register(Dibi\Connection $connection)
{
Debugger::getBar()->addPanel($this);
Debugger::getBlueScreen()->addPanel([__CLASS__, 'renderException']);
@@ -47,7 +53,7 @@ class DibiNettePanel implements Nette\Diagnostics\IBarPanel
* After event notification.
* @return void
*/
public function logEvent(DibiEvent $event)
public function logEvent(Event $event)
{
if (($event->type & $this->filter) === 0) {
return;
@@ -62,10 +68,10 @@ class DibiNettePanel implements Nette\Diagnostics\IBarPanel
*/
public static function renderException($e)
{
if ($e instanceof DibiException && $e->getSql()) {
if ($e instanceof Dibi\Exception && $e->getSql()) {
return [
'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) {
$totalTime += $event->time;
$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 {
$backup = [$event->connection->onEvent, dibi::$numOfQueries, dibi::$totalTime];
$backup = [$event->connection->onEvent, \dibi::$numOfQueries, \dibi::$totalTime];
$event->connection->onEvent = NULL;
$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);
} catch (DibiException $e) {
$explain = Helpers::dump($event->connection->nativeQuery("$cmd $event->sql"), TRUE);
} 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);
@@ -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 .= '</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) {
$s .= "<div id='nette-debug-DibiProfiler-row-$counter' class='nette-collapsed'>{$explain}</div>";
}

View File

@@ -7,9 +7,10 @@
namespace Dibi\Bridges\Tracy;
use dibi;
use Dibi;
use Dibi\Event;
use Dibi\Helpers;
use Tracy;
use DibiHelpers;
/**
@@ -17,7 +18,7 @@ use DibiHelpers;
*/
class Panel implements Tracy\IBarPanel
{
use \DibiStrict;
use Dibi\Strict;
/** @var int maximum SQL length */
public static $maxLength = 1000;
@@ -34,12 +35,12 @@ class Panel implements Tracy\IBarPanel
public function __construct($explain = TRUE, $filter = NULL)
{
$this->filter = $filter ? (int) $filter : \DibiEvent::QUERY;
$this->filter = $filter ? (int) $filter : Event::QUERY;
$this->explain = $explain;
}
public function register(\DibiConnection $connection)
public function register(Dibi\Connection $connection)
{
Tracy\Debugger::getBar()->addPanel($this);
Tracy\Debugger::getBlueScreen()->addPanel([__CLASS__, 'renderException']);
@@ -51,7 +52,7 @@ class Panel implements Tracy\IBarPanel
* After event notification.
* @return void
*/
public function logEvent(\DibiEvent $event)
public function logEvent(Event $event)
{
if (($event->type & $this->filter) === 0) {
return;
@@ -66,10 +67,10 @@ class Panel implements Tracy\IBarPanel
*/
public static function renderException($e)
{
if ($e instanceof \DibiException && $e->getSql()) {
if ($e instanceof Dibi\Exception && $e->getSql()) {
return [
'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) {
$totalTime += $event->time;
$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 {
$backup = [$event->connection->onEvent, dibi::$numOfQueries, dibi::$totalTime];
$backup = [$event->connection->onEvent, \dibi::$numOfQueries, \dibi::$totalTime];
$event->connection->onEvent = NULL;
$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);
} catch (\DibiException $e) {
$explain = Helpers::dump($event->connection->nativeQuery("$cmd $event->sql"), TRUE);
} 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);
@@ -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 .= '</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) {
$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)
*/
namespace Dibi;
use Traversable;
/**
* dibi connection.
@@ -12,26 +16,26 @@
* @property-read int $affectedRows
* @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;
/** @var array Current connection configuration */
private $config;
/** @var IDibiDriver */
/** @var Driver */
private $driver;
/** @var DibiTranslator */
/** @var Translator */
private $translator;
/** @var bool Is connected? */
private $connected = FALSE;
/** @var DibiHashMap Substitutes for identifiers */
/** @var HashMap Substitutes for identifiers */
private $substitutes;
@@ -47,7 +51,7 @@ class DibiConnection
* @param mixed connection parameters
* @param string connection name
* @throws DibiException
* @throws Exception
*/
public function __construct($config, $name = NULL)
{
@@ -62,7 +66,7 @@ class DibiConnection
$config = $tmp;
} 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');
@@ -72,19 +76,19 @@ class DibiConnection
self::alias($config, 'result|formatDateTime', 'resultDateTime');
if (!isset($config['driver'])) {
$config['driver'] = dibi::$defaultDriver;
$config['driver'] = \dibi::$defaultDriver;
}
$class = $tmp = preg_replace(['#\W#', '#sql#'], ['_', 'Sql'], ucfirst(strtolower($config['driver'])));
$class = "Dibi{$class}Driver";
$class = "Dibi\\Drivers\\{$class}Driver";
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;
$this->config = $config;
$this->driver = new $class;
$this->translator = new DibiTranslator($this);
$this->translator = new Translator($this);
// profiler
$profilerCfg = & $config['profiler'];
@@ -92,23 +96,23 @@ class DibiConnection
$profilerCfg = ['run' => (bool) $profilerCfg];
}
if (!empty($profilerCfg['run'])) {
$filter = isset($profilerCfg['filter']) ? $profilerCfg['filter'] : DibiEvent::QUERY;
$filter = isset($profilerCfg['filter']) ? $profilerCfg['filter'] : Event::QUERY;
if (isset($profilerCfg['file'])) {
$this->onEvent[] = [new DibiFileLogger($profilerCfg['file'], $filter), 'logEvent'];
$this->onEvent[] = [new Loggers\FileLogger($profilerCfg['file'], $filter), 'logEvent'];
}
if (DibiFirePhpLogger::isAvailable()) {
$this->onEvent[] = [new DibiFirePhpLogger($filter), 'logEvent'];
if (Loggers\FirePhpLogger::isAvailable()) {
$this->onEvent[] = [new Loggers\FirePhpLogger($filter), 'logEvent'];
}
if (!interface_exists('Tracy\IBarPanel') && interface_exists('Nette\Diagnostics\IBarPanel') && class_exists('DibiNettePanel')) {
$panel = new DibiNettePanel(isset($profilerCfg['explain']) ? $profilerCfg['explain'] : TRUE, $filter);
if (!interface_exists('Tracy\IBarPanel') && interface_exists('Nette\Diagnostics\IBarPanel') && class_exists('Dibi\Bridges\Nette\Panel')) {
$panel = new Bridges\Nette\Panel(isset($profilerCfg['explain']) ? $profilerCfg['explain'] : TRUE, $filter);
$panel->register($this);
}
}
$this->substitutes = new DibiHashMap(function ($expr) { return ":$expr:"; });
$this->substitutes = new HashMap(function ($expr) { return ":$expr:"; });
if (!empty($config['substitutes'])) {
foreach ($config['substitutes'] as $key => $value) {
$this->substitutes->$key = $value;
@@ -138,13 +142,13 @@ class DibiConnection
*/
final public function connect()
{
$event = $this->onEvent ? new DibiEvent($this, DibiEvent::CONNECT) : NULL;
$event = $this->onEvent ? new Event($this, Event::CONNECT) : NULL;
try {
$this->driver->connect($this->config);
$this->connected = TRUE;
$event && $this->onEvent($event->done());
} catch (DibiException $e) {
} catch (Exception $e) {
$event && $this->onEvent($event->done($e));
throw $e;
}
@@ -216,7 +220,7 @@ class DibiConnection
/**
* Returns the driver and connects to a database in lazy mode.
* @return IDibiDriver
* @return Driver
*/
final public function getDriver()
{
@@ -228,8 +232,8 @@ class DibiConnection
/**
* Generates (translates) and executes SQL query.
* @param array|mixed one or more arguments
* @return DibiResult|int result set object (if any)
* @throws DibiException
* @return Result|int result set object (if any)
* @throws Exception
*/
final public function query($args)
{
@@ -242,7 +246,7 @@ class DibiConnection
* Generates SQL query.
* @param array|mixed one or more arguments
* @return string
* @throws DibiException
* @throws Exception
*/
final public function translate($args)
{
@@ -260,12 +264,12 @@ class DibiConnection
{
$args = func_get_args();
try {
DibiHelpers::dump($this->translateArgs($args));
Helpers::dump($this->translateArgs($args));
return TRUE;
} catch (DibiException $e) {
} catch (Exception $e) {
if ($e->getSql()) {
DibiHelpers::dump($e->getSql());
Helpers::dump($e->getSql());
} else {
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
* @return DibiDataSource
* @throws DibiException
* @return DataSource
* @throws Exception
*/
final public function dataSource($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.
* @param string SQL statement.
* @return DibiResult|int result set object (if any)
* @throws DibiException
* @return Result|int result set object (if any)
* @throws Exception
*/
final public function nativeQuery($sql)
{
$this->connected || $this->connect();
dibi::$sql = $sql;
$event = $this->onEvent ? new DibiEvent($this, DibiEvent::QUERY, $sql) : NULL;
\dibi::$sql = $sql;
$event = $this->onEvent ? new Event($this, Event::QUERY, $sql) : NULL;
try {
$res = $this->driver->query($sql);
} catch (DibiException $e) {
} catch (Exception $e) {
$event && $this->onEvent($event->done($e));
throw $e;
}
@@ -333,14 +337,14 @@ class DibiConnection
/**
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
* @return int number of rows
* @throws DibiException
* @throws Exception
*/
public function getAffectedRows()
{
$this->connected || $this->connect();
$rows = $this->driver->getAffectedRows();
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;
}
@@ -349,7 +353,7 @@ class DibiConnection
/**
* Gets the number of affected rows. Alias for getAffectedRows().
* @return int number of rows
* @throws DibiException
* @throws Exception
*/
public function affectedRows()
{
@@ -361,14 +365,14 @@ class DibiConnection
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
* @param string optional sequence name
* @return int
* @throws DibiException
* @throws Exception
*/
public function getInsertId($sequence = NULL)
{
$this->connected || $this->connect();
$id = $this->driver->getInsertId($sequence);
if ($id < 1) {
throw new DibiException('Cannot retrieve last generated ID.');
throw new Exception('Cannot retrieve last generated ID.');
}
return (int) $id;
}
@@ -378,7 +382,7 @@ class DibiConnection
* Retrieves the ID generated for an AUTO_INCREMENT column. Alias for getInsertId().
* @param string optional sequence name
* @return int
* @throws DibiException
* @throws Exception
*/
public function insertId($sequence = NULL)
{
@@ -394,12 +398,12 @@ class DibiConnection
public function begin($savepoint = NULL)
{
$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 {
$this->driver->begin($savepoint);
$event && $this->onEvent($event->done());
} catch (DibiException $e) {
} catch (Exception $e) {
$event && $this->onEvent($event->done($e));
throw $e;
}
@@ -414,12 +418,12 @@ class DibiConnection
public function commit($savepoint = NULL)
{
$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 {
$this->driver->commit($savepoint);
$event && $this->onEvent($event->done());
} catch (DibiException $e) {
} catch (Exception $e) {
$event && $this->onEvent($event->done($e));
throw $e;
}
@@ -434,12 +438,12 @@ class DibiConnection
public function rollback($savepoint = NULL)
{
$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 {
$this->driver->rollback($savepoint);
$event && $this->onEvent($event->done());
} catch (DibiException $e) {
} catch (Exception $e) {
$event && $this->onEvent($event->done($e));
throw $e;
}
@@ -448,14 +452,14 @@ class DibiConnection
/**
* Result set factory.
* @param IDibiResultDriver
* @return DibiResult
* @param ResultDriver
* @return Result
*/
public function createResultSet(IDibiResultDriver $resultDriver)
public function createResultSet(ResultDriver $resultDriver)
{
$res = new DibiResult($resultDriver);
return $res->setFormat(DibiType::DATE, $this->config['result']['formatDate'])
->setFormat(DibiType::DATETIME, $this->config['result']['formatDateTime']);
$res = new Result($resultDriver);
return $res->setFormat(Type::DATE, $this->config['result']['formatDate'])
->setFormat(Type::DATETIME, $this->config['result']['formatDateTime']);
}
@@ -463,17 +467,17 @@ class DibiConnection
/**
* @return DibiFluent
* @return Fluent
*/
public function command()
{
return new DibiFluent($this);
return new Fluent($this);
}
/**
* @param string column name
* @return DibiFluent
* @return Fluent
*/
public function select($args)
{
@@ -485,12 +489,12 @@ class DibiConnection
/**
* @param string table
* @param array
* @return DibiFluent
* @return Fluent
*/
public function update($table, $args)
{
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);
}
@@ -499,14 +503,14 @@ class DibiConnection
/**
* @param string table
* @param array
* @return DibiFluent
* @return Fluent
*/
public function insert($table, $args)
{
if ($args instanceof Traversable) {
$args = iterator_to_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()
->into('%n', $table, '(%n)', array_keys($args))->values('%l', $args);
@@ -515,7 +519,7 @@ class DibiConnection
/**
* @param string table
* @return DibiFluent
* @return Fluent
*/
public function delete($table)
{
@@ -528,7 +532,7 @@ class DibiConnection
/**
* Returns substitution hashmap.
* @return DibiHashMap
* @return HashMap
*/
public function getSubstitutes()
{
@@ -554,8 +558,8 @@ class DibiConnection
/**
* Executes SQL query and fetch result - shortcut for query() & fetch().
* @param array|mixed one or more arguments
* @return DibiRow
* @throws DibiException
* @return Row
* @throws Exception
*/
public function fetch($args)
{
@@ -567,8 +571,8 @@ class DibiConnection
/**
* Executes SQL query and fetch results - shortcut for query() & fetchAll().
* @param array|mixed one or more arguments
* @return DibiRow[]
* @throws DibiException
* @return Row[]
* @throws Exception
*/
public function fetchAll($args)
{
@@ -581,7 +585,7 @@ class DibiConnection
* Executes SQL query and fetch first column - shortcut for query() & fetchSingle().
* @param array|mixed one or more arguments
* @return string
* @throws DibiException
* @throws Exception
*/
public function fetchSingle($args)
{
@@ -594,7 +598,7 @@ class DibiConnection
* Executes SQL query and fetch pairs - shortcut for query() & fetchPairs().
* @param array|mixed one or more arguments
* @return string
* @throws DibiException
* @throws Exception
*/
public function fetchPairs($args)
{
@@ -618,7 +622,7 @@ class DibiConnection
$handle = @fopen($file, 'r'); // intentionally @
if (!$handle) {
throw new RuntimeException("Cannot open file '$file'.");
throw new \RuntimeException("Cannot open file '$file'.");
}
$count = 0;
@@ -650,12 +654,12 @@ class DibiConnection
/**
* Gets a information about the current database.
* @return DibiDatabaseInfo
* @return Reflection\Database
*/
public function getDatabaseInfo()
{
$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()
{
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()
{
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)
*/
namespace 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;
/** @var string */
private $sql;
/** @var DibiResult */
/** @var Result */
private $result;
/** @var int */
@@ -47,9 +49,9 @@ class DibiDataSource implements IDataSource
/**
* @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) {
$this->sql = $connection->getDriver()->escapeIdentifier($sql); // table name
@@ -131,7 +133,7 @@ class DibiDataSource implements IDataSource
/**
* Returns the dibi connection.
* @return DibiConnection
* @return Connection
*/
final public function getConnection()
{
@@ -143,8 +145,8 @@ class DibiDataSource implements IDataSource
/**
* Returns (and queries) DibiResult.
* @return DibiResult
* Returns (and queries) Result.
* @return Result
*/
public function getResult()
{
@@ -156,7 +158,7 @@ class DibiDataSource implements IDataSource
/**
* @return DibiResultIterator
* @return ResultIterator
*/
public function getIterator()
{
@@ -166,7 +168,7 @@ class DibiDataSource implements IDataSource
/**
* 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()
{
@@ -231,8 +233,8 @@ class DibiDataSource implements IDataSource
/**
* Returns this data source wrapped in DibiFluent object.
* @return DibiFluent
* Returns this data source wrapped in Fluent object.
* @return Fluent
*/
public function toFluent()
{
@@ -241,8 +243,8 @@ class DibiDataSource implements IDataSource
/**
* Returns this data source wrapped in DibiDataSource object.
* @return DibiDataSource
* Returns this data source wrapped in DataSource object.
* @return DataSource
*/
public function toDataSource()
{
@@ -264,7 +266,7 @@ FROM %SQL', $this->sql, '
%ex', $this->sorting ? ['ORDER BY %by', $this->sorting] : NULL, '
%ofs %lmt', $this->offset, $this->limit
);
} catch (Exception $e) {
} catch (\Exception $e) {
trigger_error($e->getMessage(), E_USER_ERROR);
}
}

View File

@@ -5,19 +5,21 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/
namespace Dibi;
/**
* 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)) {
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) {
parent::__construct($time);
} else {

View File

@@ -5,6 +5,10 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/
namespace Dibi\Drivers;
use Dibi;
/**
* The dibi driver for Firebird/InterBase database.
@@ -16,11 +20,11 @@
* - 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.
* - 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;
@@ -41,12 +45,12 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
/**
* @throws DibiNotSupportedException
* @throws Dibi\NotSupportedException
*/
public function __construct()
{
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.
* @return void
* @throws DibiException
* @throws Dibi\Exception
*/
public function connect(array & $config)
{
DibiConnection::alias($config, 'database', 'db');
Dibi\Connection::alias($config, 'database', 'db');
if (isset($config['resource'])) {
$this->connection = $config['resource'];
@@ -73,18 +77,18 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
'buffers' => 0,
];
DibiDriverException::tryError();
Dibi\DriverException::tryError();
if (empty($config['persistent'])) {
$this->connection = ibase_connect($config['database'], $config['username'], $config['password'], $config['charset'], $config['buffers']); // intentionally @
} else {
$this->connection = ibase_pconnect($config['database'], $config['username'], $config['password'], $config['charset'], $config['buffers']); // intentionally @
}
if (DibiDriverException::catchError($msg)) {
throw new DibiDriverException($msg, ibase_errcode());
if (Dibi\DriverException::catchError($msg)) {
throw new Dibi\DriverException($msg, ibase_errcode());
}
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.
* @param string SQL statement.
* @return IDibiResultDriver|NULL
* @throws DibiDriverException|DibiException
* @return Dibi\ResultDriver|NULL
* @throws Dibi\DriverException|Dibi\Exception
*/
public function query($sql)
{
DibiDriverException::tryError();
Dibi\DriverException::tryError();
$resource = $this->inTransaction ? $this->transaction : $this->connection;
$res = ibase_query($resource, $sql);
if (DibiDriverException::catchError($msg)) {
if (Dibi\DriverException::catchError($msg)) {
if (ibase_errcode() == self::ERROR_EXCEPTION_THROWN) {
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 {
throw new DibiDriverException(ibase_errmsg(), ibase_errcode(), dibi::$sql);
throw new Dibi\DriverException(ibase_errmsg(), ibase_errcode(), \dibi::$sql);
}
}
if ($res === FALSE) {
throw new DibiDriverException(ibase_errmsg(), ibase_errcode(), $sql);
throw new Dibi\DriverException(ibase_errmsg(), ibase_errcode(), $sql);
} elseif (is_resource($res)) {
return $this->createResultDriver($res);
@@ -156,12 +160,12 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function begin($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->inTransaction = TRUE;
@@ -172,16 +176,16 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function commit($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)) {
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;
@@ -192,16 +196,16 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function rollback($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)) {
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;
@@ -230,7 +234,7 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
/**
* Returns the connection reflector.
* @return IDibiReflector
* @return Dibi\Reflector
*/
public function getReflector()
{
@@ -241,7 +245,7 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
/**
* Result set driver factory.
* @param resource
* @return IDibiResultDriver
* @return Dibi\ResultDriver
*/
public function createResultDriver($resource)
{
@@ -285,8 +289,8 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
public function escapeDate($value)
{
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
$value = new DibiDateTime($value);
if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new Dibi\DateTime($value);
}
return $value->format("'Y-m-d'");
}
@@ -294,8 +298,8 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
public function escapeDateTime($value)
{
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
$value = new DibiDateTime($value);
if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new Dibi\DateTime($value);
}
return $value->format("'Y-m-d H:i:s'");
}
@@ -309,7 +313,7 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
*/
public function escapeLike($value, $pos)
{
throw new DibiNotImplementedException;
throw new Dibi\NotImplementedException;
}
@@ -327,7 +331,7 @@ class DibiFirebirdDriver implements IDibiDriver, IDibiResultDriver, IDibiReflect
/** @deprecated */
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()
{
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)
{
DibiDriverException::tryError();
Dibi\DriverException::tryError();
$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) {
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 {
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.
* @param int the 0-based cursor pos to seek to
* @return bool TRUE on success, FALSE if unable to seek to specified record
* @throws DibiException
* @throws Dibi\Exception
*/
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)
*/
namespace Dibi\Drivers;
use Dibi;
use Dibi\Connection;
/**
* 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}
* - charset => character encoding to set (default is UTF-8)
* - 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 */
private $connection;
@@ -37,12 +42,12 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
/**
* @throws DibiNotSupportedException
* @throws Dibi\NotSupportedException
*/
public function __construct()
{
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.
* @return void
* @throws DibiException
* @throws Dibi\Exception
*/
public function connect(array & $config)
{
DibiConnection::alias($config, 'options|UID', 'username');
DibiConnection::alias($config, 'options|PWD', 'password');
DibiConnection::alias($config, 'options|Database', 'database');
DibiConnection::alias($config, 'options|CharacterSet', 'charset');
Connection::alias($config, 'options|UID', 'username');
Connection::alias($config, 'options|PWD', 'password');
Connection::alias($config, 'options|Database', 'database');
Connection::alias($config, 'options|CharacterSet', 'charset');
if (isset($config['resource'])) {
$this->connection = $config['resource'];
@@ -73,7 +78,7 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
if (!is_resource($this->connection)) {
$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.
* @param string SQL statement.
* @return IDibiResultDriver|NULL
* @throws DibiDriverException
* @return Dibi\ResultDriver|NULL
* @throws Dibi\DriverException
*/
public function query($sql)
{
@@ -101,7 +106,7 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
if ($res === FALSE) {
$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)) {
$this->affectedRows = sqlsrv_rows_affected($res);
@@ -139,7 +144,7 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function begin($savepoint = NULL)
{
@@ -151,7 +156,7 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function commit($savepoint = NULL)
{
@@ -163,7 +168,7 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function rollback($savepoint = NULL)
{
@@ -183,18 +188,18 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
/**
* Returns the connection reflector.
* @return IDibiReflector
* @return Dibi\Reflector
*/
public function getReflector()
{
return new DibiMssql2005Reflector($this);
return new Mssql2005Reflector($this);
}
/**
* Result set driver factory.
* @param resource
* @return IDibiResultDriver
* @return Dibi\ResultDriver
*/
public function createResultDriver($resource)
{
@@ -239,8 +244,8 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
public function escapeDate($value)
{
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
$value = new DibiDateTime($value);
if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new Dibi\DateTime($value);
}
return $value->format("'Y-m-d'");
}
@@ -248,14 +253,13 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
public function escapeDateTime($value)
{
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
$value = new DibiDateTime($value);
if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new Dibi\DateTime($value);
}
return $value->format("'Y-m-d H:i:s'");
}
/**
* Encodes string for use in a LIKE statement.
* @param string
@@ -283,7 +287,7 @@ class DibiMsSql2005Driver implements IDibiDriver, IDibiResultDriver
/** @deprecated */
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) {
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()
{
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)
{
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)
*/
namespace Dibi\Drivers;
use Dibi;
/**
* The dibi reflector for MSSQL2005 databases.
* @internal
*/
class DibiMsSql2005Reflector implements IDibiReflector
class MsSql2005Reflector implements Dibi\Reflector
{
use DibiStrict;
use Dibi\Strict;
/** @var IDibiDriver */
/** @var Dibi\Driver */
private $driver;
public function __construct(IDibiDriver $driver)
public function __construct(Dibi\Driver $driver)
{
$this->driver = $driver;
}
@@ -126,7 +130,7 @@ class DibiMsSql2005Reflector implements IDibiReflector
*/
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)
*/
namespace Dibi\Drivers;
use Dibi;
/**
* The dibi driver for MS SQL database.
@@ -16,11 +20,11 @@
* - database => the database name to select
* - persistent (bool) => try to find a persistent link?
* - 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 */
private $connection;
@@ -33,12 +37,12 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
/**
* @throws DibiNotSupportedException
* @throws Dibi\NotSupportedException
*/
public function __construct()
{
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.
* @return void
* @throws DibiException
* @throws Dibi\Exception
*/
public function connect(array & $config)
{
@@ -59,11 +63,11 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
}
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 @
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.
* @param string SQL statement.
* @return IDibiResultDriver|NULL
* @throws DibiDriverException
* @return Dibi\ResultDriver|NULL
* @throws Dibi\DriverException
*/
public function query($sql)
{
$res = @mssql_query($sql, $this->connection); // intentionally @
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)) {
return $this->createResultDriver($res);
@@ -126,7 +130,7 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function begin($savepoint = NULL)
{
@@ -138,7 +142,7 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function commit($savepoint = NULL)
{
@@ -150,7 +154,7 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function rollback($savepoint = NULL)
{
@@ -170,18 +174,18 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
/**
* Returns the connection reflector.
* @return IDibiReflector
* @return Dibi\Reflector
*/
public function getReflector()
{
return new DibiMsSqlReflector($this);
return new MsSqlReflector($this);
}
/**
* Result set driver factory.
* @param resource
* @return IDibiResultDriver
* @return Dibi\ResultDriver
*/
public function createResultDriver($resource)
{
@@ -226,8 +230,8 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
public function escapeDate($value)
{
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
$value = new DibiDateTime($value);
if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new Dibi\DateTime($value);
}
return $value->format("'Y-m-d'");
}
@@ -235,8 +239,8 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
public function escapeDateTime($value)
{
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
$value = new DibiDateTime($value);
if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new Dibi\DateTime($value);
}
return $value->format("'Y-m-d H:i:s'");
}
@@ -269,7 +273,7 @@ class DibiMsSqlDriver implements IDibiDriver, IDibiResultDriver
/** @deprecated */
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) {
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)
*/
namespace Dibi\Drivers;
use Dibi;
/**
* The dibi reflector for MsSQL databases.
* @internal
*/
class DibiMsSqlReflector implements IDibiReflector
class MsSqlReflector implements Dibi\Reflector
{
use DibiStrict;
use Dibi\Strict;
/** @var IDibiDriver */
/** @var Dibi\Driver */
private $driver;
public function __construct(IDibiDriver $driver)
public function __construct(Dibi\Driver $driver)
{
$this->driver = $driver;
}

View File

@@ -5,6 +5,10 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/
namespace Dibi\Drivers;
use Dibi;
/**
* The dibi driver for MySQL database.
@@ -22,11 +26,11 @@
* - 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
* - 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_DUPLICATE_ENTRY = 1062;
@@ -46,12 +50,12 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
/**
* @throws DibiNotSupportedException
* @throws Dibi\NotSupportedException
*/
public function __construct()
{
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.
* @return void
* @throws DibiException
* @throws Dibi\Exception
*/
public function connect(array & $config)
{
@@ -68,7 +72,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
} else {
// default values
DibiConnection::alias($config, 'flags', 'options');
Dibi\Connection::alias($config, 'flags', 'options');
$config += [
'charset' => 'utf8',
'timezone' => date('P'),
@@ -102,7 +106,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
}
if (!is_resource($this->connection)) {
throw new DibiDriverException(mysql_error(), mysql_errno());
throw new Dibi\DriverException(mysql_error(), mysql_errno());
}
if (isset($config['charset'])) {
@@ -113,7 +117,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
if (isset($config['database'])) {
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.
* @param string SQL statement.
* @return IDibiResultDriver|NULL
* @throws DibiDriverException
* @return Dibi\ResultDriver|NULL
* @throws Dibi\DriverException
*/
public function query($sql)
{
@@ -154,7 +158,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
}
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)) {
return $this->createResultDriver($res);
@@ -171,7 +175,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
$res = [];
preg_match_all('#(.+?): +(\d+) *#', mysql_info($this->connection), $matches, PREG_SET_ORDER);
if (preg_last_error()) {
throw new DibiPcreException;
throw new Dibi\PcreException;
}
foreach ($matches as $m) {
@@ -205,7 +209,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function begin($savepoint = NULL)
{
@@ -217,7 +221,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function commit($savepoint = NULL)
{
@@ -229,7 +233,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function rollback($savepoint = NULL)
{
@@ -249,18 +253,18 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
/**
* Returns the connection reflector.
* @return IDibiReflector
* @return Dibi\Reflector
*/
public function getReflector()
{
return new DibiMySqlReflector($this);
return new MySqlReflector($this);
}
/**
* Result set driver factory.
* @param resource
* @return IDibiResultDriver
* @return Dibi\ResultDriver
*/
public function createResultDriver($resource)
{
@@ -311,8 +315,8 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
public function escapeDate($value)
{
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
$value = new DibiDateTime($value);
if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new Dibi\DateTime($value);
}
return $value->format("'Y-m-d'");
}
@@ -320,8 +324,8 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
public function escapeDateTime($value)
{
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
$value = new DibiDateTime($value);
if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new Dibi\DateTime($value);
}
return $value->format("'Y-m-d H:i:s'");
}
@@ -354,7 +358,7 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
/** @deprecated */
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()
{
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);
}
@@ -413,12 +417,12 @@ class DibiMySqlDriver implements IDibiDriver, IDibiResultDriver
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
* @return bool TRUE on success, FALSE if unable to seek to specified record
* @throws DibiException
* @throws Dibi\Exception
*/
public function seek($row)
{
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);

View File

@@ -5,20 +5,24 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/
namespace Dibi\Drivers;
use Dibi;
/**
* The dibi reflector for MySQL databases.
* @internal
*/
class DibiMySqlReflector implements IDibiReflector
class MySqlReflector implements Dibi\Reflector
{
use DibiStrict;
use Dibi\Strict;
/** @var IDibiDriver */
/** @var Dibi\Driver */
private $driver;
public function __construct(IDibiDriver $driver)
public function __construct(Dibi\Driver $driver)
{
$this->driver = $driver;
}
@@ -110,13 +114,13 @@ class DibiMySqlReflector implements IDibiReflector
* Returns metadata for all foreign keys in a table.
* @param string
* @return array
* @throws DibiNotSupportedException
* @throws Dibi\NotSupportedException
*/
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);
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("

View File

@@ -5,6 +5,10 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/
namespace Dibi\Drivers;
use Dibi;
/**
* 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?
* - sqlmode => see http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html
* - 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_DUPLICATE_ENTRY = 1062;
@@ -47,12 +51,12 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
/**
* @throws DibiNotSupportedException
* @throws Dibi\NotSupportedException
*/
public function __construct()
{
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.
* @return void
* @throws DibiException
* @throws Dibi\Exception
*/
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 @
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.
* @param string SQL statement.
* @return IDibiResultDriver|NULL
* @throws DibiDriverException
* @return Dibi\ResultDriver|NULL
* @throws Dibi\DriverException
*/
public function query($sql)
{
$res = @mysqli_query($this->connection, $sql, $this->buffered ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT); // intentionally @
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)) {
return $this->createResultDriver($res);
@@ -166,7 +170,7 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
$res = [];
preg_match_all('#(.+?): +(\d+) *#', mysqli_info($this->connection), $matches, PREG_SET_ORDER);
if (preg_last_error()) {
throw new DibiPcreException;
throw new Dibi\PcreException;
}
foreach ($matches as $m) {
@@ -200,7 +204,7 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function begin($savepoint = NULL)
{
@@ -212,7 +216,7 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function commit($savepoint = NULL)
{
@@ -224,7 +228,7 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function rollback($savepoint = NULL)
{
@@ -244,20 +248,20 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
/**
* Returns the connection reflector.
* @return IDibiReflector
* @return Dibi\Reflector
*/
public function getReflector()
{
return new DibiMySqlReflector($this);
return new MySqlReflector($this);
}
/**
* Result set driver factory.
* @param mysqli_result
* @return IDibiResultDriver
* @return Dibi\ResultDriver
*/
public function createResultDriver(mysqli_result $resource)
public function createResultDriver(\mysqli_result $resource)
{
$res = clone $this;
$res->resultSet = $resource;
@@ -299,8 +303,8 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
public function escapeDate($value)
{
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
$value = new DibiDateTime($value);
if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new Dibi\DateTime($value);
}
return $value->format("'Y-m-d'");
}
@@ -308,8 +312,8 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
public function escapeDateTime($value)
{
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
$value = new DibiDateTime($value);
if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new Dibi\DateTime($value);
}
return $value->format("'Y-m-d H:i:s'");
}
@@ -342,7 +346,7 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
/** @deprecated */
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()
{
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);
}
@@ -401,12 +405,12 @@ class DibiMySqliDriver implements IDibiDriver, IDibiResultDriver
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
* @return bool TRUE on success, FALSE if unable to seek to specified record
* @throws DibiException
* @throws Dibi\Exception
*/
public function seek($row)
{
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);
}

View File

@@ -5,6 +5,10 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/
namespace Dibi\Drivers;
use Dibi;
/**
* The dibi driver interacting with databases via ODBC connections.
@@ -15,11 +19,11 @@
* - password (or pass)
* - persistent (bool) => try to find a persistent link?
* - 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 */
private $connection;
@@ -38,12 +42,12 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/**
* @throws DibiNotSupportedException
* @throws Dibi\NotSupportedException
*/
public function __construct()
{
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.
* @return void
* @throws DibiException
* @throws Dibi\Exception
*/
public function connect(array & $config)
{
@@ -73,7 +77,7 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
}
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.
* @param string SQL statement.
* @return IDibiResultDriver|NULL
* @throws DibiDriverException
* @return Dibi\ResultDriver|NULL
* @throws Dibi\DriverException
*/
public function query($sql)
{
@@ -100,7 +104,7 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
$res = @odbc_exec($this->connection, $sql); // intentionally @
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)) {
$this->affectedRows = odbc_num_rows($res);
@@ -125,7 +129,7 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
*/
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).
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function begin($savepoint = NULL)
{
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.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function commit($savepoint = NULL)
{
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);
}
@@ -162,12 +166,12 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function rollback($savepoint = NULL)
{
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);
}
@@ -195,7 +199,7 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/**
* Returns the connection reflector.
* @return IDibiReflector
* @return Dibi\Reflector
*/
public function getReflector()
{
@@ -206,7 +210,7 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/**
* Result set driver factory.
* @param resource
* @return IDibiResultDriver
* @return Dibi\ResultDriver
*/
public function createResultDriver($resource)
{
@@ -250,8 +254,8 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
public function escapeDate($value)
{
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
$value = new DibiDateTime($value);
if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new Dibi\DateTime($value);
}
return $value->format("#m/d/Y#");
}
@@ -259,8 +263,8 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
public function escapeDateTime($value)
{
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
$value = new DibiDateTime($value);
if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new Dibi\DateTime($value);
}
return $value->format("#m/d/Y H:i:s#");
}
@@ -293,7 +297,7 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/** @deprecated */
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) {
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)
{
throw new DibiNotImplementedException;
throw new Dibi\NotImplementedException;
}
@@ -484,7 +488,7 @@ class DibiOdbcDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
*/
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)
*/
namespace Dibi\Drivers;
use Dibi;
/**
* The dibi driver for Oracle database.
@@ -19,11 +23,11 @@
* - formatDateTime => how to format datetime in SQL (@see date)
* - resource (resource) => existing connection resource
* - 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 */
private $connection;
@@ -42,12 +46,12 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/**
* @throws DibiNotSupportedException
* @throws Dibi\NotSupportedException
*/
public function __construct()
{
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.
* @return void
* @throws DibiException
* @throws Dibi\Exception
*/
public function connect(array & $config)
{
@@ -73,7 +77,7 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
if (!$this->connection) {
$err = oci_error();
throw new DibiDriverException($err['message'], $err['code']);
throw new Dibi\DriverException($err['message'], $err['code']);
}
if (isset($config['schema'])) {
@@ -95,8 +99,8 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/**
* Executes the SQL query.
* @param string SQL statement.
* @return IDibiResultDriver|NULL
* @throws DibiDriverException
* @return Dibi\ResultDriver|NULL
* @throws Dibi\DriverException
*/
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);
$err = oci_error($res);
if ($err) {
throw new DibiDriverException($err['message'], $err['code'], $sql);
throw new Dibi\DriverException($err['message'], $err['code'], $sql);
} elseif (is_resource($res)) {
return $this->createResultDriver($res);
}
} else {
$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()
{
throw new DibiNotImplementedException;
throw new Dibi\NotImplementedException;
}
@@ -153,13 +157,13 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function commit($savepoint = NULL)
{
if (!oci_commit($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;
}
@@ -169,13 +173,13 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function rollback($savepoint = NULL)
{
if (!oci_rollback($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;
}
@@ -193,7 +197,7 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/**
* Returns the connection reflector.
* @return IDibiReflector
* @return Dibi\Reflector
*/
public function getReflector()
{
@@ -204,7 +208,7 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/**
* Result set driver factory.
* @param resource
* @return IDibiResultDriver
* @return Dibi\ResultDriver
*/
public function createResultDriver($resource)
{
@@ -249,8 +253,8 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
public function escapeDate($value)
{
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
$value = new DibiDateTime($value);
if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new Dibi\DateTime($value);
}
return $value->format($this->fmtDate);
}
@@ -258,8 +262,8 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
public function escapeDateTime($value)
{
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
$value = new DibiDateTime($value);
if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new Dibi\DateTime($value);
}
return $value->format($this->fmtDateTime);
}
@@ -293,7 +297,7 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
/** @deprecated */
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()
{
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)
{
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)
{
throw new DibiNotImplementedException;
throw new Dibi\NotImplementedException;
}
@@ -444,7 +448,7 @@ class DibiOracleDriver implements IDibiDriver, IDibiResultDriver, IDibiReflector
*/
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)
{
throw new DibiNotImplementedException;
throw new Dibi\NotImplementedException;
}
}

View File

@@ -5,6 +5,11 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/
namespace Dibi\Drivers;
use Dibi;
use PDO;
/**
* The dibi driver for PDO.
@@ -16,16 +21,16 @@
* - options (array) => driver specific options {@see PDO::__construct}
* - resource (PDO) => existing connection
* - 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 */
private $connection;
/** @var PDOStatement Resultset resource */
/** @var \PDOStatement Resultset resource */
private $resultSet;
/** @var int|FALSE Affected rows */
@@ -39,12 +44,12 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
/**
* @throws DibiNotSupportedException
* @throws Dibi\NotSupportedException
*/
public function __construct()
{
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.
* @return void
* @throws DibiException
* @throws Dibi\Exception
*/
public function connect(array & $config)
{
$foo = & $config['dsn'];
$foo = & $config['options'];
DibiConnection::alias($config, 'resource', 'pdo');
Dibi\Connection::alias($config, 'resource', 'pdo');
if ($config['resource'] instanceof PDO) {
$this->connection = $config['resource'];
@@ -66,11 +71,11 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
} else {
try {
$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') {
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.
* @param string SQL statement.
* @return IDibiResultDriver|NULL
* @throws DibiDriverException
* @return Dibi\ResultDriver|NULL
* @throws Dibi\DriverException
*/
public function query($sql)
{
@@ -109,7 +114,7 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
if ($this->affectedRows === FALSE) {
$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 {
@@ -117,7 +122,7 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
if ($res === FALSE) {
$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 {
return $this->createResultDriver($res);
}
@@ -149,13 +154,13 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function begin($savepoint = NULL)
{
if (!$this->connection->beginTransaction()) {
$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.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function commit($savepoint = NULL)
{
if (!$this->connection->commit()) {
$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.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function rollback($savepoint = NULL)
{
if (!$this->connection->rollBack()) {
$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.
* @return IDibiReflector
* @return Dibi\Reflector
*/
public function getReflector()
{
switch ($this->driverName) {
case 'mysql':
return new DibiMySqlReflector($this);
return new MySqlReflector($this);
case 'sqlite':
return new DibiSqliteReflector($this);
return new SqliteReflector($this);
default:
throw new DibiNotSupportedException;
throw new Dibi\NotSupportedException;
}
}
/**
* Result set driver factory.
* @param PDOStatement
* @return IDibiResultDriver
* @param \PDOStatement
* @return Dibi\ResultDriver
*/
public function createResultDriver(PDOStatement $resource)
public function createResultDriver(\PDOStatement $resource)
{
$res = clone $this;
$res->resultSet = $resource;
@@ -299,8 +304,8 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
public function escapeDate($value)
{
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
$value = new DibiDateTime($value);
if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new Dibi\DateTime($value);
}
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)
{
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
$value = new DibiDateTime($value);
if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new Dibi\DateTime($value);
}
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 */
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
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)
{
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.
* @return array
* @throws DibiException
* @throws Dibi\Exception
*/
public function getResultColumns()
{
@@ -495,7 +500,7 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
for ($i = 0; $i < $count; $i++) {
$row = @$this->resultSet->getColumnMeta($i); // intentionally @
if ($row === FALSE) {
throw new DibiNotSupportedException('Driver does not support meta data.');
throw new Dibi\NotSupportedException('Driver does not support meta data.');
}
$row = $row + [
'table' => NULL,
@@ -516,7 +521,7 @@ class DibiPdoDriver implements IDibiDriver, IDibiResultDriver
/**
* Returns the result set resource.
* @return PDOStatement
* @return \PDOStatement
*/
public function getResultResource()
{

View File

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

View File

@@ -5,6 +5,11 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/
namespace Dibi\Drivers;
use Dibi;
use SQLite3;
/**
* The dibi driver for SQLite3 database.
@@ -16,16 +21,16 @@
* - dbcharset => database character encoding (will be converted to 'charset')
* - charset => character encoding to set (default is UTF-8)
* - 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 */
private $connection;
/** @var SQLite3Result Resultset resource */
/** @var \SQLite3Result Resultset resource */
private $resultSet;
/** @var bool */
@@ -39,12 +44,12 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
/**
* @throws DibiNotSupportedException
* @throws Dibi\NotSupportedException
*/
public function __construct()
{
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.
* @return void
* @throws DibiException
* @throws Dibi\Exception
*/
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->fmtDateTime = isset($config['formatDateTime']) ? $config['formatDateTime'] : 'U';
@@ -65,8 +70,8 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
} else {
try {
$this->connection = new SQLite3($config['database']);
} catch (Exception $e) {
throw new DibiDriverException($e->getMessage(), $e->getCode());
} catch (\Exception $e) {
throw new Dibi\DriverException($e->getMessage(), $e->getCode());
}
}
@@ -97,8 +102,8 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
/**
* Executes the SQL query.
* @param string SQL statement.
* @return IDibiResultDriver|NULL
* @throws DibiDriverException
* @return Dibi\ResultDriver|NULL
* @throws Dibi\DriverException
*/
public function query($sql)
{
@@ -108,9 +113,9 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
$res = @$this->connection->query($sql); // intentionally @
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);
}
}
@@ -140,7 +145,7 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function begin($savepoint = NULL)
{
@@ -152,7 +157,7 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function commit($savepoint = NULL)
{
@@ -164,7 +169,7 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
* @throws DibiDriverException
* @throws Dibi\DriverException
*/
public function rollback($savepoint = NULL)
{
@@ -184,20 +189,20 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
/**
* Returns the connection reflector.
* @return IDibiReflector
* @return Dibi\Reflector
*/
public function getReflector()
{
return new DibiSqliteReflector($this);
return new SqliteReflector($this);
}
/**
* Result set driver factory.
* @param SQLite3Result
* @return IDibiResultDriver
* @param \SQLite3Result
* @return Dibi\ResultDriver
*/
public function createResultDriver(SQLite3Result $resource)
public function createResultDriver(\SQLite3Result $resource)
{
$res = clone $this;
$res->resultSet = $resource;
@@ -239,8 +244,8 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
public function escapeDate($value)
{
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
$value = new DibiDateTime($value);
if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new Dibi\DateTime($value);
}
return $value->format($this->fmtDate);
}
@@ -248,8 +253,8 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
public function escapeDateTime($value)
{
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
$value = new DibiDateTime($value);
if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
$value = new Dibi\DateTime($value);
}
return $value->format($this->fmtDateTime);
}
@@ -282,7 +287,7 @@ class DibiSqlite3Driver implements IDibiDriver, IDibiResultDriver
/** @deprecated */
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.
* @return int
* @throws DibiNotSupportedException
* @throws Dibi\NotSupportedException
*/
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.
* @param int the 0-based cursor pos to seek to
* @return bool TRUE on success, FALSE if unable to seek to specified record
* @throws DibiNotSupportedException
* @throws Dibi\NotSupportedException
*/
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)
*/
namespace Dibi\Drivers;
use Dibi;
/**
* The dibi reflector for SQLite database.
* @internal
*/
class DibiSqliteReflector implements IDibiReflector
class SqliteReflector implements Dibi\Reflector
{
use DibiStrict;
use Dibi\Strict;
/** @var IDibiDriver */
/** @var Dibi\Driver */
private $driver;
public function __construct(IDibiDriver $driver)
public function __construct(Dibi\Driver $driver)
{
$this->driver = $driver;
}

View File

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

View File

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

View File

@@ -5,12 +5,14 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/
namespace Dibi;
/**
* Lazy cached storage.
* @internal
*/
abstract class DibiHashMapBase
abstract class HashMapBase
{
private $callback;
@@ -25,7 +27,7 @@ abstract class DibiHashMapBase
{
if (!is_callable($callback)) {
$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;
}
@@ -44,7 +46,7 @@ abstract class DibiHashMapBase
*
* @internal
*/
final class DibiHashMap extends DibiHashMapBase
final class HashMap extends HashMapBase
{
public function __set($nm, $val)

View File

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

View File

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

View File

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

View File

@@ -5,13 +5,17 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/
namespace Dibi\Loggers;
use Dibi;
/**
* dibi FirePHP logger.
*/
class DibiFirePhpLogger
class FirePhpLogger
{
use DibiStrict;
use Dibi\Strict;
/** maximum number of rows */
public static $maxQueries = 30;
@@ -46,7 +50,7 @@ class DibiFirePhpLogger
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.
* @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) {
return;
@@ -70,7 +74,7 @@ class DibiFirePhpLogger
self::$fireTable[] = [
sprintf('%0.3f', $event->time * 1000),
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'),
];

View File

@@ -5,13 +5,18 @@
* 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.
*
* @property-read string $name
* @property-read string $fullName
* @property-read DibiTableInfo $table
* @property-read Table $table
* @property-read string $type
* @property-read mixed $nativeType
* @property-read int $size
@@ -20,21 +25,21 @@
* @property-read bool $autoIncrement
* @property-read mixed $default
*/
class DibiColumnInfo
class Column
{
use DibiStrict;
use Dibi\Strict;
/** @var array */
private static $types;
/** @var IDibiReflector|NULL when created by DibiResultInfo */
/** @var Dibi\Reflector|NULL when created by Result */
private $reflector;
/** @var array (name, nativetype, [table], [fullname], [size], [nullable], [default], [autoincrement], [vendor]) */
private $info;
public function __construct(IDibiReflector $reflector = NULL, array $info)
public function __construct(Dibi\Reflector $reflector = NULL, array $info)
{
$this->reflector = $reflector;
$this->info = $info;
@@ -69,14 +74,14 @@ class DibiColumnInfo
/**
* @return DibiTableInfo
* @return Table
*/
public function getTable()
{
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)
{
static $patterns = [
'^_' => DibiType::TEXT, // PostgreSQL arrays
'BYTEA|BLOB|BIN' => DibiType::BINARY,
'TEXT|CHAR|POINT|INTERVAL' => DibiType::TEXT,
'YEAR|BYTE|COUNTER|SERIAL|INT|LONG|SHORT' => DibiType::INTEGER,
'CURRENCY|REAL|MONEY|FLOAT|DOUBLE|DECIMAL|NUMERIC|NUMBER' => DibiType::FLOAT,
'^TIME$' => DibiType::TIME,
'TIME' => DibiType::DATETIME, // DATETIME, TIMESTAMP
'DATE' => DibiType::DATE,
'BOOL' => DibiType::BOOL,
'^_' => Type::TEXT, // PostgreSQL arrays
'BYTEA|BLOB|BIN' => Type::BINARY,
'TEXT|CHAR|POINT|INTERVAL' => Type::TEXT,
'YEAR|BYTE|COUNTER|SERIAL|INT|LONG|SHORT' => Type::INTEGER,
'CURRENCY|REAL|MONEY|FLOAT|DOUBLE|DECIMAL|NUMERIC|NUMBER' => Type::FLOAT,
'^TIME$' => Type::TIME,
'TIME' => Type::DATETIME, // DATETIME, TIMESTAMP
'DATE' => Type::DATE,
'BOOL' => Type::BOOL,
];
foreach ($patterns as $s => $val) {
@@ -187,7 +192,7 @@ class DibiColumnInfo
return $val;
}
}
return DibiType::TEXT;
return Type::TEXT;
}
@@ -197,7 +202,7 @@ class DibiColumnInfo
public static function getTypeCache()
{
if (self::$types === NULL) {
self::$types = new DibiHashMap([__CLASS__, 'detectType']);
self::$types = new Dibi\HashMap([__CLASS__, 'detectType']);
}
return self::$types;
}

View File

@@ -5,6 +5,10 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/
namespace Dibi\Reflection;
use Dibi;
/**
* Reflection metadata class for a database.
@@ -13,11 +17,11 @@
* @property-read array $tables
* @property-read array $tableNames
*/
class DibiDatabaseInfo
class Database
{
use DibiStrict;
use Dibi\Strict;
/** @var IDibiReflector */
/** @var Dibi\Reflector */
private $reflector;
/** @var string */
@@ -27,7 +31,7 @@ class DibiDatabaseInfo
private $tables;
public function __construct(IDibiReflector $reflector, $name)
public function __construct(Dibi\Reflector $reflector, $name)
{
$this->reflector = $reflector;
$this->name = $name;
@@ -44,7 +48,7 @@ class DibiDatabaseInfo
/**
* @return DibiTableInfo[]
* @return Table[]
*/
public function getTables()
{
@@ -69,7 +73,7 @@ class DibiDatabaseInfo
/**
* @param string
* @return DibiTableInfo
* @return Table
*/
public function getTable($name)
{
@@ -79,7 +83,7 @@ class DibiDatabaseInfo
return $this->tables[$l];
} 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) {
$this->tables = [];
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)
*/
namespace Dibi\Reflection;
use Dibi;
/**
* Reflection metadata class for a foreign key.
@@ -12,9 +16,9 @@
* @property-read string $name
* @property-read array $references
*/
class DibiForeignKeyInfo
class ForeignKey
{
use DibiStrict;
use Dibi\Strict;
/** @var string */
private $name;

View File

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

View File

@@ -5,6 +5,10 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/
namespace Dibi\Reflection;
use Dibi;
/**
* Reflection metadata class for a result set.
@@ -12,11 +16,11 @@
* @property-read array $columns
* @property-read array $columnNames
*/
class DibiResultInfo
class Result
{
use DibiStrict;
use Dibi\Strict;
/** @var IDibiResultDriver */
/** @var Dibi\ResultDriver */
private $driver;
/** @var array */
@@ -26,14 +30,14 @@ class DibiResultInfo
private $names;
public function __construct(IDibiResultDriver $driver)
public function __construct(Dibi\ResultDriver $driver)
{
$this->driver = $driver;
}
/**
* @return DibiColumnInfo[]
* @return Column[]
*/
public function getColumns()
{
@@ -59,7 +63,7 @@ class DibiResultInfo
/**
* @param string
* @return DibiColumnInfo
* @return Column
*/
public function getColumn($name)
{
@@ -69,7 +73,7 @@ class DibiResultInfo
return $this->names[$l];
} 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) {
$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) {
$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)
*/
namespace Dibi\Reflection;
use Dibi;
/**
* Reflection metadata class for a database table.
@@ -15,13 +19,13 @@
* @property-read array $columnNames
* @property-read array $foreignKeys
* @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;
/** @var string */
@@ -39,11 +43,11 @@ class DibiTableInfo
/** @var array */
private $indexes;
/** @var DibiIndexInfo */
/** @var Index */
private $primaryKey;
public function __construct(IDibiReflector $reflector, array $info)
public function __construct(Dibi\Reflector $reflector, array $info)
{
$this->reflector = $reflector;
$this->name = $info['name'];
@@ -70,7 +74,7 @@ class DibiTableInfo
/**
* @return DibiColumnInfo[]
* @return Column[]
*/
public function getColumns()
{
@@ -95,7 +99,7 @@ class DibiTableInfo
/**
* @param string
* @return DibiColumnInfo
* @return Column
*/
public function getColumn($name)
{
@@ -105,7 +109,7 @@ class DibiTableInfo
return $this->columns[$l];
} 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()
{
@@ -132,7 +136,7 @@ class DibiTableInfo
/**
* @return DibiIndexInfo[]
* @return Index[]
*/
public function getIndexes()
{
@@ -142,7 +146,7 @@ class DibiTableInfo
/**
* @return DibiIndexInfo
* @return Index
*/
public function getPrimaryKey()
{
@@ -159,7 +163,7 @@ class DibiTableInfo
if ($this->columns === NULL) {
$this->columns = [];
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) {
$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'])) {
$this->primaryKey = $this->indexes[strtolower($info['name'])];
}
@@ -191,7 +195,7 @@ class DibiTableInfo
*/
protected function initForeignKeys()
{
throw new DibiNotImplementedException;
throw new Dibi\NotImplementedException;
}
}

View File

@@ -5,6 +5,8 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/
namespace Dibi;
/**
* dibi result set.
@@ -24,26 +26,26 @@
*
* @property-read int $rowCount
*/
class DibiResult implements IDataSource
class Result implements IDataSource
{
use DibiStrict;
use Strict;
/** @var array IDibiResultDriver */
/** @var array ResultDriver */
private $driver;
/** @var array Translate table */
private $types = [];
/** @var DibiResultInfo */
/** @var Reflection\Result */
private $meta;
/** @var bool Already fetched? Used for allowance for first seek(0) */
private $fetched = FALSE;
/** @var string returned object class */
private $rowClass = 'DibiRow';
private $rowClass = 'Dibi\Row';
/** @var Callback returned object factory*/
/** @var callable returned object factory*/
private $rowFactory;
/** @var array format */
@@ -51,7 +53,7 @@ class DibiResult implements IDataSource
/**
* @param IDibiResultDriver
* @param ResultDriver
*/
public function __construct($driver)
{
@@ -84,13 +86,13 @@ class DibiResult implements IDataSource
/**
* Safe access to property $driver.
* @return IDibiResultDriver
* @throws RuntimeException
* @return ResultDriver
* @throws \RuntimeException
*/
final public function getResultDriver()
{
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;
@@ -104,7 +106,7 @@ class DibiResult implements IDataSource
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
* @return bool TRUE on success, FALSE if unable to seek to specified record
* @throws DibiException
* @throws Exception
*/
final public function seek($row)
{
@@ -134,11 +136,11 @@ class DibiResult implements IDataSource
/**
* Required by the IteratorAggregate interface.
* @return DibiResultIterator
* @return ResultIterator
*/
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
* @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
* @return self
*/
@@ -182,7 +184,7 @@ class DibiResult implements IDataSource
/**
* Fetches the row at current position, process optional type conversion.
* 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()
{
@@ -221,7 +223,7 @@ class DibiResult implements IDataSource
* Fetches all records from table.
* @param int offset
* @param int limit
* @return DibiRow[]
* @return Row[]
*/
final public function fetchAll($offset = NULL, $limit = NULL)
{
@@ -253,8 +255,8 @@ class DibiResult implements IDataSource
* - associative descriptor: col1|col2->col3=col4
* builds a tree: $tree[$val1][$val2]->col3[$val3] = val4
* @param string associative descriptor
* @return DibiRow
* @throws InvalidArgumentException
* @return Row
* @throws \InvalidArgumentException
*/
final public function fetchAssoc($assoc)
{
@@ -275,7 +277,7 @@ class DibiResult implements IDataSource
foreach ($assoc as $as) {
// offsetExists ignores NULL in PHP 5.2.1, isset() surprisingly NULL accepts
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 value
* @return array
* @throws InvalidArgumentException
* @throws \InvalidArgumentException
*/
final public function fetchPairs($key = NULL, $value = NULL)
{
@@ -417,7 +419,7 @@ class DibiResult implements IDataSource
if ($value === 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
@@ -434,7 +436,7 @@ class DibiResult implements IDataSource
} else {
if (!property_exists($row, $value)) {
throw new InvalidArgumentException("Unknown value column '$value'.");
throw new \InvalidArgumentException("Unknown value column '$value'.");
}
if ($key === NULL) { // indexed-array
@@ -445,7 +447,7 @@ class DibiResult implements IDataSource
}
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()
{
$cache = DibiColumnInfo::getTypeCache();
$cache = Reflection\Column::getTypeCache();
try {
foreach ($this->getResultDriver()->getResultColumns() as $col) {
$this->types[$col['name']] = $cache->{$col['nativetype']};
}
} catch (DibiNotSupportedException $e) {
} catch (NotSupportedException $e) {
}
}
@@ -488,24 +490,24 @@ class DibiResult implements IDataSource
continue;
}
$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;
} 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;
} elseif ($type === DibiType::BOOL) {
} elseif ($type === Type::BOOL) {
$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', ...
$value = new DibiDateTime($value);
$value = new DateTime($value);
$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);
}
}
@@ -515,7 +517,7 @@ class DibiResult implements IDataSource
/**
* Define column type.
* @param string column
* @param string type (use constant DibiType::*)
* @param string type (use constant Type::*)
* @return self
*/
final public function setType($col, $type)
@@ -537,7 +539,7 @@ class DibiResult implements IDataSource
/**
* Sets data format.
* @param string type (use constant DibiType::*)
* @param string type (use constant Type::*)
* @param string format
* @return self
*/
@@ -563,12 +565,12 @@ class DibiResult implements IDataSource
/**
* Returns a meta information about the current result set.
* @return DibiResultInfo
* @return Reflection\Result
*/
public function getInfo()
{
if ($this->meta === NULL) {
$this->meta = new DibiResultInfo($this->getResultDriver());
$this->meta = new Reflection\Result($this->getResultDriver());
}
return $this->meta;
}

View File

@@ -5,11 +5,13 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/
namespace Dibi;
/**
* 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>
* $result = dibi::query('SELECT * FROM table');
* foreach ($result as $row) {
@@ -18,11 +20,11 @@
* unset($result);
* </code>
*/
class DibiResultIterator implements Iterator, Countable
class ResultIterator implements \Iterator, \Countable
{
use DibiStrict;
use Strict;
/** @var DibiResult */
/** @var Result */
private $result;
/** @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;
}

View File

@@ -5,11 +5,13 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/
namespace Dibi;
/**
* Result set single row.
*/
class DibiRow implements ArrayAccess, IteratorAggregate, Countable
class Row implements \ArrayAccess, \IteratorAggregate, \Countable
{
public function __construct($arr)
@@ -30,16 +32,16 @@ class DibiRow implements ArrayAccess, IteratorAggregate, Countable
* Converts value to DateTime object.
* @param string key
* @param string format
* @return DateTime
* @return \DateTime
*/
public function asDateTime($key, $format = NULL)
{
$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', ...
return NULL;
}
$time = new DibiDateTime($time);
$time = new DateTime($time);
}
return $format === NULL ? $time : $time->format($format);
}
@@ -47,7 +49,7 @@ class DibiRow implements ArrayAccess, IteratorAggregate, Countable
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);
}
@@ -63,7 +65,7 @@ class DibiRow implements ArrayAccess, IteratorAggregate, Countable
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)
*/
namespace Dibi;
use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
/**
* Better OOP experience.
*/
trait DibiStrict
trait Strict
{
/** @var array [method => [type => callback]] */
private static $extMethods;
@@ -17,7 +23,7 @@ trait DibiStrict
/**
* Call to undefined method.
* @throws LogicException
* @throws \LogicException
*/
public function __call($name, $args)
{
@@ -27,27 +33,27 @@ trait DibiStrict
}
$class = method_exists($this, $name) ? 'parent' : get_class($this);
$items = (new ReflectionClass($this))->getMethods(ReflectionMethod::IS_PUBLIC);
$hint = ($t = DibiHelpers::getSuggestion($items, $name)) ? ", did you mean $t()?" : '.';
throw new LogicException("Call to undefined method $class::$name()$hint");
$hint = ($t = Helpers::getSuggestion($items, $name)) ? ", did you mean $t()?" : '.';
throw new \LogicException("Call to undefined method $class::$name()$hint");
}
/**
* Call to undefined static method.
* @throws LogicException
* @throws \LogicException
*/
public static function __callStatic($name, $args)
{
$rc = new ReflectionClass(get_called_class());
$items = array_intersect($rc->getMethods(ReflectionMethod::IS_PUBLIC), $rc->getMethods(ReflectionMethod::IS_STATIC));
$hint = ($t = DibiHelpers::getSuggestion($items, $name)) ? ", did you mean $t()?" : '.';
throw new LogicException("Call to undefined static method {$rc->getName()}::$name()$hint");
$hint = ($t = Helpers::getSuggestion($items, $name)) ? ", did you mean $t()?" : '.';
throw new \LogicException("Call to undefined static method {$rc->getName()}::$name()$hint");
}
/**
* Access to undeclared property.
* @throws LogicException
* @throws \LogicException
*/
public function &__get($name)
{
@@ -59,21 +65,21 @@ trait DibiStrict
}
$rc = new ReflectionClass($this);
$items = array_diff($rc->getProperties(ReflectionProperty::IS_PUBLIC), $rc->getProperties(ReflectionProperty::IS_STATIC));
$hint = ($t = DibiHelpers::getSuggestion($items, $name)) ? ", did you mean $$t?" : '.';
throw new LogicException("Attempt to read undeclared property {$rc->getName()}::$$name$hint");
$hint = ($t = Helpers::getSuggestion($items, $name)) ? ", did you mean $$t?" : '.';
throw new \LogicException("Attempt to read undeclared property {$rc->getName()}::$$name$hint");
}
/**
* Access to undeclared property.
* @throws LogicException
* @throws \LogicException
*/
public function __set($name, $value)
{
$rc = new ReflectionClass($this);
$items = array_diff($rc->getProperties(ReflectionProperty::IS_PUBLIC), $rc->getProperties(ReflectionProperty::IS_STATIC));
$hint = ($t = DibiHelpers::getSuggestion($items, $name)) ? ", did you mean $$t?" : '.';
throw new LogicException("Attempt to write to undeclared property {$rc->getName()}::$$name$hint");
$hint = ($t = Helpers::getSuggestion($items, $name)) ? ", did you mean $$t?" : '.';
throw new \LogicException("Attempt to write to undeclared property {$rc->getName()}::$$name$hint");
}
@@ -88,12 +94,12 @@ trait DibiStrict
/**
* Access to undeclared property.
* @throws LogicException
* @throws \LogicException
*/
public function __unset($name)
{
$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();
} else {
list($class, $name) = explode('::', $name);
$class = (new \ReflectionClass($class))->getName();
$class = (new ReflectionClass($class))->getName();
}
$list = & self::$extMethods[strtolower($name)];
if ($callback === NULL) { // getter

View File

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

View File

@@ -5,11 +5,13 @@
* Copyright (c) 2005 David Grudl (https://davidgrudl.com)
*/
namespace Dibi;
/**
* Data types.
*/
class DibiType
class Type
{
const
TEXT = 's', // as 'string'
@@ -23,7 +25,7 @@ class DibiType
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)
*/
use Dibi\Type;
/**
* This class is static container class for creating DB objects and
@@ -12,7 +14,7 @@
*/
class dibi
{
use DibiStrict;
use Dibi\Strict;
const
AFFECTED_ROWS = 'a',
@@ -30,27 +32,27 @@ class dibi
/** @deprecated */
const
TEXT = DibiType::TEXT,
BINARY = DibiType::BINARY,
BOOL = DibiType::BOOL,
INTEGER = DibiType::INTEGER,
FLOAT = DibiType::FLOAT,
DATE = DibiType::DATE,
DATETIME = DibiType::DATETIME,
TIME = DibiType::TIME,
FIELD_TEXT = DibiType::TEXT,
FIELD_BINARY = DibiType::BINARY,
FIELD_BOOL = DibiType::BOOL,
FIELD_INTEGER = DibiType::INTEGER,
FIELD_FLOAT = DibiType::FLOAT,
FIELD_DATE = DibiType::DATE,
FIELD_DATETIME = DibiType::DATETIME,
FIELD_TIME = DibiType::TIME;
TEXT = Type::TEXT,
BINARY = Type::BINARY,
BOOL = Type::BOOL,
INTEGER = Type::INTEGER,
FLOAT = Type::FLOAT,
DATE = Type::DATE,
DATETIME = Type::DATETIME,
TIME = Type::TIME,
FIELD_TEXT = Type::TEXT,
FIELD_BINARY = Type::BINARY,
FIELD_BOOL = Type::BOOL,
FIELD_INTEGER = Type::INTEGER,
FIELD_FLOAT = Type::FLOAT,
FIELD_DATE = Type::DATE,
FIELD_DATETIME = Type::DATETIME,
FIELD_TIME = Type::TIME;
/** @var DibiConnection[] Connection registry storage for DibiConnection objects */
/** @var Dibi\Connection[] Connection registry storage for DibiConnection objects */
private static $registry = [];
/** @var DibiConnection Current connection */
/** @var Dibi\Connection Current connection */
private static $connection;
/** @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 string connection name
* @return DibiConnection
* @throws DibiException
* @return Dibi\Connection
* @throws Dibi\Exception
*/
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
*/
public static function disconnect()
@@ -117,21 +119,21 @@ class dibi
/**
* Retrieve active connection.
* @param string connection registy name
* @return DibiConnection
* @throws DibiException
* @return Dibi\Connection
* @throws Dibi\Exception
*/
public static function getConnection($name = NULL)
{
if ($name === 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;
}
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];
@@ -140,10 +142,10 @@ class dibi
/**
* Sets connection.
* @param DibiConnection
* @return DibiConnection
* @param Dibi\Connection
* @return Dibi\Connection
*/
public static function setConnection(DibiConnection $connection)
public static function setConnection(Dibi\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
* @return DibiResult|int result set object (if any)
* @throws DibiException
* @return Dibi\Result|int result set object (if any)
* @throws Dibi\Exception
*/
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.
* @return DibiResult|int result set object (if any)
* @return Dibi\Result|int result set object (if any)
*/
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
* @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
* @return DibiDataSource
* @return Dibi\DataSource
*/
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
* @return DibiRow
* @throws DibiException
* @return Dibi\Row
* @throws Dibi\Exception
*/
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
* @return DibiRow[]
* @throws DibiException
* @return Dibi\Row[]
* @throws Dibi\Exception
*/
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
* @return string
* @throws DibiException
* @throws Dibi\Exception
*/
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
* @return string
* @throws DibiException
* @throws Dibi\Exception
*/
public static function fetchPairs($args)
{
@@ -264,9 +266,9 @@ class dibi
/**
* Gets the number of affected rows.
* Monostate for DibiConnection::getAffectedRows()
* Monostate for Dibi\Connection::getAffectedRows()
* @return int number of rows
* @throws DibiException
* @throws Dibi\Exception
*/
public static function getAffectedRows()
{
@@ -277,7 +279,7 @@ class dibi
/**
* Gets the number of affected rows. Alias for getAffectedRows().
* @return int number of rows
* @throws DibiException
* @throws Dibi\Exception
*/
public static function affectedRows()
{
@@ -287,10 +289,10 @@ class dibi
/**
* 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
* @return int
* @throws DibiException
* @throws Dibi\Exception
*/
public static function getInsertId($sequence = NULL)
{
@@ -302,7 +304,7 @@ class dibi
* Retrieves the ID generated for an AUTO_INCREMENT column. Alias for getInsertId().
* @param string optional sequence name
* @return int
* @throws DibiException
* @throws Dibi\Exception
*/
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
* @return void
* @throws DibiException
* @throws Dibi\Exception
*/
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
* @return void
* @throws DibiException
* @throws Dibi\Exception
*/
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
* @return void
* @throws DibiException
* @throws Dibi\Exception
*/
public static function rollback($savepoint = NULL)
{
@@ -347,8 +349,8 @@ class dibi
/**
* Gets a information about the current database - Monostate for DibiConnection::getDatabaseInfo().
* @return DibiDatabaseInfo
* Gets a information about the current database - Monostate for Dibi\Connection::getDatabaseInfo().
* @return Dibi\Reflection\Database
*/
public static function getDatabaseInfo()
{
@@ -383,7 +385,7 @@ class dibi
/**
* @return DibiFluent
* @return Dibi\Fluent
*/
public static function command()
{
@@ -393,7 +395,7 @@ class dibi
/**
* @param string column name
* @return DibiFluent
* @return Dibi\Fluent
*/
public static function select($args)
{
@@ -405,7 +407,7 @@ class dibi
/**
* @param string table
* @param array
* @return DibiFluent
* @return Dibi\Fluent
*/
public static function update($table, $args)
{
@@ -416,7 +418,7 @@ class dibi
/**
* @param string table
* @param array
* @return DibiFluent
* @return Dibi\Fluent
*/
public static function insert($table, $args)
{
@@ -426,7 +428,7 @@ class dibi
/**
* @param string table
* @return DibiFluent
* @return Dibi\Fluent
*/
public static function delete($table)
{
@@ -438,8 +440,8 @@ class dibi
/**
* Returns substitution hashmap - Monostate for DibiConnection::getSubstitutes().
* @return DibiHashMap
* Returns substitution hashmap - Monostate for Dibi\Connection::getSubstitutes().
* @return Dibi\HashMap
*/
public static function getSubstitutes()
{
@@ -451,14 +453,14 @@ class dibi
/**
* Prints out a syntax highlighted version of the SQL command or DibiResult.
* @param string|DibiResult
* Prints out a syntax highlighted version of the SQL command or Result.
* @param string|Result
* @param bool return output instead of printing it?
* @return string
*/
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)
*/
namespace Dibi;
/**
* dibi common exception.
*/
class DibiException extends Exception
class Exception extends \Exception
{
use DibiStrict;
use Strict;
/** @var string */
private $sql;
@@ -53,7 +55,7 @@ class DibiException extends Exception
/**
* database server exception.
*/
class DibiDriverException extends DibiException
class DriverException extends Exception
{
/********************* error catching ****************d*g**/
@@ -110,9 +112,9 @@ class DibiDriverException extends DibiException
/**
* PCRE exception.
*/
class DibiPcreException extends Exception
class PcreException extends \Exception
{
use DibiStrict;
use Strict;
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.
*/
class DibiProcedureException extends DibiException
class ProcedureException extends Exception
{
/** @var string */
protected $severity;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,13 +1,14 @@
<?php
use Tester\Assert;
use Dibi\Fluent;
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');
$dolly = clone $fluent;
$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);
$fluent = new DibiFluent($conn);
$fluent = new Fluent($conn);
$fluent->select('id')->from('table')->where('id = %i', 1);
$dolly = clone $fluent;
$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);
$fluent = new DibiFluent($conn);
$fluent = new Fluent($conn);
$fluent->select('*')->from('table');
$dolly = clone $fluent;
$dolly->removeClause('select')->select('count(*)');

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -25,7 +25,7 @@ $tests = function ($conn) {
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 standard_conforming_strings = on');

View File

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

View File

@@ -4,15 +4,15 @@ use Tester\Assert;
require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config);
$conn = new Dibi\Connection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql");
$res = $conn->query('SELECT * FROM [customers]');
// 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([
'customer_id' => new DibiDateTime('1970-01-01 01:00:01'),
Assert::equal(new Dibi\Row([
'customer_id' => new Dibi\DateTime('1970-01-01 01:00:01'),
'name' => 'Dave Lister',
]), $res->fetch());

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -5,10 +5,11 @@
*/
use Tester\Assert;
use Dibi\DateTime;
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
@@ -76,7 +77,7 @@ Assert::same(
// invalid input
$e = Assert::exception(function () use ($conn) {
$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(
@@ -148,7 +149,7 @@ Assert::same(
if ($config['system'] === 'odbc') {
Assert::exception(function () use ($conn) {
$conn->translate('SELECT * FROM [products] %lmt %ofs', 2, 1);
}, 'DibiException');
}, 'Dibi\Exception');
} else {
// with limit = 2, offset = 1
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)",
]),
$conn->translate('INSERT INTO test', [
'a2' => new DibiDateTime('1212-09-26'),
'a4' => new DibiDateTime(-10000),
'a2' => new DateTime('1212-09-26'),
'a4' => new DateTime(-10000),
'b1%d' => '1212-09-26',
'b2%t' => '1212-09-26',
'b3%d' => -10000,
@@ -227,7 +228,7 @@ if ($config['system'] === 'pgsql') {
$e = Assert::exception(function () use ($conn) {
$conn->translate("SELECT '");
}, 'DibiException', 'SQL translate error');
}, 'Dibi\Exception', 'SQL translate error');
Assert::same('SELECT **Alone quote**', $e->getSql());
Assert::match(
@@ -273,7 +274,7 @@ $array3 = [
$array4 = [
'a' => 12,
'b' => NULL,
'c' => new DibiDateTime('12.3.2007'),
'c' => new DateTime('12.3.2007'),
'd' => 'any string',
];
@@ -472,7 +473,7 @@ $e = Assert::exception(function () use ($conn) {
'num%i' => ['1', ''],
];
$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());
$array6 = [

View File

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

View File

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