1
0
mirror of https://github.com/dg/dibi.git synced 2025-08-31 17:51:43 +02:00

Compare commits

...

92 Commits

Author SHA1 Message Date
David Grudl
5970db58aa Released version 2.3.0 2015-01-25 17:24:28 +01:00
David Grudl
5ea37c9894 Merge pull request #160 from milo/pull-pglike
Fix DibiPostgreDriver::escapeLike()
2015-01-23 17:26:05 +01:00
Miloslav Hůla
2892e3eae3 Postgre: added test for matching by %like 2015-01-23 09:29:58 +01:00
Miloslav Hůla
91e2d76a0a Postgre: fixed %like escaping [Closes #159] 2015-01-23 09:13:05 +01:00
David Grudl
97b50bd243 Dibi: $defaultDriver changed to mysqli [Closes #156] 2015-01-13 15:45:17 +01:00
David Grudl
97d4c8c35f Released 2.3.0-RC1 2015-01-13 15:35:18 +01:00
David Grudl
f7fd9104e9 removed bridge for Nette 2.0 (BC break) 2015-01-13 15:35:18 +01:00
David Grudl
a923ce7ecb dibi: named connections and activate() are deprecated (BC break) 2015-01-13 15:31:03 +01:00
David Grudl
9a95edf003 Merge pull request #149 from JirkaChadima/oracle-schema
Oracle: adds support for login schema option
2015-01-13 05:25:33 +01:00
MartyIX
23efb97b0c DibiFluent: add leftJoin and on to phpdoc. 2015-01-13 05:24:23 +01:00
Ondrej Brablc
3b96dc7012 DibiFirePhpLogger: save some header operations for sites with hundreds of sql queries. 2015-01-13 05:22:45 +01:00
Ondrej Brablc
39be00e08b DibiFirePhpLogger: Allow user defined size of json stream chunks [Closes #148] 2015-01-13 05:22:34 +01:00
Martin Hradil
d6826d62ed DibiTranslator: respect %if blocks for %lmt and %ofs as well [Closes #145][Closes #87] 2015-01-13 05:14:42 +01:00
Petr BAGR Smrkovský
9189d56c05 DibiResult: float detection locale fix [Closes #154] 2015-01-13 04:40:36 +01:00
David Grudl
26b167fe13 DibiMySqliDriver.php: fixes for HHVM 2015-01-12 11:01:46 +01:00
David Grudl
100f978b9b DibiPdoDriver: missing driver throws DibiNotSupportedException exception 2015-01-12 11:01:12 +01:00
David Grudl
8395abb04f added new tests 2015-01-12 10:41:07 +01:00
David Grudl
f5f4f786f1 tests: improved testing environment 2015-01-12 10:41:06 +01:00
David Grudl
59da4bd66a DibiDatabaseInfo: no table is returned as NULL 2015-01-12 08:58:28 +01:00
David Grudl
50782c037c DibiSqliteReflector: fixed detection of autoincrement 2015-01-12 08:58:27 +01:00
David Grudl
ddbf8c779e DibiOdbcDriver: compatible applyLimit 2015-01-12 04:45:30 +01:00
David Grudl
e2fe4d122e DibiPdoDriver: improved and fixed escaping 2015-01-12 04:45:30 +01:00
David Grudl
2082357f0c * .travis: added code checker 2015-01-10 19:11:30 +01:00
David Grudl
c11a97294a examples: improved Tracy examples 2015-01-10 19:07:29 +01:00
Ing. Andrej Poliak
4f315a0d74 DibiPostgreDriver: added support for pg_ping [Closes #144] 2015-01-10 18:41:56 +01:00
David Grudl
34deb6c04f Merge pull request #158 from paranoiq/patch-1
dump: added bunch of reserved words
2015-01-05 12:49:25 +01:00
Vlasta Neubauer
31122c1969 dump: added bunch of reserved words 2015-01-05 12:40:41 +01:00
David Grudl
f534c15f0e Merge pull request #155 from JirkaChadima/dbliblimitsupport
MSSQL: Adds limit support for PDO dblib driver on unix
2014-11-04 23:47:23 +01:00
Jirka Chadima
985f59a2b2 MSSQL: Adds limit support for PDO dblib driver on unix 2014-11-04 11:43:05 +01:00
David Grudl
6fc99254ab Merge pull request #152 from zeleznypa/master
Oracle does not support any brackets around table name
2014-10-26 14:01:41 +01:00
Pavel Zelezny
dc688f3ee7 Oracle use double quotes for escaping 2014-10-26 13:56:34 +01:00
Jirka Chadima
4e99d7821c Oracle: adds support for login schema option 2014-10-21 17:01:59 +02:00
David Grudl
cde5af7cbe Merge pull request #142 from JanRossler/multi-search-path
PostgreSQL: fixed identifier escaping in reflection.
2014-07-16 17:46:08 +02:00
Rossler Jan
7c35e49a1c PostgreSQL: fixed identifier escaping in reflection. 2014-07-16 14:06:14 +02:00
David Grudl
6b08cf0711 Merge pull request #140 from JanRossler/multi-search-path
PostgreSQL: fixed search path resolution in table and column reflection.
2014-07-16 11:46:38 +02:00
David Grudl
4b0ebc76b0 Merge pull request #141 from JanRossler/php52
DibiDateTime: Restored php 5.2 support.
2014-07-15 12:46:42 +02:00
Rossler Jan
5993ea8aaf DibiDateTime: Restored php 5.2 support. 2014-07-15 12:39:51 +02:00
Rossler Jan
f89a2310cc PostgreSQL: fixed search path resolution in table and column reflection. 2014-07-07 01:51:56 +02:00
David Grudl
a118c2cf96 Released version 2.2.2 2014-06-30 17:08:04 +02:00
castamir
9b0e64220b Tracy loaded from composer instead of a local copy [Closes #139] 2014-06-30 14:52:44 +02:00
David Grudl
1c386d5582 typos 2014-06-30 14:52:43 +02:00
David Grudl
c9944b3886 Partially reverts "DibiTranslator: object is initialized in constructor", fixes lazy connection [Closes #138]
This reverts commit 0071b80938.
2014-06-24 21:40:54 +02:00
David Grudl
d0fd009dda readme.md: buy me a coffee 2014-06-13 17:54:46 +02:00
David Grudl
c32251357d fixed bug 'interface IBarPanel not found' [Closes #137] 2014-06-11 16:16:32 +02:00
David Grudl
c23d9c2866 Released version 2.2.0 2014-06-02 16:35:20 +02:00
David Grudl
60893a1c11 removed some old and deprecated stuff 2014-06-02 16:35:19 +02:00
David Grudl
f31d4a9afa tests: Nette\Debugger replaced with Tracy, examples requires PHP 5.3 2014-06-02 16:03:04 +02:00
David Grudl
abd3e2116c added bridge for Nette 2.2 & Tracy 2014-06-02 16:03:03 +02:00
David Grudl
e4e767048f fixed example 2014-06-02 16:03:03 +02:00
David Grudl
1ebb2deb83 file dibi.php split to Dibi class and loader dibi.php 2014-06-02 16:03:02 +02:00
David Grudl
47f8a6f88d bridges: changed file structure 2014-05-13 17:45:47 +02:00
Rossler Jan
fee5c294d8 PostgreSQL: added support for reflection of materialized views. 2014-05-13 17:45:46 +02:00
David Grudl
b14a4efbbb typos 2014-05-13 17:44:07 +02:00
David Grudl
6949f37a7a removed magic_quotes_runtime checking 2014-05-13 17:44:06 +02:00
David Grudl
e99ce9d053 updated test support files 2014-05-13 02:59:34 +02:00
Emmanuel еΜanwʬĔbdƎv
d4c72bbd4d readme.md: typos 2014-05-13 02:42:36 +02:00
Caspern
c802f9343a .gitattributes: ignoring some paths when downloading from github 2014-05-13 02:34:35 +02:00
David Grudl
771bdbe124 fixed test support files 2014-03-24 19:18:11 +01:00
David Grudl
1a4fca41a7 composer: added branch alias & PHP version 2014-03-24 19:08:18 +01:00
Patrik Votocek
176b1a8895 Add support for DateTimeInterface 2014-03-24 19:03:31 +01:00
David Grudl
0071b80938 DibiTranslator: object is initialized in constructor 2014-03-24 19:03:31 +01:00
David Grudl
4f64bd726b Merge pull request #129 from erikfercak/add_apostrophes_to_dates
Add aposthrophes back to dates
2014-02-22 04:08:22 +01:00
Erik Fercak
7fc3d76072 Add aposthrophes back to dates
Commit 7318658017 removed apostrophes from dates and that caused
dibi to build different queries. Compare:
...WHERE `date_created` < '2014-02-21';
vs.
...WHERE `date_created` < 2014-02-21;
2014-02-21 14:08:07 +01:00
David Grudl
a6cc588d91 Merge pull request #128 from brablc/master
Avoid error handler invocation
2014-02-20 19:38:54 +01:00
Ondrej Brablc
6666d71e5b Avoid error handler invocation 2014-02-20 18:47:35 +01:00
David Grudl
5082282e35 Merge pull request #127 from Ciki/patch-1
fix casting to float
2014-02-11 17:34:17 +01:00
Ciki
7cee7997e2 fix casting to float
Now, when sql returns float from (0,1) interval, e.g. '.842' - the decimal part is missing & it won't get cast to float.
This is fix for that situation
2014-02-11 17:04:19 +01:00
David Grudl
738c0c91ed DibiConnection::loadFile() supports DELIMITER [Closes #119] 2014-02-04 03:09:31 +01:00
David Grudl
2769f1ae0a typos 2014-02-04 03:09:31 +01:00
David Grudl
bf8fb69b9a Merge pull request #118 from emanwebdev/patch-1
Fix minor typos
2013-12-27 02:53:48 -08:00
Emmanuel еΜanwʬĔbdƎv
3780a42971 Fix minor typos 2013-12-27 11:33:16 +01:00
David Grudl
791d001bfd DibiDateTime: fixed buggy constructor 2013-12-19 04:21:45 +01:00
David Grudl
367b115ad2 DibiRow: null time checking consistent with DibiResult 2013-12-12 18:14:18 +01:00
Etienne CHAMPETIER
7318658017 Use DateTime instead of date()
On 32bits systems, date() is affected bug the 2038 bug
DateTime always uses 64bits representation [Closes #110]

Signed-off-by: Etienne CHAMPETIER <etienne.champetier@fiducial.net>
2013-12-12 18:14:17 +01:00
David Grudl
ddf7b74bf0 DibiDateTime: works with UNIX timestamps bigger than 32bits 2013-12-12 18:14:17 +01:00
Rossler Jan
30b5290c9d DibiDateTime: fixed unknown timezone error when serialized date includes the timezone (i. e. 'Y-m-d H:i:sP') [Closes #107] 2013-12-12 06:18:12 +01:00
David Grudl
a36678d3db Merge pull request #114 from JanTvrdik/master_array_typo
typo (array of foo -> foo[]) – master
2013-11-05 12:10:20 -08:00
Jan Tvrdik
530e7d30c9 typo 2013-10-24 21:15:48 +02:00
David Grudl
3b1e9e2632 typos 2013-10-17 01:20:44 +02:00
Rossler Jan
1b38d13422 DibiResult: fixed illegal offset type in fetchPairs. 2013-10-17 01:20:43 +02:00
daliborcaja
f348828223 DibiFluent::execute(dibi::AFFECTED_ROWS) returns number of affected rows 2013-10-17 01:20:42 +02:00
Jiří Pudil
5599dde525 Implemented getForeignKeys() in DibiMySqlReflector 2013-10-17 01:20:42 +02:00
Jan Tvrdik
32518eca54 composer.json: fix compatibility with dg/dibi requirements 2013-10-11 13:05:30 +02:00
David Grudl
a47395d16a Merge pull request #106 from enumag/patch-1
Fixed usage of deprecated parameter
2013-08-29 01:28:25 -07:00
Jáchym Toušek
a1f7413c9f Fixed usage of deprecated parameter 2013-08-29 03:02:11 +02:00
David Grudl
1728437f5d Merge pull request #101 from milo/fix-normalize-time
DibiResult: fixed normalization of time when begins by 00:
2013-08-11 11:59:28 -07:00
Miloslav Hůla
cf942c68ce DibiResult: fixed normalization of time when begins by 00: 2013-07-15 15:22:04 +02:00
David Grudl
e87c112d71 typos & whitespace 2013-07-13 20:23:13 +02:00
David Grudl
9e23730cb0 added examples to readme.md 2013-07-01 12:38:29 +02:00
David Grudl
a388767848 added .travis.yml & other files 2013-06-23 03:36:01 +02:00
David Grudl
bc59eb6a14 updated examples, SQlite3 is used instead of SQLite2 2013-06-23 02:34:15 +02:00
David Grudl
44aba8a986 opened 2.2-dev 2013-06-23 02:34:14 +02:00
109 changed files with 4143 additions and 3628 deletions

4
.gitattributes vendored Normal file
View File

@@ -0,0 +1,4 @@
.gitattributes export-ignore
.gitignore export-ignore
.travis.yml export-ignore
tests/ export-ignore

30
.travis.yml Normal file
View File

@@ -0,0 +1,30 @@
language: php
php:
- 5.3.3
- 5.4
- 5.5
- 5.6
- hhvm
matrix:
allow_failures:
- php: hhvm
script:
- vendor/bin/tester tests -s -p php -c tests/php-unix.ini
- php code-checker/src/code-checker.php
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 & Code Checker
- composer install --no-interaction --dev --prefer-source
- composer create-project nette/code-checker code-checker ~2.3 --no-interaction --prefer-source
# Create databases.ini
- cp ./tests/databases.sample.ini ./tests/databases.ini
# Create Postgre database
- psql -c 'CREATE DATABASE dibi_test' -U postgres

View File

@@ -1,19 +1,31 @@
{
"name": "dibi/dibi",
"description": "Dibi is Database Abstraction Library for PHP 5.",
"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", "GPLv2", "GPLv3"],
"homepage": "http://dibiphp.com",
"license": ["BSD-3-Clause", "GPL-2.0", "GPL-3.0"],
"authors": [
{
"name": "David Grudl",
"homepage": "http://davidgrudl.com"
}
],
"require": {
"php": ">=5.2.0"
},
"require-dev": {
"nette/tester": "@dev"
"tracy/tracy": "~2.2",
"nette/tester": "~1.3"
},
"replace": {
"dg/dibi": "self.version"
},
"autoload": {
"classmap": ["dibi/"]
},
"extra": {
"branch-alias": {
"dev-master": "2.3-dev"
}
}
}

View File

@@ -2,15 +2,10 @@
/**
* 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 extension for Nette Framework 2.1. Creates 'connection' service.
*
@@ -28,7 +23,7 @@ class DibiNette21Extension extends Nette\DI\CompilerExtension
$useProfiler = isset($config['profiler'])
? $config['profiler']
: !$container->parameters['productionMode'];
: $container->parameters['debugMode'];
unset($config['profiler']);

View File

@@ -2,19 +2,10 @@
/**
* 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');
}
use Nette\Diagnostics\Debugger;
/**
@@ -23,7 +14,7 @@ if (interface_exists('Nette\Diagnostics\IBarPanel')) {
* @author David Grudl
* @package dibi\nette
*/
class DibiNettePanel extends DibiObject implements IBarPanel
class DibiNettePanel extends DibiObject implements Nette\Diagnostics\IBarPanel
{
/** @var int maximum SQL length */
static public $maxLength = 1000;
@@ -38,7 +29,6 @@ class DibiNettePanel extends DibiObject implements IBarPanel
private $events = array();
public function __construct($explain = TRUE, $filter = NULL)
{
$this->filter = $filter ? (int) $filter : DibiEvent::QUERY;
@@ -46,31 +36,14 @@ 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)
NDebugger::$bar && NDebugger::$bar->addPanel($this);
NDebugger::$blueScreen && NDebugger::$blueScreen->addPanel(array(__CLASS__, '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
Debugger::$bar && Debugger::$bar->addPanel($this);
Debugger::$blueScreen && Debugger::$blueScreen->addPanel(array(__CLASS__, 'renderException'), __CLASS__);
$connection->onEvent[] = array($this, 'logEvent');
}
Debugger::getBar()->addPanel($this);
Debugger::getBlueScreen()->addPanel(array(__CLASS__, 'renderException'));
$connection->onEvent[] = array($this, 'logEvent');
}
/**
* After event notification.
* @return void
@@ -84,7 +57,6 @@ class DibiNettePanel extends DibiObject implements IBarPanel
}
/**
* Returns blue-screen custom tab.
* @return mixed
@@ -100,7 +72,6 @@ class DibiNettePanel extends DibiObject implements IBarPanel
}
/**
* Returns HTML code for custom tab. (Nette\Diagnostics\IBarPanel)
* @return mixed
@@ -113,12 +84,11 @@ 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', $totalTime * 1000) . 'ms' : '')
. ($totalTime ? sprintf(' / %0.1f ms', $totalTime * 1000) : '')
. '</span>';
}
/**
* Returns HTML code for custom panel. (Nette\Diagnostics\IBarPanel)
* @return mixed
@@ -166,7 +136,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 ? '' : ', time: ' . sprintf('%0.3f', $totalTime * 1000) . ' ms') . '</h1>
<h1>Queries: ' . count($this->events) . ($totalTime === NULL ? '' : sprintf(', time: %0.3f ms', $totalTime * 1000)) . '</h1>
<div class="nette-inner nette-DibiProfiler">
<table>
<tr><th>Time&nbsp;ms</th><th>SQL Statement</th><th>Rows</th><th>Connection</th></tr>' . $s . '

View File

@@ -2,23 +2,22 @@
/**
* 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.
*/
namespace Dibi\Bridges\Nette;
use dibi,
Nette;
/**
* Dibi extension for Nette Framework 2.0. Creates 'connection' service.
* Dibi extension for Nette Framework 2.2. Creates 'connection' & 'panel' services.
*
* @author David Grudl
* @package dibi\nette
* @phpversion 5.3
*/
class DibiNette20Extension extends Nette\Config\CompilerExtension
class DibiExtension22 extends Nette\DI\CompilerExtension
{
public function loadConfiguration()
@@ -28,7 +27,7 @@ class DibiNette20Extension extends Nette\Config\CompilerExtension
$useProfiler = isset($config['profiler'])
? $config['profiler']
: !$container->parameters['productionMode'];
: class_exists('Tracy\Debugger') && $container->parameters['debugMode'];
unset($config['profiler']);
@@ -45,11 +44,8 @@ class DibiNette20Extension extends Nette\Config\CompilerExtension
if ($useProfiler) {
$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'));
$connection->addSetup('$service->onEvent[] = ?', array(array($panel, 'logEvent')));
->setClass('Dibi\Bridges\Tracy\Panel');
$connection->addSetup(array($panel, 'register'), array($connection));
}
}

View File

@@ -0,0 +1,12 @@
# 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

View File

@@ -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

View File

@@ -0,0 +1,145 @@
<?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&nbsp;ms</th><th>SQL Statement</th><th>Rows</th><th>Connection</th></tr>' . $s . '
</table>
</div>';
}
}

View File

@@ -4,9 +4,6 @@
* 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.
*/
@@ -17,11 +14,9 @@ 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';
@@ -38,644 +33,3 @@ 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/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.1.0',
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);
// 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";
}
}
}

View File

@@ -2,11 +2,7 @@
/**
* 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.
*/
@@ -56,13 +52,12 @@ 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');
@@ -71,11 +66,13 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
} else {
// default values
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;
$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,
);
DibiDriverException::tryError();
if (empty($config['persistent'])) {
@@ -95,7 +92,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Disconnects from a database.
* @return void
@@ -106,7 +102,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Executes the SQL query.
* @param string SQL statement.
@@ -138,7 +133,6 @@ 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
@@ -149,7 +143,6 @@ 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
@@ -161,7 +154,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
@@ -178,7 +170,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Commits statements in a transaction.
* @param string optional savepoint name
@@ -199,7 +190,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
@@ -220,7 +210,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Is in transaction?
* @return bool
@@ -231,7 +220,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Returns the connection resource.
* @return resource
@@ -242,7 +230,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Returns the connection reflector.
* @return IDibiReflector
@@ -253,7 +240,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Result set driver factory.
* @param resource
@@ -267,11 +253,9 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/********************* SQL ********************/
/**
* Encodes data for use in a SQL statement.
* @param mixed value
@@ -282,29 +266,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:
return $value instanceof DateTime ? $value->format("'Y-m-d'") : date("'Y-m-d'", $value);
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::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.');
default:
throw new InvalidArgumentException('Unsupported type.');
}
}
/**
* Encodes string for use in a LIKE statement.
* @param string
@@ -317,7 +301,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Decodes data from result set.
* @param string value
@@ -334,28 +317,22 @@ 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 < 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 . ')';
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 . ')';
}
}
/********************* result set ********************/
/**
* Automatically frees the resources allocated for this result set.
* @return void
@@ -366,7 +343,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Returns the number of rows in a result set.
* @return int
@@ -377,7 +353,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Fetches the row at current position and moves the internal cursor to the next position.
* @param bool TRUE for associative array, FALSE for numeric
@@ -402,7 +377,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
@@ -415,7 +389,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Frees the resources allocated for this result set.
* @return void
@@ -427,10 +400,9 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Returns the result set resource.
* @return mysqli_result
* @return resource
*/
public function getResultResource()
{
@@ -439,7 +411,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Returns metadata for all columns in a result set.
* @return array
@@ -461,11 +432,9 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/********************* IDibiReflector ********************/
/**
* Returns list of tables.
* @return array
@@ -489,7 +458,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Returns metadata for all columns in a table.
* @param string
@@ -545,7 +513,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Returns metadata for all indexes in a table (the constraints are included).
* @param string
@@ -580,7 +547,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Returns metadata for all foreign keys in a table.
* @param string
@@ -611,7 +577,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Returns list of indices in given table (the constraints are not listed).
* @param string
@@ -634,7 +599,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Returns list of constraints in given table.
* @param string
@@ -659,7 +623,6 @@ 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)
@@ -709,7 +672,6 @@ 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)
@@ -732,7 +694,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Returns metadata from stored procedures and their input and output parameters.
* @param string
@@ -786,7 +747,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Returns list of stored procedures.
* @return array
@@ -805,7 +765,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Returns list of generators.
* @return array
@@ -825,7 +784,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Returns list of user defined functions (UDF).
* @return array
@@ -847,8 +805,6 @@ class DibiFirebirdDriver extends DibiObject implements IDibiDriver, IDibiResultD
}
/**
* Database procedure exception.
*
@@ -875,7 +831,6 @@ class DibiProcedureException extends DibiException
}
/**
* Gets the exception severity.
* @return string

View File

@@ -2,11 +2,7 @@
/**
* 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.
*/
@@ -44,7 +40,6 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
private $affectedRows = FALSE;
/**
* @throws DibiNotSupportedException
*/
@@ -56,13 +51,12 @@ 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');
@@ -74,7 +68,9 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
} else {
// Default values
if (!isset($config['options']['CharacterSet'])) $config['options']['CharacterSet'] = 'UTF-8';
if (!isset($config['options']['CharacterSet'])) {
$config['options']['CharacterSet'] = 'UTF-8';
}
$this->connection = sqlsrv_connect($config['host'], (array) $config['options']);
}
@@ -86,7 +82,6 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
}
/**
* Disconnects from a database.
* @return void
@@ -97,7 +92,6 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
}
/**
* Executes the SQL query.
* @param string SQL statement.
@@ -120,7 +114,6 @@ 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
@@ -131,7 +124,6 @@ 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
@@ -147,7 +139,6 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
}
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
@@ -160,7 +151,6 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
}
/**
* Commits statements in a transaction.
* @param string optional savepoint name
@@ -173,7 +163,6 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
}
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
@@ -186,7 +175,6 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
}
/**
* Returns the connection resource.
* @return mixed
@@ -197,7 +185,6 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
}
/**
* Returns the connection reflector.
* @return IDibiReflector
@@ -208,7 +195,6 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
}
/**
* Result set driver factory.
* @param resource
@@ -222,11 +208,9 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
}
/********************* SQL ****************d*g**/
/**
* Encodes data for use in a SQL statement.
* @param mixed value
@@ -237,30 +221,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(']', ']]', $value) . ']';
case dibi::BOOL:
return $value ? 1 : 0;
case dibi::BOOL:
return $value ? 1 : 0;
case dibi::DATE:
return $value instanceof DateTime ? $value->format("'Y-m-d'") : date("'Y-m-d'", $value);
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::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.');
default:
throw new InvalidArgumentException('Unsupported type.');
}
}
/**
* Encodes string for use in a LIKE statement.
* @param string
@@ -274,7 +258,6 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
}
/**
* Decodes data from result set.
* @param string value
@@ -291,15 +274,11 @@ 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) {
@@ -312,11 +291,9 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
}
/********************* result set ****************d*g**/
/**
* Automatically frees the resources allocated for this result set.
* @return void
@@ -327,7 +304,6 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
}
/**
* Returns the number of rows in a result set.
* @return int
@@ -338,7 +314,6 @@ 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
@@ -350,7 +325,6 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
}
/**
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
@@ -362,7 +336,6 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
}
/**
* Frees the resources allocated for this result set.
* @return void
@@ -374,7 +347,6 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
}
/**
* Returns metadata for all columns in a result set.
* @return array
@@ -393,7 +365,6 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
}
/**
* Returns the result set resource.
* @return mixed

View File

@@ -2,11 +2,7 @@
/**
* 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.
*/
@@ -23,14 +19,12 @@ class DibiMsSql2005Reflector extends DibiObject implements IDibiReflector
private $driver;
public function __construct(IDibiDriver $driver)
{
$this->driver = $driver;
}
/**
* Returns list of tables.
* @return array
@@ -49,7 +43,6 @@ class DibiMsSql2005Reflector extends DibiObject implements IDibiReflector
}
/**
* Returns metadata for all columns in a table.
* @param string
@@ -102,7 +95,6 @@ class DibiMsSql2005Reflector extends DibiObject implements IDibiReflector
}
/**
* Returns metadata for all indexes in a table.
* @param string
@@ -128,7 +120,6 @@ class DibiMsSql2005Reflector extends DibiObject implements IDibiReflector
}
/**
* Returns metadata for all foreign keys in a table.
* @param string

View File

@@ -2,11 +2,7 @@
/**
* 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';
@@ -38,7 +34,6 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
private $autoFree = TRUE;
/**
* @throws DibiNotSupportedException
*/
@@ -50,13 +45,12 @@ 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'];
@@ -76,7 +70,6 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Disconnects from a database.
* @return void
@@ -87,7 +80,6 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Executes the SQL query.
* @param string SQL statement.
@@ -107,7 +99,6 @@ 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
@@ -118,7 +109,6 @@ 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
@@ -134,7 +124,6 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
@@ -147,7 +136,6 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Commits statements in a transaction.
* @param string optional savepoint name
@@ -160,7 +148,6 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
@@ -173,7 +160,6 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Returns the connection resource.
* @return mixed
@@ -184,7 +170,6 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Returns the connection reflector.
* @return IDibiReflector
@@ -195,7 +180,6 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Result set driver factory.
* @param resource
@@ -209,11 +193,9 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/********************* SQL ****************d*g**/
/**
* Encodes data for use in a SQL statement.
* @param mixed value
@@ -224,30 +206,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:
return $value instanceof DateTime ? $value->format("'Y-m-d'") : date("'Y-m-d'", $value);
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::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.');
default:
throw new InvalidArgumentException('Unsupported type.');
}
}
/**
* Encodes string for use in a LIKE statement.
* @param string
@@ -261,7 +243,6 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Decodes data from result set.
* @param string value
@@ -278,15 +259,11 @@ 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) {
@@ -299,11 +276,9 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/********************* result set ****************d*g**/
/**
* Automatically frees the resources allocated for this result set.
* @return void
@@ -314,7 +289,6 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Returns the number of rows in a result set.
* @return int
@@ -325,7 +299,6 @@ 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
@@ -337,7 +310,6 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
@@ -349,7 +321,6 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Frees the resources allocated for this result set.
* @return void
@@ -361,7 +332,6 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Returns metadata for all columns in a result set.
* @return array
@@ -383,7 +353,6 @@ class DibiMsSqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Returns the result set resource.
* @return mixed

View File

@@ -5,9 +5,6 @@
*
* 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
*/
@@ -25,14 +22,12 @@ class DibiMsSqlReflector extends DibiObject implements IDibiReflector
private $driver;
public function __construct(IDibiDriver $driver)
{
$this->driver = $driver;
}
/**
* Returns list of tables.
* @return array
@@ -54,7 +49,6 @@ class DibiMsSqlReflector extends DibiObject implements IDibiReflector
}
/**
* Returns count of rows in a table
* @param string
@@ -87,7 +81,6 @@ class DibiMsSqlReflector extends DibiObject implements IDibiReflector
}
/**
* Returns metadata for all columns in a table.
* @param string
@@ -138,7 +131,6 @@ class DibiMsSqlReflector extends DibiObject implements IDibiReflector
}
/**
* Returns metadata for all indexes in a table.
* @param string
@@ -180,7 +172,6 @@ class DibiMsSqlReflector extends DibiObject implements IDibiReflector
}
/**
* Returns metadata for all foreign keys in a table.
* @param string

View File

@@ -2,11 +2,7 @@
/**
* 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.
*/
@@ -53,7 +49,6 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
private $buffered;
/**
* @throws DibiNotSupportedException
*/
@@ -65,13 +60,12 @@ 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'];
@@ -79,17 +73,21 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
} else {
// default values
DibiConnection::alias($config, 'flags', 'options');
if (!isset($config['charset'])) $config['charset'] = 'utf8';
if (!isset($config['timezone'])) $config['timezone'] = date('P');
if (!isset($config['username'])) $config['username'] = ini_get('mysql.default_user');
if (!isset($config['password'])) $config['password'] = ini_get('mysql.default_password');
$config += array(
'charset' => 'utf8',
'timezone' => date('P'),
'username' => ini_get('mysql.default_user'),
'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;
}
}
@@ -140,7 +138,6 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Disconnects from a database.
* @return void
@@ -151,7 +148,6 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Executes the SQL query.
* @param string SQL statement.
@@ -175,7 +171,6 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Retrieves information about the most recently executed query.
* @return array
@@ -184,7 +179,9 @@ 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];
@@ -193,7 +190,6 @@ 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
@@ -204,7 +200,6 @@ 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
@@ -215,7 +210,6 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
@@ -228,7 +222,6 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Commits statements in a transaction.
* @param string optional savepoint name
@@ -241,7 +234,6 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
@@ -254,7 +246,6 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Returns the connection resource.
* @return mixed
@@ -265,7 +256,6 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Returns the connection reflector.
* @return IDibiReflector
@@ -276,7 +266,6 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Result set driver factory.
* @param resource
@@ -290,11 +279,9 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/********************* SQL ****************d*g**/
/**
* Encodes data for use in a SQL statement.
* @param mixed value
@@ -305,38 +292,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:
return $value instanceof DateTime ? $value->format("'Y-m-d'") : date("'Y-m-d'", $value);
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::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.');
default:
throw new InvalidArgumentException('Unsupported type.');
}
}
/**
* Encodes string for use in a LIKE statement.
* @param string
@@ -350,7 +337,6 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Decodes data from result set.
* @param string value
@@ -367,29 +353,23 @@ 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 < 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 : '');
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 : '');
}
}
/********************* result set ****************d*g**/
/**
* Automatically frees the resources allocated for this result set.
* @return void
@@ -400,7 +380,6 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Returns the number of rows in a result set.
* @return int
@@ -414,7 +393,6 @@ 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
@@ -426,7 +404,6 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
@@ -443,7 +420,6 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Frees the resources allocated for this result set.
* @return void
@@ -455,7 +431,6 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Returns metadata for all columns in a result set.
* @return array
@@ -478,7 +453,6 @@ class DibiMySqlDriver extends DibiObject implements IDibiDriver, IDibiResultDriv
}
/**
* Returns the result set resource.
* @return mixed

View File

@@ -2,11 +2,7 @@
/**
* 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.
*/
@@ -23,14 +19,12 @@ class DibiMySqlReflector extends DibiObject implements IDibiReflector
private $driver;
public function __construct(IDibiDriver $driver)
{
$this->driver = $driver;
}
/**
* Returns list of tables.
* @return array
@@ -54,7 +48,6 @@ class DibiMySqlReflector extends DibiObject implements IDibiReflector
}
/**
* Returns metadata for all columns in a table.
* @param string
@@ -88,7 +81,6 @@ class DibiMySqlReflector extends DibiObject implements IDibiReflector
}
/**
* Returns metadata for all indexes in a table.
* @param string
@@ -115,15 +107,44 @@ 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)
{
throw new DibiNotImplementedException;
$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);
}
}

View File

@@ -2,11 +2,7 @@
/**
* 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.
*/
@@ -54,7 +50,6 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
private $buffered;
/**
* @throws DibiNotSupportedException
*/
@@ -66,13 +61,12 @@ 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'])) {
@@ -80,12 +74,14 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
} else {
// default values
if (!isset($config['charset'])) $config['charset'] = 'utf8';
if (!isset($config['timezone'])) $config['timezone'] = date('P');
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;
$config += array(
'charset' => 'utf8',
'timezone' => date('P'),
'username' => ini_get('mysqli.default_user'),
'password' => ini_get('mysqli.default_pw'),
'socket' => (string) ini_get('mysqli.default_socket'),
'port' => NULL,
);
if (!isset($config['host'])) {
$host = ini_get('mysqli.default_host');
if ($host) {
@@ -119,12 +115,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
if (isset($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) {
if (!@mysqli_set_charset($this->connection, $config['charset'])) {
$this->query("SET NAMES '$config[charset]'");
}
}
@@ -141,7 +132,6 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Disconnects from a database.
* @return void
@@ -152,7 +142,6 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Executes the SQL query.
* @param string SQL statement.
@@ -172,7 +161,6 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Retrieves information about the most recently executed query.
* @return array
@@ -181,7 +169,9 @@ 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];
@@ -190,7 +180,6 @@ 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
@@ -201,7 +190,6 @@ class DibiMySqliDriver 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
@@ -212,7 +200,6 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
@@ -225,7 +212,6 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Commits statements in a transaction.
* @param string optional savepoint name
@@ -238,7 +224,6 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
@@ -251,7 +236,6 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Returns the connection resource.
* @return mysqli
@@ -262,7 +246,6 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Returns the connection reflector.
* @return IDibiReflector
@@ -273,7 +256,6 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Result set driver factory.
* @param mysqli_result
@@ -287,11 +269,9 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/********************* SQL ****************d*g**/
/**
* Encodes data for use in a SQL statement.
* @param mixed value
@@ -302,31 +282,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:
return $value instanceof DateTime ? $value->format("'Y-m-d'") : date("'Y-m-d'", $value);
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::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.');
default:
throw new InvalidArgumentException('Unsupported type.');
}
}
/**
* Encodes string for use in a LIKE statement.
* @param string
@@ -340,7 +320,6 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Decodes data from result set.
* @param string value
@@ -357,29 +336,23 @@ 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 < 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 : '');
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 : '');
}
}
/********************* result set ****************d*g**/
/**
* Automatically frees the resources allocated for this result set.
* @return void
@@ -390,7 +363,6 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Returns the number of rows in a result set.
* @return int
@@ -404,7 +376,6 @@ 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
@@ -416,7 +387,6 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
@@ -432,7 +402,6 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Frees the resources allocated for this result set.
* @return void
@@ -444,7 +413,6 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Returns metadata for all columns in a result set.
* @return array
@@ -452,9 +420,10 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
public function getResultColumns()
{
static $types;
if (empty($types)) {
if ($types === NULL) {
$consts = get_defined_constants(TRUE);
foreach ($consts['mysqli'] as $key => $value) {
$types = array();
foreach (isset($consts['mysqli']) ? $consts['mysqli'] : array() as $key => $value) {
if (strncmp($key, 'MYSQLI_TYPE_', 12) === 0) {
$types[$value] = substr($key, 12);
}
@@ -470,7 +439,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
'name' => $row['name'],
'table' => $row['orgtable'],
'fullname' => $row['table'] ? $row['table'] . '.' . $row['name'] : $row['name'],
'nativetype' => $types[$row['type']],
'nativetype' => isset($types[$row['type']]) ? $types[$row['type']] : $row['type'],
'vendor' => $row,
);
}
@@ -478,7 +447,6 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Returns the result set resource.
* @return mysqli_result
@@ -486,7 +454,7 @@ class DibiMySqliDriver extends DibiObject implements IDibiDriver, IDibiResultDri
public function getResultResource()
{
$this->autoFree = FALSE;
return @$this->resultSet->type === NULL ? NULL : $this->resultSet;
return $this->resultSet;
}
}

View File

@@ -2,11 +2,7 @@
/**
* 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.
*/
@@ -42,7 +38,6 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
private $row = 0;
/**
* @throws DibiNotSupportedException
*/
@@ -54,21 +49,22 @@ 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
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');
$config += array(
'username' => ini_get('odbc.default_user'),
'password' => ini_get('odbc.default_pw'),
'dsn' => ini_get('odbc.default_db'),
);
if (empty($config['persistent'])) {
$this->connection = @odbc_connect($config['dsn'], $config['username'], $config['password']); // intentionally @
@@ -83,7 +79,6 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/**
* Disconnects from a database.
* @return void
@@ -94,7 +89,6 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/**
* Executes the SQL query.
* @param string SQL statement.
@@ -116,7 +110,6 @@ 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
@@ -127,7 +120,6 @@ 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
@@ -138,7 +130,6 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
@@ -153,7 +144,6 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/**
* Commits statements in a transaction.
* @param string optional savepoint name
@@ -169,7 +159,6 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
@@ -185,7 +174,6 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/**
* Is in transaction?
* @return bool
@@ -196,7 +184,6 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/**
* Returns the connection resource.
* @return mixed
@@ -207,7 +194,6 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/**
* Returns the connection reflector.
* @return IDibiReflector
@@ -218,7 +204,6 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/**
* Result set driver factory.
* @param resource
@@ -232,11 +217,9 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/********************* SQL ****************d*g**/
/**
* Encodes data for use in a SQL statement.
* @param mixed value
@@ -247,29 +230,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:
return $value instanceof DateTime ? $value->format("#m/d/Y#") : date("#m/d/Y#", $value);
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::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.');
default:
throw new InvalidArgumentException('Unsupported type.');
}
}
/**
* Encodes string for use in a LIKE statement.
* @param string
@@ -283,7 +266,6 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/**
* Decodes data from result set.
* @param string value
@@ -300,30 +282,26 @@ 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 . ')';
$sql = 'SELECT TOP ' . (int) $limit . ' * FROM (' . $sql . ') t';
}
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
@@ -334,7 +312,6 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/**
* Returns the number of rows in a result set.
* @return int
@@ -346,7 +323,6 @@ 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
@@ -358,7 +334,9 @@ 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);
@@ -367,7 +345,6 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/**
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
@@ -380,7 +357,6 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/**
* Frees the resources allocated for this result set.
* @return void
@@ -392,7 +368,6 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/**
* Returns metadata for all columns in a result set.
* @return array
@@ -413,7 +388,6 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/**
* Returns the result set resource.
* @return mixed
@@ -425,11 +399,9 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/********************* IDibiReflector ****************d*g**/
/**
* Returns list of tables.
* @return array
@@ -451,7 +423,6 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/**
* Returns metadata for all columns in a table.
* @param string
@@ -478,7 +449,6 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/**
* Returns metadata for all indexes in a table.
* @param string
@@ -490,7 +460,6 @@ class DibiOdbcDriver extends DibiObject implements IDibiDriver, IDibiResultDrive
}
/**
* Returns metadata for all foreign keys in a table.
* @param string

View File

@@ -2,11 +2,7 @@
/**
* 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.
*/
@@ -18,6 +14,7 @@
* - username (or user)
* - password (or pass)
* - charset => character encoding to set
* - schema => alters session schema
* - formatDate => how to format date in SQL (@see date)
* - formatDateTime => how to format datetime in SQL (@see date)
* - resource (resource) => existing connection resource
@@ -45,7 +42,6 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
private $fmtDate, $fmtDateTime;
/**
* @throws DibiNotSupportedException
*/
@@ -57,13 +53,12 @@ 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';
@@ -81,8 +76,11 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
$err = oci_error();
throw new DibiDriverException($err['message'], $err['code']);
}
}
if (isset($config['schema'])) {
$this->query('ALTER SESSION SET CURRENT_SCHEMA=' . $config['schema']);
}
}
/**
@@ -95,7 +93,6 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Executes the SQL query.
* @param string SQL statement.
@@ -121,7 +118,6 @@ 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
@@ -132,7 +128,6 @@ 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
@@ -144,7 +139,6 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
@@ -156,7 +150,6 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Commits statements in a transaction.
* @param string optional savepoint name
@@ -173,7 +166,6 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
@@ -190,7 +182,6 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Returns the connection resource.
* @return mixed
@@ -201,7 +192,6 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Returns the connection reflector.
* @return IDibiReflector
@@ -212,7 +202,6 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Result set driver factory.
* @param resource
@@ -226,11 +215,9 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/********************* SQL ****************d*g**/
/**
* Encodes data for use in a SQL statement.
* @param mixed value
@@ -241,30 +228,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:
return $value instanceof DateTime ? $value->format($this->fmtDate) : date($this->fmtDate, $value);
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::DATETIME:
return $value instanceof DateTime ? $value->format($this->fmtDateTime) : date($this->fmtDateTime, $value);
default:
throw new InvalidArgumentException('Unsupported type.');
default:
throw new InvalidArgumentException('Unsupported type.');
}
}
/**
* Encodes string for use in a LIKE statement.
* @param string
@@ -279,7 +266,6 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Decodes data from result set.
* @param string value
@@ -296,19 +282,17 @@ 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;
@@ -316,11 +300,9 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/********************* result set ****************d*g**/
/**
* Automatically frees the resources allocated for this result set.
* @return void
@@ -331,7 +313,6 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Returns the number of rows in a result set.
* @return int
@@ -342,7 +323,6 @@ 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
@@ -354,7 +334,6 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
@@ -366,7 +345,6 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Frees the resources allocated for this result set.
* @return void
@@ -378,7 +356,6 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Returns metadata for all columns in a result set.
* @return array
@@ -399,7 +376,6 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Returns the result set resource.
* @return mixed
@@ -411,11 +387,9 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/********************* IDibiReflector ****************d*g**/
/**
* Returns list of tables.
* @return array
@@ -436,7 +410,6 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Returns metadata for all columns in a table.
* @param string
@@ -448,7 +421,6 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Returns metadata for all indexes in a table.
* @param string
@@ -460,7 +432,6 @@ class DibiOracleDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Returns metadata for all foreign keys in a table.
* @param string

View File

@@ -2,11 +2,7 @@
/**
* 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.
*/
@@ -43,7 +39,6 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
private $driverName;
/**
* @throws DibiNotSupportedException
*/
@@ -55,13 +50,12 @@ 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'];
@@ -74,18 +68,16 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
$this->connection = new PDO($config['dsn'], $config['username'], $config['password'], $config['options']);
} catch (PDOException $e) {
if ($e->getMessage() === 'could not find driver') {
throw new DibiNotSupportedException("PHP extension for PDO is not loaded.");
}
throw new DibiDriverException($e->getMessage(), $e->getCode());
}
if (!$this->connection) {
throw new DibiDriverException('Connecting error.');
}
$this->driverName = $this->connection->getAttribute(PDO::ATTR_DRIVER_NAME);
}
/**
* Disconnects from a database.
* @return void
@@ -96,7 +88,6 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
}
/**
* Executes the SQL query.
* @param string SQL statement.
@@ -131,7 +122,6 @@ 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
@@ -142,7 +132,6 @@ 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
@@ -153,7 +142,6 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
}
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
@@ -169,7 +157,6 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
}
/**
* Commits statements in a transaction.
* @param string optional savepoint name
@@ -185,7 +172,6 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
}
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
@@ -201,7 +187,6 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
}
/**
* Returns the connection resource.
* @return PDO
@@ -212,7 +197,6 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
}
/**
* Returns the connection reflector.
* @return IDibiReflector
@@ -220,20 +204,19 @@ 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
@@ -247,11 +230,9 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
}
/********************* SQL ****************d*g**/
/**
* Encodes data for use in a SQL statement.
* @param mixed value
@@ -262,52 +243,62 @@ 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:
case dibi::BINARY:
if ($this->driverName === 'odbc') {
return "'" . str_replace("'", "''", $value) . "'";
} else {
return $this->connection->quote($value, $type === dibi::TEXT ? PDO::PARAM_STR : 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 'oci':
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 'mssql':
return '[' . str_replace(array('[', ']'), array('[[', ']]'), $value) . ']';
case 'odbc':
case 'oci': // TODO: not tested
case 'mssql':
return '[' . str_replace(array('[', ']'), array('[[', ']]'), $value) . ']';
case 'sqlsrv':
return '[' . str_replace(']', ']]', $value) . ']';
case 'sqlsrv':
return '[' . str_replace(']', ']]', $value) . ']';
default:
return $value;
}
case dibi::BOOL:
if ($this->driverName === 'pgsql') {
return $value ? 'TRUE' : 'FALSE';
} else {
return $value ? 1 : 0;
}
case dibi::DATE:
case dibi::DATETIME:
if (!$value instanceof DateTime && !$value instanceof DateTimeInterface) {
$value = new DibiDateTime($value);
}
if ($this->driverName === 'odbc') {
return $value->format($type === dibi::DATETIME ? "#m/d/Y H:i:s#" : "#m/d/Y#");
} else {
return $value->format($type === dibi::DATETIME ? "'Y-m-d H:i:s'" : "'Y-m-d'");
}
default:
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.');
throw new InvalidArgumentException('Unsupported type.');
}
}
/**
* Encodes string for use in a LIKE statement.
* @param string
@@ -316,9 +307,37 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
*/
public function escapeLike($value, $pos)
{
throw new DibiNotImplementedException;
}
switch ($this->driverName) {
case 'mysql':
$value = addcslashes(str_replace('\\', '\\\\', $value), "\x00\n\r\\'%_");
return ($pos <= 0 ? "'%" : "'") . $value . ($pos >= 0 ? "%'" : "'");
case 'oci':
$value = addcslashes(str_replace('\\', '\\\\', $value), "\x00\\%_");
$value = str_replace("'", "''", $value);
return ($pos <= 0 ? "'%" : "'") . $value . ($pos >= 0 ? "%'" : "'");
case 'pgsql':
$bs = substr($this->connection->quote('\\', PDO::PARAM_STR), 1, -1); // standard_conforming_strings = on/off
$value = substr($this->connection->quote($value, PDO::PARAM_STR), 1, -1);
$value = strtr($value, array('%' => $bs . '%', '_' => $bs . '_', '\\' => '\\\\'));
return ($pos <= 0 ? "'%" : "'") . $value . ($pos >= 0 ? "%'" : "'");
case 'sqlite':
case 'sqlite2':
$value = addcslashes(substr($this->connection->quote($value, PDO::PARAM_STR), 1, -1), '%_\\');
return ($pos <= 0 ? "'%" : "'") . $value . ($pos >= 0 ? "%'" : "'") . " ESCAPE '\\'";
case 'odbc':
case 'mssql':
case 'sqlsrv':
$value = strtr($value, array("'" => "''", '%' => '[%]', '_' => '[_]', '[' => '[[]'));
return ($pos <= 0 ? "'%" : "'") . $value . ($pos >= 0 ? "%'" : "'");
default:
throw new DibiNotImplementedException;
}
}
/**
@@ -337,62 +356,65 @@ 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 : '');
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':
case 'sqlsrv':
if ($offset < 1) {
$sql = 'SELECT TOP ' . (int) $limit . ' * FROM (' . $sql . ') t';
case 'mysql':
$sql .= ' LIMIT ' . ($limit < 0 ? '18446744073709551615' : (int) $limit)
. ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
break;
}
// intentionally break omitted
default:
throw new DibiNotSupportedException('PDO or driver does not support applying limit or offset.');
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 'dblib':
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.');
}
}
/********************* result set ****************d*g**/
/**
* Returns the number of rows in a result set.
* @return int
@@ -403,7 +425,6 @@ 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
@@ -415,7 +436,6 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
}
/**
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
@@ -427,7 +447,6 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
}
/**
* Frees the resources allocated for this result set.
* @return void
@@ -438,7 +457,6 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
}
/**
* Returns metadata for all columns in a result set.
* @return array
@@ -472,7 +490,6 @@ class DibiPdoDriver extends DibiObject implements IDibiDriver, IDibiResultDriver
}
/**
* Returns the result set resource.
* @return PDOStatement

View File

@@ -2,11 +2,7 @@
/**
* 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.
*/
@@ -39,10 +35,6 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
/** @var int|FALSE Affected rows */
private $affectedRows = FALSE;
/** @var bool Escape method */
private $escMethod = FALSE;
/**
* @throws DibiNotSupportedException
@@ -55,19 +47,20 @@ 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 {
if (!isset($config['charset'])) $config['charset'] = 'utf8';
$config += array(
'charset' => 'utf8',
);
if (isset($config['string'])) {
$string = $config['string'];
} else {
@@ -75,7 +68,9 @@ 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] . ' ';
}
}
}
@@ -105,12 +100,9 @@ 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
@@ -121,6 +113,15 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Pings database.
* @return boolean
*/
public function ping()
{
return pg_ping($this->connection);
}
/**
* Executes the SQL query.
@@ -145,7 +146,6 @@ 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
@@ -156,7 +156,6 @@ 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
@@ -170,14 +169,15 @@ 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
@@ -190,7 +190,6 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Commits statements in a transaction.
* @param string optional savepoint name
@@ -203,7 +202,6 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
@@ -216,7 +214,6 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Is in transaction?
* @return bool
@@ -227,7 +224,6 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Returns the connection resource.
* @return mixed
@@ -238,7 +234,6 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Returns the connection reflector.
* @return IDibiReflector
@@ -249,7 +244,6 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Result set driver factory.
* @param resource
@@ -263,11 +257,9 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/********************* SQL ****************d*g**/
/**
* Encodes data for use in a SQL statement.
* @param mixed value
@@ -278,46 +270,38 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
public function escape($value, $type)
{
switch ($type) {
case dibi::TEXT:
if ($this->escMethod) {
case dibi::TEXT:
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:
if ($this->escMethod) {
case dibi::BINARY:
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:
return $value instanceof DateTime ? $value->format("'Y-m-d'") : date("'Y-m-d'", $value);
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::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.');
default:
throw new InvalidArgumentException('Unsupported type.');
}
}
/**
* Encodes string for use in a LIKE statement.
* @param string
@@ -326,18 +310,13 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
*/
public function escapeLike($value, $pos)
{
if ($this->escMethod) {
$value = pg_escape_string($this->connection, $value);
} else {
$value = pg_escape_string($value);
}
$value = strtr($value, array( '%' => '\\\\%', '_' => '\\\\_'));
$bs = pg_escape_string($this->connection, '\\'); // standard_conforming_strings = on/off
$value = pg_escape_string($this->connection, $value);
$value = strtr($value, array('%' => $bs . '%', '_' => $bs . '_', '\\' => '\\\\'));
return ($pos <= 0 ? "'%" : "'") . $value . ($pos >= 0 ? "%'" : "'");
}
/**
* Decodes data from result set.
* @param string value
@@ -354,29 +333,25 @@ 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
@@ -387,7 +362,6 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Returns the number of rows in a result set.
* @return int
@@ -398,7 +372,6 @@ 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
@@ -410,7 +383,6 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
@@ -422,7 +394,6 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Frees the resources allocated for this result set.
* @return void
@@ -434,20 +405,18 @@ 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' => $hasTable ? pg_field_table($this->resultSet, $i) : NULL,
'table' => pg_field_table($this->resultSet, $i),
'nativetype'=> pg_field_type($this->resultSet, $i),
);
$row['fullname'] = $row['table'] ? $row['table'] . '.' . $row['name'] : $row['name'];
@@ -457,7 +426,6 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Returns the result set resource.
* @return mixed
@@ -469,11 +437,9 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/********************* IDibiReflector ****************d*g**/
/**
* Returns list of tables.
* @return array
@@ -485,7 +451,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
throw new DibiDriverException('Reflection requires PostgreSQL 7.4 and newer.');
}
$res = $this->query("
$query = "
SELECT
table_name AS name,
CASE table_type
@@ -495,14 +461,25 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
FROM
information_schema.tables
WHERE
table_schema = current_schema()
");
table_schema = ANY (current_schemas(false))";
if ($version >= 9.3) {
$query .= "
UNION ALL
SELECT
matviewname, 1
FROM
pg_matviews
WHERE
schemaname = ANY (current_schemas(false))";
}
$res = $this->query($query);
$tables = pg_fetch_all($res->resultSet);
return $tables ? $tables : array();
}
/**
* Returns metadata for all columns in a table.
* @param string
@@ -510,21 +487,48 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
*/
public function getColumns($table)
{
$_table = $this->escape($table, dibi::TEXT);
$_table = $this->escape($this->escape($table, dibi::IDENTIFIER), dibi::TEXT);
$res = $this->query("
SELECT indkey
FROM pg_class
LEFT JOIN pg_index on pg_class.oid = pg_index.indrelid AND pg_index.indisprimary
WHERE pg_class.relname = $_table
WHERE pg_class.oid = $_table::regclass
");
$primary = (int) pg_fetch_object($res->resultSet)->indkey;
$res = $this->query("
SELECT *
FROM information_schema.columns
WHERE table_name = $_table AND table_schema = current_schema()
ORDER BY ordinal_position
FROM information_schema.columns c
JOIN pg_class ON pg_class.relname = c.table_name
JOIN pg_namespace nsp ON nsp.oid = pg_class.relnamespace AND nsp.nspname = c.table_schema
WHERE pg_class.oid = $_table::regclass
ORDER BY c.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']);
@@ -532,8 +536,8 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
'name' => $row['column_name'],
'table' => $table,
'nativetype' => strtoupper($row['udt_name']),
'size' => $size ? $size : NULL,
'nullable' => $row['is_nullable'] === 'YES',
'size' => $size > 0 ? $size : NULL,
'nullable' => $row['is_nullable'] === 'YES' || $row['is_nullable'] === 't',
'default' => $row['column_default'],
'autoincrement' => (int) $row['ordinal_position'] === $primary && substr($row['column_default'], 0, 7) === 'nextval',
'vendor' => $row,
@@ -543,7 +547,6 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Returns metadata for all indexes in a table.
* @param string
@@ -551,11 +554,18 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
*/
public function getIndexes($table)
{
$_table = $this->escape($table, dibi::TEXT);
$_table = $this->escape($this->escape($table, dibi::IDENTIFIER), dibi::TEXT);
$res = $this->query("
SELECT ordinal_position, column_name
FROM information_schema.columns
WHERE table_name = $_table AND table_schema = current_schema()
SELECT
a.attnum AS ordinal_position,
a.attname AS column_name
FROM
pg_attribute a
JOIN pg_class cls ON a.attrelid = cls.oid
WHERE
a.attrelid = $_table::regclass
AND a.attnum > 0
AND NOT a.attisdropped
ORDER BY ordinal_position
");
@@ -569,7 +579,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
FROM pg_class
LEFT JOIN pg_index on pg_class.oid = pg_index.indrelid
INNER JOIN pg_class as pg_class2 on pg_class2.oid = pg_index.indexrelid
WHERE pg_class.relname = $_table
WHERE pg_class.oid = $_table::regclass
");
$indexes = array();
@@ -585,7 +595,6 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Returns metadata for all foreign keys in a table.
* @param string
@@ -593,7 +602,7 @@ class DibiPostgreDriver extends DibiObject implements IDibiDriver, IDibiResultDr
*/
public function getForeignKeys($table)
{
$_table = $this->escape($table, dibi::TEXT);
$_table = $this->escape($this->escape($table, dibi::IDENTIFIER), dibi::TEXT);
$res = $this->query("
SELECT

View File

@@ -2,11 +2,7 @@
/**
* 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.
*/
@@ -46,7 +42,6 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
private $dbcharset, $charset;
/**
* @throws DibiNotSupportedException
*/
@@ -58,13 +53,12 @@ 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';
@@ -93,7 +87,6 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Disconnects from a database.
* @return void
@@ -104,7 +97,6 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Executes the SQL query.
* @param string SQL statement.
@@ -127,7 +119,6 @@ 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
@@ -138,7 +129,6 @@ 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
@@ -149,7 +139,6 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
@@ -162,7 +151,6 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Commits statements in a transaction.
* @param string optional savepoint name
@@ -175,7 +163,6 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
@@ -188,7 +175,6 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Returns the connection resource.
* @return mixed
@@ -199,7 +185,6 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Returns the connection reflector.
* @return IDibiReflector
@@ -210,7 +195,6 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Result set driver factory.
* @param SQLite3Result
@@ -224,11 +208,9 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/********************* SQL ****************d*g**/
/**
* Encodes data for use in a SQL statement.
* @param mixed value
@@ -239,31 +221,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:
return $value instanceof DateTime ? $value->format($this->fmtDate) : date($this->fmtDate, $value);
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::DATETIME:
return $value instanceof DateTime ? $value->format($this->fmtDateTime) : date($this->fmtDateTime, $value);
default:
throw new InvalidArgumentException('Unsupported type.');
default:
throw new InvalidArgumentException('Unsupported type.');
}
}
/**
* Encodes string for use in a LIKE statement.
* @param string
@@ -277,7 +259,6 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Decodes data from result set.
* @param string value
@@ -294,26 +275,21 @@ 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 < 1) return;
$sql .= ' LIMIT ' . $limit . ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
if ($limit >= 0 || $offset > 0) {
$sql .= ' LIMIT ' . (int) $limit . ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
}
}
/********************* result set ****************d*g**/
/**
* Automatically frees the resources allocated for this result set.
* @return void
@@ -324,7 +300,6 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Returns the number of rows in a result set.
* @return int
@@ -336,7 +311,6 @@ 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
@@ -360,7 +334,6 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
@@ -373,7 +346,6 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Frees the resources allocated for this result set.
* @return void
@@ -385,7 +357,6 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Returns metadata for all columns in a result set.
* @return array
@@ -407,7 +378,6 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Returns the result set resource.
* @return mixed
@@ -419,11 +389,9 @@ 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
@@ -437,7 +405,6 @@ class DibiSqlite3Driver extends DibiObject implements IDibiDriver, IDibiResultDr
}
/**
* Registers an aggregating user defined function for use in SQL statements.
* @param string function name

View File

@@ -2,11 +2,7 @@
/**
* 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.
*/
@@ -48,7 +44,6 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
private $dbcharset, $charset;
/**
* @throws DibiNotSupportedException
*/
@@ -60,13 +55,12 @@ 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';
@@ -95,7 +89,6 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Disconnects from a database.
* @return void
@@ -106,7 +99,6 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Executes the SQL query.
* @param string SQL statement.
@@ -134,7 +126,6 @@ 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
@@ -145,7 +136,6 @@ 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
@@ -156,7 +146,6 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
@@ -169,7 +158,6 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Commits statements in a transaction.
* @param string optional savepoint name
@@ -182,7 +170,6 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
@@ -195,7 +182,6 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Returns the connection resource.
* @return mixed
@@ -206,7 +192,6 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Returns the connection reflector.
* @return IDibiReflector
@@ -217,7 +202,6 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Result set driver factory.
* @param resource
@@ -231,11 +215,9 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/********************* SQL ****************d*g**/
/**
* Encodes data for use in a SQL statement.
* @param mixed value
@@ -246,29 +228,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:
return $value instanceof DateTime ? $value->format($this->fmtDate) : date($this->fmtDate, $value);
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::DATETIME:
return $value instanceof DateTime ? $value->format($this->fmtDateTime) : date($this->fmtDateTime, $value);
default:
throw new InvalidArgumentException('Unsupported type.');
default:
throw new InvalidArgumentException('Unsupported type.');
}
}
/**
* Encodes string for use in a LIKE statement.
* @param string
@@ -281,7 +263,6 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Decodes data from result set.
* @param string value
@@ -298,26 +279,21 @@ 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 < 1) return;
$sql .= ' LIMIT ' . $limit . ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
if ($limit >= 0 || $offset > 0) {
$sql .= ' LIMIT ' . (int) $limit . ($offset > 0 ? ' OFFSET ' . (int) $offset : '');
}
}
/********************* result set ****************d*g**/
/**
* Returns the number of rows in a result set.
* @return int
@@ -331,7 +307,6 @@ 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
@@ -355,7 +330,6 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Moves cursor position without fetching row.
* @param int the 0-based cursor pos to seek to
@@ -371,7 +345,6 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Frees the resources allocated for this result set.
* @return void
@@ -382,7 +355,6 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Returns metadata for all columns in a result set.
* @return array
@@ -405,7 +377,6 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Returns the result set resource.
* @return mixed
@@ -416,11 +387,9 @@ 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
@@ -434,7 +403,6 @@ class DibiSqliteDriver extends DibiObject implements IDibiDriver, IDibiResultDri
}
/**
* Registers an aggregating user defined function for use in SQL statements.
* @param string function name

View File

@@ -2,11 +2,7 @@
/**
* 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.
*/
@@ -23,14 +19,12 @@ class DibiSqliteReflector extends DibiObject implements IDibiReflector
private $driver;
public function __construct(IDibiDriver $driver)
{
$this->driver = $driver;
}
/**
* Returns list of tables.
* @return array
@@ -51,7 +45,6 @@ class DibiSqliteReflector extends DibiObject implements IDibiReflector
}
/**
* Returns metadata for all columns in a table.
* @param string
@@ -69,7 +62,6 @@ class DibiSqliteReflector extends DibiObject implements IDibiReflector
$columns = array();
while ($row = $res->fetch(TRUE)) {
$column = $row['name'];
$pattern = "/(\"$column\"|\[$column\]|$column)\\s+[^,]+\\s+PRIMARY\\s+KEY\\s+AUTOINCREMENT/Ui";
$type = explode('(', $row['type']);
$columns[] = array(
'name' => $column,
@@ -79,7 +71,7 @@ class DibiSqliteReflector extends DibiObject implements IDibiReflector
'size' => isset($type[1]) ? (int) $type[1] : NULL,
'nullable' => $row['notnull'] == '0',
'default' => $row['dflt_value'],
'autoincrement' => (bool) preg_match($pattern, $meta['sql']),
'autoincrement' => $row['pk'] && $type[0] === 'INTEGER',
'vendor' => $row,
);
}
@@ -87,7 +79,6 @@ class DibiSqliteReflector extends DibiObject implements IDibiReflector
}
/**
* Returns metadata for all indexes in a table.
* @param string
@@ -139,7 +130,6 @@ class DibiSqliteReflector extends DibiObject implements IDibiReflector
}
/**
* Returns metadata for all foreign keys in a table.
* @param string

544
dibi/libs/Dibi.php Normal file
View File

@@ -0,0 +1,544 @@
<?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.3.0',
REVISION = 'released on 2015-01-23';
/** 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 = 'mysqli';
/**
* 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
* @return DibiConnection
* @throws DibiException
*/
public static function connect($config = array(), $name = 0)
{
if ($name) {
trigger_error(__METHOD__ . '(): named connections are deprecated.', E_USER_DEPRECATED);
}
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.
* @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;
}
trigger_error(__METHOD__ . '(): named connections are deprecated.', E_USER_DEPRECATED);
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;
}
/**
* @deprecated
*/
public static function activate($name)
{
trigger_error(__METHOD__ . '() is deprecated.', E_USER_DEPRECATED);
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|START\s+TRANSACTION|BEGIN|COMMIT|ROLLBACK(?:\s+TO\s+SAVEPOINT)?|(?:RELEASE\s+)?SAVEPOINT';
static $keywords2 = 'ALL|DISTINCT|DISTINCTROW|IGNORE|AS|USING|ON|AND|OR|IN|IS|NOT|NULL|LIKE|RLIKE|REGEXP|TRUE|FALSE';
// 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";
}
}
}

View File

@@ -2,15 +2,10 @@
/**
* 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.
*
@@ -45,7 +40,6 @@ class DibiConnection extends DibiObject
private $substitutes;
/**
* Connection options: (see driver-specific options too)
* - lazy (bool) => if TRUE, connection will be established only when required
@@ -62,9 +56,6 @@ 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);
@@ -91,7 +82,7 @@ class DibiConnection extends DibiObject
$class = preg_replace(array('#\W#', '#sql#'), array('_', 'Sql'), ucfirst(strtolower($config['driver'])));
$class = "Dibi{$class}Driver";
if (!class_exists($class, FALSE)) {
if (!class_exists($class)) {
include_once dirname(__FILE__) . "/../drivers/$class.php";
if (!class_exists($class, FALSE)) {
@@ -120,7 +111,7 @@ class DibiConnection extends DibiObject
$this->onEvent[] = array(new DibiFirePhpLogger($filter), 'logEvent');
}
if (class_exists('DibiNettePanel', FALSE)) {
if (!interface_exists('Tracy\IBarPanel') && interface_exists('Nette\Diagnostics\IBarPanel') && class_exists('DibiNettePanel')) {
$panel = new DibiNettePanel(isset($profilerCfg['explain']) ? $profilerCfg['explain'] : TRUE, $filter);
$panel->register($this);
}
@@ -139,7 +130,6 @@ class DibiConnection extends DibiObject
}
/**
* Automatically frees the resources allocated for this result set.
* @return void
@@ -151,7 +141,6 @@ class DibiConnection extends DibiObject
}
/**
* Connects to a database.
* @return void
@@ -171,7 +160,6 @@ class DibiConnection extends DibiObject
}
/**
* Disconnects from a database.
* @return void
@@ -183,7 +171,6 @@ class DibiConnection extends DibiObject
}
/**
* Returns TRUE when connection was established.
* @return bool
@@ -194,7 +181,6 @@ class DibiConnection extends DibiObject
}
/**
* Returns configuration variable. If no $key is passed, returns the entire array.
* @see self::__construct
@@ -216,7 +202,6 @@ class DibiConnection extends DibiObject
}
/**
* Apply configuration alias or default values.
* @param array connect configuration
@@ -224,10 +209,12 @@ 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];
@@ -236,7 +223,6 @@ class DibiConnection extends DibiObject
}
/**
* Returns the driver and connects to a database in lazy mode.
* @return IDibiDriver
@@ -248,7 +234,6 @@ class DibiConnection extends DibiObject
}
/**
* Generates (translates) and executes SQL query.
* @param array|mixed one or more arguments
@@ -262,7 +247,6 @@ class DibiConnection extends DibiObject
}
/**
* Generates SQL query.
* @param array|mixed one or more arguments
@@ -276,7 +260,6 @@ class DibiConnection extends DibiObject
}
/**
* Generates and prints SQL query.
* @param array|mixed one or more arguments
@@ -300,7 +283,6 @@ class DibiConnection extends DibiObject
}
/**
* Generates (translates) and returns SQL query as DibiDataSource.
* @param array|mixed one or more arguments
@@ -314,7 +296,6 @@ class DibiConnection extends DibiObject
}
/**
* Generates SQL query.
* @param array
@@ -327,7 +308,6 @@ class DibiConnection extends DibiObject
}
/**
* Executes the SQL query.
* @param string SQL statement.
@@ -359,7 +339,6 @@ class DibiConnection extends DibiObject
}
/**
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
* @return int number of rows
@@ -369,12 +348,13 @@ 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
@@ -386,7 +366,6 @@ class DibiConnection extends DibiObject
}
/**
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
* @param string optional sequence name
@@ -397,12 +376,13 @@ 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
@@ -415,7 +395,6 @@ class DibiConnection extends DibiObject
}
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
@@ -436,7 +415,6 @@ class DibiConnection extends DibiObject
}
/**
* Commits statements in a transaction.
* @param string optional savepoint name
@@ -457,7 +435,6 @@ class DibiConnection extends DibiObject
}
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
@@ -478,7 +455,6 @@ class DibiConnection extends DibiObject
}
/**
* Result set factory.
* @param IDibiResultDriver
@@ -492,11 +468,9 @@ class DibiConnection extends DibiObject
}
/********************* fluent SQL builders ****************d*g**/
/**
* @return DibiFluent
*/
@@ -506,7 +480,6 @@ class DibiConnection extends DibiObject
}
/**
* @param string column name
* @return DibiFluent
@@ -518,7 +491,6 @@ class DibiConnection extends DibiObject
}
/**
* @param string table
* @param array
@@ -533,7 +505,6 @@ class DibiConnection extends DibiObject
}
/**
* @param string table
* @param array
@@ -551,7 +522,6 @@ class DibiConnection extends DibiObject
}
/**
* @param string table
* @return DibiFluent
@@ -562,11 +532,9 @@ class DibiConnection extends DibiObject
}
/********************* substitutions ****************d*g**/
/**
* Returns substitution hashmap.
* @return DibiHashMap
@@ -577,7 +545,6 @@ class DibiConnection extends DibiObject
}
/**
* Provides substitution.
* @return string
@@ -588,7 +555,6 @@ class DibiConnection extends DibiObject
}
/**
* Substitution callback.
*/
@@ -598,11 +564,9 @@ class DibiConnection extends DibiObject
}
/********************* shortcuts ****************d*g**/
/**
* Executes SQL query and fetch result - shortcut for query() & fetch().
* @param array|mixed one or more arguments
@@ -616,11 +580,10 @@ class DibiConnection extends DibiObject
}
/**
* Executes SQL query and fetch results - shortcut for query() & fetchAll().
* @param array|mixed one or more arguments
* @return array of DibiRow
* @return DibiRow[]
* @throws DibiException
*/
public function fetchAll($args)
@@ -630,7 +593,6 @@ class DibiConnection extends DibiObject
}
/**
* Executes SQL query and fetch first column - shortcut for query() & fetchSingle().
* @param array|mixed one or more arguments
@@ -644,7 +606,6 @@ class DibiConnection extends DibiObject
}
/**
* Executes SQL query and fetch pairs - shortcut for query() & fetchPairs().
* @param array|mixed one or more arguments
@@ -658,11 +619,9 @@ class DibiConnection extends DibiObject
}
/********************* misc ****************d*g**/
/**
* Import SQL dump from file - extreme fast!
* @param string filename
@@ -679,14 +638,21 @@ class DibiConnection extends DibiObject
}
$count = 0;
$delimiter = ';';
$sql = '';
while (!feof($handle)) {
$s = fgets($handle);
$sql .= $s;
if (substr(rtrim($s), -1) === ';') {
$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));
$this->driver->query($sql);
$sql = '';
$count++;
} else {
$sql .= $s . "\n";
}
}
if (trim($sql) !== '') {
@@ -698,7 +664,6 @@ class DibiConnection extends DibiObject
}
/**
* Gets a information about the current database.
* @return DibiDatabaseInfo
@@ -710,7 +675,6 @@ class DibiConnection extends DibiObject
}
/**
* Prevents unserialization.
*/
@@ -720,7 +684,6 @@ class DibiConnection extends DibiObject
}
/**
* Prevents serialization.
*/

View File

@@ -2,15 +2,10 @@
/**
* 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.
*
@@ -55,7 +50,6 @@ class DibiDataSource extends DibiObject implements IDataSource
private $limit;
/**
* @param string SQL command or table or view name, as data source
* @param DibiConnection connection
@@ -71,12 +65,11 @@ 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 DibiDataSource provides a fluent interface
* @return self
*/
public function select($col, $as = NULL)
{
@@ -90,11 +83,10 @@ class DibiDataSource extends DibiObject implements IDataSource
}
/**
* Adds conditions to query.
* @param mixed conditions
* @return DibiDataSource provides a fluent interface
* @return self
*/
public function where($cond)
{
@@ -109,12 +101,11 @@ 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 DibiDataSource provides a fluent interface
* @return self
*/
public function orderBy($row, $sorting = 'ASC')
{
@@ -128,12 +119,11 @@ class DibiDataSource extends DibiObject implements IDataSource
}
/**
* Limits number of rows.
* @param int limit
* @param int offset
* @return DibiDataSource provides a fluent interface
* @return self
*/
public function applyLimit($limit, $offset = NULL)
{
@@ -144,7 +134,6 @@ class DibiDataSource extends DibiObject implements IDataSource
}
/**
* Returns the dibi connection.
* @return DibiConnection
@@ -155,11 +144,9 @@ class DibiDataSource extends DibiObject implements IDataSource
}
/********************* executing ****************d*g**/
/**
* Returns (and queries) DibiResult.
* @return DibiResult
@@ -173,7 +160,6 @@ class DibiDataSource extends DibiObject implements IDataSource
}
/**
* @return DibiResultIterator
*/
@@ -183,7 +169,6 @@ 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
@@ -194,7 +179,6 @@ class DibiDataSource extends DibiObject implements IDataSource
}
/**
* Like fetch(), but returns only first field.
* @return mixed value on success, FALSE if no next record
@@ -205,7 +189,6 @@ class DibiDataSource extends DibiObject implements IDataSource
}
/**
* Fetches all records from table.
* @return array
@@ -216,7 +199,6 @@ class DibiDataSource extends DibiObject implements IDataSource
}
/**
* Fetches all records from table and returns associative tree.
* @param string associative descriptor
@@ -228,7 +210,6 @@ class DibiDataSource extends DibiObject implements IDataSource
}
/**
* Fetches all records from table like $key => $value pairs.
* @param string associative key
@@ -241,7 +222,6 @@ class DibiDataSource extends DibiObject implements IDataSource
}
/**
* Discards the internal cache.
* @return void
@@ -252,11 +232,9 @@ class DibiDataSource extends DibiObject implements IDataSource
}
/********************* exporting ****************d*g**/
/**
* Returns this data source wrapped in DibiFluent object.
* @return DibiFluent
@@ -267,7 +245,6 @@ class DibiDataSource extends DibiObject implements IDataSource
}
/**
* Returns this data source wrapped in DibiDataSource object.
* @return DibiDataSource
@@ -278,7 +255,6 @@ class DibiDataSource extends DibiObject implements IDataSource
}
/**
* Returns SQL query.
* @return string
@@ -299,11 +275,9 @@ FROM %SQL', $this->sql, '
}
/********************* counting ****************d*g**/
/**
* Returns the number of rows in a given data source.
* @return int
@@ -321,7 +295,6 @@ FROM %SQL', $this->sql, '
}
/**
* Returns the number of rows in a given data source.
* @return int

View File

@@ -2,15 +2,10 @@
/**
* 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.
*
@@ -33,7 +28,6 @@ class DibiDatabaseInfo extends DibiObject
private $tables;
public function __construct(IDibiReflector $reflector, $name)
{
$this->reflector = $reflector;
@@ -41,7 +35,6 @@ class DibiDatabaseInfo extends DibiObject
}
/**
* @return string
*/
@@ -51,9 +44,8 @@ class DibiDatabaseInfo extends DibiObject
}
/**
* @return array of DibiTableInfo
* @return DibiTableInfo[]
*/
public function getTables()
{
@@ -62,9 +54,8 @@ class DibiDatabaseInfo extends DibiObject
}
/**
* @return array of string
* @return string[]
*/
public function getTableNames()
{
@@ -77,7 +68,6 @@ class DibiDatabaseInfo extends DibiObject
}
/**
* @param string
* @return DibiTableInfo
@@ -95,7 +85,6 @@ class DibiDatabaseInfo extends DibiObject
}
/**
* @param string
* @return bool
@@ -107,7 +96,6 @@ class DibiDatabaseInfo extends DibiObject
}
/**
* @return void
*/
@@ -124,8 +112,6 @@ class DibiDatabaseInfo extends DibiObject
}
/**
* Reflection metadata class for a database table.
*
@@ -164,7 +150,6 @@ class DibiTableInfo extends DibiObject
private $primaryKey;
public function __construct(IDibiReflector $reflector, array $info)
{
$this->reflector = $reflector;
@@ -173,7 +158,6 @@ class DibiTableInfo extends DibiObject
}
/**
* @return string
*/
@@ -183,7 +167,6 @@ class DibiTableInfo extends DibiObject
}
/**
* @return bool
*/
@@ -193,9 +176,8 @@ class DibiTableInfo extends DibiObject
}
/**
* @return array of DibiColumnInfo
* @return DibiColumnInfo[]
*/
public function getColumns()
{
@@ -204,9 +186,8 @@ class DibiTableInfo extends DibiObject
}
/**
* @return array of string
* @return string[]
*/
public function getColumnNames()
{
@@ -219,7 +200,6 @@ class DibiTableInfo extends DibiObject
}
/**
* @param string
* @return DibiColumnInfo
@@ -237,7 +217,6 @@ class DibiTableInfo extends DibiObject
}
/**
* @param string
* @return bool
@@ -249,9 +228,8 @@ class DibiTableInfo extends DibiObject
}
/**
* @return array of DibiForeignKeyInfo
* @return DibiForeignKeyInfo[]
*/
public function getForeignKeys()
{
@@ -260,9 +238,8 @@ class DibiTableInfo extends DibiObject
}
/**
* @return array of DibiIndexInfo
* @return DibiIndexInfo[]
*/
public function getIndexes()
{
@@ -271,7 +248,6 @@ class DibiTableInfo extends DibiObject
}
/**
* @return DibiIndexInfo
*/
@@ -282,7 +258,6 @@ class DibiTableInfo extends DibiObject
}
/**
* @return void
*/
@@ -297,7 +272,6 @@ class DibiTableInfo extends DibiObject
}
/**
* @return void
*/
@@ -319,7 +293,6 @@ class DibiTableInfo extends DibiObject
}
/**
* @return void
*/
@@ -331,8 +304,6 @@ class DibiTableInfo extends DibiObject
}
/**
* Reflection metadata class for a result set.
*
@@ -354,16 +325,14 @@ class DibiResultInfo extends DibiObject
private $names;
public function __construct(IDibiResultDriver $driver)
{
$this->driver = $driver;
}
/**
* @return array of DibiColumnInfo
* @return DibiColumnInfo[]
*/
public function getColumns()
{
@@ -372,10 +341,9 @@ class DibiResultInfo extends DibiObject
}
/**
* @param bool
* @return array of string
* @return string[]
*/
public function getColumnNames($fullNames = FALSE)
{
@@ -388,7 +356,6 @@ class DibiResultInfo extends DibiObject
}
/**
* @param string
* @return DibiColumnInfo
@@ -406,7 +373,6 @@ class DibiResultInfo extends DibiObject
}
/**
* @param string
* @return bool
@@ -418,7 +384,6 @@ class DibiResultInfo extends DibiObject
}
/**
* @return void
*/
@@ -436,8 +401,6 @@ class DibiResultInfo extends DibiObject
}
/**
* Reflection metadata class for a table or result set column.
*
@@ -467,7 +430,6 @@ class DibiColumnInfo extends DibiObject
private $info;
public function __construct(IDibiReflector $reflector = NULL, array $info)
{
$this->reflector = $reflector;
@@ -475,7 +437,6 @@ class DibiColumnInfo extends DibiObject
}
/**
* @return string
*/
@@ -485,7 +446,6 @@ class DibiColumnInfo extends DibiObject
}
/**
* @return string
*/
@@ -495,7 +455,6 @@ class DibiColumnInfo extends DibiObject
}
/**
* @return bool
*/
@@ -505,7 +464,6 @@ class DibiColumnInfo extends DibiObject
}
/**
* @return DibiTableInfo
*/
@@ -518,17 +476,15 @@ class DibiColumnInfo extends DibiObject
}
/**
* @return string
*/
public function getTableName()
{
return isset($this->info['table']) ? $this->info['table'] : NULL;
return isset($this->info['table']) && $this->info['table'] != NULL ? $this->info['table'] : NULL; // intentionally ==
}
/**
* @return string
*/
@@ -538,7 +494,6 @@ class DibiColumnInfo extends DibiObject
}
/**
* @return mixed
*/
@@ -548,7 +503,6 @@ class DibiColumnInfo extends DibiObject
}
/**
* @return int
*/
@@ -558,7 +512,6 @@ class DibiColumnInfo extends DibiObject
}
/**
* @return bool
*/
@@ -568,7 +521,6 @@ class DibiColumnInfo extends DibiObject
}
/**
* @return bool
*/
@@ -578,7 +530,6 @@ class DibiColumnInfo extends DibiObject
}
/**
* @return bool
*/
@@ -588,7 +539,6 @@ class DibiColumnInfo extends DibiObject
}
/**
* @return mixed
*/
@@ -598,7 +548,6 @@ class DibiColumnInfo extends DibiObject
}
/**
* @param string
* @return mixed
@@ -609,7 +558,6 @@ class DibiColumnInfo extends DibiObject
}
/**
* Heuristic type detection.
* @param string
@@ -639,7 +587,6 @@ class DibiColumnInfo extends DibiObject
}
/**
* @internal
*/
@@ -654,8 +601,6 @@ class DibiColumnInfo extends DibiObject
}
/**
* Reflection metadata class for a foreign key.
*
@@ -675,7 +620,6 @@ class DibiForeignKeyInfo extends DibiObject
private $references;
public function __construct($name, array $references)
{
$this->name = $name;
@@ -683,7 +627,6 @@ class DibiForeignKeyInfo extends DibiObject
}
/**
* @return string
*/
@@ -693,7 +636,6 @@ class DibiForeignKeyInfo extends DibiObject
}
/**
* @return array
*/
@@ -705,8 +647,6 @@ class DibiForeignKeyInfo extends DibiObject
}
/**
* Reflection metadata class for a index or primary key.
*
@@ -730,7 +670,6 @@ class DibiIndexInfo extends DibiObject
}
/**
* @return string
*/
@@ -740,7 +679,6 @@ class DibiIndexInfo extends DibiObject
}
/**
* @return array
*/
@@ -750,7 +688,6 @@ class DibiIndexInfo extends DibiObject
}
/**
* @return bool
*/
@@ -760,7 +697,6 @@ class DibiIndexInfo extends DibiObject
}
/**
* @return bool
*/

View File

@@ -2,15 +2,10 @@
/**
* 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.
*
@@ -23,9 +18,9 @@ class DibiDateTime extends DateTime
public function __construct($time = 'now', DateTimeZone $timezone = NULL)
{
if (is_numeric($time)) {
$time = date('Y-m-d H:i:s', $time);
}
if ($timezone === NULL) {
parent::__construct('@' . $time);
$this->setTimeZone($timezone ? $timezone : new DateTimeZone(date_default_timezone_get()));
} elseif ($timezone === NULL) {
parent::__construct($time);
} else {
parent::__construct($time, $timezone);
@@ -33,7 +28,6 @@ class DibiDateTime extends DateTime
}
public function modifyClone($modify = '')
{
$dolly = clone($this);
@@ -41,7 +35,6 @@ class DibiDateTime extends DateTime
}
public function modify($modify)
{
parent::modify($modify);
@@ -49,40 +42,48 @@ class DibiDateTime extends DateTime
}
public function __sleep()
public function setTimestamp($timestamp)
{
$this->fix = array($this->format('Y-m-d H:i:s'), $this->getTimezone()->getName());
return array('fix');
$zone = PHP_VERSION_ID === 50206 ? new DateTimeZone($this->getTimezone()->getName()) : $this->getTimezone();
$this->__construct('@' . $timestamp);
$this->setTimeZone($zone);
return $this;
}
public function __wakeup()
{
$this->__construct($this->fix[0], new DateTimeZone($this->fix[1]));
unset($this->fix);
}
public function getTimestamp()
{
return (int) $this->format('U');
$ts = $this->format('U');
return is_float($tmp = $ts * 1) ? $ts : $tmp;
}
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);
}
}

View File

@@ -2,15 +2,10 @@
/**
* 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.
*
@@ -54,7 +49,6 @@ class DibiEvent
public $source;
public function __construct(DibiConnection $connection, $type, $sql = NULL)
{
$this->connection = $connection;
@@ -85,7 +79,6 @@ class DibiEvent
}
public function done($result = NULL)
{
$this->result = $result;

View File

@@ -2,15 +2,10 @@
/**
* 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.
*
@@ -36,7 +31,6 @@ class DibiException extends Exception
}
/**
* @return string The SQL passed to the constructor
*/
@@ -46,7 +40,6 @@ class DibiException extends Exception
}
/**
* @return string string represenation of exception with SQL command
*/
@@ -58,8 +51,6 @@ class DibiException extends Exception
}
/**
* database server exception.
*
@@ -72,12 +63,10 @@ class DibiDriverException extends DibiException
/********************* error catching ****************d*g**/
/** @var string */
private static $errorMsg;
/**
* Starts catching potential errors/warnings.
* @return void
@@ -89,7 +78,6 @@ class DibiDriverException extends DibiException
}
/**
* Returns catched error/warning message.
* @param string catched message
@@ -104,7 +92,6 @@ class DibiDriverException extends DibiException
}
/**
* Internal error handler. Do not call directly.
* @internal
@@ -124,8 +111,6 @@ class DibiDriverException extends DibiException
}
/**
* PCRE exception.
*
@@ -149,7 +134,6 @@ class DibiPcreException extends Exception {
}
/**
* @package dibi
*/
@@ -157,7 +141,6 @@ class DibiNotImplementedException extends DibiException
{}
/**
* @package dibi
*/

View File

@@ -2,15 +2,10 @@
/**
* 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.
*
@@ -26,7 +21,6 @@ class DibiFileLogger extends DibiObject
public $filter;
public function __construct($file, $filter = NULL)
{
$this->file = $file;
@@ -34,7 +28,6 @@ class DibiFileLogger extends DibiObject
}
/**
* After event notification.
* @return void
@@ -46,7 +39,9 @@ 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) {
@@ -65,7 +60,7 @@ class DibiFileLogger extends DibiObject
fwrite($handle,
"OK: " . $event->sql
. ($event->count ? ";\n-- rows: " . $event->count : '')
. "\n-- takes: " . sprintf('%0.3f', $event->time * 1000) . ' ms'
. "\n-- takes: " . sprintf('%0.3f ms', $event->time * 1000)
. "\n-- source: " . implode(':', $event->source)
. "\n-- driver: " . $event->connection->getConfig('driver') . '/' . $event->connection->getConfig('name')
. "\n-- " . date('Y-m-d H:i:s')

View File

@@ -2,15 +2,10 @@
/**
* 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.
*
@@ -25,6 +20,9 @@ class DibiFirePhpLogger extends DibiObject
/** maximum SQL length */
static public $maxLength = 1000;
/** size of json stream chunk */
static public $streamChunkSize = 4990;
/** @var int */
public $filter;
@@ -38,7 +36,6 @@ class DibiFirePhpLogger extends DibiObject
private static $fireTable = array(array('Time', 'SQL Statement', 'Rows', 'Connection'));
/**
* @return bool
*/
@@ -48,14 +45,12 @@ class DibiFirePhpLogger extends DibiObject
}
public function __construct($filter = NULL)
{
$this->filter = $filter ? (int) $filter : DibiEvent::QUERY;
}
/**
* After event notification.
* @return void
@@ -66,6 +61,11 @@ class DibiFirePhpLogger extends DibiObject
return;
}
if (!$this->numOfQueries) {
header('X-Wf-Protocol-dibi: http://meta.wildfirehq.org/Protocol/JsonStream/0.2');
header('X-Wf-dibi-Plugin-1: http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.2.0');
header('X-Wf-dibi-Structure-1: http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1');
}
$this->totalTime += $event->time;
$this->numOfQueries++;
self::$fireTable[] = array(
@@ -75,10 +75,6 @@ class DibiFirePhpLogger extends DibiObject
$event->connection->getConfig('driver') . '/' . $event->connection->getConfig('name')
);
header('X-Wf-Protocol-dibi: http://meta.wildfirehq.org/Protocol/JsonStream/0.2');
header('X-Wf-dibi-Plugin-1: http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.2.0');
header('X-Wf-dibi-Structure-1: http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1');
$payload = json_encode(array(
array(
'Type' => 'TABLE',
@@ -86,7 +82,7 @@ class DibiFirePhpLogger extends DibiObject
),
self::$fireTable,
));
foreach (str_split($payload, 4990) as $num => $s) {
foreach (str_split($payload, self::$streamChunkSize) as $num => $s) {
$num++;
header("X-Wf-dibi-1-1-d$num: |$s|\\"); // protocol-, structure-, plugin-, message-index
}

View File

@@ -2,15 +2,10 @@
/**
* 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!
*
@@ -29,6 +24,8 @@
* @method DibiFluent orderBy($field)
* @method DibiFluent limit(int $limit)
* @method DibiFluent offset(int $offset)
* @method DibiFluent leftJoin($table)
* @method DibiFluent on($cond)
*/
class DibiFluent extends DibiObject implements IDataSource
{
@@ -101,7 +98,6 @@ class DibiFluent extends DibiObject implements IDataSource
private static $normalizer;
/**
* @param DibiConnection
*/
@@ -115,12 +111,11 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* Appends new argument to the clause.
* @param string clause name
* @param array arguments
* @return DibiFluent provides a fluent interface
* @return self
*/
public function __call($clause, $args)
{
@@ -205,21 +200,15 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* Switch to a clause.
* @param string clause name
* @return DibiFluent provides a fluent interface
* @return self
*/
public function clause($clause, $remove = FALSE)
public function clause($clause)
{
$this->cursor = & $this->clauses[self::$normalizer->$clause];
if ($remove) { // deprecated, use removeClause
trigger_error(__METHOD__ . '(..., TRUE) is deprecated; use removeClause() instead.', E_USER_NOTICE);
$this->cursor = NULL;
} elseif ($this->cursor === NULL) {
if ($this->cursor === NULL) {
$this->cursor = array();
}
@@ -227,11 +216,10 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* Removes a clause.
* @param string clause name
* @return DibiFluent provides a fluent interface
* @return self
*/
public function removeClause($clause)
{
@@ -240,12 +228,11 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* Change a SQL flag.
* @param string flag name
* @param bool value
* @return DibiFluent provides a fluent interface
* @return self
*/
public function setFlag($flag, $value = TRUE)
{
@@ -259,7 +246,6 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* Is a flag set?
* @param string flag name
@@ -271,7 +257,6 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* Returns SQL command.
* @return string
@@ -282,7 +267,6 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* Returns the dibi connection.
* @return DibiConnection
@@ -293,12 +277,11 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* Adds DibiResult setup.
* @param string method
* @param mixed args
* @return DibiFluent provides a fluent interface
* @return self
*/
public function setupResult($method)
{
@@ -307,11 +290,9 @@ class DibiFluent extends DibiObject implements IDataSource
}
/********************* executing ****************d*g**/
/**
* Generates and executes SQL query.
* @param mixed what to return?
@@ -321,11 +302,17 @@ class DibiFluent extends DibiObject implements IDataSource
public function execute($return = NULL)
{
$res = $this->query($this->_export());
return $return === dibi::IDENTIFIER ? $this->connection->getInsertId() : $res;
switch ($return) {
case dibi::IDENTIFIER:
return $this->connection->getInsertId();
case dibi::AFFECTED_ROWS:
return $this->connection->getAffectedRows();
default:
return $res;
}
}
/**
* Generates, executes SQL query and fetches the single row.
* @return DibiRow|FALSE array on success, FALSE if no next record
@@ -340,7 +327,6 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* Like fetch(), but returns only first field.
* @return mixed value on success, FALSE if no next record
@@ -355,7 +341,6 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* Fetches all records from table.
* @param int offset
@@ -368,7 +353,6 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* Fetches all records from table and returns associative tree.
* @param string associative descriptor
@@ -380,7 +364,6 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* Fetches all records from table like $key => $value pairs.
* @param string associative key
@@ -393,7 +376,6 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* Required by the IteratorAggregate interface.
* @param int offset
@@ -406,7 +388,6 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* Generates and prints SQL query or it's part.
* @param string clause name
@@ -418,7 +399,6 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* @return int
*/
@@ -430,7 +410,6 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* @return DibiResult
*/
@@ -444,11 +423,9 @@ class DibiFluent extends DibiObject implements IDataSource
}
/********************* exporting ****************d*g**/
/**
* @return DibiDataSource
*/
@@ -458,7 +435,6 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* Returns SQL query.
* @return string
@@ -473,7 +449,6 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* Generates parameters for DibiTranslator.
* @param string clause name
@@ -499,7 +474,9 @@ 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;
}
}
}
@@ -507,7 +484,6 @@ class DibiFluent extends DibiObject implements IDataSource
}
/**
* Format camelCase clause name to UPPER CASE.
* @param string
@@ -524,7 +500,6 @@ class DibiFluent extends DibiObject implements IDataSource
}
public function __clone()
{
// remove references

View File

@@ -2,15 +2,10 @@
/**
* 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.
*
@@ -29,7 +24,6 @@ abstract class DibiHashMapBase
}
public function setCallback($callback)
{
if (!is_callable($callback)) {
@@ -40,7 +34,6 @@ abstract class DibiHashMapBase
}
public function getCallback()
{
return $this->callback;
@@ -49,7 +42,6 @@ abstract class DibiHashMapBase
}
/**
* Lazy cached storage.
*
@@ -68,7 +60,6 @@ final class DibiHashMap extends DibiHashMapBase
}
public function __get($nm)
{
if ($nm == '') {

View File

@@ -2,19 +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.
*/
/**
* SQL literal value.
*
* @author David Grudl
* @package dibi
*/
class DibiLiteral extends DibiObject
{
@@ -28,7 +24,6 @@ class DibiLiteral extends DibiObject
}
/**
* @return string
*/

View File

@@ -2,15 +2,10 @@
/**
* 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.
*
@@ -58,7 +53,6 @@ abstract class DibiObject
private static $extMethods;
/**
* Returns the name of the class of this object.
* @return string
@@ -69,7 +63,6 @@ abstract class DibiObject
}
/**
* Access to reflection.
* @return \ReflectionObject
@@ -80,7 +73,6 @@ abstract class DibiObject
}
/**
* Call to undefined method.
* @param string method name
@@ -125,7 +117,6 @@ abstract class DibiObject
}
/**
* Call to undefined static method.
* @param string method name (in lower case!)
@@ -140,7 +131,6 @@ abstract class DibiObject
}
/**
* Adding method to class.
* @param string method name
@@ -158,7 +148,9 @@ abstract class DibiObject
self::$extMethods[$pair[1]][''] = NULL;
}
}
if ($name === NULL) return NULL;
if ($name === NULL) {
return NULL;
}
}
$name = strtolower($name);
@@ -202,14 +194,13 @@ 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);
@@ -222,8 +213,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;
}
@@ -239,7 +230,6 @@ abstract class DibiObject
}
/**
* Sets value of a property. Do not call directly.
* @param string property name
@@ -274,7 +264,6 @@ abstract class DibiObject
}
/**
* Is property defined?
* @param string property name
@@ -287,7 +276,6 @@ abstract class DibiObject
}
/**
* Access to undeclared property.
* @param string property name
@@ -301,7 +289,6 @@ abstract class DibiObject
}
/**
* Has property an accessor?
* @param string class name

View File

@@ -2,15 +2,10 @@
/**
* 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.
*
@@ -61,7 +56,6 @@ class DibiResult extends DibiObject implements IDataSource
private $formats = array();
/**
* @param IDibiResultDriver
*/
@@ -72,7 +66,6 @@ class DibiResult extends DibiObject implements IDataSource
}
/**
* @deprecated
*/
@@ -82,7 +75,6 @@ class DibiResult extends DibiObject implements IDataSource
}
/**
* Frees the resources allocated for this result set.
* @return void
@@ -96,7 +88,6 @@ class DibiResult extends DibiObject implements IDataSource
}
/**
* Safe access to property $driver.
* @return IDibiResultDriver
@@ -112,11 +103,9 @@ 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
@@ -129,7 +118,6 @@ class DibiResult extends DibiObject implements IDataSource
}
/**
* Required by the Countable interface.
* @return int
@@ -140,7 +128,6 @@ class DibiResult extends DibiObject implements IDataSource
}
/**
* Returns the number of rows in a result set.
* @return int
@@ -151,41 +138,23 @@ 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 DibiResult provides a fluent interface
* @return self
*/
public function setRowClass($class)
{
@@ -194,7 +163,6 @@ class DibiResult extends DibiObject implements IDataSource
}
/**
* Returns fetched object class name.
* @return string
@@ -205,11 +173,10 @@ class DibiResult extends DibiObject implements IDataSource
}
/**
* Set a factory to create fetched object instances. These should extend the DibiRow class.
* @param callback
* @return DibiResult provides a fluent interface
* @return self
*/
public function setRowFactory($callback)
{
@@ -218,7 +185,6 @@ class DibiResult extends DibiObject implements IDataSource
}
/**
* Fetches the row at current position, process optional type conversion.
* and moves the internal cursor to the next position
@@ -241,7 +207,6 @@ class DibiResult extends DibiObject implements IDataSource
}
/**
* Like fetch(), but returns only first field.
* @return mixed value on success, FALSE if no next record
@@ -258,23 +223,26 @@ class DibiResult extends DibiObject implements IDataSource
}
/**
* Fetches all records from table.
* @param int offset
* @param int limit
* @return array of DibiRow
* @return 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());
@@ -283,7 +251,6 @@ class DibiResult extends DibiObject implements IDataSource
}
/**
* Fetches all records from table and returns associative tree.
* Examples:
@@ -303,7 +270,9 @@ 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);
@@ -362,7 +331,6 @@ class DibiResult extends DibiObject implements IDataSource
}
/**
* @deprecated
*/
@@ -370,7 +338,9 @@ 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);
@@ -435,7 +405,6 @@ class DibiResult extends DibiObject implements IDataSource
}
/**
* Fetches all records from table like $key => $value pairs.
* @param string associative key
@@ -447,7 +416,9 @@ 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();
@@ -486,18 +457,16 @@ class DibiResult extends DibiObject implements IDataSource
}
do {
$data[ $row[$key] ] = $row[$value];
$data[ (string) $row[$key] ] = $row[$value];
} while ($row = $this->fetch());
return $data;
}
/********************* column types ****************d*g**/
/**
* Autodetect column types.
* @return void
@@ -513,7 +482,6 @@ class DibiResult extends DibiObject implements IDataSource
}
/**
* Converts values to specified type and format.
* @param array
@@ -532,26 +500,15 @@ class DibiResult extends DibiObject implements IDataSource
$row[$key] = is_float($tmp = $value * 1) ? $value : $tmp;
} elseif ($type === dibi::FLOAT) {
$row[$key] = (string) ($tmp = (float) $value) === rtrim(rtrim($value, '0'), '.') ? $tmp : $value;
$row[$key] = str_replace(',', '.', ltrim((string) ($tmp = (float) $value), '0')) === ltrim(rtrim(rtrim($value, '0'), '.'), '0') ? $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) { // '', 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 {
if ((int) $value !== 0 || substr((string) $value, 0, 3) === '00:') { // '', NULL, FALSE, '0000-00-00', ...
$value = new DibiDateTime($value);
$row[$key] = $value->format($this->formats[$type]);
$row[$key] = empty($this->formats[$type]) ? $value : $value->format($this->formats[$type]);
}
} elseif ($type === dibi::BINARY) {
@@ -561,12 +518,11 @@ class DibiResult extends DibiObject implements IDataSource
}
/**
* Define column type.
* @param string column
* @param string type (use constant Dibi::*)
* @return DibiResult provides a fluent interface
* @return self
*/
final public function setType($col, $type)
{
@@ -575,7 +531,6 @@ class DibiResult extends DibiObject implements IDataSource
}
/**
* Returns column type.
* @return string
@@ -586,12 +541,11 @@ class DibiResult extends DibiObject implements IDataSource
}
/**
* Sets data format.
* @param string type (use constant Dibi::*)
* @param string format
* @return DibiResult provides a fluent interface
* @return self
*/
final public function setFormat($type, $format)
{
@@ -600,7 +554,6 @@ class DibiResult extends DibiObject implements IDataSource
}
/**
* Returns data format.
* @return string
@@ -611,11 +564,9 @@ class DibiResult extends DibiObject implements IDataSource
}
/********************* meta info ****************d*g**/
/**
* Returns a meta information about the current result set.
* @return DibiResultInfo
@@ -629,7 +580,6 @@ class DibiResult extends DibiObject implements IDataSource
}
/**
* @deprecated
*/
@@ -639,20 +589,9 @@ 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.
* @return void
@@ -668,7 +607,7 @@ class DibiResult extends DibiObject implements IDataSource
if ($i === 0) {
foreach ($row as $col => $foo) {
$len = mb_strlen($col);
if ($len > $maxLen) $maxLen = $len;
$maxLen = max($len, $maxLen);
}
}
@@ -687,7 +626,9 @@ class DibiResult extends DibiObject implements IDataSource
$i++;
}
if ($i === 0) echo "empty result set\n";
if ($i === 0) {
echo "empty result set\n";
}
echo "\n";
} else {

View File

@@ -2,15 +2,10 @@
/**
* 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.
*
@@ -47,7 +42,6 @@ class DibiResultIterator implements Iterator, Countable
}
/**
* Rewinds the iterator to the first element.
* @return void
@@ -60,7 +54,6 @@ class DibiResultIterator implements Iterator, Countable
}
/**
* Returns the key of the current element.
* @return mixed
@@ -71,7 +64,6 @@ class DibiResultIterator implements Iterator, Countable
}
/**
* Returns the current element.
* @return mixed
@@ -82,7 +74,6 @@ class DibiResultIterator implements Iterator, Countable
}
/**
* Moves forward to next element.
* @return void
@@ -94,7 +85,6 @@ class DibiResultIterator implements Iterator, Countable
}
/**
* Checks if there is a current element after calls to rewind() or next().
* @return bool
@@ -105,7 +95,6 @@ class DibiResultIterator implements Iterator, Countable
}
/**
* Required by the Countable interface.
* @return int

View File

@@ -2,15 +2,10 @@
/**
* 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.
*
@@ -22,18 +17,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
@@ -44,97 +39,48 @@ class DibiRow implements ArrayAccess, IteratorAggregate, Countable
{
$time = $this[$key];
if (!$time instanceof DibiDateTime) {
if ((int) $time === 0) { // '', NULL, FALSE, '0000-00-00', ...
if ((int) $time === 0 && substr((string) $time, 0, 3) !== '00:') { // '', NULL, FALSE, '0000-00-00', ...
return NULL;
}
$time = new DibiDateTime(is_numeric($time) ? date('Y-m-d H:i:s', $time) : $time);
$time = new DibiDateTime($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);

View File

@@ -2,15 +2,10 @@
/**
* 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.
*
@@ -53,14 +48,13 @@ final class DibiTranslator extends DibiObject
private $identifiers;
public function __construct(DibiConnection $connection)
{
$this->connection = $connection;
$this->identifiers = new DibiHashMap(array($this, 'delimite'));
}
/**
* Generates SQL.
* @param array
@@ -69,8 +63,9 @@ final class DibiTranslator extends DibiObject
*/
public function translate(array $args)
{
$this->identifiers = new DibiHashMap(array($this, 'delimite'));
$this->driver = $this->connection->getDriver();
if (!$this->driver) {
$this->driver = $this->connection->getDriver();
}
$args = array_values($args);
while (count($args) === 1 && is_array($args[0])) { // implicit array expansion
@@ -94,8 +89,7 @@ final class DibiTranslator extends DibiObject
// iterate
$sql = array();
while ($cursor < count($this->args))
{
while ($cursor < count($this->args)) {
$arg = $this->args[$cursor];
$cursor++;
@@ -126,7 +120,9 @@ 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;
}
@@ -148,7 +144,9 @@ 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;
@@ -161,7 +159,9 @@ final class DibiTranslator extends DibiObject
} // while
if ($comment) $sql[] = "*/";
if ($comment) {
$sql[] = "*/";
}
$sql = implode(' ', $sql);
@@ -178,7 +178,6 @@ final class DibiTranslator extends DibiObject
}
/**
* Apply modifier to single value.
* @param mixed
@@ -191,6 +190,10 @@ final class DibiTranslator extends DibiObject
return "...";
}
if (!$this->driver) {
$this->driver = $this->connection->getDriver();
}
// array processing (with or without modifier)
if ($value instanceof Traversable) {
$value = iterator_to_array($value);
@@ -199,231 +202,235 @@ 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 {
$op = '= ';
$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;
}
$vx[] = $k . $op . $v;
} else {
$vx[] = $this->formatValue($v, 'ex');
}
} 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.**';
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);
}
} else {
$proto = array_keys($v);
$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));
}
} 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));
foreach ($vx as $k => $v) {
$vx[$k] = '(' . implode(', ', $v) . ')';
}
}
foreach ($vx as $k => $v) {
$vx[$k] = '(' . implode(', ', $v) . ')';
}
return '(' . implode(', ', $kx) . ') VALUES ' . implode(', ', $vx);
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;
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);
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);
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)) { // array is already processed
if ($value !== NULL && !is_scalar($value) && !$value instanceof DateTime && !$value instanceof DateTimeInterface) { // array is already processed
$this->hasError = TRUE;
return '**Unexpected type ' . gettype($value) . '**';
}
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 '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);
case 'iN': // signed int or NULL
case 'in': // deprecated
if ($value == '') {
$value = NULL;
}
return $this->driver->escape($value, $modifier);
}
// intentionally break omitted
case 'by':
case 'n': // identifier name
return $this->identifiers->$value;
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 '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;
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 'SQL': // preserve as real SQL (TODO: rename to %sql)
return (string) $value;
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, -1);
case 'by':
case 'n': // identifier name
return $this->identifiers->$value;
case '~like~': // LIKE %string%
return $this->driver->escapeLike($value, 0);
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;
case 'and':
case 'or':
case 'a':
case 'l':
case 'v':
$this->hasError = TRUE;
return '**Unexpected type ' . gettype($value) . '**';
case 'SQL': // preserve as real SQL (TODO: rename to %sql)
return (string) $value;
default:
$this->hasError = TRUE;
return "**Unknown or invalid modifier %$modifier**";
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 +451,7 @@ final class DibiTranslator extends DibiObject
} elseif ($value === NULL) {
return 'NULL';
} elseif ($value instanceof DateTime) {
} elseif ($value instanceof DateTime || $value instanceof DateTimeInterface) {
return $this->driver->escape($value, dibi::DATETIME);
} elseif ($value instanceof DibiLiteral) {
@@ -457,7 +464,6 @@ final class DibiTranslator extends DibiObject
}
/**
* PREG callback from translate() or formatValue().
* @param array
@@ -536,13 +542,23 @@ final class DibiTranslator extends DibiObject
return '';
} elseif ($mod === 'lmt') { // apply limit
if ($this->args[$cursor] !== NULL) $this->limit = (int) $this->args[$cursor];
$cursor++;
$arg = $this->args[$cursor++];
if ($arg === NULL) {
} elseif ($this->comment) {
return "(limit $arg)";
} else {
$this->limit = (int) $arg;
}
return '';
} elseif ($mod === 'ofs') { // apply offset
if ($this->args[$cursor] !== NULL) $this->offset = (int) $this->args[$cursor];
$cursor++;
$arg = $this->args[$cursor++];
if ($arg === NULL) {
} elseif ($this->comment) {
return "(offset $arg)";
} else {
$this->offset = (int) $arg;
}
return '';
} else { // default processing
@@ -551,21 +567,23 @@ 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]};
if ($matches[2]) // SQL identifiers: [ident]
} elseif ($matches[2]) { // SQL identifiers: [ident]
return $this->identifiers->{$matches[2]};
if ($matches[3]) // SQL strings: '...'
} elseif ($matches[3]) { // SQL strings: '...'
return $this->driver->escape( str_replace("''", "'", $matches[4]), dibi::TEXT);
if ($matches[5]) // SQL strings: "..."
} elseif ($matches[5]) { // SQL strings: "..."
return $this->driver->escape( str_replace('""', '"', $matches[6]), dibi::TEXT);
if ($matches[7]) { // string quote
} elseif ($matches[7]) { // string quote
$this->hasError = TRUE;
return '**Alone quote**';
}
@@ -580,7 +598,6 @@ final class DibiTranslator extends DibiObject
}
/**
* Apply substitutions to indentifier and delimites it.
* @param string indentifier
@@ -592,7 +609,9 @@ 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);
}

View File

@@ -2,15 +2,10 @@
/**
* 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
@@ -22,7 +17,6 @@ interface IDataSource extends Countable, IteratorAggregate
}
/**
* dibi driver interface.
* @package dibi
@@ -36,7 +30,7 @@ interface IDibiDriver
* @return void
* @throws DibiException
*/
function connect(array &$config);
function connect(array & $config);
/**
* Disconnects from a database.
@@ -120,19 +114,13 @@ 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
@@ -193,9 +181,6 @@ interface IDibiResultDriver
}
/**
* dibi driver reflection.
*

1
examples/.gitignore vendored
View File

@@ -1,3 +1,4 @@
_test.bat
ref
output
log

File diff suppressed because one or more lines are too long

View File

@@ -1,62 +0,0 @@
Licenses
========
Good news! You may use Nette Framework 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 Nette Framework in commercial projects as long as the copyright header
remains intact.
Please be advised that the name "Nette Framework" is a protected trademark and its
usage has some limitations. So please do not use word "Nette" 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) 2004, 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 "Nette Framework" 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

View File

@@ -1,3 +0,0 @@
This file is part of Nette Framework
For more information please see http://nette.org

View File

@@ -4,16 +4,15 @@
<?php
require dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
require __DIR__ . '/../dibi/dibi.php';
// connects to SQlite using dibi class
echo '<p>Connecting to Sqlite: ';
try {
dibi::connect(array(
'driver' => 'sqlite',
'database' => 'data/sample.sdb',
'driver' => 'sqlite3',
'database' => 'data/sample.s3db',
));
echo 'OK';
@@ -23,14 +22,12 @@ try {
echo "</p>\n";
// connects to SQlite using DibiConnection object
echo '<p>Connecting to Sqlite: ';
try {
$connection = new DibiConnection(array(
'driver' => 'sqlite',
'database' => 'data/sample.sdb',
'driver' => 'sqlite3',
'database' => 'data/sample.s3db',
));
echo 'OK';
@@ -40,8 +37,6 @@ try {
echo "</p>\n";
// connects to MySQL using DSN
echo '<p>Connecting to MySQL: ';
try {
@@ -54,8 +49,6 @@ try {
echo "</p>\n";
// connects to MySQLi using array
echo '<p>Connecting to MySQLi: ';
try {
@@ -78,8 +71,6 @@ try {
echo "</p>\n";
// connects to ODBC
echo '<p>Connecting to ODBC: ';
try {
@@ -87,7 +78,7 @@ try {
'driver' => 'odbc',
'username' => 'root',
'password' => '***',
'dsn' => 'Driver={Microsoft Access Driver (*.mdb)};Dbq='.dirname(__FILE__).'/data/sample.mdb',
'dsn' => 'Driver={Microsoft Access Driver (*.mdb)};Dbq='.__DIR__.'/data/sample.mdb',
));
echo 'OK';
@@ -97,8 +88,6 @@ try {
echo "</p>\n";
// connects to PostgreSql
echo '<p>Connecting to PostgreSql: ';
try {
@@ -115,8 +104,6 @@ try {
echo "</p>\n";
// connects to PDO
echo '<p>Connecting to Sqlite via PDO: ';
try {
@@ -132,7 +119,6 @@ try {
echo "</p>\n";
// connects to MS SQL
echo '<p>Connecting to MS SQL: ';
try {
@@ -150,7 +136,6 @@ try {
echo "</p>\n";
// connects to MS SQL 2005
echo '<p>Connecting to MS SQL 2005: ';
try {
@@ -169,7 +154,6 @@ try {
echo "</p>\n";
// connects to Oracle
echo '<p>Connecting to Oracle: ';
try {

View File

@@ -2,7 +2,7 @@ body {
font: 15px/1.5 Tahoma, Verdana, Myriad Web, Syntax, sans-serif;
color: #333;
background: #fff url('dibi-powered.gif') no-repeat 99% 1em;
margin: 1.6em;
margin: 1.6em;
padding: 0;
}
@@ -41,24 +41,24 @@ table.dump th {
}
/* dump() */
pre.nette-dump, pre.dump {
pre.tracy-dump, pre.dump {
color: #444; background: white;
border: 1px solid silver;
padding: 1em;
margin: 1em 0;
}
pre.nette-dump .php-array, pre.nette-dump .php-object {
pre.tracy-dump .php-array, pre.tracy-dump .php-object {
color: #C22;
}
pre.nette-dump .php-string {
pre.tracy-dump .php-string {
color: #080;
}
pre.nette-dump .php-int, pre.nette-dump .php-float {
pre.tracy-dump .php-int, pre.tracy-dump .php-float {
color: #37D;
}
pre.nette-dump .php-null, pre.nette-dump .php-bool {
pre.tracy-dump .php-null, pre.tracy-dump .php-bool {
color: black;
}
pre.nette-dump .php-visibility {
pre.tracy-dump .php-visibility {
font-size: 85%; color: #999;
}

View File

@@ -4,17 +4,15 @@
<?php
require dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
require __DIR__ . '/../dibi/dibi.php';
dibi::connect(array(
'driver' => 'sqlite',
'database' => 'data/sample.sdb',
'driver' => 'sqlite3',
'database' => 'data/sample.s3db',
));
// retrieve database reflection
$database = dibi::getDatabaseInfo();
@@ -26,7 +24,6 @@ foreach ($database->getTables() as $table) {
echo "</ul>\n";
// table reflection
$table = $database->getTable('products');
@@ -40,7 +37,6 @@ foreach ($table->getColumns() as $column) {
echo "</ul>\n";
echo "Indexes";
echo "<ul>\n";
foreach ($table->getIndexes() as $index) {

View File

@@ -4,17 +4,15 @@
<?php
require dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
require __DIR__ . '/../dibi/dibi.php';
dibi::connect(array(
'driver' => 'sqlite',
'database' => 'data/sample.sdb',
'driver' => 'sqlite3',
'database' => 'data/sample.s3db',
));
$res = dibi::query('
SELECT * FROM products
INNER JOIN orders USING (product_id)

View File

@@ -4,14 +4,16 @@
<?php
require dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
if (@!include __DIR__ . '/../vendor/autoload.php') {
die('Install dependencies using `composer install --dev`');
}
Tracy\Debugger::enable();
ndebug();
dibi::connect(array(
'driver' => 'sqlite',
'database' => 'data/sample.sdb',
'driver' => 'sqlite3',
'database' => 'data/sample.s3db',
));
@@ -30,38 +32,40 @@ product_id | title
// fetch a single row
echo "<h2>fetch()</h2>\n";
$row = dibi::fetch('SELECT title FROM products');
dump($row); // Chair
Tracy\Dumper::dump($row); // Chair
// fetch a single value
echo "<h2>fetchSingle()</h2>\n";
$value = dibi::fetchSingle('SELECT title FROM products');
dump($value); // Chair
Tracy\Dumper::dump($value); // Chair
// fetch complete result set
echo "<h2>fetchAll()</h2>\n";
$all = dibi::fetchAll('SELECT * FROM products');
dump($all);
Tracy\Dumper::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
dump($assoc);
Tracy\Dumper::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');
dump($pairs);
Tracy\Dumper::dump($pairs);
// fetch row by row
echo "<h2>using foreach</h2>\n";
$res = dibi::query('SELECT * FROM products');
foreach ($res as $n => $row) {
dump($row);
Tracy\Dumper::dump($row);
}
@@ -73,14 +77,16 @@ $res = dibi::query('
INNER JOIN customers USING (customer_id)
');
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";
$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);

View File

@@ -4,13 +4,12 @@
<?php
require dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
require __DIR__ . '/../dibi/dibi.php';
dibi::connect(array(
'driver' => 'sqlite',
'database' => 'data/sample.sdb',
'driver' => 'sqlite3',
'database' => 'data/sample.s3db',
));

View File

@@ -1,45 +0,0 @@
<!DOCTYPE html><link rel="stylesheet" href="data/style.css">
<h1>Nette Debugger & SQL Exceptions | dibi</h1>
<p>Dibi can display and log exceptions via Nette Debugger, part of Nette Framework.</p>
<ul>
<li>Nette Framework: http://nette.org
</ul>
<?php
require dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
// enable Nette Debugger
ndebug();
dibi::connect(array(
'driver' => 'sqlite',
'database' => 'data/sample.sdb',
'profiler' => array(
'run' => TRUE,
)
));
// throws error because SQL is bad
dibi::query('SELECT * FROM customers WHERE customer_id < ?', 38);
dibi::connect(array(
'driver' => 'sqlite',
'database' => 'data/sample.sdb',
'profiler' => array(
'run' => TRUE,
)
));
// throws error because SQL is bad
dibi::query('SELECT FROM customers WHERE customer_id < ?', 38);

View File

@@ -1,32 +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>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 dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../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]' );

View File

@@ -4,8 +4,7 @@
<?php
require dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
require __DIR__ . '/../dibi/dibi.php';
dibi::connect(array(
@@ -32,8 +31,6 @@ dibi::test('
// -> SELECT * FROM customers WHERE name LIKE 'K%'
// if & else & (optional) end
dibi::test("
SELECT *
@@ -45,7 +42,6 @@ dibi::test("
// -> SELECT * FROM people WHERE id > 0 AND bar=2
// nested condition
dibi::test('
SELECT *
@@ -58,7 +54,6 @@ dibi::test('
// -> SELECT * FROM customers WHERE LIMIT 10
// IF()
dibi::test('UPDATE products SET', array(
'price' => array('IF(price_fixed, price, ?)', 123),

View File

@@ -4,8 +4,7 @@
<?php
require dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
require __DIR__ . '/../dibi/dibi.php';
date_default_timezone_set('Europe/Prague');
@@ -29,7 +28,6 @@ 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(
@@ -40,7 +38,6 @@ dibi::test('
// -> REPLACE INTO products ([title], [price], [active]) VALUES ('Super product', 318, 1)
// multiple INSERT command
$array = array(
'title' => 'Super Product',
@@ -52,7 +49,6 @@ 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(
@@ -63,7 +59,6 @@ dibi::test("
// -> UPDATE colors SET [color]='blue', [order]=12 WHERE id=123
// modifier applied to array
$array = array(1, 2, 3);
dibi::test("
@@ -74,7 +69,6 @@ dibi::test("
// -> SELECT * FROM people WHERE id IN ( 1, 2, 3 )
// modifier %by for ORDER BY
$order = array(
'field1' => 'asc',
@@ -88,7 +82,6 @@ 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'

View File

@@ -1,19 +1,21 @@
<!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 dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
if (@!include __DIR__ . '/../vendor/autoload.php') {
die('Install dependencies using `composer install --dev`');
}
Tracy\Debugger::enable();
ndebug();
date_default_timezone_set('Europe/Prague');
dibi::connect(array(
'driver' => 'sqlite',
'database' => 'data/sample.sdb',
'driver' => 'sqlite3',
'database' => 'data/sample.s3db',
));
@@ -25,7 +27,7 @@ $res->setType('customer_id', Dibi::INTEGER)
->setFormat(dibi::DATETIME, 'Y-m-d H:i:s');
dump( $res->fetch() );
Tracy\Dumper::dump( $res->fetch() );
// outputs:
// DibiRow(3) {
// customer_id => 1
@@ -33,11 +35,10 @@ dump( $res->fetch() );
// added => "2007-03-11 17:20:03" (19)
// using auto-detection (works well with MySQL or other strictly typed databases)
$res = dibi::query('SELECT * FROM [customers]');
dump( $res->fetch() );
Tracy\Dumper::dump( $res->fetch() );
// outputs:
// DibiRow(3) {
// customer_id => 1

View File

@@ -0,0 +1,33 @@
<!DOCTYPE html><link rel="stylesheet" href="data/style.css">
<h1>Tracy & SQL Exceptions | dibi</h1>
<p>Dibi can display and log exceptions via <a href="http://tracy.nette.org">Tracy</a>.</p>
<?php
if (@!include __DIR__ . '/../vendor/autoload.php') {
die('Install dependencies using `composer install --dev`');
}
// enable Tracy
Tracy\Debugger::enable();
$connection = dibi::connect(array(
'driver' => 'sqlite3',
'database' => 'data/sample.s3db',
'profiler' => array(
'run' => TRUE,
)
));
// add panel to debug bar
$panel = new Dibi\Bridges\Tracy\Panel;
$panel->register($connection);
// throws error because SQL is bad
dibi::query('SELECT FROM customers WHERE customer_id < ?', 38);

38
examples/tracy.php Normal file
View File

@@ -0,0 +1,38 @@
<!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 | dibi</h1>
<p>Dibi can log queries and dump variables to the <a href="http://tracy.nette.org">Tracy</a>.</p>
<?php
if (@!include __DIR__ . '/../vendor/autoload.php') {
die('Install dependencies using `composer install --dev`');
}
// enable Tracy
Tracy\Debugger::enable();
$connection = dibi::connect(array(
'driver' => 'sqlite3',
'database' => 'data/sample.s3db',
'profiler' => array(
'run' => TRUE,
)
));
// add panel to debug bar
$panel = new Dibi\Bridges\Tracy\Panel;
$panel->register($connection);
// query will be logged
dibi::query('SELECT 123');
// result set will be dumped
Tracy\Debugger::barDump( dibi::fetchAll('SELECT * FROM customers WHERE customer_id < ?', 38), '[customers]' );

View File

@@ -4,23 +4,20 @@
<?php
require dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
require __DIR__ . '/../dibi/dibi.php';
date_default_timezone_set('Europe/Prague');
// CHANGE TO REAL PARAMETERS!
dibi::connect(array(
'driver' => 'sqlite',
'database' => 'data/sample.sdb',
'driver' => 'sqlite3',
'database' => 'data/sample.s3db',
'formatDate' => "'Y-m-d'",
'formatDateTime' => "'Y-m-d H-i-s'",
));
// generate and dump SQL
dibi::test("
INSERT INTO [mytable]", array(

View File

@@ -4,28 +4,29 @@
<?php
require dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
if (@!include __DIR__ . '/../vendor/autoload.php') {
die('Install dependencies using `composer install --dev`');
}
Tracy\Debugger::enable();
ndebug();
dibi::connect(array(
'driver' => 'sqlite',
'database' => 'data/sample.sdb',
'driver' => 'sqlite3',
'database' => 'data/sample.s3db',
));
// using the "prototype" to add custom method to class DibiResult
function DibiResult_prototype_fetchShuffle(DibiResult $obj)
DibiResult::extensionMethod('fetchShuffle', function(DibiResult $obj)
{
$all = $obj->fetchAll();
shuffle($all);
return $all;
}
});
// fetch complete result set shuffled
$res = dibi::query('SELECT * FROM [customers]');
$all = $res->fetchShuffle();
dump($all);
Tracy\Dumper::dump($all);

View File

@@ -4,15 +4,14 @@
<?php
require dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
require __DIR__ . '/../dibi/dibi.php';
date_default_timezone_set('Europe/Prague');
dibi::connect(array(
'driver' => 'sqlite',
'database' => 'data/sample.sdb',
'driver' => 'sqlite3',
'database' => 'data/sample.s3db',
));
@@ -35,7 +34,6 @@ 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')
@@ -43,7 +41,6 @@ echo dibi::select('title')->as('id')
// -> Chair (as result of query: SELECT [title] AS [id] FROM [products])
// INSERT ...
dibi::insert('products', $record)
->setFlag('IGNORE')
@@ -51,7 +48,6 @@ 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)
@@ -59,7 +55,6 @@ 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)
@@ -67,7 +62,6 @@ dibi::delete('products')
// -> DELETE FROM [products] WHERE product_id = 10
// custom commands
dibi::command()
->update('products')
@@ -77,7 +71,6 @@ dibi::command()
// -> UPDATE [products] SET [title]='Super product', [price]=318, [active]=1 WHERE product_id = 10
dibi::command()
->truncate('products')
->test();

View File

@@ -4,13 +4,12 @@
<?php
require dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
require __DIR__ . '/../dibi/dibi.php';
dibi::connect(array(
'driver' => 'sqlite',
'database' => 'data/sample.sdb',
'driver' => 'sqlite3',
'database' => 'data/sample.s3db',
));
@@ -19,13 +18,11 @@ 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

View File

@@ -4,15 +4,14 @@
<?php
require dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
require __DIR__ . '/../dibi/dibi.php';
date_default_timezone_set('Europe/Prague');
dibi::connect(array(
'driver' => 'sqlite',
'database' => 'data/sample.sdb',
'driver' => 'sqlite3',
'database' => 'data/sample.s3db',
// enable query logging to this file
'profiler' => array(
'run' => TRUE,
@@ -21,7 +20,6 @@ dibi::connect(array(
));
try {
$res = dibi::query('SELECT * FROM [customers] WHERE [customer_id] = ?', 1);

View File

@@ -1,4 +1,4 @@
<?php ob_start(1) // needed by FirePHP ?>
<?php ob_start() // needed by FirePHP ?>
<!DOCTYPE html><link rel="stylesheet" href="data/style.css">
@@ -6,13 +6,12 @@
<?php
require dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
require __DIR__ . '/../dibi/dibi.php';
dibi::connect(array(
'driver' => 'sqlite',
'database' => 'data/sample.sdb',
'driver' => 'sqlite3',
'database' => 'data/sample.s3db',
'profiler' => array(
'run' => TRUE,
)

View File

@@ -4,18 +4,15 @@
<?php
require dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
require __DIR__ . '/../dibi/dibi.php';
dibi::connect(array(
'driver' => 'sqlite',
'database' => 'data/sample.sdb',
'driver' => 'sqlite3',
'database' => 'data/sample.s3db',
));
// create new substitution :blog: ==> wp_
dibi::getSubstitutes()->blog = 'wp_';
@@ -23,9 +20,6 @@ dibi::test("SELECT * FROM [:blog:items]");
// -> SELECT * FROM [wp_items]
// create new substitution :: (empty) ==> my_
dibi::getSubstitutes()->{''} = 'my_';
@@ -33,9 +27,6 @@ dibi::test("UPDATE ::table SET [text]='Hello World'");
// -> UPDATE my_table SET [text]='Hello World'
// create substitutions using fallback callback
function substFallBack($expr)
{

View File

@@ -4,13 +4,12 @@
<?php
require dirname(__FILE__) . '/Nette/Debugger.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
require __DIR__ . '/../dibi/dibi.php';
dibi::connect(array(
'driver' => 'sqlite',
'database' => 'data/sample.sdb',
'driver' => 'sqlite3',
'database' => 'data/sample.s3db',
));

View File

@@ -13,11 +13,10 @@ use Dibi in commercial projects as long as the copyright header
remains intact.
New BSD License
---------------
Copyright (c) 2004, 2013 David Grudl (http://davidgrudl.com)
Copyright (c) 2004, 2014 David Grudl (http://davidgrudl.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
@@ -46,7 +45,6 @@ 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
--------------------------

126
readme.md
View File

@@ -1,18 +1,130 @@
[Dibi](http://dibiphp.com) - smart database layer for PHP
[Dibi](http://dibiphp.com) - smart database layer for PHP [![Buy me a coffee](http://files.nette.org/images/coffee1s.png)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=9XXL5ZJHAYQUN)
=========================================================
Database access functions in PHP are not standardised. This library
hides the differences between them, a above all, it gives you a very handy interface.
[![Downloads this Month](https://img.shields.io/packagist/dm/dibi/dibi.svg)](https://packagist.org/packages/dibi/dibi)
[![Build Status](https://travis-ci.org/dg/dibi.svg?branch=master)](https://travis-ci.org/dg/dibi)
The best way how to install Dibi is to use a [Composer](http://getcomposer.org/download):
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 a latest package from http://dibiphp.com. In this
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 library, but just use it.
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).
Dibi requires PHP 5.2.0 or later. It has been tested with PHP 5.5 too.
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;
```

4
tests/.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
output
/tmp
/test.log
/databases.ini

View File

@@ -1,43 +0,0 @@
<?php
/**
* Test: Cloning of DibiFluent
*
* @author David Grudl
*/
require dirname(__FILE__) . '/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 );

View File

@@ -1,18 +0,0 @@
<?php
/**
* Test initialization and helpers.
*
* @author David Grudl
* @package Nette\Test
*/
require dirname(__FILE__) . '/../vendor/nette/tester/Tester/bootstrap.php';
require dirname(__FILE__) . '/../dibi/dibi.php';
date_default_timezone_set('Europe/Prague');
class_alias('Tester\Assert', 'Assert');
// load connections
define('DIR', dirname(__FILE__));
$config = parse_ini_file(dirname(__FILE__) . '/config.ini', TRUE);

View File

@@ -1,67 +0,0 @@
[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

Binary file not shown.

View File

@@ -1,149 +0,0 @@
-- phpMyAdmin SQL Dump
-- version 2.11.1.2
-- http://www.phpmyadmin.net
--
-- Po<50><6F>ta<74>: localhost
-- Vygenerov<6F>no: Ned<65>le 02. prosince 2007, 19:49
-- Verze MySQL: 5.0.45
-- Verze PHP: 5.2.1
SET FOREIGN_KEY_CHECKS=0;
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
--
-- Datab<61>ze: `dibi`
--
-- --------------------------------------------------------
--
-- Struktura tabulky `customers`
--
DROP TABLE IF EXISTS `customers`;
CREATE TABLE IF NOT EXISTS `customers` (
`customer_id` int(11) NOT NULL auto_increment,
`name` varchar(100) default NULL,
PRIMARY KEY (`customer_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;
--
-- Vypisuji data pro tabulku `customers`
--
INSERT INTO `customers` (`customer_id`, `name`) VALUES
(1, 'Dave Lister'),
(2, 'Arnold Rimmer'),
(3, 'The Cat'),
(4, 'Holly'),
(5, 'Kryten'),
(6, 'Kristine Kochanski');
-- --------------------------------------------------------
--
-- Struktura tabulky `enumtest`
--
DROP TABLE IF EXISTS `enumtest`;
CREATE TABLE IF NOT EXISTS `enumtest` (
`id` int(11) NOT NULL auto_increment,
`test` enum('a','b','c') NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
-- Vypisuji data pro tabulku `enumtest`
--
-- --------------------------------------------------------
--
-- Struktura tabulky `orders`
--
DROP TABLE IF EXISTS `orders`;
CREATE TABLE IF NOT EXISTS `orders` (
`order_id` int(11) NOT NULL,
`customer_id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
`amount` float NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
--
-- Vypisuji data pro tabulku `orders`
--
INSERT INTO `orders` (`order_id`, `customer_id`, `product_id`, `amount`) VALUES
(1, 2, 1, 7),
(2, 2, 3, 2),
(3, 1, 2, 3),
(4, 6, 3, 5);
-- --------------------------------------------------------
--
-- Struktura tabulky `products`
--
DROP TABLE IF EXISTS `products`;
CREATE TABLE IF NOT EXISTS `products` (
`product_id` int(11) NOT NULL auto_increment,
`title` varchar(100) default NULL,
PRIMARY KEY (`product_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
-- Vypisuji data pro tabulku `products`
--
INSERT INTO `products` (`product_id`, `title`) VALUES
(1, 'Chair'),
(2, 'Table'),
(3, 'Computer');
-- --------------------------------------------------------
--
-- Struktura tabulky `settest`
--
DROP TABLE IF EXISTS `settest`;
CREATE TABLE IF NOT EXISTS `settest` (
`id` int(11) NOT NULL auto_increment,
`test` set('a','b','c') NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
-- Vypisuji data pro tabulku `settest`
--
-- --------------------------------------------------------
--
-- Struktura tabulky `where`
--
DROP TABLE IF EXISTS `where`;
CREATE TABLE IF NOT EXISTS `where` (
`select` int(11) NOT NULL,
`dot.dot` int(11) NOT NULL,
`is` int(11) NOT NULL,
`quot'n' space` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
--
-- Vypisuji data pro tabulku `where`
--
INSERT INTO `where` (`select`, `dot.dot`, `is`, `quot'n' space`) VALUES
(1, 2, 3, 4);
SET FOREIGN_KEY_CHECKS=1;
SET SQL_MODE="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION";

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,76 @@
[mysql]
driver = mysql
host = 127.0.0.1
username = root
password =
charset = utf8
system = mysql
[mysqli]
driver = mysqli
host = 127.0.0.1
username = root
password =
charset = utf8
system = mysql
[sqlite2]
driver = sqlite
database = :memory:
system = sqlite
[sqlite3] ; default
driver = sqlite3
database = :memory:
system = sqlite
[pgsql]
driver = postgre
host = 127.0.0.1
username = postgres
password =
system = pgsql
[odbc]
driver = odbc
dsn = "Driver={Microsoft Access Driver (*.mdb)}Dbq=data/odbc_tmp.mdb"
system = odbc
[mssql]
driver = mssql
host = 127.0.0.1
username = dibi
password =
system = mssql
[mssql2005]
driver = mssql2005
host = (local)
username = dibi
password =
system = mssql
[oracle]
driver = oracle
username = dibi
password =
system = oracle
[sqlite-pdo]
driver = pdo
dsn = "sqlite::memory:"
system = sqlite
[mysql-pdo]
driver = pdo
dsn = "mysql:host=127.0.0.1"
username = root
password =
system = mysql
[pgsql-pdo]
driver = pdo
dsn = "pgsql:host=127.0.0.1;dbname=dibi_test"
username = postgres
password =
system = pgsql

159
tests/dibi/DataSource.phpt Normal file
View File

@@ -0,0 +1,159 @@
<?php
use Tester\Assert;
require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql");
$ds = $conn->dataSource('SELECT * FROM products');
Assert::match(
reformat("
SELECT *
FROM (SELECT * FROM products) t"),
(string) $ds
);
Assert::same(3, $ds->count());
Assert::same(3, $ds->getTotalCount());
Assert::same(
reformat('SELECT COUNT(*) FROM (SELECT * FROM products) t'),
dibi::$sql
);
$ds->select('title');
$ds->orderBy('title', dibi::DESC);
$ds->where('title like "%a%"');
Assert::match(
reformat("
SELECT [title]
FROM (SELECT * FROM products) t
WHERE (title like '%a%')
ORDER BY [title] DESC
"),
(string) $ds
);
$ds->select('product_id');
$ds->orderBy('product_id', dibi::ASC);
$ds->where('product_id = %i', 1);
Assert::match(
reformat("
SELECT [title], [product_id]
FROM (SELECT * FROM products) t
WHERE (title like '%a%') AND (product_id = 1)
ORDER BY [title] DESC, [product_id] ASC
"),
(string) $ds
);
$ds->select(array('product_id'));
$ds->orderBy(array('product_id' => dibi::ASC));
$ds->where(array('product_id = 1'));
Assert::match(
reformat("
SELECT [product_id]
FROM (SELECT * FROM products) t
WHERE (title like '%a%') AND (product_id = 1) AND (product_id = 1)
ORDER BY [product_id] ASC
"),
(string) $ds
);
Assert::same(1, $ds->count());
Assert::same(3, $ds->getTotalCount());
Assert::match(reformat("SELECT COUNT(*) FROM (
SELECT [product_id]
FROM (SELECT * FROM products) t
WHERE (title like '%a%') AND (product_id = 1) AND (product_id = 1)
ORDER BY [product_id] ASC
) t"), dibi::$sql);
Assert::same(1, $ds->toDataSource()->count());
Assert::equal(array(
new DibiRow(array(
'product_id' => 1,
)),
), iterator_to_array($ds));
Assert::match(
reformat("
SELECT [product_id]
FROM (SELECT * FROM products) t
WHERE (title like '%a%') AND (product_id = 1) AND (product_id = 1)
ORDER BY [product_id] ASC
"),
dibi::$sql
);
$fluent = $ds->toFluent();
Assert::same(1, $fluent->count());
Assert::match(
reformat("SELECT * FROM (
SELECT [product_id]
FROM (SELECT * FROM products) t
WHERE (title like '%a%') AND (product_id = 1) AND (product_id = 1)
ORDER BY [product_id] ASC
) t"),
(string) $fluent
);
$ds = $conn->select('title')->from('products')->toDataSource();
Assert::match(
reformat("
SELECT *
FROM (SELECT [title] FROM [products]) t"),
(string) $ds
);
Assert::equal(new DibiRow(array(
'product_id' => 1,
'title' => 'Chair',
)), $conn->dataSource('SELECT * FROM products ORDER BY product_id')->fetch());
Assert::same(1, $conn->dataSource('SELECT * FROM products ORDER BY product_id')->fetchSingle());
Assert::same(
array(1 => 'Chair', 'Table', 'Computer'),
$conn->dataSource('SELECT * FROM products ORDER BY product_id')->fetchPairs()
);
Assert::equal(array(
1 => new DibiRow(array(
'product_id' => 1,
'title' => 'Chair',
)),
new DibiRow(array(
'product_id' => 2,
'title' => 'Table',
)),
new DibiRow(array(
'product_id' => 3,
'title' => 'Computer',
)),
), $conn->dataSource('SELECT * FROM products ORDER BY product_id')->fetchAssoc('product_id'));
$ds = new DibiDataSource('products', $conn);
Assert::match(
reformat("
SELECT *
FROM [products]"),
(string) $ds
);
Assert::same(3, $ds->count());
Assert::same(3, $ds->getTotalCount());
Assert::same(reformat('SELECT COUNT(*) FROM [products]'), dibi::$sql);

View File

@@ -0,0 +1,35 @@
<?php
/**
* @dataProvider ../databases.ini
*/
use Tester\Assert;
require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql");
$conn->query('INSERT INTO products', array(
'title' => 'Test product',
));
Assert::same(1, $conn->getAffectedRows());
$conn->query('UPDATE products SET title="xxx" WHERE product_id > 100');
Assert::same(0, $conn->getAffectedRows());
$conn->query('UPDATE products SET title="xxx"');
Assert::same(4, $conn->getAffectedRows());
$conn->query('DELETE FROM orders');
$conn->query('DELETE FROM products WHERE product_id > 100');
Assert::same(0, $conn->getAffectedRows());
$conn->query('DELETE FROM products WHERE product_id < 3');
Assert::same(2, $conn->getAffectedRows());

View File

@@ -0,0 +1,37 @@
<?php
/**
* @dataProvider ../databases.ini
*/
use Tester\Assert;
require __DIR__ . '/bootstrap.php';
test(function() use ($config) {
$conn = new DibiConnection($config);
Assert::true($conn->isConnected());
$conn->disconnect();
Assert::false($conn->isConnected());
});
test(function() use ($config) { // lazy
$conn = new DibiConnection($config + array('lazy' => TRUE));
Assert::false($conn->isConnected());
$conn->query('SELECT 1');
Assert::true($conn->isConnected());
});
test(function() use ($config) { // query string
$conn = new DibiConnection(http_build_query($config, NULL, '&'));
Assert::true($conn->isConnected());
Assert::null($conn->getConfig('lazy'));
Assert::same($config['driver'], $conn->getConfig('driver'));
Assert::type('IDibiDriver', $conn->getDriver());
});

View File

@@ -0,0 +1,329 @@
<?php
/**
* @dataProvider ../databases.ini
*/
use Tester\Assert;
require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql");
function num($n)
{
global $config;
if (substr(@$config['dsn'], 0, 5) === 'odbc:' || $config['driver'] === 'sqlite') {
$n = is_float($n) ? "$n.0" : (string) $n;
}
return $n;
}
// fetch a single value
$res = $conn->query('SELECT [title] FROM [products]');
Assert::same('Chair', $res->fetchSingle());
// fetch complete result set
$res = $conn->query('SELECT * FROM [products] ORDER BY product_id');
Assert::equal(array(
new DibiRow(array('product_id' => num(1), 'title' => 'Chair')),
new DibiRow(array('product_id' => num(2), 'title' => 'Table')),
new DibiRow(array('product_id' => num(3), 'title' => 'Computer')),
), $res->fetchAll());
// fetch complete result set like pairs key => value
$res = $conn->query('SELECT * FROM [products] ORDER BY product_id');
Assert::same(
array(1 => 'Chair', 'Table', 'Computer'),
$res->fetchPairs('product_id', 'title')
);
$res = $conn->query('SELECT * FROM [products] ORDER BY product_id');
Assert::same(
array(1 => 'Chair', 'Table', 'Computer'),
$res->fetchPairs()
);
// fetch row by row
$res = $conn->query('SELECT * FROM [products] ORDER BY product_id');
Assert::equal(array(
new DibiRow(array('product_id' => num(1), 'title' => 'Chair')),
new DibiRow(array('product_id' => num(2), 'title' => 'Table')),
new DibiRow(array('product_id' => num(3), 'title' => 'Computer')),
), iterator_to_array($res));
// fetch complete result set like association array
$res = $conn->query('SELECT * FROM [products] ORDER BY product_id');
Assert::equal(array(
'Chair' => new DibiRow(array('product_id' => num(1), 'title' => 'Chair')),
'Table' => new DibiRow(array('product_id' => num(2), 'title' => 'Table')),
'Computer' => new DibiRow(array('product_id' => num(3), 'title' => 'Computer')),
), $res->fetchAssoc('title'));
// more complex association array
function query($conn) {
return $conn->query($conn->getConfig('system') === 'odbc' ? '
SELECT products.title, customers.name, orders.amount
FROM ([products]
INNER JOIN [orders] ON [products.product_id] = [orders.product_id])
INNER JOIN [customers] ON [orders.customer_id] = [customers.customer_id]
ORDER BY orders.order_id
' : '
SELECT products.title AS title, customers.name AS name, orders.amount AS amount
FROM [products]
INNER JOIN [orders] USING ([product_id])
INNER JOIN [customers] USING ([customer_id])
ORDER BY orders.order_id
');
}
Assert::equal(array(
'Arnold Rimmer' => array(
'Chair' => new DibiRow(array('title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0))),
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0))),
),
'Dave Lister' => array(
'Table' => new DibiRow(array('title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0))),
),
'Kristine Kochanski' => array(
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0))),
),
), query($conn)->fetchAssoc('name,title'));
Assert::equal(array(
'Arnold Rimmer' => array(
array(
'Chair' => new DibiRow(array('title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0))),
),
array(
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0))),
),
),
'Dave Lister' => array(
array(
'Table' => new DibiRow(array('title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0))),
),
),
'Kristine Kochanski' => array(
array(
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0))),
),
),
), query($conn)->fetchAssoc('name,#,title'));
Assert::equal(array(
'Arnold Rimmer' => array(
'title' => array(
'Chair' => new DibiRow(array('title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0))),
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0))),
),
'name' => 'Arnold Rimmer',
'amount' => num(7.0),
),
'Dave Lister' => array(
'title' => array(
'Table' => new DibiRow(array('title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0))),
),
'name' => 'Dave Lister',
'amount' => num(3.0),
),
'Kristine Kochanski' => array(
'title' => array(
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0))),
),
'name' => 'Kristine Kochanski',
'amount' => num(5.0),
),
), query($conn)->fetchAssoc('name,=,title'));
Assert::equal(array(
'Arnold Rimmer' => new DibiRow(array(
'title' => array(
'Chair' => new DibiRow(array('title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0))),
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0))),
),
'name' => 'Arnold Rimmer',
'amount' => num(7.0),
)),
'Dave Lister' => new DibiRow(array(
'title' => array(
'Table' => new DibiRow(array('title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0))),
),
'name' => 'Dave Lister',
'amount' => num(3.0),
)),
'Kristine Kochanski' => new DibiRow(array(
'title' => array(
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0))),
),
'name' => 'Kristine Kochanski',
'amount' => num(5.0),
)),
), query($conn)->fetchAssoc('name,@,title'));
Assert::equal(array(
new DibiRow(array('title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0))),
new DibiRow(array(
'title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0))),
new DibiRow(array(
'title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0))),
new DibiRow(array(
'title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0))),
), query($conn)->fetchAssoc('@,='));
Assert::equal(array(
'Arnold Rimmer' => array(
'title' => array(
'Chair' => new DibiRow(array('title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0))),
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0))),
),
'name' => 'Arnold Rimmer',
'amount' => num(7.0),
),
'Dave Lister' => array(
'title' => array(
'Table' => new DibiRow(array('title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0))),
),
'name' => 'Dave Lister',
'amount' => num(3.0),
),
'Kristine Kochanski' => array(
'title' => array(
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0))),
),
'name' => 'Kristine Kochanski',
'amount' => num(5.0),
),
), query($conn)->fetchAssoc('name,=,title,@'));
// old syntax
Assert::equal(array(
'Arnold Rimmer' => array(
'Chair' => new DibiRow(array('title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0))),
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0))),
),
'Dave Lister' => array(
'Table' => new DibiRow(array('title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0))),
),
'Kristine Kochanski' => array(
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0))),
),
), query($conn)->fetchAssoc('name|title'));
Assert::equal(array(
'Arnold Rimmer' => array(
array(
'Chair' => new DibiRow(array('title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0))),
),
array(
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0))),
),
),
'Dave Lister' => array(
array(
'Table' => new DibiRow(array('title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0))),
),
),
'Kristine Kochanski' => array(
array(
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0))),
),
),
), query($conn)->fetchAssoc('name[]title'));
Assert::equal(array(
'Arnold Rimmer' => new DibiRow(array(
'title' => array(
'Chair' => new DibiRow(array('title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0))),
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0))),
),
'name' => 'Arnold Rimmer',
'amount' => num(7.0),
)),
'Dave Lister' => new DibiRow(array(
'title' => array(
'Table' => new DibiRow(array('title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0))),
),
'name' => 'Dave Lister',
'amount' => num(3.0),
)),
'Kristine Kochanski' => new DibiRow(array(
'title' => array(
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0))),
),
'name' => 'Kristine Kochanski',
'amount' => num(5.0),
)),
), query($conn)->fetchAssoc('name->title'));
Assert::equal(array(
'Arnold Rimmer' => new DibiRow(array(
'title' => array('Chair' => 'Arnold Rimmer', 'Computer' => 'Arnold Rimmer'),
'name' => 'Arnold Rimmer',
'amount' => num(7.0),
)),
'Dave Lister' => new DibiRow(array(
'title' => array('Table' => 'Dave Lister'),
'name' => 'Dave Lister',
'amount' => num(3.0),
)),
'Kristine Kochanski' => new DibiRow(array(
'title' => array('Computer' => 'Kristine Kochanski'),
'name' => 'Kristine Kochanski',
'amount' => num(5.0),
)),
), query($conn)->fetchAssoc('name->title=name'));
Assert::equal(array(
new DibiRow(array('title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0))),
new DibiRow(array('title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0))),
new DibiRow(array('title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0))),
new DibiRow(array('title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0))),
), query($conn)->fetchAssoc('[]'));
Assert::equal(array(
'Arnold Rimmer' => new DibiRow(array(
'title' => array(
'Chair' => new DibiRow(array('title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0))),
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0))),
),
'name' => 'Arnold Rimmer',
'amount' => num(7.0),
)),
'Dave Lister' => new DibiRow(array(
'title' => array(
'Table' => new DibiRow(array('title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0))),
),
'name' => 'Dave Lister',
'amount' => num(3.0),
)),
'Kristine Kochanski' => new DibiRow(array(
'title' => array(
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0))),
),
'name' => 'Kristine Kochanski',
'amount' => num(5.0),
)),
), query($conn)->fetchAssoc('name->title->'));

View File

@@ -0,0 +1,26 @@
<?php
use Tester\Assert;
require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config);
// create new substitution :blog: ==> wp_
$conn->getSubstitutes()->blog = 'wp_';
Assert::same(
reformat('UPDATE wp_items SET [text]=\'Hello World\''),
$conn->translate("UPDATE :blog:items SET [text]='Hello World'")
);
Assert::same(
reformat('UPDATE \'wp_\' SET [text]=\'Hello World\''),
$conn->translate("UPDATE :blog: SET [text]='Hello World'")
);
Assert::same(
reformat('UPDATE \':blg:\' SET [text]=\'Hello World\''),
$conn->translate("UPDATE :blg: SET [text]='Hello World'")
);

View File

@@ -0,0 +1,48 @@
<?php
/**
* @dataProvider ../databases.ini
*/
use Tester\Assert;
require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql");
/*Assert::exception(function() use ($conn) {
$conn->rollback();
}, 'DibiException');
Assert::exception(function() use ($conn) {
$conn->commit();
}, 'DibiException');
$conn->begin();
Assert::exception(function() use ($conn) {
$conn->begin();
}, 'DibiException');
*/
$conn->begin();
Assert::same(3, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());
$conn->query('INSERT INTO [products]', array(
'title' => 'Test product',
));
Assert::same(4, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());
$conn->rollback();
Assert::same(3, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());
$conn->begin();
$conn->query('INSERT INTO [products]', array(
'title' => 'Test product',
));
$conn->commit();
Assert::same(4, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());

View File

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

View File

@@ -0,0 +1,45 @@
<?php
use Tester\Assert;
require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config);
$fluent = $conn->delete('table')->as('bAlias')
->setFlag('IGNORE');
Assert::same(
reformat('DELETE IGNORE FROM [table] AS [bAlias]'),
(string) $fluent
);
$fluent->removeClause('from')->from('anotherTable');
Assert::same(
reformat('DELETE IGNORE FROM [anotherTable]'),
(string) $fluent
);
$fluent->using('thirdTable');
Assert::same(
reformat('DELETE IGNORE FROM [anotherTable] USING [thirdTable]'),
(string) $fluent
);
$fluent->setFlag('IGNORE', FALSE);
Assert::same(
reformat('DELETE FROM [anotherTable] USING [thirdTable]'),
(string) $fluent
);
$fluent->limit(10);
Assert::same(
reformat('DELETE FROM [anotherTable] USING [thirdTable] LIMIT 10'),
(string) $fluent
);

View File

@@ -0,0 +1,59 @@
<?php
/**
* @dataProvider ../databases.ini
*/
use Tester\Assert;
require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql");
function num($n)
{
global $config;
if (substr(@$config['dsn'], 0, 5) === 'odbc:' || $config['driver'] === 'sqlite') {
$n = is_float($n) ? "$n.0" : (string) $n;
}
return $n;
}
// fetch a single value
$res = $conn->select('title')->from('products')->orderBy('product_id');
Assert::equal('Chair', $res->fetchSingle());
// fetch complete result set
$res = $conn->select('*')->from('products')->orderBy('product_id');
Assert::equal(array(
new DibiRow(array('product_id' => num(1), 'title' => 'Chair')),
new DibiRow(array('product_id' => num(2), 'title' => 'Table')),
new DibiRow(array('product_id' => num(3), 'title' => 'Computer')),
), $res->fetchAll());
// more complex association array
if ($config['system'] !== 'odbc') {
$res = $conn->select(array('products.title' => 'title', 'customers.name' => 'name'))->select('orders.amount')->as('amount')
->from('products')
->innerJoin('orders')->using('(product_id)')
->innerJoin('customers')->using('([customer_id])')
->orderBy('order_id');
Assert::equal(array(
'Arnold Rimmer' => array(
'Chair' => new DibiRow(array('title' => 'Chair', 'name' => 'Arnold Rimmer', 'amount' => num(7.0))),
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Arnold Rimmer', 'amount' => num(2.0))),
),
'Dave Lister' => array(
'Table' => new DibiRow(array('title' => 'Table', 'name' => 'Dave Lister', 'amount' => num(3.0))),
),
'Kristine Kochanski' => array(
'Computer' => new DibiRow(array('title' => 'Computer', 'name' => 'Kristine Kochanski', 'amount' => num(5.0))),
),
), $res->fetchAssoc('name,title'));
}

View File

@@ -0,0 +1,58 @@
<?php
use Tester\Assert;
require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config);
$arr = array(
'title' => 'Super Product',
'price' => 12,
'brand' => NULL,
);
$fluent = $conn->insert('table', $arr)
->setFlag('IGNORE')->setFlag('DELAYED');
Assert::same(
reformat('INSERT IGNORE DELAYED INTO [table] ([title], [price], [brand]) VALUES (\'Super Product\', 12, NULL)'),
(string) $fluent
);
$fluent->setFlag('IGNORE', FALSE);
Assert::same(
reformat('INSERT DELAYED INTO [table] ([title], [price], [brand]) VALUES (\'Super Product\', 12, NULL)'),
(string) $fluent
);
$fluent->setFlag('HIGH_priority');
Assert::same(
reformat('INSERT DELAYED HIGH_PRIORITY INTO [table] ([title], [price], [brand]) VALUES (\'Super Product\', 12, NULL)'),
(string) $fluent
);
$fluent->into('anotherTable');
Assert::same(
reformat('INSERT DELAYED HIGH_PRIORITY INTO [anotherTable] VALUES (\'Super Product\', 12, NULL)'),
(string) $fluent
);
$fluent->values('%l', $arr);
Assert::same(
reformat('INSERT DELAYED HIGH_PRIORITY INTO [anotherTable] VALUES (\'Super Product\', 12, NULL) , (\'Super Product\', 12, NULL)'),
(string) $fluent
);
$fluent->values($arr);
Assert::same(
reformat('INSERT DELAYED HIGH_PRIORITY INTO [anotherTable] VALUES (\'Super Product\', 12, NULL) , (\'Super Product\', 12, NULL) , (\'Super Product\', 12, NULL)'),
(string) $fluent
);

View File

@@ -0,0 +1,139 @@
<?php
use Tester\Assert;
require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config);
$max = 10;
$min = 5;
$fluent = $conn->select('*')
->select('a')
->select('b')->as('bAlias')
->select(array('c', 'd', 'e'))
->select('%n', 'd');
Assert::same(
reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d]'),
(string) $fluent
);
$fluent->from('table')->as('tableAlias')
->innerJoin('table1')->on('table.col = table1.col')
->innerJoin('table2')->on('table.col = table2.col');
Assert::same(
reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d] FROM [table] AS [tableAlias] INNER JOIN [table1] ON table.col = table1.col INNER JOIN [table2] ON table.col = table2.col'),
(string) $fluent
);
$fluent->from('anotherTable');
Assert::same(
reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d] FROM [table] AS [tableAlias] INNER JOIN [table1] ON table.col = table1.col INNER JOIN [table2] ON table.col = table2.col , [anotherTable]'),
(string) $fluent
);
$fluent->removeClause('from')->from('anotherTable');
Assert::same(
reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d] FROM [anotherTable]'),
(string) $fluent
);
$fluent->as('anotherAlias')
->clause('from')
->innerJoin('table3')
->on('table.col = table3.col');
Assert::same(
reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d] FROM [anotherTable] AS [anotherAlias] INNER JOIN [table3] ON table.col = table3.col'),
(string) $fluent
);
$fluent->where('col > %i', $max)
->or('col < %i', $min)
->where('active = 1')
->where('col')->in(array(1,2,3))
->orderBy('val')->asc()
->orderBy('[val2] DESC')
->orderBy(array('val3' => -1));
Assert::same(
reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d] FROM [anotherTable] AS [anotherAlias] INNER JOIN [table3] ON table.col = table3.col WHERE col > 10 OR col < 5 AND active = 1 AND [col] IN (1, 2, 3) ORDER BY [val] ASC , [val2] DESC , [val3] DESC'),
(string) $fluent
);
$fluent->orderBy(DibiFluent::REMOVE);
Assert::same(
reformat('SELECT * , [a] , [b] AS [bAlias] , [c], [d], [e] , [d] FROM [anotherTable] AS [anotherAlias] INNER JOIN [table3] ON table.col = table3.col WHERE col > 10 OR col < 5 AND active = 1 AND [col] IN (1, 2, 3)'),
(string) $fluent
);
try {
$fluent = $conn->select('*')->from('table')->fetch();
} catch (Exception $e) {
}
Assert::same(
reformat(' SELECT * FROM [table] LIMIT 1'),
dibi::$sql
);
$fluent = $conn->select('*')
->select(
$conn->select('count(*)')
->from('precteni')->as('P')
->where('P.id_clanku', '=', 'C.id_clanku')
)
->from('clanky')->as('C')
->where('id_clanku=%i', 123)
->limit(1)
->offset(0);
Assert::same(
reformat('SELECT * , (SELECT count(*) FROM [precteni] AS [P] WHERE P.id_clanku = C.id_clanku) FROM [clanky] AS [C] WHERE id_clanku=123 LIMIT 1 OFFSET 0'),
(string) $fluent
);
$fluent = $conn->select('*')
->select(array('x' => 'xAlias'))
->from('products')
->innerJoin('orders')->using('(product_id)')
->innerJoin('customers')->using('([customer_id])')
->innerJoin('items')->using('(%n)', array('customer_id', 'order_id'));
Assert::same(
reformat('SELECT * , [x] AS [xAlias] FROM [products] INNER JOIN [orders] USING (product_id) INNER JOIN [customers] USING ([customer_id]) INNER JOIN [items] USING ([customer_id], [order_id])'),
(string) $fluent
);
$fluent = $conn->command()->select()
->from('products')
->select('*')
->innerJoin('orders')->using('(product_id)');
Assert::same(
reformat('SELECT * FROM [products] INNER JOIN [orders] USING (product_id)'),
(string) $fluent
);
$fluent = $conn->select('*')
->from(array('me' => 't'))
->where('col > %i', $max)
->where(array('x' => 'a', 'b', 'c'));
Assert::same(
reformat('SELECT * FROM [me] AS [t] WHERE col > 10 AND ([x] = \'a\') AND (b) AND (c)'),
(string) $fluent
);

View File

@@ -0,0 +1,30 @@
<?php
use Tester\Assert;
require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config);
$arr = array(
'title' => 'Super Product',
'price' => 12,
'brand' => NULL,
);
$fluent = $conn->update('table', $arr)
->setFlag('IGNORE')->setFlag('DELAYED');
Assert::same(
reformat('UPDATE IGNORE DELAYED [table] SET [title]=\'Super Product\', [price]=12, [brand]=NULL'),
(string) $fluent
);
$fluent->set(array('another' => 123));
Assert::same(
reformat('UPDATE IGNORE DELAYED [table] SET [title]=\'Super Product\', [price]=12, [brand]=NULL , [another]=123'),
(string) $fluent
);

View File

@@ -0,0 +1,57 @@
<?php
/**
* @dataProvider ../databases.ini
*/
use Tester\Assert;
require __DIR__ . '/bootstrap.php';
if ($config['system'] === 'odbc') {
Tester\Environment::skip('Not supported.');
}
$conn = new DibiConnection($config);
$conn->loadFile(__DIR__ . "/data/$config[system].sql");
$info = $conn->query('
SELECT products.product_id, orders.order_id, customers.name, products.product_id + 1 AS xxx
FROM products
INNER JOIN orders USING (product_id)
INNER JOIN customers USING (customer_id)
')->getInfo();
Assert::same(
array('product_id', 'order_id', 'name', 'xxx'),
$info->getColumnNames()
);
if ($config['driver'] !== 'sqlite3' && $config['driver'] !== 'pdo') {
Assert::same(
array('products.product_id', 'orders.order_id', 'customers.name', 'xxx'),
$info->getColumnNames(TRUE)
);
}
$columns = $info->getColumns();
Assert::same('product_id', $columns[0]->name);
if ($config['driver'] !== 'sqlite3' && $config['driver'] !== 'pdo') {
Assert::same('products', $columns[0]->tableName);
}
Assert::null($columns[0]->getVendorInfo('xxx'));
if ($config['system'] !== 'sqlite') {
Assert::same('i', $columns[0]->type);
}
Assert::null($columns[0]->nullable);
Assert::same('xxx', $columns[3]->name);
Assert::null($columns[3]->tableName);
if ($config['system'] !== 'sqlite') {
Assert::same('i', $columns[0]->type);
}
Assert::null($columns[3]->nullable);

View File

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

View File

@@ -0,0 +1,17 @@
<?php
/**
* @phpversion 5.5
*/
use Tester\Assert;
require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config);
$translator = new DibiTranslator($conn);
$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));

View File

@@ -0,0 +1,88 @@
<?php
/**
* @dataProvider ../databases.ini
*/
use Tester\Assert;
require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config);
// if & end
Assert::same(
reformat("
SELECT *
FROM [customers]
/* WHERE ... LIKE ... */"),
$conn->translate('
SELECT *
FROM [customers]
%if', isset($name), 'WHERE [name] LIKE %s', 'xxx', '%end'
));
// if & else & end (last end is optional)
Assert::same(
reformat("
SELECT *
FROM [customers] /* ... */"),
$conn->translate('
SELECT *
FROM %if', TRUE, '[customers] %else [products]'
));
// if & else & (optional) end
Assert::match(
reformat("
SELECT *
FROM [people]
WHERE [id] > 0
/* AND ...=...
*/ AND [bar]=1
"),
$conn->translate("
SELECT *
FROM [people]
WHERE [id] > 0
%if", FALSE, "AND [foo]=%i", 1, "
%else %if", TRUE, "AND [bar]=%i", 1, "
"));
// nested condition
Assert::match(
reformat("
SELECT *
FROM [customers]
WHERE
[name] LIKE 'xxx'
/* AND ...=1 */
/* 1 LIMIT 10 */"),
$conn->translate('
SELECT *
FROM [customers]
WHERE
%if', TRUE, '[name] LIKE %s', 'xxx', '
%if', FALSE, 'AND [admin]=1 %end
%else 1 LIMIT 10 %end'
));
// limit & offset
Assert::same(
'SELECT * FROM foo /* (limit 3) (offset 5) */',
$conn->translate(
'SELECT * FROM foo',
'%if', FALSE,
'%lmt', 3,
'%ofs', 5,
'%end'
));

View File

@@ -0,0 +1,47 @@
<?php
/**
* @dataProvider ../databases.ini
*/
use Tester\Assert;
require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config);
Assert::same(
reformat('SELECT * FROM where WHERE select < 2'),
$conn->translate('SELECT * FROM where WHERE select < 2')
);
Assert::same(
reformat('SELECT * FROM [where] WHERE where.select < 2'),
$conn->translate('SELECT * FROM [where] WHERE where.select < 2')
);
Assert::same(
reformat('SELECT * FROM [where] WHERE [where].[select] < 2'),
$conn->translate('SELECT * FROM [where] WHERE [where.select] < 2')
);
Assert::same(
reformat('SELECT * FROM [where] as [temp] WHERE [temp].[select] < 2'),
$conn->translate('SELECT * FROM [where] as [temp] WHERE [temp.select] < 2')
);
Assert::same(
reformat('SELECT * FROM [where] WHERE [quot\'n\' space] > 2'),
$conn->translate("SELECT * FROM [where] WHERE [quot'n' space] > 2")
);
Assert::same(
reformat('SELECT * FROM [where] WHERE [where].[quot\'n\' space] > 2'),
$conn->translate("SELECT * FROM [where] WHERE [where.quot'n' space] > 2")
);

View File

@@ -0,0 +1,531 @@
<?php
/**
* @dataProvider ../databases.ini
*/
use Tester\Assert;
require __DIR__ . '/bootstrap.php';
$conn = new DibiConnection($config + array('formatDateTime' => "'Y-m-d H:i:s'", 'formatDate' => "'Y-m-d'"));
// dibi detects INSERT or REPLACE command & booleans
Assert::same(
reformat("REPLACE INTO [products] ([title], [price]) VALUES ('Drticka', 318)"),
$conn->translate('REPLACE INTO [products]', array(
'title' => 'Drticka',
'price' => 318,
)));
// multiple INSERT command
$array = array(
'title' => 'Super Product',
'price' => 12,
'brand' => NULL,
);
Assert::same(
reformat('INSERT INTO [products] ([title], [price], [brand]) VALUES (\'Super Product\', 12, NULL) , (\'Super Product\', 12, NULL) , (\'Super Product\', 12, NULL)'),
$conn->translate("INSERT INTO [products]", $array, $array, $array)
);
// multiple INSERT command II
$array = array(
array('pole' => 'hodnota1', 'bit' => 1),
array('pole' => 'hodnota2', 'bit' => 1),
array('pole' => 'hodnota3', 'bit' => 1)
);
Assert::same(
reformat('INSERT INTO [products] ([pole], [bit]) VALUES (\'hodnota1\', 1) , (\'hodnota2\', 1) , (\'hodnota3\', 1)'),
$conn->translate("INSERT INTO [products] %ex", $array)
);
// dibi detects UPDATE command
Assert::same(
reformat("UPDATE [colors] SET [color]='blue', [order]=12 WHERE [id]=123"),
$conn->translate('UPDATE [colors] SET', array(
'color' => 'blue',
'order' => 12,
), "WHERE [id]=%i", 123));
// IN array
$array = array(1, 2, 3);
Assert::same(
reformat('SELECT * FROM [people] WHERE [id] IN ( 1, 2, 3 )'),
$conn->translate("SELECT * FROM [people] WHERE [id] IN (", $array, ")")
);
// long numbers
Assert::same(
reformat('SELECT -123456789123456789123456789'),
$conn->translate("SELECT %i", '-123456789123456789123456789')
);
// long float numbers
Assert::same(
reformat('SELECT -.12345678912345678912345678e10'),
$conn->translate("SELECT %f", '-.12345678912345678912345678e10')
);
// hex numbers
Assert::same(
reformat('SELECT 17'),
$conn->translate("SELECT %i", '0x11')
);
// invalid input
$e = Assert::exception(function() use ($conn) {
$conn->translate("SELECT %s", (object) array(123), ', %m', 123);
}, 'DibiException', 'SQL translate error');
Assert::same('SELECT **Unexpected type object** , **Unknown or invalid modifier %m**', $e->getSql());
Assert::same(
reformat('SELECT * FROM [table] WHERE id=10 AND name=\'ahoj\''),
$conn->translate('SELECT * FROM [table] WHERE id=%i AND name=%s', 10, 'ahoj')
);
Assert::same(
reformat('TEST ([cond] > 2) OR ([cond2] = \'3\') OR (cond3 < RAND())'),
$conn->translate('TEST %or', array('[cond] > 2', '[cond2] = "3"', 'cond3 < RAND()'))
);
Assert::same(
reformat('TEST ([cond] > 2) AND ([cond2] = \'3\') AND (cond3 < RAND())'),
$conn->translate('TEST %and', array('[cond] > 2', '[cond2] = "3"', 'cond3 < RAND()'))
);
//
$where = array();
$where[] = '[age] > 20';
$where[] = '[email] IS NOT NULL';
Assert::same(
reformat('SELECT * FROM [table] WHERE ([age] > 20) AND ([email] IS NOT NULL)'),
$conn->translate('SELECT * FROM [table] WHERE %and', $where)
);
$where = array();
$where['age'] = NULL;
$where['email'] = 'ahoj';
$where['id%l'] = array(10, 20, 30);
Assert::same(
reformat('SELECT * FROM [table] WHERE ([age] IS NULL) AND ([email] = \'ahoj\') AND ([id] IN (10, 20, 30))'),
$conn->translate('SELECT * FROM [table] WHERE %and', $where)
);
$where = array();
Assert::same(
reformat('SELECT * FROM [table] WHERE 1=1'),
$conn->translate('SELECT * FROM [table] WHERE %and', $where)
);
// ORDER BY array
$order = array(
'field1' => 'asc',
'field2' => 'desc',
'field3' => 1,
'field4' => -1,
'field5' => TRUE,
'field6' => FALSE,
);
Assert::same(
reformat("SELECT * FROM [people] ORDER BY [field1] ASC, [field2] DESC, [field3] ASC, [field4] DESC, [field5] ASC, [field6] DESC"),
$conn->translate("SELECT * FROM [people] ORDER BY %by", $order)
);
// with limit = 2
Assert::same(
reformat(array(
'odbc' => 'SELECT TOP 2 * FROM (SELECT * FROM [products] ) t',
'SELECT * FROM [products] LIMIT 2',
)),
$conn->translate('SELECT * FROM [products] %lmt', 2)
);
if ($config['system'] === 'odbc') {
Assert::exception(function() use ($conn) {
$conn->translate('SELECT * FROM [products] %lmt %ofs', 2, 1);
}, 'DibiException');
} else {
// with limit = 2, offset = 1
Assert::same(
reformat('SELECT * FROM [products] LIMIT 2 OFFSET 1'),
$conn->translate('SELECT * FROM [products] %lmt %ofs', 2, 1)
);
// with offset = 50
Assert::same(
reformat(array(
'mysql' => 'SELECT * FROM `products` LIMIT 18446744073709551615 OFFSET 50',
'pgsql' => 'SELECT * FROM "products" OFFSET 50',
'SELECT * FROM [products] LIMIT -1 OFFSET 50',
)),
$conn->translate('SELECT * FROM [products] %ofs', 50)
);
}
Assert::same(
reformat(array(
'odbc' => 'INSERT INTO test ([a2], [a4], [b1], [b2], [b3], [b4], [b5], [b6], [b7], [b8], [b9]) VALUES (#09/26/1212 00:00:00#, #12/31/1969 22:13:20#, #09/26/1212#, #09/26/1212 00:00:00#, #12/31/1969#, #12/31/1969 22:13:20#, #09/26/1212 00:00:00#, #09/26/1212#, #09/26/1212 00:00:00#, NULL, NULL)',
"INSERT INTO test ([a2], [a4], [b1], [b2], [b3], [b4], [b5], [b6], [b7], [b8], [b9]) VALUES ('1212-09-26 00:00:00', '1969-12-31 22:13:20', '1212-09-26', '1212-09-26 00:00:00', '1969-12-31', '1969-12-31 22:13:20', '1212-09-26 00:00:00', '1212-09-26', '1212-09-26 00:00:00', NULL, NULL)",
)),
$conn->translate("INSERT INTO test", array(
'a2' => new DibiDateTime('1212-09-26'),
'a4' => new DibiDateTime(-10000),
'b1%d' => '1212-09-26',
'b2%t' => '1212-09-26',
'b3%d' => -10000,
'b4%t' => -10000,
'b5' => new DateTime('1212-09-26'),
'b6%d' => new DateTime('1212-09-26'),
'b7%t' => new DateTime('1212-09-26'),
'b8%d' => NULL,
'b9%t' => NULL,
)));
// like
$args = array(
"SELECT * FROM products WHERE (title LIKE %like~ AND title LIKE %~like) OR title LIKE %~like~",
'C',
'r',
"a\n%_\\'\""
);
if ($config['system'] === 'pgsql') {
$conn->query('SET escape_string_warning = off'); // do not log warnings
$conn->query('SET standard_conforming_strings = off');
Assert::same(
"SELECT * FROM products WHERE (title LIKE 'C%' AND title LIKE '%r') OR title LIKE '%a\n\\\\%\\\\_\\\\\\\\''\"%'",
$conn->translate($args[0], $args[1], $args[2], $args[3])
);
$conn->query('SET standard_conforming_strings = on');
Assert::same(
"SELECT * FROM products WHERE (title LIKE 'C%' AND title LIKE '%r') OR title LIKE '%a\n\\%\\_\\\\''\"%'",
$conn->translate($args[0], $args[1], $args[2], $args[3])
);
} elseif ($config['driver'] !== 'sqlite') { // sqlite2
Assert::same(
reformat(array(
'sqlite' => "SELECT * FROM products WHERE (title LIKE 'C%' ESCAPE '\\' AND title LIKE '%r' ESCAPE '\\') OR title LIKE '%a\n\\%\\_\\\\''\"%' ESCAPE '\\'",
'odbc' => "SELECT * FROM products WHERE (title LIKE 'C%' AND title LIKE '%r') OR title LIKE '%a\n[%][_]\\''\"%'",
"SELECT * FROM products WHERE (title LIKE 'C%' AND title LIKE '%r') OR title LIKE '%a\\n\\%\\_\\\\\\\\\'\"%'",
)),
$conn->translate($args[0], $args[1], $args[2], $args[3])
);
}
$e = Assert::exception(function() use ($conn) {
$conn->translate("SELECT '");
}, 'DibiException', 'SQL translate error');
Assert::same('SELECT **Alone quote**', $e->getSql());
Assert::match(
reformat(array(
'mysql' => "SELECT DISTINCT HIGH_PRIORITY SQL_BUFFER_RESULT
CONCAT(last_name, ', ', first_name) AS full_name
GROUP BY `user`
HAVING MAX(salary) > %i 123
INTO OUTFILE '/tmp/result\'.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\\\"'
LINES TERMINATED BY '\\\\n'
",
"SELECT DISTINCT HIGH_PRIORITY SQL_BUFFER_RESULT
CONCAT(last_name, ', ', first_name) AS full_name
GROUP BY [user]
HAVING MAX(salary) > %i 123
INTO OUTFILE '/tmp/result''.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\\n'
"
)),
$conn->translate('%sql', "SELECT DISTINCT HIGH_PRIORITY SQL_BUFFER_RESULT
CONCAT(last_name, \", \", first_name) AS full_name
GROUP BY [user]
HAVING MAX(salary) > %i", 123, "
INTO OUTFILE '/tmp/result''.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\\n'
")
);
$array1 = array(1, 2, 3);
$array2 = array('one', 'two', 'three');
$array3 = array(
'col1' => 'one',
'col2' => 'two',
'col3' => 'three',
);
$array4 = array(
'a' => 12,
'b' => NULL,
'c' => new DibiDateTime('12.3.2007'),
'd' => 'any string',
);
$array5 = array('RAND()', '[col1] > [col2]');
Assert::match(
reformat(array(
'mysql' => "SELECT *
FROM `db`.`table`
WHERE (`test`.`a` LIKE '1995-03-01'
OR `b1` IN ( 1, 2, 3 )
OR `b2` IN ('1', '2', '3' )
OR `b3` IN ( )
OR `b4` IN ( 'one', 'two', 'three' )
OR `b5` IN (`col1` AS `one`, `col2` AS `two`, `col3` AS `three` )
OR `b6` IN ('one', 'two', 'three')
OR `b7` IN (NULL)
OR `b8` IN (RAND() `col1` > `col2` )
OR `b9` IN ( )
AND `c` = 'embedded \' string'
OR `d`=10
OR `e`=NULL
OR `true`= 1
OR `false`= 0
OR `str_null`=NULL
OR `str_not_null`='hello'
LIMIT 10",
'pgsql' => 'SELECT *
FROM "db"."table"
WHERE ("test"."a" LIKE \'1995-03-01\'
OR "b1" IN ( 1, 2, 3 )
OR "b2" IN (\'1\', \'2\', \'3\' )
OR "b3" IN ( )
OR "b4" IN ( \'one\', \'two\', \'three\' )
OR "b5" IN ("col1" AS "one", "col2" AS "two", "col3" AS "three" )
OR "b6" IN (\'one\', \'two\', \'three\')
OR "b7" IN (NULL)
OR "b8" IN (RAND() "col1" > "col2" )
OR "b9" IN ( )
AND "c" = \'embedded \'\' string\'
OR "d"=10
OR "e"=NULL
OR "true"= TRUE
OR "false"= FALSE
OR "str_null"=NULL
OR "str_not_null"=\'hello\'
LIMIT 10',
'odbc' => "SELECT *
FROM [db].[table]
WHERE ([test].[a] LIKE #03/01/1995#
OR [b1] IN ( 1, 2, 3 )
OR [b2] IN ('1', '2', '3' )
OR [b3] IN ( )
OR [b4] IN ( 'one', 'two', 'three' )
OR [b5] IN ([col1] AS [one], [col2] AS [two], [col3] AS [three] )
OR [b6] IN ('one', 'two', 'three')
OR [b7] IN (NULL)
OR [b8] IN (RAND() [col1] > [col2] )
OR [b9] IN ( )
AND [c] = 'embedded '' string'
OR [d]=10
OR [e]=NULL
OR [true]= 1
OR [false]= 0
OR [str_null]=NULL
OR [str_not_null]='hello'
LIMIT 10",
"SELECT *
FROM [db].[table]
WHERE ([test].[a] LIKE '1995-03-01'
OR [b1] IN ( 1, 2, 3 )
OR [b2] IN ('1', '2', '3' )
OR [b3] IN ( )
OR [b4] IN ( 'one', 'two', 'three' )
OR [b5] IN ([col1] AS [one], [col2] AS [two], [col3] AS [three] )
OR [b6] IN ('one', 'two', 'three')
OR [b7] IN (NULL)
OR [b8] IN (RAND() [col1] > [col2] )
OR [b9] IN ( )
AND [c] = 'embedded '' string'
OR [d]=10
OR [e]=NULL
OR [true]= 1
OR [false]= 0
OR [str_null]=NULL
OR [str_not_null]='hello'
LIMIT 10",
)),
$conn->translate("SELECT *
FROM [db.table]
WHERE ([test.a] LIKE %d", '1995-03-01', "
OR [b1] IN (", $array1, ")
OR [b2] IN (%s", $array1, ")
OR [b3] IN (%s", array(), ")
OR [b4] IN (", $array2, ")
OR [b5] IN (%n", $array3, ")
OR [b6] IN %l", $array3, "
OR [b7] IN %in", array(), "
OR [b8] IN (%sql", $array5, ")
OR [b9] IN (", array(), ")
AND [c] = 'embedded '' string'
OR [d]=%i", 10.3, "
OR [e]=%i", NULL, "
OR [true]=", TRUE, "
OR [false]=", FALSE, "
OR [str_null]=%sn", '', "
OR [str_not_null]=%sn", 'hello', "
LIMIT 10")
);
Assert::same(
reformat('TEST [cond] > 2 [cond2] = \'3\' cond3 < RAND() 123'),
$conn->translate('TEST %ex', array('[cond] > 2', '[cond2] = "3"', 'cond3 < RAND()'), 123)
);
Assert::same(
reformat('TEST ([cond] > 2) OR ([cond2] > 3) OR ([cond3] = 10 + 1)'),
$conn->translate('TEST %or', array('`cond` > 2', array('[cond2] > %i', '3'), 'cond3%sql' => array('10 + 1')))
);
Assert::same(
reformat('TEST ([cond] = 2) OR ([cond3] = RAND())'),
$conn->translate('TEST %or', array('cond' => 2, 'cond3%sql' => 'RAND()'))
);
Assert::same(
reformat('TEST ([cond1] 3) OR ([cond2] RAND()) OR ([cond3] LIKE \'string\')'),
$conn->translate('TEST %or', array('cond1%ex' => 3, 'cond2%ex' => 'RAND()', 'cond3%ex' => array('LIKE %s', 'string')))
);
Assert::same(
reformat(array(
'odbc' => 'SELECT TOP 10 * FROM (SELECT * FROM [test] WHERE [id] LIKE \'%d%t\' ) t',
'SELECT * FROM [test] WHERE [id] LIKE \'%d%t\' LIMIT 10',
)),
$conn->translate("SELECT * FROM [test] WHERE %n LIKE '%d%t' %lmt", 'id', 10)
);
$where = array(
'tablename.column' => 1,
);
Assert::same(
reformat('SELECT * FROM [tablename] WHERE ([tablename].[column] = 1)'),
$conn->translate('SELECT * FROM [tablename] WHERE %and', $where)
);
Assert::same(
reformat('SELECT FROM ... '),
$conn->translate('SELECT FROM ... %lmt', NULL)
);
Assert::same(
reformat('SELECT \'%i\''),
$conn->translate("SELECT '%i'")
);
Assert::same(
reformat('SELECT \'%i\''),
$conn->translate('SELECT "%i"')
);
Assert::same(
reformat('INSERT INTO [products] ([product_id], [title]) VALUES (1, SHA1(\'Test product\')) , (1, SHA1(\'Test product\'))'),
$conn->translate('INSERT INTO [products]', array(
'product_id' => 1,
'title' => array('SHA1(%s)', 'Test product'),
), array(
'product_id' => 1,
'title' => array('SHA1(%s)', 'Test product'),
))
);
Assert::same(
reformat('UPDATE [products] [product_id]=1, [title]=SHA1(\'Test product\')'),
$conn->translate('UPDATE [products]', array(
'product_id' => 1,
'title' => array('SHA1(%s)', 'Test product'),
))
);
$e = Assert::exception(function() use ($conn) {
$array6 = array(
'id' => array(1, 2, 3, 4),
'text' => array('ahoj', 'jak', 'se', array('SUM(%i)', '5')),
'num%i' => array('1', ''),
);
$conn->translate('INSERT INTO test %m', $array6);
}, 'DibiException', 'SQL translate error');
Assert::same('INSERT INTO test **Multi-insert array "num%i" is different.**', $e->getSql());
$array6 = array(
'id' => array(1, 2, 3, 4),
'text' => array('ahoj', 'jak', 'se', array('SUM(%i)', '5')),
'num%i' => array('1', '', 10.3, 1),
);
Assert::same(
reformat('INSERT INTO test ([id], [text], [num]) VALUES (1, \'ahoj\', 1), (2, \'jak\', 0), (3, \'se\', 10), (4, SUM(5), 1)'),
$conn->translate('INSERT INTO test %m', $array6)
);
$by = array (
array('funkce(nazev_pole) ASC'),
'jine_pole' => 'DESC'
);
Assert::same(
reformat('SELECT * FROM table ORDER BY funkce(nazev_pole) ASC, [jine_pole] DESC'),
$conn->translate("SELECT * FROM table ORDER BY %by", $by)
);
Assert::same(
reformat('INSERT INTO [test].*'),
$conn->translate('INSERT INTO [test.*]')
);
Assert::same(
reformat('INSERT INTO 0'),
$conn->translate('INSERT INTO %f', 'ahoj')
);
setLocale(LC_ALL, 'czech');
Assert::same(
reformat("UPDATE [colors] SET [color]='blue', [price]=-12.4, [spec]=-9E-005, [spec2]=1000, [spec3]=10000, [spec4]=10000 WHERE [price]=123.5"),
$conn->translate("UPDATE [colors] SET", array(
'color' => 'blue',
'price' => -12.4,
'spec%f' => '-9E-005',
'spec2%f' => 1000.00,
'spec3%i' => 10000,
'spec4' => 10000,
), "WHERE [price]=%f", 123.5)
);

View File

@@ -0,0 +1,34 @@
<?php
/**
* @dataProvider ../databases.ini
*/
use Tester\Assert;
require __DIR__ . '/bootstrap.php';
if ($config['system'] !== 'pgsql') {
Tester\Environment::skip("Not supported system '$config[system]'.");
}
$tests = function($conn) {
Assert::false($conn->query("SELECT 'AAxBB' LIKE %~like~", 'A_B')->fetchSingle());
Assert::true( $conn->query("SELECT 'AA_BB' LIKE %~like~", 'A_B')->fetchSingle());
Assert::false($conn->query("SELECT 'AAxBB' LIKE %~like~", 'A%B')->fetchSingle());
Assert::true( $conn->query("SELECT 'AA%BB' LIKE %~like~", 'A%B')->fetchSingle());
Assert::same('AA\\BB', $conn->query("SELECT 'AA\\BB'")->fetchSingle());
Assert::false($conn->query("SELECT 'AAxBB' LIKE %~like~", 'A\\B')->fetchSingle());
Assert::true( $conn->query("SELECT 'AA\\BB' LIKE %~like~", 'A\\B')->fetchSingle());
};
$conn = new DibiConnection($config);
$conn->query('SET escape_string_warning = off'); // do not log warnings
$conn->query('SET standard_conforming_strings = on');
$tests($conn);
$conn->query('SET standard_conforming_strings = off');
$tests($conn);

71
tests/dibi/bootstrap.php Normal file
View File

@@ -0,0 +1,71 @@
<?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 connection
try {
$config = Tester\Environment::loadData();
} catch (Exception $e) {
$config = parse_ini_file(__DIR__ . '/../databases.ini', TRUE);
$config = $config['sqlite3'];
}
// lock
define('TEMP_DIR', __DIR__ . '/../tmp');
@mkdir(TEMP_DIR); // @ - directory may already exist
Tester\Environment::lock($config['system'], TEMP_DIR);
// ODBC
if ($config['system'] === 'odbc') {
copy(__DIR__ . '/data/odbc.mdb', TEMP_DIR . '/odbc.mdb');
$config['dsn'] = str_replace('data/odbc.mdb', TEMP_DIR . '/odbc.mdb', $config['dsn']);
}
try {
new DibiConnection($config);
} catch (DibiNotSupportedException $e) {
Tester\Environment::skip($e->getMessage());
}
function test(\Closure $function)
{
$function();
}
/** Replaces [] with driver-specific quotes */
function reformat($s)
{
global $config;
if (is_array($s)) {
if (isset($s[$config['system']])) {
return $s[$config['system']];
}
$s = $s[0];
}
if ($config['system'] === 'mysql') {
return strtr($s, '[]', '``');
} elseif ($config['system'] === 'pgsql') {
return strtr($s, '[]', '""');
} elseif ($config['system'] === 'odbc' || $config['system'] === 'sqlite') {
return $s;
} else {
trigger_error("Unsupported driver $config[system]", E_USER_WARNING);
}
}

Some files were not shown because too many files have changed in this diff Show More