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

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