{"size": 1462, "ext": "js", "max_stars_repo_path": "index.js", "max_stars_repo_name": "gimenete/pgprom", "max_stars_repo_stars_event_min_datetime": "2016-01-24T18:22:55.000Z", "max_stars_repo_stars_event_max_datetime": "2016-06-01T09:04:41.000Z", "max_issues_repo_path": "index.js", "max_issues_repo_name": "gimenete/pgprom", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "index.js", "max_forks_repo_name": "gimenete/pgprom", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 2, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 23.2063492063, "max_line_length": 54, "alphanum_fraction": 0.487004104}
'use strict'

var pg = require('pg')

function Raw(string) {
  this.toString = function() {
    return string
  }
}

module.exports = function(conString) {

  return {
    query(strings) {
      var sql = ''
      var params = []
      for (var i = 0; i < strings.length-1; i++) {
        let value = arguments[i+1]
        sql += strings[i]
        if (value instanceof Raw) {
          sql += value
        } else if (Array.isArray(value)) {
          for (var i = 0; i < value.length; i++) {
            params.push(value[i])
            if (i > 0) sql+=','
            sql += '$'+params.length
          }
        } else {
          params.push(value)
          sql += '$'+params.length
        }
      }
      sql += strings[strings.length-1]

      return new Promise((resolve, reject) => {
        pg.connect(conString, (err, client, done) => {
          if (err) return reject(err)
          client.query(sql, params, (err, result) => {
            done()
            if (err) return reject(err)
            resolve(result)
          })
        })
      })
    },
    find() {
      return this.query.apply(this, arguments)
        .then((result) => result.rows)
    },
    findOne() {
      return this.query.apply(this, arguments)
        .then((result) => result.rows[0])
    },
    execute() {
      return this.query.apply(this, arguments)
        .then((result) => result.rowCount)
    },
    raw(string) {
      return new Raw(string)
    }
  }
}
