Search in sources :

Example 11 with SessionContext

use of io.crate.action.sql.SessionContext in project crate by crate.

the class PostgresWireProtocolTest method submitQueriesThroughSimpleQueryMode.

private void submitQueriesThroughSimpleQueryMode(String statements, @Nullable Throwable failure) {
    SQLOperations sqlOperations = Mockito.mock(SQLOperations.class);
    Session session = mock(Session.class);
    SessionContext sessionContext = new SessionContext(User.CRATE_USER);
    when(session.sessionContext()).thenReturn(sessionContext);
    when(sqlOperations.createSession(any(String.class), any(User.class))).thenReturn(session);
    DescribeResult describeResult = mock(DescribeResult.class);
    when(describeResult.getFields()).thenReturn(null);
    when(session.describe(anyChar(), anyString())).thenReturn(describeResult);
    when(session.transactionState()).thenReturn(TransactionState.IDLE);
    PostgresWireProtocol ctx = new PostgresWireProtocol(sqlOperations, sessionCtx -> AccessControl.DISABLED, new AlwaysOKAuthentication(userName -> User.CRATE_USER), null);
    channel = new EmbeddedChannel(ctx.decoder, ctx.handler);
    if (failure != null) {
        when(session.sync()).thenAnswer(invocationOnMock -> {
            Messages.sendErrorResponse(channel, AccessControl.DISABLED, failure);
            return CompletableFuture.failedFuture(failure);
        });
    } else {
        when(session.sync()).thenReturn(CompletableFuture.completedFuture(null));
    }
    sendStartupMessage(channel);
    readAuthenticationOK(channel);
    skipParameterMessages(channel);
    readReadyForQueryMessage(channel);
    ByteBuf query = Unpooled.buffer();
    try {
        // the actual statements don't have to be valid as they are not executed
        Messages.writeCString(query, statements.getBytes(StandardCharsets.UTF_8));
        ctx.handleSimpleQuery(query, new DelayableWriteChannel(channel));
    } finally {
        query.release();
    }
}
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) DescribeResult(io.crate.action.sql.DescribeResult) User(io.crate.user.User) SessionContext(io.crate.action.sql.SessionContext) 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)

Example 12 with SessionContext

use of io.crate.action.sql.SessionContext in project crate by crate.

the class PostgresWireProtocolTest method testBindMessageCanBeReadIfTypeForParamsIsUnknown.

@Test
public void testBindMessageCanBeReadIfTypeForParamsIsUnknown() throws Exception {
    PostgresWireProtocol ctx = new PostgresWireProtocol(sqlOperations, sessionContext -> AccessControl.DISABLED, new AlwaysOKAuthentication(userName -> User.CRATE_USER), null);
    channel = new EmbeddedChannel(ctx.decoder, ctx.handler);
    ByteBuf buffer = Unpooled.buffer();
    ClientMessages.sendStartupMessage(buffer, "doc");
    // no type hints for parameters
    ClientMessages.sendParseMessage(buffer, "S1", "select ?, ?", new int[0]);
    List<Object> params = Arrays.asList(10, 20);
    ClientMessages.sendBindMessage(buffer, "P1", "S1", params);
    channel.writeInbound(buffer);
    channel.releaseInbound();
    Session session = sessions.get(0);
    // If the query can be retrieved via portalName it means bind worked
    assertThat(session.getQuery("P1"), is("select ?, ?"));
}
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) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ByteBuf(io.netty.buffer.ByteBuf) Session(io.crate.action.sql.Session) CrateDummyClusterServiceUnitTest(io.crate.test.integration.CrateDummyClusterServiceUnitTest) Test(org.junit.Test)

Example 13 with SessionContext

use of io.crate.action.sql.SessionContext in project crate by crate.

the class PostgresWireProtocolTest method testDescribeStatementMessage.

@Test
public void testDescribeStatementMessage() throws Exception {
    PostgresWireProtocol ctx = new PostgresWireProtocol(sqlOperations, sessionContext -> AccessControl.DISABLED, new AlwaysOKAuthentication(userName -> User.CRATE_USER), null);
    channel = new EmbeddedChannel(ctx.decoder, ctx.handler);
    {
        ByteBuf buffer = Unpooled.buffer();
        ClientMessages.sendStartupMessage(buffer, "doc");
        ClientMessages.sendParseMessage(buffer, "S1", "select ? in (1, 2, 3)", new int[0]);
        channel.writeInbound(buffer);
        channel.releaseInbound();
        // we're not interested in the startup, parse, or bind replies
        channel.flushOutbound();
        channel.releaseOutbound();
        channel.outboundMessages().clear();
    }
    {
        // try the describe statement variant
        ByteBuf buffer = Unpooled.buffer();
        ClientMessages.sendDescribeMessage(buffer, ClientMessages.DescribeType.STATEMENT, "S1");
        channel.writeInbound(buffer);
        channel.releaseInbound();
        // we should get back a ParameterDescription message
        channel.flushOutbound();
        ByteBuf response = channel.readOutbound();
        try {
            assertThat(response.readByte(), is((byte) 't'));
            assertThat(response.readInt(), is(10));
            assertThat(response.readShort(), is((short) 1));
            assertThat(response.readInt(), is(PGTypes.get(DataTypes.INTEGER).oid()));
        } finally {
            response.release();
        }
        // we should get back a RowDescription message
        response = channel.readOutbound();
        try {
            assertThat(response.readByte(), is((byte) 'T'));
            assertThat(response.readInt(), is(46));
            assertThat(response.readShort(), is((short) 1));
            assertThat(PostgresWireProtocol.readCString(response), is("($1 = ANY([1, 2, 3]))"));
            assertThat(response.readInt(), is(0));
            assertThat(response.readShort(), is((short) 0));
            assertThat(response.readInt(), is(PGTypes.get(DataTypes.BOOLEAN).oid()));
            assertThat(response.readShort(), is(PGTypes.get(DataTypes.BOOLEAN).typeLen()));
            assertThat(response.readInt(), is(PGTypes.get(DataTypes.LONG).typeMod()));
            assertThat(response.readShort(), is((short) 0));
        } finally {
            response.release();
        }
    }
}
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) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ByteBuf(io.netty.buffer.ByteBuf) CrateDummyClusterServiceUnitTest(io.crate.test.integration.CrateDummyClusterServiceUnitTest) Test(org.junit.Test)

Example 14 with SessionContext

use of io.crate.action.sql.SessionContext in project crate by crate.

the class PostgresWireProtocolTest method testDescribePortalMessage.

@Test
public void testDescribePortalMessage() throws Exception {
    PostgresWireProtocol ctx = new PostgresWireProtocol(sqlOperations, sessionContext -> AccessControl.DISABLED, new AlwaysOKAuthentication(userName -> User.CRATE_USER), null);
    channel = new EmbeddedChannel(ctx.decoder, ctx.handler);
    {
        ByteBuf buffer = Unpooled.buffer();
        ClientMessages.sendStartupMessage(buffer, "doc");
        ClientMessages.sendParseMessage(buffer, "S1", "select ? in (1, 2, 3)", new int[] { PGTypes.get(DataTypes.INTEGER).oid() });
        ClientMessages.sendBindMessage(buffer, "P1", "S1", Collections.singletonList(1));
        channel.writeInbound(buffer);
        channel.releaseInbound();
        // we're not interested in the startup, parse, or bind replies
        channel.flushOutbound();
        channel.releaseOutbound();
        channel.outboundMessages().clear();
    }
    {
        // try portal describe message
        ByteBuf buffer = Unpooled.buffer();
        ClientMessages.sendDescribeMessage(buffer, ClientMessages.DescribeType.PORTAL, "P1");
        channel.writeInbound(buffer);
        channel.releaseInbound();
        // we should get back a RowDescription message
        channel.flushOutbound();
        ByteBuf response = channel.readOutbound();
        try {
            assertThat(response.readByte(), is((byte) 'T'));
            assertThat(response.readInt(), is(46));
            assertThat(response.readShort(), is((short) 1));
            assertThat(PostgresWireProtocol.readCString(response), is("($1 = ANY([1, 2, 3]))"));
            assertThat(response.readInt(), is(0));
            assertThat(response.readShort(), is((short) 0));
            assertThat(response.readInt(), is(PGTypes.get(DataTypes.BOOLEAN).oid()));
            assertThat(response.readShort(), is(PGTypes.get(DataTypes.BOOLEAN).typeLen()));
            assertThat(response.readInt(), is(PGTypes.get(DataTypes.LONG).typeMod()));
            assertThat(response.readShort(), is((short) 0));
        } finally {
            response.release();
        }
    }
}
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) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ByteBuf(io.netty.buffer.ByteBuf) CrateDummyClusterServiceUnitTest(io.crate.test.integration.CrateDummyClusterServiceUnitTest) Test(org.junit.Test)

Example 15 with SessionContext

use of io.crate.action.sql.SessionContext in project crate by crate.

the class SQLIntegrationTestCase method plan.

public PlanForNode plan(String stmt) {
    String[] nodeNames = internalCluster().getNodeNames();
    String nodeName = nodeNames[randomIntBetween(1, nodeNames.length) - 1];
    Analyzer analyzer = internalCluster().getInstance(Analyzer.class, nodeName);
    Planner planner = internalCluster().getInstance(Planner.class, nodeName);
    NodeContext nodeCtx = internalCluster().getInstance(NodeContext.class, nodeName);
    SessionContext sessionContext = new SessionContext(User.CRATE_USER, sqlExecutor.getCurrentSchema());
    CoordinatorTxnCtx coordinatorTxnCtx = new CoordinatorTxnCtx(sessionContext);
    RoutingProvider routingProvider = new RoutingProvider(Randomness.get().nextInt(), planner.getAwarenessAttributes());
    PlannerContext plannerContext = new PlannerContext(planner.currentClusterState(), routingProvider, UUID.randomUUID(), coordinatorTxnCtx, nodeCtx, 0, null);
    Plan plan = planner.plan(analyzer.analyze(SqlParser.createStatement(stmt), coordinatorTxnCtx.sessionContext(), ParamTypeHints.EMPTY), plannerContext);
    return new PlanForNode(plan, nodeName, plannerContext);
}
Also used : RoutingProvider(io.crate.metadata.RoutingProvider) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) PlannerContext(io.crate.planner.PlannerContext) NodeContext(io.crate.metadata.NodeContext) SessionContext(io.crate.action.sql.SessionContext) Planner(io.crate.planner.Planner) Analyzer(io.crate.analyze.Analyzer) Plan(io.crate.planner.Plan)

Aggregations

SessionContext (io.crate.action.sql.SessionContext)31 Test (org.junit.Test)26 CrateDummyClusterServiceUnitTest (io.crate.test.integration.CrateDummyClusterServiceUnitTest)18 SQLExecutor (io.crate.testing.SQLExecutor)14 User (io.crate.user.User)13 List (java.util.List)13 ArrayList (java.util.ArrayList)12 DependencyCarrier (io.crate.planner.DependencyCarrier)11 DataTypes (io.crate.types.DataTypes)11 Arrays (java.util.Arrays)11 Map (java.util.Map)11 DescribeResult (io.crate.action.sql.DescribeResult)10 SQLOperations (io.crate.action.sql.SQLOperations)10 Session (io.crate.action.sql.Session)10 AccessControl (io.crate.auth.AccessControl)10 AlwaysOKAuthentication (io.crate.auth.AlwaysOKAuthentication)10 Authentication (io.crate.auth.Authentication)10 AuthenticationMethod (io.crate.auth.AuthenticationMethod)10 JobKilledException (io.crate.exceptions.JobKilledException)10 JobsLogs (io.crate.execution.engine.collect.stats.JobsLogs)10