mirror of
https://github.com/dg/dibi.git
synced 2025-08-30 17:29:53 +02:00
Compare commits
13 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
2dc30747e5 | ||
|
23531a0f3d | ||
|
22c6f2dfda | ||
|
f51ac0b67e | ||
|
43f5e08296 | ||
|
997f5a98f8 | ||
|
e4b3cfb12c | ||
|
26082294b6 | ||
|
b3052b4ce2 | ||
|
efa3a48232 | ||
|
24511a1d96 | ||
|
a20ba29b13 | ||
|
a606be0efa |
4
.gitattributes
vendored
4
.gitattributes
vendored
@@ -1,4 +0,0 @@
|
||||
.gitattributes export-ignore
|
||||
.gitignore export-ignore
|
||||
.travis.yml export-ignore
|
||||
tests/ export-ignore
|
2
.gitignore
vendored
2
.gitignore
vendored
@@ -1,2 +0,0 @@
|
||||
/vendor
|
||||
/composer.lock
|
21
.travis.yml
21
.travis.yml
@@ -1,21 +0,0 @@
|
||||
language: php
|
||||
php:
|
||||
- 5.3.3
|
||||
- 5.4
|
||||
- 5.5
|
||||
- 5.6
|
||||
- hhvm
|
||||
|
||||
matrix:
|
||||
allow_failures:
|
||||
- php: hhvm
|
||||
|
||||
script: vendor/bin/tester tests -s -c tests/php-unix.ini
|
||||
|
||||
after_failure:
|
||||
# Print *.actual content
|
||||
- for i in $(find tests -name \*.actual); do echo "--- $i"; cat $i; echo; echo; done
|
||||
|
||||
before_script:
|
||||
# Install Nette Tester
|
||||
- composer install --no-interaction --dev --prefer-source
|
@@ -1,30 +1,16 @@
|
||||
{
|
||||
"name": "dibi/dibi",
|
||||
"description": "Dibi is Database Abstraction Library for PHP",
|
||||
"keywords": ["database", "dbal", "mysql", "postgresql", "sqlite", "mssql", "oracle", "access", "pdo", "odbc"],
|
||||
"homepage": "http://dibiphp.com",
|
||||
"license": ["BSD-3-Clause", "GPL-2.0", "GPL-3.0"],
|
||||
"name": "dg/dibi",
|
||||
"description": "Dibi is Database Abstraction Library for PHP 5.",
|
||||
"keywords": ["dibi", "database", "dbal", "mysql", "postgresql", "sqlite", "mssql", "oracle", "access", "pdo", "odbc"],
|
||||
"homepage": "http://dibiphp.com/",
|
||||
"license": ["BSD-3", "GPLv2", "GPLv3"],
|
||||
"authors": [
|
||||
{
|
||||
"name": "David Grudl",
|
||||
"homepage": "http://davidgrudl.com"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": ">=5.2.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"nette/tester": "~1.1"
|
||||
},
|
||||
"replace": {
|
||||
"dg/dibi": "self.version"
|
||||
},
|
||||
"autoload": {
|
||||
"classmap": ["dibi/"]
|
||||
},
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "2.2-dev"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -10,14 +10,15 @@
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Dibi extension for Nette Framework 2.0. Creates 'connection' service.
|
||||
* Dibi extension for Nette Framework. Creates 'connection' service.
|
||||
*
|
||||
* @author David Grudl
|
||||
* @package dibi\nette
|
||||
* @phpversion 5.3
|
||||
*/
|
||||
class DibiNette20Extension extends Nette\Config\CompilerExtension
|
||||
class DibiNetteExtension extends Nette\Config\CompilerExtension
|
||||
{
|
||||
|
||||
public function loadConfiguration()
|
||||
@@ -46,7 +47,7 @@ class DibiNette20Extension extends Nette\Config\CompilerExtension
|
||||
$panel = $container->addDefinition($this->prefix('panel'))
|
||||
->setClass('DibiNettePanel')
|
||||
->addSetup('Nette\Diagnostics\Debugger::$bar->addPanel(?)', array('@self'))
|
||||
->addSetup('Nette\Diagnostics\Debugger::$blueScreen->addPanel(?)', array('DibiNettePanel::renderException'));
|
||||
->addSetup('Nette\Diagnostics\Debugger::$blueScreen->addPanel(?)', array(array('@self', 'renderException')));
|
||||
|
||||
$connection->addSetup('$service->onEvent[] = ?', array(array($panel, 'logEvent')));
|
||||
}
|
@@ -2,15 +2,21 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
if (interface_exists('Nette\Diagnostics\IBarPanel')) {
|
||||
class_alias('Nette\Diagnostics\IBarPanel', 'IBarPanel');
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Dibi panel for Nette\Diagnostics.
|
||||
*
|
||||
@@ -32,6 +38,7 @@ class DibiNettePanel extends DibiObject implements IBarPanel
|
||||
private $events = array();
|
||||
|
||||
|
||||
|
||||
public function __construct($explain = TRUE, $filter = NULL)
|
||||
{
|
||||
$this->filter = $filter ? (int) $filter : DibiEvent::QUERY;
|
||||
@@ -39,29 +46,25 @@ class DibiNettePanel extends DibiObject implements IBarPanel
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function register(DibiConnection $connection)
|
||||
{
|
||||
if (is_callable('Nette\Diagnostics\Debugger::enable') && !class_exists('NDebugger')) {
|
||||
class_alias('Nette\Diagnostics\Debugger', 'NDebugger'); // PHP 5.2 code compatibility
|
||||
}
|
||||
if (is_callable('NDebugger::enable') && is_callable('NDebugger::getBlueScreen')) { // Nette Framework 2.1
|
||||
NDebugger::getBar()->addPanel($this);
|
||||
NDebugger::getBlueScreen()->addPanel(array(__CLASS__, 'renderException'));
|
||||
$connection->onEvent[] = array($this, 'logEvent');
|
||||
|
||||
} elseif (is_callable('NDebugger::enable')) { // Nette Framework 2.0 (for PHP 5.3 or PHP 5.2 prefixed)
|
||||
if (is_callable('NDebugger::enable')) {
|
||||
NDebugger::$bar && NDebugger::$bar->addPanel($this);
|
||||
NDebugger::$blueScreen && NDebugger::$blueScreen->addPanel(array(__CLASS__, 'renderException'), __CLASS__);
|
||||
NDebugger::$blueScreen && NDebugger::$blueScreen->addPanel(array($this, 'renderException'), __CLASS__);
|
||||
$connection->onEvent[] = array($this, 'logEvent');
|
||||
|
||||
} elseif (is_callable('Debugger::enable') && !is_callable('Debugger::getBlueScreen')) { // Nette Framework 2.0 for PHP 5.2 non-prefixed
|
||||
} elseif (is_callable('Debugger::enable')) {
|
||||
Debugger::$bar && Debugger::$bar->addPanel($this);
|
||||
Debugger::$blueScreen && Debugger::$blueScreen->addPanel(array(__CLASS__, 'renderException'), __CLASS__);
|
||||
Debugger::$blueScreen && Debugger::$blueScreen->addPanel(array($this, 'renderException'), __CLASS__);
|
||||
$connection->onEvent[] = array($this, 'logEvent');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* After event notification.
|
||||
* @return void
|
||||
@@ -75,11 +78,12 @@ class DibiNettePanel extends DibiObject implements IBarPanel
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns blue-screen custom tab.
|
||||
* @return mixed
|
||||
*/
|
||||
public static function renderException($e)
|
||||
public function renderException($e)
|
||||
{
|
||||
if ($e instanceof DibiException && $e->getSql()) {
|
||||
return array(
|
||||
@@ -90,6 +94,7 @@ class DibiNettePanel extends DibiObject implements IBarPanel
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns HTML code for custom tab. (Nette\Diagnostics\IBarPanel)
|
||||
* @return mixed
|
||||
@@ -102,11 +107,12 @@ class DibiNettePanel extends DibiObject implements IBarPanel
|
||||
}
|
||||
return '<span title="dibi"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAEYSURBVBgZBcHPio5hGAfg6/2+R980k6wmJgsJ5U/ZOAqbSc2GnXOwUg7BESgLUeIQ1GSjLFnMwsKGGg1qxJRmPM97/1zXFAAAAEADdlfZzr26miup2svnelq7d2aYgt3rebl585wN6+K3I1/9fJe7O/uIePP2SypJkiRJ0vMhr55FLCA3zgIAOK9uQ4MS361ZOSX+OrTvkgINSjS/HIvhjxNNFGgQsbSmabohKDNoUGLohsls6BaiQIMSs2FYmnXdUsygQYmumy3Nhi6igwalDEOJEjPKP7CA2aFNK8Bkyy3fdNCg7r9/fW3jgpVJbDmy5+PB2IYp4MXFelQ7izPrhkPHB+P5/PjhD5gCgCenx+VR/dODEwD+A3T7nqbxwf1HAAAAAElFTkSuQmCC" />'
|
||||
. count($this->events) . ' queries'
|
||||
. ($totalTime ? sprintf(' / %0.1f ms', $totalTime * 1000) : '')
|
||||
. ($totalTime ? ' / ' . sprintf('%0.1f', $totalTime * 1000) . 'ms' : '')
|
||||
. '</span>';
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns HTML code for custom panel. (Nette\Diagnostics\IBarPanel)
|
||||
* @return mixed
|
||||
@@ -132,7 +138,7 @@ class DibiNettePanel extends DibiObject implements IBarPanel
|
||||
if ($explain) {
|
||||
static $counter;
|
||||
$counter++;
|
||||
$s .= "<br /><a href='#nette-debug-DibiProfiler-row-$counter' class='nette-toggler nette-toggle-collapsed' rel='#nette-debug-DibiProfiler-row-$counter'>explain</a>";
|
||||
$s .= "<br /><a href='#' class='nette-toggler' rel='#nette-debug-DibiProfiler-row-$counter'>explain ►</a>";
|
||||
}
|
||||
|
||||
$s .= '</td><td class="nette-DibiProfiler-sql">' . dibi::dump(strlen($event->sql) > self::$maxLength ? substr($event->sql, 0, self::$maxLength) . '...' : $event->sql, TRUE);
|
||||
@@ -154,7 +160,7 @@ class DibiNettePanel extends DibiObject implements IBarPanel
|
||||
'<style> #nette-debug td.nette-DibiProfiler-sql { background: white !important }
|
||||
#nette-debug .nette-DibiProfiler-source { color: #999 !important }
|
||||
#nette-debug nette-DibiProfiler tr table { margin: 8px 0; max-height: 150px; overflow:auto } </style>
|
||||
<h1>Queries: ' . count($this->events) . ($totalTime === NULL ? '' : sprintf(', time: %0.3f ms', $totalTime * 1000)) . '</h1>
|
||||
<h1>Queries: ' . count($this->events) . ($totalTime === NULL ? '' : ', time: ' . sprintf('%0.3f', $totalTime * 1000) . ' ms') . '</h1>
|
||||
<div class="nette-inner nette-DibiProfiler">
|
||||
<table>
|
||||
<tr><th>Time ms</th><th>SQL Statement</th><th>Rows</th><th>Connection</th></tr>' . $s . '
|
@@ -1,17 +0,0 @@
|
||||
# Requires Nette Framework 2.0 for PHP 5.3
|
||||
#
|
||||
# In bootstrap.php append these lines after line $configurator = new Nette\Config\Configurator;
|
||||
#
|
||||
# $configurator->onCompile[] = function($configurator, $compiler) {
|
||||
# $compiler->addExtension('dibi', new DibiNette20Extension);
|
||||
# };
|
||||
#
|
||||
# This will create service named 'dibi.connection'.
|
||||
|
||||
common:
|
||||
dibi:
|
||||
host: localhost
|
||||
username: root
|
||||
password: ***
|
||||
database: foo
|
||||
lazy: TRUE
|
@@ -1,51 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Dibi extension for Nette Framework 2.1. Creates 'connection' service.
|
||||
*
|
||||
* @author David Grudl
|
||||
* @package dibi\nette
|
||||
* @phpversion 5.3
|
||||
*/
|
||||
class DibiNette21Extension extends Nette\DI\CompilerExtension
|
||||
{
|
||||
|
||||
public function loadConfiguration()
|
||||
{
|
||||
$container = $this->getContainerBuilder();
|
||||
$config = $this->getConfig();
|
||||
|
||||
$useProfiler = isset($config['profiler'])
|
||||
? $config['profiler']
|
||||
: $container->parameters['debugMode'];
|
||||
|
||||
unset($config['profiler']);
|
||||
|
||||
if (isset($config['flags'])) {
|
||||
$flags = 0;
|
||||
foreach ((array) $config['flags'] as $flag) {
|
||||
$flags |= constant($flag);
|
||||
}
|
||||
$config['flags'] = $flags;
|
||||
}
|
||||
|
||||
$connection = $container->addDefinition($this->prefix('connection'))
|
||||
->setClass('DibiConnection', array($config));
|
||||
|
||||
if ($useProfiler) {
|
||||
$panel = $container->addDefinition($this->prefix('panel'))
|
||||
->setClass('DibiNettePanel')
|
||||
->addSetup('Nette\Diagnostics\Debugger::getBar()->addPanel(?)', array('@self'))
|
||||
->addSetup('Nette\Diagnostics\Debugger::getBlueScreen()->addPanel(?)', array('DibiNettePanel::renderException'));
|
||||
|
||||
$connection->addSetup('$service->onEvent[] = ?', array(array($panel, 'logEvent')));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@@ -1,12 +0,0 @@
|
||||
# This will create service named 'dibi.connection'.
|
||||
# Requires Nette Framework 2.1
|
||||
|
||||
extensions:
|
||||
dibi: DibiNette21Extension
|
||||
|
||||
dibi:
|
||||
host: localhost
|
||||
username: root
|
||||
password: ***
|
||||
database: foo
|
||||
lazy: TRUE
|
@@ -1,52 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*/
|
||||
|
||||
namespace Dibi\Bridges\Nette;
|
||||
|
||||
use dibi,
|
||||
Nette;
|
||||
|
||||
|
||||
/**
|
||||
* Dibi extension for Nette Framework 2.2. Creates 'connection' & 'panel' services.
|
||||
*
|
||||
* @author David Grudl
|
||||
* @package dibi\nette
|
||||
*/
|
||||
class DibiExtension22 extends Nette\DI\CompilerExtension
|
||||
{
|
||||
|
||||
public function loadConfiguration()
|
||||
{
|
||||
$container = $this->getContainerBuilder();
|
||||
$config = $this->getConfig();
|
||||
|
||||
$useProfiler = isset($config['profiler'])
|
||||
? $config['profiler']
|
||||
: class_exists('Tracy\Debugger') && $container->parameters['debugMode'];
|
||||
|
||||
unset($config['profiler']);
|
||||
|
||||
if (isset($config['flags'])) {
|
||||
$flags = 0;
|
||||
foreach ((array) $config['flags'] as $flag) {
|
||||
$flags |= constant($flag);
|
||||
}
|
||||
$config['flags'] = $flags;
|
||||
}
|
||||
|
||||
$connection = $container->addDefinition($this->prefix('connection'))
|
||||
->setClass('DibiConnection', array($config));
|
||||
|
||||
if ($useProfiler) {
|
||||
$panel = $container->addDefinition($this->prefix('panel'))
|
||||
->setClass('Dibi\Bridges\Tracy\Panel');
|
||||
$connection->addSetup(array($panel, 'register'), array($connection));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@@ -1,12 +0,0 @@
|
||||
# This will create service named 'dibi.connection'.
|
||||
# Requires Nette Framework 2.2
|
||||
|
||||
extensions:
|
||||
dibi: Dibi\Bridges\Nette\DibiExtension22
|
||||
|
||||
dibi:
|
||||
host: localhost
|
||||
username: root
|
||||
password: ***
|
||||
database: foo
|
||||
lazy: TRUE
|
@@ -1,145 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*/
|
||||
|
||||
namespace Dibi\Bridges\Tracy;
|
||||
|
||||
use dibi,
|
||||
Tracy;
|
||||
|
||||
|
||||
/**
|
||||
* Dibi panel for Tracy.
|
||||
*
|
||||
* @author David Grudl
|
||||
*/
|
||||
class Panel extends \DibiObject implements Tracy\IBarPanel
|
||||
{
|
||||
/** @var int maximum SQL length */
|
||||
static public $maxLength = 1000;
|
||||
|
||||
/** @var bool explain queries? */
|
||||
public $explain;
|
||||
|
||||
/** @var int */
|
||||
public $filter;
|
||||
|
||||
/** @var array */
|
||||
private $events = array();
|
||||
|
||||
|
||||
public function __construct($explain = TRUE, $filter = NULL)
|
||||
{
|
||||
$this->filter = $filter ? (int) $filter : \DibiEvent::QUERY;
|
||||
$this->explain = $explain;
|
||||
}
|
||||
|
||||
|
||||
public function register(\DibiConnection $connection)
|
||||
{
|
||||
Tracy\Debugger::getBar()->addPanel($this);
|
||||
Tracy\Debugger::getBlueScreen()->addPanel(array(__CLASS__, 'renderException'));
|
||||
$connection->onEvent[] = array($this, 'logEvent');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* After event notification.
|
||||
* @return void
|
||||
*/
|
||||
public function logEvent(\DibiEvent $event)
|
||||
{
|
||||
if (($event->type & $this->filter) === 0) {
|
||||
return;
|
||||
}
|
||||
$this->events[] = $event;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns blue-screen custom tab.
|
||||
* @return mixed
|
||||
*/
|
||||
public static function renderException($e)
|
||||
{
|
||||
if ($e instanceof \DibiException && $e->getSql()) {
|
||||
return array(
|
||||
'tab' => 'SQL',
|
||||
'panel' => dibi::dump($e->getSql(), TRUE),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns HTML code for custom tab. (Tracy\IBarPanel)
|
||||
* @return mixed
|
||||
*/
|
||||
public function getTab()
|
||||
{
|
||||
$totalTime = 0;
|
||||
foreach ($this->events as $event) {
|
||||
$totalTime += $event->time;
|
||||
}
|
||||
return '<span title="dibi"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAEYSURBVBgZBcHPio5hGAfg6/2+R980k6wmJgsJ5U/ZOAqbSc2GnXOwUg7BESgLUeIQ1GSjLFnMwsKGGg1qxJRmPM97/1zXFAAAAEADdlfZzr26miup2svnelq7d2aYgt3rebl585wN6+K3I1/9fJe7O/uIePP2SypJkiRJ0vMhr55FLCA3zgIAOK9uQ4MS361ZOSX+OrTvkgINSjS/HIvhjxNNFGgQsbSmabohKDNoUGLohsls6BaiQIMSs2FYmnXdUsygQYmumy3Nhi6igwalDEOJEjPKP7CA2aFNK8Bkyy3fdNCg7r9/fW3jgpVJbDmy5+PB2IYp4MXFelQ7izPrhkPHB+P5/PjhD5gCgCenx+VR/dODEwD+A3T7nqbxwf1HAAAAAElFTkSuQmCC" />'
|
||||
. count($this->events) . ' queries'
|
||||
. ($totalTime ? sprintf(' / %0.1f ms', $totalTime * 1000) : '')
|
||||
. '</span>';
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns HTML code for custom panel. (Tracy\IBarPanel)
|
||||
* @return mixed
|
||||
*/
|
||||
public function getPanel()
|
||||
{
|
||||
$totalTime = $s = NULL;
|
||||
$h = 'htmlSpecialChars';
|
||||
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) {
|
||||
try {
|
||||
$backup = array($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' : 'EXPLAIN');
|
||||
$explain = dibi::dump($event->connection->nativeQuery("$cmd $event->sql"), TRUE);
|
||||
} catch (\DibiException $e) {}
|
||||
list($event->connection->onEvent, dibi::$numOfQueries, dibi::$totalTime) = $backup;
|
||||
}
|
||||
|
||||
$s .= '<tr><td>' . sprintf('%0.3f', $event->time * 1000);
|
||||
if ($explain) {
|
||||
static $counter;
|
||||
$counter++;
|
||||
$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">' . dibi::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>";
|
||||
}
|
||||
if ($event->source) {
|
||||
$s .= Tracy\Helpers::editorLink($event->source[0], $event->source[1]);//->class('tracy-DibiProfiler-source');
|
||||
}
|
||||
|
||||
$s .= "</td><td>{$event->count}</td><td>{$h($event->connection->getConfig('driver') . '/' . $event->connection->getConfig('name'))}</td></tr>";
|
||||
}
|
||||
|
||||
return empty($this->events) ? '' :
|
||||
'<style> #tracy-debug td.tracy-DibiProfiler-sql { background: white !important }
|
||||
#tracy-debug .tracy-DibiProfiler-source { color: #999 !important }
|
||||
#tracy-debug tracy-DibiProfiler tr table { margin: 8px 0; max-height: 150px; overflow:auto } </style>
|
||||
<h1>Queries: ' . count($this->events) . ($totalTime === NULL ? '' : sprintf(', time: %0.3f ms', $totalTime * 1000)) . '</h1>
|
||||
<div class="tracy-inner tracy-DibiProfiler">
|
||||
<table>
|
||||
<tr><th>Time ms</th><th>SQL Statement</th><th>Rows</th><th>Connection</th></tr>' . $s . '
|
||||
</table>
|
||||
</div>';
|
||||
}
|
||||
|
||||
}
|
624
dibi/dibi.php
624
dibi/dibi.php
@@ -4,6 +4,9 @@
|
||||
* dibi - smart database abstraction layer (http://dibiphp.com)
|
||||
*
|
||||
* Copyright (c) 2005, 2012 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
@@ -14,9 +17,11 @@ if (version_compare(PHP_VERSION, '5.2.0', '<')) {
|
||||
throw new Exception('dibi needs PHP 5.2.0 or newer.');
|
||||
}
|
||||
|
||||
@set_magic_quotes_runtime(FALSE); // intentionally @
|
||||
|
||||
|
||||
|
||||
require_once dirname(__FILE__) . '/libs/interfaces.php';
|
||||
require_once dirname(__FILE__) . '/libs/Dibi.php';
|
||||
require_once dirname(__FILE__) . '/libs/DibiDateTime.php';
|
||||
require_once dirname(__FILE__) . '/libs/DibiObject.php';
|
||||
require_once dirname(__FILE__) . '/libs/DibiLiteral.php';
|
||||
@@ -33,7 +38,620 @@ require_once dirname(__FILE__) . '/libs/DibiDatabaseInfo.php';
|
||||
require_once dirname(__FILE__) . '/libs/DibiEvent.php';
|
||||
require_once dirname(__FILE__) . '/libs/DibiFileLogger.php';
|
||||
require_once dirname(__FILE__) . '/libs/DibiFirePhpLogger.php';
|
||||
|
||||
if (interface_exists('Nette\Diagnostics\IBarPanel') || interface_exists('IBarPanel')) {
|
||||
require_once dirname(__FILE__) . '/bridges/Nette-2.1/DibiNettePanel.php';
|
||||
require_once dirname(__FILE__) . '/Nette/DibiNettePanel.php';
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Interface for database drivers.
|
||||
*
|
||||
* This class is static container class for creating DB objects and
|
||||
* store connections info.
|
||||
*
|
||||
* @author David Grudl
|
||||
* @package dibi
|
||||
*/
|
||||
class dibi
|
||||
{
|
||||
/** column type */
|
||||
const TEXT = 's', // as 'string'
|
||||
BINARY = 'bin',
|
||||
BOOL = 'b',
|
||||
INTEGER = 'i',
|
||||
FLOAT = 'f',
|
||||
DATE = 'd',
|
||||
DATETIME = 't',
|
||||
TIME = 't';
|
||||
|
||||
const IDENTIFIER = 'n';
|
||||
|
||||
/** @deprecated */
|
||||
const FIELD_TEXT = dibi::TEXT,
|
||||
FIELD_BINARY = dibi::BINARY,
|
||||
FIELD_BOOL = dibi::BOOL,
|
||||
FIELD_INTEGER = dibi::INTEGER,
|
||||
FIELD_FLOAT = dibi::FLOAT,
|
||||
FIELD_DATE = dibi::DATE,
|
||||
FIELD_DATETIME = dibi::DATETIME,
|
||||
FIELD_TIME = dibi::TIME;
|
||||
|
||||
/** version */
|
||||
const VERSION = '2.0.2',
|
||||
REVISION = '$WCREV$ released on $WCDATE$';
|
||||
|
||||
/** sorting order */
|
||||
const ASC = 'ASC',
|
||||
DESC = 'DESC';
|
||||
|
||||
/** @var DibiConnection[] Connection registry storage for DibiConnection objects */
|
||||
private static $registry = array();
|
||||
|
||||
/** @var DibiConnection Current connection */
|
||||
private static $connection;
|
||||
|
||||
/** @var array @see addHandler */
|
||||
private static $handlers = array();
|
||||
|
||||
/** @var string Last SQL command @see dibi::query() */
|
||||
public static $sql;
|
||||
|
||||
/** @var int Elapsed time for last query */
|
||||
public static $elapsedTime;
|
||||
|
||||
/** @var int Elapsed time for all queries */
|
||||
public static $totalTime;
|
||||
|
||||
/** @var int Number or queries */
|
||||
public static $numOfQueries = 0;
|
||||
|
||||
/** @var string Default dibi driver */
|
||||
public static $defaultDriver = 'mysql';
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Static class - cannot be instantiated.
|
||||
*/
|
||||
final public function __construct()
|
||||
{
|
||||
throw new LogicException("Cannot instantiate static class " . get_class($this));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* connections handling ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new DibiConnection object and connects it to specified database.
|
||||
* @param mixed connection parameters
|
||||
* @param string connection name
|
||||
* @return DibiConnection
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function connect($config = array(), $name = 0)
|
||||
{
|
||||
return self::$connection = self::$registry[$name] = new DibiConnection($config, $name);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Disconnects from database (doesn't destroy DibiConnection object).
|
||||
* @return void
|
||||
*/
|
||||
public static function disconnect()
|
||||
{
|
||||
self::getConnection()->disconnect();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns TRUE when connection was established.
|
||||
* @return bool
|
||||
*/
|
||||
public static function isConnected()
|
||||
{
|
||||
return (self::$connection !== NULL) && self::$connection->isConnected();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Retrieve active connection.
|
||||
* @param string connection registy name
|
||||
* @return DibiConnection
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function getConnection($name = NULL)
|
||||
{
|
||||
if ($name === NULL) {
|
||||
if (self::$connection === NULL) {
|
||||
throw new DibiException('Dibi is not connected to database.');
|
||||
}
|
||||
|
||||
return self::$connection;
|
||||
}
|
||||
|
||||
if (!isset(self::$registry[$name])) {
|
||||
throw new DibiException("There is no connection named '$name'.");
|
||||
}
|
||||
|
||||
return self::$registry[$name];
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Sets connection.
|
||||
* @param DibiConnection
|
||||
* @return DibiConnection
|
||||
*/
|
||||
public static function setConnection(DibiConnection $connection)
|
||||
{
|
||||
return self::$connection = $connection;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Change active connection.
|
||||
* @param string connection registy name
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function activate($name)
|
||||
{
|
||||
self::$connection = self::getConnection($name);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* monostate for active connection ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Generates and executes SQL query - Monostate for DibiConnection::query().
|
||||
* @param array|mixed one or more arguments
|
||||
* @return DibiResult|int result set object (if any)
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function query($args)
|
||||
{
|
||||
$args = func_get_args();
|
||||
return self::getConnection()->query($args);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes the SQL query - Monostate for DibiConnection::nativeQuery().
|
||||
* @param string SQL statement.
|
||||
* @return DibiResult|int result set object (if any)
|
||||
*/
|
||||
public static function nativeQuery($sql)
|
||||
{
|
||||
return self::getConnection()->nativeQuery($sql);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Generates and prints SQL query - Monostate for DibiConnection::test().
|
||||
* @param array|mixed one or more arguments
|
||||
* @return bool
|
||||
*/
|
||||
public static function test($args)
|
||||
{
|
||||
$args = func_get_args();
|
||||
return self::getConnection()->test($args);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Generates and returns SQL query as DibiDataSource - Monostate for DibiConnection::test().
|
||||
* @param array|mixed one or more arguments
|
||||
* @return DibiDataSource
|
||||
*/
|
||||
public static function dataSource($args)
|
||||
{
|
||||
$args = func_get_args();
|
||||
return self::getConnection()->dataSource($args);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes SQL query and fetch result - Monostate for DibiConnection::query() & fetch().
|
||||
* @param array|mixed one or more arguments
|
||||
* @return DibiRow
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function fetch($args)
|
||||
{
|
||||
$args = func_get_args();
|
||||
return self::getConnection()->query($args)->fetch();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes SQL query and fetch results - Monostate for DibiConnection::query() & fetchAll().
|
||||
* @param array|mixed one or more arguments
|
||||
* @return array of DibiRow
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function fetchAll($args)
|
||||
{
|
||||
$args = func_get_args();
|
||||
return self::getConnection()->query($args)->fetchAll();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes SQL query and fetch first column - Monostate for DibiConnection::query() & fetchSingle().
|
||||
* @param array|mixed one or more arguments
|
||||
* @return string
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function fetchSingle($args)
|
||||
{
|
||||
$args = func_get_args();
|
||||
return self::getConnection()->query($args)->fetchSingle();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes SQL query and fetch pairs - Monostate for DibiConnection::query() & fetchPairs().
|
||||
* @param array|mixed one or more arguments
|
||||
* @return string
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function fetchPairs($args)
|
||||
{
|
||||
$args = func_get_args();
|
||||
return self::getConnection()->query($args)->fetchPairs();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets the number of affected rows.
|
||||
* Monostate for DibiConnection::getAffectedRows()
|
||||
* @return int number of rows
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function getAffectedRows()
|
||||
{
|
||||
return self::getConnection()->getAffectedRows();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets the number of affected rows. Alias for getAffectedRows().
|
||||
* @return int number of rows
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function affectedRows()
|
||||
{
|
||||
return self::getConnection()->getAffectedRows();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
|
||||
* Monostate for DibiConnection::getInsertId()
|
||||
* @param string optional sequence name
|
||||
* @return int
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function getInsertId($sequence=NULL)
|
||||
{
|
||||
return self::getConnection()->getInsertId($sequence);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves the ID generated for an AUTO_INCREMENT column. Alias for getInsertId().
|
||||
* @param string optional sequence name
|
||||
* @return int
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function insertId($sequence=NULL)
|
||||
{
|
||||
return self::getConnection()->getInsertId($sequence);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Begins a transaction - Monostate for DibiConnection::begin().
|
||||
* @param string optional savepoint name
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function begin($savepoint = NULL)
|
||||
{
|
||||
self::getConnection()->begin($savepoint);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Commits statements in a transaction - Monostate for DibiConnection::commit($savepoint = NULL).
|
||||
* @param string optional savepoint name
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function commit($savepoint = NULL)
|
||||
{
|
||||
self::getConnection()->commit($savepoint);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Rollback changes in a transaction - Monostate for DibiConnection::rollback().
|
||||
* @param string optional savepoint name
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function rollback($savepoint = NULL)
|
||||
{
|
||||
self::getConnection()->rollback($savepoint);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets a information about the current database - Monostate for DibiConnection::getDatabaseInfo().
|
||||
* @return DibiDatabaseInfo
|
||||
*/
|
||||
public static function getDatabaseInfo()
|
||||
{
|
||||
return self::getConnection()->getDatabaseInfo();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Import SQL dump from file - extreme fast!
|
||||
* @param string filename
|
||||
* @return int count of sql commands
|
||||
*/
|
||||
public static function loadFile($file)
|
||||
{
|
||||
return self::getConnection()->loadFile($file);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Replacement for majority of dibi::methods() in future.
|
||||
*/
|
||||
public static function __callStatic($name, $args)
|
||||
{
|
||||
//if ($name = 'select', 'update', ...') {
|
||||
// return self::command()->$name($args);
|
||||
//}
|
||||
return call_user_func_array(array(self::getConnection(), $name), $args);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* fluent SQL builders ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return DibiFluent
|
||||
*/
|
||||
public static function command()
|
||||
{
|
||||
return self::getConnection()->command();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param string column name
|
||||
* @return DibiFluent
|
||||
*/
|
||||
public static function select($args)
|
||||
{
|
||||
$args = func_get_args();
|
||||
return call_user_func_array(array(self::getConnection(), 'select'), $args);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param string table
|
||||
* @param array
|
||||
* @return DibiFluent
|
||||
*/
|
||||
public static function update($table, $args)
|
||||
{
|
||||
return self::getConnection()->update($table, $args);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param string table
|
||||
* @param array
|
||||
* @return DibiFluent
|
||||
*/
|
||||
public static function insert($table, $args)
|
||||
{
|
||||
return self::getConnection()->insert($table, $args);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param string table
|
||||
* @return DibiFluent
|
||||
*/
|
||||
public static function delete($table)
|
||||
{
|
||||
return self::getConnection()->delete($table);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* data types ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return DibiDateTime
|
||||
*/
|
||||
public static function datetime($time = NULL)
|
||||
{
|
||||
trigger_error(__METHOD__ . '() is deprecated; create DibiDateTime object instead.', E_USER_WARNING);
|
||||
return new DibiDateTime($time);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
public static function date($date = NULL)
|
||||
{
|
||||
trigger_error(__METHOD__ . '() is deprecated; create DibiDateTime object instead.', E_USER_WARNING);
|
||||
return new DibiDateTime($date);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* substitutions ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns substitution hashmap - Monostate for DibiConnection::getSubstitutes().
|
||||
* @return DibiHashMap
|
||||
*/
|
||||
public static function getSubstitutes()
|
||||
{
|
||||
return self::getConnection()->getSubstitutes();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/** @deprecated */
|
||||
public static function addSubst($expr, $subst)
|
||||
{
|
||||
trigger_error(__METHOD__ . '() is deprecated; use dibi::getSubstitutes()->expr = val; instead.', E_USER_WARNING);
|
||||
self::getSubstitutes()->$expr = $subst;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/** @deprecated */
|
||||
public static function removeSubst($expr)
|
||||
{
|
||||
trigger_error(__METHOD__ . '() is deprecated; use unset(dibi::getSubstitutes()->expr) instead.', E_USER_WARNING);
|
||||
$substitutes = self::getSubstitutes();
|
||||
if ($expr === TRUE) {
|
||||
foreach ($substitutes as $expr => $foo) {
|
||||
unset($substitutes->$expr);
|
||||
}
|
||||
} else {
|
||||
unset($substitutes->$expr);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/** @deprecated */
|
||||
public static function setSubstFallback($callback)
|
||||
{
|
||||
trigger_error(__METHOD__ . '() is deprecated; use dibi::getSubstitutes()->setCallback() instead.', E_USER_WARNING);
|
||||
self::getSubstitutes()->setCallback($callback);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* misc tools ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Prints out a syntax highlighted version of the SQL command or DibiResult.
|
||||
* @param string|DibiResult
|
||||
* @param bool return output instead of printing it?
|
||||
* @return string
|
||||
*/
|
||||
public static function dump($sql = NULL, $return = FALSE)
|
||||
{
|
||||
ob_start();
|
||||
if ($sql instanceof DibiResult) {
|
||||
$sql->dump();
|
||||
|
||||
} else {
|
||||
if ($sql === NULL) $sql = self::$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|SET|VALUES|LEFT\s+JOIN|INNER\s+JOIN|TRUNCATE';
|
||||
static $keywords2 = 'ALL|DISTINCT|DISTINCTROW|IGNORE|AS|USING|ON|AND|OR|IN|IS|NOT|NULL|LIKE|RLIKE|REGEXP|TRUE|FALSE';
|
||||
|
||||
// insert new lines
|
||||
$sql = " $sql ";
|
||||
$sql = preg_replace("#(?<=[\\s,(])($keywords1)(?=[\\s,)])#i", "\n\$1", $sql);
|
||||
|
||||
// reduce spaces
|
||||
$sql = preg_replace('#[ \t]{2,}#', " ", $sql);
|
||||
|
||||
$sql = wordwrap($sql, 100);
|
||||
$sql = preg_replace("#([ \t]*\r?\n){2,}#", "\n", $sql);
|
||||
|
||||
if (PHP_SAPI === 'cli') {
|
||||
echo trim($sql) . "\n\n";
|
||||
} else {
|
||||
// syntax highlight
|
||||
$sql = htmlSpecialChars($sql);
|
||||
$sql = preg_replace_callback("#(/\\*.+?\\*/)|(\\*\\*.+?\\*\\*)|(?<=[\\s,(])($keywords1)(?=[\\s,)])|(?<=[\\s,(=])($keywords2)(?=[\\s,)=])#is", array('dibi', 'highlightCallback'), $sql);
|
||||
echo '<pre class="dump">', trim($sql), "</pre>\n";
|
||||
}
|
||||
}
|
||||
|
||||
if ($return) {
|
||||
return ob_get_clean();
|
||||
} else {
|
||||
ob_end_flush();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
private static function highlightCallback($matches)
|
||||
{
|
||||
if (!empty($matches[1])) // comment
|
||||
return '<em style="color:gray">' . $matches[1] . '</em>';
|
||||
|
||||
if (!empty($matches[2])) // error
|
||||
return '<strong style="color:red">' . $matches[2] . '</strong>';
|
||||
|
||||
if (!empty($matches[3])) // most important keywords
|
||||
return '<strong style="color:blue">' . $matches[3] . '</strong>';
|
||||
|
||||
if (!empty($matches[4])) // other keywords
|
||||
return '<strong style="color:green">' . $matches[4] . '</strong>';
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -1,133 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* The dibi reflector for MSSQL2005 databases.
|
||||
*
|
||||
* @author Daniel Kouba
|
||||
* @package dibi\drivers
|
||||
* @internal
|
||||
*/
|
||||
class DibiMsSql2005Reflector extends DibiObject implements IDibiReflector
|
||||
{
|
||||
/** @var IDibiDriver */
|
||||
private $driver;
|
||||
|
||||
|
||||
public function __construct(IDibiDriver $driver)
|
||||
{
|
||||
$this->driver = $driver;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns list of tables.
|
||||
* @return array
|
||||
*/
|
||||
public function getTables()
|
||||
{
|
||||
$res = $this->driver->query('SELECT TABLE_NAME, TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES');
|
||||
$tables = array();
|
||||
while ($row = $res->fetch(FALSE)) {
|
||||
$tables[] = array(
|
||||
'name' => $row[0],
|
||||
'view' => isset($row[1]) && $row[1] === 'VIEW',
|
||||
);
|
||||
}
|
||||
return $tables;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a table.
|
||||
* @param string
|
||||
* @return array
|
||||
*/
|
||||
public function getColumns($table)
|
||||
{
|
||||
$res = $this->driver->query("
|
||||
SELECT c.name as COLUMN_NAME, c.is_identity AS AUTO_INCREMENT
|
||||
FROM sys.columns c
|
||||
INNER JOIN sys.tables t ON c.object_id = t.object_id
|
||||
WHERE t.name = {$this->driver->escape($table, dibi::TEXT)}
|
||||
");
|
||||
|
||||
$autoIncrements = array();
|
||||
while ($row = $res->fetch(TRUE)) {
|
||||
$autoIncrements[$row['COLUMN_NAME']] = (bool) $row['AUTO_INCREMENT'];
|
||||
}
|
||||
|
||||
$res = $this->driver->query("
|
||||
SELECT C.COLUMN_NAME, C.DATA_TYPE, C.CHARACTER_MAXIMUM_LENGTH , C.COLUMN_DEFAULT , C.NUMERIC_PRECISION, C.NUMERIC_SCALE , C.IS_NULLABLE, Case When Z.CONSTRAINT_NAME Is Null Then 0 Else 1 End As IsPartOfPrimaryKey
|
||||
FROM INFORMATION_SCHEMA.COLUMNS As C
|
||||
Outer Apply (
|
||||
SELECT CCU.CONSTRAINT_NAME
|
||||
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS As TC
|
||||
Join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE As CCU
|
||||
On CCU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME
|
||||
WHERE TC.TABLE_SCHEMA = C.TABLE_SCHEMA
|
||||
And TC.TABLE_NAME = C.TABLE_NAME
|
||||
And TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
|
||||
And CCU.COLUMN_NAME = C.COLUMN_NAME
|
||||
) As Z
|
||||
WHERE C.TABLE_NAME = {$this->driver->escape($table, dibi::TEXT)}
|
||||
");
|
||||
$columns = array();
|
||||
while ($row = $res->fetch(TRUE)) {
|
||||
$columns[] = array(
|
||||
'name' => $row['COLUMN_NAME'],
|
||||
'table' => $table,
|
||||
'nativetype' => strtoupper($row['DATA_TYPE']),
|
||||
'size' => $row['CHARACTER_MAXIMUM_LENGTH'],
|
||||
'unsigned' => TRUE,
|
||||
'nullable' => $row['IS_NULLABLE'] === 'YES',
|
||||
'default' => $row['COLUMN_DEFAULT'],
|
||||
'autoincrement' => $autoIncrements[$row['COLUMN_NAME']],
|
||||
'vendor' => $row,
|
||||
);
|
||||
}
|
||||
return $columns;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all indexes in a table.
|
||||
* @param string
|
||||
* @return array
|
||||
*/
|
||||
public function getIndexes($table)
|
||||
{
|
||||
$keyUsagesRes = $this->driver->query("SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = {$this->driver->escape($table, dibi::TEXT)}");
|
||||
$keyUsages = array();
|
||||
while( $row = $keyUsagesRes->fetch(TRUE) ) {
|
||||
$keyUsages[$row['CONSTRAINT_NAME']][(int) $row['ORDINAL_POSITION'] - 1] = $row['COLUMN_NAME'];
|
||||
}
|
||||
|
||||
$res = $this->driver->query("SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = {$this->driver->escape($table, dibi::TEXT)}");
|
||||
$indexes = array();
|
||||
while ($row = $res->fetch(TRUE)) {
|
||||
$indexes[$row['CONSTRAINT_NAME']]['name'] = $row['CONSTRAINT_NAME'];
|
||||
$indexes[$row['CONSTRAINT_NAME']]['unique'] = $row['CONSTRAINT_TYPE'] === 'UNIQUE';
|
||||
$indexes[$row['CONSTRAINT_NAME']]['primary'] = $row['CONSTRAINT_TYPE'] === 'PRIMARY KEY';
|
||||
$indexes[$row['CONSTRAINT_NAME']]['columns'] = isset($keyUsages[$row['CONSTRAINT_NAME']]) ? $keyUsages[$row['CONSTRAINT_NAME']] : array();
|
||||
}
|
||||
return array_values($indexes);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all foreign keys in a table.
|
||||
* @param string
|
||||
* @return array
|
||||
*/
|
||||
public function getForeignKeys($table)
|
||||
{
|
||||
throw new DibiNotImplementedException;
|
||||
}
|
||||
|
||||
}
|
@@ -2,7 +2,11 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
@@ -52,12 +56,13 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Connects to a database.
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
public function connect(array & $config)
|
||||
public function connect(array &$config)
|
||||
{
|
||||
DibiConnection::alias($config, 'database', 'db');
|
||||
|
||||
@@ -66,13 +71,11 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
|
||||
} else {
|
||||
// default values
|
||||
$config += array(
|
||||
'username' => ini_get('ibase.default_password'),
|
||||
'password' => ini_get('ibase.default_user'),
|
||||
'database' => ini_get('ibase.default_db'),
|
||||
'charset' => ini_get('ibase.default_charset'),
|
||||
'buffers' => 0,
|
||||
);
|
||||
if (!isset($config['username'])) $config['username'] = ini_get('ibase.default_password');
|
||||
if (!isset($config['password'])) $config['password'] = ini_get('ibase.default_user');
|
||||
if (!isset($config['database'])) $config['database'] = ini_get('ibase.default_db');
|
||||
if (!isset($config['charset'])) $config['charset'] = ini_get('ibase.default_charset');
|
||||
if (!isset($config['buffers'])) $config['buffers'] = 0;
|
||||
|
||||
DibiDriverException::tryError();
|
||||
if (empty($config['persistent'])) {
|
||||
@@ -92,6 +95,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Disconnects from a database.
|
||||
* @return void
|
||||
@@ -102,6 +106,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes the SQL query.
|
||||
* @param string SQL statement.
|
||||
@@ -133,6 +138,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
|
||||
* @return int|FALSE number of rows or FALSE on error
|
||||
@@ -143,6 +149,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
|
||||
* @param string generator name
|
||||
@@ -154,6 +161,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Begins a transaction (if supported).
|
||||
* @param string optional savepoint name
|
||||
@@ -170,6 +178,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Commits statements in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -190,6 +199,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Rollback changes in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -210,6 +220,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Is in transaction?
|
||||
* @return bool
|
||||
@@ -220,6 +231,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection resource.
|
||||
* @return resource
|
||||
@@ -230,6 +242,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection reflector.
|
||||
* @return IDibiReflector
|
||||
@@ -240,6 +253,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Result set driver factory.
|
||||
* @param resource
|
||||
@@ -253,9 +267,11 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* SQL ********************/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes data for use in a SQL statement.
|
||||
* @param mixed value
|
||||
@@ -266,29 +282,29 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
public function escape($value, $type)
|
||||
{
|
||||
switch ($type) {
|
||||
case dibi::TEXT:
|
||||
case dibi::BINARY:
|
||||
return "'" . str_replace("'", "''", $value) . "'";
|
||||
case dibi::TEXT:
|
||||
case dibi::BINARY:
|
||||
return "'" . str_replace("'", "''", $value) . "'";
|
||||
|
||||
case dibi::IDENTIFIER:
|
||||
return $value;
|
||||
case dibi::IDENTIFIER:
|
||||
return $value;
|
||||
|
||||
case dibi::BOOL:
|
||||
return $value ? 1 : 0;
|
||||
case dibi::BOOL:
|
||||
return $value ? 1 : 0;
|
||||
|
||||
case dibi::DATE:
|
||||
case dibi::DATETIME:
|
||||
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
|
||||
$value = new DibiDateTime($value);
|
||||
}
|
||||
return $value->format($type === dibi::DATETIME ? "'Y-m-d H:i:s'" : "'Y-m-d'");
|
||||
case dibi::DATE:
|
||||
return $value instanceof DateTime ? $value->format("'Y-m-d'") : date("'Y-m-d'", $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
case dibi::DATETIME:
|
||||
return $value instanceof DateTime ? $value->format("'Y-m-d H:i:s'") : date("'Y-m-d H:i:s'", $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes string for use in a LIKE statement.
|
||||
* @param string
|
||||
@@ -301,6 +317,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Decodes data from result set.
|
||||
* @param string value
|
||||
@@ -317,22 +334,28 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Injects LIMIT/OFFSET to the SQL query.
|
||||
* @param string &$sql The SQL query that will be modified.
|
||||
* @param int $limit
|
||||
* @param int $offset
|
||||
* @return void
|
||||
*/
|
||||
public function applyLimit(& $sql, $limit, $offset)
|
||||
public function applyLimit(&$sql, $limit, $offset)
|
||||
{
|
||||
if ($limit >= 0 && $offset > 0) {
|
||||
// see http://scott.yang.id.au/2004/01/limit-in-select-statements-in-firebird/
|
||||
$sql = 'SELECT FIRST ' . (int) $limit . ($offset > 0 ? ' SKIP ' . (int) $offset : '') . ' * FROM (' . $sql . ')';
|
||||
}
|
||||
if ($limit < 0 && $offset < 1) return;
|
||||
|
||||
// see http://scott.yang.id.au/2004/01/limit-in-select-statements-in-firebird/
|
||||
$sql = 'SELECT FIRST ' . (int) $limit . ($offset > 0 ? ' SKIP ' . (int) $offset : '') . ' * FROM (' . $sql . ')';
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* result set ********************/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Automatically frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -343,16 +366,18 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the number of rows in a result set.
|
||||
* @return int
|
||||
*/
|
||||
public function getRowCount()
|
||||
{
|
||||
throw new DibiNotSupportedException("Firebird/Interbase do not support returning number of rows in result set.");
|
||||
return ibase_num_fields($this->resultSet);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches the row at current position and moves the internal cursor to the next position.
|
||||
* @param bool TRUE for associative array, FALSE for numeric
|
||||
@@ -365,7 +390,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
|
||||
if (DibiDriverException::catchError($msg)) {
|
||||
if (ibase_errcode() == self::ERROR_EXCEPTION_THROWN) {
|
||||
preg_match('/exception (\d+) (\w+) (.*)/is', ibase_errmsg(), $match);
|
||||
preg_match('/exception (\d+) (\w+) (.*)/i', ibase_errmsg(), $match);
|
||||
throw new DibiProcedureException($match[3], $match[1], $match[2], dibi::$sql);
|
||||
|
||||
} else {
|
||||
@@ -377,6 +402,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Moves cursor position without fetching row.
|
||||
* @param int the 0-based cursor pos to seek to
|
||||
@@ -389,6 +415,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -400,6 +427,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the result set resource.
|
||||
* @return mysqli_result
|
||||
@@ -411,6 +439,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a result set.
|
||||
* @return array
|
||||
@@ -432,9 +461,11 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* IDibiReflector ********************/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns list of tables.
|
||||
* @return array
|
||||
@@ -458,6 +489,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a table.
|
||||
* @param string
|
||||
@@ -513,6 +545,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all indexes in a table (the constraints are included).
|
||||
* @param string
|
||||
@@ -547,6 +580,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all foreign keys in a table.
|
||||
* @param string
|
||||
@@ -577,6 +611,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns list of indices in given table (the constraints are not listed).
|
||||
* @param string
|
||||
@@ -599,6 +634,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns list of constraints in given table.
|
||||
* @param string
|
||||
@@ -623,6 +659,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all triggers in a table or database.
|
||||
* (Only if user has permissions on ALTER TABLE, INSERT/UPDATE/DELETE record in table)
|
||||
@@ -672,6 +709,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns list of triggers for given table.
|
||||
* (Only if user has permissions on ALTER TABLE, INSERT/UPDATE/DELETE record in table)
|
||||
@@ -694,6 +732,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata from stored procedures and their input and output parameters.
|
||||
* @param string
|
||||
@@ -747,6 +786,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns list of stored procedures.
|
||||
* @return array
|
||||
@@ -765,6 +805,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns list of generators.
|
||||
* @return array
|
||||
@@ -784,6 +825,7 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns list of user defined functions (UDF).
|
||||
* @return array
|
||||
@@ -805,6 +847,8 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Database procedure exception.
|
||||
*
|
||||
@@ -831,6 +875,7 @@ class DibiProcedureException extends DibiException
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets the exception severity.
|
||||
* @return string
|
@@ -2,10 +2,14 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
require_once dirname(__FILE__) . '/DibiMsSqlReflector.php';
|
||||
require_once dirname(__FILE__) . '/mssql.reflector.php';
|
||||
|
||||
/**
|
||||
* The dibi driver for MS SQL database.
|
||||
@@ -34,6 +38,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
private $autoFree = TRUE;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @throws DibiNotSupportedException
|
||||
*/
|
||||
@@ -45,12 +50,13 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Connects to a database.
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
public function connect(array & $config)
|
||||
public function connect(array &$config)
|
||||
{
|
||||
if (isset($config['resource'])) {
|
||||
$this->connection = $config['resource'];
|
||||
@@ -70,6 +76,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Disconnects from a database.
|
||||
* @return void
|
||||
@@ -80,6 +87,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes the SQL query.
|
||||
* @param string SQL statement.
|
||||
@@ -99,6 +107,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
|
||||
* @return int|FALSE number of rows or FALSE on error
|
||||
@@ -109,6 +118,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
|
||||
* @return int|FALSE int on success or FALSE on failure
|
||||
@@ -124,6 +134,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Begins a transaction (if supported).
|
||||
* @param string optional savepoint name
|
||||
@@ -136,6 +147,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Commits statements in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -148,6 +160,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Rollback changes in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -160,6 +173,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection resource.
|
||||
* @return mixed
|
||||
@@ -170,6 +184,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection reflector.
|
||||
* @return IDibiReflector
|
||||
@@ -180,6 +195,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Result set driver factory.
|
||||
* @param resource
|
||||
@@ -193,9 +209,11 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* SQL ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes data for use in a SQL statement.
|
||||
* @param mixed value
|
||||
@@ -206,30 +224,30 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
public function escape($value, $type)
|
||||
{
|
||||
switch ($type) {
|
||||
case dibi::TEXT:
|
||||
case dibi::BINARY:
|
||||
return "'" . str_replace("'", "''", $value) . "'";
|
||||
case dibi::TEXT:
|
||||
case dibi::BINARY:
|
||||
return "'" . str_replace("'", "''", $value) . "'";
|
||||
|
||||
case dibi::IDENTIFIER:
|
||||
// @see http://msdn.microsoft.com/en-us/library/ms176027.aspx
|
||||
return '[' . str_replace(array('[', ']'), array('[[', ']]'), $value) . ']';
|
||||
case dibi::IDENTIFIER:
|
||||
// @see http://msdn.microsoft.com/en-us/library/ms176027.aspx
|
||||
return '[' . str_replace(array('[', ']'), array('[[', ']]'), $value) . ']';
|
||||
|
||||
case dibi::BOOL:
|
||||
return $value ? 1 : 0;
|
||||
case dibi::BOOL:
|
||||
return $value ? 1 : 0;
|
||||
|
||||
case dibi::DATE:
|
||||
case dibi::DATETIME:
|
||||
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
|
||||
$value = new DibiDateTime($value);
|
||||
}
|
||||
return $value->format($type === dibi::DATETIME ? "'Y-m-d H:i:s'" : "'Y-m-d'");
|
||||
case dibi::DATE:
|
||||
return $value instanceof DateTime ? $value->format("'Y-m-d'") : date("'Y-m-d'", $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
case dibi::DATETIME:
|
||||
return $value instanceof DateTime ? $value->format("'Y-m-d H:i:s'") : date("'Y-m-d H:i:s'", $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes string for use in a LIKE statement.
|
||||
* @param string
|
||||
@@ -243,6 +261,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Decodes data from result set.
|
||||
* @param string value
|
||||
@@ -259,11 +278,15 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Injects LIMIT/OFFSET to the SQL query.
|
||||
* @param string &$sql The SQL query that will be modified.
|
||||
* @param int $limit
|
||||
* @param int $offset
|
||||
* @return void
|
||||
*/
|
||||
public function applyLimit(& $sql, $limit, $offset)
|
||||
public function applyLimit(&$sql, $limit, $offset)
|
||||
{
|
||||
// offset support is missing
|
||||
if ($limit >= 0) {
|
||||
@@ -276,9 +299,11 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* result set ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Automatically frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -289,6 +314,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the number of rows in a result set.
|
||||
* @return int
|
||||
@@ -299,6 +325,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches the row at current position and moves the internal cursor to the next position.
|
||||
* @param bool TRUE for associative array, FALSE for numeric
|
||||
@@ -310,6 +337,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Moves cursor position without fetching row.
|
||||
* @param int the 0-based cursor pos to seek to
|
||||
@@ -321,6 +349,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -332,6 +361,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a result set.
|
||||
* @return array
|
||||
@@ -353,6 +383,7 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the result set resource.
|
||||
* @return mixed
|
441
dibi/drivers/DibiMsSqlReflector.php → dibi/drivers/mssql.reflector.php
Normal file → Executable file
441
dibi/drivers/DibiMsSqlReflector.php → dibi/drivers/mssql.reflector.php
Normal file → Executable file
@@ -1,216 +1,225 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005, 2010 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* @package dibi\drivers
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* The dibi reflector for MsSQL databases.
|
||||
*
|
||||
* @author Steven Bredenberg
|
||||
* @package dibi\drivers
|
||||
* @internal
|
||||
*/
|
||||
class DibiMsSqlReflector extends DibiObject implements IDibiReflector
|
||||
{
|
||||
/** @var IDibiDriver */
|
||||
private $driver;
|
||||
|
||||
|
||||
public function __construct(IDibiDriver $driver)
|
||||
{
|
||||
$this->driver = $driver;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns list of tables.
|
||||
* @return array
|
||||
*/
|
||||
public function getTables()
|
||||
{
|
||||
$res = $this->driver->query("
|
||||
SELECT TABLE_NAME, TABLE_TYPE
|
||||
FROM INFORMATION_SCHEMA.TABLES
|
||||
");
|
||||
$tables = array();
|
||||
while ($row = $res->fetch(FALSE)) {
|
||||
$tables[] = array(
|
||||
'name' => $row[0],
|
||||
'view' => isset($row[1]) && $row[1] === 'VIEW',
|
||||
);
|
||||
}
|
||||
return $tables;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns count of rows in a table
|
||||
* @param string
|
||||
* @return integer
|
||||
*/
|
||||
public function getTableCount($table, $fallback=true)
|
||||
{
|
||||
if (empty($table)) {
|
||||
return false;
|
||||
}
|
||||
$result = $this->driver->query("
|
||||
SELECT MAX(rowcnt)
|
||||
FROM sys.sysindexes
|
||||
WHERE id=OBJECT_ID({$this->driver->escape($table, dibi::IDENTIFIER)})
|
||||
");
|
||||
$row = $result->fetch(FALSE);
|
||||
|
||||
if (!is_array($row) || count($row) < 1) {
|
||||
if ($fallback) {
|
||||
$row = $this->driver->query("SELECT COUNT(*) FROM {$this->driver->escape($table, dibi::IDENTIFIER)}")->fetch(FALSE);
|
||||
$count = intval($row[0]);
|
||||
} else {
|
||||
$count = false;
|
||||
}
|
||||
} else {
|
||||
$count = intval($row[0]);
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a table.
|
||||
* @param string
|
||||
* @return array
|
||||
*/
|
||||
public function getColumns($table)
|
||||
{
|
||||
$res = $this->driver->query("
|
||||
SELECT * FROM
|
||||
INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_NAME = {$this->driver->escape($table, dibi::TEXT)}
|
||||
ORDER BY TABLE_NAME, ORDINAL_POSITION
|
||||
");
|
||||
$columns = array();
|
||||
while ($row = $res->fetch(TRUE)) {
|
||||
$size = false;
|
||||
$type = strtoupper($row['DATA_TYPE']);
|
||||
|
||||
$size_cols = array(
|
||||
'DATETIME'=>'DATETIME_PRECISION',
|
||||
'DECIMAL'=>'NUMERIC_PRECISION',
|
||||
'CHAR'=>'CHARACTER_MAXIMUM_LENGTH',
|
||||
'NCHAR'=>'CHARACTER_OCTET_LENGTH',
|
||||
'NVARCHAR'=>'CHARACTER_OCTET_LENGTH',
|
||||
'VARCHAR'=>'CHARACTER_OCTET_LENGTH'
|
||||
);
|
||||
|
||||
if (isset($size_cols[$type])) {
|
||||
if ($size_cols[$type]) {
|
||||
$size = $row[$size_cols[$type]];
|
||||
}
|
||||
}
|
||||
|
||||
$columns[] = array(
|
||||
'name' => $row['COLUMN_NAME'],
|
||||
'table' => $table,
|
||||
'nativetype' => $type,
|
||||
'size' => $size,
|
||||
'unsigned' => NULL,
|
||||
'nullable' => $row['IS_NULLABLE'] === 'YES',
|
||||
'default' => $row['COLUMN_DEFAULT'],
|
||||
'autoincrement' => false,
|
||||
'vendor' => $row,
|
||||
);
|
||||
}
|
||||
|
||||
return $columns;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all indexes in a table.
|
||||
* @param string
|
||||
* @return array
|
||||
*/
|
||||
public function getIndexes($table)
|
||||
{
|
||||
$res = $this->driver->query(
|
||||
"SELECT ind.name index_name, ind.index_id, ic.index_column_id,
|
||||
col.name column_name, ind.is_unique, ind.is_primary_key
|
||||
FROM sys.indexes ind
|
||||
INNER JOIN sys.index_columns ic ON
|
||||
(ind.object_id = ic.object_id AND ind.index_id = ic.index_id)
|
||||
INNER JOIN sys.columns col ON
|
||||
(ic.object_id = col.object_id and ic.column_id = col.column_id)
|
||||
INNER JOIN sys.tables t ON
|
||||
(ind.object_id = t.object_id)
|
||||
WHERE t.name = {$this->driver->escape($table, dibi::TEXT)}
|
||||
AND t.is_ms_shipped = 0
|
||||
ORDER BY
|
||||
t.name, ind.name, ind.index_id, ic.index_column_id
|
||||
");
|
||||
|
||||
$indexes = array();
|
||||
while ($row = $res->fetch(TRUE)) {
|
||||
$index_name = $row['index_name'];
|
||||
|
||||
if (!isset($indexes[$index_name])) {
|
||||
$indexes[$index_name] = array();
|
||||
$indexes[$index_name]['name'] = $index_name;
|
||||
$indexes[$index_name]['unique'] = (bool)$row['is_unique'];
|
||||
$indexes[$index_name]['primary'] = (bool)$row['is_primary_key'];
|
||||
$indexes[$index_name]['columns'] = array();
|
||||
}
|
||||
$indexes[$index_name]['columns'][] = $row['column_name'];
|
||||
}
|
||||
|
||||
return array_values($indexes);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all foreign keys in a table.
|
||||
* @param string
|
||||
* @return array
|
||||
*/
|
||||
public function getForeignKeys($table)
|
||||
{
|
||||
$res = $this->driver->query("
|
||||
SELECT f.name AS foreign_key,
|
||||
OBJECT_NAME(f.parent_object_id) AS table_name,
|
||||
COL_NAME(fc.parent_object_id,
|
||||
fc.parent_column_id) AS column_name,
|
||||
OBJECT_NAME (f.referenced_object_id) AS reference_table_name,
|
||||
COL_NAME(fc.referenced_object_id,
|
||||
fc.referenced_column_id) AS reference_column_name,
|
||||
fc.*
|
||||
FROM sys.foreign_keys AS f
|
||||
INNER JOIN sys.foreign_key_columns AS fc
|
||||
ON f.OBJECT_ID = fc.constraint_object_id
|
||||
WHERE OBJECT_NAME(f.parent_object_id) = {$this->driver->escape($table, dibi::TEXT)}
|
||||
");
|
||||
|
||||
$keys = array();
|
||||
while ($row = $res->fetch(TRUE)) {
|
||||
$key_name = $row['foreign_key'];
|
||||
|
||||
if (!isset($keys[$key_name])) {
|
||||
$keys[$key_name]['name'] = $row['foreign_key']; // foreign key name
|
||||
$keys[$key_name]['local'] = array($row['column_name']); // local columns
|
||||
$keys[$key_name]['table'] = $row['reference_table_name']; // referenced table
|
||||
$keys[$key_name]['foreign'] = array($row['reference_column_name']); // referenced columns
|
||||
$keys[$key_name]['onDelete'] = false;
|
||||
$keys[$key_name]['onUpdate'] = false;
|
||||
} else {
|
||||
$keys[$key_name]['local'][] = $row['column_name']; // local columns
|
||||
$keys[$key_name]['foreign'][] = $row['reference_column_name']; // referenced columns
|
||||
}
|
||||
}
|
||||
return array_values($keys);
|
||||
}
|
||||
|
||||
}
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005, 2010 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*
|
||||
* @package dibi\drivers
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* The dibi reflector for MsSQL databases.
|
||||
*
|
||||
* @author Steven Bredenberg
|
||||
* @package dibi\drivers
|
||||
* @internal
|
||||
*/
|
||||
class DibiMsSqlReflector extends DibiObject implements IDibiReflector
|
||||
{
|
||||
/** @var IDibiDriver */
|
||||
private $driver;
|
||||
|
||||
|
||||
|
||||
public function __construct(IDibiDriver $driver)
|
||||
{
|
||||
$this->driver = $driver;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns list of tables.
|
||||
* @return array
|
||||
*/
|
||||
public function getTables()
|
||||
{
|
||||
$res = $this->driver->query("
|
||||
SELECT TABLE_NAME, TABLE_TYPE
|
||||
FROM INFORMATION_SCHEMA.TABLES
|
||||
");
|
||||
$tables = array();
|
||||
while ($row = $res->fetch(FALSE)) {
|
||||
$tables[] = array(
|
||||
'name' => $row[0],
|
||||
'view' => isset($row[1]) && $row[1] === 'VIEW',
|
||||
);
|
||||
}
|
||||
return $tables;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns count of rows in a table
|
||||
* @param string
|
||||
* @return integer
|
||||
*/
|
||||
public function getTableCount($table, $fallback=true)
|
||||
{
|
||||
if (empty($table)) {
|
||||
return false;
|
||||
}
|
||||
$result = $this->driver->query("
|
||||
SELECT MAX(rowcnt)
|
||||
FROM sys.sysindexes
|
||||
WHERE id=OBJECT_ID({$this->driver->escape($table, dibi::IDENTIFIER)})
|
||||
");
|
||||
$row = $result->fetch(FALSE);
|
||||
|
||||
if (!is_array($row) || count($row) < 1) {
|
||||
if ($fallback) {
|
||||
$row = $this->driver->query("SELECT COUNT(*) FROM {$this->driver->escape($table, dibi::IDENTIFIER)}")->fetch(FALSE);
|
||||
$count = intval($row[0]);
|
||||
} else {
|
||||
$count = false;
|
||||
}
|
||||
} else {
|
||||
$count = intval($row[0]);
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a table.
|
||||
* @param string
|
||||
* @return array
|
||||
*/
|
||||
public function getColumns($table)
|
||||
{
|
||||
$res = $this->driver->query("
|
||||
SELECT * FROM
|
||||
INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_NAME = {$this->driver->escape($table, dibi::TEXT)}
|
||||
ORDER BY TABLE_NAME, ORDINAL_POSITION
|
||||
");
|
||||
$columns = array();
|
||||
while ($row = $res->fetch(TRUE)) {
|
||||
$size = false;
|
||||
$type = strtoupper($row['DATA_TYPE']);
|
||||
|
||||
$size_cols = array(
|
||||
'DATETIME'=>'DATETIME_PRECISION',
|
||||
'DECIMAL'=>'NUMERIC_PRECISION',
|
||||
'CHAR'=>'CHARACTER_MAXIMUM_LENGTH',
|
||||
'NCHAR'=>'CHARACTER_OCTET_LENGTH',
|
||||
'NVARCHAR'=>'CHARACTER_OCTET_LENGTH',
|
||||
'VARCHAR'=>'CHARACTER_OCTET_LENGTH'
|
||||
);
|
||||
|
||||
if (isset($size_cols[$type])) {
|
||||
if ($size_cols[$type]) {
|
||||
$size = $row[$size_cols[$type]];
|
||||
}
|
||||
}
|
||||
|
||||
$columns[] = array(
|
||||
'name' => $row['COLUMN_NAME'],
|
||||
'table' => $table,
|
||||
'nativetype' => $type,
|
||||
'size' => $size,
|
||||
'unsigned' => NULL,
|
||||
'nullable' => $row['IS_NULLABLE'] === 'YES',
|
||||
'default' => $row['COLUMN_DEFAULT'],
|
||||
'autoincrement' => false,
|
||||
'vendor' => $row,
|
||||
);
|
||||
}
|
||||
|
||||
return $columns;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all indexes in a table.
|
||||
* @param string
|
||||
* @return array
|
||||
*/
|
||||
public function getIndexes($table)
|
||||
{
|
||||
$res = $this->driver->query(
|
||||
"SELECT ind.name index_name, ind.index_id, ic.index_column_id,
|
||||
col.name column_name, ind.is_unique, ind.is_primary_key
|
||||
FROM sys.indexes ind
|
||||
INNER JOIN sys.index_columns ic ON
|
||||
(ind.object_id = ic.object_id AND ind.index_id = ic.index_id)
|
||||
INNER JOIN sys.columns col ON
|
||||
(ic.object_id = col.object_id and ic.column_id = col.column_id)
|
||||
INNER JOIN sys.tables t ON
|
||||
(ind.object_id = t.object_id)
|
||||
WHERE t.name = {$this->driver->escape($table, dibi::TEXT)}
|
||||
AND t.is_ms_shipped = 0
|
||||
ORDER BY
|
||||
t.name, ind.name, ind.index_id, ic.index_column_id
|
||||
");
|
||||
|
||||
$indexes = array();
|
||||
while ($row = $res->fetch(TRUE)) {
|
||||
$index_name = $row['index_name'];
|
||||
|
||||
if (!isset($indexes[$index_name])) {
|
||||
$indexes[$index_name] = array();
|
||||
$indexes[$index_name]['name'] = $index_name;
|
||||
$indexes[$index_name]['unique'] = (bool)$row['is_unique'];
|
||||
$indexes[$index_name]['primary'] = (bool)$row['is_primary_key'];
|
||||
$indexes[$index_name]['columns'] = array();
|
||||
}
|
||||
$indexes[$index_name]['columns'][] = $row['column_name'];
|
||||
}
|
||||
|
||||
return array_values($indexes);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all foreign keys in a table.
|
||||
* @param string
|
||||
* @return array
|
||||
*/
|
||||
public function getForeignKeys($table)
|
||||
{
|
||||
$res = $this->driver->query("
|
||||
SELECT f.name AS foreign_key,
|
||||
OBJECT_NAME(f.parent_object_id) AS table_name,
|
||||
COL_NAME(fc.parent_object_id,
|
||||
fc.parent_column_id) AS column_name,
|
||||
OBJECT_NAME (f.referenced_object_id) AS reference_table_name,
|
||||
COL_NAME(fc.referenced_object_id,
|
||||
fc.referenced_column_id) AS reference_column_name,
|
||||
fc.*
|
||||
FROM sys.foreign_keys AS f
|
||||
INNER JOIN sys.foreign_key_columns AS fc
|
||||
ON f.OBJECT_ID = fc.constraint_object_id
|
||||
WHERE OBJECT_NAME(f.parent_object_id) = {$this->driver->escape($table, dibi::TEXT)}
|
||||
");
|
||||
|
||||
$keys = array();
|
||||
while ($row = $res->fetch(TRUE)) {
|
||||
$key_name = $row['foreign_key'];
|
||||
|
||||
if (!isset($keys[$key_name])) {
|
||||
$keys[$key_name]['name'] = $row['foreign_key']; // foreign key name
|
||||
$keys[$key_name]['local'] = array($row['column_name']); // local columns
|
||||
$keys[$key_name]['table'] = $row['reference_table_name']; // referenced table
|
||||
$keys[$key_name]['foreign'] = array($row['reference_column_name']); // referenced columns
|
||||
$keys[$key_name]['onDelete'] = false;
|
||||
$keys[$key_name]['onUpdate'] = false;
|
||||
} else {
|
||||
$keys[$key_name]['local'][] = $row['column_name']; // local columns
|
||||
$keys[$key_name]['foreign'][] = $row['reference_column_name']; // referenced columns
|
||||
}
|
||||
}
|
||||
return array_values($keys);
|
||||
}
|
||||
|
||||
}
|
@@ -2,13 +2,14 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
require_once dirname(__FILE__) . '/DibiMsSql2005Reflector.php';
|
||||
|
||||
|
||||
/**
|
||||
* The dibi driver for MS SQL Driver 2005 database.
|
||||
*
|
||||
@@ -40,6 +41,7 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
private $affectedRows = FALSE;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @throws DibiNotSupportedException
|
||||
*/
|
||||
@@ -51,12 +53,13 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Connects to a database.
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
public function connect(array & $config)
|
||||
public function connect(array &$config)
|
||||
{
|
||||
DibiConnection::alias($config, 'options|UID', 'username');
|
||||
DibiConnection::alias($config, 'options|PWD', 'password');
|
||||
@@ -67,11 +70,6 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
$this->connection = $config['resource'];
|
||||
|
||||
} else {
|
||||
// Default values
|
||||
if (!isset($config['options']['CharacterSet'])) {
|
||||
$config['options']['CharacterSet'] = 'UTF-8';
|
||||
}
|
||||
|
||||
$this->connection = sqlsrv_connect($config['host'], (array) $config['options']);
|
||||
}
|
||||
|
||||
@@ -82,6 +80,7 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Disconnects from a database.
|
||||
* @return void
|
||||
@@ -92,6 +91,7 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes the SQL query.
|
||||
* @param string SQL statement.
|
||||
@@ -114,6 +114,7 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
|
||||
* @return int|FALSE number of rows or FALSE on error
|
||||
@@ -124,6 +125,7 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
|
||||
* @return int|FALSE int on success or FALSE on failure
|
||||
@@ -139,6 +141,7 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Begins a transaction (if supported).
|
||||
* @param string optional savepoint name
|
||||
@@ -151,6 +154,7 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Commits statements in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -163,6 +167,7 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Rollback changes in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -175,6 +180,7 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection resource.
|
||||
* @return mixed
|
||||
@@ -185,16 +191,18 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection reflector.
|
||||
* @return IDibiReflector
|
||||
*/
|
||||
public function getReflector()
|
||||
{
|
||||
return new DibiMssql2005Reflector($this);
|
||||
throw new DibiNotSupportedException;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Result set driver factory.
|
||||
* @param resource
|
||||
@@ -208,9 +216,11 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* SQL ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes data for use in a SQL statement.
|
||||
* @param mixed value
|
||||
@@ -221,30 +231,30 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
public function escape($value, $type)
|
||||
{
|
||||
switch ($type) {
|
||||
case dibi::TEXT:
|
||||
case dibi::BINARY:
|
||||
return "'" . str_replace("'", "''", $value) . "'";
|
||||
case dibi::TEXT:
|
||||
case dibi::BINARY:
|
||||
return "'" . str_replace("'", "''", $value) . "'";
|
||||
|
||||
case dibi::IDENTIFIER:
|
||||
// @see http://msdn.microsoft.com/en-us/library/ms176027.aspx
|
||||
return '[' . str_replace(']', ']]', $value) . ']';
|
||||
case dibi::IDENTIFIER:
|
||||
// @see http://msdn.microsoft.com/en-us/library/ms176027.aspx
|
||||
return '[' . str_replace(array('[', ']'), array('[[', ']]'), $value) . ']';
|
||||
|
||||
case dibi::BOOL:
|
||||
return $value ? 1 : 0;
|
||||
case dibi::BOOL:
|
||||
return $value ? 1 : 0;
|
||||
|
||||
case dibi::DATE:
|
||||
case dibi::DATETIME:
|
||||
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
|
||||
$value = new DibiDateTime($value);
|
||||
}
|
||||
return $value->format($type === dibi::DATETIME ? "'Y-m-d H:i:s'" : "'Y-m-d'");
|
||||
case dibi::DATE:
|
||||
return $value instanceof DateTime ? $value->format("'Y-m-d'") : date("'Y-m-d'", $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
case dibi::DATETIME:
|
||||
return $value instanceof DateTime ? $value->format("'Y-m-d H:i:s'") : date("'Y-m-d H:i:s'", $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes string for use in a LIKE statement.
|
||||
* @param string
|
||||
@@ -258,6 +268,7 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Decodes data from result set.
|
||||
* @param string value
|
||||
@@ -274,15 +285,19 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Injects LIMIT/OFFSET to the SQL query.
|
||||
* @param string &$sql The SQL query that will be modified.
|
||||
* @param int $limit
|
||||
* @param int $offset
|
||||
* @return void
|
||||
*/
|
||||
public function applyLimit(& $sql, $limit, $offset)
|
||||
public function applyLimit(&$sql, $limit, $offset)
|
||||
{
|
||||
// offset support is missing
|
||||
if ($limit >= 0) {
|
||||
$sql = 'SELECT TOP ' . (int) $limit . ' * FROM (' . $sql . ') AS T ';
|
||||
$sql = 'SELECT TOP ' . (int) $limit . ' * FROM (' . $sql . ')';
|
||||
}
|
||||
|
||||
if ($offset) {
|
||||
@@ -291,9 +306,11 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* result set ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Automatically frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -304,6 +321,7 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the number of rows in a result set.
|
||||
* @return int
|
||||
@@ -314,6 +332,7 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches the row at current position and moves the internal cursor to the next position.
|
||||
* @param bool TRUE for associative array, FALSE for numeric
|
||||
@@ -325,6 +344,7 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Moves cursor position without fetching row.
|
||||
* @param int the 0-based cursor pos to seek to
|
||||
@@ -336,6 +356,7 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -347,6 +368,7 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a result set.
|
||||
* @return array
|
||||
@@ -365,6 +387,7 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the result set resource.
|
||||
* @return mixed
|
@@ -2,11 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
require_once dirname(__FILE__) . '/DibiMySqlReflector.php';
|
||||
require_once dirname(__FILE__) . '/mysql.reflector.php';
|
||||
|
||||
|
||||
/**
|
||||
@@ -49,6 +53,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
private $buffered;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @throws DibiNotSupportedException
|
||||
*/
|
||||
@@ -60,12 +65,13 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Connects to a database.
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
public function connect(array & $config)
|
||||
public function connect(array &$config)
|
||||
{
|
||||
if (isset($config['resource'])) {
|
||||
$this->connection = $config['resource'];
|
||||
@@ -73,21 +79,16 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
} else {
|
||||
// default values
|
||||
DibiConnection::alias($config, 'flags', 'options');
|
||||
$config += array(
|
||||
'charset' => 'utf8',
|
||||
'timezone' => date('P'),
|
||||
'username' => ini_get('mysql.default_user'),
|
||||
'password' => ini_get('mysql.default_password'),
|
||||
);
|
||||
if (!isset($config['charset'])) $config['charset'] = 'utf8';
|
||||
if (!isset($config['username'])) $config['username'] = ini_get('mysql.default_user');
|
||||
if (!isset($config['password'])) $config['password'] = ini_get('mysql.default_password');
|
||||
if (!isset($config['host'])) {
|
||||
$host = ini_get('mysql.default_host');
|
||||
if ($host) {
|
||||
$config['host'] = $host;
|
||||
$config['port'] = ini_get('mysql.default_port');
|
||||
} else {
|
||||
if (!isset($config['socket'])) {
|
||||
$config['socket'] = ini_get('mysql.default_socket');
|
||||
}
|
||||
if (!isset($config['socket'])) $config['socket'] = ini_get('mysql.default_socket');
|
||||
$config['host'] = NULL;
|
||||
}
|
||||
}
|
||||
@@ -130,14 +131,13 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
$this->query("SET sql_mode='$config[sqlmode]'");
|
||||
}
|
||||
|
||||
if (isset($config['timezone'])) {
|
||||
$this->query("SET time_zone='$config[timezone]'");
|
||||
}
|
||||
$this->query("SET time_zone='" . date('P') . "'");
|
||||
|
||||
$this->buffered = empty($config['unbuffered']);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Disconnects from a database.
|
||||
* @return void
|
||||
@@ -148,6 +148,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes the SQL query.
|
||||
* @param string SQL statement.
|
||||
@@ -171,6 +172,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves information about the most recently executed query.
|
||||
* @return array
|
||||
@@ -179,9 +181,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
{
|
||||
$res = array();
|
||||
preg_match_all('#(.+?): +(\d+) *#', mysql_info($this->connection), $matches, PREG_SET_ORDER);
|
||||
if (preg_last_error()) {
|
||||
throw new DibiPcreException;
|
||||
}
|
||||
if (preg_last_error()) throw new DibiPcreException;
|
||||
|
||||
foreach ($matches as $m) {
|
||||
$res[$m[1]] = (int) $m[2];
|
||||
@@ -190,6 +190,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
|
||||
* @return int|FALSE number of rows or FALSE on error
|
||||
@@ -200,6 +201,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
|
||||
* @return int|FALSE int on success or FALSE on failure
|
||||
@@ -210,6 +212,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Begins a transaction (if supported).
|
||||
* @param string optional savepoint name
|
||||
@@ -222,6 +225,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Commits statements in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -234,6 +238,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Rollback changes in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -246,6 +251,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection resource.
|
||||
* @return mixed
|
||||
@@ -256,6 +262,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection reflector.
|
||||
* @return IDibiReflector
|
||||
@@ -266,6 +273,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Result set driver factory.
|
||||
* @param resource
|
||||
@@ -279,9 +287,11 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* SQL ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes data for use in a SQL statement.
|
||||
* @param mixed value
|
||||
@@ -292,38 +302,38 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
public function escape($value, $type)
|
||||
{
|
||||
switch ($type) {
|
||||
case dibi::TEXT:
|
||||
if (!is_resource($this->connection)) {
|
||||
throw new DibiException('Lost connection to server.');
|
||||
}
|
||||
return "'" . mysql_real_escape_string($value, $this->connection) . "'";
|
||||
case dibi::TEXT:
|
||||
if (!is_resource($this->connection)) {
|
||||
throw new DibiException('Lost connection to server.');
|
||||
}
|
||||
return "'" . mysql_real_escape_string($value, $this->connection) . "'";
|
||||
|
||||
case dibi::BINARY:
|
||||
if (!is_resource($this->connection)) {
|
||||
throw new DibiException('Lost connection to server.');
|
||||
}
|
||||
return "_binary'" . mysql_real_escape_string($value, $this->connection) . "'";
|
||||
case dibi::BINARY:
|
||||
if (!is_resource($this->connection)) {
|
||||
throw new DibiException('Lost connection to server.');
|
||||
}
|
||||
return "_binary'" . mysql_real_escape_string($value, $this->connection) . "'";
|
||||
|
||||
case dibi::IDENTIFIER:
|
||||
// @see http://dev.mysql.com/doc/refman/5.0/en/identifiers.html
|
||||
return '`' . str_replace('`', '``', $value) . '`';
|
||||
case dibi::IDENTIFIER:
|
||||
// @see http://dev.mysql.com/doc/refman/5.0/en/identifiers.html
|
||||
return '`' . str_replace('`', '``', $value) . '`';
|
||||
|
||||
case dibi::BOOL:
|
||||
return $value ? 1 : 0;
|
||||
case dibi::BOOL:
|
||||
return $value ? 1 : 0;
|
||||
|
||||
case dibi::DATE:
|
||||
case dibi::DATETIME:
|
||||
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
|
||||
$value = new DibiDateTime($value);
|
||||
}
|
||||
return $value->format($type === dibi::DATETIME ? "'Y-m-d H:i:s'" : "'Y-m-d'");
|
||||
case dibi::DATE:
|
||||
return $value instanceof DateTime ? $value->format("'Y-m-d'") : date("'Y-m-d'", $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
case dibi::DATETIME:
|
||||
return $value instanceof DateTime ? $value->format("'Y-m-d H:i:s'") : date("'Y-m-d H:i:s'", $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes string for use in a LIKE statement.
|
||||
* @param string
|
||||
@@ -337,6 +347,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Decodes data from result set.
|
||||
* @param string value
|
||||
@@ -353,23 +364,29 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Injects LIMIT/OFFSET to the SQL query.
|
||||
* @param string &$sql The SQL query that will be modified.
|
||||
* @param int $limit
|
||||
* @param int $offset
|
||||
* @return void
|
||||
*/
|
||||
public function applyLimit(& $sql, $limit, $offset)
|
||||
public function applyLimit(&$sql, $limit, $offset)
|
||||
{
|
||||
if ($limit >= 0 || $offset > 0) {
|
||||
// see http://dev.mysql.com/doc/refman/5.0/en/select.html
|
||||
$sql .= ' LIMIT ' . ($limit < 0 ? '18446744073709551615' : (int) $limit)
|
||||
. ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
|
||||
}
|
||||
if ($limit < 0 && $offset < 1) return;
|
||||
|
||||
// see http://dev.mysql.com/doc/refman/5.0/en/select.html
|
||||
$sql .= ' LIMIT ' . ($limit < 0 ? '18446744073709551615' : (int) $limit)
|
||||
. ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* result set ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Automatically frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -380,6 +397,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the number of rows in a result set.
|
||||
* @return int
|
||||
@@ -393,6 +411,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches the row at current position and moves the internal cursor to the next position.
|
||||
* @param bool TRUE for associative array, FALSE for numeric
|
||||
@@ -404,6 +423,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Moves cursor position without fetching row.
|
||||
* @param int the 0-based cursor pos to seek to
|
||||
@@ -420,6 +440,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -431,6 +452,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a result set.
|
||||
* @return array
|
||||
@@ -453,6 +475,7 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the result set resource.
|
||||
* @return mixed
|
@@ -2,7 +2,11 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
@@ -19,12 +23,14 @@ class DibiMySqlReflector extends DibiObject implements IDibiReflector
|
||||
private $driver;
|
||||
|
||||
|
||||
|
||||
public function __construct(IDibiDriver $driver)
|
||||
{
|
||||
$this->driver = $driver;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns list of tables.
|
||||
* @return array
|
||||
@@ -48,6 +54,7 @@ class DibiMySqlReflector extends DibiObject implements IDibiReflector
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a table.
|
||||
* @param string
|
||||
@@ -81,6 +88,7 @@ class DibiMySqlReflector extends DibiObject implements IDibiReflector
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all indexes in a table.
|
||||
* @param string
|
||||
@@ -107,44 +115,15 @@ class DibiMySqlReflector extends DibiObject implements IDibiReflector
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all foreign keys in a table.
|
||||
* @param string
|
||||
* @return array
|
||||
* @throws DibiNotSupportedException
|
||||
*/
|
||||
public function getForeignKeys($table)
|
||||
{
|
||||
$data = $this->driver->query("SELECT `ENGINE` FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = {$this->driver->escape($table, dibi::TEXT)}")->fetch(TRUE);
|
||||
if ($data['ENGINE'] !== 'InnoDB') {
|
||||
throw new DibiNotSupportedException("Foreign keys are not supported in {$data['ENGINE']} tables.");
|
||||
}
|
||||
|
||||
$res = $this->driver->query("
|
||||
SELECT rc.CONSTRAINT_NAME, rc.UPDATE_RULE, rc.DELETE_RULE, kcu.REFERENCED_TABLE_NAME,
|
||||
GROUP_CONCAT(kcu.REFERENCED_COLUMN_NAME ORDER BY kcu.ORDINAL_POSITION) AS REFERENCED_COLUMNS,
|
||||
GROUP_CONCAT(kcu.COLUMN_NAME ORDER BY kcu.ORDINAL_POSITION) AS COLUMNS
|
||||
FROM information_schema.REFERENTIAL_CONSTRAINTS rc
|
||||
INNER JOIN information_schema.KEY_COLUMN_USAGE kcu ON
|
||||
kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
|
||||
AND kcu.CONSTRAINT_SCHEMA = rc.CONSTRAINT_SCHEMA
|
||||
WHERE rc.CONSTRAINT_SCHEMA = DATABASE()
|
||||
AND rc.TABLE_NAME = {$this->driver->escape($table, dibi::TEXT)}
|
||||
GROUP BY rc.CONSTRAINT_NAME
|
||||
");
|
||||
|
||||
$foreignKeys = array();
|
||||
while ($row = $res->fetch(TRUE)) {
|
||||
$keyName = $row['CONSTRAINT_NAME'];
|
||||
|
||||
$foreignKeys[$keyName]['name'] = $keyName;
|
||||
$foreignKeys[$keyName]['local'] = explode(",", $row['COLUMNS']);
|
||||
$foreignKeys[$keyName]['table'] = $row['REFERENCED_TABLE_NAME'];
|
||||
$foreignKeys[$keyName]['foreign'] = explode(",", $row['REFERENCED_COLUMNS']);
|
||||
$foreignKeys[$keyName]['onDelete'] = $row['DELETE_RULE'];
|
||||
$foreignKeys[$keyName]['onUpdate'] = $row['UPDATE_RULE'];
|
||||
}
|
||||
return array_values($foreignKeys);
|
||||
throw new DibiNotImplementedException;
|
||||
}
|
||||
|
||||
}
|
@@ -2,11 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
require_once dirname(__FILE__) . '/DibiMySqlReflector.php';
|
||||
require_once dirname(__FILE__) . '/mysql.reflector.php';
|
||||
|
||||
|
||||
/**
|
||||
@@ -50,6 +54,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
private $buffered;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @throws DibiNotSupportedException
|
||||
*/
|
||||
@@ -61,12 +66,13 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Connects to a database.
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
public function connect(array & $config)
|
||||
public function connect(array &$config)
|
||||
{
|
||||
mysqli_report(MYSQLI_REPORT_OFF);
|
||||
if (isset($config['resource'])) {
|
||||
@@ -74,14 +80,11 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
|
||||
} else {
|
||||
// default values
|
||||
$config += array(
|
||||
'charset' => 'utf8',
|
||||
'timezone' => date('P'),
|
||||
'username' => ini_get('mysqli.default_user'),
|
||||
'password' => ini_get('mysqli.default_pw'),
|
||||
'socket' => ini_get('mysqli.default_socket'),
|
||||
'port' => NULL,
|
||||
);
|
||||
if (!isset($config['charset'])) $config['charset'] = 'utf8';
|
||||
if (!isset($config['username'])) $config['username'] = ini_get('mysqli.default_user');
|
||||
if (!isset($config['password'])) $config['password'] = ini_get('mysqli.default_pw');
|
||||
if (!isset($config['socket'])) $config['socket'] = ini_get('mysqli.default_socket');
|
||||
if (!isset($config['port'])) $config['port'] = NULL;
|
||||
if (!isset($config['host'])) {
|
||||
$host = ini_get('mysqli.default_host');
|
||||
if ($host) {
|
||||
@@ -115,7 +118,12 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
if (isset($config['charset'])) {
|
||||
if (!@mysqli_set_charset($this->connection, $config['charset'])) {
|
||||
$ok = FALSE;
|
||||
if (version_compare(PHP_VERSION , '5.1.5', '>=')) {
|
||||
// affects the character set used by mysql_real_escape_string() (was added in MySQL 5.0.7 and PHP 5.0.5, fixed in PHP 5.1.5)
|
||||
$ok = @mysqli_set_charset($this->connection, $config['charset']); // intentionally @
|
||||
}
|
||||
if (!$ok) {
|
||||
$this->query("SET NAMES '$config[charset]'");
|
||||
}
|
||||
}
|
||||
@@ -124,14 +132,13 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
$this->query("SET sql_mode='$config[sqlmode]'");
|
||||
}
|
||||
|
||||
if (isset($config['timezone'])) {
|
||||
$this->query("SET time_zone='$config[timezone]'");
|
||||
}
|
||||
$this->query("SET time_zone='" . date('P') . "'");
|
||||
|
||||
$this->buffered = empty($config['unbuffered']);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Disconnects from a database.
|
||||
* @return void
|
||||
@@ -142,6 +149,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes the SQL query.
|
||||
* @param string SQL statement.
|
||||
@@ -161,6 +169,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves information about the most recently executed query.
|
||||
* @return array
|
||||
@@ -169,9 +178,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
{
|
||||
$res = array();
|
||||
preg_match_all('#(.+?): +(\d+) *#', mysqli_info($this->connection), $matches, PREG_SET_ORDER);
|
||||
if (preg_last_error()) {
|
||||
throw new DibiPcreException;
|
||||
}
|
||||
if (preg_last_error()) throw new DibiPcreException;
|
||||
|
||||
foreach ($matches as $m) {
|
||||
$res[$m[1]] = (int) $m[2];
|
||||
@@ -180,16 +187,18 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
|
||||
* @return int|FALSE number of rows or FALSE on error
|
||||
*/
|
||||
public function getAffectedRows()
|
||||
{
|
||||
return mysqli_affected_rows($this->connection) === -1 ? FALSE : mysqli_affected_rows($this->connection);
|
||||
return mysqli_affected_rows($this->connection);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
|
||||
* @return int|FALSE int on success or FALSE on failure
|
||||
@@ -200,6 +209,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Begins a transaction (if supported).
|
||||
* @param string optional savepoint name
|
||||
@@ -212,6 +222,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Commits statements in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -224,6 +235,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Rollback changes in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -236,6 +248,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection resource.
|
||||
* @return mysqli
|
||||
@@ -246,6 +259,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection reflector.
|
||||
* @return IDibiReflector
|
||||
@@ -256,6 +270,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Result set driver factory.
|
||||
* @param mysqli_result
|
||||
@@ -269,9 +284,11 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* SQL ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes data for use in a SQL statement.
|
||||
* @param mixed value
|
||||
@@ -282,31 +299,31 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
public function escape($value, $type)
|
||||
{
|
||||
switch ($type) {
|
||||
case dibi::TEXT:
|
||||
return "'" . mysqli_real_escape_string($this->connection, $value) . "'";
|
||||
case dibi::TEXT:
|
||||
return "'" . mysqli_real_escape_string($this->connection, $value) . "'";
|
||||
|
||||
case dibi::BINARY:
|
||||
return "_binary'" . mysqli_real_escape_string($this->connection, $value) . "'";
|
||||
case dibi::BINARY:
|
||||
return "_binary'" . mysqli_real_escape_string($this->connection, $value) . "'";
|
||||
|
||||
case dibi::IDENTIFIER:
|
||||
return '`' . str_replace('`', '``', $value) . '`';
|
||||
case dibi::IDENTIFIER:
|
||||
return '`' . str_replace('`', '``', $value) . '`';
|
||||
|
||||
case dibi::BOOL:
|
||||
return $value ? 1 : 0;
|
||||
case dibi::BOOL:
|
||||
return $value ? 1 : 0;
|
||||
|
||||
case dibi::DATE:
|
||||
case dibi::DATETIME:
|
||||
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
|
||||
$value = new DibiDateTime($value);
|
||||
}
|
||||
return $value->format($type === dibi::DATETIME ? "'Y-m-d H:i:s'" : "'Y-m-d'");
|
||||
case dibi::DATE:
|
||||
return $value instanceof DateTime ? $value->format("'Y-m-d'") : date("'Y-m-d'", $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
case dibi::DATETIME:
|
||||
return $value instanceof DateTime ? $value->format("'Y-m-d H:i:s'") : date("'Y-m-d H:i:s'", $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes string for use in a LIKE statement.
|
||||
* @param string
|
||||
@@ -320,6 +337,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Decodes data from result set.
|
||||
* @param string value
|
||||
@@ -336,23 +354,29 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Injects LIMIT/OFFSET to the SQL query.
|
||||
* @param string &$sql The SQL query that will be modified.
|
||||
* @param int $limit
|
||||
* @param int $offset
|
||||
* @return void
|
||||
*/
|
||||
public function applyLimit(& $sql, $limit, $offset)
|
||||
public function applyLimit(&$sql, $limit, $offset)
|
||||
{
|
||||
if ($limit >= 0 || $offset > 0) {
|
||||
// see http://dev.mysql.com/doc/refman/5.0/en/select.html
|
||||
$sql .= ' LIMIT ' . ($limit < 0 ? '18446744073709551615' : (int) $limit)
|
||||
. ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
|
||||
}
|
||||
if ($limit < 0 && $offset < 1) return;
|
||||
|
||||
// see http://dev.mysql.com/doc/refman/5.0/en/select.html
|
||||
$sql .= ' LIMIT ' . ($limit < 0 ? '18446744073709551615' : (int) $limit)
|
||||
. ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* result set ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Automatically frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -363,6 +387,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the number of rows in a result set.
|
||||
* @return int
|
||||
@@ -376,6 +401,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches the row at current position and moves the internal cursor to the next position.
|
||||
* @param bool TRUE for associative array, FALSE for numeric
|
||||
@@ -387,6 +413,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Moves cursor position without fetching row.
|
||||
* @param int the 0-based cursor pos to seek to
|
||||
@@ -402,6 +429,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -413,6 +441,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a result set.
|
||||
* @return array
|
||||
@@ -446,6 +475,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the result set resource.
|
||||
* @return mysqli_result
|
||||
@@ -453,7 +483,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
public function getResultResource()
|
||||
{
|
||||
$this->autoFree = FALSE;
|
||||
return $this->resultSet === NULL || $this->resultSet->type === NULL ? NULL : $this->resultSet;
|
||||
return @$this->resultSet->type === NULL ? NULL : $this->resultSet;
|
||||
}
|
||||
|
||||
}
|
@@ -2,7 +2,11 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
@@ -38,6 +42,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
private $row = 0;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @throws DibiNotSupportedException
|
||||
*/
|
||||
@@ -49,22 +54,21 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Connects to a database.
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
public function connect(array & $config)
|
||||
public function connect(array &$config)
|
||||
{
|
||||
if (isset($config['resource'])) {
|
||||
$this->connection = $config['resource'];
|
||||
} else {
|
||||
// default values
|
||||
$config += array(
|
||||
'username' => ini_get('odbc.default_user'),
|
||||
'password' => ini_get('odbc.default_pw'),
|
||||
'dsn' => ini_get('odbc.default_db'),
|
||||
);
|
||||
if (!isset($config['username'])) $config['username'] = ini_get('odbc.default_user');
|
||||
if (!isset($config['password'])) $config['password'] = ini_get('odbc.default_pw');
|
||||
if (!isset($config['dsn'])) $config['dsn'] = ini_get('odbc.default_db');
|
||||
|
||||
if (empty($config['persistent'])) {
|
||||
$this->connection = @odbc_connect($config['dsn'], $config['username'], $config['password']); // intentionally @
|
||||
@@ -79,6 +83,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Disconnects from a database.
|
||||
* @return void
|
||||
@@ -89,6 +94,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes the SQL query.
|
||||
* @param string SQL statement.
|
||||
@@ -110,6 +116,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
|
||||
* @return int|FALSE number of rows or FALSE on error
|
||||
@@ -120,6 +127,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
|
||||
* @return int|FALSE int on success or FALSE on failure
|
||||
@@ -130,6 +138,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Begins a transaction (if supported).
|
||||
* @param string optional savepoint name
|
||||
@@ -144,6 +153,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Commits statements in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -159,6 +169,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Rollback changes in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -174,6 +185,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Is in transaction?
|
||||
* @return bool
|
||||
@@ -184,6 +196,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection resource.
|
||||
* @return mixed
|
||||
@@ -194,6 +207,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection reflector.
|
||||
* @return IDibiReflector
|
||||
@@ -204,6 +218,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Result set driver factory.
|
||||
* @param resource
|
||||
@@ -217,9 +232,11 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* SQL ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes data for use in a SQL statement.
|
||||
* @param mixed value
|
||||
@@ -230,29 +247,29 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
public function escape($value, $type)
|
||||
{
|
||||
switch ($type) {
|
||||
case dibi::TEXT:
|
||||
case dibi::BINARY:
|
||||
return "'" . str_replace("'", "''", $value) . "'";
|
||||
case dibi::TEXT:
|
||||
case dibi::BINARY:
|
||||
return "'" . str_replace("'", "''", $value) . "'";
|
||||
|
||||
case dibi::IDENTIFIER:
|
||||
return '[' . str_replace(array('[', ']'), array('[[', ']]'), $value) . ']';
|
||||
case dibi::IDENTIFIER:
|
||||
return '[' . str_replace(array('[', ']'), array('[[', ']]'), $value) . ']';
|
||||
|
||||
case dibi::BOOL:
|
||||
return $value ? 1 : 0;
|
||||
case dibi::BOOL:
|
||||
return $value ? 1 : 0;
|
||||
|
||||
case dibi::DATE:
|
||||
case dibi::DATETIME:
|
||||
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
|
||||
$value = new DibiDateTime($value);
|
||||
}
|
||||
return $value->format($type === dibi::DATETIME ? "#m/d/Y H:i:s#" : "#m/d/Y#");
|
||||
case dibi::DATE:
|
||||
return $value instanceof DateTime ? $value->format("#m/d/Y#") : date("#m/d/Y#", $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
case dibi::DATETIME:
|
||||
return $value instanceof DateTime ? $value->format("#m/d/Y H:i:s#") : date("#m/d/Y H:i:s#", $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes string for use in a LIKE statement.
|
||||
* @param string
|
||||
@@ -266,6 +283,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Decodes data from result set.
|
||||
* @param string value
|
||||
@@ -282,26 +300,30 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Injects LIMIT/OFFSET to the SQL query.
|
||||
* @param string &$sql The SQL query that will be modified.
|
||||
* @param int $limit
|
||||
* @param int $offset
|
||||
* @return void
|
||||
*/
|
||||
public function applyLimit(& $sql, $limit, $offset)
|
||||
public function applyLimit(&$sql, $limit, $offset)
|
||||
{
|
||||
// offset support is missing
|
||||
if ($limit >= 0) {
|
||||
$sql = 'SELECT TOP ' . (int) $limit . ' * FROM (' . $sql . ')';
|
||||
}
|
||||
|
||||
if ($offset) {
|
||||
throw new DibiNotSupportedException('Offset is not implemented in driver odbc.');
|
||||
}
|
||||
if ($offset) throw new DibiNotSupportedException('Offset is not implemented in driver odbc.');
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* result set ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Automatically frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -312,6 +334,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the number of rows in a result set.
|
||||
* @return int
|
||||
@@ -323,6 +346,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches the row at current position and moves the internal cursor to the next position.
|
||||
* @param bool TRUE for associative array, FALSE for numeric
|
||||
@@ -334,9 +358,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
return odbc_fetch_array($this->resultSet, ++$this->row);
|
||||
} else {
|
||||
$set = $this->resultSet;
|
||||
if (!odbc_fetch_row($set, ++$this->row)) {
|
||||
return FALSE;
|
||||
}
|
||||
if (!odbc_fetch_row($set, ++$this->row)) return FALSE;
|
||||
$count = odbc_num_fields($set);
|
||||
$cols = array();
|
||||
for ($i = 1; $i <= $count; $i++) $cols[] = odbc_result($set, $i);
|
||||
@@ -345,6 +367,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Moves cursor position without fetching row.
|
||||
* @param int the 0-based cursor pos to seek to
|
||||
@@ -357,6 +380,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -368,6 +392,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a result set.
|
||||
* @return array
|
||||
@@ -388,6 +413,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the result set resource.
|
||||
* @return mixed
|
||||
@@ -399,9 +425,11 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* IDibiReflector ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns list of tables.
|
||||
* @return array
|
||||
@@ -423,6 +451,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a table.
|
||||
* @param string
|
||||
@@ -449,6 +478,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all indexes in a table.
|
||||
* @param string
|
||||
@@ -460,6 +490,7 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all foreign keys in a table.
|
||||
* @param string
|
@@ -2,7 +2,11 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
@@ -17,7 +21,6 @@
|
||||
* - formatDate => how to format date in SQL (@see date)
|
||||
* - 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
|
||||
*
|
||||
* @author David Grudl
|
||||
@@ -41,6 +44,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
private $fmtDate, $fmtDateTime;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @throws DibiNotSupportedException
|
||||
*/
|
||||
@@ -52,12 +56,13 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Connects to a database.
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
public function connect(array & $config)
|
||||
public function connect(array &$config)
|
||||
{
|
||||
$foo = & $config['charset'];
|
||||
$this->fmtDate = isset($config['formatDate']) ? $config['formatDate'] : 'U';
|
||||
@@ -65,10 +70,8 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
|
||||
if (isset($config['resource'])) {
|
||||
$this->connection = $config['resource'];
|
||||
} elseif (empty($config['persistent'])) {
|
||||
$this->connection = @oci_new_connect($config['username'], $config['password'], $config['database'], $config['charset']); // intentionally @
|
||||
} else {
|
||||
$this->connection = @oci_pconnect($config['username'], $config['password'], $config['database'], $config['charset']); // intentionally @
|
||||
$this->connection = @oci_new_connect($config['username'], $config['password'], $config['database'], $config['charset']); // intentionally @
|
||||
}
|
||||
|
||||
if (!$this->connection) {
|
||||
@@ -78,6 +81,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Disconnects from a database.
|
||||
* @return void
|
||||
@@ -88,6 +92,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes the SQL query.
|
||||
* @param string SQL statement.
|
||||
@@ -113,6 +118,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
|
||||
* @return int|FALSE number of rows or FALSE on error
|
||||
@@ -123,6 +129,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
|
||||
* @return int|FALSE int on success or FALSE on failure
|
||||
@@ -134,6 +141,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Begins a transaction (if supported).
|
||||
* @param string optional savepoint name
|
||||
@@ -145,6 +153,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Commits statements in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -161,6 +170,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Rollback changes in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -177,6 +187,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection resource.
|
||||
* @return mixed
|
||||
@@ -187,6 +198,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection reflector.
|
||||
* @return IDibiReflector
|
||||
@@ -197,6 +209,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Result set driver factory.
|
||||
* @param resource
|
||||
@@ -210,9 +223,11 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* SQL ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes data for use in a SQL statement.
|
||||
* @param mixed value
|
||||
@@ -223,30 +238,30 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
public function escape($value, $type)
|
||||
{
|
||||
switch ($type) {
|
||||
case dibi::TEXT:
|
||||
case dibi::BINARY:
|
||||
return "'" . str_replace("'", "''", $value) . "'"; // TODO: not tested
|
||||
case dibi::TEXT:
|
||||
case dibi::BINARY:
|
||||
return "'" . str_replace("'", "''", $value) . "'"; // TODO: not tested
|
||||
|
||||
case dibi::IDENTIFIER:
|
||||
// @see http://download.oracle.com/docs/cd/B10500_01/server.920/a96540/sql_elements9a.htm
|
||||
return '"' . str_replace('"', '""', $value) . '"';
|
||||
case dibi::IDENTIFIER:
|
||||
// @see http://download.oracle.com/docs/cd/B10500_01/server.920/a96540/sql_elements9a.htm
|
||||
return '"' . str_replace('"', '""', $value) . '"';
|
||||
|
||||
case dibi::BOOL:
|
||||
return $value ? 1 : 0;
|
||||
case dibi::BOOL:
|
||||
return $value ? 1 : 0;
|
||||
|
||||
case dibi::DATE:
|
||||
case dibi::DATETIME:
|
||||
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
|
||||
$value = new DibiDateTime($value);
|
||||
}
|
||||
return $value->format($type === dibi::DATETIME ? $this->fmtDateTime : $this->fmtDate);
|
||||
case dibi::DATE:
|
||||
return $value instanceof DateTime ? $value->format($this->fmtDate) : date($this->fmtDate, $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
case dibi::DATETIME:
|
||||
return $value instanceof DateTime ? $value->format($this->fmtDateTime) : date($this->fmtDateTime, $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes string for use in a LIKE statement.
|
||||
* @param string
|
||||
@@ -261,6 +276,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Decodes data from result set.
|
||||
* @param string value
|
||||
@@ -277,17 +293,19 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Injects LIMIT/OFFSET to the SQL query.
|
||||
* @param string &$sql The SQL query that will be modified.
|
||||
* @param int $limit
|
||||
* @param int $offset
|
||||
* @return void
|
||||
*/
|
||||
public function applyLimit(& $sql, $limit, $offset)
|
||||
public function applyLimit(&$sql, $limit, $offset)
|
||||
{
|
||||
if ($offset > 0) {
|
||||
// see http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html
|
||||
$sql = 'SELECT * FROM (SELECT t.*, ROWNUM AS "__rnum" FROM (' . $sql . ') t '
|
||||
. ($limit >= 0 ? 'WHERE ROWNUM <= ' . ((int) $offset + (int) $limit) : '')
|
||||
. ') WHERE "__rnum" > '. (int) $offset;
|
||||
$sql = 'SELECT * FROM (SELECT t.*, ROWNUM AS "__rnum" FROM (' . $sql . ') t ' . ($limit >= 0 ? 'WHERE ROWNUM <= ' . ((int) $offset + (int) $limit) : '') . ') WHERE "__rnum" > '. (int) $offset;
|
||||
|
||||
} elseif ($limit >= 0) {
|
||||
$sql = 'SELECT * FROM (' . $sql . ') WHERE ROWNUM <= ' . (int) $limit;
|
||||
@@ -295,9 +313,11 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* result set ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Automatically frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -308,6 +328,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the number of rows in a result set.
|
||||
* @return int
|
||||
@@ -318,6 +339,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches the row at current position and moves the internal cursor to the next position.
|
||||
* @param bool TRUE for associative array, FALSE for numeric
|
||||
@@ -329,6 +351,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Moves cursor position without fetching row.
|
||||
* @param int the 0-based cursor pos to seek to
|
||||
@@ -340,6 +363,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -351,6 +375,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a result set.
|
||||
* @return array
|
||||
@@ -371,6 +396,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the result set resource.
|
||||
* @return mixed
|
||||
@@ -382,9 +408,11 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* IDibiReflector ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns list of tables.
|
||||
* @return array
|
||||
@@ -405,6 +433,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a table.
|
||||
* @param string
|
||||
@@ -416,6 +445,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all indexes in a table.
|
||||
* @param string
|
||||
@@ -427,6 +457,7 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all foreign keys in a table.
|
||||
* @param string
|
@@ -2,12 +2,16 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
require_once dirname(__FILE__) . '/DibiMySqlReflector.php';
|
||||
require_once dirname(__FILE__) . '/DibiSqliteReflector.php';
|
||||
require_once dirname(__FILE__) . '/mysql.reflector.php';
|
||||
require_once dirname(__FILE__) . '/sqlite.reflector.php';
|
||||
|
||||
|
||||
/**
|
||||
@@ -39,6 +43,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
private $driverName;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @throws DibiNotSupportedException
|
||||
*/
|
||||
@@ -50,12 +55,13 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Connects to a database.
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
public function connect(array & $config)
|
||||
public function connect(array &$config)
|
||||
{
|
||||
$foo = & $config['dsn'];
|
||||
$foo = & $config['options'];
|
||||
@@ -79,6 +85,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Disconnects from a database.
|
||||
* @return void
|
||||
@@ -89,6 +96,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes the SQL query.
|
||||
* @param string SQL statement.
|
||||
@@ -123,6 +131,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
|
||||
* @return int|FALSE number of rows or FALSE on error
|
||||
@@ -133,6 +142,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
|
||||
* @return int|FALSE int on success or FALSE on failure
|
||||
@@ -143,6 +153,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Begins a transaction (if supported).
|
||||
* @param string optional savepoint name
|
||||
@@ -158,6 +169,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Commits statements in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -173,6 +185,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Rollback changes in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -188,6 +201,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection resource.
|
||||
* @return PDO
|
||||
@@ -198,6 +212,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection reflector.
|
||||
* @return IDibiReflector
|
||||
@@ -205,19 +220,20 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
public function getReflector()
|
||||
{
|
||||
switch ($this->driverName) {
|
||||
case 'mysql':
|
||||
return new DibiMySqlReflector($this);
|
||||
case 'mysql':
|
||||
return new DibiMySqlReflector($this);
|
||||
|
||||
case 'sqlite':
|
||||
case 'sqlite2':
|
||||
return new DibiSqliteReflector($this);
|
||||
case 'sqlite':
|
||||
case 'sqlite2':
|
||||
return new DibiSqliteReflector($this);
|
||||
|
||||
default:
|
||||
throw new DibiNotSupportedException;
|
||||
default:
|
||||
throw new DibiNotSupportedException;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Result set driver factory.
|
||||
* @param PDOStatement
|
||||
@@ -231,9 +247,11 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* SQL ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes data for use in a SQL statement.
|
||||
* @param mixed value
|
||||
@@ -244,52 +262,49 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
public function escape($value, $type)
|
||||
{
|
||||
switch ($type) {
|
||||
case dibi::TEXT:
|
||||
return $this->connection->quote($value, PDO::PARAM_STR);
|
||||
case dibi::TEXT:
|
||||
return $this->connection->quote($value, PDO::PARAM_STR);
|
||||
|
||||
case dibi::BINARY:
|
||||
return $this->connection->quote($value, PDO::PARAM_LOB);
|
||||
case dibi::BINARY:
|
||||
return $this->connection->quote($value, PDO::PARAM_LOB);
|
||||
|
||||
case dibi::IDENTIFIER:
|
||||
switch ($this->driverName) {
|
||||
case 'mysql':
|
||||
return '`' . str_replace('`', '``', $value) . '`';
|
||||
case dibi::IDENTIFIER:
|
||||
switch ($this->driverName) {
|
||||
case 'mysql':
|
||||
return '`' . str_replace('`', '``', $value) . '`';
|
||||
|
||||
case 'pgsql':
|
||||
return '"' . str_replace('"', '""', $value) . '"';
|
||||
case 'pgsql':
|
||||
return '"' . str_replace('"', '""', $value) . '"';
|
||||
|
||||
case 'sqlite':
|
||||
case 'sqlite2':
|
||||
return '[' . strtr($value, '[]', ' ') . ']';
|
||||
case 'sqlite':
|
||||
case 'sqlite2':
|
||||
return '[' . strtr($value, '[]', ' ') . ']';
|
||||
|
||||
case 'odbc':
|
||||
case 'oci': // TODO: not tested
|
||||
case 'mssql':
|
||||
return '[' . str_replace(array('[', ']'), array('[[', ']]'), $value) . ']';
|
||||
|
||||
case 'sqlsrv':
|
||||
return '[' . str_replace(']', ']]', $value) . ']';
|
||||
|
||||
default:
|
||||
return $value;
|
||||
}
|
||||
|
||||
case dibi::BOOL:
|
||||
return $this->connection->quote($value, PDO::PARAM_BOOL);
|
||||
|
||||
case dibi::DATE:
|
||||
case dibi::DATETIME:
|
||||
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
|
||||
$value = new DibiDateTime($value);
|
||||
}
|
||||
return $value->format($type === dibi::DATETIME ? "'Y-m-d H:i:s'" : "'Y-m-d'");
|
||||
case 'odbc':
|
||||
case 'oci': // TODO: not tested
|
||||
case 'mssql':
|
||||
return '[' . str_replace(array('[', ']'), array('[[', ']]'), $value) . ']';
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
return $value;
|
||||
}
|
||||
|
||||
case dibi::BOOL:
|
||||
return $this->connection->quote($value, PDO::PARAM_BOOL);
|
||||
|
||||
case dibi::DATE:
|
||||
return $value instanceof DateTime ? $value->format("'Y-m-d'") : date("'Y-m-d'", $value);
|
||||
|
||||
case dibi::DATETIME:
|
||||
return $value instanceof DateTime ? $value->format("'Y-m-d H:i:s'") : date("'Y-m-d H:i:s'", $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes string for use in a LIKE statement.
|
||||
* @param string
|
||||
@@ -302,6 +317,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Decodes data from result set.
|
||||
* @param string value
|
||||
@@ -318,64 +334,61 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Injects LIMIT/OFFSET to the SQL query.
|
||||
* @param string &$sql The SQL query that will be modified.
|
||||
* @param int $limit
|
||||
* @param int $offset
|
||||
* @return void
|
||||
*/
|
||||
public function applyLimit(& $sql, $limit, $offset)
|
||||
public function applyLimit(&$sql, $limit, $offset)
|
||||
{
|
||||
if ($limit < 0 && $offset < 1) {
|
||||
return;
|
||||
}
|
||||
if ($limit < 0 && $offset < 1) return;
|
||||
|
||||
switch ($this->driverName) {
|
||||
case 'mysql':
|
||||
$sql .= ' LIMIT ' . ($limit < 0 ? '18446744073709551615' : (int) $limit)
|
||||
. ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
|
||||
case 'mysql':
|
||||
$sql .= ' LIMIT ' . ($limit < 0 ? '18446744073709551615' : (int) $limit)
|
||||
. ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
|
||||
break;
|
||||
|
||||
case 'pgsql':
|
||||
if ($limit >= 0) $sql .= ' LIMIT ' . (int) $limit;
|
||||
if ($offset > 0) $sql .= ' OFFSET ' . (int) $offset;
|
||||
break;
|
||||
|
||||
case 'sqlite':
|
||||
case 'sqlite2':
|
||||
$sql .= ' LIMIT ' . $limit . ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
|
||||
break;
|
||||
|
||||
case 'oci':
|
||||
if ($offset > 0) {
|
||||
$sql = 'SELECT * FROM (SELECT t.*, ROWNUM AS "__rnum" FROM (' . $sql . ') t ' . ($limit >= 0 ? 'WHERE ROWNUM <= ' . ((int) $offset + (int) $limit) : '') . ') WHERE "__rnum" > '. (int) $offset;
|
||||
} elseif ($limit >= 0) {
|
||||
$sql = 'SELECT * FROM (' . $sql . ') WHERE ROWNUM <= ' . (int) $limit;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'odbc':
|
||||
case 'mssql':
|
||||
if ($offset < 1) {
|
||||
$sql = 'SELECT TOP ' . (int) $limit . ' * FROM (' . $sql . ')';
|
||||
break;
|
||||
}
|
||||
// intentionally break omitted
|
||||
|
||||
case 'pgsql':
|
||||
if ($limit >= 0) {
|
||||
$sql .= ' LIMIT ' . (int) $limit;
|
||||
}
|
||||
if ($offset > 0) {
|
||||
$sql .= ' OFFSET ' . (int) $offset;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'sqlite':
|
||||
case 'sqlite2':
|
||||
$sql .= ' LIMIT ' . $limit . ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
|
||||
break;
|
||||
|
||||
case 'oci':
|
||||
if ($offset > 0) {
|
||||
$sql = 'SELECT * FROM (SELECT t.*, ROWNUM AS "__rnum" FROM (' . $sql . ') t '
|
||||
. ($limit >= 0 ? 'WHERE ROWNUM <= ' . ((int) $offset + (int) $limit) : '')
|
||||
. ') WHERE "__rnum" > '. (int) $offset;
|
||||
} elseif ($limit >= 0) {
|
||||
$sql = 'SELECT * FROM (' . $sql . ') WHERE ROWNUM <= ' . (int) $limit;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'odbc':
|
||||
case 'mssql':
|
||||
case 'sqlsrv':
|
||||
if ($offset < 1) {
|
||||
$sql = 'SELECT TOP ' . (int) $limit . ' * FROM (' . $sql . ') t';
|
||||
break;
|
||||
}
|
||||
// intentionally break omitted
|
||||
|
||||
default:
|
||||
throw new DibiNotSupportedException('PDO or driver does not support applying limit or offset.');
|
||||
default:
|
||||
throw new DibiNotSupportedException('PDO or driver does not support applying limit or offset.');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* result set ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the number of rows in a result set.
|
||||
* @return int
|
||||
@@ -386,6 +399,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches the row at current position and moves the internal cursor to the next position.
|
||||
* @param bool TRUE for associative array, FALSE for numeric
|
||||
@@ -397,6 +411,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Moves cursor position without fetching row.
|
||||
* @param int the 0-based cursor pos to seek to
|
||||
@@ -408,6 +423,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -418,6 +434,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a result set.
|
||||
* @return array
|
||||
@@ -434,10 +451,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
}
|
||||
// PHP < 5.2.3 compatibility
|
||||
// @see: http://php.net/manual/en/pdostatement.getcolumnmeta.php#pdostatement.getcolumnmeta.changelog
|
||||
$row = $row + array(
|
||||
'table' => NULL,
|
||||
'native_type' => 'VAR_STRING',
|
||||
);
|
||||
$row['table'] = isset($row['table']) ? $row['table'] : NULL;
|
||||
|
||||
$columns[] = array(
|
||||
'name' => $row['name'],
|
||||
@@ -451,6 +465,7 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the result set resource.
|
||||
* @return PDOStatement
|
@@ -2,7 +2,11 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
@@ -35,6 +39,10 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
/** @var int|FALSE Affected rows */
|
||||
private $affectedRows = FALSE;
|
||||
|
||||
/** @var bool Escape method */
|
||||
private $escMethod = FALSE;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @throws DibiNotSupportedException
|
||||
@@ -47,20 +55,19 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Connects to a database.
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
public function connect(array & $config)
|
||||
public function connect(array &$config)
|
||||
{
|
||||
if (isset($config['resource'])) {
|
||||
$this->connection = $config['resource'];
|
||||
|
||||
} else {
|
||||
$config += array(
|
||||
'charset' => 'utf8',
|
||||
);
|
||||
if (!isset($config['charset'])) $config['charset'] = 'utf8';
|
||||
if (isset($config['string'])) {
|
||||
$string = $config['string'];
|
||||
} else {
|
||||
@@ -68,9 +75,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
DibiConnection::alias($config, 'user', 'username');
|
||||
DibiConnection::alias($config, 'dbname', 'database');
|
||||
foreach (array('host','hostaddr','port','dbname','user','password','connect_timeout','options','sslmode','service') as $key) {
|
||||
if (isset($config[$key])) {
|
||||
$string .= $key . '=' . $config[$key] . ' ';
|
||||
}
|
||||
if (isset($config[$key])) $string .= $key . '=' . $config[$key] . ' ';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,9 +105,12 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
if (isset($config['schema'])) {
|
||||
$this->query('SET search_path TO "' . $config['schema'] . '"');
|
||||
}
|
||||
|
||||
$this->escMethod = version_compare(PHP_VERSION , '5.2.0', '>=');
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Disconnects from a database.
|
||||
* @return void
|
||||
@@ -113,6 +121,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes the SQL query.
|
||||
* @param string SQL statement.
|
||||
@@ -136,6 +145,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
|
||||
* @return int|FALSE number of rows or FALSE on error
|
||||
@@ -146,6 +156,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
|
||||
* @return int|FALSE int on success or FALSE on failure
|
||||
@@ -159,15 +170,14 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
$res = $this->query("SELECT CURRVAL('$sequence')");
|
||||
}
|
||||
|
||||
if (!$res) {
|
||||
return FALSE;
|
||||
}
|
||||
if (!$res) return FALSE;
|
||||
|
||||
$row = $res->fetch(FALSE);
|
||||
return is_array($row) ? $row[0] : FALSE;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Begins a transaction (if supported).
|
||||
* @param string optional savepoint name
|
||||
@@ -180,6 +190,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Commits statements in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -192,6 +203,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Rollback changes in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -204,6 +216,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Is in transaction?
|
||||
* @return bool
|
||||
@@ -214,6 +227,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection resource.
|
||||
* @return mixed
|
||||
@@ -224,6 +238,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection reflector.
|
||||
* @return IDibiReflector
|
||||
@@ -234,6 +249,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Result set driver factory.
|
||||
* @param resource
|
||||
@@ -247,9 +263,11 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* SQL ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes data for use in a SQL statement.
|
||||
* @param mixed value
|
||||
@@ -260,38 +278,46 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
public function escape($value, $type)
|
||||
{
|
||||
switch ($type) {
|
||||
case dibi::TEXT:
|
||||
case dibi::TEXT:
|
||||
if ($this->escMethod) {
|
||||
if (!is_resource($this->connection)) {
|
||||
throw new DibiException('Lost connection to server.');
|
||||
}
|
||||
return "'" . pg_escape_string($this->connection, $value) . "'";
|
||||
} else {
|
||||
return "'" . pg_escape_string($value) . "'";
|
||||
}
|
||||
|
||||
case dibi::BINARY:
|
||||
case dibi::BINARY:
|
||||
if ($this->escMethod) {
|
||||
if (!is_resource($this->connection)) {
|
||||
throw new DibiException('Lost connection to server.');
|
||||
}
|
||||
return "'" . pg_escape_bytea($this->connection, $value) . "'";
|
||||
} else {
|
||||
return "'" . pg_escape_bytea($value) . "'";
|
||||
}
|
||||
|
||||
case dibi::IDENTIFIER:
|
||||
// @see http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
|
||||
return '"' . str_replace('"', '""', $value) . '"';
|
||||
case dibi::IDENTIFIER:
|
||||
// @see http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
|
||||
return '"' . str_replace('"', '""', $value) . '"';
|
||||
|
||||
case dibi::BOOL:
|
||||
return $value ? 'TRUE' : 'FALSE';
|
||||
case dibi::BOOL:
|
||||
return $value ? 'TRUE' : 'FALSE';
|
||||
|
||||
case dibi::DATE:
|
||||
case dibi::DATETIME:
|
||||
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
|
||||
$value = new DibiDateTime($value);
|
||||
}
|
||||
return $value->format($type === dibi::DATETIME ? "'Y-m-d H:i:s'" : "'Y-m-d'");
|
||||
case dibi::DATE:
|
||||
return $value instanceof DateTime ? $value->format("'Y-m-d'") : date("'Y-m-d'", $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
case dibi::DATETIME:
|
||||
return $value instanceof DateTime ? $value->format("'Y-m-d H:i:s'") : date("'Y-m-d H:i:s'", $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes string for use in a LIKE statement.
|
||||
* @param string
|
||||
@@ -300,12 +326,18 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
*/
|
||||
public function escapeLike($value, $pos)
|
||||
{
|
||||
$value = pg_escape_string($this->connection, $value);
|
||||
if ($this->escMethod) {
|
||||
$value = pg_escape_string($this->connection, $value);
|
||||
} else {
|
||||
$value = pg_escape_string($value);
|
||||
}
|
||||
|
||||
$value = strtr($value, array( '%' => '\\\\%', '_' => '\\\\_'));
|
||||
return ($pos <= 0 ? "'%" : "'") . $value . ($pos >= 0 ? "%'" : "'");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Decodes data from result set.
|
||||
* @param string value
|
||||
@@ -322,25 +354,29 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Injects LIMIT/OFFSET to the SQL query.
|
||||
* @param string &$sql The SQL query that will be modified.
|
||||
* @param int $limit
|
||||
* @param int $offset
|
||||
* @return void
|
||||
*/
|
||||
public function applyLimit(& $sql, $limit, $offset)
|
||||
public function applyLimit(&$sql, $limit, $offset)
|
||||
{
|
||||
if ($limit >= 0) {
|
||||
if ($limit >= 0)
|
||||
$sql .= ' LIMIT ' . (int) $limit;
|
||||
}
|
||||
|
||||
if ($offset > 0) {
|
||||
if ($offset > 0)
|
||||
$sql .= ' OFFSET ' . (int) $offset;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* result set ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Automatically frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -351,6 +387,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the number of rows in a result set.
|
||||
* @return int
|
||||
@@ -361,6 +398,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches the row at current position and moves the internal cursor to the next position.
|
||||
* @param bool TRUE for associative array, FALSE for numeric
|
||||
@@ -372,6 +410,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Moves cursor position without fetching row.
|
||||
* @param int the 0-based cursor pos to seek to
|
||||
@@ -383,6 +422,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -394,18 +434,20 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a result set.
|
||||
* @return array
|
||||
*/
|
||||
public function getResultColumns()
|
||||
{
|
||||
$hasTable = version_compare(PHP_VERSION , '5.2.0', '>=');
|
||||
$count = pg_num_fields($this->resultSet);
|
||||
$columns = array();
|
||||
for ($i = 0; $i < $count; $i++) {
|
||||
$row = array(
|
||||
'name' => pg_field_name($this->resultSet, $i),
|
||||
'table' => pg_field_table($this->resultSet, $i),
|
||||
'table' => $hasTable ? pg_field_table($this->resultSet, $i) : NULL,
|
||||
'nativetype'=> pg_field_type($this->resultSet, $i),
|
||||
);
|
||||
$row['fullname'] = $row['table'] ? $row['table'] . '.' . $row['name'] : $row['name'];
|
||||
@@ -415,6 +457,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the result set resource.
|
||||
* @return mixed
|
||||
@@ -426,9 +469,11 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* IDibiReflector ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns list of tables.
|
||||
* @return array
|
||||
@@ -440,7 +485,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
throw new DibiDriverException('Reflection requires PostgreSQL 7.4 and newer.');
|
||||
}
|
||||
|
||||
$query = "
|
||||
$res = $this->query("
|
||||
SELECT
|
||||
table_name AS name,
|
||||
CASE table_type
|
||||
@@ -450,25 +495,14 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
FROM
|
||||
information_schema.tables
|
||||
WHERE
|
||||
table_schema = current_schema()";
|
||||
|
||||
if ($version >= 9.3) {
|
||||
$query .= "
|
||||
UNION ALL
|
||||
SELECT
|
||||
matviewname, 1
|
||||
FROM
|
||||
pg_matviews
|
||||
WHERE
|
||||
schemaname = current_schema()";
|
||||
}
|
||||
|
||||
$res = $this->query($query);
|
||||
table_schema = current_schema()
|
||||
");
|
||||
$tables = pg_fetch_all($res->resultSet);
|
||||
return $tables ? $tables : array();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a table.
|
||||
* @param string
|
||||
@@ -491,31 +525,6 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
WHERE table_name = $_table AND table_schema = current_schema()
|
||||
ORDER BY ordinal_position
|
||||
");
|
||||
|
||||
if (!$res->getRowCount()) {
|
||||
$res = $this->query("
|
||||
SELECT
|
||||
a.attname AS column_name,
|
||||
pg_type.typname AS udt_name,
|
||||
a.attlen AS numeric_precision,
|
||||
a.atttypmod-4 AS character_maximum_length,
|
||||
NOT a.attnotnull AS is_nullable,
|
||||
a.attnum AS ordinal_position,
|
||||
adef.adsrc AS column_default
|
||||
FROM
|
||||
pg_attribute a
|
||||
JOIN pg_type ON a.atttypid = pg_type.oid
|
||||
JOIN pg_class cls ON a.attrelid = cls.oid
|
||||
LEFT JOIN pg_attrdef adef ON adef.adnum = a.attnum AND adef.adrelid = a.attrelid
|
||||
WHERE
|
||||
cls.relkind IN ('r', 'v', 'mv')
|
||||
AND a.attrelid = $_table::regclass
|
||||
AND a.attnum > 0
|
||||
AND NOT a.attisdropped
|
||||
ORDER BY ordinal_position
|
||||
");
|
||||
}
|
||||
|
||||
$columns = array();
|
||||
while ($row = $res->fetch(TRUE)) {
|
||||
$size = (int) max($row['character_maximum_length'], $row['numeric_precision']);
|
||||
@@ -523,8 +532,8 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
'name' => $row['column_name'],
|
||||
'table' => $table,
|
||||
'nativetype' => strtoupper($row['udt_name']),
|
||||
'size' => $size > 0 ? $size : NULL,
|
||||
'nullable' => $row['is_nullable'] === 'YES' || $row['is_nullable'] === 't',
|
||||
'size' => $size ? $size : NULL,
|
||||
'nullable' => $row['is_nullable'] === 'YES',
|
||||
'default' => $row['column_default'],
|
||||
'autoincrement' => (int) $row['ordinal_position'] === $primary && substr($row['column_default'], 0, 7) === 'nextval',
|
||||
'vendor' => $row,
|
||||
@@ -534,6 +543,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all indexes in a table.
|
||||
* @param string
|
||||
@@ -575,6 +585,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all foreign keys in a table.
|
||||
* @param string
|
@@ -2,11 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
require_once dirname(__FILE__) . '/DibiSqliteReflector.php';
|
||||
require_once dirname(__FILE__) . '/sqlite.reflector.php';
|
||||
|
||||
|
||||
/**
|
||||
@@ -44,6 +48,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
private $dbcharset, $charset;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @throws DibiNotSupportedException
|
||||
*/
|
||||
@@ -55,12 +60,13 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Connects to a database.
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
public function connect(array & $config)
|
||||
public function connect(array &$config)
|
||||
{
|
||||
DibiConnection::alias($config, 'database', 'file');
|
||||
$this->fmtDate = isset($config['formatDate']) ? $config['formatDate'] : 'U';
|
||||
@@ -89,6 +95,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Disconnects from a database.
|
||||
* @return void
|
||||
@@ -99,6 +106,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes the SQL query.
|
||||
* @param string SQL statement.
|
||||
@@ -126,6 +134,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
|
||||
* @return int|FALSE number of rows or FALSE on error
|
||||
@@ -136,6 +145,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
|
||||
* @return int|FALSE int on success or FALSE on failure
|
||||
@@ -146,6 +156,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Begins a transaction (if supported).
|
||||
* @param string optional savepoint name
|
||||
@@ -158,6 +169,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Commits statements in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -170,6 +182,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Rollback changes in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -182,6 +195,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection resource.
|
||||
* @return mixed
|
||||
@@ -192,6 +206,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection reflector.
|
||||
* @return IDibiReflector
|
||||
@@ -202,6 +217,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Result set driver factory.
|
||||
* @param resource
|
||||
@@ -215,9 +231,11 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* SQL ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes data for use in a SQL statement.
|
||||
* @param mixed value
|
||||
@@ -228,29 +246,29 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
public function escape($value, $type)
|
||||
{
|
||||
switch ($type) {
|
||||
case dibi::TEXT:
|
||||
case dibi::BINARY:
|
||||
return "'" . sqlite_escape_string($value) . "'";
|
||||
case dibi::TEXT:
|
||||
case dibi::BINARY:
|
||||
return "'" . sqlite_escape_string($value) . "'";
|
||||
|
||||
case dibi::IDENTIFIER:
|
||||
return '[' . strtr($value, '[]', ' ') . ']';
|
||||
case dibi::IDENTIFIER:
|
||||
return '[' . strtr($value, '[]', ' ') . ']';
|
||||
|
||||
case dibi::BOOL:
|
||||
return $value ? 1 : 0;
|
||||
case dibi::BOOL:
|
||||
return $value ? 1 : 0;
|
||||
|
||||
case dibi::DATE:
|
||||
case dibi::DATETIME:
|
||||
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
|
||||
$value = new DibiDateTime($value);
|
||||
}
|
||||
return $value->format($type === dibi::DATETIME ? $this->fmtDateTime : $this->fmtDate);
|
||||
case dibi::DATE:
|
||||
return $value instanceof DateTime ? $value->format($this->fmtDate) : date($this->fmtDate, $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
case dibi::DATETIME:
|
||||
return $value instanceof DateTime ? $value->format($this->fmtDateTime) : date($this->fmtDateTime, $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes string for use in a LIKE statement.
|
||||
* @param string
|
||||
@@ -263,6 +281,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Decodes data from result set.
|
||||
* @param string value
|
||||
@@ -279,21 +298,26 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Injects LIMIT/OFFSET to the SQL query.
|
||||
* @param string &$sql The SQL query that will be modified.
|
||||
* @param int $limit
|
||||
* @param int $offset
|
||||
* @return void
|
||||
*/
|
||||
public function applyLimit(& $sql, $limit, $offset)
|
||||
public function applyLimit(&$sql, $limit, $offset)
|
||||
{
|
||||
if ($limit >= 0 || $offset > 0) {
|
||||
$sql .= ' LIMIT ' . (int) $limit . ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
|
||||
}
|
||||
if ($limit < 0 && $offset < 1) return;
|
||||
$sql .= ' LIMIT ' . $limit . ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* result set ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the number of rows in a result set.
|
||||
* @return int
|
||||
@@ -307,6 +331,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches the row at current position and moves the internal cursor to the next position.
|
||||
* @param bool TRUE for associative array, FALSE for numeric
|
||||
@@ -330,6 +355,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Moves cursor position without fetching row.
|
||||
* @param int the 0-based cursor pos to seek to
|
||||
@@ -345,6 +371,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -355,6 +382,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a result set.
|
||||
* @return array
|
||||
@@ -377,6 +405,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the result set resource.
|
||||
* @return mixed
|
||||
@@ -387,9 +416,11 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* user defined functions ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Registers an user defined function for use in SQL statements.
|
||||
* @param string function name
|
||||
@@ -403,6 +434,7 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Registers an aggregating user defined function for use in SQL statements.
|
||||
* @param string function name
|
@@ -2,7 +2,11 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
@@ -19,12 +23,14 @@ class DibiSqliteReflector extends DibiObject implements IDibiReflector
|
||||
private $driver;
|
||||
|
||||
|
||||
|
||||
public function __construct(IDibiDriver $driver)
|
||||
{
|
||||
$this->driver = $driver;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns list of tables.
|
||||
* @return array
|
||||
@@ -45,6 +51,7 @@ class DibiSqliteReflector extends DibiObject implements IDibiReflector
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a table.
|
||||
* @param string
|
||||
@@ -80,6 +87,7 @@ class DibiSqliteReflector extends DibiObject implements IDibiReflector
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all indexes in a table.
|
||||
* @param string
|
||||
@@ -131,6 +139,7 @@ class DibiSqliteReflector extends DibiObject implements IDibiReflector
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all foreign keys in a table.
|
||||
* @param string
|
@@ -2,11 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
require_once dirname(__FILE__) . '/DibiSqliteReflector.php';
|
||||
require_once dirname(__FILE__) . '/sqlite.reflector.php';
|
||||
|
||||
|
||||
/**
|
||||
@@ -42,6 +46,7 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
private $dbcharset, $charset;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @throws DibiNotSupportedException
|
||||
*/
|
||||
@@ -53,12 +58,13 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Connects to a database.
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
public function connect(array & $config)
|
||||
public function connect(array &$config)
|
||||
{
|
||||
DibiConnection::alias($config, 'database', 'file');
|
||||
$this->fmtDate = isset($config['formatDate']) ? $config['formatDate'] : 'U';
|
||||
@@ -87,6 +93,7 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Disconnects from a database.
|
||||
* @return void
|
||||
@@ -97,6 +104,7 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes the SQL query.
|
||||
* @param string SQL statement.
|
||||
@@ -119,6 +127,7 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
|
||||
* @return int|FALSE number of rows or FALSE on error
|
||||
@@ -129,6 +138,7 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
|
||||
* @return int|FALSE int on success or FALSE on failure
|
||||
@@ -139,6 +149,7 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Begins a transaction (if supported).
|
||||
* @param string optional savepoint name
|
||||
@@ -151,6 +162,7 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Commits statements in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -163,6 +175,7 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Rollback changes in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -175,6 +188,7 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection resource.
|
||||
* @return mixed
|
||||
@@ -185,6 +199,7 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the connection reflector.
|
||||
* @return IDibiReflector
|
||||
@@ -195,6 +210,7 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Result set driver factory.
|
||||
* @param SQLite3Result
|
||||
@@ -208,9 +224,11 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* SQL ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes data for use in a SQL statement.
|
||||
* @param mixed value
|
||||
@@ -221,31 +239,31 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
public function escape($value, $type)
|
||||
{
|
||||
switch ($type) {
|
||||
case dibi::TEXT:
|
||||
return "'" . $this->connection->escapeString($value) . "'";
|
||||
case dibi::TEXT:
|
||||
return "'" . $this->connection->escapeString($value) . "'";
|
||||
|
||||
case dibi::BINARY:
|
||||
return "X'" . bin2hex((string) $value) . "'";
|
||||
case dibi::BINARY:
|
||||
return "X'" . bin2hex((string) $value) . "'";
|
||||
|
||||
case dibi::IDENTIFIER:
|
||||
return '[' . strtr($value, '[]', ' ') . ']';
|
||||
case dibi::IDENTIFIER:
|
||||
return '[' . strtr($value, '[]', ' ') . ']';
|
||||
|
||||
case dibi::BOOL:
|
||||
return $value ? 1 : 0;
|
||||
case dibi::BOOL:
|
||||
return $value ? 1 : 0;
|
||||
|
||||
case dibi::DATE:
|
||||
case dibi::DATETIME:
|
||||
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
|
||||
$value = new DibiDateTime($value);
|
||||
}
|
||||
return $value->format($type === dibi::DATETIME ? $this->fmtDateTime : $this->fmtDate);
|
||||
case dibi::DATE:
|
||||
return $value instanceof DateTime ? $value->format($this->fmtDate) : date($this->fmtDate, $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
case dibi::DATETIME:
|
||||
return $value instanceof DateTime ? $value->format($this->fmtDateTime) : date($this->fmtDateTime, $value);
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported type.');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Encodes string for use in a LIKE statement.
|
||||
* @param string
|
||||
@@ -259,6 +277,7 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Decodes data from result set.
|
||||
* @param string value
|
||||
@@ -275,21 +294,26 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Injects LIMIT/OFFSET to the SQL query.
|
||||
* @param string &$sql The SQL query that will be modified.
|
||||
* @param int $limit
|
||||
* @param int $offset
|
||||
* @return void
|
||||
*/
|
||||
public function applyLimit(& $sql, $limit, $offset)
|
||||
public function applyLimit(&$sql, $limit, $offset)
|
||||
{
|
||||
if ($limit >= 0 || $offset > 0) {
|
||||
$sql .= ' LIMIT ' . (int) $limit . ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
|
||||
}
|
||||
if ($limit < 0 && $offset < 1) return;
|
||||
$sql .= ' LIMIT ' . $limit . ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* result set ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Automatically frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -300,6 +324,7 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the number of rows in a result set.
|
||||
* @return int
|
||||
@@ -311,6 +336,7 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches the row at current position and moves the internal cursor to the next position.
|
||||
* @param bool TRUE for associative array, FALSE for numeric
|
||||
@@ -334,6 +360,7 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Moves cursor position without fetching row.
|
||||
* @param int the 0-based cursor pos to seek to
|
||||
@@ -346,6 +373,7 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -357,6 +385,7 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns metadata for all columns in a result set.
|
||||
* @return array
|
||||
@@ -378,6 +407,7 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the result set resource.
|
||||
* @return mixed
|
||||
@@ -389,9 +419,11 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* user defined functions ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Registers an user defined function for use in SQL statements.
|
||||
* @param string function name
|
||||
@@ -405,6 +437,7 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Registers an aggregating user defined function for use in SQL statements.
|
||||
* @param string function name
|
@@ -1,543 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* This class is static container class for creating DB objects and
|
||||
* store connections info.
|
||||
*
|
||||
* @author David Grudl
|
||||
* @package dibi
|
||||
*/
|
||||
class dibi
|
||||
{
|
||||
/** column type */
|
||||
const TEXT = 's', // as 'string'
|
||||
BINARY = 'bin',
|
||||
BOOL = 'b',
|
||||
INTEGER = 'i',
|
||||
FLOAT = 'f',
|
||||
DATE = 'd',
|
||||
DATETIME = 't',
|
||||
TIME = 't';
|
||||
|
||||
const IDENTIFIER = 'n',
|
||||
AFFECTED_ROWS = 'a';
|
||||
|
||||
/** @deprecated */
|
||||
const FIELD_TEXT = dibi::TEXT,
|
||||
FIELD_BINARY = dibi::BINARY,
|
||||
FIELD_BOOL = dibi::BOOL,
|
||||
FIELD_INTEGER = dibi::INTEGER,
|
||||
FIELD_FLOAT = dibi::FLOAT,
|
||||
FIELD_DATE = dibi::DATE,
|
||||
FIELD_DATETIME = dibi::DATETIME,
|
||||
FIELD_TIME = dibi::TIME;
|
||||
|
||||
/** version */
|
||||
const VERSION = '2.2.0',
|
||||
REVISION = 'released on 2014-06-02';
|
||||
|
||||
/** sorting order */
|
||||
const ASC = 'ASC',
|
||||
DESC = 'DESC';
|
||||
|
||||
/** @var DibiConnection[] Connection registry storage for DibiConnection objects */
|
||||
private static $registry = array();
|
||||
|
||||
/** @var DibiConnection Current connection */
|
||||
private static $connection;
|
||||
|
||||
/** @var array @see addHandler */
|
||||
private static $handlers = array();
|
||||
|
||||
/** @var string Last SQL command @see dibi::query() */
|
||||
public static $sql;
|
||||
|
||||
/** @var int Elapsed time for last query */
|
||||
public static $elapsedTime;
|
||||
|
||||
/** @var int Elapsed time for all queries */
|
||||
public static $totalTime;
|
||||
|
||||
/** @var int Number or queries */
|
||||
public static $numOfQueries = 0;
|
||||
|
||||
/** @var string Default dibi driver */
|
||||
public static $defaultDriver = 'mysql';
|
||||
|
||||
|
||||
/**
|
||||
* Static class - cannot be instantiated.
|
||||
*/
|
||||
final public function __construct()
|
||||
{
|
||||
throw new LogicException("Cannot instantiate static class " . get_class($this));
|
||||
}
|
||||
|
||||
|
||||
/********************* connections handling ****************d*g**/
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new DibiConnection object and connects it to specified database.
|
||||
* @param mixed connection parameters
|
||||
* @param string connection name
|
||||
* @return DibiConnection
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function connect($config = array(), $name = 0)
|
||||
{
|
||||
return self::$connection = self::$registry[$name] = new DibiConnection($config, $name);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Disconnects from database (doesn't destroy DibiConnection object).
|
||||
* @return void
|
||||
*/
|
||||
public static function disconnect()
|
||||
{
|
||||
self::getConnection()->disconnect();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns TRUE when connection was established.
|
||||
* @return bool
|
||||
*/
|
||||
public static function isConnected()
|
||||
{
|
||||
return (self::$connection !== NULL) && self::$connection->isConnected();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Retrieve active connection.
|
||||
* @param string connection registy name
|
||||
* @return DibiConnection
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function getConnection($name = NULL)
|
||||
{
|
||||
if ($name === NULL) {
|
||||
if (self::$connection === NULL) {
|
||||
throw new DibiException('Dibi is not connected to database.');
|
||||
}
|
||||
|
||||
return self::$connection;
|
||||
}
|
||||
|
||||
if (!isset(self::$registry[$name])) {
|
||||
throw new DibiException("There is no connection named '$name'.");
|
||||
}
|
||||
|
||||
return self::$registry[$name];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sets connection.
|
||||
* @param DibiConnection
|
||||
* @return DibiConnection
|
||||
*/
|
||||
public static function setConnection(DibiConnection $connection)
|
||||
{
|
||||
return self::$connection = $connection;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Change active connection.
|
||||
* @param string connection registy name
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function activate($name)
|
||||
{
|
||||
self::$connection = self::getConnection($name);
|
||||
}
|
||||
|
||||
|
||||
/********************* monostate for active connection ****************d*g**/
|
||||
|
||||
|
||||
/**
|
||||
* Generates and executes SQL query - Monostate for DibiConnection::query().
|
||||
* @param array|mixed one or more arguments
|
||||
* @return DibiResult|int result set object (if any)
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function query($args)
|
||||
{
|
||||
$args = func_get_args();
|
||||
return self::getConnection()->query($args);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Executes the SQL query - Monostate for DibiConnection::nativeQuery().
|
||||
* @param string SQL statement.
|
||||
* @return DibiResult|int result set object (if any)
|
||||
*/
|
||||
public static function nativeQuery($sql)
|
||||
{
|
||||
return self::getConnection()->nativeQuery($sql);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Generates and prints SQL query - Monostate for DibiConnection::test().
|
||||
* @param array|mixed one or more arguments
|
||||
* @return bool
|
||||
*/
|
||||
public static function test($args)
|
||||
{
|
||||
$args = func_get_args();
|
||||
return self::getConnection()->test($args);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Generates and returns SQL query as DibiDataSource - Monostate for DibiConnection::test().
|
||||
* @param array|mixed one or more arguments
|
||||
* @return DibiDataSource
|
||||
*/
|
||||
public static function dataSource($args)
|
||||
{
|
||||
$args = func_get_args();
|
||||
return self::getConnection()->dataSource($args);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Executes SQL query and fetch result - Monostate for DibiConnection::query() & fetch().
|
||||
* @param array|mixed one or more arguments
|
||||
* @return DibiRow
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function fetch($args)
|
||||
{
|
||||
$args = func_get_args();
|
||||
return self::getConnection()->query($args)->fetch();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Executes SQL query and fetch results - Monostate for DibiConnection::query() & fetchAll().
|
||||
* @param array|mixed one or more arguments
|
||||
* @return DibiRow[]
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function fetchAll($args)
|
||||
{
|
||||
$args = func_get_args();
|
||||
return self::getConnection()->query($args)->fetchAll();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Executes SQL query and fetch first column - Monostate for DibiConnection::query() & fetchSingle().
|
||||
* @param array|mixed one or more arguments
|
||||
* @return string
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function fetchSingle($args)
|
||||
{
|
||||
$args = func_get_args();
|
||||
return self::getConnection()->query($args)->fetchSingle();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Executes SQL query and fetch pairs - Monostate for DibiConnection::query() & fetchPairs().
|
||||
* @param array|mixed one or more arguments
|
||||
* @return string
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function fetchPairs($args)
|
||||
{
|
||||
$args = func_get_args();
|
||||
return self::getConnection()->query($args)->fetchPairs();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Gets the number of affected rows.
|
||||
* Monostate for DibiConnection::getAffectedRows()
|
||||
* @return int number of rows
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function getAffectedRows()
|
||||
{
|
||||
return self::getConnection()->getAffectedRows();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Gets the number of affected rows. Alias for getAffectedRows().
|
||||
* @return int number of rows
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function affectedRows()
|
||||
{
|
||||
return self::getConnection()->getAffectedRows();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
|
||||
* Monostate for DibiConnection::getInsertId()
|
||||
* @param string optional sequence name
|
||||
* @return int
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function getInsertId($sequence=NULL)
|
||||
{
|
||||
return self::getConnection()->getInsertId($sequence);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves the ID generated for an AUTO_INCREMENT column. Alias for getInsertId().
|
||||
* @param string optional sequence name
|
||||
* @return int
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function insertId($sequence=NULL)
|
||||
{
|
||||
return self::getConnection()->getInsertId($sequence);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Begins a transaction - Monostate for DibiConnection::begin().
|
||||
* @param string optional savepoint name
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function begin($savepoint = NULL)
|
||||
{
|
||||
self::getConnection()->begin($savepoint);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Commits statements in a transaction - Monostate for DibiConnection::commit($savepoint = NULL).
|
||||
* @param string optional savepoint name
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function commit($savepoint = NULL)
|
||||
{
|
||||
self::getConnection()->commit($savepoint);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Rollback changes in a transaction - Monostate for DibiConnection::rollback().
|
||||
* @param string optional savepoint name
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
public static function rollback($savepoint = NULL)
|
||||
{
|
||||
self::getConnection()->rollback($savepoint);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Gets a information about the current database - Monostate for DibiConnection::getDatabaseInfo().
|
||||
* @return DibiDatabaseInfo
|
||||
*/
|
||||
public static function getDatabaseInfo()
|
||||
{
|
||||
return self::getConnection()->getDatabaseInfo();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Import SQL dump from file - extreme fast!
|
||||
* @param string filename
|
||||
* @return int count of sql commands
|
||||
*/
|
||||
public static function loadFile($file)
|
||||
{
|
||||
return self::getConnection()->loadFile($file);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Replacement for majority of dibi::methods() in future.
|
||||
*/
|
||||
public static function __callStatic($name, $args)
|
||||
{
|
||||
//if ($name = 'select', 'update', ...') {
|
||||
// return self::command()->$name($args);
|
||||
//}
|
||||
return call_user_func_array(array(self::getConnection(), $name), $args);
|
||||
}
|
||||
|
||||
|
||||
/********************* fluent SQL builders ****************d*g**/
|
||||
|
||||
|
||||
/**
|
||||
* @return DibiFluent
|
||||
*/
|
||||
public static function command()
|
||||
{
|
||||
return self::getConnection()->command();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string column name
|
||||
* @return DibiFluent
|
||||
*/
|
||||
public static function select($args)
|
||||
{
|
||||
$args = func_get_args();
|
||||
return call_user_func_array(array(self::getConnection(), 'select'), $args);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string table
|
||||
* @param array
|
||||
* @return DibiFluent
|
||||
*/
|
||||
public static function update($table, $args)
|
||||
{
|
||||
return self::getConnection()->update($table, $args);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string table
|
||||
* @param array
|
||||
* @return DibiFluent
|
||||
*/
|
||||
public static function insert($table, $args)
|
||||
{
|
||||
return self::getConnection()->insert($table, $args);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string table
|
||||
* @return DibiFluent
|
||||
*/
|
||||
public static function delete($table)
|
||||
{
|
||||
return self::getConnection()->delete($table);
|
||||
}
|
||||
|
||||
|
||||
/********************* substitutions ****************d*g**/
|
||||
|
||||
|
||||
/**
|
||||
* Returns substitution hashmap - Monostate for DibiConnection::getSubstitutes().
|
||||
* @return DibiHashMap
|
||||
*/
|
||||
public static function getSubstitutes()
|
||||
{
|
||||
return self::getConnection()->getSubstitutes();
|
||||
}
|
||||
|
||||
|
||||
/********************* misc tools ****************d*g**/
|
||||
|
||||
|
||||
/**
|
||||
* Prints out a syntax highlighted version of the SQL command or DibiResult.
|
||||
* @param string|DibiResult
|
||||
* @param bool return output instead of printing it?
|
||||
* @return string
|
||||
*/
|
||||
public static function dump($sql = NULL, $return = FALSE)
|
||||
{
|
||||
ob_start();
|
||||
if ($sql instanceof DibiResult) {
|
||||
$sql->dump();
|
||||
|
||||
} else {
|
||||
if ($sql === NULL) {
|
||||
$sql = self::$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|SET|VALUES|LEFT\s+JOIN|INNER\s+JOIN|TRUNCATE';
|
||||
static $keywords2 = 'ALL|DISTINCT|DISTINCTROW|IGNORE|AS|USING|ON|AND|OR|IN|IS|NOT|NULL|LIKE|RLIKE|REGEXP|TRUE|FALSE';
|
||||
|
||||
// insert new lines
|
||||
$sql = " $sql ";
|
||||
$sql = preg_replace("#(?<=[\\s,(])($keywords1)(?=[\\s,)])#i", "\n\$1", $sql);
|
||||
|
||||
// reduce spaces
|
||||
$sql = preg_replace('#[ \t]{2,}#', " ", $sql);
|
||||
|
||||
$sql = wordwrap($sql, 100);
|
||||
$sql = preg_replace("#([ \t]*\r?\n){2,}#", "\n", $sql);
|
||||
|
||||
// syntax highlight
|
||||
$highlighter = "#(/\\*.+?\\*/)|(\\*\\*.+?\\*\\*)|(?<=[\\s,(])($keywords1)(?=[\\s,)])|(?<=[\\s,(=])($keywords2)(?=[\\s,)=])#is";
|
||||
if (PHP_SAPI === 'cli') {
|
||||
if (substr(getenv('TERM'), 0, 5) === 'xterm') {
|
||||
$sql = preg_replace_callback($highlighter, array('dibi', 'cliHighlightCallback'), $sql);
|
||||
}
|
||||
echo trim($sql) . "\n\n";
|
||||
|
||||
} else {
|
||||
$sql = htmlSpecialChars($sql);
|
||||
$sql = preg_replace_callback($highlighter, array('dibi', 'highlightCallback'), $sql);
|
||||
echo '<pre class="dump">', trim($sql), "</pre>\n\n";
|
||||
}
|
||||
}
|
||||
|
||||
if ($return) {
|
||||
return ob_get_clean();
|
||||
} else {
|
||||
ob_end_flush();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static function highlightCallback($matches)
|
||||
{
|
||||
if (!empty($matches[1])) { // comment
|
||||
return '<em style="color:gray">' . $matches[1] . '</em>';
|
||||
|
||||
} elseif (!empty($matches[2])) { // error
|
||||
return '<strong style="color:red">' . $matches[2] . '</strong>';
|
||||
|
||||
} elseif (!empty($matches[3])) { // most important keywords
|
||||
return '<strong style="color:blue">' . $matches[3] . '</strong>';
|
||||
|
||||
} elseif (!empty($matches[4])) { // other keywords
|
||||
return '<strong style="color:green">' . $matches[4] . '</strong>';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static function cliHighlightCallback($matches)
|
||||
{
|
||||
if (!empty($matches[1])) { // comment
|
||||
return "\033[1;30m" . $matches[1] . "\033[0m";
|
||||
|
||||
} elseif (!empty($matches[2])) { // error
|
||||
return "\033[1;31m" . $matches[2] . "\033[0m";
|
||||
|
||||
} elseif (!empty($matches[3])) { // most important keywords
|
||||
return "\033[1;34m" . $matches[3] . "\033[0m";
|
||||
|
||||
} elseif (!empty($matches[4])) { // other keywords
|
||||
return "\033[1;32m" . $matches[4] . "\033[0m";
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@@ -2,10 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* dibi connection.
|
||||
*
|
||||
@@ -40,6 +45,7 @@ class DibiConnection extends DibiObject
|
||||
private $substitutes;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Connection options: (see driver-specific options too)
|
||||
* - lazy (bool) => if TRUE, connection will be established only when required
|
||||
@@ -56,6 +62,9 @@ class DibiConnection extends DibiObject
|
||||
*/
|
||||
public function __construct($config, $name = NULL)
|
||||
{
|
||||
class_exists('dibi'); // ensure class dibi is loaded
|
||||
|
||||
// DSN string
|
||||
if (is_string($config)) {
|
||||
parse_str($config, $config);
|
||||
|
||||
@@ -80,10 +89,10 @@ class DibiConnection extends DibiObject
|
||||
$config['driver'] = dibi::$defaultDriver;
|
||||
}
|
||||
|
||||
$class = preg_replace(array('#\W#', '#sql#'), array('_', 'Sql'), ucfirst(strtolower($config['driver'])));
|
||||
$class = "Dibi{$class}Driver";
|
||||
if (!class_exists($class)) {
|
||||
include_once dirname(__FILE__) . "/../drivers/$class.php";
|
||||
$driver = preg_replace('#[^a-z0-9_]#', '_', strtolower($config['driver']));
|
||||
$class = "Dibi" . $driver . "Driver";
|
||||
if (!class_exists($class, FALSE)) {
|
||||
include_once dirname(__FILE__) . "/../drivers/$driver.php";
|
||||
|
||||
if (!class_exists($class, FALSE)) {
|
||||
throw new DibiException("Unable to create instance of dibi driver '$class'.");
|
||||
@@ -111,7 +120,7 @@ class DibiConnection extends DibiObject
|
||||
$this->onEvent[] = array(new DibiFirePhpLogger($filter), 'logEvent');
|
||||
}
|
||||
|
||||
if (!interface_exists('Tracy\IBarPanel') && (interface_exists('Nette\Diagnostics\IBarPanel') || interface_exists('IBarPanel'))) {
|
||||
if (class_exists('DibiNettePanel', FALSE)) {
|
||||
$panel = new DibiNettePanel(isset($profilerCfg['explain']) ? $profilerCfg['explain'] : TRUE, $filter);
|
||||
$panel->register($this);
|
||||
}
|
||||
@@ -130,6 +139,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Automatically frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -141,6 +151,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Connects to a database.
|
||||
* @return void
|
||||
@@ -160,6 +171,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Disconnects from a database.
|
||||
* @return void
|
||||
@@ -171,6 +183,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns TRUE when connection was established.
|
||||
* @return bool
|
||||
@@ -181,6 +194,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns configuration variable. If no $key is passed, returns the entire array.
|
||||
* @see self::__construct
|
||||
@@ -202,6 +216,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Apply configuration alias or default values.
|
||||
* @param array connect configuration
|
||||
@@ -209,12 +224,10 @@ class DibiConnection extends DibiObject
|
||||
* @param string alias key
|
||||
* @return void
|
||||
*/
|
||||
public static function alias(& $config, $key, $alias)
|
||||
public static function alias(&$config, $key, $alias)
|
||||
{
|
||||
$foo = & $config;
|
||||
foreach (explode('|', $key) as $key) {
|
||||
$foo = & $foo[$key];
|
||||
}
|
||||
foreach (explode('|', $key) as $key) $foo = & $foo[$key];
|
||||
|
||||
if (!isset($foo) && isset($config[$alias])) {
|
||||
$foo = $config[$alias];
|
||||
@@ -223,6 +236,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the driver and connects to a database in lazy mode.
|
||||
* @return IDibiDriver
|
||||
@@ -234,6 +248,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Generates (translates) and executes SQL query.
|
||||
* @param array|mixed one or more arguments
|
||||
@@ -247,6 +262,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Generates SQL query.
|
||||
* @param array|mixed one or more arguments
|
||||
@@ -260,6 +276,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Generates and prints SQL query.
|
||||
* @param array|mixed one or more arguments
|
||||
@@ -283,6 +300,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Generates (translates) and returns SQL query as DibiDataSource.
|
||||
* @param array|mixed one or more arguments
|
||||
@@ -296,6 +314,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Generates SQL query.
|
||||
* @param array
|
||||
@@ -308,6 +327,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes the SQL query.
|
||||
* @param string SQL statement.
|
||||
@@ -318,7 +338,6 @@ class DibiConnection extends DibiObject
|
||||
{
|
||||
$this->connected || $this->connect();
|
||||
|
||||
dibi::$sql = $sql;
|
||||
$event = $this->onEvent ? new DibiEvent($this, DibiEvent::QUERY, $sql) : NULL;
|
||||
try {
|
||||
$res = $this->driver->query($sql);
|
||||
@@ -339,6 +358,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
|
||||
* @return int number of rows
|
||||
@@ -348,13 +368,12 @@ class DibiConnection extends DibiObject
|
||||
{
|
||||
$this->connected || $this->connect();
|
||||
$rows = $this->driver->getAffectedRows();
|
||||
if (!is_int($rows) || $rows < 0) {
|
||||
throw new DibiException('Cannot retrieve number of affected rows.');
|
||||
}
|
||||
if (!is_int($rows) || $rows < 0) throw new DibiException('Cannot retrieve number of affected rows.');
|
||||
return $rows;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets the number of affected rows. Alias for getAffectedRows().
|
||||
* @return int number of rows
|
||||
@@ -366,6 +385,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
|
||||
* @param string optional sequence name
|
||||
@@ -376,13 +396,12 @@ class DibiConnection extends DibiObject
|
||||
{
|
||||
$this->connected || $this->connect();
|
||||
$id = $this->driver->getInsertId($sequence);
|
||||
if ($id < 1) {
|
||||
throw new DibiException('Cannot retrieve last generated ID.');
|
||||
}
|
||||
if ($id < 1) throw new DibiException('Cannot retrieve last generated ID.');
|
||||
return (int) $id;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves the ID generated for an AUTO_INCREMENT column. Alias for getInsertId().
|
||||
* @param string optional sequence name
|
||||
@@ -395,6 +414,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Begins a transaction (if supported).
|
||||
* @param string optional savepoint name
|
||||
@@ -415,6 +435,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Commits statements in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -435,6 +456,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Rollback changes in a transaction.
|
||||
* @param string optional savepoint name
|
||||
@@ -455,6 +477,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Result set factory.
|
||||
* @param IDibiResultDriver
|
||||
@@ -468,9 +491,11 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* fluent SQL builders ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return DibiFluent
|
||||
*/
|
||||
@@ -480,6 +505,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param string column name
|
||||
* @return DibiFluent
|
||||
@@ -491,6 +517,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param string table
|
||||
* @param array
|
||||
@@ -505,6 +532,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param string table
|
||||
* @param array
|
||||
@@ -522,6 +550,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param string table
|
||||
* @return DibiFluent
|
||||
@@ -532,9 +561,11 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* substitutions ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns substitution hashmap.
|
||||
* @return DibiHashMap
|
||||
@@ -545,6 +576,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Provides substitution.
|
||||
* @return string
|
||||
@@ -555,6 +587,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Substitution callback.
|
||||
*/
|
||||
@@ -564,9 +597,11 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* shortcuts ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes SQL query and fetch result - shortcut for query() & fetch().
|
||||
* @param array|mixed one or more arguments
|
||||
@@ -580,10 +615,11 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes SQL query and fetch results - shortcut for query() & fetchAll().
|
||||
* @param array|mixed one or more arguments
|
||||
* @return DibiRow[]
|
||||
* @return array of DibiRow
|
||||
* @throws DibiException
|
||||
*/
|
||||
public function fetchAll($args)
|
||||
@@ -593,6 +629,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes SQL query and fetch first column - shortcut for query() & fetchSingle().
|
||||
* @param array|mixed one or more arguments
|
||||
@@ -606,6 +643,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Executes SQL query and fetch pairs - shortcut for query() & fetchPairs().
|
||||
* @param array|mixed one or more arguments
|
||||
@@ -619,9 +657,11 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* misc ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Import SQL dump from file - extreme fast!
|
||||
* @param string filename
|
||||
@@ -638,21 +678,14 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
$count = 0;
|
||||
$delimiter = ';';
|
||||
$sql = '';
|
||||
while (!feof($handle)) {
|
||||
$s = rtrim(fgets($handle));
|
||||
if (substr($s, 0, 10) === 'DELIMITER ') {
|
||||
$delimiter = substr($s, 10);
|
||||
|
||||
} elseif (substr($s, -strlen($delimiter)) === $delimiter) {
|
||||
$sql .= substr($s, 0, -strlen($delimiter));
|
||||
$s = fgets($handle);
|
||||
$sql .= $s;
|
||||
if (substr(rtrim($s), -1) === ';') {
|
||||
$this->driver->query($sql);
|
||||
$sql = '';
|
||||
$count++;
|
||||
|
||||
} else {
|
||||
$sql .= $s . "\n";
|
||||
}
|
||||
}
|
||||
if (trim($sql) !== '') {
|
||||
@@ -664,6 +697,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Gets a information about the current database.
|
||||
* @return DibiDatabaseInfo
|
||||
@@ -675,6 +709,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Prevents unserialization.
|
||||
*/
|
||||
@@ -684,6 +719,7 @@ class DibiConnection extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Prevents serialization.
|
||||
*/
|
||||
|
@@ -2,10 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Default implementation of IDataSource for dibi.
|
||||
*
|
||||
@@ -50,6 +55,7 @@ class DibiDataSource extends DibiObject implements IDataSource
|
||||
private $limit;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param string SQL command or table or view name, as data source
|
||||
* @param DibiConnection connection
|
||||
@@ -65,11 +71,12 @@ class DibiDataSource extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Selects columns to query.
|
||||
* @param string|array column name or array of column names
|
||||
* @param string column alias
|
||||
* @return self
|
||||
* @param string column alias
|
||||
* @return DibiDataSource provides a fluent interface
|
||||
*/
|
||||
public function select($col, $as = NULL)
|
||||
{
|
||||
@@ -83,10 +90,11 @@ class DibiDataSource extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Adds conditions to query.
|
||||
* @param mixed conditions
|
||||
* @return self
|
||||
* @return DibiDataSource provides a fluent interface
|
||||
*/
|
||||
public function where($cond)
|
||||
{
|
||||
@@ -101,11 +109,12 @@ class DibiDataSource extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Selects columns to order by.
|
||||
* @param string|array column name or array of column names
|
||||
* @param string sorting direction
|
||||
* @return self
|
||||
* @param string sorting direction
|
||||
* @return DibiDataSource provides a fluent interface
|
||||
*/
|
||||
public function orderBy($row, $sorting = 'ASC')
|
||||
{
|
||||
@@ -119,11 +128,12 @@ class DibiDataSource extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Limits number of rows.
|
||||
* @param int limit
|
||||
* @param int offset
|
||||
* @return self
|
||||
* @return DibiDataSource provides a fluent interface
|
||||
*/
|
||||
public function applyLimit($limit, $offset = NULL)
|
||||
{
|
||||
@@ -134,6 +144,7 @@ class DibiDataSource extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the dibi connection.
|
||||
* @return DibiConnection
|
||||
@@ -144,9 +155,11 @@ class DibiDataSource extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* executing ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns (and queries) DibiResult.
|
||||
* @return DibiResult
|
||||
@@ -160,6 +173,7 @@ class DibiDataSource extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return DibiResultIterator
|
||||
*/
|
||||
@@ -169,6 +183,7 @@ class DibiDataSource extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Generates, executes SQL query and fetches the single row.
|
||||
* @return DibiRow|FALSE array on success, FALSE if no next record
|
||||
@@ -179,6 +194,7 @@ class DibiDataSource extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Like fetch(), but returns only first field.
|
||||
* @return mixed value on success, FALSE if no next record
|
||||
@@ -189,6 +205,7 @@ class DibiDataSource extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches all records from table.
|
||||
* @return array
|
||||
@@ -199,6 +216,7 @@ class DibiDataSource extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches all records from table and returns associative tree.
|
||||
* @param string associative descriptor
|
||||
@@ -210,6 +228,7 @@ class DibiDataSource extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches all records from table like $key => $value pairs.
|
||||
* @param string associative key
|
||||
@@ -222,6 +241,7 @@ class DibiDataSource extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Discards the internal cache.
|
||||
* @return void
|
||||
@@ -232,9 +252,11 @@ class DibiDataSource extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* exporting ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns this data source wrapped in DibiFluent object.
|
||||
* @return DibiFluent
|
||||
@@ -245,6 +267,7 @@ class DibiDataSource extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns this data source wrapped in DibiDataSource object.
|
||||
* @return DibiDataSource
|
||||
@@ -255,6 +278,7 @@ class DibiDataSource extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns SQL query.
|
||||
* @return string
|
||||
@@ -275,9 +299,11 @@ FROM %SQL', $this->sql, '
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* counting ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the number of rows in a given data source.
|
||||
* @return int
|
||||
@@ -295,6 +321,7 @@ FROM %SQL', $this->sql, '
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the number of rows in a given data source.
|
||||
* @return int
|
||||
|
@@ -2,10 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reflection metadata class for a database.
|
||||
*
|
||||
@@ -28,6 +33,7 @@ class DibiDatabaseInfo extends DibiObject
|
||||
private $tables;
|
||||
|
||||
|
||||
|
||||
public function __construct(IDibiReflector $reflector, $name)
|
||||
{
|
||||
$this->reflector = $reflector;
|
||||
@@ -35,6 +41,7 @@ class DibiDatabaseInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
@@ -44,8 +51,9 @@ class DibiDatabaseInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return DibiTableInfo[]
|
||||
* @return array of DibiTableInfo
|
||||
*/
|
||||
public function getTables()
|
||||
{
|
||||
@@ -54,8 +62,9 @@ class DibiDatabaseInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
* @return array of string
|
||||
*/
|
||||
public function getTableNames()
|
||||
{
|
||||
@@ -68,6 +77,7 @@ class DibiDatabaseInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param string
|
||||
* @return DibiTableInfo
|
||||
@@ -85,6 +95,7 @@ class DibiDatabaseInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param string
|
||||
* @return bool
|
||||
@@ -96,6 +107,7 @@ class DibiDatabaseInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
@@ -112,6 +124,8 @@ class DibiDatabaseInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reflection metadata class for a database table.
|
||||
*
|
||||
@@ -150,6 +164,7 @@ class DibiTableInfo extends DibiObject
|
||||
private $primaryKey;
|
||||
|
||||
|
||||
|
||||
public function __construct(IDibiReflector $reflector, array $info)
|
||||
{
|
||||
$this->reflector = $reflector;
|
||||
@@ -158,6 +173,7 @@ class DibiTableInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
@@ -167,6 +183,7 @@ class DibiTableInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
@@ -176,8 +193,9 @@ class DibiTableInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return DibiColumnInfo[]
|
||||
* @return array of DibiColumnInfo
|
||||
*/
|
||||
public function getColumns()
|
||||
{
|
||||
@@ -186,8 +204,9 @@ class DibiTableInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
* @return array of string
|
||||
*/
|
||||
public function getColumnNames()
|
||||
{
|
||||
@@ -200,6 +219,7 @@ class DibiTableInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param string
|
||||
* @return DibiColumnInfo
|
||||
@@ -217,6 +237,7 @@ class DibiTableInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param string
|
||||
* @return bool
|
||||
@@ -228,8 +249,9 @@ class DibiTableInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return DibiForeignKeyInfo[]
|
||||
* @return array of DibiForeignKeyInfo
|
||||
*/
|
||||
public function getForeignKeys()
|
||||
{
|
||||
@@ -238,8 +260,9 @@ class DibiTableInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return DibiIndexInfo[]
|
||||
* @return array of DibiIndexInfo
|
||||
*/
|
||||
public function getIndexes()
|
||||
{
|
||||
@@ -248,6 +271,7 @@ class DibiTableInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return DibiIndexInfo
|
||||
*/
|
||||
@@ -258,6 +282,7 @@ class DibiTableInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
@@ -272,6 +297,7 @@ class DibiTableInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
@@ -293,6 +319,7 @@ class DibiTableInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
@@ -304,6 +331,8 @@ class DibiTableInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reflection metadata class for a result set.
|
||||
*
|
||||
@@ -325,14 +354,16 @@ class DibiResultInfo extends DibiObject
|
||||
private $names;
|
||||
|
||||
|
||||
|
||||
public function __construct(IDibiResultDriver $driver)
|
||||
{
|
||||
$this->driver = $driver;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return DibiColumnInfo[]
|
||||
* @return array of DibiColumnInfo
|
||||
*/
|
||||
public function getColumns()
|
||||
{
|
||||
@@ -341,9 +372,10 @@ class DibiResultInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param bool
|
||||
* @return string[]
|
||||
* @return array of string
|
||||
*/
|
||||
public function getColumnNames($fullNames = FALSE)
|
||||
{
|
||||
@@ -356,6 +388,7 @@ class DibiResultInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param string
|
||||
* @return DibiColumnInfo
|
||||
@@ -373,6 +406,7 @@ class DibiResultInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param string
|
||||
* @return bool
|
||||
@@ -384,6 +418,7 @@ class DibiResultInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
@@ -401,6 +436,8 @@ class DibiResultInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reflection metadata class for a table or result set column.
|
||||
*
|
||||
@@ -430,6 +467,7 @@ class DibiColumnInfo extends DibiObject
|
||||
private $info;
|
||||
|
||||
|
||||
|
||||
public function __construct(IDibiReflector $reflector = NULL, array $info)
|
||||
{
|
||||
$this->reflector = $reflector;
|
||||
@@ -437,6 +475,7 @@ class DibiColumnInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
@@ -446,6 +485,7 @@ class DibiColumnInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
@@ -455,6 +495,7 @@ class DibiColumnInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
@@ -464,6 +505,7 @@ class DibiColumnInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return DibiTableInfo
|
||||
*/
|
||||
@@ -476,6 +518,7 @@ class DibiColumnInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
@@ -485,6 +528,7 @@ class DibiColumnInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
@@ -494,6 +538,7 @@ class DibiColumnInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
@@ -503,6 +548,7 @@ class DibiColumnInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
@@ -512,6 +558,7 @@ class DibiColumnInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
@@ -521,6 +568,7 @@ class DibiColumnInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
@@ -530,6 +578,7 @@ class DibiColumnInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
@@ -539,6 +588,7 @@ class DibiColumnInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
@@ -548,6 +598,7 @@ class DibiColumnInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param string
|
||||
* @return mixed
|
||||
@@ -558,6 +609,7 @@ class DibiColumnInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Heuristic type detection.
|
||||
* @param string
|
||||
@@ -569,13 +621,13 @@ class DibiColumnInfo extends DibiObject
|
||||
static $patterns = array(
|
||||
'^_' => dibi::TEXT, // PostgreSQL arrays
|
||||
'BYTEA|BLOB|BIN' => dibi::BINARY,
|
||||
'TEXT|CHAR|POINT|INTERVAL' => dibi::TEXT,
|
||||
'YEAR|BYTE|COUNTER|SERIAL|INT|LONG|SHORT' => dibi::INTEGER,
|
||||
'TEXT|CHAR' => dibi::TEXT,
|
||||
'YEAR|BYTE|COUNTER|SERIAL|INT|LONG' => dibi::INTEGER,
|
||||
'CURRENCY|REAL|MONEY|FLOAT|DOUBLE|DECIMAL|NUMERIC|NUMBER' => dibi::FLOAT,
|
||||
'^TIME$' => dibi::TIME,
|
||||
'TIME' => dibi::DATETIME, // DATETIME, TIMESTAMP
|
||||
'DATE' => dibi::DATE,
|
||||
'BOOL' => dibi::BOOL,
|
||||
'BOOL|BIT' => dibi::BOOL,
|
||||
);
|
||||
|
||||
foreach ($patterns as $s => $val) {
|
||||
@@ -587,6 +639,7 @@ class DibiColumnInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
@@ -601,6 +654,8 @@ class DibiColumnInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reflection metadata class for a foreign key.
|
||||
*
|
||||
@@ -620,6 +675,7 @@ class DibiForeignKeyInfo extends DibiObject
|
||||
private $references;
|
||||
|
||||
|
||||
|
||||
public function __construct($name, array $references)
|
||||
{
|
||||
$this->name = $name;
|
||||
@@ -627,6 +683,7 @@ class DibiForeignKeyInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
@@ -636,6 +693,7 @@ class DibiForeignKeyInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
@@ -647,6 +705,8 @@ class DibiForeignKeyInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reflection metadata class for a index or primary key.
|
||||
*
|
||||
@@ -670,6 +730,7 @@ class DibiIndexInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
@@ -679,6 +740,7 @@ class DibiIndexInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
@@ -688,6 +750,7 @@ class DibiIndexInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
@@ -697,6 +760,7 @@ class DibiIndexInfo extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
|
@@ -2,10 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* DateTime with serialization and timestamp support for PHP 5.2.
|
||||
*
|
||||
@@ -18,9 +23,9 @@ class DibiDateTime extends DateTime
|
||||
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()));
|
||||
} elseif ($timezone === NULL) {
|
||||
$time = date('Y-m-d H:i:s', $time);
|
||||
}
|
||||
if ($timezone === NULL) {
|
||||
parent::__construct($time);
|
||||
} else {
|
||||
parent::__construct($time, $timezone);
|
||||
@@ -28,6 +33,7 @@ class DibiDateTime extends DateTime
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function modifyClone($modify = '')
|
||||
{
|
||||
$dolly = clone($this);
|
||||
@@ -35,6 +41,7 @@ class DibiDateTime extends DateTime
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function modify($modify)
|
||||
{
|
||||
parent::modify($modify);
|
||||
@@ -42,48 +49,40 @@ class DibiDateTime extends DateTime
|
||||
}
|
||||
|
||||
|
||||
public function setTimestamp($timestamp)
|
||||
|
||||
public function __sleep()
|
||||
{
|
||||
$zone = PHP_VERSION_ID === 50206 ? new \DateTimeZone($this->getTimezone()->getName()) : $this->getTimezone();
|
||||
$this->__construct('@' . $timestamp);
|
||||
$this->setTimeZone($zone);
|
||||
return $this;
|
||||
$this->fix = array($this->format('Y-m-d H:i:s'), $this->getTimezone()->getName());
|
||||
return array('fix');
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function __wakeup()
|
||||
{
|
||||
$this->__construct($this->fix[0], new DateTimeZone($this->fix[1]));
|
||||
unset($this->fix);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function getTimestamp()
|
||||
{
|
||||
$ts = $this->format('U');
|
||||
return is_float($tmp = $ts * 1) ? $ts : $tmp;
|
||||
return (int) $this->format('U');
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function setTimestamp($timestamp)
|
||||
{
|
||||
return $this->__construct(date('Y-m-d H:i:s', $timestamp), new DateTimeZone($this->getTimezone()->getName())); // getTimeZone() crashes in PHP 5.2.6
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function __toString()
|
||||
{
|
||||
return $this->format('Y-m-d H:i:s');
|
||||
}
|
||||
|
||||
|
||||
public function __sleep()
|
||||
{
|
||||
$zone = $this->getTimezone()->getName();
|
||||
if ($zone[0] === '+') {
|
||||
$this->fix = array($this->format('Y-m-d H:i:sP'));
|
||||
} else {
|
||||
$this->fix = array($this->format('Y-m-d H:i:s'), $zone);
|
||||
}
|
||||
return array('fix');
|
||||
}
|
||||
|
||||
|
||||
public function __wakeup()
|
||||
{
|
||||
if (isset($this->fix[1])) {
|
||||
$this->__construct($this->fix[0], new DateTimeZone($this->fix[1]));
|
||||
} else {
|
||||
$this->__construct($this->fix[0]);
|
||||
}
|
||||
unset($this->fix);
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -2,10 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Profiler & logger event.
|
||||
*
|
||||
@@ -49,6 +54,7 @@ class DibiEvent
|
||||
public $source;
|
||||
|
||||
|
||||
|
||||
public function __construct(DibiConnection $connection, $type, $sql = NULL)
|
||||
{
|
||||
$this->connection = $connection;
|
||||
@@ -79,6 +85,7 @@ class DibiEvent
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function done($result = NULL)
|
||||
{
|
||||
$this->result = $result;
|
||||
|
@@ -2,10 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* dibi common exception.
|
||||
*
|
||||
@@ -31,6 +36,7 @@ class DibiException extends Exception
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return string The SQL passed to the constructor
|
||||
*/
|
||||
@@ -40,6 +46,7 @@ class DibiException extends Exception
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return string string represenation of exception with SQL command
|
||||
*/
|
||||
@@ -51,6 +58,8 @@ class DibiException extends Exception
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* database server exception.
|
||||
*
|
||||
@@ -63,10 +72,12 @@ class DibiDriverException extends DibiException
|
||||
/********************* error catching ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/** @var string */
|
||||
private static $errorMsg;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Starts catching potential errors/warnings.
|
||||
* @return void
|
||||
@@ -78,6 +89,7 @@ class DibiDriverException extends DibiException
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns catched error/warning message.
|
||||
* @param string catched message
|
||||
@@ -92,6 +104,7 @@ class DibiDriverException extends DibiException
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Internal error handler. Do not call directly.
|
||||
* @internal
|
||||
@@ -111,6 +124,8 @@ class DibiDriverException extends DibiException
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* PCRE exception.
|
||||
*
|
||||
@@ -134,6 +149,7 @@ class DibiPcreException extends Exception {
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @package dibi
|
||||
*/
|
||||
@@ -141,6 +157,7 @@ class DibiNotImplementedException extends DibiException
|
||||
{}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @package dibi
|
||||
*/
|
||||
|
@@ -2,10 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* dibi file logger.
|
||||
*
|
||||
@@ -21,6 +26,7 @@ class DibiFileLogger extends DibiObject
|
||||
public $filter;
|
||||
|
||||
|
||||
|
||||
public function __construct($file, $filter = NULL)
|
||||
{
|
||||
$this->file = $file;
|
||||
@@ -28,6 +34,7 @@ class DibiFileLogger extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* After event notification.
|
||||
* @return void
|
||||
@@ -39,9 +46,7 @@ class DibiFileLogger extends DibiObject
|
||||
}
|
||||
|
||||
$handle = fopen($this->file, 'a');
|
||||
if (!$handle) {
|
||||
return; // or throw exception?
|
||||
}
|
||||
if (!$handle) return; // or throw exception?
|
||||
flock($handle, LOCK_EX);
|
||||
|
||||
if ($event->result instanceof Exception) {
|
||||
@@ -60,7 +65,7 @@ class DibiFileLogger extends DibiObject
|
||||
fwrite($handle,
|
||||
"OK: " . $event->sql
|
||||
. ($event->count ? ";\n-- rows: " . $event->count : '')
|
||||
. "\n-- takes: " . sprintf('%0.3f ms', $event->time * 1000)
|
||||
. "\n-- takes: " . sprintf('%0.3f', $event->time * 1000) . ' ms'
|
||||
. "\n-- source: " . implode(':', $event->source)
|
||||
. "\n-- driver: " . $event->connection->getConfig('driver') . '/' . $event->connection->getConfig('name')
|
||||
. "\n-- " . date('Y-m-d H:i:s')
|
||||
|
@@ -2,10 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* dibi FirePHP logger.
|
||||
*
|
||||
@@ -33,6 +38,7 @@ class DibiFirePhpLogger extends DibiObject
|
||||
private static $fireTable = array(array('Time', 'SQL Statement', 'Rows', 'Connection'));
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
@@ -42,12 +48,14 @@ class DibiFirePhpLogger extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function __construct($filter = NULL)
|
||||
{
|
||||
$this->filter = $filter ? (int) $filter : DibiEvent::QUERY;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* After event notification.
|
||||
* @return void
|
||||
|
@@ -2,10 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* dibi SQL builder via fluent interfaces. EXPERIMENTAL!
|
||||
*
|
||||
@@ -96,6 +101,7 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
private static $normalizer;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param DibiConnection
|
||||
*/
|
||||
@@ -109,11 +115,12 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Appends new argument to the clause.
|
||||
* @param string clause name
|
||||
* @param array arguments
|
||||
* @return self
|
||||
* @return DibiFluent provides a fluent interface
|
||||
*/
|
||||
public function __call($clause, $args)
|
||||
{
|
||||
@@ -198,15 +205,21 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Switch to a clause.
|
||||
* @param string clause name
|
||||
* @return self
|
||||
* @return DibiFluent provides a fluent interface
|
||||
*/
|
||||
public function clause($clause)
|
||||
public function clause($clause, $remove = FALSE)
|
||||
{
|
||||
$this->cursor = & $this->clauses[self::$normalizer->$clause];
|
||||
if ($this->cursor === NULL) {
|
||||
|
||||
if ($remove) { // deprecated, use removeClause
|
||||
trigger_error(__METHOD__ . '(..., TRUE) is deprecated; use removeClause() instead.', E_USER_NOTICE);
|
||||
$this->cursor = NULL;
|
||||
|
||||
} elseif ($this->cursor === NULL) {
|
||||
$this->cursor = array();
|
||||
}
|
||||
|
||||
@@ -214,10 +227,11 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Removes a clause.
|
||||
* @param string clause name
|
||||
* @return self
|
||||
* @return DibiFluent provides a fluent interface
|
||||
*/
|
||||
public function removeClause($clause)
|
||||
{
|
||||
@@ -226,11 +240,12 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Change a SQL flag.
|
||||
* @param string flag name
|
||||
* @param bool value
|
||||
* @return self
|
||||
* @return DibiFluent provides a fluent interface
|
||||
*/
|
||||
public function setFlag($flag, $value = TRUE)
|
||||
{
|
||||
@@ -244,6 +259,7 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Is a flag set?
|
||||
* @param string flag name
|
||||
@@ -255,6 +271,7 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns SQL command.
|
||||
* @return string
|
||||
@@ -265,6 +282,7 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the dibi connection.
|
||||
* @return DibiConnection
|
||||
@@ -275,11 +293,12 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Adds DibiResult setup.
|
||||
* @param string method
|
||||
* @param mixed args
|
||||
* @return self
|
||||
* @return DibiFluent provides a fluent interface
|
||||
*/
|
||||
public function setupResult($method)
|
||||
{
|
||||
@@ -288,9 +307,11 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* executing ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Generates and executes SQL query.
|
||||
* @param mixed what to return?
|
||||
@@ -300,17 +321,11 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
public function execute($return = NULL)
|
||||
{
|
||||
$res = $this->query($this->_export());
|
||||
switch ($return) {
|
||||
case dibi::IDENTIFIER:
|
||||
return $this->connection->getInsertId();
|
||||
case dibi::AFFECTED_ROWS:
|
||||
return $this->connection->getAffectedRows();
|
||||
default:
|
||||
return $res;
|
||||
}
|
||||
return $return === dibi::IDENTIFIER ? $this->connection->getInsertId() : $res;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Generates, executes SQL query and fetches the single row.
|
||||
* @return DibiRow|FALSE array on success, FALSE if no next record
|
||||
@@ -325,6 +340,7 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Like fetch(), but returns only first field.
|
||||
* @return mixed value on success, FALSE if no next record
|
||||
@@ -339,6 +355,7 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches all records from table.
|
||||
* @param int offset
|
||||
@@ -351,6 +368,7 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches all records from table and returns associative tree.
|
||||
* @param string associative descriptor
|
||||
@@ -362,6 +380,7 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches all records from table like $key => $value pairs.
|
||||
* @param string associative key
|
||||
@@ -374,6 +393,7 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Required by the IteratorAggregate interface.
|
||||
* @param int offset
|
||||
@@ -386,6 +406,7 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Generates and prints SQL query or it's part.
|
||||
* @param string clause name
|
||||
@@ -397,6 +418,7 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
@@ -408,6 +430,7 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return DibiResult
|
||||
*/
|
||||
@@ -421,9 +444,11 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* exporting ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return DibiDataSource
|
||||
*/
|
||||
@@ -433,6 +458,7 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns SQL query.
|
||||
* @return string
|
||||
@@ -447,6 +473,7 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Generates parameters for DibiTranslator.
|
||||
* @param string clause name
|
||||
@@ -472,9 +499,7 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
if ($clause === $this->command && $this->flags) {
|
||||
$args[] = implode(' ', array_keys($this->flags));
|
||||
}
|
||||
foreach ($statement as $arg) {
|
||||
$args[] = $arg;
|
||||
}
|
||||
foreach ($statement as $arg) $args[] = $arg;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -482,6 +507,7 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Format camelCase clause name to UPPER CASE.
|
||||
* @param string
|
||||
@@ -498,6 +524,7 @@ class DibiFluent extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function __clone()
|
||||
{
|
||||
// remove references
|
||||
|
@@ -2,10 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Lazy cached storage.
|
||||
*
|
||||
@@ -24,6 +29,7 @@ abstract class DibiHashMapBase
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function setCallback($callback)
|
||||
{
|
||||
if (!is_callable($callback)) {
|
||||
@@ -34,6 +40,7 @@ abstract class DibiHashMapBase
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function getCallback()
|
||||
{
|
||||
return $this->callback;
|
||||
@@ -42,6 +49,7 @@ abstract class DibiHashMapBase
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Lazy cached storage.
|
||||
*
|
||||
@@ -60,6 +68,7 @@ final class DibiHashMap extends DibiHashMapBase
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function __get($nm)
|
||||
{
|
||||
if ($nm == '') {
|
||||
|
@@ -2,15 +2,19 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* SQL literal value.
|
||||
*
|
||||
* @author David Grudl
|
||||
* @package dibi
|
||||
*/
|
||||
class DibiLiteral extends DibiObject
|
||||
{
|
||||
@@ -24,6 +28,7 @@ class DibiLiteral extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
|
@@ -2,10 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* DibiObject is the ultimate ancestor of all instantiable classes.
|
||||
*
|
||||
@@ -53,6 +58,7 @@ abstract class DibiObject
|
||||
private static $extMethods;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the name of the class of this object.
|
||||
* @return string
|
||||
@@ -63,6 +69,7 @@ abstract class DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Access to reflection.
|
||||
* @return \ReflectionObject
|
||||
@@ -73,6 +80,7 @@ abstract class DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Call to undefined method.
|
||||
* @param string method name
|
||||
@@ -117,6 +125,7 @@ abstract class DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Call to undefined static method.
|
||||
* @param string method name (in lower case!)
|
||||
@@ -131,6 +140,7 @@ abstract class DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Adding method to class.
|
||||
* @param string method name
|
||||
@@ -148,9 +158,7 @@ abstract class DibiObject
|
||||
self::$extMethods[$pair[1]][''] = NULL;
|
||||
}
|
||||
}
|
||||
if ($name === NULL) {
|
||||
return NULL;
|
||||
}
|
||||
if ($name === NULL) return NULL;
|
||||
}
|
||||
|
||||
$name = strtolower($name);
|
||||
@@ -194,13 +202,14 @@ abstract class DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns property value. Do not call directly.
|
||||
* @param string property name
|
||||
* @return mixed property value
|
||||
* @throws \LogicException if the property is not defined.
|
||||
*/
|
||||
public function & __get($name)
|
||||
public function &__get($name)
|
||||
{
|
||||
$class = get_class($this);
|
||||
|
||||
@@ -213,8 +222,8 @@ abstract class DibiObject
|
||||
$m = 'get' . $name;
|
||||
if (self::hasAccessor($class, $m)) {
|
||||
// ampersands:
|
||||
// - uses & __get() because declaration should be forward compatible (e.g. with Nette\Web\Html)
|
||||
// - doesn't call & $this->$m because user could bypass property setter by: $x = & $obj->property; $x = 'new value';
|
||||
// - uses &__get() because declaration should be forward compatible (e.g. with Nette\Web\Html)
|
||||
// - doesn't call &$this->$m because user could bypass property setter by: $x = & $obj->property; $x = 'new value';
|
||||
$val = $this->$m();
|
||||
return $val;
|
||||
}
|
||||
@@ -230,6 +239,7 @@ abstract class DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Sets value of a property. Do not call directly.
|
||||
* @param string property name
|
||||
@@ -264,6 +274,7 @@ abstract class DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Is property defined?
|
||||
* @param string property name
|
||||
@@ -276,6 +287,7 @@ abstract class DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Access to undeclared property.
|
||||
* @param string property name
|
||||
@@ -289,6 +301,7 @@ abstract class DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Has property an accessor?
|
||||
* @param string class name
|
||||
|
@@ -2,10 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* dibi result set.
|
||||
*
|
||||
@@ -49,13 +54,11 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
/** @var string returned object class */
|
||||
private $rowClass = 'DibiRow';
|
||||
|
||||
/** @var Callback returned object factory*/
|
||||
private $rowFactory;
|
||||
|
||||
/** @var array format */
|
||||
private $formats = array();
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param IDibiResultDriver
|
||||
*/
|
||||
@@ -66,6 +69,7 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
@@ -75,6 +79,7 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Frees the resources allocated for this result set.
|
||||
* @return void
|
||||
@@ -88,6 +93,7 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Safe access to property $driver.
|
||||
* @return IDibiResultDriver
|
||||
@@ -103,9 +109,11 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* rows ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Moves cursor position without fetching row.
|
||||
* @param int the 0-based cursor pos to seek to
|
||||
@@ -118,6 +126,7 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Required by the Countable interface.
|
||||
* @return int
|
||||
@@ -128,6 +137,7 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the number of rows in a result set.
|
||||
* @return int
|
||||
@@ -138,23 +148,41 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the number of rows in a result set. Alias for getRowCount().
|
||||
* @deprecated
|
||||
*/
|
||||
final public function rowCount()
|
||||
{
|
||||
trigger_error(__METHOD__ . '() is deprecated; use count($res) or $res->getRowCount() instead.', E_USER_WARNING);
|
||||
return $this->getResultDriver()->getRowCount();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Required by the IteratorAggregate interface.
|
||||
* @return DibiResultIterator
|
||||
*/
|
||||
final public function getIterator()
|
||||
{
|
||||
if (func_num_args()) {
|
||||
trigger_error(__METHOD__ . ' arguments $offset & $limit have been dropped; use SQL clauses instead.', E_USER_WARNING);
|
||||
}
|
||||
return new DibiResultIterator($this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* fetching rows ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Set fetched object class. This class should extend the DibiRow class.
|
||||
* @param string
|
||||
* @return self
|
||||
* @return DibiResult provides a fluent interface
|
||||
*/
|
||||
public function setRowClass($class)
|
||||
{
|
||||
@@ -163,6 +191,7 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns fetched object class name.
|
||||
* @return string
|
||||
@@ -173,17 +202,6 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Set a factory to create fetched object instances. These should extend the DibiRow class.
|
||||
* @param callback
|
||||
* @return self
|
||||
*/
|
||||
public function setRowFactory($callback)
|
||||
{
|
||||
$this->rowFactory = $callback;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Fetches the row at current position, process optional type conversion.
|
||||
@@ -198,15 +216,14 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
$this->fetched = TRUE;
|
||||
$this->normalize($row);
|
||||
if ($this->rowFactory) {
|
||||
return call_user_func($this->rowFactory, $row);
|
||||
} elseif ($this->rowClass) {
|
||||
if ($this->rowClass) {
|
||||
$row = new $this->rowClass($row);
|
||||
}
|
||||
return $row;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Like fetch(), but returns only first field.
|
||||
* @return mixed value on success, FALSE if no next record
|
||||
@@ -223,26 +240,23 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches all records from table.
|
||||
* @param int offset
|
||||
* @param int limit
|
||||
* @return DibiRow[]
|
||||
* @return array of DibiRow
|
||||
*/
|
||||
final public function fetchAll($offset = NULL, $limit = NULL)
|
||||
{
|
||||
$limit = $limit === NULL ? -1 : (int) $limit;
|
||||
$this->seek((int) $offset);
|
||||
$row = $this->fetch();
|
||||
if (!$row) {
|
||||
return array(); // empty result set
|
||||
}
|
||||
if (!$row) return array(); // empty result set
|
||||
|
||||
$data = array();
|
||||
do {
|
||||
if ($limit === 0) {
|
||||
break;
|
||||
}
|
||||
if ($limit === 0) break;
|
||||
$limit--;
|
||||
$data[] = $row;
|
||||
} while ($row = $this->fetch());
|
||||
@@ -251,6 +265,7 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches all records from table and returns associative tree.
|
||||
* Examples:
|
||||
@@ -270,9 +285,7 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
|
||||
$this->seek(0);
|
||||
$row = $this->fetch();
|
||||
if (!$row) {
|
||||
return array(); // empty result set
|
||||
}
|
||||
if (!$row) return array(); // empty result set
|
||||
|
||||
$data = NULL;
|
||||
$assoc = preg_split('#(\[\]|->|=|\|)#', $assoc, NULL, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
|
||||
@@ -331,6 +344,7 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
@@ -338,9 +352,7 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
{
|
||||
$this->seek(0);
|
||||
$row = $this->fetch();
|
||||
if (!$row) {
|
||||
return array(); // empty result set
|
||||
}
|
||||
if (!$row) return array(); // empty result set
|
||||
|
||||
$data = NULL;
|
||||
$assoc = explode(',', $assoc);
|
||||
@@ -405,6 +417,7 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Fetches all records from table like $key => $value pairs.
|
||||
* @param string associative key
|
||||
@@ -416,9 +429,7 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
{
|
||||
$this->seek(0);
|
||||
$row = $this->fetch();
|
||||
if (!$row) {
|
||||
return array(); // empty result set
|
||||
}
|
||||
if (!$row) return array(); // empty result set
|
||||
|
||||
$data = array();
|
||||
|
||||
@@ -457,16 +468,18 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
do {
|
||||
$data[ (string) $row[$key] ] = $row[$value];
|
||||
$data[ $row[$key] ] = $row[$value];
|
||||
} while ($row = $this->fetch());
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* column types ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Autodetect column types.
|
||||
* @return void
|
||||
@@ -482,6 +495,7 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Converts values to specified type and format.
|
||||
* @param array
|
||||
@@ -500,15 +514,26 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
$row[$key] = is_float($tmp = $value * 1) ? $value : $tmp;
|
||||
|
||||
} elseif ($type === dibi::FLOAT) {
|
||||
$row[$key] = ltrim((string) ($tmp = (float) $value), '0') === ltrim(rtrim(rtrim($value, '0'), '.'), '0') ? $tmp : $value;
|
||||
$row[$key] = (string) ($tmp = (float) $value) === $value ? $tmp : $value;
|
||||
|
||||
} elseif ($type === dibi::BOOL) {
|
||||
$row[$key] = ((bool) $value) && $value !== 'f' && $value !== 'F';
|
||||
|
||||
} elseif ($type === dibi::DATE || $type === dibi::DATETIME) {
|
||||
if ((int) $value !== 0 || substr((string) $value, 0, 3) === '00:') { // '', NULL, FALSE, '0000-00-00', ...
|
||||
if ((int) $value === 0) { // '', NULL, FALSE, '0000-00-00', ...
|
||||
|
||||
} elseif (empty($this->formats[$type])) { // return DateTime object (default)
|
||||
$row[$key] = new DibiDateTime(is_numeric($value) ? date('Y-m-d H:i:s', $value) : $value);
|
||||
|
||||
} elseif ($this->formats[$type] === 'U') { // return timestamp
|
||||
$row[$key] = is_numeric($value) ? (int) $value : strtotime($value);
|
||||
|
||||
} elseif (is_numeric($value)) { // formatted date
|
||||
$row[$key] = date($this->formats[$type], $value);
|
||||
|
||||
} else {
|
||||
$value = new DibiDateTime($value);
|
||||
$row[$key] = empty($this->formats[$type]) ? $value : $value->format($this->formats[$type]);
|
||||
$row[$key] = $value->format($this->formats[$type]);
|
||||
}
|
||||
|
||||
} elseif ($type === dibi::BINARY) {
|
||||
@@ -518,11 +543,12 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Define column type.
|
||||
* @param string column
|
||||
* @param string type (use constant Dibi::*)
|
||||
* @return self
|
||||
* @return DibiResult provides a fluent interface
|
||||
*/
|
||||
final public function setType($col, $type)
|
||||
{
|
||||
@@ -531,6 +557,7 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns column type.
|
||||
* @return string
|
||||
@@ -541,11 +568,12 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Sets data format.
|
||||
* @param string type (use constant Dibi::*)
|
||||
* @param string format
|
||||
* @return self
|
||||
* @return DibiResult provides a fluent interface
|
||||
*/
|
||||
final public function setFormat($type, $format)
|
||||
{
|
||||
@@ -554,6 +582,7 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns data format.
|
||||
* @return string
|
||||
@@ -564,9 +593,11 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* meta info ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns a meta information about the current result set.
|
||||
* @return DibiResultInfo
|
||||
@@ -580,6 +611,7 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
@@ -589,74 +621,52 @@ class DibiResult extends DibiObject implements IDataSource
|
||||
}
|
||||
|
||||
|
||||
|
||||
/** @deprecated */
|
||||
public function getColumnNames($fullNames = FALSE)
|
||||
{
|
||||
trigger_error(__METHOD__ . '() is deprecated; use $res->getInfo()->getColumnNames() instead.', E_USER_WARNING);
|
||||
return $this->getInfo()->getColumnNames($fullNames);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* misc tools ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Displays complete result set as HTML or text table for debug purposes.
|
||||
* Displays complete result set as HTML table for debug purposes.
|
||||
* @return void
|
||||
*/
|
||||
final public function dump()
|
||||
{
|
||||
$i = 0;
|
||||
$this->seek(0);
|
||||
if (PHP_SAPI === 'cli') {
|
||||
$hasColors = (substr(getenv('TERM'), 0, 5) === 'xterm');
|
||||
$maxLen = 0;
|
||||
while ($row = $this->fetch()) {
|
||||
if ($i === 0) {
|
||||
foreach ($row as $col => $foo) {
|
||||
$len = mb_strlen($col);
|
||||
$maxLen = max($len, $maxLen);
|
||||
}
|
||||
}
|
||||
|
||||
if ($hasColors) {
|
||||
echo "\033[1;37m#row: $i\033[0m\n";
|
||||
} else {
|
||||
echo "#row: $i\n";
|
||||
}
|
||||
|
||||
foreach ($row as $col => $val) {
|
||||
$spaces = $maxLen - mb_strlen($col) + 2;
|
||||
echo "$col" . str_repeat(" ", $spaces) . "$val\n";
|
||||
}
|
||||
|
||||
echo "\n";
|
||||
$i++;
|
||||
}
|
||||
|
||||
while ($row = $this->fetch()) {
|
||||
if ($i === 0) {
|
||||
echo "empty result set\n";
|
||||
}
|
||||
echo "\n";
|
||||
echo "\n<table class=\"dump\">\n<thead>\n\t<tr>\n\t\t<th>#row</th>\n";
|
||||
|
||||
foreach ($row as $col => $foo) {
|
||||
echo "\t\t<th>" . htmlSpecialChars($col) . "</th>\n";
|
||||
}
|
||||
|
||||
echo "\t</tr>\n</thead>\n<tbody>\n";
|
||||
}
|
||||
|
||||
echo "\t<tr>\n\t\t<th>", $i, "</th>\n";
|
||||
foreach ($row as $col) {
|
||||
//if (is_object($col)) $col = $col->__toString();
|
||||
echo "\t\t<td>", htmlSpecialChars($col), "</td>\n";
|
||||
}
|
||||
echo "\t</tr>\n";
|
||||
$i++;
|
||||
}
|
||||
|
||||
if ($i === 0) {
|
||||
echo '<p><em>empty result set</em></p>';
|
||||
} else {
|
||||
while ($row = $this->fetch()) {
|
||||
if ($i === 0) {
|
||||
echo "\n<table class=\"dump\">\n<thead>\n\t<tr>\n\t\t<th>#row</th>\n";
|
||||
|
||||
foreach ($row as $col => $foo) {
|
||||
echo "\t\t<th>" . htmlSpecialChars($col) . "</th>\n";
|
||||
}
|
||||
|
||||
echo "\t</tr>\n</thead>\n<tbody>\n";
|
||||
}
|
||||
|
||||
echo "\t<tr>\n\t\t<th>", $i, "</th>\n";
|
||||
foreach ($row as $col) {
|
||||
//if (is_object($col)) $col = $col->__toString();
|
||||
echo "\t\t<td>", htmlSpecialChars($col), "</td>\n";
|
||||
}
|
||||
echo "\t</tr>\n";
|
||||
$i++;
|
||||
}
|
||||
|
||||
if ($i === 0) {
|
||||
echo '<p><em>empty result set</em></p>';
|
||||
} else {
|
||||
echo "</tbody>\n</table>\n";
|
||||
}
|
||||
echo "</tbody>\n</table>\n";
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -2,10 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* External result set iterator.
|
||||
*
|
||||
@@ -42,6 +47,7 @@ class DibiResultIterator implements Iterator, Countable
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Rewinds the iterator to the first element.
|
||||
* @return void
|
||||
@@ -54,6 +60,7 @@ class DibiResultIterator implements Iterator, Countable
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the key of the current element.
|
||||
* @return mixed
|
||||
@@ -64,6 +71,7 @@ class DibiResultIterator implements Iterator, Countable
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the current element.
|
||||
* @return mixed
|
||||
@@ -74,6 +82,7 @@ class DibiResultIterator implements Iterator, Countable
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Moves forward to next element.
|
||||
* @return void
|
||||
@@ -85,6 +94,7 @@ class DibiResultIterator implements Iterator, Countable
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Checks if there is a current element after calls to rewind() or next().
|
||||
* @return bool
|
||||
@@ -95,6 +105,7 @@ class DibiResultIterator implements Iterator, Countable
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Required by the Countable interface.
|
||||
* @return int
|
||||
|
@@ -2,10 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Result set single row.
|
||||
*
|
||||
@@ -17,18 +22,18 @@ class DibiRow implements ArrayAccess, IteratorAggregate, Countable
|
||||
|
||||
public function __construct($arr)
|
||||
{
|
||||
foreach ($arr as $k => $v) {
|
||||
$this->$k = $v;
|
||||
}
|
||||
foreach ($arr as $k => $v) $this->$k = $v;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function toArray()
|
||||
{
|
||||
return (array) $this;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Converts value to DateTime object.
|
||||
* @param string key
|
||||
@@ -39,48 +44,97 @@ class DibiRow implements ArrayAccess, IteratorAggregate, Countable
|
||||
{
|
||||
$time = $this[$key];
|
||||
if (!$time instanceof DibiDateTime) {
|
||||
if ((int) $time === 0 && substr((string) $time, 0, 3) !== '00:') { // '', NULL, FALSE, '0000-00-00', ...
|
||||
if ((int) $time === 0) { // '', NULL, FALSE, '0000-00-00', ...
|
||||
return NULL;
|
||||
}
|
||||
$time = new DibiDateTime($time);
|
||||
$time = new DibiDateTime(is_numeric($time) ? date('Y-m-d H:i:s', $time) : $time);
|
||||
}
|
||||
return $format === NULL ? $time : $time->format($format);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Converts value to UNIX timestamp.
|
||||
* @param string key
|
||||
* @return int
|
||||
*/
|
||||
public function asTimestamp($key)
|
||||
{
|
||||
trigger_error(__METHOD__ . '() is deprecated.', E_USER_WARNING);
|
||||
$time = $this[$key];
|
||||
return (int) $time === 0 // '', NULL, FALSE, '0000-00-00', ...
|
||||
? NULL
|
||||
: (is_numeric($time) ? (int) $time : strtotime($time));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Converts value to boolean.
|
||||
* @param string key
|
||||
* @return mixed
|
||||
*/
|
||||
public function asBool($key)
|
||||
{
|
||||
trigger_error(__METHOD__ . '() is deprecated.', E_USER_WARNING);
|
||||
return $this[$key];
|
||||
}
|
||||
|
||||
|
||||
|
||||
/** @deprecated */
|
||||
public function asDate($key, $format = NULL)
|
||||
{
|
||||
trigger_error(__METHOD__ . '() is deprecated.', E_USER_WARNING);
|
||||
if ($format === NULL) {
|
||||
return $this->asTimestamp($key);
|
||||
} else {
|
||||
return $this->asDateTime($key, $format === TRUE ? NULL : $format);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* interfaces ArrayAccess, Countable & IteratorAggregate ****************d*g**/
|
||||
|
||||
|
||||
|
||||
final public function count()
|
||||
{
|
||||
return count((array) $this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
final public function getIterator()
|
||||
{
|
||||
return new ArrayIterator($this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
final public function offsetSet($nm, $val)
|
||||
{
|
||||
$this->$nm = $val;
|
||||
}
|
||||
|
||||
|
||||
|
||||
final public function offsetGet($nm)
|
||||
{
|
||||
return $this->$nm;
|
||||
}
|
||||
|
||||
|
||||
|
||||
final public function offsetExists($nm)
|
||||
{
|
||||
return isset($this->$nm);
|
||||
}
|
||||
|
||||
|
||||
|
||||
final public function offsetUnset($nm)
|
||||
{
|
||||
unset($this->$nm);
|
||||
|
@@ -2,10 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* dibi SQL translator.
|
||||
*
|
||||
@@ -48,14 +53,14 @@ final class DibiTranslator extends DibiObject
|
||||
private $identifiers;
|
||||
|
||||
|
||||
|
||||
public function __construct(DibiConnection $connection)
|
||||
{
|
||||
$this->connection = $connection;
|
||||
$this->driver = $connection->getDriver();
|
||||
$this->identifiers = new DibiHashMap(array($this, 'delimite'));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Generates SQL.
|
||||
* @param array
|
||||
@@ -64,6 +69,9 @@ final class DibiTranslator extends DibiObject
|
||||
*/
|
||||
public function translate(array $args)
|
||||
{
|
||||
$this->identifiers = new DibiHashMap(array($this, 'delimite'));
|
||||
$this->driver = $this->connection->getDriver();
|
||||
|
||||
$args = array_values($args);
|
||||
while (count($args) === 1 && is_array($args[0])) { // implicit array expansion
|
||||
$args = array_values($args[0]);
|
||||
@@ -86,7 +94,8 @@ final class DibiTranslator extends DibiObject
|
||||
|
||||
// iterate
|
||||
$sql = array();
|
||||
while ($cursor < count($this->args)) {
|
||||
while ($cursor < count($this->args))
|
||||
{
|
||||
$arg = $this->args[$cursor];
|
||||
$cursor++;
|
||||
|
||||
@@ -117,9 +126,7 @@ final class DibiTranslator extends DibiObject
|
||||
array($this, 'cb'),
|
||||
substr($arg, $toSkip)
|
||||
);
|
||||
if (preg_last_error()) {
|
||||
throw new DibiPcreException;
|
||||
}
|
||||
if (preg_last_error()) throw new DibiPcreException;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -141,9 +148,7 @@ final class DibiTranslator extends DibiObject
|
||||
$commandIns = $commandIns === 'INSERT' || $commandIns === 'REPLAC';
|
||||
$sql[] = $this->formatValue($arg, $commandIns ? 'v' : 'a');
|
||||
} else {
|
||||
if ($lastArr === $cursor - 1) {
|
||||
$sql[] = ',';
|
||||
}
|
||||
if ($lastArr === $cursor - 1) $sql[] = ',';
|
||||
$sql[] = $this->formatValue($arg, $commandIns ? 'l' : 'a');
|
||||
}
|
||||
$lastArr = $cursor;
|
||||
@@ -156,9 +161,7 @@ final class DibiTranslator extends DibiObject
|
||||
} // while
|
||||
|
||||
|
||||
if ($comment) {
|
||||
$sql[] = "*/";
|
||||
}
|
||||
if ($comment) $sql[] = "*/";
|
||||
|
||||
$sql = implode(' ', $sql);
|
||||
|
||||
@@ -175,6 +178,7 @@ final class DibiTranslator extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Apply modifier to single value.
|
||||
* @param mixed
|
||||
@@ -195,235 +199,231 @@ final class DibiTranslator extends DibiObject
|
||||
if (is_array($value)) {
|
||||
$vx = $kx = array();
|
||||
switch ($modifier) {
|
||||
case 'and':
|
||||
case 'or': // key=val AND key IS NULL AND ...
|
||||
if (empty($value)) {
|
||||
return '1=1';
|
||||
}
|
||||
case 'and':
|
||||
case 'or': // key=val AND key IS NULL AND ...
|
||||
if (empty($value)) {
|
||||
return '1=1';
|
||||
}
|
||||
|
||||
foreach ($value as $k => $v) {
|
||||
if (is_string($k)) {
|
||||
$pair = explode('%', $k, 2); // split into identifier & modifier
|
||||
$k = $this->identifiers->{$pair[0]} . ' ';
|
||||
if (!isset($pair[1])) {
|
||||
$v = $this->formatValue($v, FALSE);
|
||||
$vx[] = $k . ($v === 'NULL' ? 'IS ' : '= ') . $v;
|
||||
foreach ($value as $k => $v) {
|
||||
if (is_string($k)) {
|
||||
$pair = explode('%', $k, 2); // split into identifier & modifier
|
||||
$k = $this->identifiers->{$pair[0]} . ' ';
|
||||
if (!isset($pair[1])) {
|
||||
$v = $this->formatValue($v, FALSE);
|
||||
$vx[] = $k . ($v === 'NULL' ? 'IS ' : '= ') . $v;
|
||||
|
||||
} elseif ($pair[1] === 'ex') { // TODO: this will be removed
|
||||
$vx[] = $k . $this->formatValue($v, 'ex');
|
||||
} elseif ($pair[1] === 'ex') { // TODO: this will be removed
|
||||
$vx[] = $k . $this->formatValue($v, 'ex');
|
||||
|
||||
} else {
|
||||
$v = $this->formatValue($v, $pair[1]);
|
||||
if ($pair[1] === 'l' || $pair[1] === 'in') {
|
||||
$op = 'IN ';
|
||||
} elseif (strpos($pair[1], 'like') !== FALSE) {
|
||||
$op = 'LIKE ';
|
||||
} elseif ($v === 'NULL') {
|
||||
$op = 'IS ';
|
||||
} else {
|
||||
$v = $this->formatValue($v, $pair[1]);
|
||||
if ($pair[1] === 'l' || $pair[1] === 'in') {
|
||||
$op = 'IN ';
|
||||
} elseif (strpos($pair[1], 'like') !== FALSE) {
|
||||
$op = 'LIKE ';
|
||||
} elseif ($v === 'NULL') {
|
||||
$op = 'IS ';
|
||||
} else {
|
||||
$op = '= ';
|
||||
}
|
||||
$vx[] = $k . $op . $v;
|
||||
$op = '= ';
|
||||
}
|
||||
|
||||
} else {
|
||||
$vx[] = $this->formatValue($v, 'ex');
|
||||
$vx[] = $k . $op . $v;
|
||||
}
|
||||
|
||||
} else {
|
||||
$vx[] = $this->formatValue($v, 'ex');
|
||||
}
|
||||
return '(' . implode(') ' . strtoupper($modifier) . ' (', $vx) . ')';
|
||||
}
|
||||
return '(' . implode(') ' . strtoupper($modifier) . ' (', $vx) . ')';
|
||||
|
||||
case 'n': // key, key, ... identifier names
|
||||
foreach ($value as $k => $v) {
|
||||
if (is_string($k)) {
|
||||
$vx[] = $this->identifiers->$k . (empty($v) ? '' : ' AS ' . $this->identifiers->$v);
|
||||
} else {
|
||||
$pair = explode('%', $v, 2); // split into identifier & modifier
|
||||
$vx[] = $this->identifiers->{$pair[0]};
|
||||
}
|
||||
case 'n': // key, key, ... identifier names
|
||||
foreach ($value as $k => $v) {
|
||||
if (is_string($k)) {
|
||||
$vx[] = $this->identifiers->$k . (empty($v) ? '' : ' AS ' . $this->identifiers->$v);
|
||||
} else {
|
||||
$pair = explode('%', $v, 2); // split into identifier & modifier
|
||||
$vx[] = $this->identifiers->{$pair[0]};
|
||||
}
|
||||
return implode(', ', $vx);
|
||||
}
|
||||
return implode(', ', $vx);
|
||||
|
||||
|
||||
case 'a': // key=val, key=val, ...
|
||||
foreach ($value as $k => $v) {
|
||||
$pair = explode('%', $k, 2); // split into identifier & modifier
|
||||
$vx[] = $this->identifiers->{$pair[0]} . '='
|
||||
. $this->formatValue($v, isset($pair[1]) ? $pair[1] : (is_array($v) ? 'ex' : FALSE));
|
||||
}
|
||||
return implode(', ', $vx);
|
||||
case 'a': // key=val, key=val, ...
|
||||
foreach ($value as $k => $v) {
|
||||
$pair = explode('%', $k, 2); // split into identifier & modifier
|
||||
$vx[] = $this->identifiers->{$pair[0]} . '='
|
||||
. $this->formatValue($v, isset($pair[1]) ? $pair[1] : (is_array($v) ? 'ex' : FALSE));
|
||||
}
|
||||
return implode(', ', $vx);
|
||||
|
||||
|
||||
case 'in':// replaces scalar %in modifier!
|
||||
case 'l': // (val, val, ...)
|
||||
foreach ($value as $k => $v) {
|
||||
$pair = explode('%', $k, 2); // split into identifier & modifier
|
||||
$vx[] = $this->formatValue($v, isset($pair[1]) ? $pair[1] : (is_array($v) ? 'ex' : FALSE));
|
||||
}
|
||||
return '(' . (($vx || $modifier === 'l') ? implode(', ', $vx) : 'NULL') . ')';
|
||||
case 'in':// replaces scalar %in modifier!
|
||||
case 'l': // (val, val, ...)
|
||||
foreach ($value as $k => $v) {
|
||||
$pair = explode('%', $k, 2); // split into identifier & modifier
|
||||
$vx[] = $this->formatValue($v, isset($pair[1]) ? $pair[1] : (is_array($v) ? 'ex' : FALSE));
|
||||
}
|
||||
return '(' . (($vx || $modifier === 'l') ? implode(', ', $vx) : 'NULL') . ')';
|
||||
|
||||
|
||||
case 'v': // (key, key, ...) VALUES (val, val, ...)
|
||||
foreach ($value as $k => $v) {
|
||||
$pair = explode('%', $k, 2); // split into identifier & modifier
|
||||
$kx[] = $this->identifiers->{$pair[0]};
|
||||
$vx[] = $this->formatValue($v, isset($pair[1]) ? $pair[1] : (is_array($v) ? 'ex' : FALSE));
|
||||
}
|
||||
return '(' . implode(', ', $kx) . ') VALUES (' . implode(', ', $vx) . ')';
|
||||
case 'v': // (key, key, ...) VALUES (val, val, ...)
|
||||
foreach ($value as $k => $v) {
|
||||
$pair = explode('%', $k, 2); // split into identifier & modifier
|
||||
$kx[] = $this->identifiers->{$pair[0]};
|
||||
$vx[] = $this->formatValue($v, isset($pair[1]) ? $pair[1] : (is_array($v) ? 'ex' : FALSE));
|
||||
}
|
||||
return '(' . implode(', ', $kx) . ') VALUES (' . implode(', ', $vx) . ')';
|
||||
|
||||
case 'm': // (key, key, ...) VALUES (val, val, ...), (val, val, ...), ...
|
||||
foreach ($value as $k => $v) {
|
||||
if (is_array($v)) {
|
||||
if (isset($proto)) {
|
||||
if ($proto !== array_keys($v)) {
|
||||
$this->hasError = TRUE;
|
||||
return '**Multi-insert array "' . $k . '" is different.**';
|
||||
}
|
||||
} else {
|
||||
$proto = array_keys($v);
|
||||
case 'm': // (key, key, ...) VALUES (val, val, ...), (val, val, ...), ...
|
||||
foreach ($value as $k => $v) {
|
||||
if (is_array($v)) {
|
||||
if (isset($proto)) {
|
||||
if ($proto !== array_keys($v)) {
|
||||
$this->hasError = TRUE;
|
||||
return '**Multi-insert array "' . $k . '" is different.**';
|
||||
}
|
||||
} else {
|
||||
$this->hasError = TRUE;
|
||||
return '**Unexpected type ' . gettype($v) . '**';
|
||||
}
|
||||
|
||||
$pair = explode('%', $k, 2); // split into identifier & modifier
|
||||
$kx[] = $this->identifiers->{$pair[0]};
|
||||
foreach ($v as $k2 => $v2) {
|
||||
$vx[$k2][] = $this->formatValue($v2, isset($pair[1]) ? $pair[1] : (is_array($v2) ? 'ex' : FALSE));
|
||||
$proto = array_keys($v);
|
||||
}
|
||||
} else {
|
||||
$this->hasError = TRUE;
|
||||
return '**Unexpected type ' . gettype($v) . '**';
|
||||
}
|
||||
foreach ($vx as $k => $v) {
|
||||
$vx[$k] = '(' . implode(', ', $v) . ')';
|
||||
}
|
||||
return '(' . implode(', ', $kx) . ') VALUES ' . implode(', ', $vx);
|
||||
|
||||
case 'by': // key ASC, key DESC
|
||||
foreach ($value as $k => $v) {
|
||||
if (is_array($v)) {
|
||||
$vx[] = $this->formatValue($v, 'ex');
|
||||
} elseif (is_string($k)) {
|
||||
$v = (is_string($v) && strncasecmp($v, 'd', 1)) || $v > 0 ? 'ASC' : 'DESC';
|
||||
$vx[] = $this->identifiers->$k . ' ' . $v;
|
||||
} else {
|
||||
$vx[] = $this->identifiers->$v;
|
||||
}
|
||||
$pair = explode('%', $k, 2); // split into identifier & modifier
|
||||
$kx[] = $this->identifiers->{$pair[0]};
|
||||
foreach ($v as $k2 => $v2) {
|
||||
$vx[$k2][] = $this->formatValue($v2, isset($pair[1]) ? $pair[1] : (is_array($v2) ? 'ex' : FALSE));
|
||||
}
|
||||
return implode(', ', $vx);
|
||||
}
|
||||
foreach ($vx as $k => $v) {
|
||||
$vx[$k] = '(' . implode(', ', $v) . ')';
|
||||
}
|
||||
return '(' . implode(', ', $kx) . ') VALUES ' . implode(', ', $vx);
|
||||
|
||||
case 'ex':
|
||||
case 'sql':
|
||||
$translator = new self($this->connection);
|
||||
return $translator->translate($value);
|
||||
|
||||
default: // value, value, value - all with the same modifier
|
||||
foreach ($value as $v) {
|
||||
$vx[] = $this->formatValue($v, $modifier);
|
||||
case 'by': // key ASC, key DESC
|
||||
foreach ($value as $k => $v) {
|
||||
if (is_array($v)) {
|
||||
$vx[] = $this->formatValue($v, 'ex');
|
||||
} elseif (is_string($k)) {
|
||||
$v = (is_string($v) && strncasecmp($v, 'd', 1)) || $v > 0 ? 'ASC' : 'DESC';
|
||||
$vx[] = $this->identifiers->$k . ' ' . $v;
|
||||
} else {
|
||||
$vx[] = $this->identifiers->$v;
|
||||
}
|
||||
return implode(', ', $vx);
|
||||
}
|
||||
return implode(', ', $vx);
|
||||
|
||||
case 'ex':
|
||||
case 'sql':
|
||||
$translator = new self($this->connection);
|
||||
return $translator->translate($value);
|
||||
|
||||
default: // value, value, value - all with the same modifier
|
||||
foreach ($value as $v) {
|
||||
$vx[] = $this->formatValue($v, $modifier);
|
||||
}
|
||||
return implode(', ', $vx);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 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)) { // array is already processed
|
||||
$this->hasError = TRUE;
|
||||
return '**Unexpected type ' . gettype($value) . '**';
|
||||
}
|
||||
|
||||
switch ($modifier) {
|
||||
case 's': // string
|
||||
case 'bin':// binary
|
||||
case 'b': // boolean
|
||||
return $value === NULL ? 'NULL' : $this->driver->escape($value, $modifier);
|
||||
case 's': // string
|
||||
case 'bin':// binary
|
||||
case 'b': // boolean
|
||||
return $value === NULL ? 'NULL' : $this->driver->escape($value, $modifier);
|
||||
|
||||
case 'sN': // string or NULL
|
||||
case 'sn':
|
||||
return $value == '' ? 'NULL' : $this->driver->escape($value, dibi::TEXT); // notice two equal signs
|
||||
case 'sN': // string or NULL
|
||||
case 'sn':
|
||||
return $value == '' ? 'NULL' : $this->driver->escape($value, dibi::TEXT); // notice two equal signs
|
||||
|
||||
case 'iN': // signed int or NULL
|
||||
case 'in': // deprecated
|
||||
if ($value == '') {
|
||||
$value = NULL;
|
||||
}
|
||||
// intentionally break omitted
|
||||
case 'iN': // signed int or NULL
|
||||
case 'in': // deprecated
|
||||
if ($value == '') $value = NULL;
|
||||
// intentionally break omitted
|
||||
|
||||
case 'i': // signed int
|
||||
case 'u': // unsigned int, ignored
|
||||
// support for long numbers - keep them unchanged
|
||||
if (is_string($value) && preg_match('#[+-]?\d++(e\d+)?\z#A', $value)) {
|
||||
return $value;
|
||||
} else {
|
||||
return $value === NULL ? 'NULL' : (string) (int) ($value + 0);
|
||||
}
|
||||
|
||||
case 'f': // float
|
||||
// support for extreme numbers - keep them unchanged
|
||||
if (is_string($value) && is_numeric($value) && strpos($value, 'x') === FALSE) {
|
||||
return $value; // something like -9E-005 is accepted by SQL, HEX values are not
|
||||
} else {
|
||||
return $value === NULL ? 'NULL' : rtrim(rtrim(number_format($value + 0, 10, '.', ''), '0'), '.');
|
||||
}
|
||||
|
||||
case 'd': // date
|
||||
case 't': // datetime
|
||||
if ($value === NULL) {
|
||||
return 'NULL';
|
||||
} else {
|
||||
if (is_numeric($value)) {
|
||||
$value = (int) $value; // timestamp
|
||||
|
||||
} elseif (is_string($value)) {
|
||||
$value = new DateTime($value);
|
||||
}
|
||||
return $this->driver->escape($value, $modifier);
|
||||
}
|
||||
|
||||
case 'by':
|
||||
case 'n': // identifier name
|
||||
return $this->identifiers->$value;
|
||||
|
||||
case 'ex':
|
||||
case 'sql': // preserve as dibi-SQL (TODO: leave only %ex)
|
||||
$value = (string) $value;
|
||||
// speed-up - is regexp required?
|
||||
$toSkip = strcspn($value, '`[\'":');
|
||||
if (strlen($value) !== $toSkip) {
|
||||
$value = substr($value, 0, $toSkip)
|
||||
. preg_replace_callback(
|
||||
'/(?=[`[\'":])(?:`(.+?)`|\[(.+?)\]|(\')((?:\'\'|[^\'])*)\'|(")((?:""|[^"])*)"|(\'|")|:(\S*?:)([a-zA-Z0-9._]?))/s',
|
||||
array($this, 'cb'),
|
||||
substr($value, $toSkip)
|
||||
);
|
||||
if (preg_last_error()) {
|
||||
throw new DibiPcreException;
|
||||
}
|
||||
}
|
||||
case 'i': // signed int
|
||||
case 'u': // unsigned int, ignored
|
||||
// support for long numbers - keep them unchanged
|
||||
if (is_string($value) && preg_match('#[+-]?\d++(e\d+)?\z#A', $value)) {
|
||||
return $value;
|
||||
} else {
|
||||
return $value === NULL ? 'NULL' : (string) (int) ($value + 0);
|
||||
}
|
||||
|
||||
case 'SQL': // preserve as real SQL (TODO: rename to %sql)
|
||||
return (string) $value;
|
||||
case 'f': // float
|
||||
// support for extreme numbers - keep them unchanged
|
||||
if (is_string($value) && is_numeric($value) && strpos($value, 'x') === FALSE) {
|
||||
return $value; // something like -9E-005 is accepted by SQL, HEX values are not
|
||||
} else {
|
||||
return $value === NULL ? 'NULL' : rtrim(rtrim(number_format($value + 0, 10, '.', ''), '0'), '.');
|
||||
}
|
||||
|
||||
case 'like~': // LIKE string%
|
||||
return $this->driver->escapeLike($value, 1);
|
||||
case 'd': // date
|
||||
case 't': // datetime
|
||||
if ($value === NULL) {
|
||||
return 'NULL';
|
||||
} else {
|
||||
if (is_numeric($value)) {
|
||||
$value = (int) $value; // timestamp
|
||||
|
||||
case '~like': // LIKE %string
|
||||
return $this->driver->escapeLike($value, -1);
|
||||
} elseif (is_string($value)) {
|
||||
$value = new DateTime($value);
|
||||
}
|
||||
return $this->driver->escape($value, $modifier);
|
||||
}
|
||||
|
||||
case '~like~': // LIKE %string%
|
||||
return $this->driver->escapeLike($value, 0);
|
||||
case 'by':
|
||||
case 'n': // identifier name
|
||||
return $this->identifiers->$value;
|
||||
|
||||
case 'and':
|
||||
case 'or':
|
||||
case 'a':
|
||||
case 'l':
|
||||
case 'v':
|
||||
$this->hasError = TRUE;
|
||||
return '**Unexpected type ' . gettype($value) . '**';
|
||||
case 'ex':
|
||||
case 'sql': // preserve as dibi-SQL (TODO: leave only %ex)
|
||||
$value = (string) $value;
|
||||
// speed-up - is regexp required?
|
||||
$toSkip = strcspn($value, '`[\'":');
|
||||
if (strlen($value) !== $toSkip) {
|
||||
$value = substr($value, 0, $toSkip)
|
||||
. preg_replace_callback(
|
||||
'/(?=[`[\'":])(?:`(.+?)`|\[(.+?)\]|(\')((?:\'\'|[^\'])*)\'|(")((?:""|[^"])*)"|(\'|")|:(\S*?:)([a-zA-Z0-9._]?))/s',
|
||||
array($this, 'cb'),
|
||||
substr($value, $toSkip)
|
||||
);
|
||||
if (preg_last_error()) throw new DibiPcreException;
|
||||
}
|
||||
return $value;
|
||||
|
||||
default:
|
||||
$this->hasError = TRUE;
|
||||
return "**Unknown or invalid modifier %$modifier**";
|
||||
case 'SQL': // preserve as real SQL (TODO: rename to %sql)
|
||||
return (string) $value;
|
||||
|
||||
case 'like~': // LIKE string%
|
||||
return $this->driver->escapeLike($value, 1);
|
||||
|
||||
case '~like': // LIKE %string
|
||||
return $this->driver->escapeLike($value, -1);
|
||||
|
||||
case '~like~': // LIKE %string%
|
||||
return $this->driver->escapeLike($value, 0);
|
||||
|
||||
case 'and':
|
||||
case 'or':
|
||||
case 'a':
|
||||
case 'l':
|
||||
case 'v':
|
||||
$this->hasError = TRUE;
|
||||
return '**Unexpected type ' . gettype($value) . '**';
|
||||
|
||||
default:
|
||||
$this->hasError = TRUE;
|
||||
return "**Unknown or invalid modifier %$modifier**";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -444,7 +444,7 @@ final class DibiTranslator extends DibiObject
|
||||
} elseif ($value === NULL) {
|
||||
return 'NULL';
|
||||
|
||||
} elseif ($value instanceof DateTime || $value instanceof DateTimeInterface) {
|
||||
} elseif ($value instanceof DateTime) {
|
||||
return $this->driver->escape($value, dibi::DATETIME);
|
||||
|
||||
} elseif ($value instanceof DibiLiteral) {
|
||||
@@ -457,6 +457,7 @@ final class DibiTranslator extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* PREG callback from translate() or formatValue().
|
||||
* @param array
|
||||
@@ -535,16 +536,12 @@ final class DibiTranslator extends DibiObject
|
||||
return '';
|
||||
|
||||
} elseif ($mod === 'lmt') { // apply limit
|
||||
if ($this->args[$cursor] !== NULL) {
|
||||
$this->limit = (int) $this->args[$cursor];
|
||||
}
|
||||
if ($this->args[$cursor] !== NULL) $this->limit = (int) $this->args[$cursor];
|
||||
$cursor++;
|
||||
return '';
|
||||
|
||||
} elseif ($mod === 'ofs') { // apply offset
|
||||
if ($this->args[$cursor] !== NULL) {
|
||||
$this->offset = (int) $this->args[$cursor];
|
||||
}
|
||||
if ($this->args[$cursor] !== NULL) $this->offset = (int) $this->args[$cursor];
|
||||
$cursor++;
|
||||
return '';
|
||||
|
||||
@@ -554,23 +551,21 @@ final class DibiTranslator extends DibiObject
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->comment) {
|
||||
return '...';
|
||||
}
|
||||
if ($this->comment) return '...';
|
||||
|
||||
if ($matches[1]) { // SQL identifiers: `ident`
|
||||
if ($matches[1]) // SQL identifiers: `ident`
|
||||
return $this->identifiers->{$matches[1]};
|
||||
|
||||
} elseif ($matches[2]) { // SQL identifiers: [ident]
|
||||
if ($matches[2]) // SQL identifiers: [ident]
|
||||
return $this->identifiers->{$matches[2]};
|
||||
|
||||
} elseif ($matches[3]) { // SQL strings: '...'
|
||||
if ($matches[3]) // SQL strings: '...'
|
||||
return $this->driver->escape( str_replace("''", "'", $matches[4]), dibi::TEXT);
|
||||
|
||||
} elseif ($matches[5]) { // SQL strings: "..."
|
||||
if ($matches[5]) // SQL strings: "..."
|
||||
return $this->driver->escape( str_replace('""', '"', $matches[6]), dibi::TEXT);
|
||||
|
||||
} elseif ($matches[7]) { // string quote
|
||||
if ($matches[7]) { // string quote
|
||||
$this->hasError = TRUE;
|
||||
return '**Alone quote**';
|
||||
}
|
||||
@@ -585,6 +580,7 @@ final class DibiTranslator extends DibiObject
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Apply substitutions to indentifier and delimites it.
|
||||
* @param string indentifier
|
||||
@@ -596,9 +592,7 @@ final class DibiTranslator extends DibiObject
|
||||
$value = $this->connection->substitute($value);
|
||||
$parts = explode('.', $value);
|
||||
foreach ($parts as & $v) {
|
||||
if ($v !== '*') {
|
||||
$v = $this->driver->escape($v, dibi::IDENTIFIER);
|
||||
}
|
||||
if ($v !== '*') $v = $this->driver->escape($v, dibi::IDENTIFIER);
|
||||
}
|
||||
return implode('.', $parts);
|
||||
}
|
||||
|
@@ -2,10 +2,15 @@
|
||||
|
||||
/**
|
||||
* This file is part of the "dibi" - smart database abstraction layer.
|
||||
*
|
||||
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the file license.txt that was distributed with this source code.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Provides an interface between a dataset and data-aware components.
|
||||
* @package dibi
|
||||
@@ -17,6 +22,7 @@ interface IDataSource extends Countable, IteratorAggregate
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* dibi driver interface.
|
||||
* @package dibi
|
||||
@@ -30,7 +36,7 @@ interface IDibiDriver
|
||||
* @return void
|
||||
* @throws DibiException
|
||||
*/
|
||||
function connect(array & $config);
|
||||
function connect(array &$config);
|
||||
|
||||
/**
|
||||
* Disconnects from a database.
|
||||
@@ -114,13 +120,19 @@ interface IDibiDriver
|
||||
|
||||
/**
|
||||
* Injects LIMIT/OFFSET to the SQL query.
|
||||
* @param string &$sql The SQL query that will be modified.
|
||||
* @param int $limit
|
||||
* @param int $offset
|
||||
* @return void
|
||||
*/
|
||||
function applyLimit(& $sql, $limit, $offset);
|
||||
function applyLimit(&$sql, $limit, $offset);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* dibi result set driver interface.
|
||||
* @package dibi
|
||||
@@ -181,6 +193,9 @@ interface IDibiResultDriver
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* dibi driver reflection.
|
||||
*
|
||||
|
1
examples/.gitignore
vendored
1
examples/.gitignore
vendored
@@ -1,4 +1,3 @@
|
||||
_test.bat
|
||||
ref
|
||||
output
|
||||
log
|
847
examples/Nette/Debugger.php
Normal file
847
examples/Nette/Debugger.php
Normal file
File diff suppressed because one or more lines are too long
@@ -1,6 +1,3 @@
|
||||
Tracy - PHP debugger, see http://tracy.nette.org
|
||||
|
||||
|
||||
Licenses
|
||||
========
|
||||
|
||||
@@ -21,6 +18,7 @@ project or top-level domain, and choose a name that stands on its own merits.
|
||||
If your stuff is good, it will not take long to establish a reputation for yourselves.
|
||||
|
||||
|
||||
|
||||
New BSD License
|
||||
---------------
|
||||
|
||||
@@ -53,6 +51,7 @@ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
|
||||
GNU General Public License
|
||||
--------------------------
|
||||
|
3
examples/Nette/readme.txt
Normal file
3
examples/Nette/readme.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
This file is part of Nette Framework
|
||||
|
||||
For more information please see http://nette.org
|
Binary file not shown.
@@ -4,15 +4,16 @@
|
||||
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/../dibi/dibi.php';
|
||||
require_once 'Nette/Debugger.php';
|
||||
require_once '../dibi/dibi.php';
|
||||
|
||||
|
||||
// connects to SQlite using dibi class
|
||||
echo '<p>Connecting to Sqlite: ';
|
||||
try {
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
));
|
||||
echo 'OK';
|
||||
|
||||
@@ -22,12 +23,14 @@ try {
|
||||
echo "</p>\n";
|
||||
|
||||
|
||||
|
||||
|
||||
// connects to SQlite using DibiConnection object
|
||||
echo '<p>Connecting to Sqlite: ';
|
||||
try {
|
||||
$connection = new DibiConnection(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
));
|
||||
echo 'OK';
|
||||
|
||||
@@ -37,6 +40,8 @@ try {
|
||||
echo "</p>\n";
|
||||
|
||||
|
||||
|
||||
|
||||
// connects to MySQL using DSN
|
||||
echo '<p>Connecting to MySQL: ';
|
||||
try {
|
||||
@@ -49,6 +54,8 @@ try {
|
||||
echo "</p>\n";
|
||||
|
||||
|
||||
|
||||
|
||||
// connects to MySQLi using array
|
||||
echo '<p>Connecting to MySQLi: ';
|
||||
try {
|
||||
@@ -71,6 +78,8 @@ try {
|
||||
echo "</p>\n";
|
||||
|
||||
|
||||
|
||||
|
||||
// connects to ODBC
|
||||
echo '<p>Connecting to ODBC: ';
|
||||
try {
|
||||
@@ -78,7 +87,7 @@ try {
|
||||
'driver' => 'odbc',
|
||||
'username' => 'root',
|
||||
'password' => '***',
|
||||
'dsn' => 'Driver={Microsoft Access Driver (*.mdb)};Dbq='.__DIR__.'/data/sample.mdb',
|
||||
'dsn' => 'Driver={Microsoft Access Driver (*.mdb)};Dbq='.dirname(__FILE__).'/data/sample.mdb',
|
||||
));
|
||||
echo 'OK';
|
||||
|
||||
@@ -88,6 +97,8 @@ try {
|
||||
echo "</p>\n";
|
||||
|
||||
|
||||
|
||||
|
||||
// connects to PostgreSql
|
||||
echo '<p>Connecting to PostgreSql: ';
|
||||
try {
|
||||
@@ -104,6 +115,8 @@ try {
|
||||
echo "</p>\n";
|
||||
|
||||
|
||||
|
||||
|
||||
// connects to PDO
|
||||
echo '<p>Connecting to Sqlite via PDO: ';
|
||||
try {
|
||||
@@ -119,6 +132,7 @@ try {
|
||||
echo "</p>\n";
|
||||
|
||||
|
||||
|
||||
// connects to MS SQL
|
||||
echo '<p>Connecting to MS SQL: ';
|
||||
try {
|
||||
@@ -136,6 +150,7 @@ try {
|
||||
echo "</p>\n";
|
||||
|
||||
|
||||
|
||||
// connects to MS SQL 2005
|
||||
echo '<p>Connecting to MS SQL 2005: ';
|
||||
try {
|
||||
@@ -154,6 +169,7 @@ try {
|
||||
echo "</p>\n";
|
||||
|
||||
|
||||
|
||||
// connects to Oracle
|
||||
echo '<p>Connecting to Oracle: ';
|
||||
try {
|
||||
|
Binary file not shown.
Before Width: | Height: | Size: 1.1 KiB |
@@ -41,24 +41,24 @@ table.dump th {
|
||||
}
|
||||
|
||||
/* dump() */
|
||||
pre.tracy-dump, pre.dump {
|
||||
pre.nette-dump, pre.dump {
|
||||
color: #444; background: white;
|
||||
border: 1px solid silver;
|
||||
padding: 1em;
|
||||
margin: 1em 0;
|
||||
}
|
||||
pre.tracy-dump .php-array, pre.tracy-dump .php-object {
|
||||
pre.nette-dump .php-array, pre.nette-dump .php-object {
|
||||
color: #C22;
|
||||
}
|
||||
pre.tracy-dump .php-string {
|
||||
pre.nette-dump .php-string {
|
||||
color: #080;
|
||||
}
|
||||
pre.tracy-dump .php-int, pre.tracy-dump .php-float {
|
||||
pre.nette-dump .php-int, pre.nette-dump .php-float {
|
||||
color: #37D;
|
||||
}
|
||||
pre.tracy-dump .php-null, pre.tracy-dump .php-bool {
|
||||
pre.nette-dump .php-null, pre.nette-dump .php-bool {
|
||||
color: black;
|
||||
}
|
||||
pre.tracy-dump .php-visibility {
|
||||
pre.nette-dump .php-visibility {
|
||||
font-size: 85%; color: #999;
|
||||
}
|
||||
|
@@ -4,15 +4,17 @@
|
||||
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/../dibi/dibi.php';
|
||||
require_once 'Nette/Debugger.php';
|
||||
require_once '../dibi/dibi.php';
|
||||
|
||||
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
));
|
||||
|
||||
|
||||
|
||||
// retrieve database reflection
|
||||
$database = dibi::getDatabaseInfo();
|
||||
|
||||
@@ -24,6 +26,7 @@ foreach ($database->getTables() as $table) {
|
||||
echo "</ul>\n";
|
||||
|
||||
|
||||
|
||||
// table reflection
|
||||
$table = $database->getTable('products');
|
||||
|
||||
@@ -37,6 +40,7 @@ foreach ($table->getColumns() as $column) {
|
||||
echo "</ul>\n";
|
||||
|
||||
|
||||
|
||||
echo "Indexes";
|
||||
echo "<ul>\n";
|
||||
foreach ($table->getIndexes() as $index) {
|
||||
|
@@ -4,15 +4,17 @@
|
||||
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/../dibi/dibi.php';
|
||||
require_once 'Nette/Debugger.php';
|
||||
require_once '../dibi/dibi.php';
|
||||
|
||||
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
));
|
||||
|
||||
|
||||
|
||||
$res = dibi::query('
|
||||
SELECT * FROM products
|
||||
INNER JOIN orders USING (product_id)
|
||||
|
@@ -4,15 +4,14 @@
|
||||
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/Tracy/tracy.phar';
|
||||
require __DIR__ . '/../dibi/dibi.php';
|
||||
|
||||
Tracy\Debugger::enable();
|
||||
require_once 'Nette/Debugger.php';
|
||||
require_once '../dibi/dibi.php';
|
||||
|
||||
ndebug();
|
||||
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
));
|
||||
|
||||
|
||||
@@ -31,40 +30,38 @@ product_id | title
|
||||
// fetch a single row
|
||||
echo "<h2>fetch()</h2>\n";
|
||||
$row = dibi::fetch('SELECT title FROM products');
|
||||
Tracy\Dumper::dump($row); // Chair
|
||||
dump($row); // Chair
|
||||
|
||||
|
||||
// fetch a single value
|
||||
echo "<h2>fetchSingle()</h2>\n";
|
||||
$value = dibi::fetchSingle('SELECT title FROM products');
|
||||
Tracy\Dumper::dump($value); // Chair
|
||||
dump($value); // Chair
|
||||
|
||||
|
||||
// fetch complete result set
|
||||
echo "<h2>fetchAll()</h2>\n";
|
||||
$all = dibi::fetchAll('SELECT * FROM products');
|
||||
Tracy\Dumper::dump($all);
|
||||
dump($all);
|
||||
|
||||
|
||||
// fetch complete result set like association array
|
||||
echo "<h2>fetchAssoc('title')</h2>\n";
|
||||
$res = dibi::query('SELECT * FROM products');
|
||||
$assoc = $res->fetchAssoc('title'); // key
|
||||
Tracy\Dumper::dump($assoc);
|
||||
dump($assoc);
|
||||
|
||||
|
||||
// fetch complete result set like pairs key => value
|
||||
echo "<h2>fetchPairs('product_id', 'title')</h2>\n";
|
||||
$res = dibi::query('SELECT * FROM products');
|
||||
$pairs = $res->fetchPairs('product_id', 'title');
|
||||
Tracy\Dumper::dump($pairs);
|
||||
dump($pairs);
|
||||
|
||||
|
||||
// fetch row by row
|
||||
echo "<h2>using foreach</h2>\n";
|
||||
$res = dibi::query('SELECT * FROM products');
|
||||
foreach ($res as $n => $row) {
|
||||
Tracy\Dumper::dump($row);
|
||||
dump($row);
|
||||
}
|
||||
|
||||
|
||||
@@ -76,16 +73,14 @@ $res = dibi::query('
|
||||
INNER JOIN customers USING (customer_id)
|
||||
');
|
||||
|
||||
echo "<h2>fetchAssoc('name|title')</h2>\n";
|
||||
$assoc = $res->fetchAssoc('name|title'); // key
|
||||
Tracy\Dumper::dump($assoc);
|
||||
echo "<h2>fetchAssoc('customers.name|products.title')</h2>\n";
|
||||
$assoc = $res->fetchAssoc('customers.name|products.title'); // key
|
||||
dump($assoc);
|
||||
|
||||
echo "<h2>fetchAssoc('name[]title')</h2>\n";
|
||||
$res = dibi::query('SELECT * FROM products INNER JOIN orders USING (product_id) INNER JOIN customers USING (customer_id)');
|
||||
$assoc = $res->fetchAssoc('name[]title'); // key
|
||||
Tracy\Dumper::dump($assoc);
|
||||
echo "<h2>fetchAssoc('customers.name[]products.title')</h2>\n";
|
||||
$assoc = $res->fetchAssoc('customers.name[]products.title'); // key
|
||||
dump($assoc);
|
||||
|
||||
echo "<h2>fetchAssoc('name->title')</h2>\n";
|
||||
$res = dibi::query('SELECT * FROM products INNER JOIN orders USING (product_id) INNER JOIN customers USING (customer_id)');
|
||||
$assoc = $res->fetchAssoc('name->title'); // key
|
||||
Tracy\Dumper::dump($assoc);
|
||||
echo "<h2>fetchAssoc('customers.name->products.title')</h2>\n";
|
||||
$assoc = $res->fetchAssoc('customers.name->products.title'); // key
|
||||
dump($assoc);
|
||||
|
@@ -4,12 +4,13 @@
|
||||
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/../dibi/dibi.php';
|
||||
require_once 'Nette/Debugger.php';
|
||||
require_once '../dibi/dibi.php';
|
||||
|
||||
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
));
|
||||
|
||||
|
||||
|
@@ -1,25 +1,26 @@
|
||||
<!DOCTYPE html><link rel="stylesheet" href="data/style.css">
|
||||
|
||||
<h1>Tracy & SQL Exceptions | dibi</h1>
|
||||
<h1>Nette Debugger & SQL Exceptions | dibi</h1>
|
||||
|
||||
<p>Dibi can display and log exceptions via Tracy, part of Nette Framework.</p>
|
||||
<p>Dibi can display and log exceptions via Nette Debugger, part of Nette Framework.</p>
|
||||
|
||||
<ul>
|
||||
<li>Tracy Debugger: http://tracy.nette.org
|
||||
<li>Nette Framework: http://nette.org
|
||||
</ul>
|
||||
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/Tracy/tracy.phar';
|
||||
require __DIR__ . '/../dibi/dibi.php';
|
||||
require_once 'Nette/Debugger.php';
|
||||
require_once '../dibi/dibi.php';
|
||||
|
||||
|
||||
Tracy\Debugger::enable();
|
||||
// enable Nette Debugger
|
||||
ndebug();
|
||||
|
||||
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
'profiler' => array(
|
||||
'run' => TRUE,
|
||||
)
|
||||
@@ -30,9 +31,10 @@ dibi::connect(array(
|
||||
dibi::query('SELECT * FROM customers WHERE customer_id < ?', 38);
|
||||
|
||||
|
||||
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
'profiler' => array(
|
||||
'run' => TRUE,
|
||||
)
|
30
examples/nette-debug-and-variables.php
Normal file
30
examples/nette-debug-and-variables.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<!DOCTYPE html><link rel="stylesheet" href="data/style.css">
|
||||
|
||||
<h1>Nette Debugger & Variables | dibi</h1>
|
||||
|
||||
<p>Dibi can dump variables via Nette Debugger, part of Nette Framework.</p>
|
||||
|
||||
<ul>
|
||||
<li>Nette Framework: http://nette.org
|
||||
</ul>
|
||||
|
||||
<?php
|
||||
|
||||
require_once 'Nette/Debugger.php';
|
||||
require_once '../dibi/dibi.php';
|
||||
|
||||
|
||||
// enable Nette Debugger
|
||||
NDebugger::enable();
|
||||
|
||||
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
'profiler' => array(
|
||||
'run' => TRUE,
|
||||
)
|
||||
));
|
||||
|
||||
|
||||
NDebugger::barDump( dibi::fetchAll('SELECT * FROM customers WHERE customer_id < ?', 38), '[customers]' );
|
@@ -4,12 +4,13 @@
|
||||
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/../dibi/dibi.php';
|
||||
require_once 'Nette/Debugger.php';
|
||||
require_once '../dibi/dibi.php';
|
||||
|
||||
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
));
|
||||
|
||||
|
||||
@@ -31,6 +32,8 @@ dibi::test('
|
||||
// -> SELECT * FROM customers WHERE name LIKE 'K%'
|
||||
|
||||
|
||||
|
||||
|
||||
// if & else & (optional) end
|
||||
dibi::test("
|
||||
SELECT *
|
||||
@@ -42,6 +45,7 @@ dibi::test("
|
||||
// -> SELECT * FROM people WHERE id > 0 AND bar=2
|
||||
|
||||
|
||||
|
||||
// nested condition
|
||||
dibi::test('
|
||||
SELECT *
|
||||
@@ -52,10 +56,3 @@ dibi::test('
|
||||
%else 1 LIMIT 10 %end'
|
||||
);
|
||||
// -> SELECT * FROM customers WHERE LIMIT 10
|
||||
|
||||
|
||||
// IF()
|
||||
dibi::test('UPDATE products SET', array(
|
||||
'price' => array('IF(price_fixed, price, ?)', 123),
|
||||
));
|
||||
// -> SELECT * FROM customers WHERE LIMIT 10
|
||||
|
@@ -4,14 +4,15 @@
|
||||
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/../dibi/dibi.php';
|
||||
require_once 'Nette/Debugger.php';
|
||||
require_once '../dibi/dibi.php';
|
||||
|
||||
date_default_timezone_set('Europe/Prague');
|
||||
|
||||
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
));
|
||||
|
||||
|
||||
@@ -28,6 +29,7 @@ dibi::test('
|
||||
// -> SELECT COUNT(*) as [count] FROM [comments] WHERE [ip] LIKE '192.168.%' AND [date] > 876693600
|
||||
|
||||
|
||||
|
||||
// dibi detects INSERT or REPLACE command
|
||||
dibi::test('
|
||||
REPLACE INTO products', array(
|
||||
@@ -38,6 +40,7 @@ dibi::test('
|
||||
// -> REPLACE INTO products ([title], [price], [active]) VALUES ('Super product', 318, 1)
|
||||
|
||||
|
||||
|
||||
// multiple INSERT command
|
||||
$array = array(
|
||||
'title' => 'Super Product',
|
||||
@@ -49,6 +52,7 @@ dibi::test("INSERT INTO products", $array, $array, $array);
|
||||
// -> INSERT INTO products ([title], [price], [brand], [created]) VALUES ('Super Product', ...) , (...) , (...)
|
||||
|
||||
|
||||
|
||||
// dibi detects UPDATE command
|
||||
dibi::test("
|
||||
UPDATE colors SET", array(
|
||||
@@ -59,6 +63,7 @@ dibi::test("
|
||||
// -> UPDATE colors SET [color]='blue', [order]=12 WHERE id=123
|
||||
|
||||
|
||||
|
||||
// modifier applied to array
|
||||
$array = array(1, 2, 3);
|
||||
dibi::test("
|
||||
@@ -69,6 +74,7 @@ dibi::test("
|
||||
// -> SELECT * FROM people WHERE id IN ( 1, 2, 3 )
|
||||
|
||||
|
||||
|
||||
// modifier %by for ORDER BY
|
||||
$order = array(
|
||||
'field1' => 'asc',
|
||||
@@ -82,6 +88,7 @@ dibi::test("
|
||||
// -> SELECT * FROM people ORDER BY [field1] ASC, [field2] DESC
|
||||
|
||||
|
||||
|
||||
// indentifiers and strings syntax mix
|
||||
dibi::test('UPDATE [table] SET `item` = "5 1/4"" diskette"');
|
||||
// -> UPDATE [table] SET [item] = '5 1/4" diskette'
|
||||
|
@@ -1,20 +1,19 @@
|
||||
<!DOCTYPE html><link rel="stylesheet" href="data/style.css">
|
||||
|
||||
<h1>Result Set Data Types | dibi</h1>
|
||||
<h1>Result Set Data Types | dibi</h1>
|
||||
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/Tracy/tracy.phar';
|
||||
require __DIR__ . '/../dibi/dibi.php';
|
||||
|
||||
Tracy\Debugger::enable();
|
||||
require_once 'Nette/Debugger.php';
|
||||
require_once '../dibi/dibi.php';
|
||||
|
||||
ndebug();
|
||||
date_default_timezone_set('Europe/Prague');
|
||||
|
||||
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
));
|
||||
|
||||
|
||||
@@ -26,20 +25,23 @@ $res->setType('customer_id', Dibi::INTEGER)
|
||||
->setFormat(dibi::DATETIME, 'Y-m-d H:i:s');
|
||||
|
||||
|
||||
Tracy\Dumper::dump( $res->fetch() );
|
||||
dump( $res->fetch() );
|
||||
// outputs:
|
||||
// DibiRow(3) {
|
||||
// customer_id => 1
|
||||
// name => "Dave Lister" (11)
|
||||
// added => "2007-03-11 17:20:03" (19)
|
||||
// object(DibiRow)#3 (3) {
|
||||
// customer_id => int(1)
|
||||
// name => string(11) "Dave Lister"
|
||||
// added => object(DateTime53) {}
|
||||
// }
|
||||
|
||||
|
||||
|
||||
// using auto-detection (works well with MySQL or other strictly typed databases)
|
||||
$res = dibi::query('SELECT * FROM [customers]');
|
||||
|
||||
Tracy\Dumper::dump( $res->fetch() );
|
||||
dump( $res->fetch() );
|
||||
// outputs:
|
||||
// DibiRow(3) {
|
||||
// customer_id => 1
|
||||
// name => "Dave Lister" (11)
|
||||
// added => "2007-03-11 17:20:03" (19)
|
||||
// object(DibiRow)#3 (3) {
|
||||
// customer_id => int(1)
|
||||
// name => string(11) "Dave Lister"
|
||||
// added => string(15) "17:20 11.3.2007"
|
||||
// }
|
||||
|
@@ -1,31 +0,0 @@
|
||||
<!DOCTYPE html><link rel="stylesheet" href="data/style.css">
|
||||
|
||||
<style> html { background: url(data/arrow.png) no-repeat bottom right; height: 100%; } </style>
|
||||
|
||||
<h1>Tracy & Variables | dibi</h1>
|
||||
|
||||
<p>Dibi can dump variables via Tracy, part of Nette Framework.</p>
|
||||
|
||||
<ul>
|
||||
<li>Tracy Debugger: http://tracy.nette.org
|
||||
</ul>
|
||||
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/Tracy/tracy.phar';
|
||||
require __DIR__ . '/../dibi/dibi.php';
|
||||
|
||||
|
||||
Tracy\Debugger::enable();
|
||||
|
||||
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'profiler' => array(
|
||||
'run' => TRUE,
|
||||
)
|
||||
));
|
||||
|
||||
|
||||
Tracy\Debugger::barDump( dibi::fetchAll('SELECT * FROM customers WHERE customer_id < ?', 38), '[customers]' );
|
@@ -4,20 +4,23 @@
|
||||
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/../dibi/dibi.php';
|
||||
require_once 'Nette/Debugger.php';
|
||||
require_once '../dibi/dibi.php';
|
||||
|
||||
date_default_timezone_set('Europe/Prague');
|
||||
|
||||
|
||||
|
||||
// CHANGE TO REAL PARAMETERS!
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
'formatDate' => "'Y-m-d'",
|
||||
'formatDateTime' => "'Y-m-d H-i-s'",
|
||||
));
|
||||
|
||||
|
||||
|
||||
// generate and dump SQL
|
||||
dibi::test("
|
||||
INSERT INTO [mytable]", array(
|
||||
|
@@ -4,28 +4,28 @@
|
||||
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/Tracy/tracy.phar';
|
||||
require __DIR__ . '/../dibi/dibi.php';
|
||||
|
||||
Tracy\Debugger::enable();
|
||||
require_once 'Nette/Debugger.php';
|
||||
require_once '../dibi/dibi.php';
|
||||
|
||||
ndebug();
|
||||
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
));
|
||||
|
||||
|
||||
|
||||
// using the "prototype" to add custom method to class DibiResult
|
||||
DibiResult::extensionMethod('fetchShuffle', function(DibiResult $obj)
|
||||
function DibiResult_prototype_fetchShuffle(DibiResult $obj)
|
||||
{
|
||||
$all = $obj->fetchAll();
|
||||
shuffle($all);
|
||||
return $all;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// fetch complete result set shuffled
|
||||
$res = dibi::query('SELECT * FROM [customers]');
|
||||
$all = $res->fetchShuffle();
|
||||
Tracy\Dumper::dump($all);
|
||||
dump($all);
|
||||
|
@@ -4,14 +4,15 @@
|
||||
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/../dibi/dibi.php';
|
||||
require_once 'Nette/Debugger.php';
|
||||
require_once '../dibi/dibi.php';
|
||||
|
||||
date_default_timezone_set('Europe/Prague');
|
||||
|
||||
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
));
|
||||
|
||||
|
||||
@@ -34,6 +35,7 @@ dibi::select('product_id')->as('id')
|
||||
// USING (product_id) INNER JOIN customers USING (customer_id) ORDER BY [title]
|
||||
|
||||
|
||||
|
||||
// SELECT ...
|
||||
echo dibi::select('title')->as('id')
|
||||
->from('products')
|
||||
@@ -41,6 +43,7 @@ echo dibi::select('title')->as('id')
|
||||
// -> Chair (as result of query: SELECT [title] AS [id] FROM [products])
|
||||
|
||||
|
||||
|
||||
// INSERT ...
|
||||
dibi::insert('products', $record)
|
||||
->setFlag('IGNORE')
|
||||
@@ -48,6 +51,7 @@ dibi::insert('products', $record)
|
||||
// -> INSERT IGNORE INTO [products] ([title], [price], [active]) VALUES ('Super product', 318, 1)
|
||||
|
||||
|
||||
|
||||
// UPDATE ...
|
||||
dibi::update('products', $record)
|
||||
->where('product_id = ?', $id)
|
||||
@@ -55,6 +59,7 @@ dibi::update('products', $record)
|
||||
// -> UPDATE [products] SET [title]='Super product', [price]=318, [active]=1 WHERE product_id = 10
|
||||
|
||||
|
||||
|
||||
// DELETE ...
|
||||
dibi::delete('products')
|
||||
->where('product_id = ?', $id)
|
||||
@@ -62,6 +67,7 @@ dibi::delete('products')
|
||||
// -> DELETE FROM [products] WHERE product_id = 10
|
||||
|
||||
|
||||
|
||||
// custom commands
|
||||
dibi::command()
|
||||
->update('products')
|
||||
@@ -71,6 +77,7 @@ dibi::command()
|
||||
// -> UPDATE [products] SET [title]='Super product', [price]=318, [active]=1 WHERE product_id = 10
|
||||
|
||||
|
||||
|
||||
dibi::command()
|
||||
->truncate('products')
|
||||
->test();
|
||||
|
@@ -4,12 +4,13 @@
|
||||
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/../dibi/dibi.php';
|
||||
require_once 'Nette/Debugger.php';
|
||||
require_once '../dibi/dibi.php';
|
||||
|
||||
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
));
|
||||
|
||||
|
||||
@@ -18,11 +19,13 @@ dibi::test('SELECT * FROM [products]');
|
||||
// -> SELECT * FROM [products]
|
||||
|
||||
|
||||
|
||||
// with limit = 2
|
||||
dibi::test('SELECT * FROM [products] %lmt', 2);
|
||||
// -> SELECT * FROM [products] LIMIT 2
|
||||
|
||||
|
||||
|
||||
// with limit = 2, offset = 1
|
||||
dibi::test('SELECT * FROM [products] %lmt %ofs', 2, 1);
|
||||
// -> SELECT * FROM [products] LIMIT 2 OFFSET 1
|
||||
|
@@ -4,14 +4,15 @@
|
||||
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/../dibi/dibi.php';
|
||||
require_once 'Nette/Debugger.php';
|
||||
require_once '../dibi/dibi.php';
|
||||
|
||||
date_default_timezone_set('Europe/Prague');
|
||||
|
||||
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
// enable query logging to this file
|
||||
'profiler' => array(
|
||||
'run' => TRUE,
|
||||
@@ -20,6 +21,7 @@ dibi::connect(array(
|
||||
));
|
||||
|
||||
|
||||
|
||||
try {
|
||||
$res = dibi::query('SELECT * FROM [customers] WHERE [customer_id] = ?', 1);
|
||||
|
||||
|
@@ -1,4 +1,4 @@
|
||||
<?php ob_start() // needed by FirePHP ?>
|
||||
<?php ob_start(1) // needed by FirePHP ?>
|
||||
|
||||
<!DOCTYPE html><link rel="stylesheet" href="data/style.css">
|
||||
|
||||
@@ -6,12 +6,13 @@
|
||||
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/../dibi/dibi.php';
|
||||
require_once 'Nette/Debugger.php';
|
||||
require_once '../dibi/dibi.php';
|
||||
|
||||
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
'profiler' => array(
|
||||
'run' => TRUE,
|
||||
)
|
||||
|
@@ -4,15 +4,18 @@
|
||||
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/../dibi/dibi.php';
|
||||
require_once 'Nette/Debugger.php';
|
||||
require_once '../dibi/dibi.php';
|
||||
|
||||
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
));
|
||||
|
||||
|
||||
|
||||
|
||||
// create new substitution :blog: ==> wp_
|
||||
dibi::getSubstitutes()->blog = 'wp_';
|
||||
|
||||
@@ -20,6 +23,9 @@ dibi::test("SELECT * FROM [:blog:items]");
|
||||
// -> SELECT * FROM [wp_items]
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// create new substitution :: (empty) ==> my_
|
||||
dibi::getSubstitutes()->{''} = 'my_';
|
||||
|
||||
@@ -27,6 +33,9 @@ dibi::test("UPDATE ::table SET [text]='Hello World'");
|
||||
// -> UPDATE my_table SET [text]='Hello World'
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// create substitutions using fallback callback
|
||||
function substFallBack($expr)
|
||||
{
|
||||
|
@@ -4,12 +4,13 @@
|
||||
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/../dibi/dibi.php';
|
||||
require_once 'Nette/Debugger.php';
|
||||
require_once '../dibi/dibi.php';
|
||||
|
||||
|
||||
dibi::connect(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => 'data/sample.s3db',
|
||||
'driver' => 'sqlite',
|
||||
'database' => 'data/sample.sdb',
|
||||
));
|
||||
|
||||
|
||||
|
55
license.md
55
license.md
@@ -1,55 +0,0 @@
|
||||
Licenses
|
||||
========
|
||||
|
||||
Good news! You may use Dibi under the terms of either the New BSD License
|
||||
or the GNU General Public License (GPL) version 2 or 3.
|
||||
|
||||
The BSD License is recommended for most projects. It is easy to understand and it
|
||||
places almost no restrictions on what you can do with the framework. If the GPL
|
||||
fits better to your project, you can use the framework under this license.
|
||||
|
||||
You don't have to notify anyone which license you are using. You can freely
|
||||
use Dibi in commercial projects as long as the copyright header
|
||||
remains intact.
|
||||
|
||||
|
||||
New BSD License
|
||||
---------------
|
||||
|
||||
Copyright (c) 2004, 2014 David Grudl (http://davidgrudl.com)
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name of "Dibi" nor the names of its contributors
|
||||
may be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
This software is provided by the copyright holders and contributors "as is" and
|
||||
any express or implied warranties, including, but not limited to, the implied
|
||||
warranties of merchantability and fitness for a particular purpose are
|
||||
disclaimed. In no event shall the copyright owner or contributors be liable for
|
||||
any direct, indirect, incidental, special, exemplary, or consequential damages
|
||||
(including, but not limited to, procurement of substitute goods or services;
|
||||
loss of use, data, or profits; or business interruption) however caused and on
|
||||
any theory of liability, whether in contract, strict liability, or tort
|
||||
(including negligence or otherwise) arising in any way out of the use of this
|
||||
software, even if advised of the possibility of such damage.
|
||||
|
||||
|
||||
GNU General Public License
|
||||
--------------------------
|
||||
|
||||
GPL licenses are very very long, so instead of including them here we offer
|
||||
you URLs with full text:
|
||||
|
||||
- [GPL version 2](http://www.gnu.org/licenses/gpl-2.0.html)
|
||||
- [GPL version 3](http://www.gnu.org/licenses/gpl-3.0.html)
|
61
license.txt
Normal file
61
license.txt
Normal file
@@ -0,0 +1,61 @@
|
||||
Licenses
|
||||
========
|
||||
|
||||
Good news! You may use Dibi under the terms of either the New BSD License
|
||||
or the GNU General Public License (GPL) version 2 or 3.
|
||||
|
||||
The BSD License is recommended for most projects. It is easy to understand and it
|
||||
places almost no restrictions on what you can do with the library. If the GPL
|
||||
fits better to your project, you can use the Dibi under this license.
|
||||
|
||||
You don't have to notify anyone which license you are using. You can freely
|
||||
use Dibi in commercial projects as long as the copyright header
|
||||
remains intact.
|
||||
|
||||
Please do not use word "Dibi" in the name of your project or top-level domain,
|
||||
and choose a name that stands on its own merits. If your stuff is good,
|
||||
it will not take long to establish a reputation for yourselves.
|
||||
|
||||
|
||||
|
||||
New BSD License
|
||||
---------------
|
||||
|
||||
Copyright (c) 2005, 2012 David Grudl (http://davidgrudl.com)
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name of "Dibi" nor the names of its contributors
|
||||
may be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
|
||||
GNU General Public License
|
||||
--------------------------
|
||||
|
||||
GPL licenses are very very long, so instead of including them here we offer
|
||||
you URLs with full text:
|
||||
|
||||
- GPL version 2: http://www.gnu.org/licenses/gpl-2.0.html
|
||||
- GPL version 3: http://www.gnu.org/licenses/gpl-3.0.html
|
130
readme.md
130
readme.md
@@ -1,130 +0,0 @@
|
||||
[Dibi](http://dibiphp.com) - smart database layer for PHP
|
||||
=========================================================
|
||||
|
||||
[](https://packagist.org/packages/dibi/dibi)
|
||||
[](https://travis-ci.org/dg/dibi)
|
||||
|
||||
Database access functions in PHP are not standardised. This library
|
||||
hides the differences between them, and above all, it gives you a very handy interface.
|
||||
|
||||
The best way to install Dibi is to use a [Composer](http://getcomposer.org/download):
|
||||
|
||||
php composer.phar require dibi/dibi
|
||||
|
||||
Or you can download the latest package from http://dibiphp.com. In this
|
||||
package is also `Dibi.minified`, shrinked single-file version of whole Dibi,
|
||||
useful when you don't want to modify the library, but just use it.
|
||||
|
||||
Dibi requires PHP 5.2.0 or later. It has been tested with PHP 5.5 too.
|
||||
|
||||
|
||||
Examples
|
||||
--------
|
||||
|
||||
Refer to the `examples` directory for examples. Dibi documentation is
|
||||
available on the [homepage](http://dibiphp.com).
|
||||
|
||||
Connect to database:
|
||||
|
||||
```php
|
||||
// connect to database (static way)
|
||||
dibi::connect(array(
|
||||
'driver' => 'mysql',
|
||||
'host' => 'localhost',
|
||||
'username' => 'root',
|
||||
'password' => '***',
|
||||
));
|
||||
|
||||
// or object way; in all other examples use $connection-> instead of dibi::
|
||||
$connection = new DibiConnection($options);
|
||||
```
|
||||
|
||||
SELECT, INSERT, UPDATE
|
||||
|
||||
```php
|
||||
dibi::query('SELECT * FROM users WHERE id = ?', $id);
|
||||
|
||||
$arr = array(
|
||||
'name' => 'John',
|
||||
'is_admin' => TRUE,
|
||||
);
|
||||
dibi::query('INSERT INTO users', $arr);
|
||||
// INSERT INTO users (`name`, `is_admin`) VALUES ('John', 1)
|
||||
|
||||
dibi::query('UPDATE users SET', $arr, 'WHERE `id`=?', $x);
|
||||
// UPDATE users SET `name`='John', `is_admin`=1 WHERE `id` = 123
|
||||
|
||||
dibi::query('UPDATE users SET', array(
|
||||
'title' => array('SHA1(?)', 'tajneheslo'),
|
||||
));
|
||||
// UPDATE users SET 'title' = SHA1('tajneheslo')
|
||||
```
|
||||
|
||||
Getting results
|
||||
|
||||
```php
|
||||
$result = dibi::query('SELECT * FROM users');
|
||||
|
||||
$value = $result->fetchSingle(); // single value
|
||||
$all = $result->fetchAll(); // all rows
|
||||
$assoc = $result->fetchAssoc('id'); // all rows as associative array
|
||||
$pairs = $result->fetchPairs('customerID', 'name'); // all rows as key => value pairs
|
||||
|
||||
// iterating
|
||||
foreach ($result as $n => $row) {
|
||||
print_r($row);
|
||||
}
|
||||
```
|
||||
|
||||
Modifiers for arrays:
|
||||
|
||||
```php
|
||||
dibi::query('SELECT * FROM users WHERE %and', array(
|
||||
array('number > ?', 10),
|
||||
array('number < ?', 100),
|
||||
));
|
||||
// SELECT * FROM users WHERE (number > 10) AND (number < 100)
|
||||
```
|
||||
|
||||
<table>
|
||||
<tr><td> %and </td><td> </td><td> `[key]=val AND [key2]="val2" AND ...` </td></tr>
|
||||
<tr><td> %or </td><td> </td><td> `[key]=val OR [key2]="val2" OR ...` </td></tr>
|
||||
<tr><td> %a </td><td> assoc </td><td> `[key]=val, [key2]="val2", ...` </td></tr>
|
||||
<tr><td> %l %in </td><td> list </td><td> `(val, "val2", ...)` </td></tr>
|
||||
<tr><td> %v </td><td> values </td><td> `([key], [key2], ...) VALUES (val, "val2", ...)` </td></tr>
|
||||
<tr><td> %m </td><td> multivalues </td><td> `([key], [key2], ...) VALUES (val, "val2", ...), (val, "val2", ...), ...` </td></tr>
|
||||
<tr><td> %by </td><td> ordering </td><td> `[key] ASC, [key2] DESC ...` </td></tr>
|
||||
<tr><td> %n </td><td> identifiers </td><td> `[key], [key2] AS alias, ...` </td></tr>
|
||||
<tr><td> other </td><td> - </td><td> `val, val2, ...` </td></tr>
|
||||
</table>
|
||||
|
||||
|
||||
Modifiers for LIKE
|
||||
|
||||
```php
|
||||
dibi::query("SELECT * FROM table WHERE name LIKE %like~", $query);
|
||||
```
|
||||
|
||||
<table>
|
||||
<tr><td> %like~ </td><td> begins with </td></tr>
|
||||
<tr><td> %~like </td><td> ends with </td></tr>
|
||||
<tr><td> %~like~ </td><td> contains </td></tr>
|
||||
</table>
|
||||
|
||||
DateTime:
|
||||
|
||||
```php
|
||||
dibi::query('UPDATE users SET', array(
|
||||
'time' => new DateTime,
|
||||
));
|
||||
// UPDATE users SET ('2008-01-01 01:08:10')
|
||||
```
|
||||
|
||||
Testing:
|
||||
|
||||
```php
|
||||
echo dibi::$sql; // last SQL query
|
||||
echo dibi::$elapsedTime;
|
||||
echo dibi::$numOfQueries;
|
||||
echo dibi::$totalTime;
|
||||
```
|
31
readme.txt
Normal file
31
readme.txt
Normal file
@@ -0,0 +1,31 @@
|
||||
Introduction
|
||||
------------
|
||||
|
||||
Thank you for downloading Dibi!
|
||||
|
||||
Database access functions in PHP are not standardised. This is class library
|
||||
to hide the differences between the different databases access.
|
||||
|
||||
|
||||
Documentation and Examples
|
||||
--------------------------
|
||||
|
||||
Refer to the 'examples' directory for examples. Dibi documentation is
|
||||
available on the homepage:
|
||||
|
||||
http://dibiphp.com
|
||||
|
||||
|
||||
Dibi.minified
|
||||
-------------
|
||||
|
||||
This is shrinked single-file version of whole Dibi, useful when you don't
|
||||
want to modify library, but just use it.
|
||||
|
||||
This is exactly the same as normal version, just only comments and
|
||||
whitespaces are removed.
|
||||
|
||||
|
||||
-----
|
||||
For more information, visit the author's weblog (in czech language):
|
||||
http://phpfashion.com
|
4
tests/.gitignore
vendored
4
tests/.gitignore
vendored
@@ -1,4 +0,0 @@
|
||||
/*/output
|
||||
/coverage.dat
|
||||
/test.log
|
||||
/tmp
|
72
tests/DibiFluent.cloning.phpt
Normal file
72
tests/DibiFluent.cloning.phpt
Normal file
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Test: Cloning of DibiFluent
|
||||
*
|
||||
* @author David Grudl
|
||||
* @category Dibi
|
||||
* @subpackage UnitTests
|
||||
*/
|
||||
|
||||
|
||||
|
||||
require dirname(__FILE__) . '/initialize.php';
|
||||
|
||||
|
||||
|
||||
dibi::connect($config['sqlite']);
|
||||
|
||||
|
||||
$fluent = new DibiFluent(dibi::getConnection());
|
||||
$fluent->select('*')->from('table')->where('x=1');
|
||||
$dolly = clone $fluent;
|
||||
$dolly->where('y=1');
|
||||
$dolly->clause('FOO');
|
||||
|
||||
$fluent->test();
|
||||
$dolly->test();
|
||||
|
||||
|
||||
|
||||
$fluent = dibi::select('id')->from('table')->where('id = %i',1);
|
||||
$dolly = clone $fluent;
|
||||
$dolly->where('cd = %i',5);
|
||||
|
||||
$fluent->test();
|
||||
$dolly->test();
|
||||
|
||||
|
||||
|
||||
$fluent = dibi::select("*")->from("table");
|
||||
$dolly = clone $fluent;
|
||||
$dolly->removeClause("select")->select("count(*)");
|
||||
|
||||
$fluent->test();
|
||||
$dolly->test();
|
||||
|
||||
|
||||
|
||||
__halt_compiler() ?>
|
||||
|
||||
------EXPECT------
|
||||
SELECT *
|
||||
FROM [table]
|
||||
WHERE x=1
|
||||
|
||||
SELECT *
|
||||
FROM [table]
|
||||
WHERE x=1 AND y=1 FOO
|
||||
|
||||
SELECT [id]
|
||||
FROM [table]
|
||||
WHERE id = 1
|
||||
|
||||
SELECT [id]
|
||||
FROM [table]
|
||||
WHERE id = 1 AND cd = 5
|
||||
|
||||
SELECT *
|
||||
FROM [table]
|
||||
|
||||
SELECT count(*)
|
||||
FROM [table]
|
138
tests/NetteTest/Assert.php
Normal file
138
tests/NetteTest/Assert.php
Normal file
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Nette Framework
|
||||
*
|
||||
* @copyright Copyright (c) 2004 David Grudl
|
||||
* @license http://nette.org/license Nette license
|
||||
* @link http://nette.org
|
||||
* @category Nette
|
||||
* @package Nette\Test
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Asseratation test helpers.
|
||||
*
|
||||
* @author David Grudl
|
||||
* @package Nette\Test
|
||||
*/
|
||||
class Assert
|
||||
{
|
||||
|
||||
/**
|
||||
* Checks assertation.
|
||||
* @param mixed expected
|
||||
* @param mixed actual
|
||||
* @return void
|
||||
*/
|
||||
public static function same($expected, $actual)
|
||||
{
|
||||
if ($actual !== $expected) {
|
||||
self::note('Failed asserting that ' . self::dump($actual) . ' is not identical to ' . self::dump($expected));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Checks TRUE assertation.
|
||||
* @param mixed actual
|
||||
* @return void
|
||||
*/
|
||||
public static function true($actual)
|
||||
{
|
||||
if ($actual !== TRUE) {
|
||||
self::note('Failed asserting that ' . self::dump($actual) . ' is not TRUE');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Checks FALSE assertation.
|
||||
* @param mixed actual
|
||||
* @return void
|
||||
*/
|
||||
public static function false($actual)
|
||||
{
|
||||
if ($actual !== FALSE) {
|
||||
self::note('Failed asserting that ' . self::dump($actual) . ' is not FALSE');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Checks NULL assertation.
|
||||
* @param mixed actual
|
||||
* @return void
|
||||
*/
|
||||
public static function null($actual)
|
||||
{
|
||||
if ($actual !== NULL) {
|
||||
self::note('Failed asserting that ' . self::dump($actual) . ' is not NULL');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Dumps information about a variable in readable format.
|
||||
* @param mixed variable to dump
|
||||
* @return void
|
||||
*/
|
||||
private static function dump($var)
|
||||
{
|
||||
if (is_bool($var)) {
|
||||
return $var ? 'TRUE' : 'FALSE';
|
||||
|
||||
} elseif ($var === NULL) {
|
||||
return "NULL";
|
||||
|
||||
} elseif (is_int($var)) {
|
||||
return "$var";
|
||||
|
||||
} elseif (is_float($var)) {
|
||||
return "$var";
|
||||
|
||||
} elseif (is_string($var)) {
|
||||
return var_export($var, TRUE);
|
||||
|
||||
} elseif (is_array($var)) {
|
||||
return "array(" . count($var) . ")";
|
||||
|
||||
} elseif ($var instanceof Exception) {
|
||||
return 'Exception ' . get_class($var) . ': ' . ($var->getCode() ? '#' . $var->getCode() . ' ' : '') . $var->getMessage();
|
||||
|
||||
} elseif (is_object($var)) {
|
||||
$arr = (array) $var;
|
||||
return "object(" . get_class($var) . ") (" . count($arr) . ")";
|
||||
|
||||
} elseif (is_resource($var)) {
|
||||
return "resource(" . get_resource_type($var) . ")";
|
||||
|
||||
} else {
|
||||
return "unknown type";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns message and file and line from call stack.
|
||||
* @param string
|
||||
* @return void
|
||||
*/
|
||||
private static function note($message)
|
||||
{
|
||||
echo $message;
|
||||
$trace = debug_backtrace();
|
||||
if (isset($trace[1]['file'], $trace[1]['line'])) {
|
||||
echo ' in file ' . $trace[1]['file'] . ' on line ' . $trace[1]['line'];
|
||||
}
|
||||
echo "\n\n";
|
||||
}
|
||||
|
||||
}
|
43
tests/NetteTest/RunTests.php
Normal file
43
tests/NetteTest/RunTests.php
Normal file
@@ -0,0 +1,43 @@
|
||||
|
||||
Nette Test Framework (v0.3)
|
||||
---------------------------
|
||||
<?php
|
||||
|
||||
require_once dirname(__FILE__) . '/TestRunner.php';
|
||||
|
||||
/**
|
||||
* Help
|
||||
*/
|
||||
if (!isset($_SERVER['argv'][1])) { ?>
|
||||
Usage:
|
||||
php RunTests.php [options] [file or directory]
|
||||
|
||||
Options:
|
||||
-p <php> Specify PHP-CGI executable to run.
|
||||
-c <path> Look for php.ini in directory <path> or use <path> as php.ini.
|
||||
-d key=val Define INI entry 'key' with value 'val'.
|
||||
-l <path> Specify path to shared library files (LD_LIBRARY_PATH)
|
||||
-e <name> Load php environment <name>
|
||||
-s Show information about skipped tests
|
||||
|
||||
<?php
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Execute tests
|
||||
*/
|
||||
try {
|
||||
@unlink(dirname(__FILE__) . '/coverage.tmp'); // @ - file may not exist
|
||||
|
||||
$manager = new TestRunner;
|
||||
$manager->parseConfigFile();
|
||||
$manager->parseArguments();
|
||||
$res = $manager->run();
|
||||
die($res ? 0 : 1);
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo 'Error: ', $e->getMessage(), "\n";
|
||||
die(2);
|
||||
}
|
400
tests/NetteTest/TestCase.php
Normal file
400
tests/NetteTest/TestCase.php
Normal file
@@ -0,0 +1,400 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Nette Framework
|
||||
*
|
||||
* @copyright Copyright (c) 2004 David Grudl
|
||||
* @license http://nette.org/license Nette license
|
||||
* @link http://nette.org
|
||||
* @category Nette
|
||||
* @package Nette\Test
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Single test case.
|
||||
*
|
||||
* @author David Grudl
|
||||
* @package Nette\Test
|
||||
*/
|
||||
class TestCase
|
||||
{
|
||||
/** @var string test file */
|
||||
private $file;
|
||||
|
||||
/** @var array test file multiparts */
|
||||
private $sections;
|
||||
|
||||
/** @var string test output */
|
||||
private $output;
|
||||
|
||||
/** @var string output headers in raw format */
|
||||
private $headers;
|
||||
|
||||
/** @var string PHP command line */
|
||||
private $cmdLine;
|
||||
|
||||
/** @var string PHP command line */
|
||||
private $phpVersion;
|
||||
|
||||
/** @var array */
|
||||
private static $cachedPhp;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param string test file name
|
||||
* @param string PHP command line
|
||||
* @return void
|
||||
*/
|
||||
public function __construct($testFile)
|
||||
{
|
||||
$this->file = (string) $testFile;
|
||||
$this->sections = self::parseSections($this->file);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Runs single test.
|
||||
* @return void
|
||||
*/
|
||||
public function run()
|
||||
{
|
||||
// pre-skip?
|
||||
$options = $this->sections['options'];
|
||||
if (isset($options['skip'])) {
|
||||
$message = $options['skip'] ? $options['skip'] : 'No message.';
|
||||
throw new TestCaseException($message, TestCaseException::SKIPPED);
|
||||
|
||||
} elseif (isset($options['phpversion'])) {
|
||||
$operator = '>=';
|
||||
if (preg_match('#^(<=|le|<|lt|==|=|eq|!=|<>|ne|>=|ge|>|gt)#', $options['phpversion'], $matches)) {
|
||||
$options['phpversion'] = trim(substr($options['phpversion'], strlen($matches[1])));
|
||||
$operator = $matches[1];
|
||||
}
|
||||
if (version_compare($options['phpversion'], $this->phpVersion, $operator)) {
|
||||
throw new TestCaseException("Requires PHP $operator $options[phpversion].", TestCaseException::SKIPPED);
|
||||
}
|
||||
}
|
||||
|
||||
$this->execute();
|
||||
$output = $this->output;
|
||||
$headers = array_change_key_case(self::parseLines($this->headers, ':'), CASE_LOWER);
|
||||
$tests = 0;
|
||||
|
||||
// post-skip?
|
||||
if (isset($headers['x-nette-test-skip'])) {
|
||||
throw new TestCaseException($headers['x-nette-test-skip'], TestCaseException::SKIPPED);
|
||||
}
|
||||
|
||||
// compare output
|
||||
$expectedOutput = $this->getExpectedOutput();
|
||||
if ($expectedOutput !== NULL) {
|
||||
$tests++;
|
||||
$binary = (bool) preg_match('#[\x00-\x08\x0B\x0C\x0E-\x1F]#', $expectedOutput);
|
||||
if ($binary) {
|
||||
if ($expectedOutput !== $output) {
|
||||
throw new TestCaseException("Binary output doesn't match.");
|
||||
}
|
||||
} else {
|
||||
$output = self::normalize($output, isset($options['keeptrailingspaces']));
|
||||
$expectedOutput = self::normalize($expectedOutput, isset($options['keeptrailingspaces']));
|
||||
if (!$this->compare($output, $expectedOutput)) {
|
||||
throw new TestCaseException("Output doesn't match.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// compare headers
|
||||
$expectedHeaders = $this->getExpectedHeaders();
|
||||
if ($expectedHeaders !== NULL) {
|
||||
$tests++;
|
||||
$expectedHeaders = self::normalize($expectedHeaders, FALSE);
|
||||
$expectedHeaders = array_change_key_case(self::parseLines($expectedHeaders, ':'), CASE_LOWER);
|
||||
foreach ($expectedHeaders as $name => $header) {
|
||||
if (!isset($headers[$name])) {
|
||||
throw new TestCaseException("Missing header '$name'.");
|
||||
|
||||
} elseif (!$this->compare($headers[$name], $header)) {
|
||||
throw new TestCaseException("Header '$name' doesn't match.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$tests) { // expecting no output
|
||||
if (trim($output) !== '') {
|
||||
throw new TestCaseException("Empty output doesn't match.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Sets PHP command line.
|
||||
* @param string
|
||||
* @param string
|
||||
* @param string
|
||||
* @return TestCase provides a fluent interface
|
||||
*/
|
||||
public function setPhp($binary, $args, $environment)
|
||||
{
|
||||
if (isset(self::$cachedPhp[$binary])) {
|
||||
$this->phpVersion = self::$cachedPhp[$binary];
|
||||
|
||||
} else {
|
||||
exec($environment . escapeshellarg($binary) . ' -v', $output, $res);
|
||||
if ($res !== 0 && $res !== 255) {
|
||||
throw new Exception("Unable to execute '$binary -v'.");
|
||||
}
|
||||
|
||||
if (!preg_match('#^PHP (\S+).*cli#i', $output[0], $matches)) {
|
||||
throw new Exception("Unable to detect PHP version (output: $output[0]).");
|
||||
}
|
||||
|
||||
$this->phpVersion = self::$cachedPhp[$binary] = $matches[1];
|
||||
}
|
||||
|
||||
$this->cmdLine = $environment . escapeshellarg($binary) . $args;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Execute test.
|
||||
* @return array
|
||||
*/
|
||||
private function execute()
|
||||
{
|
||||
$this->headers = $this->output = NULL;
|
||||
|
||||
$tempFile = tempnam('', 'tmp');
|
||||
if (!$tempFile) {
|
||||
throw new Exception("Unable to create temporary file.");
|
||||
}
|
||||
|
||||
$command = $this->cmdLine;
|
||||
if (isset($this->sections['options']['phpini'])) {
|
||||
foreach (explode(';', $this->sections['options']['phpini']) as $item) {
|
||||
$command .= " -d " . escapeshellarg(trim($item));
|
||||
}
|
||||
}
|
||||
$command .= ' ' . escapeshellarg($this->file) . ' > ' . escapeshellarg($tempFile);
|
||||
|
||||
chdir(dirname($this->file));
|
||||
exec($command, $foo, $res);
|
||||
if ($res === 255) {
|
||||
// exit_status 255 => parse or fatal error
|
||||
|
||||
} elseif ($res !== 0) {
|
||||
throw new Exception("Unable to execute '$command'.");
|
||||
|
||||
}
|
||||
|
||||
$this->output = file_get_contents($tempFile);
|
||||
unlink($tempFile);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns test file section.
|
||||
* @return string
|
||||
*/
|
||||
public function getSection($name)
|
||||
{
|
||||
return isset($this->sections[$name]) ? $this->sections[$name] : NULL;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns test name.
|
||||
* @return string
|
||||
*/
|
||||
public function getName()
|
||||
{
|
||||
return $this->sections['options']['name'];
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns test output.
|
||||
* @return string
|
||||
*/
|
||||
public function getOutput()
|
||||
{
|
||||
return $this->output;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns output headers.
|
||||
* @return string
|
||||
*/
|
||||
public function getHeaders()
|
||||
{
|
||||
return $this->headers;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns expected output.
|
||||
* @return string
|
||||
*/
|
||||
public function getExpectedOutput()
|
||||
{
|
||||
if (isset($this->sections['expect'])) {
|
||||
return $this->sections['expect'];
|
||||
|
||||
} elseif (is_file($expFile = str_replace('.phpt', '', $this->file) . '.expect')) {
|
||||
return file_get_contents($expFile);
|
||||
|
||||
} else {
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns expected headers.
|
||||
* @return string
|
||||
*/
|
||||
public function getExpectedHeaders()
|
||||
{
|
||||
return $this->getSection('expectheaders');
|
||||
}
|
||||
|
||||
|
||||
|
||||
/********************* helpers ****************d*g**/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Splits file into sections.
|
||||
* @param string file
|
||||
* @return array
|
||||
*/
|
||||
public static function parseSections($testFile)
|
||||
{
|
||||
$content = file_get_contents($testFile);
|
||||
$sections = array(
|
||||
'options' => array(),
|
||||
);
|
||||
|
||||
// phpDoc
|
||||
$phpDoc = preg_match('#^/\*\*(.*?)\*/#ms', $content, $matches) ? trim($matches[1]) : '';
|
||||
preg_match_all('#^\s*\*\s*@(\S+)(.*)#mi', $phpDoc, $matches, PREG_SET_ORDER);
|
||||
foreach ($matches as $match) {
|
||||
$sections['options'][strtolower($match[1])] = isset($match[2]) ? trim($match[2]) : TRUE;
|
||||
}
|
||||
$sections['options']['name'] = preg_match('#^\s*\*\s*TEST:(.*)#mi', $phpDoc, $matches) ? trim($matches[1]) : $testFile;
|
||||
|
||||
// file parts
|
||||
$tmp = preg_split('#^-{3,}([^\s-]+)-{1,}(?:\r?\n|$)#m', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
|
||||
$i = 1;
|
||||
while (isset($tmp[$i])) {
|
||||
$sections[strtolower($tmp[$i])] = $tmp[$i+1];
|
||||
$i += 2;
|
||||
}
|
||||
return $sections;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Splits HTTP headers into array.
|
||||
* @param string
|
||||
* @param string
|
||||
* @return array
|
||||
*/
|
||||
public static function parseLines($raw, $separator)
|
||||
{
|
||||
$headers = array();
|
||||
foreach (explode("\r\n", $raw) as $header) {
|
||||
$a = strpos($header, $separator);
|
||||
if ($a !== FALSE) {
|
||||
$headers[trim(substr($header, 0, $a))] = (string) trim(substr($header, $a + 1));
|
||||
}
|
||||
}
|
||||
return $headers;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Compares results.
|
||||
* @param string
|
||||
* @param string
|
||||
* @return bool
|
||||
*/
|
||||
public static function compare($left, $right)
|
||||
{
|
||||
$right = strtr($right, array(
|
||||
'%a%' => '[^\r\n]+', // one or more of anything except the end of line characters
|
||||
'%a?%'=> '[^\r\n]*', // zero or more of anything except the end of line characters
|
||||
'%A%' => '.+', // one or more of anything including the end of line characters
|
||||
'%A?%'=> '.*', // zero or more of anything including the end of line characters
|
||||
'%s%' => '[\t ]+', // one or more white space characters except the end of line characters
|
||||
'%s?%'=> '[\t ]*', // zero or more white space characters except the end of line characters
|
||||
'%S%' => '\S+', // one or more of characters except the white space
|
||||
'%S?%'=> '\S*', // zero or more of characters except the white space
|
||||
'%c%' => '[^\r\n]', // a single character of any sort (except the end of line)
|
||||
'%d%' => '[0-9]+', // one or more digits
|
||||
'%d?%'=> '[0-9]*', // zero or more digits
|
||||
'%i%' => '[+-]?[0-9]+', // signed integer value
|
||||
'%f%' => '[+-]?\.?\d+\.?\d*(?:[Ee][+-]?\d+)?', // floating point number
|
||||
'%h%' => '[0-9a-fA-F]+',// one or more HEX digits
|
||||
'%ns%'=> '(?:[_0-9a-zA-Z\\\\]+\\\\|N)?',// PHP namespace
|
||||
'%[^' => '[^', // reg-exp
|
||||
'%[' => '[', // reg-exp
|
||||
']%' => ']+', // reg-exp
|
||||
|
||||
'.' => '\.', '\\' => '\\\\', '+' => '\+', '*' => '\*', '?' => '\?', '[' => '\[', '^' => '\^', ']' => '\]', '$' => '\$', '(' => '\(', ')' => '\)', // preg quote
|
||||
'{' => '\{', '}' => '\}', '=' => '\=', '!' => '\!', '>' => '\>', '<' => '\<', '|' => '\|', ':' => '\:', '-' => '\-', "\x00" => '\000', '#' => '\#', // preg quote
|
||||
));
|
||||
|
||||
return (bool) preg_match("#^$right$#s", $left);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Normalizes whitespace
|
||||
* @param string
|
||||
* @param bool
|
||||
* @return string
|
||||
*/
|
||||
public static function normalize($s, $keepTrailingSpaces)
|
||||
{
|
||||
$s = str_replace("\n", PHP_EOL, str_replace("\r\n", "\n", $s)); // normalize EOL
|
||||
if (!$keepTrailingSpaces) {
|
||||
$s = preg_replace("#[\t ]+(\r?\n)#", '$1', $s); // multiline right trim
|
||||
$s = rtrim($s); // ending trim
|
||||
}
|
||||
return $s;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Single test exception.
|
||||
*
|
||||
* @author David Grudl
|
||||
* @package Nette\Test
|
||||
*/
|
||||
class TestCaseException extends Exception
|
||||
{
|
||||
const SKIPPED = 1;
|
||||
|
||||
}
|
312
tests/NetteTest/TestHelpers.php
Normal file
312
tests/NetteTest/TestHelpers.php
Normal file
@@ -0,0 +1,312 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Nette Framework
|
||||
*
|
||||
* @copyright Copyright (c) 2004 David Grudl
|
||||
* @license http://nette.org/license Nette license
|
||||
* @link http://nette.org
|
||||
* @category Nette
|
||||
* @package Nette\Test
|
||||
*/
|
||||
|
||||
require dirname(__FILE__) . '/TestCase.php';
|
||||
|
||||
|
||||
/**
|
||||
* Test helpers.
|
||||
*
|
||||
* @author David Grudl
|
||||
* @package Nette\Test
|
||||
*/
|
||||
class TestHelpers
|
||||
{
|
||||
/** @var int */
|
||||
static public $maxDepth = 5;
|
||||
|
||||
/** @var array */
|
||||
private static $sections;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Configures PHP and environment.
|
||||
* @return void
|
||||
*/
|
||||
public static function startup()
|
||||
{
|
||||
error_reporting(E_ALL | E_STRICT);
|
||||
ini_set('display_errors', TRUE);
|
||||
ini_set('html_errors', FALSE);
|
||||
ini_set('log_errors', FALSE);
|
||||
|
||||
|
||||
$_SERVER = array_intersect_key($_SERVER, array_flip(array('PHP_SELF', 'SCRIPT_NAME', 'SERVER_ADDR', 'SERVER_SOFTWARE', 'HTTP_HOST', 'DOCUMENT_ROOT', 'OS')));
|
||||
$_SERVER['REQUEST_TIME'] = 1234567890;
|
||||
$_ENV = array();
|
||||
|
||||
if (PHP_SAPI !== 'cli') {
|
||||
header('Content-Type: text/plain; charset=utf-8');
|
||||
}
|
||||
|
||||
if (extension_loaded('xdebug')) {
|
||||
xdebug_disable();
|
||||
xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE);
|
||||
register_shutdown_function(array(__CLASS__, 'prepareSaveCoverage'));
|
||||
}
|
||||
|
||||
set_exception_handler(array(__CLASS__, 'exceptionHandler'));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Purges directory.
|
||||
* @param string
|
||||
* @return void
|
||||
*/
|
||||
public static function purge($dir)
|
||||
{
|
||||
@mkdir($dir); // @ - directory may already exist
|
||||
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::CHILD_FIRST) as $entry) {
|
||||
if ($entry->getBasename() === '.gitignore') {
|
||||
// ignore
|
||||
} elseif ($entry->isDir()) {
|
||||
rmdir($entry);
|
||||
} else {
|
||||
unlink($entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns current test section.
|
||||
* @param string
|
||||
* @param string
|
||||
* @return mixed
|
||||
*/
|
||||
public static function getSection($file, $section)
|
||||
{
|
||||
if (!isset(self::$sections[$file])) {
|
||||
self::$sections[$file] = TestCase::parseSections($file);
|
||||
}
|
||||
|
||||
$lowerSection = strtolower($section);
|
||||
if (!isset(self::$sections[$file][$lowerSection])) {
|
||||
throw new Exception("Missing section '$section' in file '$file'.");
|
||||
}
|
||||
|
||||
if (in_array($section, array('GET', 'POST', 'SERVER'), TRUE)) {
|
||||
return TestCase::parseLines(self::$sections[$file][$lowerSection], '=');
|
||||
} else {
|
||||
return self::$sections[$file][$lowerSection];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Writes new message.
|
||||
* @param string
|
||||
* @return void
|
||||
*/
|
||||
public static function note($message = NULL)
|
||||
{
|
||||
echo $message ? "$message\n\n" : "===\n\n";
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Dumps information about a variable in readable format.
|
||||
* @param mixed variable to dump
|
||||
* @param string
|
||||
* @return mixed variable itself or dump
|
||||
*/
|
||||
public static function dump($var, $message = NULL)
|
||||
{
|
||||
if ($message) {
|
||||
echo $message . (preg_match('#[.:?]$#', $message) ? ' ' : ': ');
|
||||
}
|
||||
|
||||
self::_dump($var, 0);
|
||||
echo "\n";
|
||||
return $var;
|
||||
}
|
||||
|
||||
|
||||
|
||||
private static function _dump(& $var, $level = 0)
|
||||
{
|
||||
static $tableUtf, $tableBin, $reBinary = '#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{10FFFF}]#u';
|
||||
if ($tableUtf === NULL) {
|
||||
foreach (range("\x00", "\xFF") as $ch) {
|
||||
if (ord($ch) < 32 && strpos("\r\n\t", $ch) === FALSE) $tableUtf[$ch] = $tableBin[$ch] = '\\x' . str_pad(dechex(ord($ch)), 2, '0', STR_PAD_LEFT);
|
||||
elseif (ord($ch) < 127) $tableUtf[$ch] = $tableBin[$ch] = $ch;
|
||||
else { $tableUtf[$ch] = $ch; $tableBin[$ch] = '\\x' . dechex(ord($ch)); }
|
||||
}
|
||||
$tableBin["\\"] = '\\\\';
|
||||
$tableBin["\r"] = '\\r';
|
||||
$tableBin["\n"] = '\\n';
|
||||
$tableBin["\t"] = '\\t';
|
||||
$tableUtf['\\x'] = $tableBin['\\x'] = '\\\\x';
|
||||
}
|
||||
|
||||
if (is_bool($var)) {
|
||||
echo ($var ? 'TRUE' : 'FALSE') . "\n";
|
||||
|
||||
} elseif ($var === NULL) {
|
||||
echo "NULL\n";
|
||||
|
||||
} elseif (is_int($var)) {
|
||||
echo "$var\n";
|
||||
|
||||
} elseif (is_float($var)) {
|
||||
$var = (string) $var;
|
||||
if (strpos($var, '.') === FALSE) $var .= '.0';
|
||||
echo "$var\n";
|
||||
|
||||
} elseif (is_string($var)) {
|
||||
$s = strtr($var, preg_match($reBinary, $var) || preg_last_error() ? $tableBin : $tableUtf);
|
||||
echo "\"$s\"\n";
|
||||
|
||||
} elseif (is_array($var)) {
|
||||
echo "array(";
|
||||
$space = str_repeat("\t", $level);
|
||||
|
||||
static $marker;
|
||||
if ($marker === NULL) $marker = uniqid("\x00", TRUE);
|
||||
if (empty($var)) {
|
||||
|
||||
} elseif (isset($var[$marker])) {
|
||||
echo " *RECURSION* ";
|
||||
|
||||
} elseif ($level < self::$maxDepth) {
|
||||
echo "\n";
|
||||
$vector = range(0, count($var) - 1) === array_keys($var);
|
||||
$var[$marker] = 0;
|
||||
foreach ($var as $k => &$v) {
|
||||
if ($k === $marker) continue;
|
||||
if ($vector) {
|
||||
echo "$space\t";
|
||||
} else {
|
||||
$k = is_int($k) ? $k : '"' . strtr($k, preg_match($reBinary, $k) || preg_last_error() ? $tableBin : $tableUtf) . '"';
|
||||
echo "$space\t$k => ";
|
||||
}
|
||||
self::_dump($v, $level + 1);
|
||||
}
|
||||
unset($var[$marker]);
|
||||
echo "$space";
|
||||
|
||||
} else {
|
||||
echo " ... ";
|
||||
}
|
||||
echo ")\n";
|
||||
|
||||
} elseif ($var instanceof Exception) {
|
||||
echo 'Exception ', get_class($var), ': ', ($var->getCode() ? '#' . $var->getCode() . ' ' : '') . $var->getMessage(), "\n";
|
||||
|
||||
} elseif (is_object($var)) {
|
||||
$arr = (array) $var;
|
||||
echo get_class($var) . "(";
|
||||
$space = str_repeat("\t", $level);
|
||||
|
||||
static $list = array();
|
||||
if (empty($arr)) {
|
||||
|
||||
} elseif (in_array($var, $list, TRUE)) {
|
||||
echo " *RECURSION* ";
|
||||
|
||||
} elseif ($level < self::$maxDepth) {
|
||||
echo "\n";
|
||||
$list[] = $var;
|
||||
foreach ($arr as $k => &$v) {
|
||||
$m = '';
|
||||
if ($k[0] === "\x00") {
|
||||
$m = $k[1] === '*' ? ' protected' : ' private';
|
||||
$k = substr($k, strrpos($k, "\x00") + 1);
|
||||
}
|
||||
$k = strtr($k, preg_match($reBinary, $k) || preg_last_error() ? $tableBin : $tableUtf);
|
||||
echo "$space\t\"$k\"$m => ";
|
||||
echo self::_dump($v, $level + 1);
|
||||
}
|
||||
array_pop($list);
|
||||
echo "$space";
|
||||
|
||||
} else {
|
||||
echo " ... ";
|
||||
}
|
||||
echo ")\n";
|
||||
|
||||
} elseif (is_resource($var)) {
|
||||
echo get_resource_type($var) . " resource\n";
|
||||
|
||||
} else {
|
||||
echo "unknown type\n";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Custom exception handler.
|
||||
* @param Exception
|
||||
* @return void
|
||||
*/
|
||||
public static function exceptionHandler(Exception $exception)
|
||||
{
|
||||
echo 'Error: Uncaught ';
|
||||
echo $exception;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Coverage saving helper.
|
||||
* @return void
|
||||
*/
|
||||
public static function prepareSaveCoverage()
|
||||
{
|
||||
register_shutdown_function(array(__CLASS__, 'saveCoverage'));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Saves information about code coverage.
|
||||
* @return void
|
||||
*/
|
||||
public static function saveCoverage()
|
||||
{
|
||||
$file = dirname(__FILE__) . '/coverage.tmp';
|
||||
$coverage = @unserialize(file_get_contents($file));
|
||||
$root = realpath(dirname(__FILE__) . '/../../Nette') . DIRECTORY_SEPARATOR;
|
||||
|
||||
foreach (xdebug_get_code_coverage() as $filename => $lines) {
|
||||
if (strncmp($root, $filename, strlen($root))) continue;
|
||||
|
||||
foreach ($lines as $num => $val) {
|
||||
if (empty($coverage[$filename][$num]) || $val > 0) {
|
||||
$coverage[$filename][$num] = $val; // -1 => untested; -2 => dead code
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
file_put_contents($file, serialize($coverage));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Skips this test.
|
||||
* @return void
|
||||
*/
|
||||
public static function skip($message = 'No message.')
|
||||
{
|
||||
header('X-Nette-Test-Skip: '. $message);
|
||||
exit;
|
||||
}
|
||||
|
||||
}
|
230
tests/NetteTest/TestRunner.php
Normal file
230
tests/NetteTest/TestRunner.php
Normal file
@@ -0,0 +1,230 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Nette Framework
|
||||
*
|
||||
* @copyright Copyright (c) 2004 David Grudl
|
||||
* @license http://nette.org/license Nette license
|
||||
* @link http://nette.org
|
||||
* @category Nette
|
||||
* @package Nette\Test
|
||||
*/
|
||||
|
||||
require dirname(__FILE__) . '/TestCase.php';
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Test runner.
|
||||
*
|
||||
* @author David Grudl
|
||||
* @package Nette\Test
|
||||
*/
|
||||
class TestRunner
|
||||
{
|
||||
const OUTPUT = 'output';
|
||||
const EXPECTED = 'expect';
|
||||
const HEADERS = 'headers';
|
||||
|
||||
/** @var string path to test file/directory */
|
||||
public $path;
|
||||
|
||||
/** @var string php-cgi binary */
|
||||
public $phpBinary;
|
||||
|
||||
/** @var string php-cgi command-line arguments */
|
||||
public $phpArgs;
|
||||
|
||||
/** @var string php-cgi environment variables */
|
||||
public $phpEnvironment;
|
||||
|
||||
/** @var bool display skipped tests information? */
|
||||
public $displaySkipped = FALSE;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Runs all tests.
|
||||
* @return void
|
||||
*/
|
||||
public function run()
|
||||
{
|
||||
$count = 0;
|
||||
$failed = $passed = $skipped = array();
|
||||
|
||||
if (is_file($this->path)) {
|
||||
$files = array($this->path);
|
||||
} else {
|
||||
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->path));
|
||||
}
|
||||
|
||||
foreach ($files as $entry) {
|
||||
$entry = (string) $entry;
|
||||
$info = pathinfo($entry);
|
||||
if (!isset($info['extension']) || $info['extension'] !== 'phpt') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$count++;
|
||||
$testCase = new TestCase($entry);
|
||||
$testCase->setPhp($this->phpBinary, $this->phpArgs, $this->phpEnvironment);
|
||||
|
||||
try {
|
||||
$testCase->run();
|
||||
echo '.';
|
||||
$passed[] = array($testCase->getName(), $entry);
|
||||
|
||||
} catch (TestCaseException $e) {
|
||||
if ($e->getCode() === TestCaseException::SKIPPED) {
|
||||
echo 's';
|
||||
$skipped[] = array($testCase->getName(), $entry, $e->getMessage());
|
||||
|
||||
} else {
|
||||
echo 'F';
|
||||
$failed[] = array($testCase->getName(), $entry, $e->getMessage());
|
||||
|
||||
$this->log($entry, $testCase->getOutput(), self::OUTPUT);
|
||||
$this->log($entry, $testCase->getExpectedOutput(), self::EXPECTED);
|
||||
|
||||
if ($testCase->getExpectedHeaders() !== NULL) {
|
||||
$this->log($entry, $testCase->getHeaders(), self::OUTPUT, self::HEADERS);
|
||||
$this->log($entry, $testCase->getExpectedHeaders(), self::EXPECTED, self::HEADERS);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$failedCount = count($failed);
|
||||
$skippedCount = count($skipped);
|
||||
|
||||
if ($this->displaySkipped && $skippedCount) {
|
||||
echo "\n\nSkipped:\n";
|
||||
foreach ($skipped as $i => $item) {
|
||||
list($name, $file, $message) = $item;
|
||||
echo "\n", ($i + 1), ") $name\n $message\n $file\n";
|
||||
}
|
||||
}
|
||||
|
||||
if (!$count) {
|
||||
echo "No tests found\n";
|
||||
|
||||
} elseif ($failedCount) {
|
||||
echo "\n\nFailures:\n";
|
||||
foreach ($failed as $i => $item) {
|
||||
list($name, $file, $message) = $item;
|
||||
echo "\n", ($i + 1), ") $name\n $message\n $file\n";
|
||||
}
|
||||
echo "\nFAILURES! ($count tests, $failedCount failures, $skippedCount skipped)\n";
|
||||
return FALSE;
|
||||
|
||||
} else {
|
||||
echo "\n\nOK ($count tests, $skippedCount skipped)\n";
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns output file for logging.
|
||||
* @param string
|
||||
* @param string
|
||||
* @param string
|
||||
* @param string
|
||||
* @return void
|
||||
*/
|
||||
public function log($testFile, $content, $type, $section = '')
|
||||
{
|
||||
$file = dirname($testFile) . '/' . $type . '/' . basename($testFile, '.phpt') . ($section ? ".$section" : '') . '.raw';
|
||||
@mkdir(dirname($file)); // @ - directory may already exist
|
||||
file_put_contents($file, $content);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Parses configuration file.
|
||||
* @return void
|
||||
*/
|
||||
public function parseConfigFile()
|
||||
{
|
||||
$configFile = dirname(__FILE__) . '/config.ini';
|
||||
if (file_exists($configFile)) {
|
||||
$this->config = parse_ini_file($configFile, TRUE);
|
||||
if ($this->config === FALSE) {
|
||||
throw new Exception('Config file parsing failed.');
|
||||
}
|
||||
foreach ($this->config as & $environment) {
|
||||
$environment += array(
|
||||
'binary' => 'php-cgi',
|
||||
'args' => '',
|
||||
'environment' => '',
|
||||
);
|
||||
// shorthand options
|
||||
if (isset($environment['php.ini'])) {
|
||||
$environment['args'] .= ' -c '. escapeshellarg($environment['php.ini']);
|
||||
}
|
||||
if (isset($environment['libraries'])) {
|
||||
$environment['environment'] .= 'LD_LIBRARY_PATH='. escapeshellarg($environment['libraries']) .' ';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Parses command line arguments.
|
||||
* @return void
|
||||
*/
|
||||
public function parseArguments()
|
||||
{
|
||||
$this->phpBinary = 'php-cgi';
|
||||
$this->phpArgs = '';
|
||||
$this->phpEnvironment = '';
|
||||
$this->path = getcwd(); // current directory
|
||||
|
||||
$args = new ArrayIterator(array_slice(isset($_SERVER['argv']) ? $_SERVER['argv'] : array(), 1));
|
||||
foreach ($args as $arg) {
|
||||
if (!preg_match('#^[-/][a-z]$#', $arg)) {
|
||||
if ($path = realpath($arg)) {
|
||||
$this->path = $path;
|
||||
} else {
|
||||
throw new Exception("Invalid path '$arg'.");
|
||||
}
|
||||
|
||||
} else switch ($arg[1]) {
|
||||
case 'p':
|
||||
$args->next();
|
||||
$this->phpBinary = $args->current();
|
||||
break;
|
||||
case 'c':
|
||||
case 'd':
|
||||
$args->next();
|
||||
$this->phpArgs .= " -$arg[1] " . escapeshellarg($args->current());
|
||||
break;
|
||||
case 'l':
|
||||
$args->next();
|
||||
$this->phpEnvironment .= 'LD_LIBRARY_PATH='. escapeshellarg($args->current()) . ' ';
|
||||
break;
|
||||
case 'e':
|
||||
$args->next();
|
||||
$name = $args->current();
|
||||
if (!isset($this->config[$name])) {
|
||||
throw new Exception("Unknown environment name '$name'.");
|
||||
}
|
||||
$this->phpBinary = $this->config[$name]['binary'];
|
||||
$this->phpArgs = $this->config[$name]['args'];
|
||||
$this->phpEnvironment = $this->config[$name]['environment'];
|
||||
break;
|
||||
case 's':
|
||||
$this->displaySkipped = TRUE;
|
||||
break;
|
||||
default:
|
||||
throw new Exception("Unknown option -$arg[1].");
|
||||
exit;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
67
tests/config.ini
Normal file
67
tests/config.ini
Normal file
@@ -0,0 +1,67 @@
|
||||
[mysql]
|
||||
driver = mysql
|
||||
host = localhost
|
||||
username = dibi
|
||||
password = dibi
|
||||
database = dibi_test
|
||||
charset = utf8
|
||||
|
||||
[mysqli]
|
||||
driver = mysqli
|
||||
host = localhost
|
||||
username = dibi
|
||||
password = dibi
|
||||
database = dibi_test
|
||||
charset = utf8
|
||||
|
||||
[sqlite]
|
||||
driver = sqlite
|
||||
database = DIR "/data/sample.sdb"
|
||||
|
||||
[sqlite3]
|
||||
driver = sqlite3
|
||||
database = DIR "/data/sample.sdb3"
|
||||
|
||||
[odbc]
|
||||
driver = odbc
|
||||
username = dibi
|
||||
password = dibi
|
||||
dsn = "Driver={Microsoft Access Driver (*.mdb)};Dbq=" DIR "/data/sample.mdb"
|
||||
|
||||
[postgresql]
|
||||
driver = postgre
|
||||
host = localhost
|
||||
port = 5432
|
||||
username = dibi
|
||||
password = dibi
|
||||
database = dibi_test
|
||||
persistent = TRUE
|
||||
|
||||
[sqlite-pdo]
|
||||
driver = pdo
|
||||
dsn = "sqlite2::" DIR "/data/sample.sdb"
|
||||
|
||||
[mysql-pdo]
|
||||
driver = pdo
|
||||
dsn = "mysql:dbname=dibi_test;host=localhost"
|
||||
username = dibi
|
||||
password = dibi
|
||||
|
||||
[mssql]
|
||||
driver = mssql
|
||||
host = localhost
|
||||
username = dibi
|
||||
password = dibi
|
||||
|
||||
[mssql2005]
|
||||
driver = mssql2005
|
||||
host = "(local)"
|
||||
username = dibi
|
||||
password = dibi
|
||||
database = dibi_test
|
||||
|
||||
[oracle]
|
||||
driver = oracle
|
||||
username = dibi
|
||||
password = dibi
|
||||
database = dibi_test
|
@@ -1,40 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Test: Cloning of DibiFluent
|
||||
*
|
||||
* @author David Grudl
|
||||
*/
|
||||
|
||||
use Tester\Assert;
|
||||
|
||||
require __DIR__ . '/bootstrap.php';
|
||||
|
||||
|
||||
dibi::connect($config['sqlite3']);
|
||||
|
||||
|
||||
$fluent = new DibiFluent(dibi::getConnection());
|
||||
$fluent->select('*')->from('table')->where('x=1');
|
||||
$dolly = clone $fluent;
|
||||
$dolly->where('y=1');
|
||||
$dolly->clause('FOO');
|
||||
|
||||
Assert::same( 'SELECT * FROM [table] WHERE x=1', (string) $fluent );
|
||||
Assert::same( 'SELECT * FROM [table] WHERE x=1 AND y=1 FOO', (string) $dolly );
|
||||
|
||||
|
||||
$fluent = dibi::select('id')->from('table')->where('id = %i',1);
|
||||
$dolly = clone $fluent;
|
||||
$dolly->where('cd = %i',5);
|
||||
|
||||
Assert::same( 'SELECT [id] FROM [table] WHERE id = 1', (string) $fluent );
|
||||
Assert::same( 'SELECT [id] FROM [table] WHERE id = 1 AND cd = 5', (string) $dolly );
|
||||
|
||||
|
||||
$fluent = dibi::select("*")->from("table");
|
||||
$dolly = clone $fluent;
|
||||
$dolly->removeClause("select")->select("count(*)");
|
||||
|
||||
Assert::same( 'SELECT * FROM [table]', (string) $fluent );
|
||||
Assert::same( 'SELECT count(*) FROM [table]', (string) $dolly );
|
@@ -1,23 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Test: DateTimeInterface of DibiTranslator
|
||||
*
|
||||
* @author Patrik Votoček
|
||||
* @phpversion 5.5
|
||||
*/
|
||||
|
||||
use Tester\Assert;
|
||||
|
||||
require __DIR__ . '/bootstrap.php';
|
||||
|
||||
$connection = new DibiConnection(array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => ':memory:',
|
||||
));
|
||||
$translator = new DibiTranslator($connection);
|
||||
|
||||
$datetime = new DateTime('1978-01-23 00:00:00');
|
||||
|
||||
Assert::equal($datetime->format('U'), $translator->formatValue(new DateTime($datetime->format('c')), NULL));
|
||||
Assert::equal($datetime->format('U'), $translator->formatValue(new DateTimeImmutable($datetime->format('c')), NULL));
|
@@ -1,18 +0,0 @@
|
||||
<?php
|
||||
|
||||
// The Nette Tester command-line runner can be
|
||||
// invoked through the command: ../../vendor/bin/tester .
|
||||
|
||||
if (@!include __DIR__ . '/../../vendor/autoload.php') {
|
||||
echo 'Install Nette Tester using `composer update --dev`';
|
||||
exit(1);
|
||||
}
|
||||
|
||||
|
||||
// configure environment
|
||||
Tester\Environment::setup();
|
||||
date_default_timezone_set('Europe/Prague');
|
||||
|
||||
|
||||
// load connections
|
||||
$config = require __DIR__ . '/config.php';
|
@@ -1,77 +0,0 @@
|
||||
<?php
|
||||
|
||||
return array(
|
||||
'mysql' => array(
|
||||
'driver' => 'mysql',
|
||||
'host' => 'localhost',
|
||||
'username' => 'root',
|
||||
'password' => 'xxx',
|
||||
'charset' => 'utf8',
|
||||
),
|
||||
|
||||
'mysqli' => array(
|
||||
'driver' => 'mysqli',
|
||||
'host' => 'localhost',
|
||||
'username' => 'dibi',
|
||||
'password' => 'dibi',
|
||||
'charset' => 'utf8',
|
||||
),
|
||||
|
||||
'sqlite' => array(
|
||||
'driver' => 'sqlite',
|
||||
'database' => dirname(__FILE__) . '/data/sample.sdb',
|
||||
),
|
||||
|
||||
'sqlite3' => array(
|
||||
'driver' => 'sqlite3',
|
||||
'database' => dirname(__FILE__) . '/data/sample.sdb3',
|
||||
),
|
||||
|
||||
'odbc' => array(
|
||||
'driver' => 'odbc',
|
||||
'username' => 'dibi',
|
||||
'password' => 'dibi',
|
||||
'dsn' => 'Driver={Microsoft Access Driver (*.mdb)};Dbq=' . dirname(__FILE__) . '/data/sample.mdb',
|
||||
),
|
||||
|
||||
'postgresql' => array(
|
||||
'driver' => 'postgre',
|
||||
'host' => 'localhost',
|
||||
'port' => '5432',
|
||||
'username' => 'dibi',
|
||||
'password' => 'dibi',
|
||||
'persistent' => '1',
|
||||
),
|
||||
|
||||
'sqlite-pdo' => array(
|
||||
'driver' => 'pdo',
|
||||
'dsn' => 'sqlite2::' . dirname(__FILE__) . '/data/sample.sdb',
|
||||
),
|
||||
|
||||
'mysql-pdo' => array(
|
||||
'driver' => 'pdo',
|
||||
'dsn' => 'mysql:host=localhost',
|
||||
'username' => 'dibi',
|
||||
'password' => 'dibi',
|
||||
),
|
||||
|
||||
'mssql' => array(
|
||||
'driver' => 'mssql',
|
||||
'host' => 'localhost',
|
||||
'username' => 'dibi',
|
||||
'password' => 'dibi',
|
||||
),
|
||||
|
||||
'mssql2005' => array(
|
||||
'driver' => 'mssql2005',
|
||||
'host' => '(local)',
|
||||
'username' => 'dibi',
|
||||
'password' => 'dibi',
|
||||
),
|
||||
|
||||
'oracle' => array(
|
||||
'driver' => 'oracle',
|
||||
'username' => 'dibi',
|
||||
'password' => 'dibi',
|
||||
),
|
||||
);
|
26
tests/initialize.php
Normal file
26
tests/initialize.php
Normal file
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Test initialization and helpers.
|
||||
*
|
||||
* @author David Grudl
|
||||
* @package Nette\Test
|
||||
*/
|
||||
|
||||
require dirname(__FILE__) . '/NetteTest/TestHelpers.php';
|
||||
require dirname(__FILE__) . '/NetteTest/Assert.php';
|
||||
require dirname(__FILE__) . '/../dibi/dibi.php';
|
||||
|
||||
date_default_timezone_set('Europe/Prague');
|
||||
|
||||
TestHelpers::startup();
|
||||
|
||||
if (function_exists('class_alias')) {
|
||||
class_alias('TestHelpers', 'T');
|
||||
} else {
|
||||
class T extends TestHelpers {}
|
||||
}
|
||||
|
||||
// load connections
|
||||
define('DIR', dirname(__FILE__));
|
||||
$config = parse_ini_file('config.ini', TRUE);
|
@@ -1,2 +0,0 @@
|
||||
[PHP]
|
||||
;extension_dir = "./ext"
|
@@ -1,3 +0,0 @@
|
||||
[PHP]
|
||||
extension_dir = "./ext"
|
||||
extension=php_sqlite3.dll
|
@@ -1 +1 @@
|
||||
Dibi 2.2.0 (released on 2014-06-02)
|
||||
Dibi 2.0.2 (revision $WCREV$ released on $WCDATE$)
|
||||
|
Reference in New Issue
Block a user