DatabaseUtil.java 29.3 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 20 21
package io.shardingjdbc.dbtest.common;

import static org.junit.Assert.assertTrue;

22
import java.sql.*;
23 24 25 26 27 28 29 30
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;

31
import io.shardingjdbc.dbtest.config.bean.*;
32 33 34 35 36
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.FastDateFormat;

import io.shardingjdbc.dbtest.exception.DbTestException;
L
liu ze jian 已提交
37
import org.junit.Assert;
38

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