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

The following examples show how to use com.alibaba.druid.sql.ast.SQLStatement. 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
Source Project: dble   Source File: DruidCreateIndexParser.java    License: 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 2
Source Project: dble   Source File: DefaultRouteStrategy.java    License: 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 3
Source Project: youran   Source File: ReverseEngineeringService.java    License: 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 4
Source Project: Mycat2   Source File: SchemaUtil.java    License: 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 5
Source Project: dble   Source File: SetHandler.java    License: 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 6
Source Project: Mycat2   Source File: DruidDeleteParser.java    License: 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 7
Source Project: Zebra   Source File: MySQLDialect.java    License: 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 8
@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 9
@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 10
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 11
Source Project: Mycat2   Source File: RouterUtil.java    License: 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 12
Source Project: dble   Source File: SchemaUtil.java    License: 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 13
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 14
Source Project: dble   Source File: DefaultDruidParser.java    License: 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 15
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 16
Source Project: dble   Source File: TableHandler.java    License: 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 17
Source Project: dble   Source File: TableHandler.java    License: 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 18
Source Project: txle   Source File: AutoCompensateDeleteHandler.java    License: 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 19
Source Project: txle   Source File: AutoCompensateHandler.java    License: 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 Project: dble   Source File: SchemaUtil.java    License: 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
private void oracleValidationQueryCheck() {
    if (validationQuery == null) {
        return;
    }
    if (validationQuery.length() == 0) {
        return;
    }

    SQLStatementParser sqlStmtParser = SQLParserUtils.createSQLStatementParser(validationQuery, this.dbType);
    List<SQLStatement> stmtList = sqlStmtParser.parseStatementList();

    if (stmtList.size() != 1) {
        return;
    }

    SQLStatement stmt = stmtList.get(0);
    if (!(stmt instanceof SQLSelectStatement)) {
        return;
    }

    SQLSelectQuery query = ((SQLSelectStatement) stmt).getSelect().getQuery();
    if (query instanceof SQLSelectQueryBlock) {
        if (((SQLSelectQueryBlock) query).getFrom() == null) {
            LOG.error("invalid oracle validationQuery. " + validationQuery + ", may should be : " + validationQuery
                    + " FROM DUAL");
        }
    }
}
 
Example 22
Source Project: Zebra   Source File: ShardLimitSqlWithConditionRewrite.java    License: 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 23
Source Project: txle   Source File: CompensateService.java    License: 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 24
Source Project: youran   Source File: ReverseEngineeringService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 执行反向工程
 *
 * @param dto
 */
@Transactional(rollbackFor = RuntimeException.class)
public void execute(ReverseEngineeringDTO dto) {
    MetaProjectPO project = metaProjectService.getAndCheckProject(dto.getProjectId());
    List<SQLStatement> list = this.parse(dto);
    for (SQLStatement sqlStatement : list) {
        this.saveEntityFromSqlStatement(project, (SQLCreateTableStatement) sqlStatement);
    }
}
 
Example 25
Source Project: dble   Source File: DescribeHandler.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void handle(String stmt, ServerConnection c) {
    try {
        SQLStatement statement = RouteStrategyFactory.getRouteStrategy().parserSQL(stmt);
        MySqlExplainStatement describeStatement = (MySqlExplainStatement) statement;
        SchemaInfo schemaInfo = SchemaUtil.getSchemaInfo(c.getUser(), c.getSchema(), describeStatement.getTableName(), null);
        c.routeSystemInfoAndExecuteSQL(RouterUtil.removeSchema(stmt, schemaInfo.getSchema()), schemaInfo, ServerParse.DESCRIBE);
    } catch (Exception e) {
        c.writeErrMessage(ErrorCode.ER_PARSE_ERROR, e.toString());
        return;
    }
}
 
Example 26
Source Project: dble   Source File: DruidUpdateParserTest.java    License: 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 27
Source Project: Mycat2   Source File: ShareJoin.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void route(SystemConfig sysConfig, SchemaConfig schema,int sqlType, String realSQL, String charset, ServerConnection sc,	LayerCachePool cachePool) {
	int rs = ServerParse.parse(realSQL);
	this.sqltype = rs & 0xff;
	this.sysConfig=sysConfig; 
	this.schema=schema;
	this.charset=charset; 
	this.sc=sc;	
	this.cachePool=cachePool;		
	try {
	 //  RouteStrategy routes=RouteStrategyFactory.getRouteStrategy();	
	  // rrs =RouteStrategyFactory.getRouteStrategy().route(sysConfig, schema, sqlType2, realSQL,charset, sc, cachePool);		   
		MySqlStatementParser parser = new MySqlStatementParser(realSQL);			
		SQLStatement statement = parser.parseStatement();
		if(statement instanceof SQLSelectStatement) {
		   SQLSelectStatement st=(SQLSelectStatement)statement;
		   SQLSelectQuery sqlSelectQuery =st.getSelect().getQuery();
			if(sqlSelectQuery instanceof MySqlSelectQueryBlock) {
				MySqlSelectQueryBlock mysqlSelectQuery = (MySqlSelectQueryBlock)sqlSelectQuery;
				joinParser=new JoinParser(mysqlSelectQuery,realSQL);
				joinParser.parser();
			}	
		}
	   /*	
	   if (routes instanceof DruidMysqlRouteStrategy) {
		   SQLSelectStatement st=((DruidMysqlRouteStrategy) routes).getSQLStatement();
		   SQLSelectQuery sqlSelectQuery =st.getSelect().getQuery();
			if(sqlSelectQuery instanceof MySqlSelectQueryBlock) {
				MySqlSelectQueryBlock mysqlSelectQuery = (MySqlSelectQueryBlock)st.getSelect().getQuery();
				joinParser=new JoinParser(mysqlSelectQuery,realSQL);
				joinParser.parser();
			}
	   }
	   */
	} catch (Exception e) {
	
	}
}
 
Example 28
Source Project: Zebra   Source File: SqlToCountSqlRewrite.java    License: Apache License 2.0 5 votes vote down vote up
public String rewrite(String sql, List<ParamContext> countParams) {
	MySqlStatementParser parser = new MySqlStatementParser(sql);
	SQLStatement stmt = parser.parseStatement();
	RewriteSqlToCountSqlVisitor visitor = new RewriteSqlToCountSqlVisitor(countParams);
	stmt.accept(visitor);

	return stmt.toString();
}
 
Example 29
Source Project: Mycat2   Source File: PreparedStatement.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static String[] getColumns(String sql) {
    String[] columnNames;
    try {
        SQLStatementParser sqlStatementParser = SQLParserUtils.createSQLStatementParser(sql, JdbcUtils.MYSQL);
        SQLStatement statement = sqlStatementParser.parseStatement();
        if (statement instanceof SQLSelectStatement) {
            SQLSelect select = ((SQLSelectStatement) statement).getSelect();
            com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock query = (com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock) select.getQuery();
            int size = query.getSelectList().size();
            if (size == 1){
                if("*".equalsIgnoreCase(   query.getSelectList().get(0).toString())){
                    throw new Exception("unsupport * in select items:"+sql);
                }
            } {
                columnNames = new String[size];
                for (int i = 0; i < size; i++) {
                    columnNames[i] = query.getSelectList().get(i).toString();
                }
                return columnNames;
            }

        }
    }catch (Exception e){
        LOGGER.error("can not get column count",e);
    }
    return new String[]{};
}
 
Example 30
Source Project: dble   Source File: ShowTablesStmtInfo.java    License: GNU General Public License v2.0 5 votes vote down vote up
ShowTablesStmtInfo(String sql) throws SQLSyntaxErrorException {
    Matcher ma = PATTERN.matcher(sql);
    ma.matches(); //always RETURN TRUE
    isFull = ma.group(3) != null;
    isAll = isFull && ma.group(4).equalsIgnoreCase("all");
    schema = ma.group(8) == null ? null : StringUtil.removeBackQuote(ma.group(8));
    cond = ma.group(10);

    StringBuilder sb = new StringBuilder(ma.group(2));
    if (isFull) {
        sb.append(" full ");
    }
    sb.append(ma.group(5));
    if (ma.group(6) != null) {
        if (ma.group(7).equalsIgnoreCase("in")) {
            sb.append(" from ");
            sb.append(schema);
        } else {
            sb.append(ma.group(6));
        }
    }
    if (cond != null)
        sb.append(cond);
    sql = sb.toString();
    SQLStatement statement = RouteStrategyFactory.getRouteStrategy().parserSQL(sql);
    whereExpr = ((SQLShowTablesStatement) statement).getWhere();
    if (whereExpr != null) {
        where = whereExpr.toString();
    }
    SQLExpr likeExpr = ((SQLShowTablesStatement) statement).getLike();
    if (likeExpr != null) {
        like = StringUtil.removeApostrophe(likeExpr.toString());
    }
}