Search in sources :

Example 1 with Session

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);
    }
}
Also used : QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) Collections.singletonList(java.util.Collections.singletonList) Collections.emptyList(java.util.Collections.emptyList) List(java.util.List) ByteBuf(io.netty.buffer.ByteBuf) Session(io.crate.action.sql.Session)

Example 2 with Session

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;
}
Also used : User(io.crate.user.User) Session(io.crate.action.sql.Session) VisibleForTesting(io.crate.common.annotations.VisibleForTesting)

Example 3 with 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;
    }
}
Also used : Arrays(java.util.Arrays) Connection(java.sql.Connection) PGTypes(io.crate.protocols.postgres.types.PGTypes) TimeoutException(java.util.concurrent.TimeoutException) Random(java.util.Random) JsonXContent(org.elasticsearch.common.xcontent.json.JsonXContent) Array(java.sql.Array) Unpooled(io.netty.buffer.Unpooled) Assert.assertThat(org.junit.Assert.assertThat) BaseResultReceiver(io.crate.action.sql.BaseResultReceiver) JtsSpatialContext(org.locationtech.spatial4j.context.jts.JtsSpatialContext) ResultSet(java.sql.ResultSet) Map(java.util.Map) AdapterActionFuture(org.elasticsearch.action.support.AdapterActionFuture) SQLOperations(io.crate.action.sql.SQLOperations) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) Priority(org.elasticsearch.common.Priority) RandomizedContext(com.carrotsearch.randomizedtesting.RandomizedContext) User(io.crate.user.User) Timestamp(java.sql.Timestamp) Collection(java.util.Collection) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) PreparedStatement(java.sql.PreparedStatement) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Objects(java.util.Objects) PointImpl(org.locationtech.spatial4j.shape.impl.PointImpl) List(java.util.List) Exceptions(io.crate.exceptions.Exceptions) Logger(org.apache.logging.log4j.Logger) Session(io.crate.action.sql.Session) Row(io.crate.data.Row) Symbol(io.crate.expression.symbol.Symbol) DataTypes(io.crate.types.DataTypes) Matchers.equalTo(org.hamcrest.Matchers.equalTo) TimeValue(io.crate.common.unit.TimeValue) PGpoint(org.postgresql.geometric.PGpoint) ResultSetMetaData(java.sql.ResultSetMetaData) Row1(io.crate.data.Row1) AccessControl(io.crate.auth.AccessControl) PGType(io.crate.protocols.postgres.types.PGType) CompletableFuture(java.util.concurrent.CompletableFuture) SearchPath(io.crate.metadata.SearchPath) PgCatalogSchemaInfo(io.crate.metadata.pgcatalog.PgCatalogSchemaInfo) ArrayList(java.util.ArrayList) PGobject(org.postgresql.util.PGobject) DeprecationHandler(org.elasticsearch.common.xcontent.DeprecationHandler) SQLException(java.sql.SQLException) ElasticsearchTimeoutException(org.elasticsearch.ElasticsearchTimeoutException) ByteBuf(io.netty.buffer.ByteBuf) Symbols(io.crate.expression.symbol.Symbols) StreamSupport(java.util.stream.StreamSupport) Requests(org.elasticsearch.client.Requests) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) FutureActionListener(io.crate.action.FutureActionListener) Properties(java.util.Properties) FutureUtils(org.elasticsearch.common.util.concurrent.FutureUtils) Client(org.elasticsearch.client.Client) Matchers(org.hamcrest.Matchers) DataType(io.crate.types.DataType) IOException(java.io.IOException) ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) PgOidVectorType(io.crate.protocols.postgres.types.PgOidVectorType) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) XContentParser(org.elasticsearch.common.xcontent.XContentParser) PGArray(io.crate.protocols.postgres.types.PGArray) ClusterHealthStatus(org.elasticsearch.cluster.health.ClusterHealthStatus) SQLExceptions(io.crate.exceptions.SQLExceptions) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) DriverManager(java.sql.DriverManager) ActionListener(org.elasticsearch.action.ActionListener) ResultReceiver(io.crate.action.sql.ResultReceiver) UNNAMED(io.crate.action.sql.Session.UNNAMED) Random(java.util.Random) ArrayList(java.util.ArrayList) Session(io.crate.action.sql.Session)

Example 4 with Session

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));
    }
}
Also used : Symbol(io.crate.expression.symbol.Symbol) BaseResultReceiver(io.crate.action.sql.BaseResultReceiver) PGpoint(org.postgresql.geometric.PGpoint) Session(io.crate.action.sql.Session)

Example 5 with Session

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));
}
Also used : Arrays(java.util.Arrays) SessionContext(io.crate.action.sql.SessionContext) PGTypes(io.crate.protocols.postgres.types.PGTypes) CrateDummyClusterServiceUnitTest(io.crate.test.integration.CrateDummyClusterServiceUnitTest) Provider(org.elasticsearch.common.inject.Provider) Unpooled(io.netty.buffer.Unpooled) DependencyCarrier(io.crate.planner.DependencyCarrier) Settings(org.elasticsearch.common.settings.Settings) After(org.junit.After) Map(java.util.Map) SecureString(org.elasticsearch.common.settings.SecureString) SQLOperations(io.crate.action.sql.SQLOperations) Matchers.isOneOf(org.hamcrest.Matchers.isOneOf) User(io.crate.user.User) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) Session(io.crate.action.sql.Session) Version(org.elasticsearch.Version) DataTypes(io.crate.types.DataTypes) UserManager(io.crate.user.UserManager) Matchers.is(org.hamcrest.Matchers.is) DescribeResult(io.crate.action.sql.DescribeResult) Mockito.any(org.mockito.Mockito.any) Mockito.mock(org.mockito.Mockito.mock) AccessControl(io.crate.auth.AccessControl) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) JobsLogs(io.crate.execution.engine.collect.stats.JobsLogs) ArrayList(java.util.ArrayList) ByteBuf(io.netty.buffer.ByteBuf) Authentication(io.crate.auth.Authentication) SQLExecutor(io.crate.testing.SQLExecutor) StubUserManager(io.crate.user.StubUserManager) Nullable(javax.annotation.Nullable) Before(org.junit.Before) ArgumentMatchers.anyChar(org.mockito.ArgumentMatchers.anyChar) JobKilledException(io.crate.exceptions.JobKilledException) AuthenticationMethod(io.crate.auth.AuthenticationMethod) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Test(org.junit.Test) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) ChannelHandler(io.netty.channel.ChannelHandler) AlwaysOKAuthentication(io.crate.auth.AlwaysOKAuthentication) Collections(java.util.Collections) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) AlwaysOKAuthentication(io.crate.auth.AlwaysOKAuthentication) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) User(io.crate.user.User) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) SecureString(org.elasticsearch.common.settings.SecureString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ByteBuf(io.netty.buffer.ByteBuf) SQLOperations(io.crate.action.sql.SQLOperations) Session(io.crate.action.sql.Session) CrateDummyClusterServiceUnitTest(io.crate.test.integration.CrateDummyClusterServiceUnitTest) Test(org.junit.Test)

Aggregations

Session (io.crate.action.sql.Session)19 SQLOperations (io.crate.action.sql.SQLOperations)12 Test (org.junit.Test)9 User (io.crate.user.User)8 JobsLogs (io.crate.execution.engine.collect.stats.JobsLogs)7 CrateDummyClusterServiceUnitTest (io.crate.test.integration.CrateDummyClusterServiceUnitTest)7 SQLExecutor (io.crate.testing.SQLExecutor)6 ByteBuf (io.netty.buffer.ByteBuf)6 ArrayList (java.util.ArrayList)6 List (java.util.List)6 SessionContext (io.crate.action.sql.SessionContext)5 AccessControl (io.crate.auth.AccessControl)5 DependencyCarrier (io.crate.planner.DependencyCarrier)5 PGTypes (io.crate.protocols.postgres.types.PGTypes)5 DataTypes (io.crate.types.DataTypes)5 StubUserManager (io.crate.user.StubUserManager)5 Unpooled (io.netty.buffer.Unpooled)5 StandardCharsets (java.nio.charset.StandardCharsets)5 Arrays (java.util.Arrays)5 Collections (java.util.Collections)5