본문 바로가기
  • writing on sticky note
카테고리 없음

깐죽깐죽깐죽깐죽ㅁㅁㅁㅁ

by 도담대디 2025. 4. 13.

Pattern pattern = Pattern.compile(
    "(\\s+(AND|OR)\\s+)?([\\w\\.]+)\\s+(=|LIKE)\\s+(?:'%'\\s*\\|\\|\\s*)?(#\\w+#|\\$\\w+\\$)(\\s*\\|\\|\\s*'%')?",
    Pattern.CASE_INSENSITIVE
);
Matcher matcher = pattern.matcher(queryText);
StringBuffer result = new StringBuffer();

while (matcher.find()) {
    String connector = matcher.group(1) != null ? matcher.group(1).trim() : "";
    String column = matcher.group(3);            // 컬럼명
    String operator = matcher.group(4);          // = 또는 LIKE
    String rawParam = matcher.group(5);          // #param# 또는 $param$
    String paramName = rawParam.replaceAll("[#$]", "");
    String suffix = matcher.group(6);            // || '%'

    Object value = param.get(paramName);

    boolean isEmpty = (value == null || value.toString().trim().isEmpty());

    if (isEmpty) {
        if (matcher.start() == 0 || "AND".equalsIgnoreCase(connector) || "OR".equalsIgnoreCase(connector)) {
            matcher.appendReplacement(result, "1=1");
        } else {
            matcher.appendReplacement(result, "");
        }
        continue;
    }

    // 숫자형 체크
    boolean isNumeric = value.toString().matches("^-?\\d+(\\.\\d+)?$");

    String replacedValue;
    if ("LIKE".equalsIgnoreCase(operator)) {
        if (isNumeric) {
            // 숫자형인데 LIKE 쓰면 = 으로 강제 처리
            replacedValue = value.toString();
            operator = "=";
        } else {
            replacedValue = "'%" + value.toString().trim() + "%'";
        }
    } else {
        replacedValue = isNumeric ? value.toString() : "'" + value.toString().trim() + "'";
    }

    String newCondition = connector + " " + column + " " + operator + " " + replacedValue;
    matcher.appendReplacement(result, Matcher.quoteReplacement(newCondition));
}

matcher.appendTail(result);

// WHERE 앞에 1=1 붙여 안정성 확보
finalQuery = result.toString().replaceAll("(?i)\\bWHERE\\b", "WHERE 1=1 AND");