class SQLUtils {

    public static String checkSql(String sql, DatabaseCategory category) {
        final boolean isMySQL = category == DatabaseCategory.MySql;

        List<SQLStatement> sqlStatements = com.alibaba.druid.sql.SQLUtils.parseStatements(sql, isMySQL? JdbcConstants.MYSQL : JdbcConstants.SQL_SERVER);
        Preconditions.checkArgument(sqlStatements.size() == 1, "请不要输入多条SQL语句");
        SQLStatement sqlStatement = sqlStatements.get(0);
        if(isMySQL) {
            if(sqlStatement instanceof SQLSelectStatement){
                AtomicInteger offset = new AtomicInteger(0);
                AtomicInteger count  = new AtomicInteger(-1);
                sqlStatement.accept(new SQLASTVisitorAdapter() {
                    @Override public boolean visit(SQLLimit x) {
                        if(x.getOffset() != null){
                            offset.set(((SQLIntegerExpr)x.getOffset()).getNumber().intValue());
                        }
                        count.set(((SQLIntegerExpr)x.getRowCount()).getNumber().intValue());
                        return true;
                    }
                });

                Preconditions.checkArgument(count.get() <= LIMIT_MAX, "请不要输入 limit > " + LIMIT_MAX);
                return PagerUtils.limit(sql, JdbcConstants.MYSQL, offset.get(), count.get() == -1 ? LIMIT_MAX  : count.get());
            }
            if (sqlStatement instanceof SQLShowTablesStatement) {
                return sql;
            }
        } else {
            if(sqlStatement instanceof SQLSelectStatement){
                AtomicInteger offset = new AtomicInteger(0);
                AtomicInteger count  = new AtomicInteger(-1);
                sqlStatement.accept(new SQLServerASTVisitorAdapter() {
                    @Override public boolean visit(SQLServerTop x) {//Check top
                        count.set(((SQLIntegerExpr)x.getExpr()).getNumber().intValue());
                        return true;
                    }
                    @Override public boolean visit(SQLServerSelectQueryBlock x) {
                        SQLLimit limit = x.getLimit();
                        if(limit != null){
                            if(limit.getOffset() != null){
                                offset.set(((SQLIntegerExpr)limit.getOffset()).getNumber().intValue());
                            }
                            if(limit.getRowCount() != null) {
                                count.set(((SQLIntegerExpr) limit.getRowCount()).getNumber().intValue());
                            }
                        }

                        return true;
                    }
                });
                Preconditions.checkArgument(count.get() <= LIMIT_MAX, "请不要输入 limit > " + LIMIT_MAX);
                return PagerUtils.limit(sql, JdbcConstants.SQL_SERVER, offset.get(), count.get() == -1 ? LIMIT_MAX  : count.get());
            }
        }
        throw new IllegalArgumentException("只支持查询SQL语句");
    }

}