/
StatementParser.java
403 lines (374 loc) · 14.2 KB
/
StatementParser.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
/*
* Copyright 2019 Google LLC
*
* 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
*
* http://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 com.google.cloud.spanner.jdbc;
import com.google.cloud.spanner.ErrorCode;
import com.google.cloud.spanner.SpannerExceptionFactory;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.jdbc.ClientSideStatementImpl.CompileException;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import java.util.Collections;
import java.util.Set;
/**
* Internal class for the Spanner Connection API.
*
* <p>Parses {@link ClientSideStatement}s and normal SQL statements. The parser is able to recognize
* the type of statement, allowing the connection API to know which method on Spanner should be
* called. The parser does not validate the validity of statements, except for {@link
* ClientSideStatement}s. This means that an invalid DML statement could be accepted by the {@link
* StatementParser} and sent to Spanner, and Spanner will then reject it with some error message.
*/
class StatementParser {
/** Singleton instance of {@link StatementParser}. */
public static final StatementParser INSTANCE = new StatementParser();
/** The type of statement that has been recognized by the parser. */
enum StatementType {
CLIENT_SIDE,
DDL,
QUERY,
UPDATE,
UNKNOWN;
}
/** A statement that has been parsed */
static class ParsedStatement {
private final StatementType type;
private final ClientSideStatementImpl clientSideStatement;
private final Statement statement;
private final String sqlWithoutComments;
private static ParsedStatement clientSideStatement(
ClientSideStatementImpl clientSideStatement,
Statement statement,
String sqlWithoutComments) {
return new ParsedStatement(clientSideStatement, statement, sqlWithoutComments);
}
private static ParsedStatement ddl(Statement statement, String sqlWithoutComments) {
return new ParsedStatement(StatementType.DDL, statement, sqlWithoutComments);
}
private static ParsedStatement query(Statement statement, String sqlWithoutComments) {
return new ParsedStatement(StatementType.QUERY, statement, sqlWithoutComments);
}
private static ParsedStatement update(Statement statement, String sqlWithoutComments) {
return new ParsedStatement(StatementType.UPDATE, statement, sqlWithoutComments);
}
private static ParsedStatement unknown(Statement statement, String sqlWithoutComments) {
return new ParsedStatement(StatementType.UNKNOWN, statement, sqlWithoutComments);
}
private ParsedStatement(
ClientSideStatementImpl clientSideStatement,
Statement statement,
String sqlWithoutComments) {
Preconditions.checkNotNull(clientSideStatement);
Preconditions.checkNotNull(statement);
this.type = StatementType.CLIENT_SIDE;
this.clientSideStatement = clientSideStatement;
this.statement = statement;
this.sqlWithoutComments = sqlWithoutComments;
}
private ParsedStatement(StatementType type, Statement statement, String sqlWithoutComments) {
Preconditions.checkNotNull(type);
Preconditions.checkNotNull(statement);
this.type = type;
this.clientSideStatement = null;
this.statement = statement;
this.sqlWithoutComments = sqlWithoutComments;
}
StatementType getType() {
return type;
}
boolean isQuery() {
switch (type) {
case CLIENT_SIDE:
return getClientSideStatement().isQuery();
case QUERY:
return true;
case UPDATE:
case DDL:
case UNKNOWN:
default:
}
return false;
}
boolean isUpdate() {
switch (type) {
case CLIENT_SIDE:
return getClientSideStatement().isUpdate();
case UPDATE:
return true;
case QUERY:
case DDL:
case UNKNOWN:
default:
}
return false;
}
boolean isDdl() {
switch (type) {
case DDL:
return true;
case CLIENT_SIDE:
case UPDATE:
case QUERY:
case UNKNOWN:
default:
}
return false;
}
Statement getStatement() {
return statement;
}
String getSqlWithoutComments() {
return sqlWithoutComments;
}
ClientSideStatement getClientSideStatement() {
Preconditions.checkState(
clientSideStatement != null,
"This ParsedStatement does not contain a ClientSideStatement");
return clientSideStatement;
}
}
private final Set<String> ddlStatements = ImmutableSet.of("CREATE", "DROP", "ALTER");
private final Set<String> selectStatements = ImmutableSet.of("SELECT", "WITH");
private final Set<String> dmlStatements = ImmutableSet.of("INSERT", "UPDATE", "DELETE");
private final Set<ClientSideStatementImpl> statements;
/** Private constructor for singleton instance. */
private StatementParser() {
try {
statements =
Collections.unmodifiableSet(ClientSideStatements.INSTANCE.getCompiledStatements());
} catch (CompileException e) {
throw new RuntimeException(e);
}
}
/**
* Parses the given statement and categorizes it as one of the possible {@link StatementType}s.
* The validity of the statement is not checked, unless it is a client-side statement.
*
* @param statement The statement to parse.
* @return the parsed and categorized statement.
*/
ParsedStatement parse(Statement statement) {
String sql = removeCommentsAndTrim(statement.getSql());
ClientSideStatementImpl client = parseClientSideStatement(sql);
if (client != null) {
return ParsedStatement.clientSideStatement(client, statement, sql);
} else if (isQuery(sql)) {
return ParsedStatement.query(statement, sql);
} else if (isUpdateStatement(sql)) {
return ParsedStatement.update(statement, sql);
} else if (isDdlStatement(sql)) {
return ParsedStatement.ddl(statement, sql);
}
return ParsedStatement.unknown(statement, sql);
}
/**
* Parses the given statement as a client-side statement. Client-side statements are statements
* that are never sent to Cloud Spanner, but that are interpreted by the Connection API and then
* translated into some action, such as for example starting a transaction or getting the last
* commit timestamp.
*
* @param sql The statement to try to parse as a client-side statement (without any comments).
* @return a valid {@link ClientSideStatement} or null if the statement is not a client-side
* statement.
*/
@VisibleForTesting
ClientSideStatementImpl parseClientSideStatement(String sql) {
for (ClientSideStatementImpl css : statements) {
if (css.matches(sql)) {
return css;
}
}
return null;
}
/**
* Checks whether the given statement is (probably) a DDL statement. The method does not check the
* validity of the statement, only if it is a DDL statement based on the first word in the
* statement.
*
* @param sql The statement to check (without any comments).
* @return <code>true</code> if the statement is a DDL statement (i.e. starts with 'CREATE',
* 'ALTER' or 'DROP').
*/
boolean isDdlStatement(String sql) {
return statementStartsWith(sql, ddlStatements);
}
/**
* Checks whether the given statement is (probably) a SELECT query. The method does not check the
* validity of the statement, only if it is a SELECT statement based on the first word in the
* statement.
*
* @param sql The statement to check (without any comments).
* @return <code>true</code> if the statement is a SELECT statement (i.e. starts with 'SELECT').
*/
boolean isQuery(String sql) {
// Skip any query hints at the beginning of the query.
if (sql.startsWith("@")) {
sql = removeStatementHint(sql);
}
return statementStartsWith(sql, selectStatements);
}
/**
* Checks whether the given statement is (probably) an update statement. The method does not check
* the validity of the statement, only if it is an update statement based on the first word in the
* statement.
*
* @param sql The statement to check (without any comments).
* @return <code>true</code> if the statement is a DML update statement (i.e. starts with
* 'INSERT', 'UPDATE' or 'DELETE').
*/
boolean isUpdateStatement(String sql) {
return statementStartsWith(sql, dmlStatements);
}
private boolean statementStartsWith(String sql, Iterable<String> checkStatements) {
Preconditions.checkNotNull(sql);
String[] tokens = sql.split("\\s+", 2);
if (tokens.length > 0) {
for (String check : checkStatements) {
if (tokens[0].equalsIgnoreCase(check)) {
return true;
}
}
}
return false;
}
/**
* Removes comments from and trims the given sql statement. Spanner supports three types of
* comments:
*
* <ul>
* <li>Single line comments starting with '--'
* <li>Single line comments starting with '#'
* <li>Multi line comments between '/*' and '*/'
* </ul>
*
* Reference: https://cloud.google.com/spanner/docs/lexical#comments
*
* @param sql The sql statement to remove comments from and to trim.
* @return the sql statement without the comments and leading and trailing spaces.
*/
static String removeCommentsAndTrim(String sql) {
Preconditions.checkNotNull(sql);
final char SINGLE_QUOTE = '\'';
final char DOUBLE_QUOTE = '"';
final char BACKTICK_QUOTE = '`';
final char HYPHEN = '-';
final char DASH = '#';
final char SLASH = '/';
final char ASTERIKS = '*';
boolean isInQuoted = false;
boolean isInSingleLineComment = false;
boolean isInMultiLineComment = false;
char startQuote = 0;
boolean lastCharWasEscapeChar = false;
boolean isTripleQuoted = false;
StringBuilder res = new StringBuilder(sql.length());
int index = 0;
while (index < sql.length()) {
char c = sql.charAt(index);
if (isInQuoted) {
if ((c == '\n' || c == '\r') && !isTripleQuoted) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "SQL statement contains an unclosed literal: " + sql);
} else if (c == startQuote) {
if (lastCharWasEscapeChar) {
lastCharWasEscapeChar = false;
} else if (isTripleQuoted) {
if (sql.length() > index + 2
&& sql.charAt(index + 1) == startQuote
&& sql.charAt(index + 2) == startQuote) {
isInQuoted = false;
startQuote = 0;
isTripleQuoted = false;
res.append(c).append(c);
index += 2;
}
} else {
isInQuoted = false;
startQuote = 0;
}
} else if (c == '\\') {
lastCharWasEscapeChar = true;
} else {
lastCharWasEscapeChar = false;
}
res.append(c);
} else {
// We are not in a quoted string.
if (isInSingleLineComment) {
if (c == '\n') {
isInSingleLineComment = false;
// Include the line feed in the result.
res.append(c);
}
} else if (isInMultiLineComment) {
if (sql.length() > index + 1 && c == ASTERIKS && sql.charAt(index + 1) == SLASH) {
isInMultiLineComment = false;
index++;
}
} else {
if (c == DASH
|| (sql.length() > index + 1 && c == HYPHEN && sql.charAt(index + 1) == HYPHEN)) {
// This is a single line comment.
isInSingleLineComment = true;
} else if (sql.length() > index + 1 && c == SLASH && sql.charAt(index + 1) == ASTERIKS) {
isInMultiLineComment = true;
index++;
} else {
if (c == SINGLE_QUOTE || c == DOUBLE_QUOTE || c == BACKTICK_QUOTE) {
isInQuoted = true;
startQuote = c;
// Check whether it is a triple-quote.
if (sql.length() > index + 2
&& sql.charAt(index + 1) == startQuote
&& sql.charAt(index + 2) == startQuote) {
isTripleQuoted = true;
res.append(c).append(c);
index += 2;
}
}
res.append(c);
}
}
}
index++;
}
if (isInQuoted) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "SQL statement contains an unclosed literal: " + sql);
}
if (res.length() > 0 && res.charAt(res.length() - 1) == ';') {
res.deleteCharAt(res.length() - 1);
}
return res.toString().trim();
}
/** Removes any statement hints at the beginning of the statement. */
static String removeStatementHint(String sql) {
// Valid statement hints at the beginning of a SQL statement can only contain a fixed set of
// possible values. Although it is possible to add a @{FORCE_INDEX=...} as a statement hint, the
// only allowed value is _BASE_TABLE. This means that we can safely assume that the statement
// hint will not contain any special characters, for example a closing curly brace, and
// that we can keep the check simple by just searching for the first occurrence of a closing
// curly brace at the end of the statement hint.
int startStatementHintIndex = sql.indexOf('{');
int endStatementHintIndex = sql.indexOf('}');
if (startStatementHintIndex == -1 || startStatementHintIndex > endStatementHintIndex) {
// Looks like an invalid statement hint. Just ignore at this point and let the caller handle
// the invalid query.
return sql;
}
return removeCommentsAndTrim(sql.substring(endStatementHintIndex + 1));
}
}