以下为本人做的SQL词法分析器初步规则的设计,当然有些可能有些错误,可能需要后期修改
SQL语句->SELECT语句|UPDATE语句|DELETE语句|INSERT语句
值->[a-zA-Z]+[0-9]*(_)[a-zA-Z]+[0-9]*
SELECT语句->SELECT语句 [UNION|UNION ALL] SELECT语句|SELECT (DISTINCT) 字段 FROM 表名 (分组) (连接) (WHERE 条件) (排序)
表名->值|SELECT语句 (AS值)
字段->字段(,字段)|值|*|(CASE语句 (AS 值))
表名->值|(SELECT语句 AS 值)
条件->条件( OR|AND 条件)|值 比较条件 值
比较条件->>|<|>=|<=|=|<>|LIKE
分组->GROUP BY 字段 (HAVING 条件)
排序->ORDER BY 字段 (ASC|DESC)
连接->[LEFT JOIN|LEFT OUTER JOIN|RIGHT JOIN|RIGHT OUTER JOIN|INNER JOIN|FULL JOIN] 表名 ON 条件
CASE语句->CASE [WHEN 条件 THEN 值]+ (ELSE 值) END | CASE 条件 [WHEN 值 THEN 值]+ (ELSE 值) END
非终结符替换
代号 |
代替的值 |
状态 |
A |
SELECT语句 |
S1 |
B |
表名 |
S2 |
C |
字段 |
S3 |
D |
分组 |
S4 |
E |
连接 |
S5 |
F |
条件 |
S6 |
G |
排序 |
S7 |
H |
值 |
S8 |
I |
CASE语句 |
S9 |
J |
比较条件 |
S10 |
K |
关键字 |
S11 |
终结符替换(关键字)
终结符 |
状态 |
WHEN |
C1 |
SELECT |
C2 |
DISTINCT |
C3 |
FROM |
C4 |
WHERE |
C5 |
LEFT JOIN |
C6 |
LEFT OUTER JOIN |
C7 |
RIGHT JOIN |
C8 |
RIGHT OUTER JOIN |
C9 |
INNER JOIN |
C10 |
FULL JOIN |
C11 |
HAVING |
C12 |
ASC |
C13 |
DESC |
C14 |
CASE |
C15 |
END |
C16 |
ELSE |
C17 |
ON |
C18 |
UNION |
C19 |
UNION ALL |
C20 |
AS |
C21 |
ORDER BY |
C22 |
GOURP BY |
C23 |
OR |
C24 |
AND |
C25 |
THEN |
C26 |
LIKE |
C27 |
推导式变为:
A->A C19 A|A C20 A|C2 (C3) C C4 B (D) (E) (C5 F) (G)
B->H|A C21 H
C->C(,C)|H|*|(I (C21 H))
D->C22 C (C12 F)
E->[C6|C7|C8|C9|C10|C12] B C18 F
F->F (C24|C25 F)|H J H
G->C23 C (C13|C14)
LETTER->A|B|…|Z|a|b|…|c
DIGIT->0|1|…|9
H->LETTER(LETTER|DIGIT)*
I->C15[ C1 F C26 H]+ (C17 H) C16|C15 C [C1 H THEN H ]+( C17 H) C16
J->>|<|>=|<=|=|<>|LIKE
消除A的直接左递归
A->C2 (C3) C C4 B (D) (E) (C5 F) (G) P1
P1->C19 A P1|ε
消除F的直接左递归
F-> H J H P2
P2-> (C24|C25 F) P2|ε
消除C的直接左递归
C-> (H|*|(I (C21 H))) P3
P3->(,C) P3|ε