<?php

if (!defined('ZBP_PATH')) {
    exit('Access denied');
}
/**
 * pdo_SQLite数据库操作类.
 */
class Database__PDO_PostgreSQL implements Database__Interface
{

    public $type = 'postgresql';

    public $version = '';

    public $error = array();

    /**
     * @var string|null 数据库名前缀
     */
    public $dbpre = null;

    private $db = null; //数据库连接实例

    /**
     * @var string|null 数据库名
     */
    public $dbname = null;

    /**
     * @var DbSql|null DbSql实例
     */
    public $sql = null;

    /**
     * @var 字符集
     */
    public $charset = 'utf8';

    /**
     * @var 字符排序
     */
    public $collate = null;

    /**
     * 构造函数，实例化$sql参数.
     */
    public function __construct()
    {
        $this->sql = new DbSql($this);
    }

    /**
     * @param $s
     *
     * @return string
     */
    public function EscapeString($s)
    {
        return str_ireplace("'", "''", $s);
    }

    /**
     * 连接数据库.
     *
     * @param array $array 数据库连接配置
     *                     $array=array(
     *                     'pgsql_server',
     *                     'pgsql_username',
     *                     'pgsql_password',
     *                     'pgsql_name',
     *                     'pgsql_pre',
     *                     'pgsql_port',
     *                     'persistent')
     *                     )
     *
     * @return bool
     */
    public function Open($array)
    {
        $array[3] = strtolower($array[3]);
        $s = "pgsql:host={$array[0]};port={$array[5]};dbname={$array[3]};user={$array[1]};password={$array[2]};options='--client_encoding=UTF8'";
        if (false == $array[5]) {
            $db_link = new PDO($s);
        } else {
            $db_link = new PDO($s, null, null, array(PDO::ATTR_PERSISTENT => true));
        }
        $this->db = $db_link;
        $this->dbpre = $array[4];
        $this->dbname = $array[3];
        $myver = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
        $this->version = SplitAndGet($myver, '-', 0);
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);

        return true;
    }

    /**
     * @param string $dbpgsql_server
     * @param string $dbpgsql_port
     * @param string $dbpgsql_username
     * @param string $dbpgsql_password
     * @param string $dbpgsql_name
     */
    public function CreateDB($dbpgsql_server, $dbpgsql_port, $dbpgsql_username, $dbpgsql_password, $dbpgsql_name)
    {
        $dbpgsql_name = strtolower($dbpgsql_name);
        $db_link = new PDO('pgsql:host=' . $dbpgsql_server . ';port=' . $dbpgsql_port, $dbpgsql_username, $dbpgsql_password);
        $this->db = $db_link;
        $this->dbname = $dbpgsql_name;

        $db_link->query("SET client_encoding='UTF-8';");

        $r = $this->db->exec($this->sql->Filter('CREATE DATABASE ' . $dbpgsql_name));
        $this->LogsError();
        return true;
    }

    /**
     * 关闭数据库连接.
     */
    public function Close()
    {
        $this->db = null;
    }

    /**
     * 执行多行SQL语句.
     *
     * @param $s
     */
    public function QueryMulit($s)
    {
        return $this->QueryMulti($s);
    }

    //错别字函数，历史原因保留下来

    public function QueryMulti($s)
    {
        //$a=explode(';',str_replace('%pre%', $this->dbpre, $s));
        $a = explode(';', $s);
        foreach ($a as $s) {
            $s = trim($s);
            if ($s != '') {
                $this->db->exec($this->sql->Filter($s));
                $this->LogsError();
            }
        }
    }

    /**
     * @param $query
     *
     * @return array
     */
    public function Query($query)
    {
        //$query=str_replace('%pre%', $this->dbpre, $query);
        // 遍历出来
        $results = $this->db->query($this->sql->Filter($query));
        $e = $this->db->errorCode();
        if ($e > 0) {
            trigger_error(implode(' ', $this->db->errorInfo()), E_USER_NOTICE);
        }
        $this->LogsError();
        //fetch || fetchAll
        if (is_object($results)) {
            return $results->fetchAll();
        } else {
            return array($results);
        }
    }

    /**
     * @param $query
     *
     * @return bool|pgsql_result
     */
    public function Update($query)
    {
        //$query=str_replace('%pre%', $this->dbpre, $query);
        $r = $this->db->query($this->sql->Filter($query));
        $this->LogsError();
        return $r;
    }

    /**
     * @param $query
     *
     * @return bool|pgsql_result
     */
    public function Delete($query)
    {
        //$query=str_replace('%pre%', $this->dbpre, $query);
        $r = $this->db->query($this->sql->Filter($query));
        $this->LogsError();
        return $r;
    }

    /**
     * @param $query
     *
     * @return int
     */
    public function Insert($query)
    {
        //$query=str_replace('%pre%', $this->dbpre, $query);
        $this->db->query($this->sql->Filter($query));
        $this->LogsError();
        $seq = explode(' ', $query, 4);
        $seq = $seq[2] . '_seq';
        $id = $this->db->lastInsertId($seq);
        return $id;
    }

    /**
     * @param $table
     * @param $datainfo
     */
    public function CreateTable($table, $datainfo, $engine = null, $charset = null, $collate = null)
    {
        $this->QueryMulit($this->sql->CreateTable($table, $datainfo));
    }

    /**
     * @param $table
     */
    public function DelTable($table)
    {
        $this->QueryMulit($this->sql->DelTable($table));
    }

    /**
     * @param $table
     *
     * @return bool
     */
    public function ExistTable($table)
    {
        $a = $this->Query($this->sql->ExistTable($table, $this->dbname));
        if (!is_array($a)) {
            return false;
        }

        $b = current($a);
        if (!is_array($b)) {
            return false;
        }

        $c = (int) current($b);
        if ($c > 0) {
            return true;
        } else {
            return false;
        }
    }

    private function LogsError()
    {
        $e = $this->db->errorCode();
        if ($e > 0) {
            $this->error[] = array($e, $this->db->errorInfo());
        }
    }

    /**
     * 事务处理
     *
     * @param string $query 指令
     *
     * @return bool
     */
    public function Transaction($query)
    {
        if (strcasecmp($query, 'begin') === 0) {
            return $this->db->beginTransaction();
        }
        if (strcasecmp($query, 'commit') === 0) {
            return $this->db->commit();
        }
        if (strcasecmp($query, 'rollback ') === 0) {
            return $this->db->rollBack();
        }
    }

    /**
     * 判断数据表的字段是否存在.
     *
     * @param string $table 表名
     * @param string $field 字段名
     *
     * @return bool
     */
    public function ExistColumn($table, $field)
    {
        $r = null;
        $table = strtolower($table);
        $field = strtolower($field);
        ZBlogException::SuspendErrorHook();
        $s = "SELECT * FROM information_schema.columns WHERE table_schema = 'public' AND table_name = '$table' AND column_name = '$field'";
        $r = @$this->Query($s);
        ZBlogException::ResumeErrorHook();
        if (is_array($r) && count($r) == 0) {
            return false;
        }
        return true;
    }

}
