com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlDeleteStatement Java Examples

The following examples show how to use com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlDeleteStatement. 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: SqlVisitor.java    From baymax with Apache License 2.0 6 votes vote down vote up
@Override
public boolean visit(MySqlDeleteStatement x) {
    setAliasMap();

    setMode(x, Mode.Delete);

    accept(x.getFrom());
    accept(x.getUsing());
    x.getTableSource().accept(this);

    if (x.getTableSource() instanceof SQLExprTableSource) {
        SQLName tableName = (SQLName) ((SQLExprTableSource) x.getTableSource()).getExpr();
        String ident = tableName.toString();
        setCurrentTable(x, ident);
        // 和父类只有这行不同
        TableStat stat = this.getTableStat(ident,ident);
        stat.incrementDeleteCount();
    }

    accept(x.getWhere());

    accept(x.getOrderBy());
    accept(x.getLimit());

    return false;
}
 
Example #2
Source File: ServerSchemaStatVisitor.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean visit(MySqlDeleteStatement x) {
    aliasMap.clear();
    accept(x.getFrom());
    accept(x.getUsing());
    x.getTableSource().accept(this);

    if (x.getTableSource() instanceof SQLExprTableSource) {
        SQLName tableName = (SQLName) ((SQLExprTableSource) x.getTableSource()).getExpr();
        currentTable = tableName.toString();
    }

    accept(x.getWhere());

    accept(x.getOrderBy());
    accept(x.getLimit());

    return false;
}
 
Example #3
Source File: DruidDeleteParser.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void statementParse(SchemaConfig schema, RouteResultset rrs, SQLStatement stmt) throws SQLNonTransientException {
	MySqlDeleteStatement delete = (MySqlDeleteStatement)stmt;
	String tableName = StringUtil.removeBackquote(delete.getTableName().getSimpleName().toUpperCase());
	ctx.addTable(tableName);

	//在解析SQL时清空该表的主键缓存
	TableConfig tableConfig = schema.getTables().get(tableName);
	if (tableConfig != null && !tableConfig.primaryKeyIsPartionKey()) {
		String cacheName = schema.getName() + "_" + tableName;
		cacheName = cacheName.toUpperCase();
		for (CachePool value : MycatServer.getInstance().getCacheService().getAllCachePools().values()) {
			value.clearCache(cacheName);
			value.getCacheStatic().reset();
		}
	}
}
 
Example #4
Source File: MycatSchemaStatVisitor.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
public boolean visit(MySqlDeleteStatement x) {
    setAliasMap();

    setMode(x, Mode.Delete);

    accept(x.getFrom());
    accept(x.getUsing());
    x.getTableSource().accept(this);

    if (x.getTableSource() instanceof SQLExprTableSource) {
        SQLName tableName = (SQLName) ((SQLExprTableSource) x.getTableSource()).getExpr();
        String ident = tableName.toString();
        setCurrentTable(x, ident);

        TableStat stat = this.getTableStat(ident,ident);
        stat.incrementDeleteCount();
    }

    accept(x.getWhere());

    accept(x.getOrderBy());
    accept(x.getLimit());

    return false;
}
 
Example #5
Source File: DeleteParser.java    From dts with Apache License 2.0 5 votes vote down vote up
@Override
protected List<Object> getWhereParams(List<Object> sqlParamsList, MySqlDeleteStatement parseSqlStatement) {
    if (sqlParamsList != null && !sqlParamsList.isEmpty()) {
        return sqlParamsList;
    }
    return Lists.newArrayList();
}
 
Example #6
Source File: DeleteParser.java    From dts with Apache License 2.0 5 votes vote down vote up
@Override
protected String selectSql(MySqlDeleteStatement mySqlUpdateStatement, Set<String> primaryKeyNameSet) {
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("SELECT * ");
    stringBuffer.append(" from ").append(mySqlUpdateStatement.getTableName().getSimpleName()).append(" where ");
    stringBuffer.append(SQLUtils.toSQLString(mySqlUpdateStatement.getWhere()));
    return stringBuffer.toString();
}
 
Example #7
Source File: SchemaUtil.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
private static boolean isNoSharding(ServerConnection source, SQLExprTableSource table, SQLStatement stmt, SQLStatement childSelectStmt, String contextSchema, Set<String> schemas, StringPtr dataNode)
        throws SQLException {
    SchemaInfo schemaInfo = SchemaUtil.getSchemaInfo(source.getUser(), contextSchema, table);
    String currentSchema = schemaInfo.schema.toUpperCase();
    if (SchemaUtil.MYSQL_SYS_SCHEMA.contains(currentSchema)) {
        schemas.add(currentSchema);
        return false;
    }

    ServerPrivileges.CheckType checkType = ServerPrivileges.CheckType.SELECT;
    if (childSelectStmt instanceof MySqlUpdateStatement) {
        checkType = ServerPrivileges.CheckType.UPDATE;
    } else if (childSelectStmt instanceof SQLSelectStatement) {
        checkType = ServerPrivileges.CheckType.SELECT;
    } else if (childSelectStmt instanceof MySqlDeleteStatement) {
        checkType = ServerPrivileges.CheckType.DELETE;
    }

    if (!ServerPrivileges.checkPrivilege(source, schemaInfo.schema, schemaInfo.table, checkType)) {
        String msg = "The statement DML privilege check is not passed, sql:" + stmt.toString().replaceAll("[\\t\\n\\r]", " ");
        throw new SQLNonTransientException(msg);
    }
    String noShardingNode = RouterUtil.isNoSharding(schemaInfo.schemaConfig, schemaInfo.table);
    schemas.add(schemaInfo.schema);
    if (noShardingNode == null) {
        return false;
    } else if (dataNode.get() == null) {
        dataNode.set(noShardingNode);
        return true;
    } else {
        return dataNode.get().equals(noShardingNode);
    }
}
 
Example #8
Source File: DruidParserFactory.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public static DruidParser create(SchemaConfig schema, SQLStatement statement, SchemaStatVisitor visitor)
{
    DruidParser parser = null;
    if (statement instanceof SQLSelectStatement)
    {
        if(schema.isNeedSupportMultiDBType())
        {
            parser = getDruidParserForMultiDB(schema, statement, visitor);

        }

        if (parser == null)
        {
            parser = new DruidSelectParser();
        }
    } else if (statement instanceof MySqlInsertStatement)
    {
        parser = new DruidInsertParser();
    } else if (statement instanceof MySqlDeleteStatement)
    {
        parser = new DruidDeleteParser();
    } else if (statement instanceof MySqlCreateTableStatement)
    {
        parser = new DruidCreateTableParser();
    } else if (statement instanceof MySqlUpdateStatement)
    {
        parser = new DruidUpdateParser();
    } else if (statement instanceof SQLAlterTableStatement)
    {
        parser = new DruidAlterTableParser();
    } else if (statement instanceof MySqlLockTableStatement) {
    	parser = new DruidLockTableParser();
    } else
    {
        parser = new DefaultDruidParser();
    }

    return parser;
}
 
Example #9
Source File: CompensateService.java    From txle with Apache License 2.0 5 votes vote down vote up
private String parseTableName(SQLStatement sqlStatement) {
    if (sqlStatement instanceof MySqlInsertStatement) {
        return ((MySqlInsertStatement) sqlStatement).getTableName().toString();
    } else if (sqlStatement instanceof MySqlDeleteStatement) {
        return ((MySqlDeleteStatement) sqlStatement).getTableName().toString();
    } else if (sqlStatement instanceof MySqlUpdateStatement) {
        return ((MySqlUpdateStatement) sqlStatement).getTableName().toString();
    }
    return "";
}
 
Example #10
Source File: DeleteParser.java    From dts with Apache License 2.0 4 votes vote down vote up
@Override
protected String getTableName(MySqlDeleteStatement parseSqlStatement) {
    return parseSqlStatement.getTableName().getSimpleName();
}
 
Example #11
Source File: ServerSchemaStatVisitor.java    From dble with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void endVisit(MySqlDeleteStatement x) {
}
 
Example #12
Source File: MycatSchemaStatVisitor.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
public void endVisit(MySqlDeleteStatement x) {
}
 
Example #13
Source File: CompensateService.java    From txle with Apache License 2.0 4 votes vote down vote up
public void constructCompensateSql(TxleTransactionStart tx, TxleTxStartAck.Builder txStartAck, Map<String, String> localTxCompensateSql) {
    for (TxleSubTransactionStart subTx : tx.getSubTxInfoList()) {
        try {
            SQLStatement sqlStatement = new MySqlStatementParser(subTx.getSql()).parseStatement();
            String tableName = parseTableName(sqlStatement);
            String tableNameWithSchema = tableName;
            if (tableName.indexOf(".") < 0) {
                tableNameWithSchema = subTx.getDbSchema() + "." + tableName;
            } else {
                tableName = tableName.substring(tableName.indexOf(".") + 1);
            }
            String txleOldBackupTableName = TxleConstants.giveBackupTableNameForOldData(subTx.getDbSchema(), tableName);
            String txleNewBackupTableName = this.schema + "." + TxleConstants.giveBackupTableNameForNewData(subTx.getDbSchema(), tableName);

            String compensateSql = "";
            if (sqlStatement instanceof MySqlInsertStatement) {
                compensateSql = String.format("DELETE FROM " + tableNameWithSchema + " WHERE id IN (SELECT id FROM " + txleNewBackupTableName + " WHERE globalTxId = '%s' AND localTxId = '%s') " + TxleConstants.ACTION_SQL, tx.getGlobalTxId(), subTx.getLocalTxId());
            } else if (sqlStatement instanceof MySqlDeleteStatement) {
                compensateSql = String.format("INSERT INTO " + tableNameWithSchema + " SELECT %s FROM " + schema + "." + txleOldBackupTableName + " WHERE globalTxId = '%s' AND localTxId = '%s' "
                        + TxleConstants.ACTION_SQL, this.readColumnNames(subTx.getDbSchema(), tableName), tx.getGlobalTxId(), subTx.getLocalTxId());
            } else if (sqlStatement instanceof MySqlUpdateStatement) {
                String setColumns = this.constructSetColumnsForUpdate(subTx.getDbSchema(), tableName);
                Object primaryKey = this.txleEhCache.get(TxleCacheType.INIT, subTx.getDbNodeId() + "." + tableNameWithSchema);
                if (primaryKey == null) {
                    List list = customRepository.executeQuery("SELECT T.field FROM BusinessDBLatestDetail T WHERE T.isprimarykey = 1 AND T.node = ? AND T.dbschema = ? AND T.tablename = ?", subTx.getDbNodeId(), subTx.getDbSchema(), tableName);
                    if (list != null && !list.isEmpty()) {
                        primaryKey = list.get(0);
                        if (primaryKey != null) {
                            txleEhCache.put(TxleCacheType.INIT, subTx.getDbNodeId() + "." + subTx.getDbSchema() + "." + tableName, primaryKey);
                        }
                    }
                }
                if (primaryKey == null) {
                    primaryKey = "id";
                }
                // construct reversed sql
                compensateSql = String.format("UPDATE %s T INNER JOIN %s T1 ON T." + primaryKey + " = T1." + primaryKey + " SET %s WHERE T1.globalTxId = '%s' AND T1.localTxId = '%s' "
                        + TxleConstants.ACTION_SQL, tableNameWithSchema, this.schema + "." + txleOldBackupTableName, setColumns, tx.getGlobalTxId(), subTx.getLocalTxId());
            }
            localTxCompensateSql.put(subTx.getLocalTxId(), compensateSql);
        } catch (Exception e) {
            handleExceptionWithFaultToleranceChecking("Failed to construct sql for compensation.", e, tx, txStartAck);
        }
    }
}
 
Example #14
Source File: CompensateService.java    From txle with Apache License 2.0 4 votes vote down vote up
public void prepareBackupSql(TxleTransactionStart tx, TxleTxStartAck.Builder txStartAck, boolean isExistsGlobalTx, Map<String, String> localTxBackupSql) {
        for (TxleSubTransactionStart subTx : tx.getSubTxInfoList()) {
            try {
                SQLStatement sqlStatement = new MySqlStatementParser(subTx.getSql()).parseStatement();
                String tableName = parseTableName(sqlStatement);
                String tableNameWithSchema = tableName;
                if (tableName.indexOf(".") < 0) {
                    tableNameWithSchema = subTx.getDbSchema() + "." + tableName;
                } else {
                    tableName = tableName.substring(tableName.indexOf(".") + 1);
                }
                String txleOldBackupTableName = TxleConstants.giveBackupTableNameForOldData(subTx.getDbSchema(), tableName), txleOldBackupTableNameWithSchema = this.schema + "." + txleOldBackupTableName;
                String txleNewBackupTableName = TxleConstants.giveBackupTableNameForNewData(subTx.getDbSchema(), tableName), txleNewBackupTableNameWithSchema = this.schema + "." + txleNewBackupTableName;

                // create backup table & alter structure
                TxleSubTxSql.Builder subTxSql = TxleSubTxSql.newBuilder().setLocalTxId(subTx.getLocalTxId()).setDbNodeId(subTx.getDbNodeId()).setDbSchema(subTx.getDbSchema()).setOrder(subTx.getOrder());
                this.constructBackupSqls(tx, isExistsGlobalTx, subTx, subTxSql, tableNameWithSchema, txleOldBackupTableName, txleOldBackupTableNameWithSchema, txleNewBackupTableName, txleNewBackupTableNameWithSchema);

                String operation = "";
                if (sqlStatement instanceof MySqlInsertStatement) {
                    operation = "insert";
                    // the formal business sql
                    subTxSql.addSubTxSql(subTx.getSql());
                    // the backup new data sql
                    Object primaryKey = this.txleEhCache.get(TxleCacheType.INIT, subTx.getDbNodeId() + "." + tableNameWithSchema);
                    if (primaryKey == null) {
                        primaryKey = "id";
                    }
                    subTxSql.addSubTxSql(String.format("INSERT INTO " + txleNewBackupTableNameWithSchema + " SELECT *, '%s', '%s' FROM %s WHERE " + primaryKey + " = (SELECT LAST_INSERT_ID()) FOR UPDATE " + TxleConstants.ACTION_SQL, tx.getGlobalTxId(), subTx.getLocalTxId(), tableNameWithSchema));
                } else if (sqlStatement instanceof MySqlDeleteStatement) {
                    operation = "delete";
                    subTxSql.addSubTxSql(String.format("INSERT INTO " + txleOldBackupTableNameWithSchema + " SELECT *, '%s', '%s' FROM %s WHERE %s FOR UPDATE "
                            + TxleConstants.ACTION_SQL, tx.getGlobalTxId(), subTx.getLocalTxId(), tableNameWithSchema, ((MySqlDeleteStatement) sqlStatement).getWhere().toString()));
                    subTxSql.addSubTxSql(subTx.getSql());
                } else if (sqlStatement instanceof MySqlUpdateStatement) {
                    operation = "update";
                    subTxSql.addSubTxSql(String.format("INSERT INTO " + txleOldBackupTableNameWithSchema + " SELECT *, '%s', '%s' FROM %s WHERE %s FOR UPDATE "
                            + TxleConstants.ACTION_SQL, tx.getGlobalTxId(), subTx.getLocalTxId(), tableNameWithSchema, ((MySqlUpdateStatement) sqlStatement).getWhere().toString()));
                    subTxSql.addSubTxSql(subTx.getSql());
                    subTxSql.addSubTxSql(String.format("INSERT INTO " + txleNewBackupTableNameWithSchema + " SELECT *, '%s', '%s' FROM %s WHERE %s FOR UPDATE "
                            + TxleConstants.ACTION_SQL, tx.getGlobalTxId(), subTx.getLocalTxId(), tableNameWithSchema, ((MySqlUpdateStatement) sqlStatement).getWhere().toString()));
                }

                if (!txleEhCache.readConfigCache(TxleConstants.getServiceInstanceId(tx.getServiceName(), tx.getServiceIP()), tx.getServiceCategory(), ConfigCenterType.ClientCompensate)) {
                    subTxSql.addSubTxSql("set autocommit=0");
                    subTxSql.addSubTxSql("commit");
                    subTxSql.addSubTxSql("set autocommit=1");
//                    subTxSql.addSubTxSql("begin");
                }

                // return SQLs to client
                txStartAck.addSubTxSql(subTxSql.build());
                final StringBuilder backupSqls = new StringBuilder();
                subTxSql.getSubTxSqlList().forEach(sql -> backupSqls.append(sql + TxleConstants.STRING_SEPARATOR));
                localTxBackupSql.put(subTx.getLocalTxId(), backupSqls.toString());

                kafkaMessageRepository.save(new KafkaMessage(tx.getGlobalTxId(), subTx.getLocalTxId(), "", subTx.getDbNodeId(), "", tableNameWithSchema, operation, ""));
            } catch (Exception e) {
                handleExceptionWithFaultToleranceChecking("Failed to prepare sqls for backup.", e, tx, txStartAck);
            }
        }
    }
 
Example #15
Source File: AutoCompensateHandler.java    From txle with Apache License 2.0 4 votes vote down vote up
@Override
public void prepareCompensationBeforeExecuting(PreparedStatement delegate, String executeSql, Map<String, Object> standbyParams) throws SQLException {
    String globalTxId = CurrentThreadOmegaContext.getGlobalTxIdFromCurThread();
    if (globalTxId == null || globalTxId.length() == 0) {
        return;
    }
    String localTxId = CurrentThreadOmegaContext.getLocalTxIdFromCurThread();
    if (localTxId == null || localTxId.length() == 0) {
        return;
    }

    // To parse SQL by SQLParser tools from Druid.
    MySqlStatementParser parser = new MySqlStatementParser(executeSql);
    SQLStatement sqlStatement = parser.parseStatement();
    if (sqlStatement instanceof MySqlSelectIntoStatement) {
        return;
    }

    if (standbyParams == null) {
        standbyParams = new HashMap<>(8);
    }

    String server = CurrentThreadOmegaContext.getServiceNameFromCurThread();

    // To set a relationship between localTxId and datSourceInfo, in order to determine to use the relative dataSource for localTxId when it need be compensated.
    DatabaseMetaData databaseMetaData = delegate.getConnection().getMetaData();
    String dburl = databaseMetaData.getURL(), dbusername = databaseMetaData.getUserName(), dbdrivername = databaseMetaData.getDriverName();
    DataSourceMappingCache.putLocalTxIdAndDataSourceInfo(localTxId, dburl, dbusername, dbdrivername);
    // To construct kafka message.
    standbyParams.put("dbdrivername", dbdrivername);
    standbyParams.put("dburl", dburl);
    standbyParams.put("dbusername", dbusername);

    if (sqlStatement instanceof MySqlInsertStatement) {
        return;
    } else if (sqlStatement instanceof MySqlUpdateStatement) {
        AutoCompensateUpdateHandler.newInstance().prepareCompensationBeforeUpdating(delegate, sqlStatement, executeSql, globalTxId, localTxId, server, standbyParams);
    } else if (sqlStatement instanceof MySqlDeleteStatement) {
        AutoCompensateDeleteHandler.newInstance().prepareCompensationBeforeDeleting(delegate, sqlStatement, executeSql, globalTxId, localTxId, server, standbyParams);
    } else {
        standbyParams.clear();
        // Default is closed, means that just does record, if it's open, then program will throw an exception about current special SQL, just for auto-compensation.
        boolean checkSpecialSql = TxleStaticConfig.getBooleanConfig("txle.transaction.auto-compensation.check-special-sql", false);
        if (checkSpecialSql) {
            throw new SQLException(TxleConstants.logErrorPrefixWithTime() + "Do not support sql [" + executeSql + "] to auto-compensation.");
        } else {
            LOG.debug(TxleConstants.logDebugPrefixWithTime() + "Do not support sql [{}] to auto-compensation, but it has been executed due to the switch 'checkSpecialSql' is closed.", executeSql);
        }
    }
}
 
Example #16
Source File: PaserExecutor.java    From dts with Apache License 2.0 4 votes vote down vote up
public static SQLType parse(StatementAdapter txcStatement) throws SQLException {
    long start = System.currentTimeMillis();
    SQLType sqlType = SQLType.SELECT;
    try {
        DbRuntimeContext txcRuntimeContext = txcStatement.getConnection().getConnectionRuntimeContext();
        String sql = txcStatement.getSql();
        SQLStatement sqlParseStatement = new MySqlStatementParser(sql).parseStatement();
        CommitInfo commitInfo = null;
        if (sqlParseStatement instanceof MySqlUpdateStatement) {
            commitInfo = UpdateParser.getInstance().parse(txcStatement);
            sqlType = SQLType.UPDATE;
            if (!Objects.isNull(commitInfo)&&!CollectionUtils.isEmpty(commitInfo.getOriginalValue().getLine())) {
                txcRuntimeContext.getInfo().add(commitInfo);
                fillDbMetaAndLockRow(txcStatement, commitInfo);
            }
        } else if (sqlParseStatement instanceof MySqlInsertStatement) {
            sqlType = SQLType.INSERT;
        } else if (sqlParseStatement instanceof MySqlDeleteStatement) {
            commitInfo = DeleteParser.getInstance().parse(txcStatement);
            sqlType = SQLType.DELETE;
            if (!Objects.isNull(commitInfo) && !CollectionUtils.isEmpty(commitInfo.getOriginalValue().getLine())) {
                txcRuntimeContext.getInfo().add(commitInfo);
                fillDbMetaAndLockRow(txcStatement, commitInfo);
            }
        } else if (sqlParseStatement instanceof SQLSelectStatement) {
            SQLSelectQueryBlock selectQueryBlock =
                ((SQLSelectStatement)sqlParseStatement).getSelect().getQueryBlock();
            if (selectQueryBlock.getFrom() != null) {
                SelectParser.getInstance().parse(txcStatement);
                sqlType = SQLType.SELECT;
            }
        }
    } catch (Exception e) {
        logger.error("parse sql error", e);
        if (e instanceof SQLException || e instanceof RuntimeException) {
            throw e;
        } else {
            throw new SQLException(e);
        }
    } finally {
        long cost = System.currentTimeMillis() - start;
        if (sqlType != SQLType.SELECT || cost > 50) {
            logger.debug("parser sql:{}, cost:{}ms", txcStatement.getSql(), cost);
        }
    }
    return sqlType;
}
 
Example #17
Source File: DeleteParser.java    From dts with Apache License 2.0 4 votes vote down vote up
@Override
protected String getWhere(MySqlDeleteStatement parseSqlStatement) {
    return SQLUtils.toSQLString(parseSqlStatement.getWhere());
}
 
Example #18
Source File: DeleteParser.java    From dts with Apache License 2.0 4 votes vote down vote up
@Override
public TableDataInfo getPresentValue(List<Object> sqlParamsList, MySqlDeleteStatement parseSqlStatement,
    StatementAdapter statementAdapter, TableMetaInfo tableMetaInfo) throws SQLException {
    return null;
}
 
Example #19
Source File: SqlParser.java    From elasticsearch-sql with Apache License 2.0 3 votes vote down vote up
public Delete parseDelete(SQLDeleteStatement deleteStatement) throws SqlParseException {
    Delete delete = new Delete();
    WhereParser whereParser = new WhereParser(this, deleteStatement);

    delete.getFrom().addAll(findFrom(deleteStatement.getTableSource()));

    delete.setWhere(whereParser.findWhere());

    delete.getHints().addAll(parseHints(((MySqlDeleteStatement) deleteStatement).getHints()));

    findLimit(((MySqlDeleteStatement) deleteStatement).getLimit(), delete);

    return delete;
}
 
Example #20
Source File: SqlVisitor.java    From baymax with Apache License 2.0 2 votes vote down vote up
@Override
public void endVisit(MySqlDeleteStatement x) {

}
 
Example #21
Source File: OrVisitor.java    From baymax with Apache License 2.0 2 votes vote down vote up
@Override
public void endVisit(MySqlDeleteStatement x) {

}