use of io.crate.action.sql.Session in project crate by crate.
the class SqlHttpHandler method channelRead0.
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) {
if (request.uri().startsWith("/_sql")) {
Session session = ensureSession(request);
Map<String, List<String>> parameters = new QueryStringDecoder(request.uri()).parameters();
ByteBuf content = request.content();
handleSQLRequest(session, content, paramContainFlag(parameters, "types")).whenComplete((result, t) -> {
try {
sendResponse(session, ctx, request, parameters, result, t);
} catch (Throwable ex) {
LOGGER.error("Error sending response", ex);
throw ex;
} finally {
request.release();
}
});
} else {
ctx.fireChannelRead(request);
}
}
use of io.crate.action.sql.Session in project crate by crate.
the class SqlHttpHandler method ensureSession.
@VisibleForTesting
Session ensureSession(FullHttpRequest request) {
String defaultSchema = request.headers().get(REQUEST_HEADER_SCHEMA);
User authenticatedUser = userFromAuthHeader(request.headers().get(HttpHeaderNames.AUTHORIZATION));
Session session = this.session;
if (session == null) {
session = sqlOperations.createSession(defaultSchema, authenticatedUser);
} else if (session.sessionContext().authenticatedUser().equals(authenticatedUser) == false) {
session.close();
session = sqlOperations.createSession(defaultSchema, authenticatedUser);
}
this.session = session;
return session;
}
use of io.crate.action.sql.Session in project crate by crate.
the class SQLTransportExecutor method executeTransportOrJdbc.
private SQLResponse executeTransportOrJdbc(TestExecutionConfig config, String stmt, @Nullable Object[] args, TimeValue timeout) {
String pgUrl = clientProvider.pgUrl();
Random random = RandomizedContext.current().getRandom();
List<String> sessionList = new ArrayList<>();
sessionList.add("set search_path to " + StreamSupport.stream(searchPath.spliterator(), false).filter(s -> !s.equals(PgCatalogSchemaInfo.NAME)).collect(Collectors.joining(", ")));
if (!config.isHashJoinEnabled()) {
sessionList.add("set enable_hashjoin=false");
LOGGER.trace("Executing with enable_hashjoin=false: {}", stmt);
}
if (pgUrl != null && config.isJdbcEnabled()) {
LOGGER.trace("Executing with pgJDBC: {}", stmt);
return executeWithPg(stmt, args, pgUrl, random, sessionList);
}
try {
try (Session session = newSession()) {
sessionList.forEach((setting) -> exec(setting, session));
return FutureUtils.get(execute(stmt, args, session), timeout.millis(), TimeUnit.MILLISECONDS);
}
} catch (RuntimeException e) {
var cause = e.getCause();
// to figure out the root cause of an error, so we prefer the cause here
if (e.getClass() == RuntimeException.class && cause != null) {
Exceptions.rethrowUnchecked(cause);
}
throw e;
}
}
use of io.crate.action.sql.Session in project crate by crate.
the class SQLTransportExecutor method execute.
private void execute(String stmt, @Nullable Object[][] bulkArgs, final ActionListener<long[]> listener) {
Session session = newSession();
try {
session.parse(UNNAMED, stmt, Collections.emptyList());
if (bulkArgs == null) {
bulkArgs = new Object[0][];
}
final long[] rowCounts = new long[bulkArgs.length];
if (rowCounts.length == 0) {
session.bind(UNNAMED, UNNAMED, Collections.emptyList(), null);
session.execute(UNNAMED, 0, new BaseResultReceiver());
} else {
for (int i = 0; i < bulkArgs.length; i++) {
session.bind(UNNAMED, UNNAMED, Arrays.asList(bulkArgs[i]), null);
ResultReceiver<?> resultReceiver = new BulkRowCountReceiver(rowCounts, i);
session.execute(UNNAMED, 0, resultReceiver);
}
}
List<Symbol> outputColumns = session.describe('P', UNNAMED).getFields();
if (outputColumns != null) {
throw new UnsupportedOperationException("Bulk operations for statements that return result sets is not supported");
}
session.sync().whenComplete((Object result, Throwable t) -> {
if (t == null) {
listener.onResponse(rowCounts);
} else {
listener.onFailure(Exceptions.toRuntimeException(t));
}
session.close();
});
} catch (Throwable t) {
session.close();
listener.onFailure(Exceptions.toRuntimeException(t));
}
}
use of io.crate.action.sql.Session in project crate by crate.
the class PostgresWireProtocolTest method test_channel_is_flushed_after_receiving_flush_request.
@Test
public void test_channel_is_flushed_after_receiving_flush_request() throws Exception {
SQLOperations sqlOperations = mock(SQLOperations.class);
Session session = mock(Session.class);
when(sqlOperations.createSession(any(String.class), any(User.class))).thenReturn(session);
PostgresWireProtocol ctx = new PostgresWireProtocol(sqlOperations, sessionContext -> AccessControl.DISABLED, new AlwaysOKAuthentication(userName -> User.CRATE_USER), null);
AtomicBoolean flushed = new AtomicBoolean(false);
channel = new EmbeddedChannel(ctx.decoder, ctx.handler) {
@Override
public Channel flush() {
flushed.set(true);
return super.flush();
}
};
ByteBuf buffer = Unpooled.buffer();
ClientMessages.sendStartupMessage(buffer, "doc");
ClientMessages.sendParseMessage(buffer, "", "select ?", new int[0]);
ClientMessages.sendFlush(buffer);
channel.writeInbound(buffer);
channel.releaseInbound();
assertThat(flushed.get(), is(true));
}
Aggregations