Рефакторинг

This commit is contained in:
origami11 2017-02-17 15:08:12 +03:00
parent 1b5852cc43
commit 981a1d0f0f
11 changed files with 626 additions and 270 deletions

View file

@ -1,23 +1,24 @@
<?php
///<reference path="database/pdostatement.php" />
require_once "database/pdostatement.php";
/**
* @package system.db
* Класс оболочка для PDO для замены Creole
*/
class Database extends PDO
{
public function __construct($dsn, $username = false, $password = false)
public $dsn;
public function __construct($dsn, $username = null, $password = null)
{
parent::__construct($dsn, $username, $password);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('PDODatabaseStatement', array()));
$this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('Database_PDOStatement', array()));
}
public function getDSN()
{
return $this->dsn;
}
public function isPostgres(){
return ($this->dsn["phptype"] == "pgsql");
}
@ -26,30 +27,43 @@ class Database extends PDO
*/
static function getConnection(array $dsn)
{
if ($dsn['phptype'] == 'pgsql' || $dsn['phptype'] == 'mysql') {
$port = (isset($dsn['port'])) ? "port={$dsn['port']};" : "";
$connection = new Database("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']);
$connection->query('SET client_encoding = "UTF-8"');
/*.Database.*/$connection = new static("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']);
if ($dsn['phptype'] == 'pgsql') {
$connection->query('SET client_encoding="UTF-8"');
}
}
if ($dsn['phptype'] == 'sqlite') {
$connection = new Database("{$dsn['phptype']}:{$dsn['database']}");
/*.Database.*/$connection = new static("{$dsn['phptype']}:{$dsn['database']}");
$connection->setAttribute(PDO::ATTR_TIMEOUT, 5);
$mode = defined('SQLITE_JOURNAL_MODE') ? SQLITE_JOURNAL_MODE : 'WAL';
$connection->query("PRAGMA journal_mode=$mode");
if(!function_exists('sqliteLower')){
function sqliteLower($str) {
return mb_strtolower($str, 'UTF-8');
}
$connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1);
}
}
$connection->dsn = $dsn;
return $connection;
}
public function executeQuery($query)
public function executeQuery($query, $values=null)
{
$stmt = $this->prepare($query);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
$stmt->cache = $stmt->fetchAll();
return $stmt;//$sth->fetchAll();
/*.Database_PDOStatement.*/$stmt = $this->prepare($query);
$stmt->execute($values);
$stmt->cache = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $stmt;
}
public function prepareStatement($query)
{
return new DatabaseStatement($query, $this);
return new Database_Statement($query, $this);
}
// Для совместимости со старым представлением баз данных CIS
@ -58,7 +72,7 @@ class Database extends PDO
*/
public function fetchAllArray($query,$values=null)
{
$sth = $this->prepare($query);
/*.Database_PDOStatement.*/$sth = $this->prepare($query);
$prep = $this->prepareValues($values);
$sth->execute($prep);
return $sth->fetchAll(PDO::FETCH_ASSOC);
@ -69,13 +83,13 @@ class Database extends PDO
*/
public function fetchOneArray($query,$values=null)
{
$sth = $this->prepare($query);
/*.Database_PDOStatement.*/$sth = $this->prepare($query);
$prep = $this->prepareValues($values);
$sth->execute($prep);
return $sth->fetch(PDO::FETCH_ASSOC);
}
private function assignQuote($x, $y)
private static function assignQuote($x, $y)
{
return $x . "=" . $this->quote($y);
}
@ -136,12 +150,17 @@ class Database extends PDO
*/
function updateQuery($table, array $values, $cond)
{
return $this->query("UPDATE $table SET " . implode(",",
array_map(array($this, 'assignQuote'), array_keys($values), array_values($values))) . " WHERE $cond");
$prep = $this->prepareValues($values);
$sql = "UPDATE $table SET " . implode(",",
array_map(function($k,$v){return $k."=".$v;}, array_keys($values), array_keys($prep))) . " WHERE $cond";
$stmt = $this->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute($prep);
}
function getIdGenerator() {
return new IdGenerator($this);
return new Database_IdGenerator($this);
}
/**
@ -149,8 +168,7 @@ class Database extends PDO
* @param string $seq Имя последовательности для ключа таблицы
* @return int Идентефикатор следующей записи
*/
function getNextId($seq)
{
function getNextId($seq) {
$result = $this->fetchOneArray("SELECT nextval('$seq')");
return $result['nextval'];
}
@ -160,249 +178,3 @@ class Database extends PDO
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
{
private $result;
private $pos = 0;
private $fetchmode;
private $row_count;
private $rs;
/**
* Construct the iterator.
* @param PgSQLResultSet $rs
*/
public function __construct($rs)
{
$this->result = $rs;
$this->row_count = $rs->getRecordCount();
}
function rewind()
{
$this->pos = 0;
}
function valid()
{
return ($this->pos < $this->row_count);
}
function key()
{
return $this->pos;
}
function current()
{
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()
{
$this->pos++;
}
function seek ( $index )
{
$this->pos = $index;
}
function count ( ) {
return $this->row_count;
}
}
class PDODatabaseStatement extends PDOStatement implements IteratorAggregate
{
protected $cursorPos = 0;
public $cache = array();
public $fields;
function getIterator()
{
return new PDODatabaseStatementIterator($this);
}
protected function __construct() {
}
function rewind()
{
$this->cursorPos = 0;
}
public function seek($rownum)
{
if ($rownum < 0) {
return false;
}
// PostgreSQL rows start w/ 0, but this works, because we are
// looking to move the position _before_ the next desired position
$this->cursorPos = $rownum;
return true;
}
function valid()
{
return ( true );
}
public function first()
{
if($this->cursorPos !== 0) { $this->seek(0); }
return $this->next();
}
function next()
{
if ($this->getRecordCount() > $this->cursorPos) {
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 {
$this->fields = null;
return false;
}
}
function key() {
return $this->cursorPos;
}
function current()
{
return $this->result->fetch(PDO::FETCH_ASSOC);
}
function getRow()
{
return $this->fields;
}
function getInt($name)
{
return intval($this->fields[$name]);
}
function getBlob($name)
{
return $this->fields[$name];
}
function getString($name)
{
return $this->fields[$name];
}
function getBoolean($name)
{
return (bool)$this->fields[$name];
}
function get($name)
{
return $this->fields[$name];
}
function getRecordCount()
{
return count($this->cache);
}
}
/**
* Класс оболочка для PDOStatement для замены Creole
*/
class DatabaseStatement
{
protected $limit = null;
protected $offset = null;
protected $statement = null;
protected $binds = array();
protected $conn;
protected $query;
function __construct($query, $conn) {
$this->query = $query;
$this->conn = $conn;
}
function setInt($n, $value)
{
$this->binds [] = array($n, $value, PDO::PARAM_INT);
}
function setString($n, $value)
{
$this->binds [] = array($n, $value, PDO::PARAM_STR);
}
function setBlob($n, $value)
{
$this->binds [] = array($n, $value, PDO::PARAM_LOB);
}
function setLimit($limit)
{
$this->limit = $limit;
}
function setOffset($offset)
{
$this->offset = $offset;
}
function executeQuery()
{
if ($this->limit) {
$this->query .= " LIMIT {$this->limit} OFFSET {$this->offset}";
}
$stmt = $this->conn->prepare($this->query);
foreach ($this->binds as $bind) {
list($n, $value, $type) = $bind;
$stmt->bindValue($n, $value, $type);
}
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
$stmt->cache = $stmt->fetchAll();
return $stmt;
}
}