SqlTask.java 21.4 KB
Newer Older
L
ligang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */
Q
qiaozhanwei 已提交
17
package org.apache.dolphinscheduler.server.worker.task.sql;
L
ligang 已提交
18

19 20 21 22 23 24 25 26
import static org.apache.dolphinscheduler.common.Constants.COMMA;
import static org.apache.dolphinscheduler.common.Constants.HIVE_CONF;
import static org.apache.dolphinscheduler.common.Constants.PASSWORD;
import static org.apache.dolphinscheduler.common.Constants.SEMICOLON;
import static org.apache.dolphinscheduler.common.Constants.STATUS;
import static org.apache.dolphinscheduler.common.Constants.USER;
import static org.apache.dolphinscheduler.common.enums.DbType.HIVE;

Q
qiaozhanwei 已提交
27
import org.apache.dolphinscheduler.alert.utils.MailUtils;
28
import org.apache.dolphinscheduler.common.Constants;
29
import org.apache.dolphinscheduler.common.enums.CommandType;
30
import org.apache.dolphinscheduler.common.enums.DbType;
Q
qiaozhanwei 已提交
31 32 33 34 35 36 37
import org.apache.dolphinscheduler.common.enums.ShowType;
import org.apache.dolphinscheduler.common.enums.TaskTimeoutStrategy;
import org.apache.dolphinscheduler.common.process.Property;
import org.apache.dolphinscheduler.common.task.AbstractParameters;
import org.apache.dolphinscheduler.common.task.sql.SqlBinds;
import org.apache.dolphinscheduler.common.task.sql.SqlParameters;
import org.apache.dolphinscheduler.common.task.sql.SqlType;
38 39 40 41 42
import org.apache.dolphinscheduler.common.utils.CollectionUtils;
import org.apache.dolphinscheduler.common.utils.CommonUtils;
import org.apache.dolphinscheduler.common.utils.EnumUtils;
import org.apache.dolphinscheduler.common.utils.JSONUtils;
import org.apache.dolphinscheduler.common.utils.ParameterUtils;
Q
qiaozhanwei 已提交
43
import org.apache.dolphinscheduler.dao.AlertDao;
44 45
import org.apache.dolphinscheduler.dao.datasource.BaseDataSource;
import org.apache.dolphinscheduler.dao.datasource.DataSourceFactory;
Q
qiaozhanwei 已提交
46
import org.apache.dolphinscheduler.dao.entity.User;
G
gaojun2048 已提交
47 48
import org.apache.dolphinscheduler.server.entity.SQLTaskExecutionContext;
import org.apache.dolphinscheduler.server.entity.TaskExecutionContext;
Q
qiaozhanwei 已提交
49 50 51
import org.apache.dolphinscheduler.server.utils.ParamUtils;
import org.apache.dolphinscheduler.server.utils.UDFUtils;
import org.apache.dolphinscheduler.server.worker.task.AbstractTask;
52
import org.apache.dolphinscheduler.service.bean.SpringApplicationContext;
L
ligang 已提交
53

K
Kirs 已提交
54
import org.apache.commons.collections.MapUtils;
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
import org.apache.commons.lang.StringUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
L
ligang 已提交
70 71
import java.util.regex.Matcher;
import java.util.regex.Pattern;
72
import java.util.stream.Collectors;
L
ligang 已提交
73

74 75 76 77
import org.slf4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
L
ligang 已提交
78
/**
79
 * sql task
L
ligang 已提交
80 81 82 83 84 85 86 87 88 89 90
 */
public class SqlTask extends AbstractTask {

    /**
     *  sql parameters
     */
    private SqlParameters sqlParameters;
    /**
     *  alert dao
     */
    private AlertDao alertDao;
G
gaojun2048 已提交
91 92 93 94
    /**
     * base datasource
     */
    private BaseDataSource baseDataSource;
L
ligang 已提交
95

journey2018's avatar
journey2018 已提交
96
    /**
G
gaojun2048 已提交
97
     * taskExecutionContext
journey2018's avatar
journey2018 已提交
98
     */
G
gaojun2048 已提交
99
    private TaskExecutionContext taskExecutionContext;
journey2018's avatar
journey2018 已提交
100

G
gaojun2048 已提交
101 102
    public SqlTask(TaskExecutionContext taskExecutionContext, Logger logger) {
        super(taskExecutionContext, logger);
L
ligang 已提交
103

G
gaojun2048 已提交
104
        this.taskExecutionContext = taskExecutionContext;
L
ligang 已提交
105

G
gaojun2048 已提交
106
        logger.info("sql task params {}", taskExecutionContext.getTaskParams());
107
        this.sqlParameters = JSONUtils.parseObject(taskExecutionContext.getTaskParams(), SqlParameters.class);
L
ligang 已提交
108 109 110 111

        if (!sqlParameters.checkParameters()) {
            throw new RuntimeException("sql task params is not valid");
        }
G
gaojun2048 已提交
112

113
        this.alertDao = SpringApplicationContext.getBean(AlertDao.class);
L
ligang 已提交
114 115 116 117 118
    }

    @Override
    public void handle() throws Exception {
        // set the name of the current thread
G
gaojun2048 已提交
119
        String threadLoggerInfoName = String.format(Constants.TASK_LOG_INFO_FORMAT, taskExecutionContext.getTaskAppId());
L
ligang 已提交
120
        Thread.currentThread().setName(threadLoggerInfoName);
G
gaojun2048 已提交
121

122
        logger.info("Full sql parameters: {}", sqlParameters);
123
        logger.info("sql type : {}, datasource : {}, sql : {} , localParams : {},udfs : {},showType : {},connParams : {}, query max result limit : {}",
journey2018's avatar
journey2018 已提交
124 125 126 127 128 129
                sqlParameters.getType(),
                sqlParameters.getDatasource(),
                sqlParameters.getSql(),
                sqlParameters.getLocalParams(),
                sqlParameters.getUdfs(),
                sqlParameters.getShowType(),
130 131
                sqlParameters.getConnParams(),
                sqlParameters.getLimit());
journey2018's avatar
journey2018 已提交
132
        try {
G
gaojun2048 已提交
133
            SQLTaskExecutionContext sqlTaskExecutionContext = taskExecutionContext.getSqlTaskExecutionContext();
journey2018's avatar
journey2018 已提交
134
            // load class
G
gaojun2048 已提交
135 136
            DataSourceFactory.loadClass(DbType.valueOf(sqlParameters.getType()));

journey2018's avatar
journey2018 已提交
137
            // get datasource
G
gaojun2048 已提交
138 139
            baseDataSource = DataSourceFactory.getDatasource(DbType.valueOf(sqlParameters.getType()),
                    sqlTaskExecutionContext.getConnectionParams());
journey2018's avatar
journey2018 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153

            // ready to execute SQL and parameter entity Map
            SqlBinds mainSqlBinds = getSqlAndSqlParamsMap(sqlParameters.getSql());
            List<SqlBinds> preStatementSqlBinds = Optional.ofNullable(sqlParameters.getPreStatements())
                    .orElse(new ArrayList<>())
                    .stream()
                    .map(this::getSqlAndSqlParamsMap)
                    .collect(Collectors.toList());
            List<SqlBinds> postStatementSqlBinds = Optional.ofNullable(sqlParameters.getPostStatements())
                    .orElse(new ArrayList<>())
                    .stream()
                    .map(this::getSqlAndSqlParamsMap)
                    .collect(Collectors.toList());

154
            List<String> createFuncs = UDFUtils.createFuncs(sqlTaskExecutionContext.getUdfFuncTenantCodeMap(),
G
gaojun2048 已提交
155
                    logger);
L
ligang 已提交
156

journey2018's avatar
journey2018 已提交
157
            // execute sql task
G
gaojun2048 已提交
158 159 160 161
            executeFuncAndSql(mainSqlBinds, preStatementSqlBinds, postStatementSqlBinds, createFuncs);

            setExitStatusCode(Constants.EXIT_CODE_SUCCESS);

162
        } catch (Exception e) {
G
gaojun2048 已提交
163
            setExitStatusCode(Constants.EXIT_CODE_FAILURE);
164
            logger.error("sql task error: {}", e.toString());
165
            throw e;
L
ligang 已提交
166 167 168 169
        }
    }

    /**
170 171
     * ready to execute SQL and parameter entity Map
     * @return SqlBinds
L
ligang 已提交
172
     */
173 174 175
    private SqlBinds getSqlAndSqlParamsMap(String sql) {
        Map<Integer,Property> sqlParamsMap =  new HashMap<>();
        StringBuilder sqlBuilder = new StringBuilder();
L
ligang 已提交
176 177

        // find process instance by task id
journey2018's avatar
journey2018 已提交
178

L
ligang 已提交
179

G
gaojun2048 已提交
180 181
        Map<String, Property> paramsMap = ParamUtils.convert(ParamUtils.getUserDefParamsMap(taskExecutionContext.getDefinedParams()),
                taskExecutionContext.getDefinedParams(),
L
ligang 已提交
182
                sqlParameters.getLocalParametersMap(),
G
gaojun2048 已提交
183 184
                CommandType.of(taskExecutionContext.getCmdTypeIfComplement()),
                taskExecutionContext.getScheduleTime());
185 186 187
        if (paramsMap == null) {
            sqlBuilder.append(sql);
            return new SqlBinds(sqlBuilder.toString(), sqlParamsMap);
K
Kirs 已提交
188 189 190 191
        }
        if (MapUtils.isNotEmpty(taskExecutionContext.getParamsMap())){
            paramsMap.putAll(taskExecutionContext.getParamsMap());
        }
L
ligang 已提交
192
        // spell SQL according to the final user-defined variable
193
        if (StringUtils.isNotEmpty(sqlParameters.getTitle())){
journey2018's avatar
journey2018 已提交
194 195
            String title = ParameterUtils.convertParameterPlaceholders(sqlParameters.getTitle(),
                    ParamUtils.convert(paramsMap));
Z
zhukai 已提交
196
            logger.info("SQL title : {}",title);
197 198
            sqlParameters.setTitle(title);
        }
199
        
200 201
        //new
        //replace variable TIME with $[YYYYmmddd...] in sql when history run job and batch complement job
G
gaojun2048 已提交
202
        sql = ParameterUtils.replaceScheduleTime(sql, taskExecutionContext.getScheduleTime());
L
ligang 已提交
203
        // special characters need to be escaped, ${} needs to be escaped
204
        String rgex = "['\"]*\\$\\{(.*?)\\}['\"]*";
journey2018's avatar
journey2018 已提交
205
        setSqlParamsMap(sql, rgex, sqlParamsMap, paramsMap);
L
ligang 已提交
206 207

        // replace the ${} of the SQL statement with the Placeholder
G
gaojun2048 已提交
208
        String formatSql = sql.replaceAll(rgex, "?");
L
ligang 已提交
209 210 211
        sqlBuilder.append(formatSql);

        // print repalce sql
G
gaojun2048 已提交
212
        printReplacedSql(sql, formatSql, rgex, sqlParamsMap);
213
        return new SqlBinds(sqlBuilder.toString(), sqlParamsMap);
L
ligang 已提交
214 215 216 217 218 219 220 221
    }

    @Override
    public AbstractParameters getParameters() {
        return this.sqlParameters;
    }

    /**
222 223 224 225 226
     * execute function and sql
     * @param mainSqlBinds          main sql binds
     * @param preStatementsBinds    pre statements binds
     * @param postStatementsBinds   post statements binds
     * @param createFuncs           create functions
L
ligang 已提交
227
     */
G
gaojun2048 已提交
228
    public void executeFuncAndSql(SqlBinds mainSqlBinds,
229 230
                                        List<SqlBinds> preStatementsBinds,
                                        List<SqlBinds> postStatementsBinds,
231
                                        List<String> createFuncs) throws Exception {
L
ligang 已提交
232
        Connection connection = null;
G
gaojun2048 已提交
233 234
        PreparedStatement stmt = null;
        ResultSet resultSet = null;
L
ligang 已提交
235
        try {
G
gaojun2048 已提交
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
            // if upload resource is HDFS and kerberos startup
            CommonUtils.loadKerberosConf();
            // create connection
            connection = createConnection();
            // create temp function
            if (CollectionUtils.isNotEmpty(createFuncs)) {
                createTempFunction(connection,createFuncs);
            }

            // pre sql
            preSql(connection,preStatementsBinds);
            stmt = prepareStatementAndBind(connection, mainSqlBinds);

            // decide whether to executeQuery or executeUpdate based on sqlType
            if (sqlParameters.getSqlType() == SqlType.QUERY.ordinal()) {
                // query statements need to be convert to JsonArray and inserted into Alert to send
                resultSet = stmt.executeQuery();
                resultProcess(resultSet);

            } else if (sqlParameters.getSqlType() == SqlType.NON_QUERY.ordinal()) {
                // non query statement
                stmt.executeUpdate();
            }

            postSql(connection,postStatementsBinds);

        } catch (Exception e) {
263 264
            logger.error("execute sql error: {}", e.getMessage());
            throw e;
G
gaojun2048 已提交
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
        } finally {
            close(resultSet,stmt,connection);
        }
    }

    /**
     * result process
     *
     * @param resultSet resultSet
     * @throws Exception
     */
    private void resultProcess(ResultSet resultSet) throws Exception{
        JSONArray resultJSONArray = new JSONArray();
        ResultSetMetaData md = resultSet.getMetaData();
        int num = md.getColumnCount();
journey2018's avatar
journey2018 已提交
280

G
gaojun2048 已提交
281 282
        int rowCount = 0;

283
        while (rowCount < sqlParameters.getLimit() && resultSet.next()) {
G
gaojun2048 已提交
284 285
            JSONObject mapOfColValues = new JSONObject(true);
            for (int i = 1; i <= num; i++) {
286
                mapOfColValues.put(md.getColumnLabel(i), resultSet.getObject(i));
G
gaojun2048 已提交
287 288 289 290
            }
            resultJSONArray.add(mapOfColValues);
            rowCount++;
        }
291
        String result = JSONUtils.toJsonString(resultJSONArray);
292 293 294 295 296 297 298 299 300
        logger.debug("execute sql result : {}", result);

        int displayRows = sqlParameters.getDisplayRows() > 0 ? sqlParameters.getDisplayRows() : Constants.DEFAULT_DISPLAY_ROWS;
        displayRows = Math.min(displayRows, resultJSONArray.size());
        logger.info("display sql result {} rows as follows:", displayRows);
        for (int i = 0; i < displayRows; i++) {
            String row = JSONUtils.toJsonString(resultJSONArray.get(i));
            logger.info("row {} : {}", i + 1, row);
        }
301

302
        if (sqlParameters.getSendEmail() == null || sqlParameters.getSendEmail()) {
303 304 305
            sendAttachment(StringUtils.isNotEmpty(sqlParameters.getTitle()) ? sqlParameters.getTitle() : taskExecutionContext.getTaskName() + " query result sets",
                    JSONUtils.toJsonString(resultJSONArray));
        }
G
gaojun2048 已提交
306 307 308 309 310 311 312 313 314 315 316 317 318 319
    }

    /**
     *  pre sql
     *
     * @param connection connection
     * @param preStatementsBinds preStatementsBinds
     */
    private void preSql(Connection connection,
                        List<SqlBinds> preStatementsBinds) throws Exception{
        for (SqlBinds sqlBind: preStatementsBinds) {
            try (PreparedStatement pstmt = prepareStatementAndBind(connection, sqlBind)){
                int result = pstmt.executeUpdate();
                logger.info("pre statement execute result: {}, for sql: {}",result,sqlBind.getSql());
L
ligang 已提交
320 321

            }
G
gaojun2048 已提交
322 323
        }
    }
L
ligang 已提交
324

G
gaojun2048 已提交
325
    /**
326
     * post sql
G
gaojun2048 已提交
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
     *
     * @param connection connection
     * @param postStatementsBinds postStatementsBinds
     * @throws Exception
     */
    private void postSql(Connection connection,
                         List<SqlBinds> postStatementsBinds) throws Exception{
        for (SqlBinds sqlBind: postStatementsBinds) {
            try (PreparedStatement pstmt = prepareStatementAndBind(connection, sqlBind)){
                int result = pstmt.executeUpdate();
                logger.info("post statement execute result: {},for sql: {}",result,sqlBind.getSql());
            }
        }
    }
    /**
     * create temp function
     *
     * @param connection connection
     * @param createFuncs createFuncs
     * @throws Exception
     */
    private void createTempFunction(Connection connection,
                                    List<String> createFuncs) throws Exception{
        try (Statement funcStmt = connection.createStatement()) {
            for (String createFunc : createFuncs) {
                logger.info("hive create function sql: {}", createFunc);
                funcStmt.execute(createFunc);
L
ligang 已提交
354
            }
G
gaojun2048 已提交
355 356
        }
    }
357
    
G
gaojun2048 已提交
358 359 360 361
    /**
     * create connection
     *
     * @return connection
362
     * @throws Exception Exception
G
gaojun2048 已提交
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
     */
    private Connection createConnection() throws Exception{
        // if hive , load connection params if exists
        Connection connection = null;
        if (HIVE == DbType.valueOf(sqlParameters.getType())) {
            Properties paramProp = new Properties();
            paramProp.setProperty(USER, baseDataSource.getUser());
            paramProp.setProperty(PASSWORD, baseDataSource.getPassword());
            Map<String, String> connParamMap = CollectionUtils.stringToMap(sqlParameters.getConnParams(),
                    SEMICOLON,
                    HIVE_CONF);
            paramProp.putAll(connParamMap);

            connection = DriverManager.getConnection(baseDataSource.getJdbcUrl(),
                    paramProp);
        }else{
            connection = DriverManager.getConnection(baseDataSource.getJdbcUrl(),
                    baseDataSource.getUser(),
                    baseDataSource.getPassword());
        }
        return connection;
    }

    /**
     *  close jdbc resource
     *
     * @param resultSet resultSet
     * @param pstmt pstmt
     * @param connection connection
     */
    private void close(ResultSet resultSet,
                       PreparedStatement pstmt,
                       Connection connection){
        if (resultSet != null){
            try {
398
                resultSet.close();
G
gaojun2048 已提交
399
            } catch (SQLException e) {
400
                logger.error("close result set error : {}",e.getMessage(),e);
L
ligang 已提交
401
            }
G
gaojun2048 已提交
402 403 404 405
        }

        if (pstmt != null){
            try {
406
                pstmt.close();
G
gaojun2048 已提交
407
            } catch (SQLException e) {
408
                logger.error("close prepared statement error : {}",e.getMessage(),e);
409
            }
G
gaojun2048 已提交
410 411 412
        }

        if (connection != null){
413 414
            try {
                connection.close();
G
gaojun2048 已提交
415
            } catch (SQLException e) {
416
                logger.error("close connection error : {}",e.getMessage(),e);
417
            }
L
ligang 已提交
418 419 420
        }
    }

journey2018's avatar
journey2018 已提交
421 422
    /**
     * preparedStatement bind
423 424 425 426
     * @param connection connection
     * @param sqlBinds  sqlBinds
     * @return PreparedStatement
     * @throws Exception Exception
journey2018's avatar
journey2018 已提交
427
     */
428
    private PreparedStatement prepareStatementAndBind(Connection connection, SqlBinds sqlBinds) throws Exception {
journey2018's avatar
journey2018 已提交
429
        // is the timeout set
G
gaojun2048 已提交
430 431
        boolean timeoutFlag = TaskTimeoutStrategy.of(taskExecutionContext.getTaskTimeoutStrategy()) == TaskTimeoutStrategy.FAILED ||
                TaskTimeoutStrategy.of(taskExecutionContext.getTaskTimeoutStrategy()) == TaskTimeoutStrategy.WARNFAILED;
432 433
        PreparedStatement stmt = connection.prepareStatement(sqlBinds.getSql());
        if(timeoutFlag){
G
gaojun2048 已提交
434
            stmt.setQueryTimeout(taskExecutionContext.getTaskTimeout());
435 436 437 438 439 440
        }
        Map<Integer, Property> params = sqlBinds.getParamsMap();
        if(params != null) {
            for (Map.Entry<Integer, Property> entry : params.entrySet()) {
                Property prop = entry.getValue();
                ParameterUtils.setInParameter(entry.getKey(), stmt, prop.getType(), prop.getValue());
441 442
            }
        }
443 444
        logger.info("prepare statement replace sql : {} ", stmt);
        return stmt;
445
    }
L
ligang 已提交
446 447

    /**
448 449 450
     * send mail as an attachment
     * @param title     title
     * @param content   content
L
ligang 已提交
451 452 453
     */
    public void sendAttachment(String title,String content){

G
gaojun2048 已提交
454
        List<User> users = alertDao.queryUserByAlertGroupId(taskExecutionContext.getSqlTaskExecutionContext().getWarningGroupId());
L
ligang 已提交
455 456

        // receiving group list
457
        List<String> receiversList = new ArrayList<>();
L
ligang 已提交
458
        for(User user:users){
459
            receiversList.add(user.getEmail().trim());
L
ligang 已提交
460 461
        }
        // custom receiver
L
ligang 已提交
462
        String receivers = sqlParameters.getReceivers();
L
ligang 已提交
463
        if (StringUtils.isNotEmpty(receivers)){
journey2018's avatar
journey2018 已提交
464
            String[] splits = receivers.split(COMMA);
L
ligang 已提交
465
            for (String receiver : splits){
466
                receiversList.add(receiver.trim());
L
ligang 已提交
467 468 469 470
            }
        }

        // copy list
471
        List<String> receiversCcList = new ArrayList<>();
L
ligang 已提交
472
        // Custom Copier
L
ligang 已提交
473
        String receiversCc = sqlParameters.getReceiversCc();
L
ligang 已提交
474
        if (StringUtils.isNotEmpty(receiversCc)){
journey2018's avatar
journey2018 已提交
475
            String[] splits = receiversCc.split(COMMA);
L
ligang 已提交
476
            for (String receiverCc : splits){
477
                receiversCcList.add(receiverCc.trim());
L
ligang 已提交
478 479 480
            }
        }

journey2018's avatar
journey2018 已提交
481
        String showTypeName = sqlParameters.getShowType().replace(COMMA,"").trim();
L
ligang 已提交
482
        if(EnumUtils.isValidEnum(ShowType.class,showTypeName)){
483 484
            Map<String, Object> mailResult = MailUtils.sendMails(receiversList,
                    receiversCcList, title, content, ShowType.valueOf(showTypeName).getDescp());
485
            if(!(boolean) mailResult.get(STATUS)){
C
chengshiwen 已提交
486
                throw new RuntimeException("send mail failed!");
487
            }
L
ligang 已提交
488 489
        }else{
            logger.error("showType: {} is not valid "  ,showTypeName);
490
            throw new RuntimeException(String.format("showType: %s is not valid ",showTypeName));
L
ligang 已提交
491 492 493 494
        }
    }

    /**
495 496 497 498 499
     * regular expressions match the contents between two specified strings
     * @param content           content
     * @param rgex              rgex
     * @param sqlParamsMap      sql params map
     * @param paramsPropsMap    params props map
L
ligang 已提交
500 501 502 503 504 505 506 507 508 509
     */
    public void setSqlParamsMap(String content, String rgex, Map<Integer,Property> sqlParamsMap, Map<String,Property> paramsPropsMap){
        Pattern pattern = Pattern.compile(rgex);
        Matcher m = pattern.matcher(content);
        int index = 1;
        while (m.find()) {

            String paramName = m.group(1);
            Property prop =  paramsPropsMap.get(paramName);

510 511 512 513 514
            if (prop == null) {
                logger.error("setSqlParamsMap: No Property with paramName: {} is found in paramsPropsMap of task instance"
                        + " with id: {}. So couldn't put Property in sqlParamsMap.", paramName, taskExecutionContext.getTaskInstanceId());
            }
            else {
L
ligang 已提交
515 516
            sqlParamsMap.put(index,prop);
            index ++;
517 518 519
                logger.info("setSqlParamsMap: Property with paramName: {} put in sqlParamsMap of content {} successfully.", paramName, content);
            }

L
ligang 已提交
520 521 522 523
        }
    }

    /**
524 525 526 527 528
     * print replace sql
     * @param content       content
     * @param formatSql     format sql
     * @param rgex          rgex
     * @param sqlParamsMap  sql params map
L
ligang 已提交
529 530 531 532
     */
    public void printReplacedSql(String content, String formatSql,String rgex, Map<Integer,Property> sqlParamsMap){
        //parameter print style
        logger.info("after replace sql , preparing : {}" , formatSql);
journey2018's avatar
journey2018 已提交
533
        StringBuilder logPrint = new StringBuilder("replaced sql , parameters:");
534 535 536 537
        if (sqlParamsMap == null) {
            logger.info("printReplacedSql: sqlParamsMap is null.");
        }
        else {
L
ligang 已提交
538 539 540
        for(int i=1;i<=sqlParamsMap.size();i++){
            logPrint.append(sqlParamsMap.get(i).getValue()+"("+sqlParamsMap.get(i).getType()+")");
        }
541
        }
542
        logger.info("Sql Params are {}", logPrint);
L
ligang 已提交
543 544
    }
}