Обновил модуль pdo

This commit is contained in:
Фёдор Подлеснов 2016-06-30 15:10:05 +03:00
parent 0e475190a2
commit bc2541644a

View file

@ -1,7 +1,8 @@
<?php <?php
/** /**
* Êëàññ îáîëî÷êà äëÿ PDO äëÿ çàìåíû Creole * @package system.db
* Класс оболочка для PDO для замены Creole
*/ */
class Database extends PDO class Database extends PDO
{ {
@ -17,9 +18,12 @@ class Database extends PDO
return $this->dsn; return $this->dsn;
} }
/**
* Создает соединение с базой данных
*/
static function getConnection(array $dsn) static function getConnection(array $dsn)
{ {
if ($dsn['phptype'] == 'pgsql') { if ($dsn['phptype'] == 'pgsql' || $dsn['phptype'] == 'mysql') {
$port = (isset($dsn['port'])) ? "port={$dsn['port']};" : ""; $port = (isset($dsn['port'])) ? "port={$dsn['port']};" : "";
$connection = new Database("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']); $connection = new Database("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']);
} }
@ -32,11 +36,14 @@ class Database extends PDO
public function executeQuery($query) public function executeQuery($query)
{ {
$sth = $this->prepare($query); if (isset($_GET['debug'])) {
$sth->setFetchMode(PDO::FETCH_ASSOC); fb($query);
$sth->execute(); }
// print_r($sth->fetchAll()); $stmt = $this->prepare($query);
return $sth;//$sth->fetchAll(); $stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
$stmt->cache = $stmt->fetchAll();
return $stmt;//$sth->fetchAll();
} }
public function prepareStatement($query) public function prepareStatement($query)
@ -44,7 +51,10 @@ class Database extends PDO
return new DatabaseStatement($query, $this); return new DatabaseStatement($query, $this);
} }
// Äëÿ ñîâìåñòèìîñòè ñî ñòàðûì ïðåäñòàâëåíèåì áàç äàííûõ CIS // Для совместимости со старым представлением баз данных CIS
/**
* Извлекает из базы все элементы по запросу
*/
public function fetchAllArray($query) public function fetchAllArray($query)
{ {
$sth = $this->prepare($query); $sth = $this->prepare($query);
@ -53,6 +63,9 @@ class Database extends PDO
return $sth->fetchAll(); return $sth->fetchAll();
} }
/**
* Извлекает из базы первый элемент по запросу
*/
public function fetchOneArray($query) public function fetchOneArray($query)
{ {
$sth = $this->prepare($query); $sth = $this->prepare($query);
@ -61,23 +74,38 @@ class Database extends PDO
return $sth->fetch(); return $sth->fetch();
} }
private function assignQuote($x, $y) private static function assignQuote($x, $y)
{ {
return $x . "=" . $this->quote($y); return $x . "=" . $this->quote($y);
} }
/**
* Создает INSERT запрос
*/
function insertQuery($table, array $values) function insertQuery($table, array $values)
{ {
return $this->query("INSERT INTO $table (" . implode(",", array_keys($values)) return $this->query("INSERT INTO $table (" . implode(",", array_keys($values))
. ") VALUES (" . implode(",", array_map(array($this, 'quote'), array_values($values))) . ")"); . ") VALUES (" . implode(",", array_map(array($this, 'quote'), array_values($values))) . ")");
} }
/**
* Создает UPDATE запрос
*/
function updateQuery($table, array $values, $cond) function updateQuery($table, array $values, $cond)
{ {
return $this->query("UPDATE $table SET " . implode(",", return $this->query("UPDATE $table SET " . implode(",",
array_map(array($this, 'assignQuote'), array_keys($values), array_values($values))) . " WHERE $cond"); array_map(array('self', 'assignQuote'), array_keys($values), array_values($values))) . " WHERE $cond");
} }
function getIdGenerator() {
return new IdGenerator($this);
}
/**
* Замечание: Только для Postgres SQL
* @param string $seq Имя последовательности для ключа таблицы
* @return int Идентефикатор следующей записи
*/
function getNextId($seq) function getNextId($seq)
{ {
$result = $this->fetchOneArray("SELECT nextval('$seq')"); $result = $this->fetchOneArray("SELECT nextval('$seq')");
@ -89,6 +117,30 @@ class Database extends PDO
return null; return null;
} }
} }
class IdGenerator {
private $db;
function __construct($db) {
$this->db = $db;
}
function isBeforeInsert() {
return false;
}
function isAfterInsert() {
return true;
}
function getId($seq) {
// $result = $this->db->fetchOneArray("SELECT nextval('$seq')");
// return $result['nextval'];
$result = $this->db->fetchOneArray("SELECT last_insert_rowid() AS nextval");
return $result['nextval'];
}
}
class PDODatabaseStatementIterator implements Iterator class PDODatabaseStatementIterator implements Iterator
{ {
@ -98,6 +150,7 @@ class PDODatabaseStatementIterator implements Iterator
private $row_count; private $row_count;
private $rs; private $rs;
/** /**
* Construct the iterator. * Construct the iterator.
* @param PgSQLResultSet $rs * @param PgSQLResultSet $rs
@ -110,13 +163,12 @@ class PDODatabaseStatementIterator implements Iterator
function rewind() function rewind()
{ {
// echo 'rewind';
$this->pos = 0; $this->pos = 0;
} }
function valid() function valid()
{ {
return ( $this->pos < $this->row_count ); return ($this->pos < $this->row_count);
} }
function key() function key()
@ -126,7 +178,10 @@ class PDODatabaseStatementIterator implements Iterator
function current() function current()
{ {
return $this->result->fetch(PDO::FETCH_ASSOC); if (!isset($this->result->cache[$this->pos])) {
$this->result->cache[$this->pos] = $this->result->fetch(PDO::FETCH_ASSOC);
}
return $this->result->cache[$this->pos];
} }
function next() function next()
@ -147,10 +202,10 @@ class PDODatabaseStatementIterator implements Iterator
class PDODatabaseStatement extends PDOStatement implements IteratorAggregate class PDODatabaseStatement extends PDOStatement implements IteratorAggregate
{ {
protected $cursorPos = 0; protected $cursorPos = 0;
public $cache = array();
function getIterator() function getIterator()
{ {
// echo 'getiterator';
return new PDODatabaseStatementIterator($this); return new PDODatabaseStatementIterator($this);
} }
@ -159,13 +214,11 @@ class PDODatabaseStatement extends PDOStatement implements IteratorAggregate
function rewind() function rewind()
{ {
// echo 'rewind';
$this->cursorPos = 0; $this->cursorPos = 0;
} }
public function seek($rownum) public function seek($rownum)
{ {
// echo 'seek';
if ($rownum < 0) { if ($rownum < 0) {
return false; return false;
} }
@ -178,38 +231,38 @@ class PDODatabaseStatement extends PDOStatement implements IteratorAggregate
function valid() function valid()
{ {
// echo 'valid';
return ( true ); return ( true );
} }
public function first() public function first()
{ {
// echo 'first';
if($this->cursorPos !== 0) { $this->seek(0); } if($this->cursorPos !== 0) { $this->seek(0); }
return $this->next(); return $this->next();
} }
function next() function next()
{ {
// echo 'next';
if ($this->getRecordCount() > $this->cursorPos) { if ($this->getRecordCount() > $this->cursorPos) {
$this->fields = $this->fetch(PDO::FETCH_ASSOC); if (!isset($this->cache[$this->cursorPos])) {
$this->cache[$this->cursorPos] = $this->fetch(PDO::FETCH_ASSOC);
}
$this->fields = $this->cache[$this->cursorPos];
$this->cursorPos++;
return true;
} else { } else {
$this->fields = null; $this->fields = null;
return false;
} }
// $this->cursorPos++;
return true;
} }
function key() { function key() {
// echo 'key';
return $this->cursorPos; return $this->cursorPos;
} }
function current() function current()
{ {
// echo 'current';
return $this->result->fetch(PDO::FETCH_ASSOC); return $this->result->fetch(PDO::FETCH_ASSOC);
} }
@ -233,20 +286,25 @@ class PDODatabaseStatement extends PDOStatement implements IteratorAggregate
return $this->fields[$name]; return $this->fields[$name];
} }
function getBoolean($name)
{
return (bool)$this->fields[$name];
}
function get($name) function get($name)
{ {
return $this->cursorPos[$name]; return $this->fields[$name];
} }
function getRecordCount() function getRecordCount()
{ {
return $this->rowCount(); return count($this->cache);
} }
} }
/** /**
* Êëàññ îáîëî÷êà äëÿ PDOStatement äëÿ çàìåíû Creole * Класс оболочка для PDOStatement для замены Creole
*/ */
class DatabaseStatement class DatabaseStatement
{ {
@ -274,7 +332,7 @@ class DatabaseStatement
function setBlob($n, $value) function setBlob($n, $value)
{ {
$this->binds [] = array($n, $value, PDO::PARAM_BLOB); $this->binds [] = array($n, $value, PDO::PARAM_LOB);
} }
function setLimit($limit) function setLimit($limit)
@ -290,7 +348,7 @@ class DatabaseStatement
function executeQuery() function executeQuery()
{ {
if ($this->limit) { if ($this->limit) {
$this->queryString .= " LIMIT {$this->limit} OFFSET {$this->offset}"; $this->query .= " LIMIT {$this->limit} OFFSET {$this->offset}";
} }
$stmt = $this->conn->prepare($this->query); $stmt = $this->conn->prepare($this->query);
foreach ($this->binds as $bind) { foreach ($this->binds as $bind) {
@ -299,7 +357,8 @@ class DatabaseStatement
} }
$stmt->setFetchMode(PDO::FETCH_ASSOC); $stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute(); $stmt->execute();
$stmt->cache = $stmt->fetchAll();
return $stmt; return $stmt;
} }
} }