com.alibaba.druid.sql.ast.SQLStatement Java Examples

The following examples show how to use com.alibaba.druid.sql.ast.SQLStatement. 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: TableHandler.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
/**
 * pre handle create table statement
 *
 * @param context
 * @param sqlStatement
 * @return whether statement is changed
 */
private boolean preHandleCreateTable(DumpFileContext context, SQLStatement sqlStatement) {
    TableConfig tableConfig = context.getTableConfig();
    List<SQLTableElement> columns = ((MySqlCreateTableStatement) sqlStatement).getTableElementList();
    boolean isChanged = false;
    if (tableConfig.isAutoIncrement() || tableConfig.getPartitionColumn() != null) {
        // check columns for sharing column index or increment column index
        isChanged = checkColumns(context, columns);
        // partition column check
        if (tableConfig.getPartitionColumn() != null && context.getPartitionColumnIndex() == -1) {
            throw new DumpException("can't find partition column in create.");
        }
        // increment column check
        if (tableConfig.isAutoIncrement() && context.getIncrementColumnIndex() == -1) {
            throw new DumpException("can't find increment column in create.");
        }
    }
    return isChanged;
}
 
Example #2
Source File: ReverseEngineeringService.java    From youran with Apache License 2.0 6 votes vote down vote up
/**
 * 解析DDL
 *
 * @param dto
 * @return
 */
public List<SQLStatement> parse(ReverseEngineeringDTO dto) {
    List<SQLStatement> sqlStatements;
    try {
        sqlStatements = SQLUtils.parseStatements(dto.getDdl(), dto.getDbType());
    } catch (ParserException e) {
        LOGGER.warn("反向工程校验失败:{}", e);
        throw new BusinessException(ErrorCode.BAD_PARAMETER, "DDL解析失败:" + e.getMessage());
    }
    if (CollectionUtils.isEmpty(sqlStatements)) {
        throw new BusinessException(ErrorCode.BAD_PARAMETER, "未找到有效DDL语句");
    }
    for (SQLStatement sqlStatement : sqlStatements) {
        if (!(sqlStatement instanceof SQLCreateTableStatement)) {
            throw new BusinessException(ErrorCode.BAD_PARAMETER, "只支持create table语句,请删除多余的sql");
        }
    }
    return sqlStatements;
}
 
Example #3
Source File: DefaultRouteStrategy.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
@Override
public SQLStatement parserSQL(String originSql) throws SQLSyntaxErrorException {
    SQLStatementParser parser = new MySqlStatementParser(originSql);

    /**
     * thrown SQL SyntaxError if parser error
     */
    try {
        List<SQLStatement> list = parser.parseStatementList();
        if (list.size() > 1) {
            throw new SQLSyntaxErrorException("MultiQueries is not supported,use single query instead ");
        }
        return list.get(0);
    } catch (Exception t) {
        LOGGER.info("routeNormalSqlWithAST", t);
        if (t.getMessage() != null) {
            throw new SQLSyntaxErrorException(t.getMessage());
        } else {
            throw new SQLSyntaxErrorException(t);
        }
    }
}
 
Example #4
Source File: DruidCreateIndexParser.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
@Override
public SchemaConfig visitorParse(SchemaConfig schema, RouteResultset rrs, SQLStatement stmt,
                                 ServerSchemaStatVisitor visitor, ServerConnection sc, boolean isExplain) throws SQLException {
    rrs.setOnline(true);
    SQLCreateIndexStatement createStmt = (SQLCreateIndexStatement) stmt;
    SQLTableSource tableSource = createStmt.getTable();
    if (tableSource instanceof SQLExprTableSource) {
        String schemaName = schema == null ? null : schema.getName();
        SchemaInfo schemaInfo = SchemaUtil.getSchemaInfo(sc.getUser(), schemaName, (SQLExprTableSource) tableSource);
        String statement = RouterUtil.removeSchema(rrs.getStatement(), schemaInfo.getSchema());
        rrs.setStatement(statement);
        String noShardingNode = RouterUtil.isNoShardingDDL(schemaInfo.getSchemaConfig(), schemaInfo.getTable());
        if (noShardingNode != null) {
            RouterUtil.routeToSingleDDLNode(schemaInfo, rrs, noShardingNode);
            return schemaInfo.getSchemaConfig();
        }
        RouterUtil.routeToDDLNode(schemaInfo, rrs);
        return schemaInfo.getSchemaConfig();
    } else {
        String msg = "The DDL is not supported, sql:" + stmt;
        throw new SQLNonTransientException(msg);
    }
}
 
Example #5
Source File: SchemaUtil.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
private static SchemaInfo parseTables(SQLStatement stmt, SchemaStatVisitor schemaStatVisitor) {

        stmt.accept(schemaStatVisitor);
        String key = schemaStatVisitor.getCurrentTable();
        if (key != null && key.contains("`")) {
            key = key.replaceAll("`", "");
        }

        if (key != null) {
            SchemaInfo schemaInfo = new SchemaInfo();
            int pos = key.indexOf(".");
            if (pos > 0) {
                schemaInfo.schema = key.substring(0, pos);
                schemaInfo.table = key.substring(pos + 1);
            } else {
                schemaInfo.table = key;
            }
            return schemaInfo;
        }

        return null;
    }
 
Example #6
Source File: SetHandler.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
private static boolean handleSetStatement(String stmt, ServerConnection c, List<Pair<KeyType, Pair<String, String>>> contextTask,
                                          List<Pair<KeyType, Pair<String, String>>> innerSetTask, StringBuilder contextSetSQL) throws SQLSyntaxErrorException {
    SQLStatement statement = parseSQL(stmt);
    if (statement instanceof SQLSetStatement) {
        List<SQLAssignItem> assignItems = ((SQLSetStatement) statement).getItems();
        if (assignItems.size() == 1) {
            contextSetSQL.append(statement.toString());
            return handleSingleVariable(stmt, assignItems.get(0), c, contextTask);
        } else {
            boolean result = handleSetMultiStatement(assignItems, c, contextTask, innerSetTask);
            contextSetSQL.append(statement.toString());
            return result;
        }
    } else if (statement instanceof MySqlSetTransactionStatement) {
        return handleTransaction(c, (MySqlSetTransactionStatement) statement);
    } else {
        c.writeErrMessage(ErrorCode.ERR_NOT_SUPPORTED, stmt + " is not recognized and ignored");
        return false;
    }
}
 
Example #7
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 #8
Source File: MySQLDialect.java    From Zebra with Apache License 2.0 6 votes vote down vote up
@Override
public String getCountSql(String sql) {
	SQLStatementParser parser = new MySqlStatementParser(sql);
	List<SQLStatement> stmtList = parser.parseStatementList();

	// 将AST通过visitor输出
	StringBuilder out = new StringBuilder();
	MysqlCountOutputVisitor visitor = new MysqlCountOutputVisitor(out);

	for (SQLStatement stmt : stmtList) {
		if (stmt instanceof SQLSelectStatement) {
			stmt.accept(visitor);
			out.append(";");
		}
	}

	return out.toString();
}
 
Example #9
Source File: DruidCreateTableParser.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 {
	MySqlCreateTableStatement createStmt = (MySqlCreateTableStatement)stmt;
	if(createStmt.getQuery() != null) {
		String msg = "create table from other table not supported :" + stmt;
		LOGGER.warn(msg);
		throw new SQLNonTransientException(msg);
	}
	String tableName = StringUtil.removeBackquote(createStmt.getTableSource().toString().toUpperCase());
	if(schema.getTables().containsKey(tableName)) {
		TableConfig tableConfig = schema.getTables().get(tableName);
		AbstractPartitionAlgorithm algorithm = tableConfig.getRule().getRuleAlgorithm();
		if(algorithm instanceof SlotFunction){
			SQLColumnDefinition column = new SQLColumnDefinition();
			column.setDataType(new SQLCharacterDataType("int"));
			column.setName(new SQLIdentifierExpr("_slot"));
			column.setComment(new SQLCharExpr("自动迁移算法slot,禁止修改"));
			((SQLCreateTableStatement)stmt).getTableElementList().add(column);
			String sql = createStmt.toString();
			rrs.setStatement(sql);
			ctx.setSql(sql);
		}
	}
	ctx.addTable(tableName);
	
}
 
Example #10
Source File: DruidTruncateTableParser.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
@Override
public SchemaConfig visitorParse(SchemaConfig schema, RouteResultset rrs, SQLStatement stmt, ServerSchemaStatVisitor visitor, ServerConnection sc, boolean isExplain)
        throws SQLException {
    rrs.setDdlType(DDLInfo.DDLType.TRUNCATE_TABLE);
    String schemaName = schema == null ? null : schema.getName();
    SQLTruncateStatement truncateTable = (SQLTruncateStatement) stmt;
    SchemaInfo schemaInfo = SchemaUtil.getSchemaInfo(sc.getUser(), schemaName, truncateTable.getTableSources().get(0));
    String statement = RouterUtil.removeSchema(rrs.getStatement(), schemaInfo.getSchema());
    rrs.setStatement(statement);
    String noShardingNode = RouterUtil.isNoShardingDDL(schemaInfo.getSchemaConfig(), schemaInfo.getTable());
    if (noShardingNode != null) {
        RouterUtil.routeToSingleDDLNode(schemaInfo, rrs, noShardingNode);
        return schemaInfo.getSchemaConfig();
    }
    RouterUtil.routeToDDLNode(schemaInfo, rrs);
    return schemaInfo.getSchemaConfig();
}
 
Example #11
Source File: DruidMysqlCreateTableTest.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
private static boolean hasColumn(SQLStatement statement) {
    for (SQLTableElement tableElement : ((SQLCreateTableStatement) statement).getTableElementList()) {
        SQLName sqlName = null;
        if (tableElement instanceof SQLColumnDefinition) {
            sqlName = ((SQLColumnDefinition) tableElement).getName();
        }

        if (sqlName != null) {
            String simpleName = sqlName.getSimpleName();
            simpleName = StringUtil.removeBackQuote(simpleName);
            if (tableElement instanceof SQLColumnDefinition && "_slot".equalsIgnoreCase(simpleName)) {
                return true;
            }
        }
    }
    return false;
}
 
Example #12
Source File: RouterUtil.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
private  static String changeCreateTable(SchemaConfig schema,String tableName,String sql) {
	if (schema.getTables().containsKey(tableName)) {
		MySqlStatementParser parser = new MySqlStatementParser(sql);
		SQLStatement insertStatement = parser.parseStatement();
		if (insertStatement instanceof MySqlCreateTableStatement) {
			TableConfig tableConfig = schema.getTables().get(tableName);
			AbstractPartitionAlgorithm algorithm = tableConfig.getRule().getRuleAlgorithm();
			if (algorithm instanceof SlotFunction) {
				SQLColumnDefinition column = new SQLColumnDefinition();
				column.setDataType(new SQLCharacterDataType("int"));
				column.setName(new SQLIdentifierExpr("_slot"));
				column.setComment(new SQLCharExpr("自动迁移算法slot,禁止修改"));
				((SQLCreateTableStatement) insertStatement).getTableElementList().add(column);
				return insertStatement.toString();

			}
		}

	}
	return sql;
}
 
Example #13
Source File: SchemaUtil.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
public static boolean isNoSharding(ServerConnection source, SQLSelectQuery sqlSelectQuery, SQLStatement selectStmt, SQLStatement childSelectStmt, String contextSchema, Set<String> schemas, StringPtr dataNode)
        throws SQLException {
    if (sqlSelectQuery instanceof MySqlSelectQueryBlock) {
        MySqlSelectQueryBlock mySqlSelectQueryBlock = (MySqlSelectQueryBlock) sqlSelectQuery;
        //CHECK IF THE SELECT LIST HAS INNER_FUNC IN,WITCH SHOULD BE DEAL BY DBLE
        for (SQLSelectItem item : mySqlSelectQueryBlock.getSelectList()) {
            if (item.getExpr() instanceof SQLMethodInvokeExpr) {
                if (ItemCreate.getInstance().isInnerFunc(((SQLMethodInvokeExpr) item.getExpr()).getMethodName())) {
                    return false;
                }
            }
        }
        return isNoSharding(source, mySqlSelectQueryBlock.getFrom(), selectStmt, childSelectStmt, contextSchema, schemas, dataNode);
    } else if (sqlSelectQuery instanceof SQLUnionQuery) {
        return isNoSharding(source, (SQLUnionQuery) sqlSelectQuery, selectStmt, contextSchema, schemas, dataNode);
    } else {
        return false;
    }
}
 
Example #14
Source File: DruidMysqlCreateTableTest.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
private static boolean hasColumn(SQLStatement statement){
    for (SQLTableElement tableElement : ((SQLCreateTableStatement)statement).getTableElementList()) {
        SQLName sqlName = null;
        if (tableElement instanceof SQLColumnDefinition) {
            sqlName = ((SQLColumnDefinition)tableElement).getName();
        }
        if (sqlName != null) {
            String simpleName = sqlName.getSimpleName();
            simpleName = StringUtil.removeBackquote(simpleName);
            if (tableElement instanceof SQLColumnDefinition && "_slot".equalsIgnoreCase(simpleName)) {
                return true;
            }
        }
    }
    return false;
}
 
Example #15
Source File: DefaultDruidParser.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
@Override
public SchemaConfig visitorParse(SchemaConfig schemaConfig, RouteResultset rrs, SQLStatement stmt, ServerSchemaStatVisitor visitor, ServerConnection sc, boolean isExplain)
        throws SQLException {
    stmt.accept(visitor);
    if (visitor.getNotSupportMsg() != null) {
        throw new SQLNonTransientException(visitor.getNotSupportMsg());
    }
    String schemaName = null;
    if (schemaConfig != null) {
        schemaName = schemaConfig.getName();
    }
    Map<String, String> tableAliasMap = getTableAliasMap(schemaName, visitor.getAliasMap());
    ctx.setRouteCalculateUnits(ConditionUtil.buildRouteCalculateUnits(visitor.getAllWhereUnit(), tableAliasMap, schemaName));

    return schemaConfig;
}
 
Example #16
Source File: ElasticSearchPreparedStatement.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
public String getExecutableSql() {
    if (parametersSize < 1) {
        return sql;
    }

    List<Object> parameters = new ArrayList<>(parametersSize);
    JdbcParameter jdbcParam;
    for (int i = 0; i < parametersSize; ++i) {
        jdbcParam = this.parameters[i];
        parameters.add(jdbcParam != null ? jdbcParam.getValue() : null);
    }

    try {
        SQLStatementParser parser = ESActionFactory.createSqlStatementParser(sql);
        List<SQLStatement> statementList = parser.parseStatementList();
        return SQLUtils.toSQLString(statementList, JdbcConstants.MYSQL, parameters, sqlFormatOption);
    } catch (ClassCastException | ParserException ex) {
        LOG.warn("format error", ex);
        return sql;
    }
}
 
Example #17
Source File: TableHandler.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
@Override
public SQLStatement preHandle(DumpFileContext context, String stmt) throws SQLSyntaxErrorException {
    SQLStatement sqlStatement = RouteStrategyFactory.getRouteStrategy().parserSQL(stmt);
    String tableName;
    if (sqlStatement instanceof MySqlCreateTableStatement) {
        tableName = StringUtil.removeBackQuote(((MySqlCreateTableStatement) sqlStatement).getTableSource().getName().getSimpleName());
        context.setTable(tableName);
        if (context.getTableType() == TableType.DEFAULT) {
            return null;
        }
        boolean isChanged = preHandleCreateTable(context, sqlStatement);
        return isChanged ? sqlStatement : null;
    } else if (sqlStatement instanceof SQLDropTableStatement) {
        tableName = StringUtil.removeBackQuote(((SQLDropTableStatement) sqlStatement).getTableSources().get(0).getName().getSimpleName());
        context.setTable(tableName);
    } else if (sqlStatement instanceof MySqlLockTableStatement) {
        tableName = StringUtil.removeBackQuote(((MySqlLockTableStatement) sqlStatement).getTableSource().getName().getSimpleName());
        context.setTable(tableName);
    }
    return null;
}
 
Example #18
Source File: ShardColumnValueUtil.java    From Zebra with Apache License 2.0 5 votes vote down vote up
private static SQLExpr getWhere(SQLParsedResult parseResult) {
	SQLExpr expr = null;
	SQLStatement stmt = parseResult.getStmt();

	if (parseResult.getType() == SqlType.SELECT || parseResult.getType() == SqlType.SELECT_FOR_UPDATE) {
		MySqlSelectQueryBlock query = (MySqlSelectQueryBlock) (((SQLSelectStatement) stmt).getSelect()).getQuery();
		expr = query.getWhere();
	} else if (parseResult.getType() == SqlType.UPDATE) {
		expr = ((MySqlUpdateStatement) stmt).getWhere();
	} else if (parseResult.getType() == SqlType.DELETE) {
		expr = ((MySqlDeleteStatement) stmt).getWhere();
	} else if (parseResult.getType() == SqlType.REPLACE) { // add for replace
		MySqlReplaceStatement replaceStatement = (MySqlReplaceStatement) stmt;
		SQLQueryExpr queryExpr = replaceStatement.getQuery();
		if (queryExpr != null) {
			SQLSelect sqlSelect = queryExpr.getSubQuery();
			sqlSelect.getQuery();
			if (sqlSelect != null) {
				MySqlSelectQueryBlock queryBlock = (MySqlSelectQueryBlock) sqlSelect.getQuery();
				if (queryBlock != null) {
					expr = queryBlock.getWhere();
				}
			}
		}
	}

	return expr;
}
 
Example #19
Source File: AutoCompensateHandler.java    From txle with Apache License 2.0 5 votes vote down vote up
@Override
public void prepareCompensationAfterExecuting(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) {
        AutoCompensateInsertHandler.newInstance().prepareCompensationAfterInserting(delegate, sqlStatement, executeSql, globalTxId, localTxId, server, standbyParams);
    } else if (sqlStatement instanceof MySqlUpdateStatement) {
        AutoCompensateUpdateHandler.newInstance().prepareCompensationAfterUpdating(delegate, sqlStatement, executeSql, globalTxId, localTxId, server, standbyParams);
    }
}
 
Example #20
Source File: SchemaUtil.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
public static boolean isNoSharding(ServerConnection source, SQLTableSource tables, SQLStatement stmt, SQLStatement childSelectStmt, String contextSchema, Set<String> schemas, StringPtr dataNode)
        throws SQLException {
    if (tables != null) {
        if (tables instanceof SQLExprTableSource) {
            if (!isNoSharding(source, (SQLExprTableSource) tables, stmt, childSelectStmt, contextSchema, schemas, dataNode)) {
                return false;
            }
        } else if (tables instanceof SQLJoinTableSource) {
            if (!isNoSharding(source, (SQLJoinTableSource) tables, stmt, childSelectStmt, contextSchema, schemas, dataNode)) {
                return false;
            }
        } else if (tables instanceof SQLSubqueryTableSource) {
            SQLSelectQuery sqlSelectQuery = ((SQLSubqueryTableSource) tables).getSelect().getQuery();
            if (!isNoSharding(source, sqlSelectQuery, stmt, new SQLSelectStatement(new SQLSelect(sqlSelectQuery)), contextSchema, schemas, dataNode)) {
                return false;
            }
        } else if (tables instanceof SQLUnionQueryTableSource) {
            if (!isNoSharding(source, ((SQLUnionQueryTableSource) tables).getUnion(), stmt, contextSchema, schemas, dataNode)) {
                return false;
            }
        } else {
            return false;
        }
    }
    ServerSchemaStatVisitor queryTableVisitor = new ServerSchemaStatVisitor();
    childSelectStmt.accept(queryTableVisitor);
    for (SQLSelect sqlSelect : queryTableVisitor.getSubQueryList()) {
        if (!isNoSharding(source, sqlSelect.getQuery(), stmt, new SQLSelectStatement(sqlSelect), contextSchema, schemas, dataNode)) {
            return false;
        }
    }
    return true;
}
 
Example #21
Source File: AutoCompensateDeleteHandler.java    From txle with Apache License 2.0 5 votes vote down vote up
public boolean prepareCompensationBeforeDeleting(PreparedStatement delegate, SQLStatement sqlStatement, String executeSql, String globalTxId, String localTxId, String server, Map<String, Object> standbyParams) throws SQLException {

        if (JdbcConstants.MYSQL.equals(sqlStatement.getDbType())) {
            return MySqlDeleteHandler.newInstance().prepareCompensationBeforeDeleting(delegate, sqlStatement, executeSql, globalTxId, localTxId, server, standbyParams);
        }

        return false;
    }
 
Example #22
Source File: DruidMycatRouteStrategy.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 获取子查询执行结果后,改写原始sql 继续执行.
 * @param statement
 * @param sqlselect
 * @param param
 * @return
 */
private String buildSql(SQLStatement statement,SQLSelect sqlselect,List param){

	SQLObject parent = sqlselect.getParent();
	RouteMiddlerReaultHandler handler = middlerResultHandler.get(parent.getClass());
	if(handler==null){
		throw new UnsupportedOperationException(parent.getClass()+" current is not supported ");
	}
	return handler.dohandler(statement, sqlselect, parent, param);
}
 
Example #23
Source File: DruidParserFactory.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private static List<String> parseTables(SQLStatement stmt, SchemaStatVisitor schemaStatVisitor)
{
    List<String> tables = new ArrayList<>();
    stmt.accept(schemaStatVisitor);

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

                if (key.equals(value))
                {
                    tables.add(key.toUpperCase());
                }
            }
        }

    }
    return tables;
}
 
Example #24
Source File: ShowColumns.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
public static void response(ServerConnection c, String stmt) {
    try {
        Pattern pattern = ShowColumns.PATTERN;
        Matcher ma = pattern.matcher(stmt);
        // always match
        if (ma.matches()) {
            int start = ma.start(6);
            int end = ma.end(6);
            String sub = stmt.substring(0, start);
            String sub2 = stmt.substring(end, stmt.length());
            stmt = sub + " from " + sub2;
        }

        SQLStatement statement = RouteStrategyFactory.getRouteStrategy().parserSQL(stmt);
        MySqlShowColumnsStatement showColumnsStatement = (MySqlShowColumnsStatement) statement;
        String table = StringUtil.removeBackQuote(showColumnsStatement.getTable().getSimpleName());
        SQLName database = showColumnsStatement.getDatabase();
        String schema = database == null ? c.getSchema() : StringUtil.removeBackQuote(database.getSimpleName());
        if (schema == null) {
            c.writeErrMessage("3D000", "No database selected", ErrorCode.ER_NO_DB_ERROR);
            return;
        }
        String sql = stmt;
        if (showColumnsStatement.getDatabase() != null) {
            showColumnsStatement.setDatabase(null);
            sql = showColumnsStatement.toString();
        }
        if (DbleServer.getInstance().getSystemVariables().isLowerCaseTableNames()) {
            schema = schema.toLowerCase();
            table = table.toLowerCase();
        }
        SchemaInfo schemaInfo = new SchemaInfo(schema, table);
        c.routeSystemInfoAndExecuteSQL(sql, schemaInfo, ServerParse.SHOW);
    } catch (Exception e) {
        c.writeErrMessage(ErrorCode.ER_PARSE_ERROR, e.toString());
    }
}
 
Example #25
Source File: ShardLimitSqlWithConditionRewrite.java    From Zebra with Apache License 2.0 5 votes vote down vote up
public String rewrite(String limitSql, RowData startData, RowData endData, MergeContext context, List<Object> params) {
	SQLStatement stmt = SQLParser.parseWithoutCache(limitSql).getStmt();

	StringBuilder out = new StringBuilder();
	ShardLimitSqlConditionVisitor visitor = new ShardLimitSqlConditionVisitor(out, startData, endData, context,
	      params);

	stmt.accept(visitor);

	return out.toString();
}
 
Example #26
Source File: DruidSelectSqlServerParser.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void statementParse(SchemaConfig schema, RouteResultset rrs, SQLStatement stmt) {
	SQLSelectStatement selectStmt = (SQLSelectStatement)stmt;
	SQLSelectQuery sqlSelectQuery = selectStmt.getSelect().getQuery();
	//从mysql解析过来
	if(sqlSelectQuery instanceof MySqlSelectQueryBlock) {
		MySqlSelectQueryBlock mysqlSelectQuery = (MySqlSelectQueryBlock)selectStmt.getSelect().getQuery();
		MySqlSelectQueryBlock.Limit limit=mysqlSelectQuery.getLimit();
		if(limit==null)
		{
               sqlserverParse(schema, rrs);


           }
		if(isNeedParseOrderAgg)
		{
			parseOrderAggGroupMysql(schema, stmt,rrs, mysqlSelectQuery);
			//更改canRunInReadDB属性
			if ((mysqlSelectQuery.isForUpdate() || mysqlSelectQuery.isLockInShareMode()) && rrs.isAutocommit() == false)
			{
				rrs.setCanRunInReadDB(false);
			}
		}

	}


}
 
Example #27
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 #28
Source File: DruidSelectOracleParser.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
protected void parseOrderAggGroupOracle(SQLStatement stmt, RouteResultset rrs, OracleSelectQueryBlock mysqlSelectQuery, SchemaConfig schema)
{
	Map<String, String> aliaColumns = parseAggGroupCommon(schema, stmt,rrs, mysqlSelectQuery);

	OracleSelectQueryBlock oracleSelect= (OracleSelectQueryBlock) mysqlSelectQuery.getParent();
	if(oracleSelect.getOrderBy() != null) {
		List<SQLSelectOrderByItem> orderByItems = oracleSelect.getOrderBy().getItems();
		rrs.setOrderByCols(buildOrderByCols(orderByItems,aliaColumns));
	}
       isNeedParseOrderAgg=false;
}
 
Example #29
Source File: DruidSelectOracleParser.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void statementParse(SchemaConfig schema, RouteResultset rrs, SQLStatement stmt) {
	SQLSelectStatement selectStmt = (SQLSelectStatement)stmt;
	SQLSelectQuery sqlSelectQuery = selectStmt.getSelect().getQuery();
      //从mysql解析过来
	if(sqlSelectQuery instanceof MySqlSelectQueryBlock) {
		MySqlSelectQueryBlock mysqlSelectQuery = (MySqlSelectQueryBlock)selectStmt.getSelect().getQuery();
		MySqlSelectQueryBlock.Limit limit=mysqlSelectQuery.getLimit();
		if(limit==null)
		{
			  //使用oracle的解析,否则会有部分oracle语法识别错误
			  OracleStatementParser oracleParser = new OracleStatementParser(getCtx().getSql());
			  SQLSelectStatement oracleStmt = (SQLSelectStatement) oracleParser.parseStatement();
               selectStmt= oracleStmt;
			  SQLSelectQuery oracleSqlSelectQuery = oracleStmt.getSelect().getQuery();
			  if(oracleSqlSelectQuery instanceof OracleSelectQueryBlock)
			  {
				  parseNativePageSql(oracleStmt, rrs, (OracleSelectQueryBlock) oracleSqlSelectQuery, schema);
			  }



		  }
		if(isNeedParseOrderAgg)
		{
			parseOrderAggGroupMysql(schema, selectStmt,rrs, mysqlSelectQuery);
			//更改canRunInReadDB属性
			if ((mysqlSelectQuery.isForUpdate() || mysqlSelectQuery.isLockInShareMode()) && rrs.isAutocommit() == false)
			{
				rrs.setCanRunInReadDB(false);
			}
		}

	}


}
 
Example #30
Source File: DruidMycatRouteStrategy.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * SELECT 语句
 */
private boolean isSelect(SQLStatement statement) {
	if(statement instanceof SQLSelectStatement) {
		return true;
	}
	return false;
}