PDOConnection.php 18 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
<?php
/**
 * Created by PhpStorm.
 * User: Zip
 * Date: 14/11/28
 * Time: 上午1:28
 */

namespace Hood\Dao\Db\PostgreSQL;

use Hood\Core\Root;
use Hood\Debug\DebugException;
use Hood\Core\Server;
use Hood\Dao\Db\PDOMySQL\Result;
use \Closure;
use Hood\Cache as hoodCache;

/**
 * 适配器
 * Class Connection
 * @package Hood\Dao\Db\PostgreSQL
 */
class PDOConnection extends Root
{
    /**
     * 数据库连接池
     * @var array
     */
    protected $_instances = array();

    /**
     * 缓存驱动
     * @var string
     */
    protected $_cacheDrive = array(
        'drive' => 'Memcached',
        'node' => null,
        'child_node' => 'hosts'
    );

    /**
     * 属性
     * @var array
     */
    private $_attribute = array(
        \PDO::ATTR_CASE => \PDO::CASE_NATURAL,
        \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION
    );


    /**
     * 设置指定集合字段
     * @var int
     */
    private $_columnNumber = 0;

    /**
     * 数据库读取模式
     * @var array
     */
    private $_modality = null;

    /**
     * FETCH_CLASS 专用 class name
     * @var null
     */
    protected $_className = null;

    /**
     *
     * @var \PDOStatement
     */
    protected $_PDOStatement;


    /**
     *
     * @var \PDO
     */
    protected $_PDOConn;


    /**
     * 数据类型
     * @var array
     */
    protected $paramType = array(
        'bool' => \PDO::PARAM_BOOL,
        'boolean' => \PDO::PARAM_BOOL,
        'null' => \PDO::PARAM_NULL,
        'integer' => \PDO::PARAM_INT,
        'int' => \PDO::PARAM_INT,
        'string' => \PDO::PARAM_STR,
        'stmt' => \PDO::PARAM_STMT,
        'object' => \PDO::PARAM_LOB,
        'float' => \PDO::PARAM_STR,
        'double' => \PDO::PARAM_STR,
        'output' => \PDO::PARAM_INPUT_OUTPUT
    );

    protected $_database;

    /**
     * 写模式
     */
    const MODALITY_WRITE = 'write';

    /**
     * 读取模式
     */
    const MODALITY_READ = 'read';


    public function __construct($database)
    {
        parent::__construct();
        $this->_database = $database;
    }

    /**
     * 强制设置数据库连接方式
     * @param $modality
     * @return $this
     */
    public function setModality($modality)
    {
        $this->_modality = $modality;
        return $this;
    }

    /**
     * 创建PDO数据库对象
     * @param string $modality (write/read)
     * @return \PDO
     * @throws DebugException
     */
    public function connect($modality = 'write')
    {
        if ($this->_modality != null) $modality = $this->_modality;
        $connectKey = $this->_database . '_' . $modality;
        if (!isset($this->instances[$connectKey])) {
            $server = $this->getServerHost('db');
            $_serverConfig = $server->getServerConfig('database', $this->_database);
            $_dbConfig = $server->getServerConfig('postgre');
            if (!isset($_serverConfig[$modality]) || !in_array($modality, array('write', 'read'))) {
                throw new DebugException('PostgreSQL db:' . $this->_database . ' Not Modality ' . $modality);
            }
            $_server = $server->getServerMap($_serverConfig[$modality], Server::SERVER_SELECT_MODEL_RAND);
            if (empty($_server)) {
                throw new DebugException('Db:' . $this->_database . ' Server is null.');
            }
            $charset = isset($_dbConfig['charset']) ? $_dbConfig['charset'] : 'UTF8';
            #如果设置了 dbname 使用 配置的
            $dbname = isset($_serverConfig['dbname']) ? $_serverConfig['dbname'] : $this->_database;
            $dsn = 'pgsql:host=' . $_server['host'] . ';port=' . $_server['port'] . ';dbname=' . $dbname;

            $options = array(
                \PDO::ATTR_PERSISTENT => isset($_dbConfig['persistent']) ? $_dbConfig['persistent'] : false,
                \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES " . $charset
            );
            try {
                $_connection = new \PDO($dsn, $_serverConfig['username'], $_serverConfig['passwd'], $options);
            } catch (\Exception $e) {
                $_connection = null;
                throw new DebugException($dsn . ' error ' . $e->getMessage());
            }

            foreach ($this->_attribute as $key => $val) {
                $_connection->setAttribute($key, $val);
            }
            $this->instances[$connectKey] = $_connection;
        }
        $this->_modality = null;
        return $this->instances[$connectKey];
    }

    /**
     * 设置属性
     * @param $attribute
     * @param $value
     * @return $this
     */
    public function setAttribute($attribute, $value)
    {
        $this->_attribute[$attribute] = $value;
        return $this;
    }

    /**
     * 单例事务处理
     * @param callable $callback
     * @return mixed
     * @throws DebugException
     * @throws \Exception
     */
    public function transaction(Closure $callback)
    {
        $this->beginTransaction();
        try {
            $result = $callback($this);
            $this->commit();
        } catch (DebugException $e) {
            $this->rollBack();
        }
        return $result;
    }

    /**
     * 开启事务
     * @throws DebugException
     */
    public function beginTransaction()
    {
        $this->connect()->beginTransaction();
    }

    /**
     * 提交事务
     * @throws DebugException
     */
    public function commit()
    {
        $this->connect()->commit();
    }

    /**
     * 判断是否有事务开启
     * @return bool
     * @throws DebugException
     */
    public function inTransaction()
    {
        return $this->connect()->inTransaction();
    }

    /**
     * 回滚
     * @throws DebugException
     */
    public function rollBack()
    {
        $this->connect()->rollBack();
    }

    /**
     * 禁用的命令
     * @var array
     */
    private $disableCommands = array('select', 'insert', 'delete', 'update');

    /**
     * 检查禁用参数
     * @param $str
     * @return bool
     */
    protected function checkDisableCommands($str)
    {
        foreach ($this->disableCommands as $command) {
            if (stristr($str, $command) !== false) {
                return false;
            }
        }
        return true;
    }

    /**
     * 替换SQL的替换参数
     * @param $sql
     * @param array $replaceMap
     * @return string
     * @throws DebugException
     */
    protected function makeReplaceMapToSql($sql, array $replaceMap)
    {
        $_replaceMap = array();
        foreach ($replaceMap as $key => $value) {
            if (!is_string($value)) {
                throw new DebugException('替换参数值不能为数组.');
            }
            if ($this->checkDisableCommands($value) == false) {
                //throw new DebugException('替换参数包括了禁用sql方法.');
            }
            $_replaceMap["#" . $key . "#"] = $value;
        }
        return strtr($sql, $_replaceMap);
    }

    /**
     * @param $sql
     * @param $parameterMap
     * @param $replaceMap
     * @return \PDOStatement
     * @throws DebugException
     */
    protected function _statement($sql, $parameterMap, $replaceMap)
    {
        $sql = $this->makeReplaceMapToSql($sql, $replaceMap);
        $this->_PDOConn = $conn = $this->connect();
        $this->_PDOStatement = $stmt = $conn->prepare($sql);
        $this->bindValues($parameterMap, $stmt);
        $stmt->execute();
        return $stmt;
    }

    /**
     * 执行SQL
     * @param $sql
     * @param $parameterMap
     * @throws DebugException
     */
    public function execute($sql, array $parameterMap = array())
    {
        $this->_PDOConn = $conn = $this->connect();
        $this->_PDOStatement = $stmt = $conn->prepare($sql);
        $this->bindValues($parameterMap, $stmt);
        $stmt->execute();
    }

    /**
     * 绑定一组数据
     * @param array $params
     * @param \PDOStatement $stmt
     * @throws DebugException
     */
    private function bindValues(array $params, \PDOStatement $stmt)
    {
        foreach ($params as $parameter => $value) {
            if (is_array($value) || is_object($value)) {
                throw new DebugException('Sql绑定参数不能为数组或对象.');
            }
            $dataType = $this->paramType [strtolower(gettype($value))];
            $stmt->bindValue($parameter, $value, $dataType);
        }
    }

    /**
     * 插入数据
     * @param $sql
     * @param array $parameterMap
     * @param array $replaceMap
     * @return Result
     */
    public function insert($sql, array $parameterMap = array(), array $replaceMap = array())
    {
        $this->_statement($sql, $parameterMap, $replaceMap);
        return new Result($this->_PDOConn, $this->_PDOStatement);
    }

    /**
     * 更新数据
     * @param string $sql
     * @param array $parameterMap
     * @param array $replaceMap
     * @return Result
     */
    public function update($sql, $parameterMap = array(), $replaceMap = array())
    {
        $this->_statement($sql, $parameterMap, $replaceMap);
        return new Result($this->_PDOConn, $this->_PDOStatement);
    }

    /**
     * 删除数据
     * @param string $sql
     * @param array $parameterMap
     * @param array $replaceMap
     * @return Result
     */
    public function delete($sql, $parameterMap = array(), $replaceMap = array())
    {
        $this->_statement($sql, $parameterMap, $replaceMap);
        return new Result($this->_PDOConn, $this->_PDOStatement);
    }

    /**
     * 原生Query
     * @param $sql
     * @return \PDOStatement
     * @throws DebugException
     */
    public function query($sql)
    {
        return $this->connect('read')->query($sql);
    }

    /**
     * 取回结果集中所有字段的值,作为关联数组返回  第一个字段作为码
     * @param $sql
     * @param array $parameterMap
     * @param array $replaceMap
     * @return array
     */
    public function fetchAssoc($sql, $parameterMap = array(), $replaceMap = array())
    {
        $stmt = $this->_statement($sql, $parameterMap, $replaceMap);
        $data = array();
        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
            $tmp = array_values(array_slice($row, 0, 1));
            $data[$tmp[0]] = $row;
        }
        return $data;
    }

    /**
     * 设置结果集的Class
     * @param null $className
     * @return $this
     */
    public function setFetchClass($className = null)
    {
        $this->_className = (string)$className;
        return $this;
    }

    /**
     * 取回结果集中所有字段的值以对象形式输出,按自定义class
     * @param $sql
     * @param array $parameterMap
     * @param array $replaceMap
     * @return array
     */
    public function fetchClass($sql, $parameterMap = array(), $replaceMap = array())
    {
        return $this->_statement($sql, $parameterMap, $replaceMap)->fetchAll(\PDO::FETCH_CLASS, $this->_className);
    }


    /**
     * 取回结果集中所有字段的值以对象形式输出,按自定义class
     * @param $sql
     * @param array $parameterMap
     * @param array $replaceMap
     * @return array
     */
    public function fetchClassRow($sql, $parameterMap = array(), $replaceMap = array())
    {
        $stmt = $this->_statement($sql, $parameterMap, $replaceMap);
        $stmt->setFetchMode(\PDO::FETCH_CLASS, $this->_className);
        return $stmt->fetch();
    }

    /**
     * 关闭游标,使语句能再次被执行
     * @return $this
     */
    public function closeCursor()
    {
        $this->_PDOStatement->closeCursor();
        return $this;
    }

    /**
     * 返回结果集中的列数
     * @param $sql
     * @param array $parameterMap
     * @param array $replaceMap
     * @return int
     */
    public function columnCount($sql, $parameterMap = array(), $replaceMap = array())
    {
        return $this->_statement($sql, $parameterMap, $replaceMap)->columnCount();
    }

    /**
     * 打印一条 SQL 预处理命令
     * @param $sql
     * @param $parameterMap
     * @param $replaceMap
     * @return bool
     */
    public function debugDumpParams($sql, $parameterMap = array(), $replaceMap = array())
    {
        return $this->_statement($sql, $parameterMap, $replaceMap)->debugDumpParams();
    }


    /**
     * 获取所有数据集合
     * @param $sql
     * @param array $parameterMap
     * @param array $replaceMap
     * @return array
     */
    public function fetchAll($sql, $parameterMap = array(), $replaceMap = array())
    {
        return $this->_statement($sql, $parameterMap, $replaceMap)->fetchAll(\PDO::FETCH_ASSOC);
    }

    /**
     * 获取一条数据集合
     * @param $sql
     * @param array $parameterMap
     * @param array $replaceMap
     * @return mixed
     */
    public function fetchRow($sql, $parameterMap = array(), $replaceMap = array())
    {
        return $this->_statement($sql, $parameterMap, $replaceMap)->fetch(\PDO::FETCH_ASSOC);
    }

    /**
     * 取回一个相关数组
     * 第一个字段值为key
     * @param $sql
     * @param array $parameterMap
     * @param array $replaceMap
     * @return array
     */
    public function fetchPairs($sql, $parameterMap = array(), $replaceMap = array())
    {
        $stmt = $this->_statement($sql, $parameterMap, $replaceMap);;
        $data = array();
        while ($row = $stmt->fetch(\PDO::FETCH_NUM)) {
            $data[$row[0]] = $row[1];
        }
        return $data;
    }

    /**
     * 取回第一个字段值
     * @param $sql
     * @param array $parameterMap
     * @param array $replaceMap
     * @return string
     */
    public function fetchOne($sql, $parameterMap = array(), $replaceMap = array())
    {
        return $this->_statement($sql, $parameterMap, $replaceMap)->fetchColumn(0);
    }

    /**
     * 字符转义
     * @param $value
     * @return string
     */
    public function quoteStr($value)
    {
        if (is_int($value)) {
            return $value;
        } elseif (is_float($value)) {
            return sprintf('%F', $value);
        }
        return "'" . addcslashes($value, "\000\n\r\\'\"\032") . "'";
    }

    /**
     * 字符转换
     * @param $string
     * @param \PDO $parameterType
     * @return string
     * @throws DebugException
     */
    public function quote($string, $parameterType = \PDO::PARAM_STR)
    {
        return $this->connect('read')->quote($string, $parameterType);
    }

    /**
     * 获取指定字段值
     * @param $sql
     * @param array $parameterMap
     * @param array $replaceMap
     * @return string
     */
    public function fetchColumn($sql, $parameterMap = array(), $replaceMap = array())
    {
        return $this->_statement($sql, $parameterMap, $replaceMap)->fetchColumn($this->_columnNumber);
    }

    /**
     * 取回所有结果行的第一个字段名
     * @param $sql
     * @param array $parameterMap
     * @param array $replaceMap
     * @return string
     */
    public function fetchCol($sql, $parameterMap = array(), $replaceMap = array())
    {
        return $this->_statement($sql, $parameterMap, $replaceMap)->fetchAll(\PDO::FETCH_COLUMN, 0);
    }

    /**
     * 设置指定集合数据字段
     * @param $columnNumber
     * @return $this
     */
    public function setFetchColumn($columnNumber)
    {
        $this->_columnNumber = (int)$columnNumber;
        return $this;
    }

    /**
     * 取回结果集中所有字段的值 以对象形式输出
     * @param $sql
     * @param array $parameterMap
     * @param array $replaceMap
     * @return mixed
     */
    public function fetchObject($sql, $parameterMap = array(), $replaceMap = array())
    {
        return $this->_statement($sql, $parameterMap, $replaceMap)->fetchObject($this->_className);
    }

    /**
     * 获取SQL
     * @param $sql
     * @param array $parameterMap
     * @param array $replaceMap
     * @return mixed|string
     * @throws DebugException
     */
    public function getSQL($sql, $parameterMap = array(), $replaceMap = array())
    {
        $sql = $this->makeReplaceMapToSql($sql, $replaceMap);
        if (strstr($sql, ':')) {
            $matches_s = array();
            foreach ($parameterMap as $key => $val) {
                if (is_string($val)) {
                    $val = "'{$val}'";
                }
                $matches_s[':' . $key] = $val;
            }
            $asSql = strtr($sql, $matches_s);
        } else {
            $asSql = $sql;
            foreach ($parameterMap as $val) {
                $strPos = strpos($asSql, '?');
                if (is_string($val)) {
                    $val = "'{$val}'";
                }
                $asSql = substr_replace($asSql, $val, $strPos, 1);
            }
        }
        return $asSql;
    }

    /**
     * 缓存tag
     * @param $tagName
     * @return $this
     */
    public function tag($tagName)
    {
        $this->_cacheTagName = $tagName;
        return $this;
    }


    /**
     * 删除多个tag时用到
     */
    public function delTags()
    {
        $this->_delTags = func_get_args();
    }

    /**
     * 缓存key
     * @param string $key
     * @param null $prefix
     * @return $this
     */
    public function key($key)
    {
        $this->_cacheKey = (string)$key;
        return $this;
    }

    /**
     * 缓存时间
     * @param $expire
     * @return $this
     */
    public function expire($expire)
    {
        $this->_cacheExpire = (int)$expire;
        return $this;
    }

    /**
     * 设置缓存
     * @param bool $status
     * @param string $drive
     * @return $this
     */
    public function cache($status = true, array $drive = array())
    {
        if (isset($drive['drive'])) {
            $this->_cacheDrive['drive'] = $drive['drive'];
        }
        if (isset($drive['drive'])) {
            $this->_cacheDrive['node'] = $drive['node'];
        }
        if (isset($drive['drive'])) {
            $this->_cacheDrive['child_node'] = $drive['child_node'];
        }
        $this->_cacheStatus = (bool)$status;
        return $this;
    }

    /**
     * 重置参数
     */
    private function _resetParameter()
    {

    }

    public function __destruct()
    {
        foreach ($this->instances as $connectKey) {
            $this->instances[$connectKey] = null;
        }
    }
}