/
PostgresqlSqlParser.java
220 lines (195 loc) · 8.94 KB
/
PostgresqlSqlParser.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/*
* Copyright 2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.r2dbc.postgresql;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static java.lang.Character.isWhitespace;
/**
* Utility to tokenize Postgres SQL statements.
*
* @since 0.9
*/
class PostgresqlSqlParser {
private static final char[] SPECIAL_AND_OPERATOR_CHARS = {
'+', '-', '*', '/', '<', '>', '=', '~', '!', '@', '#', '%', '^', '&', '|', '`', '?',
'(', ')', '[', ']', ',', ';', ':', '*', '.', '\'', '"'
};
static {
Arrays.sort(SPECIAL_AND_OPERATOR_CHARS);
}
public static ParsedSql tokenize(String sql) {
List<ParsedSql.Token> tokens = new ArrayList<>();
List<ParsedSql.TokenizedStatement> statements = new ArrayList<>();
int statementStartIndex = 0;
int i = 0;
while (i < sql.length()) {
char c = sql.charAt(i);
ParsedSql.Token token = null;
if (isWhitespace(c)) {
i++;
continue;
}
switch (c) {
case '\'': // "Standard" string constant
token = getStandardQuoteToken(sql, i);
break;
case '\"': // Quoted Identifier
token = getQuotedIdentifierToken(sql, i);
break;
case '-': // Possible start of double-dash comment
if ((i + 1) < sql.length() && sql.charAt(i + 1) == '-') {
token = getCommentToLineEndToken(sql, i);
}
break;
case '/': // Possible start of c-style comment
if ((i + 1) < sql.length() && sql.charAt(i + 1) == '*') {
token = getBlockCommentToken(sql, i);
}
break;
case '$': // Dollar-quoted constant or parameter
token = getParameterOrDollarQuoteToken(sql, i);
break;
case ';':
token = new ParsedSql.Token(ParsedSql.TokenType.STATEMENT_END, ";");
break;
default:
break;
}
if (token == null) {
if (isSpecialOrOperatorChar(c)) {
token = new ParsedSql.Token(ParsedSql.TokenType.SPECIAL_OR_OPERATOR, Character.toString(c));//getSpecialOrOperatorToken(sql, i);
} else {
token = getDefaultToken(sql, i);
}
}
i += token.getValue().length();
if (token.getType() == ParsedSql.TokenType.STATEMENT_END) {
tokens.add(token);
statements.add(new ParsedSql.TokenizedStatement(sql.substring(statementStartIndex, i), tokens));
tokens = new ArrayList<>();
statementStartIndex = i + 1;
} else {
tokens.add(token);
}
}
// If tokens is not empty, implicit statement end
if (!tokens.isEmpty()) {
statements.add(new ParsedSql.TokenizedStatement(sql.substring(statementStartIndex), tokens));
}
return new ParsedSql(sql, statements);
}
private static ParsedSql.Token getDefaultToken(String sql, int beginIndex) {
for (int i = beginIndex + 1; i < sql.length(); i++) {
char c = sql.charAt(i);
if (Character.isWhitespace(c) || isSpecialOrOperatorChar(c)) {
return new ParsedSql.Token(ParsedSql.TokenType.DEFAULT, sql.substring(beginIndex, i));
}
}
return new ParsedSql.Token(ParsedSql.TokenType.DEFAULT, sql.substring(beginIndex));
}
private static boolean isSpecialOrOperatorChar(char c) {
return Arrays.binarySearch(SPECIAL_AND_OPERATOR_CHARS, c) >= 0;
}
private static ParsedSql.Token getBlockCommentToken(String sql, int beginIndex) {
int depth = 1;
for (int i = beginIndex + 2; i < (sql.length() - 1); i++) {
char c1 = sql.charAt(i);
char c2 = sql.charAt(i + 1);
if (c1 == '/' && c2 == '*') {
depth++;
i++;
} else if (c1 == '*' && c2 == '/') {
depth--;
i++;
}
if (depth == 0) {
return new ParsedSql.Token(ParsedSql.TokenType.COMMENT, sql.substring(beginIndex, i + 1));
}
}
throw new IllegalArgumentException("Sql cannot be parsed: unclosed block comment (comment opened at index " + beginIndex + ") in statement: " + sql);
}
private static ParsedSql.Token getCommentToLineEndToken(String sql, int beginIndex) {
int lineEnding = sql.indexOf('\n', beginIndex);
if (lineEnding == -1) {
return new ParsedSql.Token(ParsedSql.TokenType.COMMENT, sql.substring(beginIndex));
} else {
return new ParsedSql.Token(ParsedSql.TokenType.COMMENT, sql.substring(beginIndex, lineEnding));
}
}
private static ParsedSql.Token getDollarQuoteToken(String sql, String tag, int beginIndex) {
int nextQuote = sql.indexOf(tag, beginIndex + tag.length());
if (nextQuote == -1) {
throw new IllegalArgumentException("Sql cannot be parsed: unclosed quote (quote opened at index " + beginIndex + ") in statement: " + sql);
} else {
return new ParsedSql.Token(ParsedSql.TokenType.STRING_CONSTANT, sql.substring(beginIndex, nextQuote + tag.length()));
}
}
private static ParsedSql.Token getParameterToken(String sql, int beginIndex) {
for (int i = beginIndex + 1; i < sql.length(); i++) {
char c = sql.charAt(i);
if (isWhitespace(c) || isSpecialOrOperatorChar(c)) {
return new ParsedSql.Token(ParsedSql.TokenType.PARAMETER, sql.substring(beginIndex, i));
}
if (!isAsciiDigit(c)) {
throw new IllegalArgumentException("Sql cannot be parsed: illegal character in parameter or dollar-quote tag: " + c);
}
}
return new ParsedSql.Token(ParsedSql.TokenType.PARAMETER, sql.substring(beginIndex));
}
private static ParsedSql.Token getParameterOrDollarQuoteToken(String sql, int beginIndex) {
char firstChar = sql.charAt(beginIndex + 1);
if (firstChar == '$') {
return getDollarQuoteToken(sql, "$$", beginIndex);
} else if (isAsciiDigit(firstChar)) {
return getParameterToken(sql, beginIndex);
} else {
for (int i = beginIndex + 1; i < sql.length(); i++) {
char c = sql.charAt(i);
if (c == '$') {
return getDollarQuoteToken(sql, sql.substring(beginIndex, i + 1), beginIndex);
}
if (!(isAsciiLetter(c) || c == '_' || isAsciiDigit(c))) {
throw new IllegalArgumentException("Sql cannot be parsed: illegal character in dollar-quote tag (quote opened at index " + beginIndex + ") in statement: " + sql);
}
}
throw new IllegalArgumentException("Sql cannot be parsed: unclosed dollar-quote tag(quote opened at index " + beginIndex + ") in statement: " + sql);
}
}
private static ParsedSql.Token getStandardQuoteToken(String sql, int beginIndex) {
int nextQuote = sql.indexOf('\'', beginIndex + 1);
if (nextQuote == -1) {
throw new IllegalArgumentException("Sql cannot be parsed: unclosed quote (quote opened at index " + beginIndex + ") in statement: " + sql);
} else {
return new ParsedSql.Token(ParsedSql.TokenType.STRING_CONSTANT, sql.substring(beginIndex, nextQuote + 1));
}
}
private static ParsedSql.Token getQuotedIdentifierToken(String sql, int beginIndex) {
int nextQuote = sql.indexOf('\"', beginIndex + 1);
if (nextQuote == -1) {
throw new IllegalArgumentException("Sql cannot be parsed: unclosed quoted identifier (identifier opened at index " + beginIndex + ") in statement: " + sql);
} else {
return new ParsedSql.Token(ParsedSql.TokenType.QUOTED_IDENTIFIER, sql.substring(beginIndex, nextQuote + 1));
}
}
private static boolean isAsciiLetter(char c){
char lower = Character.toLowerCase(c);
return lower >= 'a' && lower <= 'z';
}
private static boolean isAsciiDigit(char c){
return c >= '0' && c <= '9';
}
}