ShardingPreparedStatement.java 7.8 KB
Newer Older
T
terrymanu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/**
 * Copyright 1999-2015 dangdang.com.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * </p>
 */

package com.dangdang.ddframe.rdb.sharding.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import com.dangdang.ddframe.rdb.sharding.executor.PreparedStatementExecutor;
import com.dangdang.ddframe.rdb.sharding.jdbc.adapter.AbstractPreparedStatementAdapter;
import com.dangdang.ddframe.rdb.sharding.merger.ResultSetFactory;
G
fix #16  
gaohongtao 已提交
34
import com.dangdang.ddframe.rdb.sharding.parser.result.merger.MergeContext;
T
terrymanu 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
import com.dangdang.ddframe.rdb.sharding.router.SQLExecutionUnit;
import com.dangdang.ddframe.rdb.sharding.router.SQLRouteResult;
import com.google.common.collect.Lists;

/**
 * 支持分片的预编译语句对象.
 * 
 * @author zhangliang
 */
public final class ShardingPreparedStatement extends AbstractPreparedStatementAdapter {
    
    private final String sql;
    
    private final Collection<PreparedStatement> cachedRoutedPreparedStatements = new LinkedList<>();
    
    private Integer autoGeneratedKeys;
    
    private int[] columnIndexes;
    
    private String[] columnNames;
    
    private boolean hasExecuted;
    
    private final List<List<Object>> batchParameters = new ArrayList<>();
    
G
fix #16  
gaohongtao 已提交
60 61
    public ShardingPreparedStatement(final ShardingConnection shardingConnection, final String sql) throws SQLException {
        this(shardingConnection, sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT);
T
terrymanu 已提交
62 63
    }
    
G
fix #16  
gaohongtao 已提交
64
    public ShardingPreparedStatement(final ShardingConnection shardingConnection, 
T
terrymanu 已提交
65
            final String sql, final int resultSetType, final int resultSetConcurrency) throws SQLException {
G
fix #16  
gaohongtao 已提交
66
        this(shardingConnection, sql, resultSetType, resultSetConcurrency, ResultSet.HOLD_CURSORS_OVER_COMMIT);
T
terrymanu 已提交
67 68
    }
    
G
fix #16  
gaohongtao 已提交
69
    public ShardingPreparedStatement(final ShardingConnection shardingConnection, 
T
terrymanu 已提交
70
            final String sql, final int resultSetType, final int resultSetConcurrency, final int resultSetHoldability) throws SQLException {
G
fix #16  
gaohongtao 已提交
71
        super(shardingConnection, resultSetType, resultSetConcurrency, resultSetHoldability);
T
terrymanu 已提交
72 73 74
        this.sql = sql;
    }
    
G
fix #16  
gaohongtao 已提交
75 76
    public ShardingPreparedStatement(final ShardingConnection shardingConnection, final String sql, final int autoGeneratedKeys) throws SQLException {
        this(shardingConnection, sql);
T
terrymanu 已提交
77 78 79
        this.autoGeneratedKeys = autoGeneratedKeys;
    }
    
G
fix #16  
gaohongtao 已提交
80 81
    public ShardingPreparedStatement(final ShardingConnection shardingConnection, final String sql, final int[] columnIndexes) throws SQLException {
        this(shardingConnection, sql);
T
terrymanu 已提交
82 83 84
        this.columnIndexes = columnIndexes;
    }
    
G
fix #16  
gaohongtao 已提交
85 86
    public ShardingPreparedStatement(final ShardingConnection shardingConnection, final String sql, final String[] columnNames) throws SQLException {
        this(shardingConnection, sql);
T
terrymanu 已提交
87 88 89 90 91 92
        this.columnNames = columnNames;
    }
    
    @Override
    public ResultSet executeQuery() throws SQLException {
        hasExecuted = true;
G
fix #16  
gaohongtao 已提交
93 94
        setCurrentResultSet(ResultSetFactory.getResultSet(new PreparedStatementExecutor(getShardingConnection().getContext().getExecutorEngine(), 
                getRoutedPreparedStatements()).executeQuery(), getMergeContext()));
T
terrymanu 已提交
95 96 97 98 99 100
        return getCurrentResultSet();
    }
    
    @Override
    public int executeUpdate() throws SQLException {
        hasExecuted = true;
G
fix #16  
gaohongtao 已提交
101
        return new PreparedStatementExecutor(getShardingConnection().getContext().getExecutorEngine(), getRoutedPreparedStatements()).executeUpdate();
T
terrymanu 已提交
102 103 104 105 106
    }
    
    @Override
    public boolean execute() throws SQLException {
        hasExecuted = true;
G
fix #16  
gaohongtao 已提交
107
        return new PreparedStatementExecutor(getShardingConnection().getContext().getExecutorEngine(), getRoutedPreparedStatements()).execute();
T
terrymanu 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    }
    
    @Override
    public void addBatch() throws SQLException {
        batchParameters.add(Lists.newArrayList(getParameters()));
        getParameters().clear();
    }
    
    @Override
    public void clearBatch() throws SQLException {
        batchParameters.clear();
    }
    
    @Override
    public int[] executeBatch() throws SQLException {
        hasExecuted = true;
        int[] result = new int[batchParameters.size()];
        int i = 0;
        for (List<Object> each : batchParameters) {
G
fix #13  
gaohongtao 已提交
127 128 129
            List<PreparedStatement> routePreparedStatements = routeSQL(each);
            cachedRoutedPreparedStatements.addAll(routePreparedStatements);
            result[i++] = new PreparedStatementExecutor(getShardingConnection().getContext().getExecutorEngine(), routePreparedStatements).executeUpdate();
T
terrymanu 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
        }
        return result;
    }
    
    private Collection<PreparedStatement> getRoutedPreparedStatements() throws SQLException {
        if (!hasExecuted) {
            return Collections.emptyList();
        }
        routeIfNeed();
        return cachedRoutedPreparedStatements;
    }
    
    @Override
    public Collection<? extends Statement> getRoutedStatements() throws SQLException {
        return getRoutedPreparedStatements();
    }
    
    private void routeIfNeed() throws SQLException {
        if (!cachedRoutedPreparedStatements.isEmpty()) {
            return;
        }
        cachedRoutedPreparedStatements.addAll(routeSQL(getParameters()));
    }
    
    private List<PreparedStatement> routeSQL(final List<Object> parameters) throws SQLException {
        List<PreparedStatement> result = new ArrayList<>();
G
fix #16  
gaohongtao 已提交
156 157 158 159
        SQLRouteResult sqlRouteResult = getShardingConnection().getContext().getSqlRouteEngine().route(sql, parameters);
        MergeContext mergeContext = sqlRouteResult.getMergeContext();
        mergeContext.setExecutorEngine(getShardingConnection().getContext().getExecutorEngine());
        setMergeContext(mergeContext);
T
terrymanu 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
        for (SQLExecutionUnit each : sqlRouteResult.getExecutionUnits()) {
            PreparedStatement preparedStatement = generatePrepareStatement(getShardingConnection().getConnection(each.getDataSource()), each.getSql());
            replayMethodsInvovation(preparedStatement);
            setParameters(preparedStatement, parameters);
            result.add(preparedStatement);
        }
        return result;
    }
    
    private PreparedStatement generatePrepareStatement(final Connection conn, final String shardingSql) throws SQLException {
        if (null != autoGeneratedKeys) {
            return conn.prepareStatement(shardingSql, autoGeneratedKeys);
        }
        if (null != columnIndexes) {
            return conn.prepareStatement(shardingSql, columnIndexes);
        }
        if (null != columnNames) {
            return conn.prepareStatement(shardingSql, columnNames);
        }
        if (0 != getResultSetHoldability()) {
            return conn.prepareStatement(shardingSql, getResultSetType(), getResultSetConcurrency(), getResultSetHoldability());
        }
        return conn.prepareStatement(shardingSql, getResultSetType(), getResultSetConcurrency());
    }
    
    private void setParameters(final PreparedStatement preparedStatement, final List<Object> parameters) throws SQLException {
        int i = 1;
        for (Object each : parameters) {
            preparedStatement.setObject(i++, each);
        }
    }
}