DatabaseUtil.java 30.2 KB
Newer Older
L
liu ze jian 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * 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>
 */

18 19
package io.shardingjdbc.dbtest.common;

T
terrymanu 已提交
20 21 22 23 24 25 26 27 28
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
29 30 31 32 33 34 35 36
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

37 38 39 40 41 42 43 44 45 46 47 48
import io.shardingjdbc.dbtest.config.bean.ColumnDefinition;
import io.shardingjdbc.dbtest.config.bean.DatasetDatabase;
import io.shardingjdbc.dbtest.config.bean.DatasetDefinition;
import io.shardingjdbc.dbtest.config.bean.IndexDefinition;
import io.shardingjdbc.dbtest.config.bean.ParameterDefinition;
import io.shardingjdbc.dbtest.config.bean.ParameterValueDefinition;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.FastDateFormat;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
T
terrymanu 已提交
49
import static org.junit.Assert.assertTrue;
50
import static org.junit.Assert.fail;
51

52
public class DatabaseUtil {
53
    
L
liu ze jian 已提交
54
    /**
L
liu ze jian 已提交
55 56 57 58 59
     * Generating sql.
     *
     * @param table  table
     * @param config Map column,data
     * @return sql
L
liu ze jian 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
     */
    public static String analyzeSql(final String table, final Map<String, String> config) {
        List<String> colsConfigs = new ArrayList<>();
        List<String> valueConfigs = new ArrayList<>();
        for (Map.Entry<String, String> stringStringEntry : config.entrySet()) {
            colsConfigs.add(stringStringEntry.getKey());
            valueConfigs.add("?");
        }
        StringBuilder sbsql = new StringBuilder("insert into ");
        sbsql.append(table);
        sbsql.append(" ( ");
        sbsql.append(StringUtils.join(colsConfigs, ","));
        sbsql.append(" )");
        sbsql.append(" values ");
        sbsql.append(" ( ");
        sbsql.append(StringUtils.join(valueConfigs, ","));
        sbsql.append(" )");
        return sbsql.toString();
    }
79
    
L
liu ze jian 已提交
80 81 82 83 84 85 86 87 88 89 90
    /**
     * Insert initialization data.
     *
     * @param conn   Jdbc connection
     * @param sql    sql
     * @param datas  init data
     * @param config Table field type
     * @return Success or failure
     * @throws SQLException   SQL executes exceptions
     * @throws ParseException Precompiled anomaly
     */
L
liu ze jian 已提交
91
    public static boolean insertUsePreparedStatement(final Connection conn, final String sql,
92
                                                     final List<Map<String, String>> datas, final List<ColumnDefinition> config)
L
liu ze jian 已提交
93 94 95
            throws SQLException, ParseException {
        try (PreparedStatement pstmt = conn.prepareStatement(sql);) {
            for (Map<String, String> data : datas) {
96
                sqlParameterProcessing(config, pstmt, data);
L
liu ze jian 已提交
97 98 99 100 101
                pstmt.executeUpdate();
            }
        }
        return true;
    }
102
    
103 104 105 106 107 108 109 110
    private static void sqlParameterProcessing(final List<ColumnDefinition> config, final PreparedStatement pstmt, final Map<String, String> data) throws SQLException, ParseException {
        int index = 1;
        for (Map.Entry<String, String> each : data.entrySet()) {
            String key = each.getKey();
            String datacol = each.getValue();
            String type = "String";
            if (config != null) {
                for (ColumnDefinition eachColumnDefinition : config) {
L
liu ze jian 已提交
111
                    if (key.equals(eachColumnDefinition.getName()) && eachColumnDefinition.getType() != null) {
112 113 114 115
                        type = eachColumnDefinition.getType();
                    }
                }
            }
L
liu ze jian 已提交
116
            processingParameters(pstmt, index, datacol, type);
117 118 119 120
            index++;
        }
    }
    
L
liu ze jian 已提交
121 122 123 124 125 126 127 128 129 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 156
    private static void processingParameters(final PreparedStatement pstmt, final int index, final String datacol, final String type) throws SQLException, ParseException {
        switch (type) {
            case "byte":
                pstmt.setByte(index, Byte.valueOf(datacol));
                break;
            case "short":
                pstmt.setShort(index, Short.valueOf(datacol));
                break;
            case "int":
                pstmt.setInt(index, Integer.valueOf(datacol));
                break;
            case "long":
                pstmt.setLong(index, Long.valueOf(datacol));
                break;
            case "float":
                pstmt.setFloat(index, Float.valueOf(datacol));
                break;
            case "double":
                pstmt.setDouble(index, Double.valueOf(datacol));
                break;
            case "boolean":
                pstmt.setBoolean(index, Boolean.valueOf(datacol));
                break;
            case "Date":
                FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd");
                pstmt.setDate(index, new Date(fdf.parse(datacol).getTime()));
                break;
            case "String":
                pstmt.setString(index, datacol);
                break;
            default:
                pstmt.setString(index, datacol);
                break;
        }
    }
    
L
liu ze jian 已提交
157 158 159 160 161 162 163
    /**
     * clear table.
     *
     * @param conn  Jdbc connection
     * @param table table
     * @throws SQLException SQL executes exceptions
     */
L
liu ze jian 已提交
164 165 166 167 168
    public static void cleanAllUsePreparedStatement(final Connection conn, final String table) throws SQLException {
        try (Statement pstmt = conn.createStatement();) {
            pstmt.execute("DELETE from " + table);
        }
    }
169
    
L
liu ze jian 已提交
170 171 172
    /**
     * Use Statement Test data update.
     *
L
liu ze jian 已提交
173 174
     * @param conn                Jdbc connection
     * @param sql                 sql
175
     * @param parameterDefinition parameter
L
liu ze jian 已提交
176 177 178
     * @return Number of rows as a result of execution
     * @throws SQLException SQL executes exceptions
     */
L
liu ze jian 已提交
179
    public static int updateUseStatementToExecuteUpdate(final Connection conn, final String sql,
180
                                                        final ParameterDefinition parameterDefinition) throws SQLException {
L
liu ze jian 已提交
181
        try (Statement pstmt = conn.createStatement()) {
L
liu ze jian 已提交
182 183
            String newSql = sqlReplaceStatement(sql, parameterDefinition.getValueReplaces());
            newSql = sqlStatement(newSql, parameterDefinition.getValues());
L
liu ze jian 已提交
184
            return pstmt.executeUpdate(newSql);
L
liu ze jian 已提交
185 186
        }
    }
187
    
L
liu ze jian 已提交
188 189 190 191 192 193 194
    /**
     * Processing statement sql.
     *
     * @param sql       sql
     * @param parameter parameter
     * @return sql
     */
195 196 197 198
    private static String sqlStatement(final String sql, final List<ParameterValueDefinition> parameter) {
        if (parameter == null) {
            return sql;
        }
L
liu ze jian 已提交
199
        String result = sql;
200
        for (ParameterValueDefinition parameterDefinition : parameter) {
L
liu ze jian 已提交
201 202 203
            String type = parameterDefinition.getType();
            String datacol = parameterDefinition.getValue();
            switch (type) {
L
liu ze jian 已提交
204 205 206 207 208 209 210
                case "byte":
                case "short":
                case "int":
                case "long":
                case "float":
                case "double":
                    result = Pattern.compile("%s", Pattern.LITERAL).matcher(result)
L
liu ze jian 已提交
211
                            .replaceFirst(Matcher.quoteReplacement(datacol));
L
liu ze jian 已提交
212 213 214 215 216 217 218 219 220
                    break;
                case "boolean":
                    result = Pattern.compile("%s", Pattern.LITERAL).matcher(result)
                            .replaceFirst(Matcher.quoteReplacement(Boolean.valueOf(datacol).toString()));
                    break;
                default:
                    result = Pattern.compile("%s", Pattern.LITERAL).matcher(result)
                            .replaceFirst(Matcher.quoteReplacement("'" + datacol + "'"));
                    break;
L
liu ze jian 已提交
221 222 223 224
            }
        }
        return result;
    }
225
    
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
    /**
     * Processing statement sql.
     *
     * @param sql       sql
     * @param parameter parameter
     * @return sql
     */
    private static String sqlReplaceStatement(final String sql, final List<ParameterValueDefinition> parameter) {
        if (parameter == null) {
            return sql;
        }
        String result = sql;
        for (ParameterValueDefinition parameterDefinition : parameter) {
            String type = parameterDefinition.getType();
            String datacol = parameterDefinition.getValue();
            switch (type) {
                case "byte":
                case "short":
                case "int":
                case "long":
                case "float":
                case "double":
                    result = Pattern.compile("#s", Pattern.LITERAL).matcher(result)
                            .replaceFirst(Matcher.quoteReplacement(datacol.toString()));
                    break;
                case "boolean":
                    result = Pattern.compile("#s", Pattern.LITERAL).matcher(result)
                            .replaceFirst(Matcher.quoteReplacement(Boolean.valueOf(datacol).toString()));
                    break;
                default:
                    result = Pattern.compile("#s", Pattern.LITERAL).matcher(result)
                            .replaceFirst(Matcher.quoteReplacement("'" + datacol + "'"));
                    break;
            }
        }
        return result;
    }
    
L
liu ze jian 已提交
264 265 266
    /**
     * Use Statement Test data update.
     *
L
liu ze jian 已提交
267 268
     * @param conn                Jdbc connection
     * @param sql                 sql
269
     * @param parameterDefinition parameter
L
liu ze jian 已提交
270 271 272
     * @return Implementation results
     * @throws SQLException SQL executes exceptions
     */
273
    public static int updateUseStatementToExecute(final Connection conn, final String sql,
274
                                                  final ParameterDefinition parameterDefinition) throws SQLException {
L
liu ze jian 已提交
275
        try (Statement pstmt = conn.createStatement()) {
L
liu ze jian 已提交
276 277 278
            String newSql = sqlReplaceStatement(sql, parameterDefinition.getValueReplaces());
            newSql = sqlStatement(newSql, parameterDefinition.getValues());
            if (!pstmt.execute(newSql)) {
L
liu ze jian 已提交
279
                return pstmt.getUpdateCount();
L
liu ze jian 已提交
280
            }
L
liu ze jian 已提交
281
        }
L
liu ze jian 已提交
282
        return 0;
L
liu ze jian 已提交
283
    }
284
    
L
liu ze jian 已提交
285 286 287
    /**
     * Use PreparedStatement Test data update.
     *
L
liu ze jian 已提交
288 289
     * @param conn                Jdbc connection
     * @param sql                 sql
290
     * @param parameterDefinition parameter
L
liu ze jian 已提交
291 292 293 294
     * @return Number of rows as a result of execution
     * @throws SQLException   SQL executes exceptions
     * @throws ParseException ParseException
     */
L
liu ze jian 已提交
295
    public static int updateUsePreparedStatementToExecuteUpdate(final Connection conn, final String sql,
296
                                                                final ParameterDefinition parameterDefinition) throws SQLException, ParseException {
L
liu ze jian 已提交
297 298 299 300
        String newSql = sql.replaceAll("\\%s", "?");
        newSql = sqlReplaceStatement(newSql, parameterDefinition.getValueReplaces());
        try (PreparedStatement pstmt = conn.prepareStatement(newSql)) {
            sqlPreparedStatement(parameterDefinition.getValues(), pstmt);
L
liu ze jian 已提交
301
            return pstmt.executeUpdate();
L
liu ze jian 已提交
302
        }
L
liu ze jian 已提交
303
    }
304
    
L
liu ze jian 已提交
305 306 307
    /**
     * Use PreparedStatement Test data update.
     *
L
liu ze jian 已提交
308 309
     * @param conn                Jdbc connection
     * @param sql                 sql
310
     * @param parameterDefinition parameter
L
liu ze jian 已提交
311 312 313 314
     * @return Implementation results
     * @throws SQLException   SQL executes exceptions
     * @throws ParseException ParseException
     */
315
    public static int updateUsePreparedStatementToExecute(final Connection conn, final String sql,
316
                                                          final ParameterDefinition parameterDefinition) throws SQLException, ParseException {
L
liu ze jian 已提交
317 318 319 320 321
        String newSql = sql.replaceAll("\\%s", "?");
        newSql = sqlReplaceStatement(newSql, parameterDefinition.getValueReplaces());
        try (PreparedStatement pstmt = conn.prepareStatement(newSql)) {
            sqlPreparedStatement(parameterDefinition.getValues(), pstmt);
            if (!pstmt.execute()) {
L
liu ze jian 已提交
322
                return pstmt.getUpdateCount();
323
            }
L
liu ze jian 已提交
324
        }
L
liu ze jian 已提交
325
        return 0;
L
liu ze jian 已提交
326
    }
327
    
L
liu ze jian 已提交
328 329 330 331 332 333 334 335 336 337
    /**
     * Use PreparedStatement Test sql select.
     *
     * @param conn       Jdbc connection
     * @param sql        sql
     * @param parameters parameters
     * @return Query result set
     * @throws SQLException   SQL executes exceptions
     * @throws ParseException ParseException
     */
L
liu ze jian 已提交
338
    public static DatasetDatabase selectUsePreparedStatement(final Connection conn, final String sql,
339 340
                                                             final ParameterDefinition parameters) throws SQLException, ParseException {
        List<ParameterValueDefinition> parameter = parameters.getValues();
341 342
        String newSql = sqlReplaceStatement(sql, parameters.getValueReplaces());
        newSql = newSql.replaceAll("\\%s", "?");
L
liu ze jian 已提交
343 344 345
        try (PreparedStatement pstmt = conn.prepareStatement(newSql)) {
            sqlPreparedStatement(parameter, pstmt);
            try (ResultSet resultSet = pstmt.executeQuery()) {
L
liu ze jian 已提交
346
                return useBackResultSet(resultSet);
L
liu ze jian 已提交
347 348 349
            }
        }
    }
350
    
L
liu ze jian 已提交
351 352 353 354 355 356 357 358 359 360 361
    /**
     * Use PreparedStatement Test sql select.
     *
     * @param conn       Jdbc connection
     * @param sql        sql
     * @param parameters parameters
     * @return Query result set
     * @throws SQLException   SQL executes exceptions
     * @throws ParseException ParseException
     */
    public static DatasetDatabase selectUsePreparedStatementToExecuteSelect(final Connection conn, final String sql,
362 363
                                                                            final ParameterDefinition parameters) throws SQLException, ParseException {
        List<ParameterValueDefinition> parameter = parameters.getValues();
364 365
        String newSql = sqlReplaceStatement(sql, parameters.getValueReplaces());
        newSql = newSql.replaceAll("\\%s", "?");
L
liu ze jian 已提交
366 367 368
        try (PreparedStatement pstmt = conn.prepareStatement(newSql)) {
            sqlPreparedStatement(parameter, pstmt);
            boolean flag = pstmt.execute();
369
            assertTrue("Not a query statement.", flag);
L
liu ze jian 已提交
370
            try (ResultSet resultSet = pstmt.getResultSet()) {
L
liu ze jian 已提交
371
                return useBackResultSet(resultSet);
L
liu ze jian 已提交
372 373 374
            }
        }
    }
375 376
    
    private static void handleResultSet(final ResultSet resultSet, final List<ColumnDefinition> cols, final List<Map<String, String>> ls) throws SQLException {
L
liu ze jian 已提交
377 378
        while (resultSet.next()) {
            Map<String, String> data = new HashMap<>();
379 380 381
            for (ColumnDefinition each : cols) {
                String name = each.getName();
                String type = each.getType();
L
liu ze jian 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
                switch (type) {
                    case "boolean":
                        data.put(name, String.valueOf(resultSet.getBoolean(name)));
                        break;
                    case "char":
                        data.put(name, String.valueOf(resultSet.getString(name)));
                        break;
                    case "Date":
                        data.put(name, DateFormatUtils.format(new java.util.Date(resultSet.getDate(name).getTime()),
                                "yyyy-MM-dd"));
                        break;
                    case "Blob":
                        data.put(name, String.valueOf(resultSet.getBlob(name)));
                        break;
                    default:
L
liu ze jian 已提交
397
                        handleResultSetMore(type, resultSet, data, name);
L
liu ze jian 已提交
398
                        break;
L
liu ze jian 已提交
399 400
                }
            }
L
liu ze jian 已提交
401
            ls.add(data);
L
liu ze jian 已提交
402 403
        }
    }
404
    
L
liu ze jian 已提交
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
    private static void handleResultSetMore(final String type, final ResultSet resultSet, final Map<String, String> data, final String name) throws SQLException {
        switch (type) {
            case "int":
                data.put(name, String.valueOf(resultSet.getInt(name)));
                return;
            case "long":
                data.put(name, String.valueOf(resultSet.getLong(name)));
                break;
            case "float":
                data.put(name, String.valueOf(resultSet.getFloat(name)));
                break;
            case "double":
                data.put(name, String.valueOf(resultSet.getDouble(name)));
                break;
            default:
                data.put(name, resultSet.getString(name));
                break;
        }
    }
    
L
liu ze jian 已提交
425 426 427 428 429 430 431 432 433
    /**
     * Use Statement Test sql select.
     *
     * @param conn       Jdbc connection
     * @param sql        sql
     * @param parameters parameters
     * @return Query result set
     * @throws SQLException SQL executes exceptions
     */
L
liu ze jian 已提交
434
    public static DatasetDatabase selectUseStatement(final Connection conn, final String sql,
435 436
                                                     final ParameterDefinition parameters) throws SQLException {
        List<ParameterValueDefinition> parameter = parameters.getValues();
437
        String newSql = sqlReplaceStatement(sql, parameters.getValueReplaces());
L
liu ze jian 已提交
438
        try (Statement pstmt = conn.createStatement()) {
439
            newSql = sqlStatement(newSql, parameter);
L
liu ze jian 已提交
440
            try (ResultSet resultSet = pstmt.executeQuery(newSql)) {
L
liu ze jian 已提交
441
                return useBackResultSet(resultSet);
L
liu ze jian 已提交
442 443 444
            }
        }
    }
445
    
L
liu ze jian 已提交
446 447 448 449 450 451 452 453 454 455
    /**
     * Use Statement Test sql select.
     *
     * @param conn       Jdbc connection
     * @param sql        sql
     * @param parameters parameters
     * @return Query result set
     * @throws SQLException SQL executes exceptions
     */
    public static DatasetDatabase selectUseStatementToExecuteSelect(final Connection conn, final String sql,
456 457
                                                                    final ParameterDefinition parameters) throws SQLException {
        List<ParameterValueDefinition> parameter = parameters.getValues();
458
        String newSql = sqlReplaceStatement(sql, parameters.getValueReplaces());
L
liu ze jian 已提交
459
        try (Statement pstmt = conn.createStatement()) {
460
            newSql = sqlStatement(newSql, parameter);
L
liu ze jian 已提交
461
            try (ResultSet resultSet = pstmt.executeQuery(newSql)) {
L
liu ze jian 已提交
462
                return useBackResultSet(resultSet);
L
liu ze jian 已提交
463 464 465
            }
        }
    }
466
    
L
liu ze jian 已提交
467
    private static DatasetDatabase useBackResultSet(final ResultSet resultSet) throws SQLException {
L
liu ze jian 已提交
468 469
        ResultSetMetaData rsmd = resultSet.getMetaData();
        int colsint = rsmd.getColumnCount();
470
        List<ColumnDefinition> cols = new ArrayList<>();
L
liu ze jian 已提交
471 472 473
        for (int i = 1; i < colsint + 1; i++) {
            String name = rsmd.getColumnName(i);
            String type = getDataType(rsmd.getColumnType(i), rsmd.getScale(i));
474 475 476
            ColumnDefinition columnDefinition = new ColumnDefinition();
            columnDefinition.setName(name);
            columnDefinition.setType(type);
L
liu ze jian 已提交
477
            cols.add(columnDefinition);
L
liu ze jian 已提交
478
        }
479
        Map<String, List<ColumnDefinition>> configs = new HashMap<>();
L
liu ze jian 已提交
480 481 482 483 484 485
        configs.put("data", cols);
        List<Map<String, String>> ls = new ArrayList<>();
        Map<String, List<Map<String, String>>> datas = new HashMap<>();
        datas.put("data", ls);
        handleResultSet(resultSet, cols, ls);
        DatasetDatabase result = new DatasetDatabase();
486
        result.setMetadatas(configs);
L
liu ze jian 已提交
487 488 489
        result.setDatas(datas);
        return result;
    }
490 491
    
    
L
liu ze jian 已提交
492 493 494 495 496 497 498 499
    /**
     * Sql parameter injection.
     *
     * @param parameter parameter
     * @param pstmt     PreparedStatement
     * @throws SQLException   SQL executes exceptions
     * @throws ParseException ParseException
     */
500
    private static void sqlPreparedStatement(final List<ParameterValueDefinition> parameter, final PreparedStatement pstmt)
L
liu ze jian 已提交
501
            throws SQLException, ParseException {
502 503 504
        if (parameter == null) {
            return;
        }
L
liu ze jian 已提交
505
        int index = 1;
506
        for (ParameterValueDefinition parameterDefinition : parameter) {
L
liu ze jian 已提交
507 508
            String type = parameterDefinition.getType();
            String datacol = parameterDefinition.getValue();
L
liu ze jian 已提交
509
            processingParameters(pstmt, index, datacol, type);
L
liu ze jian 已提交
510 511 512
            index++;
        }
    }
513
    
L
liu ze jian 已提交
514 515 516 517 518 519 520 521
    /**
     * Database type to java type.
     *
     * @param type  database type
     * @param scale scale
     * @return java type
     */
    private static String getDataType(final int type, final int scale) {
522
        String result = null;
L
liu ze jian 已提交
523 524 525
        switch (type) {
            case Types.BOOLEAN:
                result = "boolean";
L
liu ze jian 已提交
526
                break;
L
liu ze jian 已提交
527 528
            case Types.CHAR:
                result = "char";
L
liu ze jian 已提交
529
                break;
L
liu ze jian 已提交
530 531 532 533 534 535 536 537 538 539 540
            case Types.NUMERIC:
                switch (scale) {
                    case 0:
                        result = "double";
                        break;
                    case -127:
                        result = "float";
                        break;
                    default:
                        result = "double";
                }
L
liu ze jian 已提交
541
                break;
L
liu ze jian 已提交
542 543
            case Types.DATE:
                result = "Date";
L
liu ze jian 已提交
544
                break;
L
liu ze jian 已提交
545 546
            case Types.TIMESTAMP:
                result = "Date";
L
liu ze jian 已提交
547
                break;
L
liu ze jian 已提交
548 549
            case Types.BLOB:
                result = "Blob";
L
liu ze jian 已提交
550 551
                break;
            default:
L
liu ze jian 已提交
552 553
                result = getDataTypeMore(type);
                break;
L
liu ze jian 已提交
554 555 556
        }
        return result;
    }
557
    
L
liu ze jian 已提交
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
    private static String getDataTypeMore(final int type) {
        switch (type) {
            case Types.INTEGER:
                return "int";
            case Types.LONGVARCHAR:
                return "long";
            case Types.BIGINT:
                return "long";
            case Types.FLOAT:
                return "float";
            case Types.DOUBLE:
                return "double";
            default:
                return "String";
        }
    }
    
575 576 577 578 579
    /**
     * Comparative data set.
     *
     * @param expected expected
     * @param actual   actual
L
liu ze jian 已提交
580 581
     * @param table    table
     * @param msg      msg
582
     */
L
liu ze jian 已提交
583
    public static void assertConfigs(final DatasetDefinition expected, final List<ColumnDefinition> actual, final String table, final String msg) {
584 585 586
        Map<String, List<ColumnDefinition>> configs = expected.getMetadatas();
        List<ColumnDefinition> columnDefinitions = configs.get(table);
        for (ColumnDefinition each : columnDefinitions) {
587 588 589 590 591 592 593 594 595 596
            checkActual(actual, msg, each);
        }
    }
    
    private static void checkActual(final List<ColumnDefinition> actual, final String msg, final ColumnDefinition expect) {
        for (ColumnDefinition each : actual) {
            if (expect.getName().equals(each.getName())) {
                if (StringUtils.isNotEmpty(expect.getType())) {
                    assertEquals(msg, expect.getType(), each.getType());
                }
L
liu ze jian 已提交
597 598 599 600
                checkDatabaseColumn(msg, expect.getDecimalDigits(), each.getDecimalDigits());
                checkDatabaseColumn(msg, expect.getNullAble(), each.getNullAble());
                checkDatabaseColumn(msg, expect.getNumPrecRadix(), each.getNumPrecRadix());
                checkDatabaseColumn(msg, expect.getSize(), each.getSize());
601 602 603 604 605
                if (expect.getIsAutoincrement() != 0 && expect.getIsAutoincrement() != each.getIsAutoincrement()) {
                    fail(msg);
                }
                List<IndexDefinition> indexs = expect.getIndexs();
                if (indexs != null && !indexs.isEmpty()) {
L
liu ze jian 已提交
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
                    checkIndex(msg, each, indexs);
                }
            }
        }
    }
    
    private static void checkDatabaseColumn(final String msg, final Integer expectData, final Integer actualData) {
        if (expectData != null && !expectData.equals(actualData)) {
            fail(msg);
        }
    }
    
    private static void checkIndex(final String msg, final ColumnDefinition each, final List<IndexDefinition> indexs) {
        for (IndexDefinition expectIndex : indexs) {
            for (IndexDefinition actualIndex : each.getIndexs()) {
                if (expectIndex.getName().equals(actualIndex.getName())) {
                    if (expectIndex.getType() != null && !expectIndex.getType().equals(actualIndex.getType())) {
                        fail(msg);
                    }
                    if (expectIndex.isUnique() != actualIndex.isUnique()) {
                        fail(msg);
627 628 629 630 631 632
                    }
                }
            }
        }
    }
    
L
liu ze jian 已提交
633 634 635 636 637
    /**
     * Comparative data set.
     *
     * @param expected expected
     * @param actual   actual
638
     * @param msg      error msg
L
liu ze jian 已提交
639
     */
640
    public static void assertDatas(final DatasetDefinition expected, final DatasetDatabase actual, final String msg) {
641 642 643
        Map<String, List<ColumnDefinition>> actualConfigs = actual.getMetadatas();
        Map<String, List<ColumnDefinition>> expectedConfigs = expected.getMetadatas();
        for (Map.Entry<String, List<ColumnDefinition>> each : expectedConfigs.entrySet()) {
L
liu ze jian 已提交
644
            List<ColumnDefinition> expectedConfig = each.getValue();
645
            List<ColumnDefinition> actualConfig = actualConfigs.get(each.getKey());
646
            assertNotNull(msg, actualConfig);
L
liu ze jian 已提交
647
            checkConfig(msg, expectedConfig, actualConfig);
L
liu ze jian 已提交
648 649 650 651 652 653
        }
        Map<String, List<Map<String, String>>> actualDatass = actual.getDatas();
        Map<String, List<Map<String, String>>> expectDedatas = expected.getDatas();
        for (Map.Entry<String, List<Map<String, String>>> stringListEntry : expectDedatas.entrySet()) {
            List<Map<String, String>> data = stringListEntry.getValue();
            List<Map<String, String>> actualDatas = actualDatass.get(stringListEntry.getKey());
654
            assertEquals(msg + " result set validation failed , The number of validation data and query data is not equal", actualDatas.size(), data.size());
L
liu ze jian 已提交
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
            checkData(msg, data, actualDatas);
        }
    }
    
    private static void checkData(final String msg, final List<Map<String, String>> data, final List<Map<String, String>> actualDatas) {
        for (int i = 0; i < data.size(); i++) {
            Map<String, String> expectData = data.get(i);
            Map<String, String> actualData = actualDatas.get(i);
            for (Map.Entry<String, String> stringStringEntry : expectData.entrySet()) {
                if (!stringStringEntry.getValue().equals(actualData.get(stringStringEntry.getKey()))) {
                    String actualMsg = actualDatas.toString();
                    String expectMsg = data.toString();
                    fail(msg + " result set validation failed . describe : actual = " + actualMsg + " . expect = " + expectMsg);
                }
            }
        }
    }
    
    private static void checkConfig(final String msg, final List<ColumnDefinition> expectedConfig, final List<ColumnDefinition> actualConfig) {
        for (ColumnDefinition eachColumn : expectedConfig) {
            boolean flag = false;
            for (ColumnDefinition eachActualColumn : actualConfig) {
                if (eachColumn.getName().equals(eachActualColumn.getName()) && eachColumn.getType().equals(eachActualColumn.getType())) {
                    flag = true;
L
liu ze jian 已提交
679 680
                }
            }
L
liu ze jian 已提交
681
            assertTrue(msg, flag);
L
liu ze jian 已提交
682 683
        }
    }
684
    
685 686 687 688 689 690 691 692 693 694 695
    /**
     * Use PreparedStatement Test sql select.
     *
     * @param conn  Jdbc connection
     * @param table table
     * @return Query result set
     * @throws SQLException   SQL executes exceptions
     * @throws ParseException ParseException
     */
    public static List<ColumnDefinition> getColumnDefinitions(final Connection conn, final String table) throws SQLException, ParseException {
        DatabaseMetaData stmt = conn.getMetaData();
L
liu ze jian 已提交
696
        try (ResultSet rs = stmt.getColumns(null, null, table, null)) {
697 698 699 700
            List<ColumnDefinition> cols = new ArrayList<ColumnDefinition>();
            while (rs.next()) {
                ColumnDefinition col = new ColumnDefinition();
                String column = rs.getString("COLUMN_NAME");
701
                col.setName(column);
702
                int size = rs.getInt("COLUMN_SIZE");
703
                col.setSize(size);
L
liu ze jian 已提交
704
                String columnType = rs.getString("TYPE_NAME").toLowerCase();
705 706
                col.setType(columnType);
                int decimalDigits = rs.getInt("DECIMAL_DIGITS");
707
                col.setDecimalDigits(decimalDigits);
708
                int numPrecRadix = rs.getInt("NUM_PREC_RADIX");
709
                col.setNumPrecRadix(numPrecRadix);
710
                int nullAble = rs.getInt("NULLABLE");
711
                col.setNullAble(nullAble);
712
                String isAutoincrement = rs.getString("IS_AUTOINCREMENT");
713 714 715 716 717
                if (StringUtils.isNotEmpty(isAutoincrement)) {
                    col.setIsAutoincrement(1);
                }
                cols.add(col);
            }
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
            geIndexDefinitions(stmt, cols, table);
            return cols;
        }
    }
    
    private static List<ColumnDefinition> geIndexDefinitions(final DatabaseMetaData stmt, final List<ColumnDefinition> cols, final String table) throws SQLException, ParseException {
        try (ResultSet rs = stmt.getIndexInfo(null, null, table, false, false)) {
            while (rs.next()) {
                IndexDefinition index = new IndexDefinition();
                String name = rs.getString("COLUMN_NAME");
                String nameIndex = rs.getString("INDEX_NAME");
                if (StringUtils.isNotEmpty(nameIndex)) {
                    index.setName(nameIndex);
                }
                String typeIndex = rs.getString("TYPE");
                if (StringUtils.isNotEmpty(typeIndex)) {
                    index.setType(typeIndex);
                }
                String uniqueIndex = rs.getString("NON_UNIQUE");
                if (StringUtils.isNotEmpty(uniqueIndex)) {
                    index.setUnique(!"TRUE".equalsIgnoreCase(uniqueIndex));
                }
                for (ColumnDefinition col : cols) {
                    if (name.equals(col.getName())) {
                        col.getIndexs().add(index);
                        break;
                    }
                }
            }
747 748 749
            return cols;
        }
    }
750
}