package org.treeleaf.db;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.treeleaf.common.bean.FastBeanUtils;
import org.treeleaf.db.handler.AnnotationBeanListHandler;
import org.treeleaf.db.meta.DBColumnMeta;
import org.treeleaf.db.meta.DBTableMeta;
import org.treeleaf.db.meta.DBTableMetaFactory;
import org.treeleaf.db.model.Model;
import org.treeleaf.db.model.example.Example;
import org.treeleaf.db.sql.AnalyzeResult;
import org.treeleaf.db.sql.SqlAnalyzer;
import org.treeleaf.db.sql.SqlAnalyzerFactory;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * MySql数据库操作器
 *
 * @Author leaf
 * 2015/1/11 0011 1:02.
 */
public class MySqlDBModelOperator extends DefaultDBOperator {

    private Logger log = LoggerFactory.getLogger(MySqlDBModelOperator.class);

    protected SqlAnalyzer sqlAnalyzer = null;

    public MySqlDBModelOperator() {
        this.sqlAnalyzer = SqlAnalyzerFactory.getSqlAnalyzer(DBType.MYSQL);
    }

    /**
     * 保存数据
     *
     * @param model
     */
    public Serializable save(Object model, Connection... connection) {
        if (model == null) {
            log.warn("更新数据失败,传入的model对象为null");
            return null;
        }

        DBTableMeta dbTableMeta = DBTableMetaFactory.getDBTableMeta(model.getClass());
        AnalyzeResult analyzeResult = getSqlAnalyzer().analyzeInsert(dbTableMeta, model);

        printSQL(analyzeResult.getSql(), analyzeResult.getParams());

        Connection conn = connection.length > 0 ? connection[0] : ConnectionContext.getConnection();

        QueryRunner queryRunner = new QueryRunner();
        try {
            queryRunner.update(conn, analyzeResult.getSql(), analyzeResult.getParams());

            if (dbTableMeta.getPrimaryKeys().size() == 1
                    && dbTableMeta.getPrimaryKeys().get(0).isAutoIncremen()) {
                Object id = queryRunner.query(conn, "SELECT LAST_INSERT_ID()", new ScalarHandler(1));
                Field field = dbTableMeta.getPrimaryKeys().get(0).getField();
                FastBeanUtils.setFieldValue(field, model, id);
                return (Serializable) id;
            } else {
                DBColumnMeta pk = dbTableMeta.getPrimaryKeys().get(0);
                return (Serializable) FastBeanUtils.getFieldValue(pk.getField(), model);
            }

        } catch (SQLException e) {
            throw new RuntimeException("保存数据失败", e);
        }

    }

    /**
     * 通过表达式查询数据
     *
     * @param example
     * @param classz
     * @param connection
     * @param <T>
     * @return
     */
    public <T extends Model> List<T> findByExample(Example example, Class<T> classz, Connection... connection) {
        DBTableMeta dbTableMeta = DBTableMetaFactory.getDBTableMeta(classz);
        AnalyzeResult analyzeResult = getSqlAnalyzer().analyzeSelectByExample(dbTableMeta, example);
        printSQL(analyzeResult.getSql(), analyzeResult.getParams());

        Connection conn = connection.length > 0 ? connection[0] : ConnectionContext.getConnection();

        QueryRunner queryRunner = new QueryRunner();
        try {
            return queryRunner.query(conn, analyzeResult.getSql(), new AnnotationBeanListHandler<>(classz), analyzeResult.getParams());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public SqlAnalyzer getSqlAnalyzer() {
        return this.sqlAnalyzer;
    }

    protected void printSQL(String sql, Object[] params) {
        Object[] newParam = new Object[params.length];
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        for (int i = 0; i < params.length; i++) {
            if (params[i] instanceof Date) {
                newParam[i] = dateFormat.format(params[i]);
            } else {
                newParam[i] = params[i];
            }
        }
        log.info("sql:[{}]; param:[{}]", sql, Arrays.toString(newParam));
    }

}

@@ -228,16 +228,52 @@
 nUtils;%0A
+import org.treeleaf.common.safe.ID;%0A
 import o
@@ -698,40 +698,8 @@
 le;%0A
-import java.lang.reflect.Field;%0A
 impo
@@ -1555,24 +1555,370 @@
 etClass());%0A
+        DBColumnMeta pk = dbTableMeta.getPrimaryKeys().get(0);%0A        if (dbTableMeta.getPrimaryKeys().size() == 1) %7B%0A            if (FastBeanUtils.getFieldValue(pk.getField(), model) == null && !pk.isAutoIncremen()) %7B//%E9%9D%9E%E6%95%B0%E6%8D%AE%E5%BA%93%E8%87%AA%E5%A2%9E%E7%9A%84%E4%B8%BB%E9%94%AE,%E5%A6%82%E6%9E%9C%E6%B2%A1%E4%BC%A0,%E5%88%99%E8%87%AA%E5%8A%A8%E7%94%9F%E6%88%90%E4%B8%80%E4%B8%AA%0A                FastBeanUtils.setFieldValue(pk.getField(), model, ID.get());%0A            %7D%0A        %7D%0A%0A
         Anal
@@ -2385,87 +2385,65 @@
 == 1
-%0A                    && dbTableMeta.getPrimaryKeys().get(0).isAutoIncremen()) %7B
+ && pk.isAutoIncremen()) %7B//%E5%AF%B9%E4%BA%8E%E5%9F%BA%E4%BA%8Emysql%E6%95%B0%E6%8D%AE%E5%BA%93%E8%87%AA%E5%A2%9E%E7%9A%84%E4%B8%BB%E9%94%AE,%E8%BF%99%E9%87%8C%E6%9F%A5%E5%87%BA%E6%9D%A5,%E5%B9%B6%E8%AE%BE%E5%80%BC%E5%9B%9E%E5%8E%BB
 %0A   
@@ -2545,86 +2545,8 @@
 ));%0A
-                Field field = dbTableMeta.getPrimaryKeys().get(0).getField();%0A
     
@@ -2589,13 +2589,21 @@
 lue(
-f
+pk.getF
 ield
+()
 , mo
@@ -2679,79 +2679,8 @@
 e %7B%0A
-                DBColumnMeta pk = dbTableMeta.getPrimaryKeys().get(0);%0A
     

添加当mode在save时如果主键只有一个,且为null,也不是数据库自增长的时候,自动调用ID.get()方法设置一个进去