0
# Command Line Interface
1
2
Interactive and non-interactive CLI for executing SQL statements with terminal support, result display, and command history. The CLI provides a rich interactive experience with auto-completion, syntax highlighting, and multiple result display formats.
3
4
## Capabilities
5
6
### CliClient Class
7
8
Core CLI client implementation handling both interactive and non-interactive SQL execution.
9
10
```java { .api }
11
public class CliClient implements AutoCloseable {
12
/**
13
* Create CLI client with terminal factory and session context
14
* @param terminalFactory Factory for creating terminal instances
15
* @param sessionId Session identifier for executor operations
16
* @param executor Executor instance for SQL operations
17
* @param historyFilePath Path to command history file
18
*/
19
public CliClient(Supplier<Terminal> terminalFactory, String sessionId, Executor executor, Path historyFilePath);
20
21
/**
22
* Create CLI client with input transformer for password masking
23
* @param terminalFactory Factory for creating terminal instances
24
* @param sessionId Session identifier for executor operations
25
* @param executor Executor instance for SQL operations
26
* @param historyFilePath Path to command history file
27
* @param inputTransformer Callback for transforming input (e.g., password masking)
28
*/
29
public CliClient(Supplier<Terminal> terminalFactory, String sessionId, Executor executor, Path historyFilePath, MaskingCallback inputTransformer);
30
}
31
```
32
33
### Interactive Mode Execution
34
35
Opens interactive SQL shell with readline support, auto-completion, and command history.
36
37
```java { .api }
38
/**
39
* Execute CLI in interactive mode with full terminal features
40
* Provides SQL auto-completion, command history, and result display
41
*/
42
public void executeInInteractiveMode();
43
```
44
45
**Usage Example:**
46
47
```java
48
import org.apache.flink.table.client.cli.CliClient;
49
import org.apache.flink.table.client.cli.TerminalUtils;
50
51
// Create CLI client and start interactive mode
52
try (CliClient cli = new CliClient(
53
TerminalUtils::createDefaultTerminal,
54
sessionId,
55
executor,
56
Paths.get(System.getProperty("user.home"), ".flink-sql-history")
57
)) {
58
cli.executeInInteractiveMode();
59
}
60
```
61
62
Interactive mode features:
63
- SQL auto-completion with table and function names
64
- Command history with up/down arrow navigation
65
- Multi-line SQL statement support
66
- Ctrl+C cancellation support
67
- Graceful shutdown with Ctrl+D
68
69
### Non-Interactive Mode Execution
70
71
Executes SQL content from files or strings without interactive features.
72
73
```java { .api }
74
/**
75
* Execute SQL content in non-interactive mode
76
* @param content SQL content to execute (file content or statement string)
77
*/
78
public void executeInNonInteractiveMode(String content);
79
```
80
81
**Usage Example:**
82
83
```java
84
// Execute SQL from file content
85
String sqlContent = Files.readString(Paths.get("queries.sql"));
86
cli.executeInNonInteractiveMode(sqlContent);
87
88
// Execute single statement
89
cli.executeInNonInteractiveMode("SELECT COUNT(*) FROM users");
90
```
91
92
Non-interactive mode characteristics:
93
- Executes all statements sequentially
94
- Stops execution on first error
95
- Uses tableau result display mode
96
- No user interaction required
97
98
### Initialization Script Execution
99
100
Executes initialization scripts with restricted operation support and silent output.
101
102
```java { .api }
103
/**
104
* Execute initialization script content
105
* @param content SQL initialization script content
106
* @return true if initialization succeeded, false if any errors occurred
107
*/
108
public boolean executeInitialization(String content);
109
```
110
111
**Usage Example:**
112
113
```java
114
// Execute initialization script
115
String initScript = """
116
SET 'sql-client.execution.result-mode' = 'tableau';
117
CREATE CATALOG my_catalog WITH (...);
118
USE CATALOG my_catalog;
119
""";
120
121
boolean success = cli.executeInitialization(initScript);
122
if (!success) {
123
System.err.println("Initialization failed - check logs for details");
124
}
125
```
126
127
Initialization mode restrictions:
128
- Only allows: SET, RESET, CREATE, DROP, USE, ALTER, LOAD MODULE, UNLOAD MODULE, ADD JAR, REMOVE JAR
129
- Other operations throw SqlExecutionException
130
- Output is captured and logged rather than displayed
131
132
### Terminal Management
133
134
Access and control terminal properties and display.
135
136
```java { .api }
137
/**
138
* Get the current terminal instance
139
* @return Terminal instance for advanced terminal operations
140
*/
141
public Terminal getTerminal();
142
143
/**
144
* Clear terminal screen (platform-aware)
145
*/
146
public void clearTerminal();
147
148
/**
149
* Check if terminal supports advanced features
150
* @return true if terminal is plain/simple, false if it supports advanced features
151
*/
152
public boolean isPlainTerminal();
153
154
/**
155
* Get terminal width
156
* @return Terminal width in characters
157
*/
158
public int getWidth();
159
160
/**
161
* Get terminal height
162
* @return Terminal height in lines
163
*/
164
public int getHeight();
165
```
166
167
**Usage Example:**
168
169
```java
170
// Check terminal capabilities
171
if (cli.isPlainTerminal()) {
172
System.out.println("Using simple terminal mode");
173
} else {
174
System.out.printf("Terminal size: %dx%d%n", cli.getWidth(), cli.getHeight());
175
}
176
177
// Clear screen
178
cli.clearTerminal();
179
```
180
181
### Session and Executor Access
182
183
Access underlying session and executor for advanced operations.
184
185
```java { .api }
186
/**
187
* Get session identifier
188
* @return Current session ID
189
*/
190
public String getSessionId();
191
192
/**
193
* Get executor instance
194
* @return Executor instance for direct SQL operations
195
*/
196
public Executor getExecutor();
197
```
198
199
## CliOptions Class
200
201
Container for parsed command line arguments and configuration.
202
203
```java { .api }
204
public class CliOptions {
205
/**
206
* Whether help should be displayed instead of starting client
207
* @return true if help flag was provided
208
*/
209
public boolean isPrintHelp();
210
211
/**
212
* Session identifier for this client instance
213
* @return session ID or null if not specified
214
*/
215
public String getSessionId();
216
217
/**
218
* Initialization script file URL
219
* @return URL to initialization script or null
220
*/
221
public URL getInitFile();
222
223
/**
224
* SQL script file URL for non-interactive execution
225
* @return URL to SQL script file or null
226
*/
227
public URL getSqlFile();
228
229
/**
230
* JAR dependency URLs to add to classpath
231
* @return List of JAR URLs
232
*/
233
public List<URL> getJars();
234
235
/**
236
* Library directory URLs for dependency resolution
237
* @return List of library directory URLs
238
*/
239
public List<URL> getLibraryDirs();
240
241
/**
242
* Single SQL statement for execution (deprecated, use getSqlFile)
243
* @return SQL statement string or null
244
*/
245
public String getUpdateStatement();
246
247
/**
248
* Command history file path
249
* @return Path to history file or null for default
250
*/
251
public String getHistoryFilePath();
252
253
/**
254
* Python-specific configuration
255
* @return Configuration for Python integration
256
*/
257
public Configuration getPythonConfiguration();
258
}
259
```
260
261
## CliOptionsParser Class
262
263
Command line argument parser with static utilities for different modes.
264
265
```java { .api }
266
public class CliOptionsParser {
267
/**
268
* Parse command line arguments for embedded mode
269
* @param args Command line arguments
270
* @return Parsed CliOptions instance
271
*/
272
public static CliOptions parseEmbeddedModeClient(String[] args);
273
274
/**
275
* Parse command line arguments for gateway mode client
276
* @param args Command line arguments
277
* @return Parsed CliOptions instance
278
*/
279
public static CliOptions parseGatewayModeClient(String[] args);
280
281
/**
282
* Print general client help information
283
*/
284
public static void printHelpClient();
285
286
/**
287
* Print embedded mode specific help
288
*/
289
public static void printHelpEmbeddedModeClient();
290
291
/**
292
* Validate file path accessibility
293
* @param filePath Path to validate
294
* @throws IllegalArgumentException if path is invalid
295
*/
296
public static void checkFilePath(String filePath);
297
}
298
```
299
300
**Usage Example:**
301
302
```java
303
// Parse embedded mode options
304
try {
305
CliOptions options = CliOptionsParser.parseEmbeddedModeClient(args);
306
if (options.isPrintHelp()) {
307
CliOptionsParser.printHelpEmbeddedModeClient();
308
return;
309
}
310
// Use options to configure client
311
} catch (Exception e) {
312
System.err.println("Invalid command line options: " + e.getMessage());
313
CliOptionsParser.printHelpEmbeddedModeClient();
314
}
315
```
316
317
## Command Line Options
318
319
### Common Options
320
321
- `--help, -h`: Display help information
322
- `--session <sessionId>`: Specify session identifier
323
- `--init <file>`: Initialization script file
324
- `--file, -f <file>`: SQL script file for non-interactive execution
325
- `--jar <jar>`: JAR files to add to classpath (can be repeated)
326
- `--library <dir>`: Library directories for dependencies (can be repeated)
327
- `--history <file>`: Command history file path
328
329
### Deprecated Options
330
331
- `--update, -u <statement>`: Single SQL statement (use --file instead)
332
333
## Error Handling
334
335
The CLI handles various error conditions gracefully:
336
337
- **SQL parsing errors**: Display error with line/column information
338
- **Execution errors**: Show detailed error messages with optional stack traces
339
- **Terminal errors**: Fallback to simple terminal mode
340
- **File access errors**: Validate file permissions and existence
341
- **Cancellation**: Handle Ctrl+C and Ctrl+D gracefully
342
343
**Example Error Display:**
344
345
```
346
Flink SQL> SELECT * FROM non_existent_table;
347
[ERROR] Could not execute SQL statement. Reason:
348
org.apache.flink.table.api.TableException: Table 'non_existent_table' not found
349
350
Flink SQL>
351
```
352
353
## Result Display Integration
354
355
The CLI integrates with result display components:
356
357
- **CliTableauResultView**: For tableau-format results
358
- **CliTableResultView**: For paginated table results
359
- **CliChangelogResultView**: For streaming changelog results
360
361
Result display is automatically selected based on query type and configuration settings.