'use strict';

import Base from './base.js';

/**
 * postgres socket class
 * @return {} []
 */
export default class extends Base {
  /**
   * init
   * @param  {Object} config []
   * @return {}        []
   */
  init(config){
    super.init(config);

    config.port = config.port || 5432;
    config.password = config.pwd;
    delete config.pwd;

    this.config = config;
  }
  /**
   * get connection
   * @return {} []
   */
  async getConnection(){
    if(this.connection){
      return this.connection;
    }
    let pg = await think.npm('pg');
    let config = this.config;
    let connectionStr = `postgres://${config.user}:${config.password}@${config.host}:${config.port}/${config.database}`;

    let deferred = think.defer();
    pg.connect(this.config, (err, client, done) => {
      this.logConnect(connectionStr, 'postgre');
      if(err){
        deferred.reject(err);
      }else{
        this.connection = client;
        this.release = done;
        deferred.resolve(client);
      }
    });
    return deferred.promise;
  }
  /**
   * query
   * @return {Promise} []
   */
  async query(sql){
    let connection = await this.getConnection();
    let startTime = Date.now();
    let fn = think.promisify(connection.query, connection);
    let promise = fn(sql).then(data => {
      this.release();
      if (this.config.log_sql) {
        think.log(sql, 'SQL', startTime);
      }
      return data.rows;
    }).catch(err => {
      this.release();
      if (this.config.log_sql) {
        think.log(sql, 'SQL', startTime);
      }
      return Promise.reject(err);
    });
    return think.error(promise);
  }
  /**
   * execute sql
   * @param  {Array} args []
   * @return {Promise}         []
   */
  execute(...args){
    return this.query(...args);
  }
  /**
   * close connection
   * @return {} []
   */
  close(){
    if(this.connection){
      this.connection.end();
      this.connection = null;
    }
  }
}
@@ -698,16 +698,64 @@
 ase%7D%60;%0A%0A
+    return think.await(connectionStr, () =%3E %7B%0A  
     let 
@@ -784,16 +784,18 @@
 ();%0A    
+ 
+ 
 pg.conne
@@ -837,24 +837,26 @@
  =%3E %7B%0A      
+  
 this.logConn
@@ -882,24 +882,26 @@
 'postgre');%0A
+  
       if(err
@@ -903,32 +903,34 @@
 f(err)%7B%0A        
+  
 deferred.reject(
@@ -941,16 +941,18 @@
 ;%0A      
+  
 %7Delse%7B%0A 
@@ -954,24 +954,26 @@
 se%7B%0A        
+ 
+ 
 this.connect
@@ -990,24 +990,26 @@
 nt;%0A        
+  
 this.release
@@ -1017,16 +1017,18 @@
 = done;%0A
+  
         
@@ -1055,26 +1055,30 @@
 ent);%0A      
-%7D%0A
+  %7D%0A  
     %7D);%0A    
@@ -1073,24 +1073,26 @@
     %7D);%0A    
+ 
+ 
 return defer
@@ -1104,16 +1104,24 @@
 romise;%0A
+    %7D);%0A
   %7D%0A  /*

update postgre