How to change Calcite's default sql grammar, to support such sql statement "select func(id) as (a, b, c) from xx;"
1 Answer
To change the grammar accepted by the SQL parser, you will need to change the parser. There are two ways of doing this.
The first is to fork the project and change the core grammar, Parser.jj. But as always when you fork a project, you are responsible for re-applying your changes each time you upgrade to a new version of the project.
The second is to use one of the grammar expansion points provided by the Calcite project. Calcite's grammar is written in JavaCC, but the it first runs the grammar though the FreeMarker template engine. The expansion points are variables in the template that your project can re-assign. For example, if you want to add a new DDL command, you can modify the createStatementParserMethods
variable, as is done in Calcite's parser extension test:
# List of methods for parsing extensions to "CREATE [OR REPLACE]" calls.
# Each must accept arguments "(Span span, boolean replace)".
createStatementParserMethods: [
"SqlCreateTable"
]
Which of these approaches to use? Definitely use the second if you can, that is, if your grammar change occurs in one of the pre-defined expansion points. Use the first if only if you must, because you will run into the problem of maintaining a fork of the grammar.
If possible, see whether Calcite will accept the changes as a contribution. This is the ideal scenario for you, because Calcite will take on responsibility for maintaining your grammar extension. But they probably will only accept your change if it is standard SQL or a useful feature implemented by one or more major databases. And they will require your code to be high quality and accompanied by tests.
-
As you mentioned, I don't want to modify
jj
file itself but it seems like*.ftl
files can only accept new customized identifiers definition & parsing methods, what if I'd like to override the defaultParser.jj
? Commented Jun 8, 2019 at 7:49 -
is there a way to expand the grammar with a database-specific keywords of existing commands such as INSERT OVERWRITE, or LATERAL VIEW EXPLODE? thanks!– ShacharCommented Oct 24, 2020 at 3:41
-
Could you please give some more instructions on what to do with my own fmpp file? Commented Jun 21, 2023 at 8:04