zoukankan      html  css  js  c++  java
  • 利用hive源码解析sql查了哪些表哪些字段

    在hiveserver2中使用了org.apache.hadoop.hive.ql.parse.BaseSemanticAnalyzer对抽象语法树(AST)进行语义分析,分析的过程可以得出hive查询的表及其字段
    于是我利用相关的类去做测试:

    package com.baidu.waimai;
    
    import org.apache.hadoop.hive.conf.HiveConf;
    import org.apache.hadoop.hive.ql.Context;
    import org.apache.hadoop.hive.ql.parse.*;
    import org.apache.hadoop.hive.ql.session.SessionState;
    
    public class TestHiveParser {
        public static void main(String[] args) throws Throwable {
    //        String sql = "select * from (select name from test.test1 where id = 1) a";
            String sql = "select * from test.test1";
    
            HiveConf hiveConf = new HiveConf();
            hiveConf.set("hive.stats.collect.tablekeys", "true");
            hiveConf.set("hive.stats.collect.scancols", "true");
    
            SessionState sessionState = SessionState.start(hiveConf);
            sessionState.initTxnMgr(hiveConf);
            SessionState.setCurrentSessionState(sessionState);
    
            Context ctx = new Context(hiveConf);
            ctx.setTryCount(Integer.MAX_VALUE);
            ctx.setCmd(sql);
            ctx.setHDFSCleanup(true);
    
            ParseDriver pd = new ParseDriver();
            ASTNode tree = pd.parse(sql);
            tree = ParseUtils.findRootNonNullToken(tree);
            System.out.println(tree);
            BaseSemanticAnalyzer baseSemanticAnalyzer = SemanticAnalyzerFactory.get(hiveConf, tree);
            System.out.println(baseSemanticAnalyzer);
            baseSemanticAnalyzer.analyze(tree, ctx);
            TableAccessInfo tableAccessInfo = baseSemanticAnalyzer.getTableAccessInfo();
            System.out.println(tableAccessInfo);
    
            ColumnAccessInfo columnAccessInfo = baseSemanticAnalyzer.getColumnAccessInfo();
            System.out.println(columnAccessInfo);
    
            sessionState.close();
            ctx.clear();
        }
    }
    

    最后可以根据columnAccessInfo去得到查询的表及其字段。
    但这么做不太满足我们的需求,比如说下面这句sql,我想要的结果是查询了test.test1表的name字段,但是它连id字段也拿出来了。

    select * from (select name from test.test1 where id = 1) a
    

    先记录一下,之后如果找到源码有解决方法的话再更新

  • 相关阅读:
    Oracle 数据块,文件块转换,查看数据块对像
    逆向与汇编视频(36课) IDA 使用
    VC++消息钩子编程
    VS2008中opengl配置
    BSP技术详解3有图有真相
    BSP技术详解1有图有真相
    oracle 跟踪文件和转储命令
    BSP技术详解2有图有真相
    Recognizing and Learning Object Categories 连接放送
    自学MVC看这里——全网最全ASP.NET MVC 教程汇总
  • 原文地址:https://www.cnblogs.com/lanhj/p/7543308.html
Copyright © 2011-2022 走看看