com.alibaba.druid.sql.ast.statement.SQLUpdateStatement Java Examples

The following examples show how to use com.alibaba.druid.sql.ast.statement.SQLUpdateStatement. 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
Source File: UpdateParser.java    From dts with Apache License 2.0 5 votes vote down vote up
@Override
public TableDataInfo getPresentValue(List<Object> sqlParamsList, SQLUpdateStatement parseSqlStatement,
    StatementAdapter statementAdapter, TableMetaInfo tableMetaInfo) throws SQLException {
    TableDataInfo txcTable = new TableDataInfo();
    txcTable.setTableName(parseSqlStatement.getTableName().getSimpleName());
    TxcLine txcLine = new TxcLine();
    List<SQLUpdateSetItem> items = parseSqlStatement.getItems();
    int variantExpr = 0;
    for (int i = 0; i < items.size(); i++) {
        SQLUpdateSetItem sqlUpdateSetItem = items.get(i);
        TxcField txcField = new TxcField();
        String cloumnName =
            SQLUtils.toSQLString(sqlUpdateSetItem.getColumn()).replace("\'", "").replace("`", "").trim();
        txcField.setName(cloumnName);
        if (sqlUpdateSetItem.getValue() instanceof SQLVariantRefExpr) {
            txcField.setValue(sqlParamsList.get(variantExpr++));
        } else if (sqlUpdateSetItem.getValue() instanceof SQLValuableExpr) {
            txcField.setValue(SQLUtils.toSQLString(items.get(i).getValue()));
        } else {
            throw new UnsupportedOperationException(
                String.format("Do not support complex sql,%s", sqlUpdateSetItem.getClass().toString()));
        }
        txcField.setJdkValue(SerializeUtils.serialize(txcField.getValue()));
        txcLine.getFields().add(txcField);
    }
    txcTable.getLine().add(txcLine);
    return txcTable;
}
 
Example #2
Source File: UpdateParser.java    From dts with Apache License 2.0 5 votes vote down vote up
@Override
protected List<Object> getWhereParams(List<Object> sqlParamsList, SQLUpdateStatement parseSqlStatement) {
    if (sqlParamsList != null && !sqlParamsList.isEmpty()) {
        int size = 0;
        for (SQLUpdateSetItem sqlUpdateSetItem : parseSqlStatement.getItems()) {
            if (sqlUpdateSetItem.getValue() instanceof SQLVariantRefExpr) {
                size++;
            }
        }
        return Lists.newArrayList(sqlParamsList.subList(size, sqlParamsList.size()));
    }
    return Lists.newArrayList();
}
 
Example #3
Source File: UpdateParser.java    From dts with Apache License 2.0 5 votes vote down vote up
@Override
protected String selectSql(SQLUpdateStatement mySqlUpdateStatement, Set<String> primaryKeyNameSet) {
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("SELECT ");
    List<SQLUpdateSetItem> items = mySqlUpdateStatement.getItems();
    for (SQLUpdateSetItem sqlUpdateSetItem : items) {
        stringBuffer.append(SQLUtils.toSQLString(sqlUpdateSetItem.getColumn())).append(",");
    }
    stringBuffer.append(String.join(",", primaryKeyNameSet));
    stringBuffer.append(" from ").append(mySqlUpdateStatement.getTableName().getSimpleName()).append(" where ");
    stringBuffer.append(SQLUtils.toSQLString(mySqlUpdateStatement.getWhere()));
    return stringBuffer.toString();
}
 
Example #4
Source File: UpdateRollback.java    From dts with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean canRollback(CommitInfo commitInfo, Connection connection) throws SQLException {
    String sql = commitInfo.getSql();
    SQLUpdateStatement sqlParseStatement = (SQLUpdateStatement)new MySqlStatementParser(sql).parseStatement();
    TableMetaInfo tableMetaInfo =
        TableMetaUtils.getTableMetaInfo(connection, sqlParseStatement.getTableName().getSimpleName());
    TableDataInfo dbValue = UpdateParser.getInstance().getOriginValue(commitInfo.getWhereParams(),
        sqlParseStatement, connection, tableMetaInfo);
    if (commitInfo.getOriginalValue().getLine().size() == 0) {
        return false;
    }
    for (TxcLine txcLine : dbValue.getLine()) {
        txcLine.setPrimaryKeyValues(commitInfo.getPresentValue().getLine().get(0).getPrimaryKeyValues());
        boolean diff = DiffUtils.diff(commitInfo.getPresentValue().getLine().get(0), txcLine);
        if (!diff) {
            try {
                logger.error("data conflict, before:{},after:{}",
                    DiffUtils.getObjectMapper().writeValueAsString(commitInfo.getPresentValue().getLine().get(0)),
                    DiffUtils.getObjectMapper().writeValueAsString(txcLine));
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            return false;
        }
    }
    return true;
}
 
Example #5
Source File: SqlParser.java    From es_data_export with Apache License 2.0 5 votes vote down vote up
public static boolean isInsertSql(String sql){
	MySqlStatementParser parser = new MySqlStatementParser(sql);
	SQLStatement statement = parser.parseStatement();
	if(statement instanceof SQLInsertStatement){
		SQLInsertStatement insert =(SQLInsertStatement) statement; 
		tableName = insert.getTableName().toString();
		return true;
	}else if(statement instanceof SQLUpdateStatement){
		SQLUpdateStatement update =(SQLUpdateStatement) statement; 
		tableName = update.getTableName().toString();
		return true;
	}
	return false;
}
 
Example #6
Source File: MycatSchemaStatVisitor.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public boolean visit(SQLUpdateStatement x) {
    setAliasMap();

    setMode(x, Mode.Update);

    SQLName identName = x.getTableName();
    if (identName != null) {
        String ident = identName.toString();
        String alias = x.getTableSource().getAlias();
        setCurrentTable(ident);

        TableStat stat = getTableStat(ident);
        stat.incrementUpdateCount();

        Map<String, String> aliasMap = getAliasMap();
        
        aliasMap.put(ident, ident);
        if(alias != null) {
        	aliasMap.put(alias, ident);
        }
    } else {
        x.getTableSource().accept(this);
    }

    accept(x.getItems());
    accept(x.getWhere());

    return false;
}
 
Example #7
Source File: DruidUpdateParserTest.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public void throwExceptionParse(String sql, boolean throwException) throws NoSuchMethodException {
    MySqlStatementParser parser = new MySqlStatementParser(sql);
    List<SQLStatement> statementList = parser.parseStatementList();
    SQLStatement sqlStatement = statementList.get(0);
    MySqlUpdateStatement update = (MySqlUpdateStatement) sqlStatement;
    SchemaConfig schemaConfig = mock(SchemaConfig.class);
    Map<String, TableConfig> tables = mock(Map.class);
    TableConfig tableConfig = mock(TableConfig.class);
    String tableName = "hotnews";
    when((schemaConfig).getTables()).thenReturn(tables);
    when(tables.get(tableName)).thenReturn(tableConfig);
    when(tableConfig.getParentTC()).thenReturn(null);
    RouteResultset routeResultset = new RouteResultset(sql, 11);
    Class c = DruidUpdateParser.class;
    Method method = c.getDeclaredMethod("confirmShardColumnNotUpdated", new Class[]{SQLUpdateStatement.class, SchemaConfig.class, String.class, String.class, String.class, RouteResultset.class});
    method.setAccessible(true);
    try {
        method.invoke(c.newInstance(), update, schemaConfig, tableName, "ID", "", routeResultset);
        if (throwException) {
            System.out.println("未抛异常,解析通过则不对!");
            Assert.assertTrue(false);
        } else {
            System.out.println("未抛异常,解析通过,此情况分片字段可能在update语句中但是实际不会被更新");
            Assert.assertTrue(true);
        }
    } catch (Exception e) {
        if (throwException) {
            System.out.println(e.getCause().getClass());
            Assert.assertTrue(e.getCause() instanceof SQLNonTransientException);
            System.out.println("抛异常原因为SQLNonTransientException则正确");
        } else {
            System.out.println("抛异常,需要检查");
            Assert.assertTrue(false);
        }
    }
}
 
Example #8
Source File: DruidUpdateParserTest.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
public void throwExceptionParse(String sql, boolean throwException) throws NoSuchMethodException {
    MySqlStatementParser parser = new MySqlStatementParser(sql);
    List<SQLStatement> statementList = parser.parseStatementList();
    SQLStatement sqlStatement = statementList.get(0);
    MySqlUpdateStatement update = (MySqlUpdateStatement) sqlStatement;
    SchemaConfig schemaConfig = mock(SchemaConfig.class);
    Map<String, TableConfig> tables = mock(Map.class);
    TableConfig tableConfig = mock(TableConfig.class);
    String tableName = "hotnews";
    when((schemaConfig).getTables()).thenReturn(tables);
    when(tables.get(tableName)).thenReturn(tableConfig);
    when(tableConfig.getParentTC()).thenReturn(null);
    RouteResultset routeResultset = new RouteResultset(sql, 11);
    Class c = DruidUpdateParser.class;
    Method method = c.getDeclaredMethod("confirmShardColumnNotUpdated", new Class[]{SQLUpdateStatement.class, SchemaConfig.class, String.class, String.class, String.class, RouteResultset.class});
    method.setAccessible(true);
    try {
        method.invoke(c.newInstance(), update, schemaConfig, tableName, "ID", "", routeResultset);
        if (throwException) {
            System.out.println("Not passed without exception is not correct");
            Assert.assertTrue(false);
        } else {
            System.out.println("Passed without exception. Maybe the partition key exists in update statement,but not update in fact");
            Assert.assertTrue(true);
        }
    } catch (Exception e) {
        if (throwException) {
            System.out.println(e.getCause().getClass());
            Assert.assertTrue(e.getCause() instanceof SQLNonTransientException);
            System.out.println("SQLNonTransientException is expected");
        } else {
            System.out.println("need checked");
            Assert.assertTrue(false);
        }
    }
}
 
Example #9
Source File: SqlVisitor.java    From baymax with Apache License 2.0 5 votes vote down vote up
@Override
public boolean visit(SQLUpdateStatement x) {
    setAliasMap();

    setMode(x, Mode.Update);

    SQLName identName = x.getTableName();
    if (identName != null) {
        String ident = identName.toString();
        //
        String alias = x.getTableSource().getAlias();
        setCurrentTable(ident);

        TableStat stat = getTableStat(ident);
        stat.incrementUpdateCount();

        Map<String, String> aliasMap = getAliasMap();
        
        aliasMap.put(ident, ident);
        //
        if(alias != null) {
        	aliasMap.put(alias, ident);
        }
    } else {
        x.getTableSource().accept(this);
    }

    accept(x.getItems());
    accept(x.getWhere());

    return false;
}
 
Example #10
Source File: UpdateParser.java    From dts with Apache License 2.0 4 votes vote down vote up
@Override
protected String getTableName(SQLUpdateStatement parseSqlStatement) {
    return parseSqlStatement.getTableName().getSimpleName();
}
 
Example #11
Source File: UpdateParser.java    From dts with Apache License 2.0 4 votes vote down vote up
@Override
protected String getWhere(SQLUpdateStatement parseSqlStatement) {
    return SQLUtils.toSQLString(parseSqlStatement.getWhere());
}
 
Example #12
Source File: MycatSchemaStatVisitor.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
/**
     * 从between语句中获取字段所属的表名。
     * 对于容易出现ambiguous的(字段不知道到底属于哪个表),实际应用中必须使用别名来避免歧义
     * @param betweenExpr
     * @param column
     * @return
     */
    private String getOwnerTableName(SQLBetweenExpr betweenExpr,String column) {
        if(tableStats.size() == 1) {//只有一个表,直接返回这一个表名
            return tableStats.keySet().iterator().next().getName();
        } else if(tableStats.size() == 0) {//一个表都没有,返回空串
            return "";
        } else {//多个表名
            for (Column col : columns.keySet())
            {
                if(col.getName().equals(column)) {
                    return col.getTable();
                }
            }
//            for(Column col : columns) {//从columns中找表名
//                if(col.getName().equals(column)) {
//                    return col.getTable();
//                }
//            }

            //前面没找到表名的,自己从parent中解析

            SQLObject parent = betweenExpr.getParent();
            if(parent instanceof SQLBinaryOpExpr)
            {
                parent=parent.getParent();
            }

            if(parent instanceof MySqlSelectQueryBlock) {
                MySqlSelectQueryBlock select = (MySqlSelectQueryBlock) parent;
                if(select.getFrom() instanceof SQLJoinTableSource) {//多表连接
                    SQLJoinTableSource joinTableSource = (SQLJoinTableSource)select.getFrom();
                    return joinTableSource.getLeft().toString();//将left作为主表,此处有不严谨处,但也是实在没有办法,如果要准确,字段前带表名或者表的别名即可
                } else if(select.getFrom() instanceof SQLExprTableSource) {//单表
                    return select.getFrom().toString();
                }
            }
            else if(parent instanceof SQLUpdateStatement) {
                SQLUpdateStatement update = (SQLUpdateStatement) parent;
                return update.getTableName().getSimpleName();
            } else if(parent instanceof SQLDeleteStatement) {
                SQLDeleteStatement delete = (SQLDeleteStatement) parent;
                return delete.getTableName().getSimpleName();
            } else {
                
            }
        }
        return "";
    }