mirror of
https://github.com/UnickSoft/graphonline.git
synced 2026-04-16 13:25:34 +00:00
first commit
This commit is contained in:
1361
lib/Db/DbSimple/Generic.php
Executable file
1361
lib/Db/DbSimple/Generic.php
Executable file
File diff suppressed because it is too large
Load Diff
290
lib/Db/DbSimple/Ibase.php
Executable file
290
lib/Db/DbSimple/Ibase.php
Executable file
@@ -0,0 +1,290 @@
|
||||
<?php
|
||||
/**
|
||||
* DbSimple_Ibase: Interbase/Firebird database.
|
||||
* (C) Dk Lab, http://en.dklab.ru
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
* See http://www.gnu.org/copyleft/lesser.html
|
||||
*
|
||||
* Placeholders are emulated because of logging purposes.
|
||||
*
|
||||
* @author Dmitry Koterov, http://forum.dklab.ru/users/DmitryKoterov/
|
||||
* @author Konstantin Zhinko, http://forum.dklab.ru/users/KonstantinGinkoTit/
|
||||
*
|
||||
* @version 2.x $Id: Ibase.php 221 2007-07-27 23:24:35Z dk $
|
||||
*/
|
||||
require_once dirname(__FILE__) . '/Generic.php';
|
||||
|
||||
/**
|
||||
* Best transaction parameters for script queries.
|
||||
* They never give us update conflicts (unlike others)!
|
||||
* Used by default.
|
||||
*/
|
||||
define('IBASE_BEST_TRANSACTION', IBASE_COMMITTED + IBASE_WAIT + IBASE_REC_VERSION);
|
||||
define('IBASE_BEST_FETCH', IBASE_UNIXTIME);
|
||||
|
||||
/**
|
||||
* Database class for Interbase/Firebird.
|
||||
*/
|
||||
|
||||
class DbSimple_Ibase extends DbSimple_Generic_Database
|
||||
{
|
||||
var $DbSimple_Ibase_BEST_TRANSACTION = IBASE_BEST_TRANSACTION;
|
||||
var $DbSimple_Ibase_USE_NATIVE_PHOLDERS = true;
|
||||
var $fetchFlags = IBASE_BEST_FETCH;
|
||||
var $link;
|
||||
var $trans;
|
||||
var $prepareCache = array();
|
||||
|
||||
/**
|
||||
* constructor(string $dsn)
|
||||
* Connect to Interbase/Firebird.
|
||||
*/
|
||||
function DbSimple_Ibase($dsn)
|
||||
{
|
||||
$p = DbSimple_Generic::parseDSN($dsn);
|
||||
if (!is_callable('ibase_connect')) {
|
||||
return $this->_setLastError("-1", "Interbase/Firebird extension is not loaded", "ibase_connect");
|
||||
}
|
||||
$ok = $this->link = ibase_connect(
|
||||
$p['host'] . (empty($p['port'])? "" : ":".$p['port']) .':'.preg_replace('{^/}s', '', $p['path']),
|
||||
$p['user'],
|
||||
$p['pass'],
|
||||
isset($p['CHARSET']) ? $p['CHARSET'] : 'win1251',
|
||||
isset($p['BUFFERS']) ? $p['BUFFERS'] : 0,
|
||||
isset($p['DIALECT']) ? $p['DIALECT'] : 3,
|
||||
isset($p['ROLE']) ? $p['ROLE'] : ''
|
||||
);
|
||||
if (isset($p['TRANSACTION'])) $this->DbSimple_Ibase_BEST_TRANSACTION = eval($p['TRANSACTION'].";");
|
||||
$this->_resetLastError();
|
||||
if (!$ok) return $this->_setDbError('ibase_connect()');
|
||||
}
|
||||
|
||||
function _performEscape($s, $isIdent=false)
|
||||
{
|
||||
if (!$isIdent)
|
||||
return "'" . str_replace("'", "''", $s) . "'";
|
||||
else
|
||||
return '"' . str_replace('"', '_', $s) . '"';
|
||||
}
|
||||
|
||||
function _performTransaction($parameters=null)
|
||||
{
|
||||
if ($parameters === null) $parameters = $this->DbSimple_Ibase_BEST_TRANSACTION;
|
||||
$this->trans = @ibase_trans($parameters, $this->link);
|
||||
}
|
||||
|
||||
function& _performNewBlob($blobid=null)
|
||||
{
|
||||
$obj =& new DbSimple_Ibase_Blob($this, $blobid);
|
||||
return $obj;
|
||||
}
|
||||
|
||||
function _performGetBlobFieldNames($result)
|
||||
{
|
||||
$blobFields = array();
|
||||
for ($i=ibase_num_fields($result)-1; $i>=0; $i--) {
|
||||
$info = ibase_field_info($result, $i);
|
||||
if ($info['type'] === "BLOB") $blobFields[] = $info['name'];
|
||||
}
|
||||
return $blobFields;
|
||||
}
|
||||
|
||||
function _performGetPlaceholderIgnoreRe()
|
||||
{
|
||||
return '
|
||||
" (?> [^"\\\\]+|\\\\"|\\\\)* " |
|
||||
\' (?> [^\'\\\\]+|\\\\\'|\\\\)* \' |
|
||||
` (?> [^`]+ | ``)* ` | # backticks
|
||||
/\* .*? \*/ # comments
|
||||
';
|
||||
}
|
||||
|
||||
function _performCommit()
|
||||
{
|
||||
if (!is_resource($this->trans)) return false;
|
||||
$result = @ibase_commit($this->trans);
|
||||
if (true === $result) {
|
||||
$this->trans = null;
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
|
||||
function _performRollback()
|
||||
{
|
||||
if (!is_resource($this->trans)) return false;
|
||||
$result = @ibase_rollback($this->trans);
|
||||
if (true === $result) {
|
||||
$this->trans = null;
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
function _performTransformQuery(&$queryMain, $how)
|
||||
{
|
||||
// If we also need to calculate total number of found rows...
|
||||
switch ($how) {
|
||||
// Prepare total calculation (if possible)
|
||||
case 'CALC_TOTAL':
|
||||
// Not possible
|
||||
return true;
|
||||
|
||||
// Perform total calculation.
|
||||
case 'GET_TOTAL':
|
||||
// XTODO: GROUP BY ... -> COUNT(DISTINCT ...)
|
||||
$re = '/^
|
||||
(?> -- [^\r\n]* | \s+)*
|
||||
(\s* SELECT \s+) #1
|
||||
((?:FIRST \s+ \S+ \s+ (?:SKIP \s+ \S+ \s+)? )?) #2
|
||||
(.*?) #3
|
||||
(\s+ FROM \s+ .*?) #4
|
||||
((?:\s+ ORDER \s+ BY \s+ .*)?) #5
|
||||
$/six';
|
||||
$m = null;
|
||||
if (preg_match($re, $queryMain[0], $m)) {
|
||||
$queryMain[0] = $m[1] . $this->_fieldList2Count($m[3]) . " AS C" . $m[4];
|
||||
$skipHead = substr_count($m[2], '?');
|
||||
if ($skipHead) array_splice($queryMain, 1, $skipHead);
|
||||
$skipTail = substr_count($m[5], '?');
|
||||
if ($skipTail) array_splice($queryMain, -$skipTail);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function _performQuery($queryMain)
|
||||
{
|
||||
$this->_lastQuery = $queryMain;
|
||||
$this->_expandPlaceholders($queryMain, $this->DbSimple_Ibase_USE_NATIVE_PHOLDERS);
|
||||
|
||||
$hash = $queryMain[0];
|
||||
|
||||
if (!isset($this->prepareCache[$hash])) {
|
||||
$this->prepareCache[$hash] = @ibase_prepare((is_resource($this->trans) ? $this->trans : $this->link), $queryMain[0]);
|
||||
} else {
|
||||
// Prepare cache hit!
|
||||
}
|
||||
|
||||
$prepared = $this->prepareCache[$hash];
|
||||
if (!$prepared) return $this->_setDbError($queryMain[0]);
|
||||
$queryMain[0] = $prepared;
|
||||
$result = @call_user_func_array('ibase_execute', $queryMain);
|
||||
// ATTENTION!!!
|
||||
// WE MUST save prepared ID (stored in $prepared variable) somewhere
|
||||
// before returning $result because of ibase destructor. Now it is done
|
||||
// by $this->prepareCache. When variable $prepared goes out of scope, it
|
||||
// is destroyed, and memory for result also freed by PHP. Totally we
|
||||
// got "Invalud statement handle" error message.
|
||||
|
||||
if ($result === false) return $this->_setDbError($queryMain[0]);
|
||||
if (!is_resource($result)) {
|
||||
// Non-SELECT queries return number of affected rows, SELECT - resource.
|
||||
return @ibase_affected_rows((is_resource($this->trans) ? $this->trans : $this->link));
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
function _performFetch($result)
|
||||
{
|
||||
// Select fetch mode.
|
||||
$flags = $this->fetchFlags;
|
||||
if (empty($this->attributes['BLOB_OBJ'])) $flags = $flags | IBASE_TEXT;
|
||||
else $flags = $flags & ~IBASE_TEXT;
|
||||
|
||||
$row = @ibase_fetch_assoc($result, $flags);
|
||||
if (ibase_errmsg()) return $this->_setDbError($this->_lastQuery);
|
||||
if ($row === false) return null;
|
||||
return $row;
|
||||
}
|
||||
|
||||
|
||||
function _setDbError($query)
|
||||
{
|
||||
return $this->_setLastError(ibase_errcode(), ibase_errmsg(), $query);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class DbSimple_Ibase_Blob extends DbSimple_Generic_Blob
|
||||
{
|
||||
var $blob; // resourse link
|
||||
var $id;
|
||||
var $database;
|
||||
|
||||
function DbSimple_Ibase_Blob(&$database, $id=null)
|
||||
{
|
||||
$this->database =& $database;
|
||||
$this->id = $id;
|
||||
$this->blob = null;
|
||||
}
|
||||
|
||||
function read($len)
|
||||
{
|
||||
if ($this->id === false) return ''; // wr-only blob
|
||||
if (!($e=$this->_firstUse())) return $e;
|
||||
$data = @ibase_blob_get($this->blob, $len);
|
||||
if ($data === false) return $this->_setDbError('read');
|
||||
return $data;
|
||||
}
|
||||
|
||||
function write($data)
|
||||
{
|
||||
if (!($e=$this->_firstUse())) return $e;
|
||||
$ok = @ibase_blob_add($this->blob, $data);
|
||||
if ($ok === false) return $this->_setDbError('add data to');
|
||||
return true;
|
||||
}
|
||||
|
||||
function close()
|
||||
{
|
||||
if (!($e=$this->_firstUse())) return $e;
|
||||
if ($this->blob) {
|
||||
$id = @ibase_blob_close($this->blob);
|
||||
if ($id === false) return $this->_setDbError('close');
|
||||
$this->blob = null;
|
||||
} else {
|
||||
$id = null;
|
||||
}
|
||||
return $this->id ? $this->id : $id;
|
||||
}
|
||||
|
||||
function length()
|
||||
{
|
||||
if ($this->id === false) return 0; // wr-only blob
|
||||
if (!($e=$this->_firstUse())) return $e;
|
||||
$info = @ibase_blob_info($this->id);
|
||||
if (!$info) return $this->_setDbError('get length of');
|
||||
return $info[0];
|
||||
}
|
||||
|
||||
function _setDbError($query)
|
||||
{
|
||||
$hId = $this->id === null ? "null" : ($this->id === false ? "false" : $this->id);
|
||||
$query = "-- $query BLOB $hId";
|
||||
$this->database->_setDbError($query);
|
||||
}
|
||||
|
||||
// Called on each blob use (reading or writing).
|
||||
function _firstUse()
|
||||
{
|
||||
// BLOB is opened - nothing to do.
|
||||
if (is_resource($this->blob)) return true;
|
||||
// Open or create blob.
|
||||
if ($this->id !== null) {
|
||||
$this->blob = @ibase_blob_open($this->id);
|
||||
if ($this->blob === false) return $this->_setDbError('open');
|
||||
} else {
|
||||
$this->blob = @ibase_blob_create($this->database->link);
|
||||
if ($this->blob === false) return $this->_setDbError('create');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
||||
230
lib/Db/DbSimple/Mysql.php
Executable file
230
lib/Db/DbSimple/Mysql.php
Executable file
@@ -0,0 +1,230 @@
|
||||
<?php
|
||||
/**
|
||||
* DbSimple_Mysql: MySQL database.
|
||||
* (C) Dk Lab, http://en.dklab.ru
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
* See http://www.gnu.org/copyleft/lesser.html
|
||||
*
|
||||
* Placeholders end blobs are emulated.
|
||||
*
|
||||
* @author Dmitry Koterov, http://forum.dklab.ru/users/DmitryKoterov/
|
||||
* @author Konstantin Zhinko, http://forum.dklab.ru/users/KonstantinGinkoTit/
|
||||
*
|
||||
* @version 2.x $Id: Mysql.php 247 2008-08-18 21:17:08Z dk $
|
||||
*/
|
||||
require_once dirname(__FILE__) . '/Generic.php';
|
||||
|
||||
|
||||
/**
|
||||
* Database class for MySQL.
|
||||
*/
|
||||
class DbSimple_Mysql extends DbSimple_Generic_Database
|
||||
{
|
||||
var $link;
|
||||
|
||||
/**
|
||||
* constructor(string $dsn)
|
||||
* Connect to MySQL.
|
||||
*/
|
||||
function DbSimple_Mysql($dsn)
|
||||
{
|
||||
$p = DbSimple_Generic::parseDSN($dsn);
|
||||
if (!is_callable('mysql_connect')) {
|
||||
return $this->_setLastError("-1", "MySQL extension is not loaded", "mysql_connect");
|
||||
}
|
||||
$ok = $this->link = @mysql_connect(
|
||||
$p['host'] . (empty($p['port'])? "" : ":".$p['port']),
|
||||
$p['user'],
|
||||
$p['pass'],
|
||||
true
|
||||
);
|
||||
$this->_resetLastError();
|
||||
if (!$ok) return $this->_setDbError('mysql_connect()');
|
||||
$ok = @mysql_select_db(preg_replace('{^/}s', '', $p['path']), $this->link);
|
||||
if (!$ok) return $this->_setDbError('mysql_select_db()');
|
||||
if (isset($p["charset"])) {
|
||||
$this->query('SET NAMES ?', $p["charset"]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function _performEscape($s, $isIdent=false)
|
||||
{
|
||||
if (!$isIdent) {
|
||||
return "'" . mysql_real_escape_string($s, $this->link) . "'";
|
||||
} else {
|
||||
return "`" . str_replace('`', '``', $s) . "`";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function _performTransaction($parameters=null)
|
||||
{
|
||||
return $this->query('BEGIN');
|
||||
}
|
||||
|
||||
|
||||
function& _performNewBlob($blobid=null)
|
||||
{
|
||||
$obj =& new DbSimple_Mysql_Blob($this, $blobid);
|
||||
return $obj;
|
||||
}
|
||||
|
||||
|
||||
function _performGetBlobFieldNames($result)
|
||||
{
|
||||
$blobFields = array();
|
||||
for ($i=mysql_num_fields($result)-1; $i>=0; $i--) {
|
||||
$type = mysql_field_type($result, $i);
|
||||
if (strpos($type, "BLOB") !== false) $blobFields[] = mysql_field_name($result, $i);
|
||||
}
|
||||
return $blobFields;
|
||||
}
|
||||
|
||||
|
||||
function _performGetPlaceholderIgnoreRe()
|
||||
{
|
||||
return '
|
||||
" (?> [^"\\\\]+|\\\\"|\\\\)* " |
|
||||
\' (?> [^\'\\\\]+|\\\\\'|\\\\)* \' |
|
||||
` (?> [^`]+ | ``)* ` | # backticks
|
||||
/\* .*? \*/ # comments
|
||||
';
|
||||
}
|
||||
|
||||
|
||||
function _performCommit()
|
||||
{
|
||||
return $this->query('COMMIT');
|
||||
}
|
||||
|
||||
|
||||
function _performRollback()
|
||||
{
|
||||
return $this->query('ROLLBACK');
|
||||
}
|
||||
|
||||
|
||||
function _performTransformQuery(&$queryMain, $how)
|
||||
{
|
||||
// If we also need to calculate total number of found rows...
|
||||
switch ($how) {
|
||||
// Prepare total calculation (if possible)
|
||||
case 'CALC_TOTAL':
|
||||
$m = null;
|
||||
if (preg_match('/^(\s* SELECT)(.*)/six', $queryMain[0], $m)) {
|
||||
if ($this->_calcFoundRowsAvailable()) {
|
||||
$queryMain[0] = $m[1] . ' SQL_CALC_FOUND_ROWS' . $m[2];
|
||||
}
|
||||
}
|
||||
return true;
|
||||
|
||||
// Perform total calculation.
|
||||
case 'GET_TOTAL':
|
||||
// Built-in calculation available?
|
||||
if ($this->_calcFoundRowsAvailable()) {
|
||||
$queryMain = array('SELECT FOUND_ROWS()');
|
||||
}
|
||||
// Else use manual calculation.
|
||||
// XTODO: GROUP BY ... -> COUNT(DISTINCT ...)
|
||||
$re = '/^
|
||||
(?> -- [^\r\n]* | \s+)*
|
||||
(\s* SELECT \s+) #1
|
||||
(.*?) #2
|
||||
(\s+ FROM \s+ .*?) #3
|
||||
((?:\s+ ORDER \s+ BY \s+ .*?)?) #4
|
||||
((?:\s+ LIMIT \s+ \S+ \s* (?:, \s* \S+ \s*)? )?) #5
|
||||
$/six';
|
||||
$m = null;
|
||||
if (preg_match($re, $queryMain[0], $m)) {
|
||||
$query[0] = $m[1] . $this->_fieldList2Count($m[2]) . " AS C" . $m[3];
|
||||
$skipTail = substr_count($m[4] . $m[5], '?');
|
||||
if ($skipTail) array_splice($query, -$skipTail);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
function _performQuery($queryMain)
|
||||
{
|
||||
$this->_lastQuery = $queryMain;
|
||||
$this->_expandPlaceholders($queryMain, false);
|
||||
$result = @mysql_query($queryMain[0], $this->link);
|
||||
if ($result === false) return $this->_setDbError($queryMain[0]);
|
||||
if (!is_resource($result)) {
|
||||
if (preg_match('/^\s* INSERT \s+/six', $queryMain[0])) {
|
||||
// INSERT queries return generated ID.
|
||||
return @mysql_insert_id($this->link);
|
||||
}
|
||||
// Non-SELECT queries return number of affected rows, SELECT - resource.
|
||||
return @mysql_affected_rows($this->link);
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
|
||||
function _performFetch($result)
|
||||
{
|
||||
$row = @mysql_fetch_assoc($result);
|
||||
if (mysql_error()) return $this->_setDbError($this->_lastQuery);
|
||||
if ($row === false) return null;
|
||||
return $row;
|
||||
}
|
||||
|
||||
|
||||
function _setDbError($query)
|
||||
{
|
||||
return $this->_setLastError(mysql_errno($this->link), mysql_error($this->link), $query);
|
||||
}
|
||||
|
||||
|
||||
function _calcFoundRowsAvailable()
|
||||
{
|
||||
$ok = version_compare(mysql_get_server_info($this->link), '4.0') >= 0;
|
||||
return $ok;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class DbSimple_Mysql_Blob extends DbSimple_Generic_Blob
|
||||
{
|
||||
// MySQL does not support separate BLOB fetching.
|
||||
var $blobdata = null;
|
||||
var $curSeek = 0;
|
||||
|
||||
function DbSimple_Mysql_Blob(&$database, $blobdata=null)
|
||||
{
|
||||
$this->blobdata = $blobdata;
|
||||
$this->curSeek = 0;
|
||||
}
|
||||
|
||||
function read($len)
|
||||
{
|
||||
$p = $this->curSeek;
|
||||
$this->curSeek = min($this->curSeek + $len, strlen($this->blobdata));
|
||||
return substr($this->blobdata, $this->curSeek, $len);
|
||||
}
|
||||
|
||||
function write($data)
|
||||
{
|
||||
$this->blobdata .= $data;
|
||||
}
|
||||
|
||||
function close()
|
||||
{
|
||||
return $this->blobdata;
|
||||
}
|
||||
|
||||
function length()
|
||||
{
|
||||
return strlen($this->blobdata);
|
||||
}
|
||||
}
|
||||
?>
|
||||
312
lib/Db/DbSimple/Postgresql.php
Executable file
312
lib/Db/DbSimple/Postgresql.php
Executable file
@@ -0,0 +1,312 @@
|
||||
<?php
|
||||
/**
|
||||
* DbSimple_Postgreql: PostgreSQL database.
|
||||
* (C) Dk Lab, http://en.dklab.ru
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Lesser General Public
|
||||
* License as published by the Free Software Foundation; either
|
||||
* version 2.1 of the License, or (at your option) any later version.
|
||||
* See http://www.gnu.org/copyleft/lesser.html
|
||||
*
|
||||
* Placeholders are emulated because of logging purposes.
|
||||
*
|
||||
* @author Dmitry Koterov, http://forum.dklab.ru/users/DmitryKoterov/
|
||||
* @author Konstantin Zhinko, http://forum.dklab.ru/users/KonstantinGinkoTit/
|
||||
*
|
||||
* @version 2.x $Id: Postgresql.php 167 2007-01-22 10:12:09Z tit $
|
||||
*/
|
||||
require_once dirname(__FILE__) . '/Generic.php';
|
||||
|
||||
|
||||
/**
|
||||
* Database class for PostgreSQL.
|
||||
*/
|
||||
class DbSimple_Postgresql extends DbSimple_Generic_Database
|
||||
{
|
||||
|
||||
var $DbSimple_Postgresql_USE_NATIVE_PHOLDERS = null;
|
||||
var $prepareCache = array();
|
||||
var $link;
|
||||
|
||||
/**
|
||||
* constructor(string $dsn)
|
||||
* Connect to PostgresSQL.
|
||||
*/
|
||||
function DbSimple_Postgresql($dsn)
|
||||
{
|
||||
$p = DbSimple_Generic::parseDSN($dsn);
|
||||
if (!is_callable('pg_connect')) {
|
||||
return $this->_setLastError("-1", "PostgreSQL extension is not loaded", "pg_connect");
|
||||
}
|
||||
|
||||
// Prepare+execute works only in PHP 5.1+.
|
||||
$this->DbSimple_Postgresql_USE_NATIVE_PHOLDERS = function_exists('pg_prepare');
|
||||
|
||||
$ok = $this->link = @pg_connect(
|
||||
$t = (!empty($p['host']) ? 'host='.$p['host'].' ' : '').
|
||||
(!empty($p['port']) ? 'port='.$p['port'].' ' : '').
|
||||
'dbname='.preg_replace('{^/}s', '', $p['path']).' '.
|
||||
(!empty($p['user']) ? 'user='.$p['user'].' ' : '').
|
||||
(!empty($p['pass']) ? 'password='.$p['pass'].' ' : '')
|
||||
);
|
||||
$this->_resetLastError();
|
||||
if (!$ok) return $this->_setDbError('pg_connect()');
|
||||
}
|
||||
|
||||
|
||||
function _performEscape($s, $isIdent=false)
|
||||
{
|
||||
if (!$isIdent)
|
||||
return "'" . str_replace("'", "''", $s) . "'";
|
||||
else
|
||||
return '"' . str_replace('"', '_', $s) . '"';
|
||||
}
|
||||
|
||||
|
||||
function _performTransaction($parameters=null)
|
||||
{
|
||||
return $this->query('BEGIN');
|
||||
}
|
||||
|
||||
|
||||
function& _performNewBlob($blobid=null)
|
||||
{
|
||||
$obj =& new DbSimple_Postgresql_Blob($this, $blobid);
|
||||
return $obj;
|
||||
}
|
||||
|
||||
|
||||
function _performGetBlobFieldNames($result)
|
||||
{
|
||||
$blobFields = array();
|
||||
for ($i=pg_num_fields($result)-1; $i>=0; $i--) {
|
||||
$type = pg_field_type($result, $i);
|
||||
if (strpos($type, "BLOB") !== false) $blobFields[] = pg_field_name($result, $i);
|
||||
}
|
||||
return $blobFields;
|
||||
}
|
||||
|
||||
// XTODO: Real PostgreSQL escape
|
||||
function _performGetPlaceholderIgnoreRe()
|
||||
{
|
||||
return '
|
||||
" (?> [^"\\\\]+|\\\\"|\\\\)* " |
|
||||
\' (?> [^\'\\\\]+|\\\\\'|\\\\)* \' |
|
||||
/\* .*? \*/ # comments
|
||||
';
|
||||
}
|
||||
|
||||
function _performGetNativePlaceholderMarker($n)
|
||||
{
|
||||
// PostgreSQL uses specific placeholders such as $1, $2, etc.
|
||||
return '$' . ($n + 1);
|
||||
}
|
||||
|
||||
function _performCommit()
|
||||
{
|
||||
return $this->query('COMMIT');
|
||||
}
|
||||
|
||||
|
||||
function _performRollback()
|
||||
{
|
||||
return $this->query('ROLLBACK');
|
||||
}
|
||||
|
||||
|
||||
function _performTransformQuery(&$queryMain, $how)
|
||||
{
|
||||
|
||||
// If we also need to calculate total number of found rows...
|
||||
switch ($how) {
|
||||
// Prepare total calculation (if possible)
|
||||
case 'CALC_TOTAL':
|
||||
// Not possible
|
||||
return true;
|
||||
|
||||
// Perform total calculation.
|
||||
case 'GET_TOTAL':
|
||||
// XTODO: GROUP BY ... -> COUNT(DISTINCT ...)
|
||||
$re = '/^
|
||||
(?> -- [^\r\n]* | \s+)*
|
||||
(\s* SELECT \s+) #1
|
||||
(.*?) #2
|
||||
(\s+ FROM \s+ .*?) #3
|
||||
((?:\s+ ORDER \s+ BY \s+ .*?)?) #4
|
||||
((?:\s+ LIMIT \s+ \S+ \s* (?: OFFSET \s* \S+ \s*)? )?) #5
|
||||
$/six';
|
||||
$m = null;
|
||||
if (preg_match($re, $queryMain[0], $m)) {
|
||||
$queryMain[0] = $m[1] . $this->_fieldList2Count($m[2]) . " AS C" . $m[3];
|
||||
$skipTail = substr_count($m[4] . $m[5], '?');
|
||||
if ($skipTail) array_splice($queryMain, -$skipTail);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
function _performQuery($queryMain)
|
||||
{
|
||||
$this->_lastQuery = $queryMain;
|
||||
$isInsert = preg_match('/^\s* INSERT \s+/six', $queryMain[0]);
|
||||
|
||||
//
|
||||
// Note that in case of INSERT query we CANNOT work with prepare...execute
|
||||
// cache, because RULEs do not work after pg_execute(). This is a very strange
|
||||
// bug... To reproduce:
|
||||
// $DB->query("CREATE TABLE test(id SERIAL, str VARCHAR(10)) WITH OIDS");
|
||||
// $DB->query("CREATE RULE test_r AS ON INSERT TO test DO (SELECT 111 AS id)");
|
||||
// print_r($DB->query("INSERT INTO test(str) VALUES ('test')"));
|
||||
// In case INSERT + pg_execute() it returns new row OID (numeric) instead
|
||||
// of result of RULE query. Strange, very strange...
|
||||
//
|
||||
|
||||
if ($this->DbSimple_Postgresql_USE_NATIVE_PHOLDERS && !$isInsert) {
|
||||
// Use native placeholders only if PG supports them.
|
||||
$this->_expandPlaceholders($queryMain, true);
|
||||
$hash = md5($queryMain[0]);
|
||||
if (!isset($this->prepareCache[$hash])) {
|
||||
$this->prepareCache[$hash] = true;
|
||||
$prepared = @pg_prepare($this->link, $hash, $queryMain[0]);
|
||||
if ($prepared === false) return $this->_setDbError($queryMain[0]);
|
||||
} else {
|
||||
// Prepare cache hit!
|
||||
}
|
||||
$result = pg_execute($this->link, $hash, array_slice($queryMain, 1));
|
||||
} else {
|
||||
// No support for native placeholders or INSERT query.
|
||||
$this->_expandPlaceholders($queryMain, false);
|
||||
$result = @pg_query($this->link, $queryMain[0]);
|
||||
}
|
||||
|
||||
if ($result === false) return $this->_setDbError($queryMain);
|
||||
if (!pg_num_fields($result)) {
|
||||
if ($isInsert) {
|
||||
// INSERT queries return generated OID (if table is WITH OIDs).
|
||||
//
|
||||
// Please note that unfortunately we cannot use lastval() PostgreSQL
|
||||
// stored function because it generates fatal error if INSERT query
|
||||
// does not contain sequence-based field at all. This error terminates
|
||||
// the current transaction, and we cannot continue to work nor know
|
||||
// if table contains sequence-updateable field or not.
|
||||
//
|
||||
// To use auto-increment functionality you must invoke
|
||||
// $insertedId = $DB->query("SELECT lastval()")
|
||||
// manually where it is really needed.
|
||||
//
|
||||
return @pg_last_oid($result);
|
||||
}
|
||||
// Non-SELECT queries return number of affected rows, SELECT - resource.
|
||||
return @pg_affected_rows($result);
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
|
||||
function _performFetch($result)
|
||||
{
|
||||
$row = @pg_fetch_assoc($result);
|
||||
if (pg_last_error($this->link)) return $this->_setDbError($this->_lastQuery);
|
||||
if ($row === false) return null;
|
||||
return $row;
|
||||
}
|
||||
|
||||
|
||||
function _setDbError($query)
|
||||
{
|
||||
return $this->_setLastError(null, pg_last_error($this->link), $query);
|
||||
}
|
||||
|
||||
function _getVersion()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class DbSimple_Postgresql_Blob extends DbSimple_Generic_Blob
|
||||
{
|
||||
var $blob; // resourse link
|
||||
var $id;
|
||||
var $database;
|
||||
|
||||
function DbSimple_Postgresql_Blob(&$database, $id=null)
|
||||
{
|
||||
$this->database =& $database;
|
||||
$this->database->transaction();
|
||||
$this->id = $id;
|
||||
$this->blob = null;
|
||||
}
|
||||
|
||||
function read($len)
|
||||
{
|
||||
if ($this->id === false) return ''; // wr-only blob
|
||||
if (!($e=$this->_firstUse())) return $e;
|
||||
$data = @pg_lo_read($this->blob, $len);
|
||||
if ($data === false) return $this->_setDbError('read');
|
||||
return $data;
|
||||
}
|
||||
|
||||
function write($data)
|
||||
{
|
||||
if (!($e=$this->_firstUse())) return $e;
|
||||
$ok = @pg_lo_write($this->blob, $data);
|
||||
if ($ok === false) return $this->_setDbError('add data to');
|
||||
return true;
|
||||
}
|
||||
|
||||
function close()
|
||||
{
|
||||
if (!($e=$this->_firstUse())) return $e;
|
||||
if ($this->blob) {
|
||||
$id = @pg_lo_close($this->blob);
|
||||
if ($id === false) return $this->_setDbError('close');
|
||||
$this->blob = null;
|
||||
} else {
|
||||
$id = null;
|
||||
}
|
||||
$this->database->commit();
|
||||
return $this->id? $this->id : $id;
|
||||
}
|
||||
|
||||
function length()
|
||||
{
|
||||
if (!($e=$this->_firstUse())) return $e;
|
||||
|
||||
@pg_lo_seek($this->blob, 0, PGSQL_SEEK_END);
|
||||
$len = @pg_lo_tell($this->blob);
|
||||
@pg_lo_seek($this->blob, 0, PGSQL_SEEK_SET);
|
||||
|
||||
if (!$len) return $this->_setDbError('get length of');
|
||||
return $len;
|
||||
}
|
||||
|
||||
function _setDbError($query)
|
||||
{
|
||||
$hId = $this->id === null? "null" : ($this->id === false? "false" : $this->id);
|
||||
$query = "-- $query BLOB $hId";
|
||||
$this->database->_setDbError($query);
|
||||
}
|
||||
|
||||
// Called on each blob use (reading or writing).
|
||||
function _firstUse()
|
||||
{
|
||||
// BLOB opened - do nothing.
|
||||
if (is_resource($this->blob)) return true;
|
||||
|
||||
// Open or create blob.
|
||||
if ($this->id !== null) {
|
||||
$this->blob = @pg_lo_open($this->database->link, $this->id, 'rw');
|
||||
if ($this->blob === false) return $this->_setDbError('open');
|
||||
} else {
|
||||
$this->id = @pg_lo_create($this->database->link);
|
||||
$this->blob = @pg_lo_open($this->database->link, $this->id, 'w');
|
||||
if ($this->blob === false) return $this->_setDbError('create');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
?>
|
||||
112
lib/Db/DbSimple/my/MyDataBaseLog.php
Executable file
112
lib/Db/DbSimple/my/MyDataBaseLog.php
Executable file
@@ -0,0 +1,112 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Для вывода лога запросов к БД (использовать совместно с DbSimple)
|
||||
*
|
||||
* @author Zmi
|
||||
*/
|
||||
class MyDataBaseLog
|
||||
{
|
||||
private static $dbLog = array();
|
||||
private static $pFuncOnError = NULL;
|
||||
|
||||
/**
|
||||
* Устанавливает функцию на ошибку запроса
|
||||
*/
|
||||
public static function SetFuncOnError($func)
|
||||
{
|
||||
self::$pFuncOnError = $func;
|
||||
}
|
||||
|
||||
/**
|
||||
* Определить функцию на получение ошибки в $info наиболее полезные параметры [query, message, code, context]
|
||||
*/
|
||||
public static function Error($message, $info)
|
||||
{
|
||||
if (!error_reporting())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!empty(self::$pFuncOnError))
|
||||
{
|
||||
call_user_func(self::$pFuncOnError, $message, $info);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Функция логирования запроса
|
||||
*/
|
||||
public static function Log($db, $sql)
|
||||
{
|
||||
$caller = $db->findLibraryCaller();
|
||||
$log = array();
|
||||
$log['q'] = $sql;
|
||||
$log['file'] = $caller['file'];
|
||||
$log['line'] = $caller['line'];
|
||||
$log['time'] = $caller['object']->_statistics['time'];
|
||||
$log['count'] = $caller['object']->_statistics['count'];
|
||||
$log['error'] = $caller['object']->error;
|
||||
$log['errorMsg'] = $caller['object']->errmsg;
|
||||
|
||||
self::$dbLog[] = $log;
|
||||
}
|
||||
|
||||
/**
|
||||
* Показывает лог-табличку
|
||||
*/
|
||||
public static function Render()
|
||||
{
|
||||
ob_start();
|
||||
?>
|
||||
<table id='iDbLogger' cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<th>№</th>
|
||||
<th>query</th>
|
||||
<th>time</th>
|
||||
</tr>
|
||||
<?php
|
||||
$totalTime = 0;
|
||||
$curElem = 0;
|
||||
$maxLen = 125;
|
||||
for ($i = 0, $j = count(self::$dbLog); $i < $j; $i+=2)
|
||||
{
|
||||
$log1 = self::$dbLog[$i];
|
||||
$log2 = isset(self::$dbLog[$i+1]) ? self::$dbLog[$i+1] : array();
|
||||
$isError = empty($log2['error']) ? false : true;
|
||||
|
||||
$execTime = $log2['time'] - $log1['time'];
|
||||
$totalTime += $execTime;
|
||||
$color = $isError ? 'red' : 'green';
|
||||
$error = $log2['error'];
|
||||
$query = $log1['q'];
|
||||
$time = number_format($execTime , 5, '.', ' ');
|
||||
$count = $log1['count'];
|
||||
?>
|
||||
<tr>
|
||||
<td class="num"><?= (int)(++$curElem)?></td>
|
||||
<td style='color: <?= $color?>'>
|
||||
<pre><?= wordwrap($query, $maxLen, PHP_EOL)?></pre>
|
||||
<?php if ($isError):?>
|
||||
<div id='iDataBaseLog_<?= $i?>'><pre><?= wordwrap(print_r($error, true), $maxLen, PHP_EOL)?></pre></div>
|
||||
<?php endif?>
|
||||
</td>
|
||||
<td><?= $time?></td>
|
||||
</tr>
|
||||
<?php
|
||||
if ($isError)
|
||||
{
|
||||
$i++;
|
||||
}
|
||||
}
|
||||
?>
|
||||
<tr class="total">
|
||||
<td colspan='2' class="center"><?= $curElem?> <span>queries</span></td>
|
||||
<td><?= number_format($totalTime, 5, '.', ' ')?></td>
|
||||
</tr>
|
||||
</table>
|
||||
<?php
|
||||
return ob_get_clean();
|
||||
}
|
||||
};
|
||||
?>
|
||||
Reference in New Issue
Block a user