Java Code Examples for org.apache.flink.table.client.gateway.SqlExecutionException

The following examples show how to use org.apache.flink.table.client.gateway.SqlExecutionException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: flink   Source File: CliClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUseNonExistingDB() throws Exception {
	Executor executor = mock(Executor.class);
	doThrow(new SqlExecutionException("mocked exception")).when(executor).useDatabase(any(), any());
	InputStream inputStream = new ByteArrayInputStream("use db;\n".getBytes());
	// don't care about the output
	OutputStream outputStream = new OutputStream() {
		@Override
		public void write(int b) throws IOException {
		}
	};
	CliClient cliClient = null;
	try (Terminal terminal = new DumbTerminal(inputStream, outputStream)) {
		cliClient = new CliClient(terminal, new SessionContext("test-session", new Environment()), executor);
		cliClient.open();
		verify(executor).useDatabase(any(), any());
	} finally {
		if (cliClient != null) {
			cliClient.close();
		}
	}
}
 
Example 2
Source Project: flink   Source File: LocalExecutor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Applies the given update statement to the given table environment with query configuration.
 */
private <C> void applyUpdate(ExecutionContext<C> context, TableEnvironment tableEnv, QueryConfig queryConfig, String updateStatement) {
	// parse and validate statement
	try {
		context.wrapClassLoader(() -> {
			if (tableEnv instanceof StreamTableEnvironment) {
				((StreamTableEnvironment) tableEnv).sqlUpdate(updateStatement, (StreamQueryConfig) queryConfig);
			} else {
				tableEnv.sqlUpdate(updateStatement);
			}
			return null;
		});
	} catch (Throwable t) {
		// catch everything such that the statement does not crash the executor
		throw new SqlExecutionException("Invalid SQL update statement.", t);
	}
}
 
Example 3
Source Project: flink   Source File: CliClient.java    License: Apache License 2.0 6 votes vote down vote up
private void callCreateView(SqlCommandCall cmdCall) {
	final String name = cmdCall.operands[0];
	final String query = cmdCall.operands[1];

	final ViewEntry previousView = context.getViews().get(name);
	if (previousView != null) {
		printExecutionError(CliStrings.MESSAGE_VIEW_ALREADY_EXISTS);
		return;
	}

	try {
		// perform and validate change
		context.addView(ViewEntry.create(name, query));
		executor.validateSession(context);
		printInfo(CliStrings.MESSAGE_VIEW_CREATED);
	} catch (SqlExecutionException e) {
		// rollback change
		context.removeView(name);
		printExecutionException(e);
	}
}
 
Example 4
Source Project: Flink-CEPplus   Source File: CliView.java    License: Apache License 2.0 6 votes vote down vote up
private void handleSignal(Signal signal) {
	synchronized (this) {
		switch (signal) {
			case INT:
				close(new SqlExecutionException("Forced interrupt."));
				break;
			case QUIT:
				close(new SqlExecutionException("Forced cancellation."));
				break;
			case WINCH:
				updateSize();
				if (isRunning) {
					display();
				}
				break;
		}
	}
}
 
Example 5
Source Project: flink   Source File: LocalExecutor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void useCatalog(SessionContext session, String catalogName) throws SqlExecutionException {
	final ExecutionContext<?> context = getOrCreateExecutionContext(session);
	final TableEnvironment tableEnv = context
		.createEnvironmentInstance()
		.getTableEnvironment();

	context.wrapClassLoader(() -> {
		// Rely on TableEnvironment/CatalogManager to validate input
		try {
			tableEnv.useCatalog(catalogName);
		} catch (CatalogException e) {
			throw new SqlExecutionException("Failed to switch to catalog " + catalogName, e);
		}
		session.setCurrentCatalog(catalogName);
		session.setCurrentDatabase(tableEnv.getCurrentDatabase());
		return null;
	});
}
 
Example 6
Source Project: Flink-CEPplus   Source File: CliClient.java    License: Apache License 2.0 6 votes vote down vote up
private void callCreateView(SqlCommandCall cmdCall) {
	final String name = cmdCall.operands[0];
	final String query = cmdCall.operands[1];

	final ViewEntry previousView = context.getViews().get(name);
	if (previousView != null) {
		printExecutionError(CliStrings.MESSAGE_VIEW_ALREADY_EXISTS);
		return;
	}

	try {
		// perform and validate change
		context.addView(ViewEntry.create(name, query));
		executor.validateSession(context);
		printInfo(CliStrings.MESSAGE_VIEW_CREATED);
	} catch (SqlExecutionException e) {
		// rollback change
		context.removeView(name);
		printExecutionException(e);
	}
}
 
Example 7
Source Project: Flink-CEPplus   Source File: SqlCompleter.java    License: Apache License 2.0 6 votes vote down vote up
public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
	String statement = line.line();

	// remove ';' at the end
	if (statement.endsWith(";")) {
		statement = statement.substring(0, statement.length() - 1);
	}

	// handle SQL client specific commands
	final String statementNormalized = statement.toUpperCase().trim();
	for (String commandHint : COMMAND_HINTS) {
		if (commandHint.startsWith(statementNormalized) && line.cursor() < commandHint.length()) {
			candidates.add(createCandidate(commandHint));
		}
	}

	// fallback to Table API hinting
	try {
		executor.completeStatement(context, statement, line.cursor())
			.forEach(hint -> candidates.add(createCandidate(hint)));
	} catch (SqlExecutionException e) {
		LOG.debug("Could not complete statement at " + line.cursor() + ":" + statement, e);
	}
}
 
Example 8
Source Project: flink   Source File: SqlCompleter.java    License: Apache License 2.0 6 votes vote down vote up
public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
	String statement = line.line();

	// remove ';' at the end
	if (statement.endsWith(";")) {
		statement = statement.substring(0, statement.length() - 1);
	}

	// handle SQL client specific commands
	final String statementNormalized = statement.toUpperCase().trim();
	for (String commandHint : COMMAND_HINTS) {
		if (commandHint.startsWith(statementNormalized) && line.cursor() < commandHint.length()) {
			candidates.add(createCandidate(commandHint));
		}
	}

	// fallback to Table API hinting
	try {
		executor.completeStatement(context, statement, line.cursor())
			.forEach(hint -> candidates.add(createCandidate(hint)));
	} catch (SqlExecutionException e) {
		LOG.debug("Could not complete statement at " + line.cursor() + ":" + statement, e);
	}
}
 
Example 9
Source Project: Flink-CEPplus   Source File: SqlClient.java    License: Apache License 2.0 5 votes vote down vote up
private static void validateEnvironment(SessionContext context, Executor executor) {
	System.out.print("Validating current environment...");
	try {
		executor.validateSession(context);
		System.out.println("done.");
	} catch (SqlExecutionException e) {
		throw new SqlClientException(
			"The configured environment is invalid. Please check your environment files again.", e);
	}
}
 
Example 10
Source Project: Flink-CEPplus   Source File: ExecutionContext.java    License: Apache License 2.0 5 votes vote down vote up
public EnvironmentInstance createEnvironmentInstance() {
	try {
		return new EnvironmentInstance();
	} catch (Throwable t) {
		// catch everything such that a wrong environment does not affect invocations
		throw new SqlExecutionException("Could not create environment instance.", t);
	}
}
 
Example 11
Source Project: Flink-CEPplus   Source File: ExecutionContext.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> CustomCommandLine<T> findActiveCommandLine(List<CustomCommandLine<?>> availableCommandLines, CommandLine commandLine) {
	for (CustomCommandLine<?> cli : availableCommandLines) {
		if (cli.isActive(commandLine)) {
			return (CustomCommandLine<T>) cli;
		}
	}
	throw new SqlExecutionException("Could not find a matching deployment.");
}
 
Example 12
Source Project: Flink-CEPplus   Source File: ExecutionContext.java    License: Apache License 2.0 5 votes vote down vote up
private static ClusterSpecification createClusterSpecification(CustomCommandLine<?> activeCommandLine, CommandLine commandLine) {
	try {
		return activeCommandLine.getClusterSpecification(commandLine);
	} catch (FlinkException e) {
		throw new SqlExecutionException("Could not create cluster specification for the given deployment.", e);
	}
}
 
Example 13
Source Project: Flink-CEPplus   Source File: ExecutionContext.java    License: Apache License 2.0 5 votes vote down vote up
private EnvironmentInstance() {
	// create environments
	if (mergedEnv.getExecution().isStreamingExecution()) {
		streamExecEnv = createStreamExecutionEnvironment();
		execEnv = null;
		tableEnv = StreamTableEnvironment.create(streamExecEnv);
	} else if (mergedEnv.getExecution().isBatchExecution()) {
		streamExecEnv = null;
		execEnv = createExecutionEnvironment();
		tableEnv = BatchTableEnvironment.create(execEnv);
	} else {
		throw new SqlExecutionException("Unsupported execution type specified.");
	}

	// create query config
	queryConfig = createQueryConfig();

	// register table sources
	tableSources.forEach(tableEnv::registerTableSource);

	// register table sinks
	tableSinks.forEach(tableEnv::registerTableSink);

	// register user-defined functions
	registerFunctions();

	// register views and temporal tables in specified order
	mergedEnv.getTables().forEach((name, entry) -> {
		// if registering a view fails at this point,
		// it means that it accesses tables that are not available anymore
		if (entry instanceof ViewEntry) {
			final ViewEntry viewEntry = (ViewEntry) entry;
			registerView(viewEntry);
		} else if (entry instanceof TemporalTableEntry) {
			final TemporalTableEntry temporalTableEntry = (TemporalTableEntry) entry;
			registerTemporalTable(temporalTableEntry);
		}
	});
}
 
Example 14
Source Project: Flink-CEPplus   Source File: ExecutionContext.java    License: Apache License 2.0 5 votes vote down vote up
private void registerFunctions() {
	if (tableEnv instanceof StreamTableEnvironment) {
		StreamTableEnvironment streamTableEnvironment = (StreamTableEnvironment) tableEnv;
		functions.forEach((k, v) -> {
			if (v instanceof ScalarFunction) {
				streamTableEnvironment.registerFunction(k, (ScalarFunction) v);
			} else if (v instanceof AggregateFunction) {
				streamTableEnvironment.registerFunction(k, (AggregateFunction<?, ?>) v);
			} else if (v instanceof TableFunction) {
				streamTableEnvironment.registerFunction(k, (TableFunction<?>) v);
			} else {
				throw new SqlExecutionException("Unsupported function type: " + v.getClass().getName());
			}
		});
	} else {
		BatchTableEnvironment batchTableEnvironment = (BatchTableEnvironment) tableEnv;
		functions.forEach((k, v) -> {
			if (v instanceof ScalarFunction) {
				batchTableEnvironment.registerFunction(k, (ScalarFunction) v);
			} else if (v instanceof AggregateFunction) {
				batchTableEnvironment.registerFunction(k, (AggregateFunction<?, ?>) v);
			} else if (v instanceof TableFunction) {
				batchTableEnvironment.registerFunction(k, (TableFunction<?>) v);
			} else {
				throw new SqlExecutionException("Unsupported function type: " + v.getClass().getName());
			}
		});
	}
}
 
Example 15
Source Project: flink   Source File: CliTableResultView.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void refresh() {
	// take snapshot
	TypedResult<Integer> result;
	try {
		result = client.getExecutor().snapshotResult(client.getContext(), resultDescriptor.getResultId(), getVisibleMainHeight());
	} catch (SqlExecutionException e) {
		close(e);
		return;
	}

	// stop retrieval if job is done
	if (result.getType() == TypedResult.ResultType.EOS) {
		stopRetrieval(false);
	}
	// update page
	else if (result.getType() == TypedResult.ResultType.PAYLOAD) {
		int newPageCount = result.getPayload();
		pageCount = newPageCount;
		if (page > newPageCount) {
			page = LAST_PAGE;
		}
		updatePage();
	}

	lastRetrieval = LocalTime.now();

	// reset view
	resetAllParts();
}
 
Example 16
Source Project: flink   Source File: CliClient.java    License: Apache License 2.0 5 votes vote down vote up
private void callShowDatabases() {
	final List<String> dbs;
	try {
		dbs = executor.listDatabases(context);
	} catch (SqlExecutionException e) {
		printExecutionException(e);
		return;
	}
	if (dbs.isEmpty()) {
		terminal.writer().println(CliStrings.messageInfo(CliStrings.MESSAGE_EMPTY).toAnsi());
	} else {
		dbs.forEach((v) -> terminal.writer().println(v));
	}
	terminal.flush();
}
 
Example 17
Source Project: Flink-CEPplus   Source File: LocalExecutor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<String> listTables(SessionContext session) throws SqlExecutionException {
	final TableEnvironment tableEnv = getOrCreateExecutionContext(session)
		.createEnvironmentInstance()
		.getTableEnvironment();
	return Arrays.asList(tableEnv.listTables());
}
 
Example 18
Source Project: Flink-CEPplus   Source File: LocalExecutor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<String> listUserDefinedFunctions(SessionContext session) throws SqlExecutionException {
	final TableEnvironment tableEnv = getOrCreateExecutionContext(session)
		.createEnvironmentInstance()
		.getTableEnvironment();
	return Arrays.asList(tableEnv.listUserDefinedFunctions());
}
 
Example 19
Source Project: flink   Source File: LocalExecutor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public TableSchema getTableSchema(SessionContext session, String name) throws SqlExecutionException {
	final ExecutionContext<?> context = getOrCreateExecutionContext(session);
	final TableEnvironment tableEnv = context
		.createEnvironmentInstance()
		.getTableEnvironment();
	try {
		return context.wrapClassLoader(() -> tableEnv.scan(name).getSchema());
	} catch (Throwable t) {
		// catch everything such that the query does not crash the executor
		throw new SqlExecutionException("No table with this name could be found.", t);
	}
}
 
Example 20
Source Project: flink   Source File: CliClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ProgramTargetDescriptor executeUpdate(SessionContext session, String statement) throws SqlExecutionException {
	receivedContext = session;
	receivedStatement = statement;
	if (failExecution) {
		throw new SqlExecutionException("Fail execution.");
	}
	return new ProgramTargetDescriptor("testClusterId", "testJobId", "http://testcluster:1234");
}
 
Example 21
Source Project: Flink-CEPplus   Source File: LocalExecutor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public TypedResult<Integer> snapshotResult(SessionContext session, String resultId, int pageSize) throws SqlExecutionException {
	final DynamicResult<?> result = resultStore.getResult(resultId);
	if (result == null) {
		throw new SqlExecutionException("Could not find a result with result identifier '" + resultId + "'.");
	}
	if (!result.isMaterialized()) {
		throw new SqlExecutionException("Invalid result retrieval mode.");
	}
	return ((MaterializedResult<?>) result).snapshot(pageSize);
}
 
Example 22
Source Project: Flink-CEPplus   Source File: LocalExecutor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a table using the given query in the given table environment.
 */
private Table createTable(TableEnvironment tableEnv, String selectQuery) {
	// parse and validate query
	try {
		return tableEnv.sqlQuery(selectQuery);
	} catch (Throwable t) {
		// catch everything such that the query does not crash the executor
		throw new SqlExecutionException("Invalid SQL statement.", t);
	}
}
 
Example 23
Source Project: Flink-CEPplus   Source File: LocalExecutor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Applies the given update statement to the given table environment with query configuration.
 */
private <C> void applyUpdate(ExecutionContext<C> context, TableEnvironment tableEnv, QueryConfig queryConfig, String updateStatement) {
	// parse and validate statement
	try {
		// update statement requires an optimization step that might reference UDFs during code compilation
		context.wrapClassLoader(() -> {
			tableEnv.sqlUpdate(updateStatement, queryConfig);
			return null;
		});
	} catch (Throwable t) {
		// catch everything such that the statement does not crash the executor
		throw new SqlExecutionException("Invalid SQL update statement.", t);
	}
}
 
Example 24
Source Project: flink   Source File: CliClient.java    License: Apache License 2.0 5 votes vote down vote up
private void callSet(SqlCommandCall cmdCall) {
	// show all properties
	if (cmdCall.operands.length == 0) {
		final Map<String, String> properties;
		try {
			properties = executor.getSessionProperties(context);
		} catch (SqlExecutionException e) {
			printExecutionException(e);
			return;
		}
		if (properties.isEmpty()) {
			terminal.writer().println(CliStrings.messageInfo(CliStrings.MESSAGE_EMPTY).toAnsi());
		} else {
			properties
				.entrySet()
				.stream()
				.map((e) -> e.getKey() + "=" + e.getValue())
				.sorted()
				.forEach((p) -> terminal.writer().println(p));
		}
	}
	// set a property
	else {
		context.setSessionProperty(cmdCall.operands[0], cmdCall.operands[1]);
		terminal.writer().println(CliStrings.messageInfo(CliStrings.MESSAGE_SET).toAnsi());
	}
	terminal.flush();
}
 
Example 25
@Override
public TypedResult<Integer> snapshot(int pageSize) {
	if (pageSize < 1) {
		throw new SqlExecutionException("Page size must be greater than 0.");
	}

	synchronized (resultLock) {
		// retrieval thread is dead and there are no results anymore
		// or program failed
		if ((!isRetrieving() && isLastSnapshot) || executionException != null) {
			return handleMissingResult();
		}
		// this snapshot is the last result that can be delivered
		else if (!isRetrieving()) {
			isLastSnapshot = true;
		}

		this.pageSize = pageSize;
		snapshot.clear();
		for (int i = validRowPosition; i < materializedTable.size(); i++) {
			snapshot.add(materializedTable.get(i));
		}

		// at least one page
		pageCount = Math.max(1, (int) Math.ceil(((double) snapshot.size() / pageSize)));

		return TypedResult.payload(pageCount);
	}
}
 
Example 26
@Override
public List<Row> retrievePage(int page) {
	synchronized (resultLock) {
		if (page <= 0 || page > pageCount) {
			throw new SqlExecutionException("Invalid page '" + page + "'.");
		}

		return snapshot.subList(pageSize * (page - 1), Math.min(snapshot.size(), pageSize * page));
	}
}
 
Example 27
@Override
public List<Row> retrievePage(int page) {
	synchronized (resultLock) {
		if (page <= 0 || page > pageCount) {
			throw new SqlExecutionException("Invalid page '" + page + "'.");
		}
		return resultTable.subList(pageSize * (page - 1), Math.min(resultTable.size(), page * pageSize));
	}
}
 
Example 28
Source Project: Flink-CEPplus   Source File: CollectStreamResult.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
	try {
		deployer.run();
	} catch (SqlExecutionException e) {
		executionException = e;
	}
}
 
Example 29
Source Project: Flink-CEPplus   Source File: CliClient.java    License: Apache License 2.0 5 votes vote down vote up
private void callSet(SqlCommandCall cmdCall) {
	// show all properties
	if (cmdCall.operands.length == 0) {
		final Map<String, String> properties;
		try {
			properties = executor.getSessionProperties(context);
		} catch (SqlExecutionException e) {
			printExecutionException(e);
			return;
		}
		if (properties.isEmpty()) {
			terminal.writer().println(CliStrings.messageInfo(CliStrings.MESSAGE_EMPTY).toAnsi());
		} else {
			properties
				.entrySet()
				.stream()
				.map((e) -> e.getKey() + "=" + e.getValue())
				.sorted()
				.forEach((p) -> terminal.writer().println(p));
		}
	}
	// set a property
	else {
		context.setSessionProperty(cmdCall.operands[0], cmdCall.operands[1]);
		terminal.writer().println(CliStrings.messageInfo(CliStrings.MESSAGE_SET).toAnsi());
	}
	terminal.flush();
}
 
Example 30
Source Project: Flink-CEPplus   Source File: CliClient.java    License: Apache License 2.0 5 votes vote down vote up
private void callShowTables() {
	final List<String> tables;
	try {
		tables = executor.listTables(context);
	} catch (SqlExecutionException e) {
		printExecutionException(e);
		return;
	}
	if (tables.isEmpty()) {
		terminal.writer().println(CliStrings.messageInfo(CliStrings.MESSAGE_EMPTY).toAnsi());
	} else {
		tables.forEach((v) -> terminal.writer().println(v));
	}
	terminal.flush();
}