此文已由作者张镐薪授权网易云社区发布。

欢迎访问网易云社区,了解更多网易技术产品运营经验。

public static void handle(String stmt, ServerConnection c, int offs) {
        int offset = offs;
        switch (ServerParseSelect.parse(stmt, offs)) {
        case ServerParseSelect.VERSION_COMMENT:
            SelectVersionComment.response(c);
            break;
        case ServerParseSelect.DATABASE:
            SelectDatabase.response(c);
            break;
        case ServerParseSelect.USER:
            SelectUser.response(c);
            break;
        case ServerParseSelect.VERSION:
            SelectVersion.response(c);
            break;
        case ServerParseSelect.SESSION_INCREMENT:
            SessionIncrement.response(c);
            break;
        case ServerParseSelect.SESSION_ISOLATION:
            SessionIsolation.response(c);
            break;
        case ServerParseSelect.LAST_INSERT_ID:
            // offset = ParseUtil.move(stmt, 0, "select".length());
            loop:for (int l=stmt.length(); offset < l; ++offset) {
                switch (stmt.charAt(offset)) {
                case ' ':
                    continue;
                case '/':
                case '#':
                    offset = ParseUtil.comment(stmt, offset);
                    continue;
                case 'L':
                case 'l':
                    break loop;
                }
            }
            offset = ServerParseSelect.indexAfterLastInsertIdFunc(stmt, offset);
            offset = ServerParseSelect.skipAs(stmt, offset);
            SelectLastInsertId.response(c, stmt, offset);
            break;
        case ServerParseSelect.IDENTITY:
            // offset = ParseUtil.move(stmt, 0, "select".length());
            loop:for (int l=stmt.length(); offset < l; ++offset) {
                switch (stmt.charAt(offset)) {
                case ' ':
                    continue;
                case '/':
                case '#':
                    offset = ParseUtil.comment(stmt, offset);
                    continue;
                case '@':
                    break loop;
                }
            }
            int indexOfAtAt = offset;
            offset += 2;
            offset = ServerParseSelect.indexAfterIdentity(stmt, offset);
            String orgName = stmt.substring(indexOfAtAt, offset);
            offset = ServerParseSelect.skipAs(stmt, offset);
            SelectIdentity.response(c, stmt, offset, orgName);
            break;
            case ServerParseSelect.SELECT_VAR_ALL:
                SelectVariables.execute(c,stmt);
                break;
        default:
            c.execute(stmt, ServerParse.SELECT);
        }
    }

下一步,ServerConnection类处理SQL语句

ServerConnection.java

public void execute(String sql, int type) {        //连接状态检查
        if (this.isClosed()) {
            LOGGER.warn("ignore execute ,server connection is closed " + this);            return;
        }        // 事务状态检查
        if (txInterrupted) {
            writeErrMessage(ErrorCode.ER_YES,                    "Transaction error, need to rollback." + txInterrputMsg);            return;
        }        // 检查当前使用的DB
        String db = this.schema;        if (db == null) {
            db = SchemaUtil.detectDefaultDb(sql, type);            if (db == null) {
                writeErrMessage(ErrorCode.ERR_BAD_LOGICDB, "No MyCAT Database selected");                return;
            }
        }        // 兼容PhpAdmin's, 支持对MySQL元数据的模拟返回
        //// TODO: 2016/5/20 支持更多information_schema特性 
        if (ServerParse.SELECT == type 
                && db.equalsIgnoreCase("information_schema") ) {
            MysqlInformationSchemaHandler.handle(sql, this);            return;
        }        if (ServerParse.SELECT == type 
                && sql.contains("mysql") 
                && sql.contains("proc")) {             SchemaUtil.SchemaInfo schemaInfo = SchemaUtil.parseSchema(sql);            if (schemaInfo != null 
                    && "mysql".equalsIgnoreCase(schemaInfo.schema)
                    && "proc".equalsIgnoreCase(schemaInfo.table)) {                // 兼容MySQLWorkbench
                MysqlProcHandler.handle(sql, this);                return;
            }
        }         SchemaConfig schema = MycatServer.getInstance().getConfig().getSchemas().get(db);        if (schema == null) {
            writeErrMessage(ErrorCode.ERR_BAD_LOGICDB,                    "Unknown MyCAT Database '" + db + "'");            return;
        }         routeEndExecuteSQL(sql, type, schema);     }

调用routeEndExecuteSQL方法,会解析出RouteResultSet。这步包含了SQL语义解析,SQL路由,SQL查询优化,SQL语句改写,全局ID生成,最后,将解析出的RouteResultSet交给这个链接对应的session进行处理。 我们先分析SQL语义解析。看调用: ServerConnection.java

rrs = MycatServer
                    .getInstance()
                    .getRouterservice()
                    .route(MycatServer.getInstance().getConfig().getSystem(),
                            schema, type, sql, this.charset, this);

首先,关注下这个Routerservice是啥?在MyCat初始化时,会新建一个Routerservice(如之前配置模块中所讲): MyCatServer.java

//路由计算初始化routerService = new RouteService(cacheService);

Routerservice结构:  其中sqlRouteCache和tableId2DataNodeCache是通过CacheService(MyCat里面是ehcache做的缓存)传入的对于sql语句缓存和tableid与后台分片对应关系的缓存。具体缓存会在缓存模块中讲。

调用route方法解析出RouteResultSet

public RouteResultset route(SystemConfig sysconf, SchemaConfig schema,            int sqlType, String stmt, String charset, ServerConnection sc)
            throws SQLNonTransientException {
        RouteResultset rrs = null;
        String cacheKey = null;        /**
         *  SELECT 类型的SQL, 检测
         */
        if (sqlType == ServerParse.SELECT) {
            cacheKey = schema.getName() + stmt;            
            rrs = (RouteResultset) sqlRouteCache.get(cacheKey);            if (rrs != null) {                return rrs;
            }
        }        /*!mycat: sql = select name from aa */
        /*!mycat: schema = test *///      boolean isMatchOldHint = stmt.startsWith(OLD_MYCAT_HINT);//      boolean isMatchNewHint = stmt.startsWith(NEW_MYCAT_HINT);//        if (isMatchOldHint || isMatchNewHint ) {
        int hintLength = RouteService.isHintSql(stmt);        if(hintLength != -1){            int endPos = stmt.indexOf("*/");            if (endPos > 0) {                
                // 用!mycat:内部的语句来做路由分析//                int hintLength = isMatchOldHint ? OLD_MYCAT_HINT.length() : NEW_MYCAT_HINT.length();
                String hint = stmt.substring(hintLength, endPos).trim();                     int firstSplitPos = hint.indexOf(HINT_SPLIT);                
                if(firstSplitPos > 0 ){
                    Map hintMap=    parseHint(hint);
                    String hintType = (String) hintMap.get(MYCAT_HINT_TYPE);
                    String hintSql = (String) hintMap.get(hintType);                    if( hintSql.length() == 0 ) {
                        LOGGER.warn("comment int sql must meet :/*!mycat:type=value*/ or /*#mycat:type=value*/ or /*mycat:type=value*/: "+stmt);                        throw new SQLSyntaxErrorException("comment int sql must meet :/*!mycat:type=value*/ or /*#mycat:type=value*/ or /*mycat:type=value*/: "+stmt);
                    }
                    String realSQL = stmt.substring(endPos + "*/".length()).trim();                     HintHandler hintHandler = HintHandlerFactory.getHintHandler(hintType);                    if( hintHandler != null ) {                             if ( hintHandler instanceof  HintSQLHandler) {                            
                              /**
                             * 修复 注解SQL的 sqlType 与 实际SQL的 sqlType 不一致问题, 如: hint=SELECT,real=INSERT
                             * fixed by zhuam
                             */
                            int hintSqlType = ServerParse.parse( hintSql ) & 0xff;     
                            rrs = hintHandler.route(sysconf, schema, sqlType, realSQL, charset, sc, tableId2DataNodeCache, hintSql,hintSqlType,hintMap);                         } else {                            
                            rrs = hintHandler.route(sysconf, schema, sqlType, realSQL, charset, sc, tableId2DataNodeCache, hintSql,sqlType,hintMap);
                        }                     }else{
                        LOGGER.warn("TODO , support hint sql type : " + hintType);
                    }                 }else{//fixed by runfriends@126.com
                    LOGGER.warn("comment in sql must meet :/*!mycat:type=value*/ or /*#mycat:type=value*/ or /*mycat:type=value*/: "+stmt);                    throw new SQLSyntaxErrorException("comment in sql must meet :/*!mcat:type=value*/ or /*#mycat:type=value*/ or /*mycat:type=value*/: "+stmt);
                }
            }
        } else {
            stmt = stmt.trim();
            rrs = RouteStrategyFactory.getRouteStrategy().route(sysconf, schema, sqlType, stmt,
                    charset, sc, tableId2DataNodeCache);
        }        if (rrs != null && sqlType == ServerParse.SELECT && rrs.isCacheAble()) {
            sqlRouteCache.putIfAbsent(cacheKey, rrs);
        }        return rrs;
    }

由于注解处理和sql解析有重叠,而且注解处理一直代码不稳定,所以,这里不涉及。只说sql正常解析的步骤

免费体验云安全(易盾)内容安全、验证码等服务

更多网易技术、产品、运营经验分享请点击

相关文章:
【推荐】 Redux其实很简单(原理篇)

数据库路由中间件MyCat - 源代码篇(15)的更多相关文章

  1. 数据库路由中间件MyCat - 源代码篇(1)

    此文已由作者张镐薪授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 进入了源代码篇,我们先从整体入手,之后拿一个简单流程前端连接建立与认证作为例子,理清代码思路和设计模式.然后 ...

  2. 数据库路由中间件MyCat - 源代码篇(13)

    此文已由作者张镐薪授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 4.配置模块 4.2 schema.xml 接上一篇,接下来载入每个schema的配置(也就是每个MyCat ...

  3. 数据库路由中间件MyCat - 源代码篇(7)

    此文已由作者张镐薪授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 3. 连接模块 3.4 FrontendConnection前端连接 构造方法: public Fronte ...

  4. 数据库路由中间件MyCat - 源代码篇(17)

    此文已由作者张镐薪授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 调用processInsert(sc,schema,sqlType,origSQL,tableName,pr ...

  5. 数据库路由中间件MyCat - 源代码篇(14)

    此文已由作者张镐薪授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 对于表的dataNode对应关系,有个特殊配置即类似dataNode="distributed(d ...

  6. 数据库路由中间件MyCat - 源代码篇(4)

    此文已由作者易国强授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 2. 前端连接建立与认证 Title:MySql连接建立以及认证过程client->MySql:1.T ...

  7. 数据库路由中间件MyCat - 源代码篇(2)

    此文已由作者张镐薪授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 2. 前端连接建立与认证 Title:MySql连接建立以及认证过程client->MySql:1.T ...

  8. 数据库路由中间件MyCat - 源代码篇(16)

    此文已由作者张镐薪授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 5. 路由模块 真正取得RouteResultset的步骤:AbstractRouteStrategy的ro ...

  9. 数据库路由中间件MyCat - 源代码篇(10)

    此文已由作者张镐薪授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 3. 连接模块 3.5 后端连接 3.5.2 后端连接获取与维护管理 还是那之前的流程, st=>st ...

随机推荐

  1. programming-languages学习笔记--第5部分

    programming-languages学习笔记–第5部分 */--> pre.src {background-color: #292b2e; color: #b2b2b2;} program ...

  2. 2019.3.6 Github学习 &Git学习

    Github学习 1.使用Github 1.1 目的 借助github托管项目代码 1.2 基本概念 仓库(Repository) 仓库的意思是:即你的项目,你想在Github上开源一个项目,那就必须 ...

  3. PHP扩展功能 ---- 伪静态

    一.入门三部曲 1.什么是伪静态? 改写URL,以静态的url形式访问页面,但其实是用PHP一类的动态脚本来处理的. 2.为什么要用伪静态? 需要动态获取数据,但是又希望能够对搜索引擎友好. 3.怎么 ...

  4. jenkins持续集成工作原理

    转载https://www.cnblogs.com/liyuanhong/p/6548925.html 片段 这里是选择Gitlab作为git server.Gitlab的功能和Github差不多,但 ...

  5. COSTA Cross-layer Optimization for Sketch-based笔记与感受

    Main Idea 网络测量在sdn中十分重要,使用sketch的方法需要消耗大量硬件资源,占用其他重要功能的资源,无法容纳更多的测量任务.基于sketch的测量方法有两个特性:基于sketch的测量 ...

  6. Reading Software Defined Traffic Measurement with OpenSketch

    NSDI '13 概要 OpenSketch是一个通用的.抽象的测量框架, 与SDN 网络架构类似, OpenSketch 提出将测量控制层和数据层解耦. 数据层运行设为可动态配置的3阶段流水线, 首 ...

  7. Reading Fast Packet Processing A Survey

    COMST 2018 主要内容 这是一篇有关快速包转发的综述,先介绍了包转发的有关基础知识和背景,具体介绍了包转发的主流方法,对这些方法进行了细致详尽的比较,最后介绍了最新的方法和未来的研究方向. 包 ...

  8. MVC 当中 [ValidateAntiForgeryToken] 的作用

     ValidateAntiForgeryToken 防止CSRF(跨网站请求伪造) 用途:防止CSRF(跨网站请求伪造). 用法:在View->Form表单中:<%:Html.AntiFo ...

  9. Oracle DataGuard启动与关闭顺序

    (一)Active DataGuard启动顺序(1)启动监听,先启从库再起主库 lsnrctl start (2)启动数据库,先启动备库在启主库 --先启备库 sql>startup nomou ...

  10. MongoDB可视化工具RoboMongo

    官网下载安装包:https://robomongo.org/download (开始使用的是mongoVUE,研究半天,最后发现貌似已经挂掉了,坑!后来上手的robomongo) 安装没什么说的,一直 ...