[alibaba/druid]MySql解析器只支持Create语句保留Comment

2025-11-11 237 views
4

在对SQL语句进行格式化时,使用

SQLUtils.format(sqlStr, DbType.mysql);

处理完后,发现Comment进行了丢弃 查看源码发现,MySqlStatementParser 只有处理Create语句时对Comment进行了保留处理

回答

0

有办法了么?

6

自定义了解析器和输出

public class WwMySqlStatementParser extends MySqlStatementParser { public WwMySqlStatementParser (String sql, SQLParserFeature... features) { super(sql, features); }

@Override
public MySqlDeleteStatement parseDeleteStatement() {
    List<String> comments = null;
    if (lexer.isKeepComments() && lexer.hasComment()) {
        comments = lexer.readAndResetComments();
    }
    MySqlDeleteStatement stmt = super.parseDeleteStatement();

    if (comments != null) {
        stmt.addBeforeComment(comments);
    }
    return stmt;
}

@Override
public SQLStatement parseAlter() {
    List<String> comments = null;
    if (lexer.isKeepComments() && lexer.hasComment()) {
        comments = lexer.readAndResetComments();
    }
    SQLStatement stmt = super.parseAlter();

    if (comments != null) {
        stmt.addBeforeComment(comments);
    }
    return stmt;
}

@Override
public SQLInsertStatement parseInsert() {
    List<String> comments = null;
    if (lexer.isKeepComments() && lexer.hasComment()) {
        comments = lexer.readAndResetComments();
    }
    SQLInsertStatement stmt =  super.parseInsert();
    if (comments != null) {
        stmt.addBeforeComment(comments);
    }
    return stmt;
}

}

public class WwMySqlOutputVisitor extends MySqlOutputVisitor {

 @Override
public boolean visit(MySqlDeleteStatement x) {
    // 打印Comments
    if (this.isPrettyFormat() && x.hasBeforeComment()) {
        this.printlnComments(x.getBeforeCommentsDirect());
    }
    return super.visit(x);
}

@Override public boolean visit(MySqlInsertStatement x) { // 打印Comments if (this.isPrettyFormat() && x.hasBeforeComment()) { this.printlnComments(x.getBeforeCommentsDirect()); } return super.visit(x); }

@Override public boolean visit(SQLAlterTableStatement x) { if (this.isPrettyFormat() && x.hasBeforeComment()) { this.printlnComments(x.getBeforeCommentsDirect()); } return super.visit(x); }

@Override public boolean visit(SQLCreateIndexStatement x) { // 打印Comments if (this.isPrettyFormat() && x.hasBeforeComment()) { this.printlnComments(x.getBeforeCommentsDirect()); } return super.visit(x); } }

2

请提交pull request