Java Code Examples for com.alibaba.druid.sql.parser.SQLStatementParser

The following examples show how to use com.alibaba.druid.sql.parser.SQLStatementParser. 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: SelectHandler.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static boolean isSupportSelect(String stmt) {
    SQLStatementParser parser = new MySqlStatementParser(stmt);
    SQLStatement statement = parser.parseStatement();
    if (!(statement instanceof SQLSelectStatement)) {
        return false;
    }

    SQLSelectQuery sqlSelectQuery = ((SQLSelectStatement) statement).getSelect().getQuery();
    if (!(sqlSelectQuery instanceof MySqlSelectQueryBlock)) {
        return false;
    }
    MySqlSelectQueryBlock selectQueryBlock = (MySqlSelectQueryBlock) sqlSelectQuery;
    SQLTableSource mysqlFrom = selectQueryBlock.getFrom();
    if (mysqlFrom != null) {
        return false;
    }
    for (SQLSelectItem item : selectQueryBlock.getSelectList()) {
        SQLExpr selectItem = item.getExpr();
        if (!isVariantRef(selectItem)) {
            return false;
        }
    }
    return true;
}
 
Example 2
Source Project: dble   Source File: ExplainHandler.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static boolean isInsertSeq(ServerConnection c, String stmt, SchemaConfig schema) throws SQLException {
    SQLStatementParser parser = new MySqlStatementParser(stmt);
    MySqlInsertStatement statement = (MySqlInsertStatement) parser.parseStatement();
    String schemaName = schema == null ? null : schema.getName();
    SQLExprTableSource tableSource = statement.getTableSource();
    SchemaUtil.SchemaInfo schemaInfo = SchemaUtil.getSchemaInfo(c.getUser(), schemaName, tableSource);
    String tableName = schemaInfo.getTable();
    schema = schemaInfo.getSchemaConfig();
    TableConfig tableConfig = schema.getTables().get(tableName);
    if (tableConfig == null) {
        return false;
    } else if (tableConfig.isAutoIncrement()) {
        return true;
    }
    return false;
}
 
Example 3
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 4
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 5
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 6
Source Project: Mycat2   Source File: ExplainHandler.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static boolean isMycatSeq(String stmt, SchemaConfig schema)
  {
      if(pattern.matcher(stmt).find()) {
	return true;
}
      SQLStatementParser parser =new MySqlStatementParser(stmt);
      MySqlInsertStatement statement = (MySqlInsertStatement) parser.parseStatement();
      String tableName=   statement.getTableName().getSimpleName();
      TableConfig tableConfig= schema.getTables().get(tableName.toUpperCase());
      if(tableConfig==null) {
	return false;
}
      if(tableConfig.isAutoIncrement())
      {
          boolean isHasIdInSql=false;
          String primaryKey = tableConfig.getPrimaryKey();
          List<SQLExpr> columns = statement.getColumns();
          for (SQLExpr column : columns)
          {
              String columnName = column.toString();
              if(primaryKey.equalsIgnoreCase(columnName))
              {
                  isHasIdInSql = true;
                  break;
              }
          }
          if(!isHasIdInSql) {
		return true;
	}
      }


      return false;
  }
 
Example 7
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 8
Source Project: Mycat2   Source File: ParseUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static String changeInsertAddSlot(String sql,int slotValue)
{
    SQLStatementParser parser = new MycatStatementParser(sql);
    MySqlInsertStatement insert = (MySqlInsertStatement) parser.parseStatement();
    insert.getColumns().add(new SQLIdentifierExpr("_slot") );
    insert.getValues().getValues().add(new SQLIntegerExpr(slotValue))  ;
    return insert.toString();
}
 
Example 9
Source Project: Mycat2   Source File: HintDataNodeHandler.java    License: GNU General Public License v3.0 5 votes vote down vote up
private LoadData parseLoadDataPram(String sql , String connectionCharset)
{
	SQLStatementParser parser = new MycatStatementParser(sql);
	MySqlLoadDataInFileStatement statement = (MySqlLoadDataInFileStatement) parser.parseStatement();

	LoadData loadData = new LoadData();
	SQLTextLiteralExpr rawLineEnd = (SQLTextLiteralExpr) statement.getLinesTerminatedBy();
	String lineTerminatedBy = rawLineEnd == null ? "\n" : rawLineEnd.getText();
	loadData.setLineTerminatedBy(lineTerminatedBy);

	SQLTextLiteralExpr rawFieldEnd = (SQLTextLiteralExpr) statement.getColumnsTerminatedBy();
	String fieldTerminatedBy = rawFieldEnd == null ? "\t" : rawFieldEnd.getText();
	loadData.setFieldTerminatedBy(fieldTerminatedBy);

	SQLTextLiteralExpr rawEnclosed = (SQLTextLiteralExpr) statement.getColumnsEnclosedBy();
	String enclose = rawEnclosed == null ? null : rawEnclosed.getText();
	loadData.setEnclose(enclose);

	SQLTextLiteralExpr escapseExpr =  (SQLTextLiteralExpr)statement.getColumnsEscaped() ;
	String escapse=escapseExpr==null?"\\":escapseExpr.getText();
	loadData.setEscape(escapse);
	String charset = statement.getCharset() != null ? statement.getCharset() : connectionCharset;
	loadData.setCharset(charset);

	String fileName = parseFileName(sql);
	if(StringUtils.isBlank(fileName)){
		throw new RuntimeException(" file name is null !");
	}

	loadData.setFileName(fileName);

	return loadData ;
}
 
Example 10
Source Project: dble   Source File: MetaHelper.java    License: GNU General Public License v2.0 5 votes vote down vote up
static TableMeta initTableMeta(String table, String sql, long timeStamp) {
    if (sql == null) {
        return null;
    }

    try {
        SQLStatementParser parser = new DbleCreateTableParser(sql);
        SQLCreateTableStatement createStatement = parser.parseCreateTable();
        return MetaHelper.initTableMeta(table, createStatement, timeStamp);
    } catch (Exception e) {
        LOGGER.warn("sql[" + sql + "] parser error:", e);
        AlertUtil.alertSelf(AlarmCode.GET_TABLE_META_FAIL, Alert.AlertLevel.WARN, "sql[" + sql + "] parser error:" + e.getMessage(), null);
        return null;
    }
}
 
Example 11
Source Project: dble   Source File: SetHandler.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static SQLStatement parseSQL(String stmt) throws SQLSyntaxErrorException {
    SQLStatementParser parser = new MySqlStatementParser(stmt);
    try {
        return parser.parseStatement();
    } catch (Exception t) {
        if (t.getMessage() != null) {
            throw new SQLSyntaxErrorException(t.getMessage());
        } else {
            throw new SQLSyntaxErrorException(t);
        }
    }
}
 
Example 12
private List<WhereUnit> getAllWhereUnit(String sql) {
    SQLStatementParser parser = new MySqlStatementParser(sql);

    ServerSchemaStatVisitor visitor;
    //throw exception
    try {
        SQLStatement statement = parser.parseStatement();
        visitor = new ServerSchemaStatVisitor();
        statement.accept(visitor);
        return visitor.getAllWhereUnit();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return  null;
}
 
Example 13
private PlanNode getPlanNode(String sql) {
    SQLStatementParser parser = new MySqlStatementParser(sql);
    SQLSelectStatement ast = (SQLSelectStatement) parser.parseStatement();
    MySQLPlanNodeVisitor visitor = new MySQLPlanNodeVisitor("TESTDB", 33, null, true, null);
    visitor.visit(ast);
    return visitor.getTableNode();
}
 
Example 14
Source Project: elasticsearch-sql   Source File: ESActionFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create the compatible Query object
 * based on the SQL query.
 * @param sql The SQL query.
 * @return Query object.
 */
   public static QueryAction create(Client client, String sql) throws SqlParseException, SQLFeatureNotSupportedException {
       sql = sql.replaceAll("\n", " ").trim();
       String firstWord = sql.substring(0, sql.indexOf(' '));
       switch (firstWord.toUpperCase()) {
		case "SELECT":
		    //zhongshu-comment 将sql字符串解析成AST,即SQLQueryExpr sqlExpr就是AST了,下面的代码就开始访问AST、从中获取token
			SQLQueryExpr sqlExpr = (SQLQueryExpr) toSqlExpr(sql);
               if(isMulti(sqlExpr)){//zhongshu-comment 判断是不是union查询,union查询两个select语句,btw:子查询也有多个select语句,至少2个
                   MultiQuerySelect multiSelect = new SqlParser().parseMultiSelect((SQLUnionQuery) sqlExpr.getSubQuery().getQuery());
                   handleSubQueries(client,multiSelect.getFirstSelect());
                   handleSubQueries(client,multiSelect.getSecondSelect());
                   return new MultiQueryAction(client, multiSelect);
               }
               else if(isJoin(sqlExpr,sql)){//zhongshu-comment join连接查询
                   JoinSelect joinSelect = new SqlParser().parseJoinSelect(sqlExpr);
                   handleSubQueries(client, joinSelect.getFirstTable());
                   handleSubQueries(client, joinSelect.getSecondTable());
                   return ESJoinQueryActionFactory.createJoinAction(client, joinSelect);
               }
               else {
                   //zhongshu-comment 大部分查询都是走这个分支,先看懂这个分支
                   Select select = new SqlParser().parseSelect(sqlExpr);
                   //todo 看不懂,测试了好几个常见的sql,都没有进去handleSubQueries该方法,那就先不理了,看别的
                   handleSubQueries(client, select);
                   return handleSelect(client, select);
               }
		case "DELETE":
               SQLStatementParser parser = createSqlStatementParser(sql);
			SQLDeleteStatement deleteStatement = parser.parseDeleteStatement();
			Delete delete = new SqlParser().parseDelete(deleteStatement);
			return new DeleteQueryAction(client, delete);
           case "SHOW":
               return new ShowQueryAction(client,sql);
		default:
			throw new SQLFeatureNotSupportedException(String.format("Unsupported query: %s", sql));
	}
}
 
Example 15
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 16
private void db2ValidationQueryCheck() {
    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 db2 validationQuery. " + validationQuery + ", may should be : " + validationQuery
                    + " FROM SYSDUMMY");
        }
    }
}
 
Example 17
Source Project: DataLink   Source File: DBUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static void sqlValid(String sql, DataBaseType dataBaseType){
    SQLStatementParser statementParser = SQLParserUtils.createSQLStatementParser(sql,dataBaseType.getTypeName());
    statementParser.parseStatementList();
}
 
Example 18
@Override
public void start(String sql)
{
    clear();
    this.sql = sql;


    SQLStatementParser parser = new MycatStatementParser(sql);
    statement = (MySqlLoadDataInFileStatement) parser.parseStatement();
    fileName = parseFileName(sql);

    if (fileName == null)
    {
        serverConnection.writeErrMessage(ErrorCode.ER_FILE_NOT_FOUND, " file name is null !");
        clear();
        return;
    }
    schema = MycatServer.getInstance().getConfig()
            .getSchemas().get(serverConnection.getSchema());
    if (schema == null){
        throw new RuntimeException("please sql:use schema  before load data");
    }
    tableId2DataNodeCache = (LayerCachePool) MycatServer.getInstance().getCacheService().getCachePool("TableID2DataNodeCache");
    tableName = statement.getTableName().getSimpleName().toUpperCase();
    tableConfig = schema.getTables().get(tableName);
  if(  tableConfig.getRule() != null && tableConfig.getRule().getRuleAlgorithm() instanceof SlotFunction){
      shoudAddSlot=true;
  }
    tempPath = SystemConfig.getHomePath() + File.separator + "temp" + File.separator + serverConnection.getId() + File.separator;
    tempFile = tempPath + "clientTemp.txt";
    tempByteBuffer = new ByteArrayOutputStream();

    List<SQLExpr> columns = statement.getColumns();
    if(tableConfig!=null)
    {
        String pColumn = getPartitionColumn();
        if (pColumn != null && columns != null && columns.size() > 0) {
            for (int i = 0, columnsSize = columns.size(); i < columnsSize; i++) {
                String column = StringUtil.removeBackquote(columns.get(i).toString());
                if (pColumn.equalsIgnoreCase(column)) {
                    partitionColumnIndex = i;
                }
                if("_slot".equalsIgnoreCase(column)){
                    shoudAddSlot=false;
                }
            }

        }
    }
        if(shoudAddSlot){
            columns.add(new SQLIdentifierExpr("_slot"));
        }
    parseLoadDataPram();
    if (statement.isLocal())
    {
        isStartLoadData = true;
        //向客户端请求发送文件
        ByteBuffer buffer = serverConnection.allocate();
        RequestFilePacket filePacket = new RequestFilePacket();
        filePacket.fileName = fileName.getBytes();
        filePacket.packetId = 1;
        filePacket.write(buffer, serverConnection, true);
    } else
    {
        if (!new File(fileName).exists())
        {
            serverConnection.writeErrMessage(ErrorCode.ER_FILE_NOT_FOUND, fileName + " is not found!");
            clear();
        } else
        {
            parseFileByLine(fileName, loadData.getCharset(), loadData.getLineTerminatedBy());
            RouteResultset rrs = buildResultSet(routeResultMap);
            if (rrs != null)
            {
                flushDataToFile();
                isStartLoadData = false;
                serverConnection.getSession2().execute(rrs, ServerParse.LOAD_DATA_INFILE_SQL);
            }

        }
    }
}
 
Example 19
Source Project: Mycat2   Source File: SchemaUtil.java    License: GNU General Public License v3.0 4 votes vote down vote up
public static SchemaInfo parseSchema(String sql) {
    SQLStatementParser parser = new MySqlStatementParser(sql);
    return parseTables(parser.parseStatement(), new MycatSchemaStatVisitor());
}
 
Example 20
Source Project: Mycat2   Source File: MycatPrivileges.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean checkDmlPrivilege(String user, String schema, String sql) {

	if ( schema == null ) {
		return true;
	}
	
	boolean isPassed = false;

	MycatConfig conf = MycatServer.getInstance().getConfig();
	UserConfig userConfig = conf.getUsers().get(user);
	if (userConfig != null) {
		
		UserPrivilegesConfig userPrivilege = userConfig.getPrivilegesConfig();
		if ( userPrivilege != null && userPrivilege.isCheck() ) {				
		
			UserPrivilegesConfig.SchemaPrivilege schemaPrivilege = userPrivilege.getSchemaPrivilege( schema );
			if ( schemaPrivilege != null ) {
	
				String tableName = null;
				int index = -1;
				
				//TODO 此处待优化,寻找更优SQL 解析器
				
				//修复bug
				// https://github.com/alibaba/druid/issues/1309
				//com.alibaba.druid.sql.parser.ParserException: syntax error, error in :'begin',expect END, actual EOF begin
				if ( sql != null && sql.length() == 5 && sql.equalsIgnoreCase("begin") ) {
					return true;
				}
				
				SQLStatementParser parser = new MycatStatementParser(sql);			
				SQLStatement stmt = parser.parseStatement();

				if (stmt instanceof MySqlReplaceStatement || stmt instanceof SQLInsertStatement ) {
					index = 0;
				} else if (stmt instanceof SQLUpdateStatement ) {
					index = 1;
				} else if (stmt instanceof SQLSelectStatement ) {
					index = 2;
				} else if (stmt instanceof SQLDeleteStatement ) {
					index = 3;
				}

				if ( index > -1) {
					
					SchemaStatVisitor schemaStatVisitor = new MycatSchemaStatVisitor();
					stmt.accept(schemaStatVisitor);
					String key = schemaStatVisitor.getCurrentTable();
					if ( key != null ) {
						
						if (key.contains("`")) {
							key = key.replaceAll("`", "");
						}
						
						int dotIndex = key.indexOf(".");
						if (dotIndex > 0) {
							tableName = key.substring(dotIndex + 1);
						} else {
							tableName = key;
						}							
						
						//获取table 权限, 此处不需要检测空值, 无设置则自动继承父级权限
						UserPrivilegesConfig.TablePrivilege tablePrivilege = schemaPrivilege.getTablePrivilege( tableName );
						if ( tablePrivilege.getDml()[index] > 0 ) {
							isPassed = true;
						}
						
					} else {
						//skip
						isPassed = true;
					}
					
					
				} else {						
					//skip
					isPassed = true;
				}
				
			} else {					
				//skip
				isPassed = true;
			}
			
		} else {
			//skip
			isPassed = true;
		}

	} else {
		//skip
		isPassed = true;
	}
	
	if( !isPassed ) {
		 ALARM.error(new StringBuilder().append(Alarms.DML_ATTACK ).append("[sql=").append( sql )
                    .append(",user=").append(user).append(']').toString());
	}
	
	return isPassed;
}
 
Example 21
Source Project: Mycat2   Source File: TableStatAnalyzer.java    License: GNU General Public License v3.0 4 votes vote down vote up
private SQLStatement parseStmt(String sql) {
	SQLStatementParser statParser = SQLParserUtils.createSQLStatementParser(sql, "mysql");
	SQLStatement stmt = statParser.parseStatement();
	return stmt;		
}
 
Example 22
Source Project: dble   Source File: ShowHandler.java    License: GNU General Public License v2.0 4 votes vote down vote up
private static boolean isSupportShow(String stmt) {
    SQLStatementParser parser = new MySqlStatementParser(stmt);
    SQLStatement statement = parser.parseStatement();
    return statement instanceof MySqlShowWarningsStatement || statement instanceof MySqlShowVariantsStatement;
}
 
Example 23
Source Project: dble   Source File: TableStatAnalyzer.java    License: GNU General Public License v2.0 4 votes vote down vote up
private SQLStatement parseStmt(String sql) {
    SQLStatementParser statParser = SQLParserUtils.createSQLStatementParser(sql, "mysql");
    SQLStatement stmt = statParser.parseStatement();
    return stmt;
}
 
Example 24
Source Project: dble   Source File: MergeBuilder.java    License: GNU General Public License v2.0 4 votes vote down vote up
private RouteResultset constructByQuery(String sql, Map<String, String> mapTableToSimple, SchemaConfig schemaConfig) throws SQLException {
    SQLStatementParser parser = new MySqlStatementParser(sql);
    SQLSelectStatement select = (SQLSelectStatement) parser.parseStatement();
    return constructByStatement(sql, mapTableToSimple, select, schemaConfig);
}
 
Example 25
Source Project: dble   Source File: MetaParseTest.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Test
public void createTableCommentTest() {
    String sql = "CREATE TABLE `suntest` (\n" +
            "\t`id` INT (11) DEFAULT NULL,\n" +
            "\t`name` VARCHAR (50) DEFAULT NULL\n" +
            ") ENGINE = INNODB DEFAULT CHARSET = latin1";
    SQLStatementParser parser = new MySqlCreateTableParser(sql);
    parser.parseCreateTable();

    sql = "CREATE TABLE `suntest` (\n" +
            "\t`id` INT (11) NOT NULL,\n" +
            "\t`name` VARCHAR (50) DEFAULT NULL,\n" +
            "\tPRIMARY KEY (`id`)\n" +
            ") ENGINE = INNODB DEFAULT CHARSET = latin1";
    parser = new MySqlCreateTableParser (sql);
    parser.parseCreateTable();


    sql = "CREATE TABLE `suntest` (\n" +
            "\t`id` INT (11) NOT NULL,\n" +
            "\t`name` VARCHAR (50) DEFAULT NULL,\n" +
            "\tPRIMARY KEY (`id`),\n" +
            "\tUNIQUE KEY `name` (`name`)\n" +
            ") ENGINE = INNODB DEFAULT CHARSET = latin1";
    parser = new MySqlCreateTableParser (sql);
    parser.parseCreateTable();


    sql = "CREATE TABLE `suntest` (\n" +
            "\t`id` INT (11) NOT NULL,\n" +
            "\t`name` VARCHAR (50) DEFAULT NULL,\n" +
            "\tPRIMARY KEY (`id`),\n" +
            "\tUNIQUE KEY `name` (`name`)\n" +
            ") ENGINE = INNODB DEFAULT CHARSET = latin1 COMMENT = 'suntest_comment'";
    parser = new MySqlCreateTableParser (sql);
    parser.parseCreateTable();


    sql = "CREATE TABLE `suntest` (\n" +
            "  `id` int(11) NOT NULL COMMENT 'test,test)',\n" +
            "  `name` varchar(50) DEFAULT NULL,\n" +
            "  PRIMARY KEY (`id`),\n" +
            "  UNIQUE KEY `name` (`name`)\n" +
            ") ENGINE=InnoDB DEFAULT CHARSET=utf8 MIN_ROWS=10 MAX_ROWS=1000 AVG_ROW_LENGTH=20 CHECKSUM=1 COMMENT='suntest_comment'";
    parser = new MySqlCreateTableParser (sql);
    parser.parseCreateTable();


    sql = "CREATE TABLE `suntest` (\n" +
            "  `id` int(11) NOT NULL COMMENT 'test''test',\n" +
            "  `name` varchar(50) DEFAULT NULL,\n" +
            "  PRIMARY KEY (`id`),\n" +
            "  KEY `name_index` (`name`) COMMENT 'ffff'\n" +
            ") ENGINE=InnoDB DEFAULT CHARSET=utf8 MIN_ROWS=10 MAX_ROWS=1000 AVG_ROW_LENGTH=20 CHECKSUM=1 COMMENT='suntest_comment'";
    parser = new MySqlCreateTableParser (sql);
    parser.parseCreateTable();

    sql = "CREATE TABLE `suntest` (\n" +
            "  `id` int(11) NOT NULL COMMENT 'test''test',\n" +
            "  `name` varchar(50) DEFAULT NULL,\n" +
            "  PRIMARY KEY (`id`),\n" +
            "  UNIQUE KEY `name` (`name`) COMMENT 'test_comment'\n" +
            ") ENGINE=InnoDB DEFAULT CHARSET=utf8 MIN_ROWS=10 MAX_ROWS=1000 AVG_ROW_LENGTH=20 CHECKSUM=1 COMMENT='suntest_comment'";
    parser = new MySqlCreateTableParser (sql);
    parser.parseCreateTable();


    sql = "CREATE TABLE `suntest` (\n" +
            "  `id` int(11) NOT NULL COMMENT 'test''test',\n" +
            "  `name` varchar(20) DEFAULT NULL,\n" +
            "  `rid` int(11) DEFAULT NULL,\n" +
            "  PRIMARY KEY (`id`),\n" +
            "  KEY `rid` (`rid`),\n" +
            "  CONSTRAINT `suntest_ibfk_1` FOREIGN KEY (`rid`) REFERENCES `dbletest` (`id`) COMMENT 'XXXX' " +
            ") ENGINE=InnoDB DEFAULT CHARSET=utf8 MIN_ROWS=10 MAX_ROWS=1000 AVG_ROW_LENGTH=20 CHECKSUM=1 COMMENT='suntest_comment'";
    parser = new MySqlCreateTableParser (sql);
    parser.parseCreateTable();


    sql = "CREATE TABLE `suntest` (\n" +
            "  `id` int(11) NOT NULL COMMENT 'test''test',\n" +
            "  `name` varchar(50) DEFAULT NULL,\n" +
            "  PRIMARY KEY (`id`),\n" +
            "  FULLTEXT KEY `name_index` (`name`) COMMENT 'sdfasdf'\n" +
            ") ENGINE=InnoDB DEFAULT CHARSET=utf8 MIN_ROWS=10 MAX_ROWS=1000 AVG_ROW_LENGTH=20 CHECKSUM=1 COMMENT='suntest_comment'";
    parser = new MySqlCreateTableParser (sql);
    parser.parseCreateTable();


    sql = "CREATE TABLE `suntest` (\n" +
            "  `id` int(11) NOT NULL COMMENT 'test''test',\n" +
            "  `name` varchar(20) DEFAULT NULL,\n" +
            "  `rid` int(11) DEFAULT NULL,\n" +
            "  PRIMARY KEY (`id`) COMMENT 'ffff',\n" +
            "  KEY `rid` (`rid`) COMMENT 'xxxxx',\n" +
            "  CONSTRAINT `suntest_ibfk_1` FOREIGN KEY (`rid`) REFERENCES `dbletest` (`id`)\n" +
            ") ENGINE=InnoDB DEFAULT CHARSET=utf8 MIN_ROWS=10 MAX_ROWS=1000 AVG_ROW_LENGTH=20 CHECKSUM=1 COMMENT='suntest_comment'";
    parser = new MySqlCreateTableParser (sql);
    parser.parseCreateTable();

}
 
Example 26
Source Project: dble   Source File: TestMySQLItemVisitor.java    License: GNU General Public License v2.0 4 votes vote down vote up
private SQLSelectStatement getSelectStatement(String sql) {
    SQLStatementParser parser = new MySqlStatementParser(sql);
    return (SQLSelectStatement) parser.parseStatement();
}
 
Example 27
Source Project: elasticsearch-sql   Source File: ESActionFactory.java    License: Apache License 2.0 4 votes vote down vote up
public static SQLStatementParser createSqlStatementParser(String sql) {
    ElasticLexer lexer = new ElasticLexer(sql);
    lexer.nextToken();
    return new MySqlStatementParser(lexer);
}
 
Example 28
private Object[] getParseTables(String sql) throws Exception{
	
	SQLStatementParser parser = new MySqlStatementParser(sql);
	SQLStatement statement = parser.parseStatement();
       MycatSchemaStatVisitor visitor = new MycatSchemaStatVisitor();
       
       
       LayerCachePool cachePool = mock(LayerCachePool.class);
       RouteResultset rrs = new RouteResultset(sql, ServerParse.SELECT);
	
	druidParser.parser(schema, rrs, statement, sql, cachePool, visitor);
	
	DruidShardingParseInfo ctx = druidParser.getCtx();
	return ctx.getTables().toArray();
}