Use Javacc to HQL-> SQL (1)

xiaoxiao2021-03-06  52

Mainly to try Javacc, use the idea of ​​compilation principle to construct your own language :)

First go to https://javacc.dev.java.net/ Javacc's home to download Javacc

Our goal today is to convert from Teacher to SELECT *.

First write .jj files

1. Define separator to open

Skip: {"" | "/ t" | "/ n" | "/ r" | "/ f"}

2. Define the keyword. From the keyword of HQL, Teacher is a class name entered by the user. It should be a word consisting of letters and numbers. We can use regular expressions: ["A" - "z", "a" - "z" , "0" - "9"].

Token: / * reserved tokens for uql * / { | }

3. Next define the order and specification of the input

Void expression (): {token ttable;} {( ttable = ) {SQLSB.Append ("SELECT *"); SQLSB.Append ("from") .append (TTable.Image);}}

Finally, write parsing code to generate Java code.

Parser_Begin (HQLParser)

Import java.lang.stringbuffer; import java.io.stringReader; import java.io.reader;

Public class hqlparser {

Private static stringbuffer sqlsb;

/ ** a string based constructor for ease of use. ** / public hqlParser (String S) {this ((Reader)); sqlsb = new stringbuffer ();}

Public string getsql () {return sqlsb.tostring (); public static void main (string args []) {Try {string query = args [}; hqlparser parser = new hqlparser (query); parser.parse (); System.out.println ("SQL:" Parser.getsql ());} catch (exception e) {E.PrintStackTrace ();}}

Public void parse () {Try {expression ();} catch (exception e) {E.PrintStackTrace ();}}} Parser_END (HQLPARSER)

Next to DOS Enter: javacc -debug_parser test.jj

-debug_parser: Used to output syntax tree

At this time, seven Java files will be generated, and the role of each file will be described in detail later.

Time only needs

Javac * .java can compile all Java files

Then perform Java HqlParser "from Teacher"

At this time, "Select * from Teacher" will be displayed.

Detailed annotations of the code will be issued tomorrow.

转载请注明原文地址:https://www.9cbs.com/read-117456.html

New Post(0)