Search in sources :

Example 16 with Session

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

the class NodeSettingsTest method testClusterName.

/**
 * The default cluster name is "crate" if not set differently in crate settings
 */
@Test
public void testClusterName() throws Exception {
    try (Session session = sqlOperations.newSystemSession()) {
        SQLResponse response = SQLTransportExecutor.execute("select name from sys.cluster", new Object[0], session).get(SQLTransportExecutor.REQUEST_TIMEOUT.millis(), TimeUnit.MILLISECONDS);
        assertThat(response.rows()[0][0], is("crate"));
    }
}
Also used : SQLResponse(io.crate.testing.SQLResponse) Session(io.crate.action.sql.Session) Test(org.junit.Test)

Example 17 with Session

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

the class JobLogIntegrationTest method testJobLogWithEnabledAndDisabledStats.

@Test
// SET extra_float_digits = 3 gets added to the jobs_log
@UseJdbc(0)
public void testJobLogWithEnabledAndDisabledStats() throws Exception {
    String setStmt = "set global transient stats.jobs_log_size=1";
    execute(setStmt);
    // We record the statements in the log **after** we notify the result receivers (see {@link JobsLogsUpdateListener usage).
    // So it might happen that the "set global ..." statement execution is returned to this test but the recording
    // in the log is done AFTER the execution of the below "select name from sys.cluster" statement (because async
    // programming is evil like that). And then this test will fail and people will spend days and days to figure
    // out what's going on.
    // So let's just wait for the "set global ... " statement to be recorded here and then move on with our test.
    assertBusy(() -> {
        boolean setStmtFound = false;
        for (JobsLogService jobsLogService : internalCluster().getDataNodeInstances(JobsLogService.class)) {
            // each node must have received the new jobs_log_size setting change instruction
            assertThat(jobsLogService.jobsLogSize(), is(1));
            JobsLogs jobsLogs = jobsLogService.get();
            Iterator<JobContextLog> iterator = jobsLogs.jobsLog().iterator();
            if (iterator.hasNext()) {
                if (iterator.next().statement().equalsIgnoreCase(setStmt)) {
                    setStmtFound = true;
                }
            }
        }
        // at least one node must have the set statement logged
        assertThat(setStmtFound, is(true));
    });
    // only the latest queries are found in the log.
    for (SQLOperations sqlOperations : internalCluster().getDataNodeInstances(SQLOperations.class)) {
        Session session = sqlOperations.newSystemSession();
        execute("select name from sys.cluster", null, session);
    }
    assertJobLogOnNodesHaveOnlyStatement("select name from sys.cluster");
    for (SQLOperations sqlOperations : internalCluster().getDataNodeInstances(SQLOperations.class)) {
        Session session = sqlOperations.newSystemSession();
        execute("select id from sys.cluster", null, session);
    }
    assertJobLogOnNodesHaveOnlyStatement("select id from sys.cluster");
    execute("set global transient stats.enabled = false");
    for (JobsLogService jobsLogService : internalCluster().getDataNodeInstances(JobsLogService.class)) {
        assertBusy(() -> assertThat(jobsLogService.isEnabled(), is(false)));
    }
    execute("select * from sys.jobs_log");
    assertThat(response.rowCount(), is(0L));
}
Also used : JobContextLog(io.crate.expression.reference.sys.job.JobContextLog) JobsLogs(io.crate.execution.engine.collect.stats.JobsLogs) SQLOperations(io.crate.action.sql.SQLOperations) JobsLogService(io.crate.execution.engine.collect.stats.JobsLogService) Session(io.crate.action.sql.Session) UseJdbc(io.crate.testing.UseJdbc) Test(org.junit.Test)

Example 18 with Session

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

the class SQLTransportExecutor method execute.

public CompletableFuture<SQLResponse> execute(String stmt, @Nullable Object[] args) {
    Session session = newSession();
    CompletableFuture<SQLResponse> result = execute(stmt, args, session);
    return result.whenComplete((res, err) -> session.close());
}
Also used : Session(io.crate.action.sql.Session)

Example 19 with Session

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

the class SQLIntegrationTestCase method systemExecute.

/**
 * Execute a SQL statement as system query on a specific node in the cluster
 *
 * @param stmt      the SQL statement
 * @param schema    the schema that should be used for this statement
 *                  schema is nullable, which means the default schema ("doc") is used
 * @param node      the name of the node on which the stmt is executed
 * @return          the SQL Response
 */
public SQLResponse systemExecute(String stmt, @Nullable String schema, String node) {
    SQLOperations sqlOperations = internalCluster().getInstance(SQLOperations.class, node);
    UserLookup userLookup;
    try {
        userLookup = internalCluster().getInstance(UserLookup.class, node);
    } catch (ConfigurationException ignored) {
        // If enterprise is not enabled there is no UserLookup instance bound in guice
        userLookup = userName -> User.CRATE_USER;
    }
    try (Session session = sqlOperations.createSession(schema, userLookup.findUser("crate"))) {
        response = sqlExecutor.exec(stmt, session);
    }
    return response;
}
Also used : ParamTypeHints(io.crate.analyze.ParamTypeHints) SessionContext(io.crate.action.sql.SessionContext) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) SessionSettings(io.crate.metadata.settings.SessionSettings) Matchers.not(org.hamcrest.Matchers.not) Inherited(java.lang.annotation.Inherited) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) Analyzer(io.crate.analyze.Analyzer) NodeLimits(io.crate.execution.jobs.NodeLimits) DependencyCarrier(io.crate.planner.DependencyCarrier) Functions(io.crate.metadata.Functions) Matchers.nullValue(org.hamcrest.Matchers.nullValue) Map(java.util.Map) SQLTransportExecutor(io.crate.testing.SQLTransportExecutor) RandomStrings(com.carrotsearch.randomizedtesting.generators.RandomStrings) TableInfo(io.crate.metadata.table.TableInfo) RandomizedContext(com.carrotsearch.randomizedtesting.RandomizedContext) TasksService(io.crate.execution.jobs.TasksService) Logger(org.apache.logging.log4j.Logger) Row(io.crate.data.Row) SubQueryResults(io.crate.planner.operators.SubQueryResults) ClusterStateRequest(org.elasticsearch.action.admin.cluster.state.ClusterStateRequest) Matchers.is(org.hamcrest.Matchers.is) XContentFactory(org.elasticsearch.common.xcontent.XContentFactory) ClusterService(org.elasticsearch.cluster.service.ClusterService) BoundTransportAddress(org.elasticsearch.common.transport.BoundTransportAddress) Metadata(org.elasticsearch.cluster.metadata.Metadata) TestName(org.junit.rules.TestName) Timeout(org.junit.rules.Timeout) IndicesService(org.elasticsearch.indices.IndicesService) Nullable(javax.annotation.Nullable) PSQL_PORT_SETTING(io.crate.protocols.postgres.PostgresNetty.PSQL_PORT_SETTING) Before(org.junit.Before) Identifiers(io.crate.sql.Identifiers) Client(org.elasticsearch.client.Client) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) IOException(java.io.IOException) Planner(io.crate.planner.Planner) Field(java.lang.reflect.Field) RoutingProvider(io.crate.metadata.RoutingProvider) Literal(io.crate.expression.symbol.Literal) PlannerContext(io.crate.planner.PlannerContext) Matcher(org.hamcrest.Matcher) Plan(io.crate.planner.Plan) PostgresNetty(io.crate.protocols.postgres.PostgresNetty) KillableCallable(io.crate.execution.jobs.kill.KillableCallable) Schemas(io.crate.metadata.Schemas) UseJdbc(io.crate.testing.UseJdbc) Randomness(org.elasticsearch.common.Randomness) TransportShardAction(io.crate.execution.dml.TransportShardAction) TransportShardUpsertAction(io.crate.execution.dml.upsert.TransportShardUpsertAction) RelationName(io.crate.metadata.RelationName) UseRandomizedSchema(io.crate.testing.UseRandomizedSchema) Random(java.util.Random) RootTask(io.crate.execution.jobs.RootTask) UseHashJoins(io.crate.testing.UseHashJoins) Settings(org.elasticsearch.common.settings.Settings) TestGroup(com.carrotsearch.randomizedtesting.annotations.TestGroup) Locale(java.util.Locale) After(org.junit.After) Documented(java.lang.annotation.Documented) ThreadPool(org.elasticsearch.threadpool.ThreadPool) Method(java.lang.reflect.Method) SQLOperations(io.crate.action.sql.SQLOperations) NodeContext(io.crate.metadata.NodeContext) User(io.crate.user.User) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) UUID(java.util.UUID) Netty4Plugin(org.elasticsearch.transport.Netty4Plugin) InetSocketAddress(java.net.InetSocketAddress) Lists2(io.crate.common.collections.Lists2) List(java.util.List) Session(io.crate.action.sql.Session) ESIntegTestCase(org.elasticsearch.test.ESIntegTestCase) Symbol(io.crate.expression.symbol.Symbol) FunctionImplementation(io.crate.metadata.FunctionImplementation) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Annotation(java.lang.annotation.Annotation) TimeValue(io.crate.common.unit.TimeValue) Paging(io.crate.data.Paging) TestingRowConsumer(io.crate.testing.TestingRowConsumer) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) UserLookup(io.crate.user.UserLookup) SQLResponse(io.crate.testing.SQLResponse) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) TransportShardDeleteAction(io.crate.execution.dml.delete.TransportShardDeleteAction) SearchPath(io.crate.metadata.SearchPath) Index(org.elasticsearch.index.Index) SETTING_HTTP_COMPRESSION(org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_COMPRESSION) TaskId(org.elasticsearch.tasks.TaskId) Retention(java.lang.annotation.Retention) Strings(org.elasticsearch.common.Strings) ElasticsearchTimeoutException(org.elasticsearch.ElasticsearchTimeoutException) Constants(io.crate.Constants) Symbols(io.crate.expression.symbol.Symbols) SqlParser(io.crate.sql.parser.SqlParser) Requests(org.elasticsearch.client.Requests) Listeners(com.carrotsearch.randomizedtesting.annotations.Listeners) TestExecutionConfig(io.crate.testing.TestExecutionConfig) ColumnIdent(io.crate.metadata.ColumnIdent) Plugin(org.elasticsearch.plugins.Plugin) Matchers(org.hamcrest.Matchers) DataType(io.crate.types.DataType) TimeUnit(java.util.concurrent.TimeUnit) ClusterStateResponse(org.elasticsearch.action.admin.cluster.state.ClusterStateResponse) Rule(org.junit.Rule) SystemPropsTestLoggingListener(io.crate.test.integration.SystemPropsTestLoggingListener) LogManager(org.apache.logging.log4j.LogManager) ConfigurationException(org.elasticsearch.common.inject.ConfigurationException) RetentionPolicy(java.lang.annotation.RetentionPolicy) ConfigurationException(org.elasticsearch.common.inject.ConfigurationException) UserLookup(io.crate.user.UserLookup) SQLOperations(io.crate.action.sql.SQLOperations) Session(io.crate.action.sql.Session)

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