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.query; 017 018import com.mybatisflex.core.dialect.IDialect; 019import com.mybatisflex.core.util.StringUtil; 020 021import java.util.List; 022 023/** 024 * 括号 025 */ 026public class Brackets extends QueryCondition { 027 028 private QueryCondition childCondition; 029 030 031 public Brackets(QueryCondition childCondition) { 032 this.childCondition = childCondition; 033 } 034 035 036 @Override 037 public QueryCondition and(QueryCondition nextCondition) { 038 connectToChild(nextCondition, SqlConnector.AND); 039 return this; 040 } 041 042 @Override 043 public QueryCondition or(QueryCondition nextCondition) { 044 connectToChild(nextCondition, SqlConnector.OR); 045 return this; 046 } 047 048 protected void connectToChild(QueryCondition nextCondition, SqlConnector connector) { 049 childCondition.connect(nextCondition, connector); 050 } 051 052 @Override 053 public Object getValue() { 054 return checkEffective() ? WrapperUtil.getValues(childCondition) : null; 055 } 056 057 @Override 058 public String toSql(List<QueryTable> queryTables, IDialect dialect) { 059 StringBuilder sql = new StringBuilder(); 060 if (checkEffective()) { 061 String childSql = childCondition.toSql(queryTables, dialect); 062 if (StringUtil.isNotBlank(childSql)) { 063 QueryCondition effectiveBefore = getEffectiveBefore(); 064 if (effectiveBefore != null) { 065 childSql = effectiveBefore.connector + "(" + childSql + ")"; 066 } 067 sql.append(childSql); 068 } else { 069 //all child conditions is not effective 070 //fixed gitee #I6W89G 071 this.effective = false; 072 } 073 } 074 075 if (this.next != null) { 076 return sql + next.toSql(queryTables, dialect); 077 } 078 079 return sql.toString(); 080 } 081 082 083 @Override 084 public String toString() { 085 return "Brackets{" + 086 "childCondition=" + childCondition + 087 '}'; 088 } 089}