Java Code Examples for com.alibaba.druid.stat.TableStat.Condition

The following examples show how to use com.alibaba.druid.stat.TableStat.Condition. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * 1层嵌套or语句
 */
@Test
public void test2() {
	String sql = "select id from travelrecord "
   			+ " where id = 1 and ( fee=3 or days=5 or name = 'zhangsan')" ;
	List<List<Condition>> list = getConditionList(sql);

	Assert.assertEquals(list.size(), 3);
	Assert.assertEquals(list.get(0).size(), 2);
	Assert.assertEquals(list.get(1).size(), 2);
	Assert.assertEquals(list.get(2).size(), 2);


	Assert.assertEquals(list.get(0).get(0).toString(), "travelrecord.name = zhangsan");
	Assert.assertEquals(list.get(0).get(1).toString(), "travelrecord.id = 1");

	Assert.assertEquals(list.get(1).get(0).toString(), "travelrecord.days = 5");
	Assert.assertEquals(list.get(1).get(1).toString(), "travelrecord.id = 1");

	Assert.assertEquals(list.get(2).get(0).toString(), "travelrecord.fee = 3");
	Assert.assertEquals(list.get(2).get(1).toString(), "travelrecord.id = 1");
}
 
Example 2
/**
 * 1层嵌套or语句
 */
@Test
public void test3() {
	String sql = "select id from travelrecord "
   			+ " where id = 1 and fee=3 or days=5 or name = 'zhangsan'" ;
	List<List<Condition>> list = getConditionList(sql);

	Assert.assertEquals(list.size(), 3);

	Assert.assertEquals(list.get(0).size(), 1);
	Assert.assertEquals(list.get(1).size(), 1);
	Assert.assertEquals(list.get(2).size(), 2);

	Assert.assertEquals(list.get(0).get(0).toString(), "travelrecord.name = zhangsan");

	Assert.assertEquals(list.get(1).get(0).toString(), "travelrecord.days = 5");

	Assert.assertEquals(list.get(2).get(0).toString(), "travelrecord.id = 1");
	Assert.assertEquals(list.get(2).get(1).toString(), "travelrecord.fee = 3");
}
 
Example 3
/**
 * or
 */
@Test
public void test2() {
    String sql = "select id from travelrecord "
            + " where id = 1 and ( fee=3 or days=5 or name = 'zhangsan')";
    List<WhereUnit> whereUnits = getAllWhereUnit(sql);
    WhereUnit whereUnit = whereUnits.get(0);
    List<Condition> list1 = whereUnit.getOutAndConditions();
    Assert.assertEquals(list1.get(0).toString(), "travelrecord.id = 1");

    WhereUnit childWhereUnits = whereUnit.getSubWhereUnit().get(0);
    List<List<Condition>> childList = childWhereUnits.getOrConditionList();

    Assert.assertEquals(childList.get(0).get(0).toString(), "travelrecord.name = zhangsan");
    Assert.assertEquals(childList.get(1).get(0).toString(), "travelrecord.days = 5");
    Assert.assertEquals(childList.get(2).get(0).toString(), "travelrecord.fee = 3");

}
 
Example 4
/**
 * OR
 */
@Test
public void test3() {
    String sql = "select id from travelrecord "
            + " where id = 1 and fee=3 or days=5 or name = 'zhangsan'";
    List<WhereUnit> whereUnits = getAllWhereUnit(sql);
    List<List<Condition>> list = whereUnits.get(0).getOrConditionList();
    Assert.assertEquals(list.size(), 3);

    Assert.assertEquals(list.get(0).size(), 1);
    Assert.assertEquals(list.get(1).size(), 1);
    Assert.assertEquals(list.get(2).size(), 2);

    Assert.assertEquals(list.get(0).get(0).toString(), "travelrecord.name = zhangsan");

    Assert.assertEquals(list.get(1).get(0).toString(), "travelrecord.days = 5");

    Assert.assertEquals(list.get(2).get(0).toString(), "travelrecord.id = 1");
    Assert.assertEquals(list.get(2).get(1).toString(), "travelrecord.fee = 3");
}
 
Example 5
/**
 * 解析 SQL 获取指定表及条件列的值
 * 
 * @param sql
 * @param tableName
 * @param colnumName
 * @return
 */
public List<Object> parseConditionValues(String sql, String tableName, String colnumName)  {
	
	List<Object> values = null;
	
	if ( sql != null && tableName != null && columnName != null ) {
	
		values = new ArrayList<Object>();
		
		MySqlStatementParser parser = new MySqlStatementParser(sql);
		SQLStatement stmt = parser.parseStatement();
		
		MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
		stmt.accept(visitor);
		
		String currentTable = visitor.getCurrentTable();
		if ( tableName.equalsIgnoreCase( currentTable ) ) {
			
			List<Condition> conditions = visitor.getConditions();
			for(Condition condition: conditions) {
				
				String ccN = condition.getColumn().getName();
				ccN = fixName(ccN);
				
				if ( colnumName.equalsIgnoreCase( ccN ) ) {					
					List<Object> ccVL = condition.getValues();
					values.addAll( ccVL );
				}
			}
		}				
	}
	return values;
}
 
Example 6
private List<List<Condition>> mergedConditions() {
	if(storedwhereUnits.size() == 0) {
		return new ArrayList<List<Condition>>();
	}
	for(WhereUnit whereUnit : storedwhereUnits) {
		mergeOneWhereUnit(whereUnit);
	}
	return getMergedConditionList(storedwhereUnits);
	
}
 
Example 7
/**
 * 一个WhereUnit内递归
 * @param whereUnit
 */
private void mergeOneWhereUnit(WhereUnit whereUnit) {
	if(whereUnit.getSubWhereUnit().size() > 0) {
		for(WhereUnit sub : whereUnit.getSubWhereUnit()) {
			mergeOneWhereUnit(sub);
		}
		
		if(whereUnit.getSubWhereUnit().size() > 1) {
			List<List<Condition>> mergedConditionList = getMergedConditionList(whereUnit.getSubWhereUnit());
			if(whereUnit.getOutConditions().size() > 0) {
				for(int i = 0; i < mergedConditionList.size() ; i++) {
					mergedConditionList.get(i).addAll(whereUnit.getOutConditions());
				}
			}
			whereUnit.setConditionList(mergedConditionList);
		} else if(whereUnit.getSubWhereUnit().size() == 1) {
			if(whereUnit.getOutConditions().size() > 0 && whereUnit.getSubWhereUnit().get(0).getConditionList().size() > 0) {
				for(int i = 0; i < whereUnit.getSubWhereUnit().get(0).getConditionList().size() ; i++) {
					whereUnit.getSubWhereUnit().get(0).getConditionList().get(i).addAll(whereUnit.getOutConditions());
				}
			}
			whereUnit.getConditionList().addAll(whereUnit.getSubWhereUnit().get(0).getConditionList());
		}
	} else {
		//do nothing
	}
}
 
Example 8
/**
 * 条件合并:多个WhereUnit中的条件组合
 * @return
 */
private List<List<Condition>> getMergedConditionList(List<WhereUnit> whereUnitList) {
	List<List<Condition>> mergedConditionList = new ArrayList<List<Condition>>();
	if(whereUnitList.size() == 0) {
		return mergedConditionList; 
	}
	mergedConditionList.addAll(whereUnitList.get(0).getConditionList());
	
	for(int i = 1; i < whereUnitList.size(); i++) {
		mergedConditionList = merge(mergedConditionList, whereUnitList.get(i).getConditionList());
	}
	return mergedConditionList;
}
 
Example 9
/**
 * 判定当前的条件列表 是否 另外一个条件列表的 子集
 * 
 * @author SvenAugustus
 * @param current 当前的条件列表 
 * @param other 另外一个条件列表
 * @return
 */
private boolean sqlConditionListInOther(List<Condition> current, List<Condition> other) {
  if (current == null) {
    if (other != null) {
      return false;
    }
    return true;
  }
  if (current.size() > other.size()) {
    return false;
  }
  if (other.size() == current.size()) {
    // 判定两个条件列表的元素是否内容相等
    return sqlConditionListEquals(current, other);
  }
  for (int j = 0; j < current.size(); j++) {
    boolean exists = false;
    for (int i = 0; i < other.size(); i++) {
      // 判定两个条件是否相等
      if (sqlConditionEquals(current.get(j), other.get(i))) {
        exists = true;
        break;
      }
    }
    if (!exists) {
      return false;
    }
  }
  return true;
}
 
Example 10
/**
 * 判定两个条件列表的元素是否内容相等
 * 
 * @author SvenAugustus
 * @param list1
 * @param list2
 * @return
 */
private boolean sqlConditionListEquals(List<Condition> list1, List<Condition> list2) {
  if (list1 == null) {
    if (list2 != null) {
      return false;
    }
    return true;
  }
  if (list2.size() != list1.size()) {
    return false;
  }
  int len = list1.size();
  for (int j = 0; j < len; j++) {
    boolean exists = false;
    for (int i = 0; i < len; i++) {
      // 判定两个条件是否相等
      if (sqlConditionEquals(list2.get(j), list1.get(i))) {
        exists = true;
        break;
      }
    }
    if (!exists) {
      return false;
    }
  }
  return true;
}
 
Example 11
/**
 * 3层嵌套or语句
 */
@Test
public void test1() {
	String sql = "select id from travelrecord "
   			+ " where id = 1 and ( fee=3 or days=5 or (traveldate = '2015-05-04 00:00:07.375' "
   			+ " and (user_id=2 or fee=days or fee = 0))) and id=2" ;
	List<List<Condition>> list = getConditionList(sql);
	Assert.assertEquals(list.size(), 5);
	Assert.assertEquals(list.get(0).size(), 2);
	Assert.assertEquals(list.get(1).size(), 2);
	Assert.assertEquals(list.get(2).size(), 3);
	Assert.assertEquals(list.get(3).size(), 4);
	Assert.assertEquals(list.get(4).size(), 3);

	Assert.assertEquals(list.get(0).get(0).toString(), "travelrecord.days = 5");
	Assert.assertEquals(list.get(0).get(1).toString(), "travelrecord.id = (1, 2)");

	Assert.assertEquals(list.get(1).get(0).toString(), "travelrecord.fee = 3");
	Assert.assertEquals(list.get(1).get(1).toString(), "travelrecord.id = (1, 2)");

	Assert.assertEquals(list.get(2).get(0).toString(), "travelrecord.fee = 0");
	Assert.assertEquals(list.get(2).get(1).toString(), "travelrecord.traveldate = 2015-05-04 00:00:07.375");
	Assert.assertEquals(list.get(2).get(2).toString(), "travelrecord.id = (1, 2)");

	Assert.assertEquals(list.get(3).get(0).toString(), "travelrecord.fee = null");
	Assert.assertEquals(list.get(3).get(1).toString(), "travelrecord.days = null");
	Assert.assertEquals(list.get(3).get(2).toString(), "travelrecord.traveldate = 2015-05-04 00:00:07.375");
	Assert.assertEquals(list.get(3).get(3).toString(), "travelrecord.id = (1, 2)");

	Assert.assertEquals(list.get(4).get(0).toString(), "travelrecord.user_id = 2");
	Assert.assertEquals(list.get(4).get(1).toString(), "travelrecord.traveldate = 2015-05-04 00:00:07.375");
	Assert.assertEquals(list.get(4).get(2).toString(), "travelrecord.id = (1, 2)");

	System.out.println(list.size());
}
 
Example 12
/**
 * 8层以上 嵌套or语句
 */
@Test
public void test5() {
  List<List<Condition>> list = getConditionList(sql);

  Assert.assertTrue(list.size() < 100);
}
 
Example 13
Source Project: dble   Source File: QueryConditionAnalyzer.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * parseConditionValues
 *
 * @param sql
 * @param table
 * @param column
 * @return
 */
public List<Object> parseConditionValues(String sql, String table, String column) {

    List<Object> values = null;

    if (sql != null && table != null && QueryConditionAnalyzer.this.columnName != null) {

        values = new ArrayList<>();

        MySqlStatementParser parser = new MySqlStatementParser(sql);
        SQLStatement stmt = parser.parseStatement();

        ServerSchemaStatVisitor visitor = new ServerSchemaStatVisitor();
        stmt.accept(visitor);

        String currentTable = visitor.getCurrentTable();
        if (table.equalsIgnoreCase(currentTable)) {

            List<Condition> conditions = visitor.getConditions();
            for (Condition condition : conditions) {

                String ccN = condition.getColumn().getName();
                ccN = fixName(ccN);

                if (column.equalsIgnoreCase(ccN)) {
                    List<Object> ccVL = condition.getValues();
                    values.addAll(ccVL);
                }
            }
        }
    }
    return values;
}
 
Example 14
Source Project: dble   Source File: ServerSchemaStatVisitor.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void handleCondition(SQLExpr expr, String operator, SQLExpr... valueExprs) {
    if (expr instanceof SQLCastExpr) {
        expr = ((SQLCastExpr) expr).getExpr();
    }

    Column column = this.getColumn(expr);
    if (column != null) {
        Condition condition = new Condition(column, operator);
        this.conditions.add(condition);

        SQLExpr[] var12 = valueExprs;
        int var13 = valueExprs.length;

        for (int var8 = 0; var8 < var13; ++var8) {
            SQLExpr item = var12[var8];
            Column valueColumn = this.getColumn(item);
            if (valueColumn == null) {
                if (item instanceof SQLNullExpr) {
                    condition.getValues().add(item);
                } else {
                    Object value = SQLEvalVisitorUtils.eval(this.getDbType(), item, this.getParameters(), false);
                    condition.getValues().add(value);
                }
            }
        }

    }
}
 
Example 15
Source Project: dble   Source File: ServerSchemaStatVisitor.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * turn all the condition in or into conditionList
 * exp (conditionA OR conditionB) into conditionList{conditionA,conditionB}
 * so the conditionA,conditionB can be group with outer conditions
 *
 */
private void resetConditionsFromWhereUnit(WhereUnit whereUnit) {
    if (!whereUnit.isFinishedExtend()) {
        List<List<Condition>> retList = new ArrayList<>();
        List<Condition> outSideCondition = new ArrayList<>();
        outSideCondition.addAll(conditions);
        List<Relationship> outSideRelationship = new ArrayList<>();
        outSideRelationship.addAll(relationships);
        this.conditions.clear();
        this.relationships.clear();
        for (SQLExpr sqlExpr : whereUnit.getSplitedExprList()) {
            sqlExpr.accept(this);
            List<Condition> conds = new ArrayList<>();
            conds.addAll(getConditions());
            conds.addAll(outSideCondition);
            Set<Relationship> relations = new HashSet<>();
            relations.addAll(getRelationships());
            relations.addAll(outSideRelationship);
            ConditionUtil.extendConditionsFromRelations(conds, relations);
            retList.add(conds);
            this.conditions.clear();
            this.relationships.clear();
        }
        whereUnit.setOrConditionList(retList);

        for (WhereUnit subWhere : whereUnit.getSubWhereUnit()) {
            resetConditionsFromWhereUnit(subWhere);
        }
        whereUnit.setFinishedExtend(true);
    }
}
 
Example 16
Source Project: dble   Source File: ServerSchemaStatVisitor.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static void mergeOuterRelations(WhereUnit whereUnit) {
    if (whereUnit.getSubWhereUnit().size() > 0) {
        for (WhereUnit sub : whereUnit.getSubWhereUnit()) {
            mergeOuterRelations(sub);
            if (whereUnit.getOutRelationships().size() > 0) {
                for (List<TableStat.Condition> subConditionList : sub.getOrConditionList()) {
                    ConditionUtil.extendConditionsFromRelations(subConditionList, whereUnit.getOutRelationships());
                }
            }
        }
    }
}
 
Example 17
Source Project: dble   Source File: ServerSchemaStatVisitor.java    License: GNU General Public License v2.0 5 votes vote down vote up
private WhereUnit generateWhereUnit() {
    List<Condition> conditionList = new ArrayList<>();
    conditionList.addAll(this.getConditions());
    ConditionUtil.extendConditionsFromRelations(conditionList, this.relationships);
    if (conditionList.size() == 0 && this.relationships.size() == 0) {
        return null;
    }
    WhereUnit whereUnit = new WhereUnit();
    whereUnit.setFinishedParse(true);
    List<List<Condition>> retList = new ArrayList<>();
    retList.add(conditionList);
    whereUnit.setOrConditionList(retList);
    whereUnit.addOutRelationships(this.relationships);
    return whereUnit;
}
 
Example 18
/**
 * 3 nest or
 */
@Test
public void test1() {
    String sql = "select id from travelrecord "
            + " where id = 1 and ( fee=3 or days=5 or (traveldate = '2015-05-04 00:00:07.375' "
            + " and (user_id=2 or fee=days or fee = 0))) and id=2";
    List<WhereUnit> whereUnits = getAllWhereUnit(sql);
    WhereUnit whereUnit = whereUnits.get(0);
    List<Condition> list1 = whereUnit.getOutAndConditions();

    Assert.assertEquals(list1.get(0).toString(), "travelrecord.id = 1");
    Assert.assertEquals(list1.get(1).toString(), "travelrecord.id = 2");

    WhereUnit childWhereUnits = whereUnit.getSubWhereUnit().get(0);
    List<List<Condition>> childList = childWhereUnits.getOrConditionList();

    Assert.assertEquals(childList.get(0).get(0).toString(), "travelrecord.days = 5");
    Assert.assertEquals(childList.get(1).get(0).toString(), "travelrecord.fee = 3");

    WhereUnit child2WhereUnits = childWhereUnits.getSubWhereUnit().get(0);
    List<Condition> child2 = child2WhereUnits.getOutAndConditions();
    Assert.assertEquals(child2.get(0).toString(), "travelrecord.traveldate = 2015-05-04 00:00:07.375");

    WhereUnit child3WhereUnits = child2WhereUnits.getSubWhereUnit().get(0);
    List<List<Condition>> child3List = child3WhereUnits.getOrConditionList();
    Assert.assertEquals(child3List.get(0).get(0).toString(), "travelrecord.fee = 0");
    Assert.assertEquals(child3List.get(1).size(), 0);
    Assert.assertEquals(child3List.get(2).get(0).toString(), "travelrecord.user_id = 2");

}
 
Example 19
Source Project: baymax   Source File: MySqlSqlParser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 默认通过visitor解析 子类可以覆盖
 *
 * 限制:分表的where中,分表key只能出现一次且必须是 a=1 或者 a in ()的类型
 * @param result
 */
@Override
public void parse(ParseResult result) {
    // 解析sql
    statement = parser.parseStatement();

    // 用visiter遍历sql
    statement.accept(visitor);

    // 表名格式化
    alisMapFix(result);

    // 原始sql
    result.setSql(sql);

    // conditions
    //if (CalculateUnitUtil.hasPartitionTable(result.getTables())){
        List<List<Condition>> mergedConditionList = new ArrayList<List<Condition>>();
        if (visitor.hasOrCondition()){
            OrVisitor orVisitor = new OrVisitor();
            mergedConditionList = new OrVisitor.OrEntity(orVisitor, statement).getOrConditions();
        }else {
            if (visitor.getConditions() != null && visitor.getConditions().size() != 0){
                mergedConditionList.add(visitor.getConditions());
            }
        }
        // 有分区表 计算路由单元
        result.setCalculateUnits(CalculateUnitUtil.buildCalculateUnits(result.getTableAliasMap(), mergedConditionList));
    //}
}
 
Example 20
Source Project: Mycat2   Source File: WhereUnit.java    License: GNU General Public License v3.0 4 votes vote down vote up
public List<Condition> getOutConditions() {
	return outConditions;
}
 
Example 21
Source Project: Mycat2   Source File: WhereUnit.java    License: GNU General Public License v3.0 4 votes vote down vote up
public void addOutConditions(List<Condition> outConditions) {
	this.outConditions.addAll(outConditions);
}
 
Example 22
Source Project: Mycat2   Source File: WhereUnit.java    License: GNU General Public License v3.0 4 votes vote down vote up
public List<List<Condition>> getConditionList() {
	return conditionList;
}
 
Example 23
Source Project: Mycat2   Source File: WhereUnit.java    License: GNU General Public License v3.0 4 votes vote down vote up
public void setConditionList(List<List<Condition>> conditionList) {
	this.conditionList = conditionList;
}
 
Example 24
/**
	 * 两个list中的条件组合
	 * @param list1
	 * @param list2
	 * @return
	 */
	    private List<List<Condition>> merge(List<List<Condition>> list1, List<List<Condition>> list2) {
        if(list1.size() == 0) {
            return list2;
        } else if (list2.size() == 0) {
            return list1;
        }
        
		List<List<Condition>> retList = new ArrayList<List<Condition>>();
		for(int i = 0; i < list1.size(); i++) {
			for(int j = 0; j < list2.size(); j++) {
//				List<Condition> listTmp = new ArrayList<Condition>();
//				listTmp.addAll(list1.get(i));
//				listTmp.addAll(list2.get(j));
//				retList.add(listTmp);
			    /**
		         * 单纯做笛卡尔积运算,会导致非常多不必要的条件列表,</br>
		         * 当whereUnit和条件相对多时,会急剧增长条件列表项,内存直线上升,导致假死状态</br>
		         * 因此,修改算法为 </br>
		         * 1、先合并两个条件列表的元素为一个条件列表</br>
		         * 2、计算合并后的条件列表,在结果retList中:</br>
		         * &nbsp;2-1、如果当前的条件列表 是 另外一个条件列表的 超集,更新,并标识已存在</br>
		         * &nbsp;2-2、如果当前的条件列表 是 另外一个条件列表的 子集,标识已存在</br>
		         * 3、最后,如果被标识不存在,加入结果retList,否则丢弃。</br>
		         * 
		         * @author SvenAugustus
		         */
  			    // 合并两个条件列表的元素为一个条件列表
                List<Condition> listTmp = mergeSqlConditionList(list1.get(i), list2.get(j));
      
                // 判定当前的条件列表 是否 另外一个条件列表的 子集
                boolean exists = false;
                Iterator<List<Condition>> it = retList.iterator();
                while (it.hasNext()) {
                  List<Condition> result = (List<Condition>) it.next();
                  if (result != null && listTmp != null && listTmp.size() > result.size()) {
                    // 如果当前的条件列表 是 另外一个条件列表的 超集,更新,并标识已存在
                    if (sqlConditionListInOther(result, listTmp)) {
                      result.clear();
                      result.addAll(listTmp);
                      exists = true;
                      break;
                    }
                  } else {
                    // 如果当前的条件列表 是 另外一个条件列表的 子集,标识已存在
                    if (sqlConditionListInOther(listTmp, result)) {
                      exists = true;
                      break;
                    }
                  }
                }
                if (!exists) {// 被标识不存在,加入
                  retList.add(listTmp);
                } // 否则丢弃
			}
		}
        return retList;
    }
 
Example 25
/**
 * 判定两个条件是否相等
 * 
 * @author SvenAugustus
 * @param obj1
 * @param obj2
 * @return
 */
private boolean sqlConditionEquals(Condition obj1, Condition obj2) {
  if (obj1 == obj2) {
    return true;
  }
  if (obj2 == null) {
    return false;
  }
  if (obj1.getClass() != obj2.getClass()) {
    return false;
  }
  Condition other = (Condition) obj2;
  if (obj1.getColumn() == null) {
    if (other.getColumn() != null) {
      return false;
    }
  } else if (!obj1.getColumn().equals(other.getColumn())) {
    return false;
  }
  if (obj1.getOperator() == null) {
    if (other.getOperator() != null) {
      return false;
    }
  } else if (!obj1.getOperator().equals(other.getOperator())) {
    return false;
  }
  if (obj1.getValues() == null) {
    if (other.getValues() != null) {
      return false;
    }
  } else {
    boolean notEquals=false;
    for (Object val1: obj1.getValues()) {
      for (Object val2: obj2.getValues()) {
        if(val1==null) {
          if(val2!=null) {
            notEquals=true;
            break;
          }
        }else if(!val1.equals(val2)) {
          notEquals=true;
          break;
        }
      }
      if(notEquals)break;
    }
    if(notEquals)
    return false;
  }
  return true;
}
 
Example 26
Source Project: Mycat2   Source File: DefaultDruidParser.java    License: GNU General Public License v3.0 4 votes vote down vote up
public List<Condition> getConditions() {
	return conditions;
}
 
Example 27
Source Project: Mycat2   Source File: DefaultDruidParser.java    License: GNU General Public License v3.0 4 votes vote down vote up
/**
	 * 子类可覆盖(如果该方法解析得不到表名、字段等信息的,就覆盖该方法,覆盖成空方法,然后通过statementPparse去解析)
	 * 通过visitor解析:有些类型的Statement通过visitor解析得不到表名、
	 * @param stmt
	 */
	@Override
	public void visitorParse(RouteResultset rrs, SQLStatement stmt,MycatSchemaStatVisitor visitor) throws SQLNonTransientException{

		stmt.accept(visitor);
		ctx.setVisitor(visitor);

		if(stmt instanceof SQLSelectStatement){
			SQLSelectQuery query = ((SQLSelectStatement) stmt).getSelect().getQuery();
			if(query instanceof MySqlSelectQueryBlock){
				if(((MySqlSelectQueryBlock)query).isForUpdate()){
					rrs.setSelectForUpdate(true);
				}
			}
		}

		List<List<Condition>> mergedConditionList = new ArrayList<List<Condition>>();
		if(visitor.hasOrCondition()) {//包含or语句
			//TODO
			//根据or拆分
			mergedConditionList = visitor.splitConditions();
		} else {//不包含OR语句
			mergedConditionList.add(visitor.getConditions());
		}
		
		if(visitor.isHasChange()){	// 在解析的过程中子查询被改写了.需要更新ctx.
			ctx.setSql(stmt.toString());
			rrs.setStatement(ctx.getSql());
		}
		
		if(visitor.getAliasMap() != null) {
			for(Map.Entry<String, String> entry : visitor.getAliasMap().entrySet()) {
				String key = entry.getKey();
				String value = entry.getValue();
				if(key != null && key.indexOf("`") >= 0) {
					key = key.replaceAll("`", "");
				}
				if(value != null && value.indexOf("`") >= 0) {
					value = value.replaceAll("`", "");
				}
				//表名前面带database的,去掉
				if(key != null) {
					int pos = key.indexOf(".");
					if(pos> 0) {
						key = key.substring(pos + 1);
					}
					
					tableAliasMap.put(key.toUpperCase(), value);
				}
				

//				else {
//					tableAliasMap.put(key, value);
//				}

			}
			ctx.addTables(visitor.getTables());
			
			visitor.getAliasMap().putAll(tableAliasMap);
			ctx.setTableAliasMap(tableAliasMap);
		}
		ctx.setRouteCalculateUnits(this.buildRouteCalculateUnits(visitor, mergedConditionList));
	}
 
Example 28
Source Project: Mycat2   Source File: DefaultDruidParser.java    License: GNU General Public License v3.0 4 votes vote down vote up
private List<RouteCalculateUnit> buildRouteCalculateUnits(SchemaStatVisitor visitor, List<List<Condition>> conditionList) {
	List<RouteCalculateUnit> retList = new ArrayList<RouteCalculateUnit>();

	//遍历condition ,找分片字段
	for(int i = 0; i < conditionList.size(); i++) {
		RouteCalculateUnit routeCalculateUnit = new RouteCalculateUnit();
		for(Condition condition : conditionList.get(i)) {
			List<Object> values = condition.getValues();
			if(values.size() == 0) {
				continue;  
			}
			if(checkConditionValues(values)) {
				String columnName = StringUtil.removeBackquote(condition.getColumn().getName().toUpperCase());
				String tableName = StringUtil.removeBackquote(condition.getColumn().getTable().toUpperCase());
				int index = 0;

					if(visitor.getAliasMap() != null && visitor.getAliasMap().get(tableName) != null
						&& !visitor.getAliasMap().get(tableName).equals(tableName)) {
					tableName = visitor.getAliasMap().get(tableName);
				}
				//处理schema.table的情况
				if ((index = tableName.indexOf(".")) != -1) {
					tableName = tableName.substring(index + 1);
				}
				tableName = tableName.toUpperCase();
				//确保表名是大写
				if(visitor.getAliasMap() != null && visitor.getAliasMap().get(tableName) == null) {//子查询的别名条件忽略掉,不参数路由计算,否则后面找不到表
					continue;
				}
				
				String operator = condition.getOperator();
				
				//只处理between ,in和=3中操作符
				if(operator.equals("between")) {
					RangeValue rv = new RangeValue(values.get(0), values.get(1), RangeValue.EE);
							routeCalculateUnit.addShardingExpr(tableName.toUpperCase(), columnName, rv);
				} else if(operator.equals("=") || operator.toLowerCase().equals("in")){ //只处理=号和in操作符,其他忽略
							routeCalculateUnit.addShardingExpr(tableName.toUpperCase(), columnName, values.toArray());
				}
			}
		}
		retList.add(routeCalculateUnit);
	}
	return retList;
}
 
Example 29
Source Project: Mycat2   Source File: DQLRouteTest.java    License: GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private List<RouteCalculateUnit> visitorParse(RouteResultset rrs, SQLStatement stmt, MycatSchemaStatVisitor visitor) throws Exception {

	stmt.accept(visitor);

	List<List<Condition>> mergedConditionList = new ArrayList<List<Condition>>();
	if (visitor.hasOrCondition()) {// 包含or语句
		// TODO
		// 根据or拆分
		mergedConditionList = visitor.splitConditions();
	} else {// 不包含OR语句
		mergedConditionList.add(visitor.getConditions());
	}

	if (visitor.getAliasMap() != null) {
		for (Map.Entry<String, String> entry : visitor.getAliasMap().entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			if (key != null && key.indexOf("`") >= 0) {
				key = key.replaceAll("`", "");
			}
			if (value != null && value.indexOf("`") >= 0) {
				value = value.replaceAll("`", "");
			}
			// 表名前面带database的,去掉
			if (key != null) {
				int pos = key.indexOf(".");
				if (pos > 0) {
					key = key.substring(pos + 1);
				}
			}

			if (key.equals(value)) {
				ctx.addTable(key.toUpperCase());
			}
			// else {
			// tableAliasMap.put(key, value);
			// }
			tableAliasMap.put(key.toUpperCase(), value);
		}
		visitor.getAliasMap().putAll(tableAliasMap);
		ctx.setTableAliasMap(tableAliasMap);
	}

	//利用反射机制单元测试DefaultDruidParser类的私有方法buildRouteCalculateUnits
	Class<?> clazz = Class.forName("io.mycat.route.parser.druid.impl.DefaultDruidParser");
	Method buildRouteCalculateUnits = clazz.getDeclaredMethod("buildRouteCalculateUnits",
			new Class[] { SchemaStatVisitor.class, List.class });
	//System.out.println("buildRouteCalculateUnits:\t" + buildRouteCalculateUnits);
	Object newInstance = clazz.newInstance();
	buildRouteCalculateUnits.setAccessible(true);
	Object returnValue = buildRouteCalculateUnits.invoke(newInstance,
			new Object[] { visitor, mergedConditionList });
	List<RouteCalculateUnit> retList = new ArrayList<RouteCalculateUnit>();
	if (returnValue instanceof ArrayList<?>) {
		retList.add(((ArrayList<RouteCalculateUnit>)returnValue).get(0));
		//retList = (ArrayList<RouteCalculateUnit>)returnValue;
		//System.out.println(taskList.get(0).getTablesAndConditions().values());			
	}
	return retList;
}
 
Example 30
Source Project: dble   Source File: WhereUnit.java    License: GNU General Public License v2.0 4 votes vote down vote up
public List<Condition> getOutAndConditions() {
    return outAndConditions;
}