public static QueryAction create ( Client client , String sql ) throws SqlParseException , SQLFeatureNotSupportedException { sql = sql . replaceAll ( "\n" , " " ) ; 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 ) ) ; } }
Create the compatible Query object based on the SQL query .