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
package edu.caltech.nanodb.client;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import edu.caltech.nanodb.server.CommandResult;
import org.antlr.v4.runtime.misc.ParseCancellationException;
/**
* This abstract class implements the basic functionality necessary for
* providing an interactive SQL client.
*/
public abstract class InteractiveClient {
private static Logger logger = LogManager.getLogger(InteractiveClient.class);
/** A string constant specifying the "first-line" command-prompt. */
private static final String CMDPROMPT_FIRST = "CMD> ";
/** A string constant specifying the "subsequent-lines" command-prompt. */
private static final String CMDPROMPT_NEXT = " > ";
/** The buffer that accumulates each command's text. */
private StringBuilder enteredText;
/** A flag that records if we are exiting the interactive client. */
private boolean exiting;
/**
* Start up the interactive client. The specific way the client
* interacts with the server dictates how this startup mechanism
* will work.
*
* @throws Exception if any error occurs during startup
*/
public abstract void startup() throws Exception;
/**
* This is the interactive mainloop that handles input from the standard
* input stream of the program.
*/
protected void mainloop() {
// We don't use the console directly, since we can't read/write it
// if someone redirects a file onto the client's input-stream.
boolean hasConsole = (System.console() != null);
if (hasConsole) {
System.out.println(
"Welcome to NanoDB. Exit with EXIT or QUIT command.\n");
}
exiting = false;
BufferedReader bufReader =
new BufferedReader(new InputStreamReader(System.in));
while (!exiting) {
enteredText = new StringBuilder();
boolean firstLine = true;
while (true) {
try {
if (hasConsole) {
if (firstLine) {
System.out.print(CMDPROMPT_FIRST);
System.out.flush();
firstLine = false;
}
else {
System.out.print(CMDPROMPT_NEXT);
System.out.flush();
}
}
String line = bufReader.readLine();
if (line == null) {
// Hit EOF.
exiting = true;
break;
}
enteredText.append(line).append('\n');
processEnteredText();
if (exiting)
break;
if (enteredText.length() == 0)
firstLine = true;
}
catch (Throwable e) {
System.out.println("Unexpected error: " + e.getClass() +
": " + e.getMessage());
logger.error("Unexpected error", e);
}
}
}
}
/**
* This helper function processes the contents of the {@link #enteredText}
* field, consuming comments, handling client "shell commands" and
* regular commands that are handled by the
* {@link edu.caltech.nanodb.server.NanoDBServer}. Whatever command or
* comment is processed will also be removed from the {@code enteredText}
* buffer by this function. Note also that multiple commands will be
* processed, if present.
*/
private void processEnteredText() {
// Process any commands in the entered text.
while (true) {
// Consume leading whitespace
while (enteredText.length() > 0 &&
Character.isWhitespace(enteredText.charAt(0))) {
enteredText.deleteCharAt(0);
}
// Consume comments
if (enteredText.length() >= 2) {
if ("--".equals(enteredText.substring(0, 2))) {
// Consume single-line comment
int endIdx = 2;
// Look for the end of the line.
while (endIdx < enteredText.length() &&
enteredText.charAt(endIdx) != '\n') {
endIdx++;
}
if (endIdx == enteredText.length()) {
// Didn't find newline character. Can't consume this
// comment yet.
return;
}
endIdx++; // Skip the newline character as well.
enteredText.delete(0, endIdx);
// Go back and try to find more commands.
continue;
}
else if ("/*".equals(enteredText.substring(0, 2))) {
// Consume block comment
int endIdx = 2;
// Look for the end of the block comment.
while (endIdx + 1 < enteredText.length() &&
(enteredText.charAt(endIdx) != '*' ||
enteredText.charAt(endIdx + 1) != '/')) {
endIdx++;
}
if (endIdx + 1 == enteredText.length()) {
// Didn't find end of block comment. Can't consume
// this comment yet.
return;
}
endIdx += 2; // Skip the end of the block-comment.
enteredText.delete(0, endIdx);
// Go back and try to find more commands.
continue;
}
}
// Look for shell commands
if (enteredText.length() > 0 && enteredText.charAt(0) == '\\') {
// This is a shell command, which continues to the
// end of the current line.
int endIdx = 0;
while (endIdx < enteredText.length() &&
enteredText.charAt(endIdx) != '\n') {
endIdx++;
}
endIdx++; // Include the newline character too
String shellCommand = enteredText.substring(0, endIdx);
enteredText.delete(0, endIdx);
handleShellCommand(shellCommand);
continue;
}
String command = getCommandString();
if (command == null)
break; // Couldn't find a complete command.
// if (logger.isDebugEnabled())
// logger.debug("Command string:\n" + command);
CommandResult result = handleCommand(command);
if (result.isExit()) {
exiting = true;
break;
}
else {
outputCommandResult(result);
}
}
}
/**
* This helper method goes through the {@link #enteredText} buffer, trying
* to identify the extent of the next command string. This is done using
* semicolons (that are not enclosed with single or double quotes). If a
* command is identified, it is removed from the internal buffer and
* returned. If no complete command is identified, {@code null} is
* returned.
*
* @return the first semicolon-terminated command in the internal data
* buffer, or {@code null} if the buffer contains no complete
* commands.
*/
private String getCommandString() {
int i = 0;
String command = null;
while (i < enteredText.length()) {
char ch = enteredText.charAt(i);
if (ch == ';') {
// Found the end of the command. Extract the string, and
// make sure the semicolon is also included.
command = enteredText.substring(0, i + 1);
enteredText.delete(0, i + 1);
// Consume any leading whitespace at the start of the entered
// text.
while (enteredText.length() > 0 &&
Character.isWhitespace(enteredText.charAt(0))) {
enteredText.deleteCharAt(0);
}
break;
}
else if (ch == '\'' || ch == '"') {
// Need to ignore all subsequent characters until we find
// the end of this quoted string.
i++;
while (i < enteredText.length() &&
enteredText.charAt(i) != ch) {
i++;
}
}
i++; // Go on to the next character.
}
return command;
}
/**
* Subclasses can implement this method to handle each command entered
* by the user. For example, a subclass may send the command over a
* socket to the server, wait for a response, then output the response
* to the console.
*
* @param command the command to handle.
*
* @return the command-result from executing the command
*/
public abstract CommandResult handleCommand(String command);
/**
* Handle "shell commands," which are commands that the client itself
* handles on behalf of the user. Shell commands start with a backslash
* "\" character.
*
* @param shellCommand the command to handle.
*/
private void handleShellCommand(String shellCommand) {
// Split the shell command into parts
String[] parts = shellCommand.split("\\s+", 2);
parts[0] = parts[0].toLowerCase();
if ("\\source".equals(parts[0])) {
// Source the requested SQL file.
StringBuilder oldText = enteredText;
enteredText = new StringBuilder();
String filename = parts[1].strip();
// Open the file with a try-with-resources so it will always be
// closed when we are done with the file.
try (BufferedReader reader =
new BufferedReader(new FileReader(filename))) {
while (true) {
String line = reader.readLine();
if (line == null)
break;
// Inject the line of the file into the buffer.
enteredText.append(line).append('\n');
// Attempt to process any operations in the entered text.
// If there are no complete commands, this will be a
// no-op. If there are multiple complete commands, they
// will all be processed.
processEnteredText();
}
}
catch (FileNotFoundException e) {
System.out.println("ERROR: Could not open file \"" +
filename + "\"");
}
catch (IOException e) {
System.out.println("ERROR: Could not read file \"" +
filename + "\": " + e.getMessage());
}
enteredText = oldText;
}
else if ("\\help".equals(parts[0])) {
// Show help information.
System.out.println("You can enter any NanoDB SQL command, or " +
"the following built-in commands.");
System.out.println("EXIT; or QUIT; will exit the NanoDB client.");
System.out.println();
System.out.println("\\help");
System.out.println("\tDisplays this help information.");
System.out.println();
System.out.println("\\source filename.sql");
System.out.println("\tLoads and executes the contents of \"filename.sql\".");
System.out.println();
}
else {
System.out.println("ERROR: Unrecognized shell command \"" +
parts[0] + "\"");
}
}
/**
* Outputs relevant information from the command-result object.
*
* @param result the command-result object to output
*/
private void outputCommandResult(CommandResult result) {
// TODO: Right now we only print out error information. In the
// future we will want to output other details. This
// functionality also needs to be integrated with the tuple-
// output code from the server. Need to think about this more.
if (result.failed()) {
Exception e = result.getFailure();
if (e instanceof ParseCancellationException) {
System.out.println("ERROR: Could not parse command");
}
else {
System.out.println("ERROR: " + e.getMessage());
}
}
}
/**
* Shut down the interactive client. The specific way the client
* interacts with the server dictates how this shutdown mechanism
* will work.
*
* @throws Exception if any error occurs during shutdown
*/
public abstract void shutdown() throws Exception;
}