1
0
mirror of https://github.com/dg/dibi.git synced 2025-08-30 09:19:48 +02:00

Compare commits

...

13 Commits

Author SHA1 Message Date
David Grudl
2dc30747e5 released 2.0.2 2012-12-04 14:43:02 +01:00
David Grudl
23531a0f3d reflectors: table names are correctly escaped 2012-12-04 14:42:12 +01:00
David Grudl
22c6f2dfda DibiTranslator: number of decimal points changed to 10 2012-12-04 14:42:08 +01:00
David Grudl
f51ac0b67e fixed invalid escaping sequences in double quoted strings, used \z instead of $ 2012-12-04 14:42:08 +01:00
David Grudl
43f5e08296 DibiConnection: fixed loadFromFile() and loading file without semicolon [Closes #63] 2012-12-04 14:42:08 +01:00
David Grudl
997f5a98f8 released 2.0.1 stable 2012-03-30 22:45:37 +02:00
Jan Marek
e4b3cfb12c added composer.json 2012-03-30 22:44:38 +02:00
David Grudl
26082294b6 DibiTranslator: number of decimal points changed to 20 2012-03-30 22:44:38 +02:00
Miloslav Hůla
b3052b4ce2 DibiFirePhpLogger: Fix undefined property access 2012-03-30 22:44:38 +02:00
David Grudl
efa3a48232 numOfQueries and totalTime moved to profilers 2012-03-30 22:44:38 +02:00
Ondrej Nespor
24511a1d96 Fixed NettePanel output for multiple connections 2012-03-30 22:44:38 +02:00
Miloslav Hůla
a20ba29b13 typos 2012-03-30 22:44:38 +02:00
Miloslav Hůla
a606be0efa Fix DibiMsSql2005Driver::getResultColumns() 2012-03-30 22:44:38 +02:00
14 changed files with 80 additions and 41 deletions

16
composer.json Normal file
View File

@@ -0,0 +1,16 @@
{
"name": "dg/dibi",
"description": "Dibi is Database Abstraction Library for PHP 5.",
"keywords": ["dibi", "database", "dbal", "mysql", "postgresql", "sqlite", "mssql", "oracle", "access", "pdo", "odbc"],
"homepage": "http://dibiphp.com/",
"license": ["BSD-3", "GPLv2", "GPLv3"],
"authors": [
{
"name": "David Grudl",
"homepage": "http://davidgrudl.com"
}
],
"autoload": {
"classmap": ["dibi/"]
}
}

View File

@@ -101,9 +101,13 @@ class DibiNettePanel extends DibiObject implements IBarPanel
*/ */
public function getTab() 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" />' 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" />'
. dibi::$numOfQueries . ' queries' . count($this->events) . ' queries'
. (dibi::$totalTime ? ' / ' . sprintf('%0.1f', dibi::$totalTime * 1000) . 'ms' : '') . ($totalTime ? ' / ' . sprintf('%0.1f', $totalTime * 1000) . 'ms' : '')
. '</span>'; . '</span>';
} }
@@ -115,9 +119,10 @@ class DibiNettePanel extends DibiObject implements IBarPanel
*/ */
public function getPanel() public function getPanel()
{ {
$s = NULL; $totalTime = $s = NULL;
$h = 'htmlSpecialChars'; $h = 'htmlSpecialChars';
foreach ($this->events as $event) { foreach ($this->events as $event) {
$totalTime += $event->time;
$explain = NULL; // EXPLAIN is called here to work SELECT FOUND_ROWS() $explain = NULL; // EXPLAIN is called here to work SELECT FOUND_ROWS()
if ($this->explain && $event->type === DibiEvent::SELECT) { if ($this->explain && $event->type === DibiEvent::SELECT) {
try { try {
@@ -155,7 +160,7 @@ class DibiNettePanel extends DibiObject implements IBarPanel
'<style> #nette-debug td.nette-DibiProfiler-sql { background: white !important } '<style> #nette-debug td.nette-DibiProfiler-sql { background: white !important }
#nette-debug .nette-DibiProfiler-source { color: #999 !important } #nette-debug .nette-DibiProfiler-source { color: #999 !important }
#nette-debug nette-DibiProfiler tr table { margin: 8px 0; max-height: 150px; overflow:auto } </style> #nette-debug nette-DibiProfiler tr table { margin: 8px 0; max-height: 150px; overflow:auto } </style>
<h1>Queries: ' . dibi::$numOfQueries . (dibi::$totalTime === NULL ? '' : ', time: ' . sprintf('%0.3f', dibi::$totalTime * 1000) . ' ms') . '</h1> <h1>Queries: ' . count($this->events) . ($totalTime === NULL ? '' : ', time: ' . sprintf('%0.3f', $totalTime * 1000) . ' ms') . '</h1>
<div class="nette-inner nette-DibiProfiler"> <div class="nette-inner nette-DibiProfiler">
<table> <table>
<tr><th>Time&nbsp;ms</th><th>SQL Statement</th><th>Rows</th><th>Connection</th></tr>' . $s . ' <tr><th>Time&nbsp;ms</th><th>SQL Statement</th><th>Rows</th><th>Connection</th></tr>' . $s . '

View File

@@ -80,7 +80,7 @@ class dibi
FIELD_TIME = dibi::TIME; FIELD_TIME = dibi::TIME;
/** version */ /** version */
const VERSION = '2.0', const VERSION = '2.0.2',
REVISION = '$WCREV$ released on $WCDATE$'; REVISION = '$WCREV$ released on $WCDATE$';
/** sorting order */ /** sorting order */

View File

@@ -65,18 +65,16 @@ class DibiMsSqlReflector extends DibiObject implements IDibiReflector
if (empty($table)) { if (empty($table)) {
return false; return false;
} }
$table = $this->driver->escape($table, dibi::TEXT);
$result = $this->driver->query(" $result = $this->driver->query("
SELECT MAX(rowcnt) SELECT MAX(rowcnt)
FROM sys.sysindexes FROM sys.sysindexes
WHERE id=OBJECT_ID({$table}) WHERE id=OBJECT_ID({$this->driver->escape($table, dibi::IDENTIFIER)})
"); ");
$row = $result->fetch(FALSE); $row = $result->fetch(FALSE);
if (!is_array($row) || count($row) < 1) { if (!is_array($row) || count($row) < 1) {
if ($fallback) { if ($fallback) {
$row = $this->driver->query("SELECT COUNT(*) FROM {$table}")->fetch(FALSE); $row = $this->driver->query("SELECT COUNT(*) FROM {$this->driver->escape($table, dibi::IDENTIFIER)}")->fetch(FALSE);
$count = intval($row[0]); $count = intval($row[0]);
} else { } else {
$count = false; $count = false;
@@ -100,7 +98,7 @@ class DibiMsSqlReflector extends DibiObject implements IDibiReflector
$res = $this->driver->query(" $res = $this->driver->query("
SELECT * FROM SELECT * FROM
INFORMATION_SCHEMA.COLUMNS INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '{$table}' WHERE TABLE_NAME = {$this->driver->escape($table, dibi::TEXT)}
ORDER BY TABLE_NAME, ORDINAL_POSITION ORDER BY TABLE_NAME, ORDINAL_POSITION
"); ");
$columns = array(); $columns = array();
@@ -148,8 +146,6 @@ class DibiMsSqlReflector extends DibiObject implements IDibiReflector
*/ */
public function getIndexes($table) public function getIndexes($table)
{ {
$table = $this->driver->escape($table, dibi::TEXT);
$res = $this->driver->query( $res = $this->driver->query(
"SELECT ind.name index_name, ind.index_id, ic.index_column_id, "SELECT ind.name index_name, ind.index_id, ic.index_column_id,
col.name column_name, ind.is_unique, ind.is_primary_key col.name column_name, ind.is_unique, ind.is_primary_key
@@ -160,7 +156,7 @@ class DibiMsSqlReflector extends DibiObject implements IDibiReflector
(ic.object_id = col.object_id and ic.column_id = col.column_id) (ic.object_id = col.object_id and ic.column_id = col.column_id)
INNER JOIN sys.tables t ON INNER JOIN sys.tables t ON
(ind.object_id = t.object_id) (ind.object_id = t.object_id)
WHERE t.name = {$table} WHERE t.name = {$this->driver->escape($table, dibi::TEXT)}
AND t.is_ms_shipped = 0 AND t.is_ms_shipped = 0
ORDER BY ORDER BY
t.name, ind.name, ind.index_id, ic.index_column_id t.name, ind.name, ind.index_id, ic.index_column_id
@@ -192,8 +188,6 @@ class DibiMsSqlReflector extends DibiObject implements IDibiReflector
*/ */
public function getForeignKeys($table) public function getForeignKeys($table)
{ {
$table = $this->driver->escape($table, dibi::TEXT);
$res = $this->driver->query(" $res = $this->driver->query("
SELECT f.name AS foreign_key, SELECT f.name AS foreign_key,
OBJECT_NAME(f.parent_object_id) AS table_name, OBJECT_NAME(f.parent_object_id) AS table_name,
@@ -206,7 +200,7 @@ class DibiMsSqlReflector extends DibiObject implements IDibiReflector
FROM sys.foreign_keys AS f FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id ON f.OBJECT_ID = fc.constraint_object_id
WHERE OBJECT_NAME(f.parent_object_id)={$table} WHERE OBJECT_NAME(f.parent_object_id) = {$this->driver->escape($table, dibi::TEXT)}
"); ");
$keys = array(); $keys = array();

View File

@@ -375,14 +375,12 @@ class DibiMsSql2005Driver extends DibiObject implements IDibiDriver, IDibiResult
*/ */
public function getResultColumns() public function getResultColumns()
{ {
$count = sqlsrv_num_fields($this->resultSet);
$columns = array(); $columns = array();
for ($i = 0; $i < $count; $i++) { foreach ((array) sqlsrv_field_metadata($this->resultSet) as $fieldMetadata) {
$row = (array) sqlsrv_field_metadata($this->resultSet, $i);
$columns[] = array( $columns[] = array(
'name' => $row['Name'], 'name' => $fieldMetadata['Name'],
'fullname' => $row['Name'], 'fullname' => $fieldMetadata['Name'],
'nativetype' => $row['Type'], 'nativetype' => $fieldMetadata['Type'],
); );
} }
return $columns; return $columns;

View File

@@ -68,7 +68,7 @@ class DibiMySqlReflector extends DibiObject implements IDibiReflector
FROM INFORMATION_SCHEMA.COLUMNS FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = $table AND TABLE_SCHEMA = DATABASE() WHERE TABLE_NAME = $table AND TABLE_SCHEMA = DATABASE()
");*/ ");*/
$res = $this->driver->query("SHOW FULL COLUMNS FROM `$table`"); $res = $this->driver->query("SHOW FULL COLUMNS FROM {$this->driver->escape($table, dibi::IDENTIFIER)}");
$columns = array(); $columns = array();
while ($row = $res->fetch(TRUE)) { while ($row = $res->fetch(TRUE)) {
$type = explode('(', $row['Type']); $type = explode('(', $row['Type']);
@@ -103,7 +103,7 @@ class DibiMySqlReflector extends DibiObject implements IDibiReflector
WHERE TABLE_NAME = $table AND TABLE_SCHEMA = DATABASE() WHERE TABLE_NAME = $table AND TABLE_SCHEMA = DATABASE()
AND REFERENCED_COLUMN_NAME IS NULL AND REFERENCED_COLUMN_NAME IS NULL
");*/ ");*/
$res = $this->driver->query("SHOW INDEX FROM `$table`"); $res = $this->driver->query("SHOW INDEX FROM {$this->driver->escape($table, dibi::IDENTIFIER)}");
$indexes = array(); $indexes = array();
while ($row = $res->fetch(TRUE)) { while ($row = $res->fetch(TRUE)) {
$indexes[$row['Key_name']]['name'] = $row['Key_name']; $indexes[$row['Key_name']]['name'] = $row['Key_name'];

View File

@@ -60,16 +60,16 @@ class DibiSqliteReflector extends DibiObject implements IDibiReflector
public function getColumns($table) public function getColumns($table)
{ {
$meta = $this->driver->query(" $meta = $this->driver->query("
SELECT sql FROM sqlite_master WHERE type = 'table' AND name = '$table' SELECT sql FROM sqlite_master WHERE type = 'table' AND name = {$this->driver->escape($table, dibi::TEXT)}
UNION ALL UNION ALL
SELECT sql FROM sqlite_temp_master WHERE type = 'table' AND name = '$table'" SELECT sql FROM sqlite_temp_master WHERE type = 'table' AND name = {$this->driver->escape($table, dibi::TEXT)}
)->fetch(TRUE); ")->fetch(TRUE);
$res = $this->driver->query("PRAGMA table_info([$table])"); $res = $this->driver->query("PRAGMA table_info({$this->driver->escape($table, dibi::IDENTIFIER)})");
$columns = array(); $columns = array();
while ($row = $res->fetch(TRUE)) { while ($row = $res->fetch(TRUE)) {
$column = $row['name']; $column = $row['name'];
$pattern = "/(\"$column\"|\[$column\]|$column)\s+[^,]+\s+PRIMARY\s+KEY\s+AUTOINCREMENT/Ui"; $pattern = "/(\"$column\"|\[$column\]|$column)\\s+[^,]+\\s+PRIMARY\\s+KEY\\s+AUTOINCREMENT/Ui";
$type = explode('(', $row['type']); $type = explode('(', $row['type']);
$columns[] = array( $columns[] = array(
'name' => $column, 'name' => $column,
@@ -95,7 +95,7 @@ class DibiSqliteReflector extends DibiObject implements IDibiReflector
*/ */
public function getIndexes($table) public function getIndexes($table)
{ {
$res = $this->driver->query("PRAGMA index_list([$table])"); $res = $this->driver->query("PRAGMA index_list({$this->driver->escape($table, dibi::IDENTIFIER)})");
$indexes = array(); $indexes = array();
while ($row = $res->fetch(TRUE)) { while ($row = $res->fetch(TRUE)) {
$indexes[$row['name']]['name'] = $row['name']; $indexes[$row['name']]['name'] = $row['name'];
@@ -103,7 +103,7 @@ class DibiSqliteReflector extends DibiObject implements IDibiReflector
} }
foreach ($indexes as $index => $values) { foreach ($indexes as $index => $values) {
$res = $this->driver->query("PRAGMA index_info([$index])"); $res = $this->driver->query("PRAGMA index_info({$this->driver->escape($index, dibi::IDENTIFIER)})");
while ($row = $res->fetch(TRUE)) { while ($row = $res->fetch(TRUE)) {
$indexes[$index]['columns'][$row['seqno']] = $row['name']; $indexes[$index]['columns'][$row['seqno']] = $row['name'];
} }
@@ -150,7 +150,7 @@ class DibiSqliteReflector extends DibiObject implements IDibiReflector
if (!($this->driver instanceof DibiSqlite3Driver)) { if (!($this->driver instanceof DibiSqlite3Driver)) {
// throw new DibiNotSupportedException; // @see http://www.sqlite.org/foreignkeys.html // throw new DibiNotSupportedException; // @see http://www.sqlite.org/foreignkeys.html
} }
$res = $this->driver->query("PRAGMA foreign_key_list([$table])"); $res = $this->driver->query("PRAGMA foreign_key_list({$this->driver->escape($table, dibi::IDENTIFIER)})");
$keys = array(); $keys = array();
while ($row = $res->fetch(TRUE)) { while ($row = $res->fetch(TRUE)) {
$keys[$row['id']]['name'] = $row['id']; // foreign key name $keys[$row['id']]['name'] = $row['id']; // foreign key name

View File

@@ -339,8 +339,6 @@ class DibiConnection extends DibiObject
$this->connected || $this->connect(); $this->connected || $this->connect();
$event = $this->onEvent ? new DibiEvent($this, DibiEvent::QUERY, $sql) : NULL; $event = $this->onEvent ? new DibiEvent($this, DibiEvent::QUERY, $sql) : NULL;
dibi::$numOfQueries++;
dibi::$sql = $sql;
try { try {
$res = $this->driver->query($sql); $res = $this->driver->query($sql);
@@ -690,6 +688,10 @@ class DibiConnection extends DibiObject
$count++; $count++;
} }
} }
if (trim($sql) !== '') {
$this->driver->query($sql);
$count++;
}
fclose($handle); fclose($handle);
return $count; return $count;
} }

View File

@@ -80,6 +80,8 @@ class DibiEvent
} }
dibi::$elapsedTime = FALSE; dibi::$elapsedTime = FALSE;
dibi::$numOfQueries++;
dibi::$sql = $sql;
} }

View File

@@ -28,6 +28,12 @@ class DibiFirePhpLogger extends DibiObject
/** @var int */ /** @var int */
public $filter; public $filter;
/** @var int Elapsed time for all queries */
public $totalTime = 0;
/** @var int Number of all queries */
public $numOfQueries = 0;
/** @var array */ /** @var array */
private static $fireTable = array(array('Time', 'SQL Statement', 'Rows', 'Connection')); private static $fireTable = array(array('Time', 'SQL Statement', 'Rows', 'Connection'));
@@ -60,10 +66,12 @@ class DibiFirePhpLogger extends DibiObject
return; return;
} }
$this->totalTime += $event->time;
$this->numOfQueries++;
self::$fireTable[] = array( self::$fireTable[] = array(
sprintf('%0.3f', $event->time * 1000), sprintf('%0.3f', $event->time * 1000),
strlen($event->sql) > self::$maxLength ? substr($event->sql, 0, self::$maxLength) . '...' : $event->sql, strlen($event->sql) > self::$maxLength ? substr($event->sql, 0, self::$maxLength) . '...' : $event->sql,
$event->result instanceof Exception ? 'ERROR' : $event->count, $event->result instanceof Exception ? 'ERROR' : (string) $event->count,
$event->connection->getConfig('driver') . '/' . $event->connection->getConfig('name') $event->connection->getConfig('driver') . '/' . $event->connection->getConfig('name')
); );
@@ -74,7 +82,7 @@ class DibiFirePhpLogger extends DibiObject
$payload = json_encode(array( $payload = json_encode(array(
array( array(
'Type' => 'TABLE', 'Type' => 'TABLE',
'Label' => 'dibi profiler (' . dibi::$numOfQueries . ' SQL queries took ' . sprintf('%0.3f', dibi::$totalTime * 1000) . ' ms)', 'Label' => 'dibi profiler (' . $this->numOfQueries . ' SQL queries took ' . sprintf('%0.3f', $this->totalTime * 1000) . ' ms)',
), ),
self::$fireTable, self::$fireTable,
)); ));

View File

@@ -181,7 +181,7 @@ class DibiFluent extends DibiObject implements IDataSource
if ($arg === TRUE) { // flag if ($arg === TRUE) { // flag
return $this; return $this;
} elseif (is_string($arg) && preg_match('#^[a-z:_][a-z0-9_.:]*$#i', $arg)) { // identifier } elseif (is_string($arg) && preg_match('#^[a-z:_][a-z0-9_.:]*\z#i', $arg)) { // identifier
$args = array('%n', $arg); $args = array('%n', $arg);
} elseif (is_array($arg) || ($arg instanceof Traversable && !$arg instanceof self)) { // any array } elseif (is_array($arg) || ($arg instanceof Traversable && !$arg instanceof self)) { // any array

View File

@@ -353,7 +353,7 @@ final class DibiTranslator extends DibiObject
case 'i': // signed int case 'i': // signed int
case 'u': // unsigned int, ignored case 'u': // unsigned int, ignored
// support for long numbers - keep them unchanged // support for long numbers - keep them unchanged
if (is_string($value) && preg_match('#[+-]?\d++(e\d+)?$#A', $value)) { if (is_string($value) && preg_match('#[+-]?\d++(e\d+)?\z#A', $value)) {
return $value; return $value;
} else { } else {
return $value === NULL ? 'NULL' : (string) (int) ($value + 0); return $value === NULL ? 'NULL' : (string) (int) ($value + 0);
@@ -364,7 +364,7 @@ final class DibiTranslator extends DibiObject
if (is_string($value) && is_numeric($value) && strpos($value, 'x') === FALSE) { 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 return $value; // something like -9E-005 is accepted by SQL, HEX values are not
} else { } else {
return $value === NULL ? 'NULL' : rtrim(rtrim(number_format($value + 0, 5, '.', ''), '0'), '.'); return $value === NULL ? 'NULL' : rtrim(rtrim(number_format($value + 0, 10, '.', ''), '0'), '.');
} }
case 'd': // date case 'd': // date
@@ -436,7 +436,7 @@ final class DibiTranslator extends DibiObject
return (string) $value; return (string) $value;
} elseif (is_float($value)) { } elseif (is_float($value)) {
return rtrim(rtrim(number_format($value, 5, '.', ''), '0'), '.'); return rtrim(rtrim(number_format($value, 10, '.', ''), '0'), '.');
} elseif (is_bool($value)) { } elseif (is_bool($value)) {
return $this->driver->escape($value, dibi::BOOL); return $this->driver->escape($value, dibi::BOOL);

View File

@@ -18,6 +18,20 @@ require_once '../dibi/dibi.php';
ndebug(); 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( dibi::connect(array(
'driver' => 'sqlite', 'driver' => 'sqlite',
'database' => 'data/sample.sdb', 'database' => 'data/sample.sdb',

View File

@@ -1 +1 @@
Dibi 2.0 (revision $WCREV$ released on $WCDATE$) Dibi 2.0.2 (revision $WCREV$ released on $WCDATE$)