001/** 002 * Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package com.mybatisflex.core.util; 017 018public class SqlUtil { 019 020 021 public static void keepColumnSafely(String column) { 022 if (StringUtil.isBlank(column)) { 023 throw new IllegalArgumentException("Column must not be empty"); 024 } else { 025 column = column.trim(); 026 } 027 028 int strLen = column.length(); 029 for (int i = 0; i < strLen; ++i) { 030 char ch = column.charAt(i); 031 if (Character.isWhitespace(ch)) { 032 throw new IllegalArgumentException("Column must not has space char."); 033 } 034 if (isUnSafeChar(ch)) { 035 throw new IllegalArgumentException("Column has unsafe char: [" + ch + "]."); 036 } 037 } 038 } 039 040 041 /** 042 * 仅支持字母、数字、下划线、空格、逗号、小数点(支持多个字段排序) 043 */ 044 private static String SQL_ORDER_BY_PATTERN = "[a-zA-Z0-9_\\ \\,\\.]+"; 045 046 public static void keepOrderBySqlSafely(String value) { 047 if (!value.matches(SQL_ORDER_BY_PATTERN)) { 048 throw new IllegalArgumentException("Order By sql not safe, order by string: " + value); 049 } 050 } 051 052 053 private static final char[] UN_SAFE_CHARS = "'`\"<>&*+=#-;".toCharArray(); 054 055 private static boolean isUnSafeChar(char ch) { 056 for (char c : UN_SAFE_CHARS) { 057 if (c == ch) { 058 return true; 059 } 060 } 061 return false; 062 } 063 064 065 /** 066 * 根据数据库响应结果判断数据库操作是否成功。 067 * 068 * @param result 数据库操作返回影响条数 069 * @return {@code true} 操作成功,{@code false} 操作失败。 070 */ 071 public static boolean retBool(int result) { 072 return result >= 1; 073 } 074 075 /** 076 * 根据数据库响应结果判断数据库操作是否成功。 077 * 078 * @param result 数据库操作返回影响条数 079 * @return {@code true} 操作成功,{@code false} 操作失败。 080 */ 081 public static boolean retBool(long result) { 082 return result >= 1L; 083 } 084 085 086}