package com.ejlchina.searcher;

import java.io.Closeable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * SQL 执行结果
 */
public class SqlResult<T> implements Closeable {

    /**
     * 检索 SQL 信息
     */
    private final SearchSql<T> searchSql;

    /**
     * 列表查询结果集
     */
    private ResultSet listResult;

    /**
     * 聚合查询结果集
     */
    private ResultSet clusterResult;

    /**
     * 列表查询语句
     */
    private Statement listStatement;

    /**
     * 聚合查询语句
     */
    private Statement clusterStatement;


    public SqlResult(SearchSql<T> searchSql) {
        this.searchSql = searchSql;
    }

    /**
     * 关闭结果集
     */
    @Override
    public void close() {
        try {
            if (listResult != null) {
                listResult.close();
            }
            if (clusterResult != null) {
                clusterResult.close();
            }
            if (listStatement != null) {
                listStatement.close();
            }
            if (clusterStatement != null) {
                clusterStatement.close();
            }
        } catch (SQLException e) {
            throw new SearchException("Can not close statement or resultSet!", e);
        }
    }

    public SearchSql<T> getSearchSql() {
        return searchSql;
    }

    public ResultSet getListResult() {
        return listResult;
    }

    public void setListResult(ResultSet listResult, Statement listStatement) {
        this.listResult = listResult;
        this.listStatement = listStatement;
    }

    public ResultSet getAlreadyClusterResult() throws SQLException {
        if (clusterResult != null) {
            if (clusterResult.isBeforeFirst()) {
                clusterResult.next();
            }
        }
        return clusterResult;
    }

    public void setClusterResult(ResultSet clusterResult, Statement clusterStatement) {
        this.clusterResult = clusterResult;
        this.clusterStatement = clusterStatement;
    }

}

@@ -409,32 +409,114 @@
 clusterResult;%0A%0A
+    // clusterResult %E6%98%AF%E5%90%A6%E5%B7%B2%E6%9C%AA%E6%89%A7%E8%A1%8C%E8%BF%87 next %E6%96%B9%E6%B3%95%0A    private boolean clusterNotReady = true;%0A%0A
     /**%0A     * %E5%88%97
@@ -1760,26 +1760,48 @@
     
-if (cluster
+// %E4%B8%BA%E4%BA%86%E5%85%BC%E5%AE%B9 ShardingSphere%EF%BC%8C%E8%BF%99%E9%87%8C%E4%B8%8D%E8%83%BD%E4%BD%BF%E7%94%A8 
 Result
-.
+Set#
 isBe
@@ -1815,48 +1815,148 @@
 st()
-) %7B%0A                clusterResult.next()
+ %E6%96%B9%E6%B3%95%EF%BC%8C%E5%9B%A0%E4%B8%BA ShardingSphere %E6%B2%A1%E6%9C%89%E5%AE%9E%E7%8E%B0%E5%AE%83%0A            if (clusterNotReady) %7B%0A                clusterResult.next();%0A                clusterNotReady = false
 ;%0A  

优化 JDBC 调用，不使用 ResultSet#isBeforeFirst() 方法，兼容 ShardingShpere