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.dialect;
017
018import com.mybatisflex.core.util.StringUtil;
019
020import java.util.Collections;
021import java.util.Locale;
022import java.util.Set;
023
024/**
025 * 用于对数据库的关键字包装
026 */
027public class KeywordWrap {
028
029    /**
030     * 无反义处理, 适用于 db2, informix, clickhouse 等
031     */
032    public final static KeywordWrap NONE = new KeywordWrap("", "") {
033        @Override
034        public String wrap(String keyword) {
035            return keyword;
036        }
037    };
038
039    /**
040     * 反引号反义处理, 适用于 mysql, h2 等
041     */
042    public final static KeywordWrap BACKQUOTE = new KeywordWrap("`", "`");
043
044    /**
045     * 双引号反义处理, 适用于 postgresql, sqlite, derby, oracle 等
046     */
047    public final static KeywordWrap DOUBLE_QUOTATION = new KeywordWrap("\"", "\"");
048
049    /**
050     * 方括号反义处理, 适用于 sqlserver
051     */
052    public final static KeywordWrap SQUARE_BRACKETS = new KeywordWrap("[", "]");
053
054    /**
055     * 大小写敏感
056     */
057    private boolean caseSensitive = false;
058
059    /**
060     * 数据库关键字
061     */
062    private Set<String> keywords = Collections.emptySet();
063
064    /**
065     * 前缀
066     */
067    private final String prefix;
068
069    /**
070     * 后缀
071     */
072    private final String suffix;
073
074
075    public KeywordWrap(String prefix, String suffix) {
076        this(false, Collections.emptySet(), prefix, suffix);
077    }
078
079    public KeywordWrap(Set<String> keywords, String prefix, String suffix) {
080        this(false, keywords, prefix, suffix);
081    }
082
083    public KeywordWrap(boolean caseSensitive, Set<String> keywords, String prefix, String suffix) {
084        this.caseSensitive = caseSensitive;
085        this.keywords = keywords;
086        this.prefix = prefix;
087        this.suffix = suffix;
088    }
089
090    public String wrap(String keyword) {
091        if (StringUtil.isBlank(keyword) || "*".equals(keyword)) {
092            return keyword;
093        }
094        if (caseSensitive || keywords.isEmpty() || keywords.contains(keyword.toUpperCase(Locale.ENGLISH))) {
095            return prefix + keyword + suffix;
096        }
097        return keyword;
098    }
099
100}