<?php
/*
* Copyright (c) 2017 Baidu.com, Inc. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace PhpLife\Library;
require_once 'Medoo/Medoo.php';

use \Medoo\Medoo;
use PhpLife\Config\Postgres\Core;

/**
 * Medoo数据库操作
 */
class Postgres
{
    public static $instance;

    /**
     * @var Medoo
     */
    public $postgres;

    public function __construct()
    {
        $this->connect();
    }

    public static function getInstance()
    {
        if (!isset(self::$instance)) {
            $instance = new self();
            self::$instance = $instance;
        } else {
            $instance = self::$instance;
        }
        return $instance;
    }

    public function select($table,$where=[],$column='*',$limit=10,$offset=0,$order=null){
        if ($limit){
            $where['LIMIT']=[$offset,$limit];
        }
        if ($order){
            $where['ORDER']=$order;
        }
        //'t_article', "*",['LIMIT'=>[4,2],'ORDER'=>'articleno']
        return $this->postgres->select($table,$column,$where);
    }

    public function connect()
    {
        $confg = Core::getData();
        $this->postgres = new medoo([
            // 必须配置项
            'database_type' => 'pgsql',
            'database_name' => $confg['dbname'],
            'server' => $confg['host'],
            'username' => $confg['username'],
            'password' => $confg['password'],
            'charset' => 'utf8',

            // 可选参数
            'port' => $confg['port'],

            // 连接参数扩展, 更多参考 http://www.php.net/manual/en/pdo.setattribute.php
            'option' => [
                \PDO::ATTR_CASE => \PDO::CASE_NATURAL
            ]
        ]);
    }

}
