var util = require('util');
var Service = require('Service');
var utils = require('utils');
var Dao = require('Dao');

/**
 * 执行SQL语句
 */
var exeSql = function() { 
  Service.call(this);
  this.sqlInject.exclude = ['sql'];
};

util.inherits(exeSql, Service);

module.exports = exeSql;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
exeSql.prototype.process =  function(req, res) {
  req.sql = utils.trimStr(req.sql);
  if(!req.sql) {
    this.onLogicError(1, '请提供SQL语句！');
    return;
  }

  var dao = new Dao(this);
  var self = this;
	if(req.sql.trim().toLowerCase().indexOf('delete')==0 
     && req.sql.toLowerCase().indexOf(' where ')<0){
    this.onLogicError(1, '不允许全表删除');
    return;
	}
	if(req.sql.trim().toLowerCase().indexOf('update')==0 
     && req.sql.toLowerCase().indexOf(' where ')<0){
    this.onLogicError(1, '不允许全表更新');
    return;
	}
  if(req.sql.trim().toLowerCase().indexOf('select')==0 
     && req.sql.toLowerCase().indexOf(' limit ')<0)
    req.sql += ' limit 100';
  dao.execute(req.sql, null, function(ret) {
    if(ret.length) {
      res.dataset = {
        columns: [],
        rows: []
      };
      for(var i=0;i<ret.length;i++) {
        let row = ret[i];
        if(i==0) {
          for(var p in row) {
            res.dataset.columns.push(p);
          }
        }
        let arr = [];
        for(var p in row) {
          arr.push(row[p]);
        }
        res.dataset.rows.push(arr);
      }
    } else {
      res.ret = ret;
    }
    console.log(ret);
	  self.end(res);
  });
};