内容简介:SQL on Hadoop 按 SQL 解析可分为两大阵营:ANTLR 阵营的包括:Apache Hive、Apache Spark、Presto。Apache Calcite 阵营的包括:Apache Flink、Apache Kylin。下面以 SparkSession 的
SQL on Hadoop 按 SQL 解析可分为两大阵营:
ANTLR 阵营的包括:Apache Hive、Apache Spark、Presto。Apache Calcite 阵营的包括:Apache Flink、Apache Kylin。
下面以 SparkSession 的 sql(sqlText: String): DataFrame
为例,描述 SQL 语句的解析过程:
/** * Executes a SQL query using Spark, returning the result as a `DataFrame`. * The dialect that is used for SQL parsing can be configured with 'spark.sql.dialect'. * * @since 2.0.0 */ def sql(sqlText: String): DataFrame = { Dataset.ofRows(self, sessionState.sqlParser.parsePlan(sqlText)) }
SparkSqlParser
在 AbstractSqlParser,实现了 ParserInterface 的 parsePlan 方法:
首先,调用 parse 方法将 SQL 解析为抽象语法树;
然后,回调方法里,从 singleStatement 结点开始,遍历语法树,将结点转换为逻辑计划。
/** Creates LogicalPlan for a given SQL string. */ override def parsePlan(sqlText: String): LogicalPlan = parse(sqlText) { parser => astBuilder.visitSingleStatement(parser.singleStatement()) match { case plan: LogicalPlan => plan case _ => val position = Origin(None, None) throw new ParseException(Option(sqlText), "Unsupported SQL statement", position, position) } }
在 parse 方法里,使用 ANTLR 4 实现了 SQL 语句的词法分析和语法分析,获得了抽象语法树。
词法分析:
val lexer = new SqlBaseLexer(new UpperCaseCharStream(CharStreams.fromString(command))) lexer.removeErrorListeners() lexer.addErrorListener(ParseErrorListener)
语法分析:
val tokenStream = new CommonTokenStream(lexer) val parser = new SqlBaseParser(tokenStream) parser.addParseListener(PostProcessor) parser.removeErrorListeners() parser.addErrorListener(ParseErrorListener)
回调:
// first, try parsing with potentially faster SLL mode parser.getInterpreter.setPredictionMode(PredictionMode.SLL) toResult(parser)
SparkSqlAstBuilder
其中,SqlBaseVisitor 和 SqlBaseBaseVistor 是由 SqlBase.g4 生成的访问者(Visitor)模式解析类。
从 singleStatement 节点开始,遍历整个语法树,生成逻辑计划。查看 SQL 生成的未解析的逻辑计划:
val unresolvedLogicalPlan = spark.sql(sql) .queryExecution .logical
基于 Spark 2.3.0 版本
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 以太坊源码分析(36)ethdb源码分析
- [源码分析] kubelet源码分析(一)之 NewKubeletCommand
- libmodbus源码分析(3)从机(服务端)功能源码分析
- [源码分析] nfs-client-provisioner源码分析
- [源码分析] kubelet源码分析(三)之 Pod的创建
- Spring事务源码分析专题(一)JdbcTemplate使用及源码分析
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Programming From The Ground Up
Jonathan Bartlett / Bartlett Publishing / 2004-07-31 / USD 34.95
Programming from the Ground Up is an introduction to programming using assembly language on the Linux platform for x86 machines. It is a great book for novices who are just learning to program as wel......一起来看看 《Programming From The Ground Up》 这本书的介绍吧!