Java Code Examples for io.crate.action.sql.SQLActionException

The following examples show how to use io.crate.action.sql.SQLActionException. 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: crate   Source File: ColumnPolicyIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInsertNewColumnTableStrictColumnPolicy() throws Exception {
    execute("create table strict_table (" +
            "  id integer primary key, " +
            "  name string" +
            ") with (column_policy='strict', number_of_replicas=0)");
    ensureYellow();
    execute("insert into strict_table (id, name) values (1, 'Ford')");
    execute("refresh table strict_table");

    execute("select * from strict_table");
    assertThat(response.rowCount(), is(1L));
    assertThat(response.cols(), is(arrayContaining("id", "name")));
    assertThat(response.rows()[0], is(Matchers.<Object>arrayContaining(1, "Ford")));

    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("Column boo unknown");
    execute("insert into strict_table (id, name, boo) values (2, 'Trillian', true)");
}
 
Example 2
Source Project: crate   Source File: PartitionedTableIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInsertPartitionedTablePrimaryKeysDuplicate() {
    execute("create table parted (" +
            "  id int, " +
            "  name string, " +
            "  date timestamp with time zone," +
            "  primary key (id, name)" +
            ") partitioned by (id, name)");
    ensureYellow();
    Long dateValue = System.currentTimeMillis();
    execute("insert into parted (id, name, date) values (?, ?, ?)",
        new Object[]{42, "Zaphod", dateValue});
    assertThat(response.rowCount(), is(1L));
    ensureYellow();
    refresh();

    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("A document with the same primary key exists already");

    execute("insert into parted (id, name, date) values (?, ?, ?)",
        new Object[]{42, "Zaphod", 0L});
}
 
Example 3
Source Project: crate   Source File: PartitionedTableIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleWritesWhenOnePartitionIsReadOnly() {
    execute("create table my_table (par int, content string) " +
            "clustered into 5 shards " +
            "partitioned by (par)");
    execute("insert into my_table (par, content) values " +
            "(1, 'content2'), " +
            "(2, 'content3')");

    ensureGreen();
    execute("alter table my_table partition (par=1) set (\"blocks.write\"=true)");
    try {
        execute("insert into my_table (par, content) values (2, 'content42'), " +
                "(2, 'content42'), " +
                "(1, 'content2'), " +
                "(3, 'content6')");
        fail("expected to throw an \"blocked\" exception");
    } catch (SQLActionException e) {
        assertThat(e.getMessage(), containsString("blocked by: [FORBIDDEN/8/index write (api)];"));
    }
    refresh();
    execute("select * from my_table");
    assertThat(response.rowCount(), Matchers.is(both(greaterThanOrEqualTo(2L)).and(lessThanOrEqualTo(5L))));
    //cleaning up
    execute("alter table my_table partition (par=1) set (\"blocks.write\"=false)");
}
 
Example 4
Source Project: crate   Source File: DDLIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAlterTableAddObjectColumnToExistingObject() {
    execute("create table t (o object as (x string)) " +
            "clustered into 1 shards " +
            "with (number_of_replicas=0)");
    ensureYellow();
    execute("alter table t add o['y'] int");
    try {
        execute("alter table t add o object as (z string)");
        fail("did not fail for existing column o");
    } catch (SQLActionException e) {
        // column o exists already
        assertThat(e.getMessage(), containsString("The table doc.t already has a column named o"));
    }
    execute("select column_name from information_schema.columns where " +
            "table_name = 't' and table_schema='doc'" +
            "order by column_name asc");
    assertThat(response.rowCount(), is(3L));

    List<String> fqColumnNames = new ArrayList<>();
    for (Object[] row : response.rows()) {
        fqColumnNames.add((String) row[0]);
    }
    assertThat(fqColumnNames, Matchers.contains("o", "o['x']", "o['y']"));
}
 
Example 5
Source Project: spring-data-crate   Source File: CrateTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T> T execute(CrateAction action, CrateActionResponseHandler<T> handler) throws DataAccessException {
   	
   	notNull(action, "An implementation of CrateAction is required");
   	notNull(handler, "An implementation of CrateActionResponseHandler<T> is required");
   	
   	try {
   		SQLRequest request = action.getSQLRequest();
   		logger.debug(SQL_STATEMENT, request.stmt(), Arrays.toString(request.args()));
   		return (T)handler.handle(client.sql(request).actionGet());
   	}catch(SQLActionException e) {
   		throw tryConvertingRuntimeException(e);
	}
   }
 
Example 6
Source Project: crate   Source File: FulltextITest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMatchNotOnSubColumn() throws Exception {
    execute("create table matchbox (" +
            "  s string index using fulltext with (analyzer='german')," +
            "  o object as (" +
            "    s string index using fulltext with (analyzer='german')," +
            "    m string index using fulltext with (analyzer='german')" +
            "  )," +
            "  o_ignored object(ignored)" +
            ") with (number_of_replicas=0)");
    execute("insert into matchbox (s, o) values ('Arthur Dent', {s='Zaphod Beeblebroox', m='Ford Prefect'})");
    refresh();
    execute("select * from matchbox where match(s, 'Arthur')");
    assertThat(response.rowCount(), is(1L));

    execute("select * from matchbox where match(o['s'], 'Arthur')");
    assertThat(response.rowCount(), is(0L));

    execute("select * from matchbox where match(o['s'], 'Zaphod')");
    assertThat(response.rowCount(), is(1L));

    execute("select * from matchbox where match(s, 'Zaphod')");
    assertThat(response.rowCount(), is(0L));

    execute("select * from matchbox where match(o['m'], 'Ford')");
    assertThat(response.rowCount(), is(1L));

    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("Can only use MATCH on columns of type STRING or GEO_SHAPE, not on 'undefined'");

    execute("select * from matchbox where match(o_ignored['a'], 'Ford')");
    assertThat(response.rowCount(), is(0L));
}
 
Example 7
Source Project: crate   Source File: PartitionedTableIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateTableWithIllegalCustomSchemaCheckedByES() {
    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("Relation name \"AAA.t\" is invalid.");
    execute(
        "create table \"AAA\".t (" +
        "   name string," +
        "   d timestamp with time zone" +
        ") partitioned by (d) with (number_of_replicas=0)");
}
 
Example 8
Source Project: crate   Source File: FulltextAnalyzerResolverTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void reuseExistingTokenizer() {
    execute("CREATE ANALYZER a9 (" +
            "  TOKENIZER a9tok WITH (" +
            "    type='ngram'," +
            "    \"token_chars\"=['letter', 'digit']" +
            "  )" +
            ")");
    try {
        execute("CREATE ANALYZER a10 (" +
                "  TOKENIZER a9tok" +
                ")");
        fail("Reusing existing tokenizer worked");
    } catch (SQLActionException e) {
        assertThat(e.getMessage(), containsString("Non-existing tokenizer 'a9tok'"));
    }
    /*
     * NOT SUPPORTED UNTIL A CONSISTENT SOLUTION IS FOUND
     * FOR IMPLICITLY CREATING TOKENIZERS ETC. WITHIN ANALYZER-DEFINITIONS

    Settings settings = getPersistentClusterSettings();
    Settings a10Settings = AnalyzerService.decodeSettings(settings.get("crate.analysis.custom.analyzer.a10"));
    assertThat(
            a10Settings.getAsMap(),
            hasEntry("index.analysis.analyzer.a10.tokenizer", "a9tok")
    );
    */
}
 
Example 9
Source Project: crate   Source File: SysShardsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGroupByUnknownOrderBy() throws Exception {
    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("Column lol unknown");
    execute(
        "select sum(num_docs), table_name from sys.shards group by table_name order by lol");
}
 
Example 10
Source Project: crate   Source File: PartitionedTableIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test_refresh_partition_in_non_partitioned_table() {
    execute("CREATE TABLE doc.not_parted (x TEXT)");
    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("table 'doc.not_parted' is not partitioned");
    execute("REFRESH TABLE doc.not_parted PARTITION (x = 'n')");
}
 
Example 11
Source Project: crate   Source File: PartitionedTableIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDisableWriteOnSinglePartition() {
    execute("create table my_table (par int, content string) " +
            "clustered into 5 shards " +
            "partitioned by (par)");
    execute("insert into my_table (par, content) values (1, 'content1'), " +
            "(1, 'content2'), " +
            "(2, 'content3'), " +
            "(2, 'content4'), " +
            "(2, 'content5'), " +
            "(3, 'content6')");

    ensureGreen();
    execute("alter table my_table partition (par=1) set (\"blocks.write\"=true)");

    // update is expected to be executed without exception since this partition has no write block
    execute("update my_table set content=\'content42\' where par=2");
    refresh();
    // verifying update
    execute("select content from my_table where par=2");
    assertThat(response.rowCount(), Matchers.is(3L));

    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("blocked by: [FORBIDDEN/8/index write (api)]");

    // trying to perform an update on a partition with a write block
    execute("update my_table set content=\'content42\' where par=1");
}
 
Example 12
Source Project: crate   Source File: KillIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
private void assertGotCancelled(final String statement, @Nullable final Object[] params, boolean killAll) throws Exception {
    try {
        ActionFuture<SQLResponse> future = sqlExecutor.execute(statement, params);
        String jobId = waitForJobEntry(statement);
        if (jobId == null) {
            // query finished too fast
            return;
        }
        if (killAll) {
            execute("kill all");
        } else {
            execute("kill ?", $(jobId));
        }
        try {
            future.get(10, TimeUnit.SECONDS);
        } catch (Throwable exception) {
            exception = SQLExceptions.unwrap(exception); // wrapped in ExecutionException
            assertThat(exception, instanceOf(SQLActionException.class));
            assertThat(exception.toString(), anyOf(
                containsString("Job killed"), // CancellationException
                containsString("RootTask for job"), // TaskMissing when root task not found
                containsString("Task for job") // TaskMissing when task not found
            ));
        }
    } finally {
        waitUntilThreadPoolTasksFinished(ThreadPool.Names.SEARCH);
    }
}
 
Example 13
Source Project: crate   Source File: TableSettingsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMappingTotalFieldsLimit() throws Exception {
    execute("create table test (id int)");
    int totalFields = 1;
    execute("alter table test set (\"mapping.total_fields.limit\"=?)", new Object[]{totalFields + 1});
    // Add a column is within the limit
    execute("alter table test add column new_column int");


    // One more column exceeds the limit
    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage(String.format(Locale.ENGLISH,
        "Limit of total fields [%d] in index [%s.test] has been exceeded", totalFields + 1, sqlExecutor.getCurrentSchema()));
    execute("alter table test add column new_column2 int");
}
 
Example 14
Source Project: crate   Source File: PrivilegesIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDropTableRemovesPrivileges() {
    executeAsSuperuser("create table doc.t1 (x int) clustered into 1 shards with (number_of_replicas = 0)");
    executeAsSuperuser("grant dql on table t1 to "+ TEST_USERNAME);

    executeAsSuperuser("drop table t1");
    ensureYellow();

    executeAsSuperuser("create table doc.t1 (x int) clustered into 1 shards with (number_of_replicas = 0)");
    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("Schema 'doc' unknown");
    execute("select * from t1", null, testUserSession());
}
 
Example 15
Source Project: crate   Source File: OpenCloseTableIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testClosePreventsSelect() throws Exception {
    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage(String.format("The relation \"%s\" doesn't support or allow READ operations, " +
                                    "as it is currently closed.", getFqn("t")));
    execute("select * from t");
}
 
Example 16
Source Project: crate   Source File: UserManagementIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateExistingUserThrowsException() throws Exception {
    executeAsSuperuser("create user ford_exists");
    assertUserIsCreated("ford_exists");

    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("UserAlreadyExistsException: User 'ford_exists' already exists");
    executeAsSuperuser("create user ford_exists");
}
 
Example 17
Source Project: crate   Source File: UpdateIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateVersionInOperator() throws Exception {
    execute("create table test (id int primary key, c int) with (number_of_replicas=0, refresh_interval=0)");
    ensureGreen();
    execute("insert into test (id, c) values (1, 1)");
    execute("refresh table test");

    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage(VersioninigValidationException.VERSION_COLUMN_USAGE_MSG);
    execute("update test set c = 4 where _version in (1,2)");
}
 
Example 18
Source Project: crate   Source File: UpdateIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateSetInvalidGeneratedColumnOnly() {
    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("Given value 1745 for generated column gen_col does not match calculation extract(YEAR FROM ts) = 1970");
    execute("create table computed (" +
            " ts timestamp with time zone," +
            " gen_col as extract(year from ts)" +
            ") with (number_of_replicas=0)");
    execute("insert into computed (ts) values (1)");
    refresh();
    execute("update computed set gen_col=1745");
}
 
Example 19
Source Project: crate   Source File: UpdateIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateNotNullSourceGeneratedColumn() {
    execute("create table generated_column (" +
            " id int primary key," +
            " ts timestamp with time zone," +
            " gen_col as extract(year from ts) not null" +
            ") with (number_of_replicas=0)");
    execute("insert into generated_column (id, ts) values (1, '2015-11-18T11:11:00')");
    assertEquals(1, response.rowCount());
    refresh();

    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("\"gen_col\" must not be null");
    execute("update generated_column set ts=null where id=1");
}
 
Example 20
Source Project: crate   Source File: UpdateIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateNotNullTargetGeneratedColumn() {
    execute("create table generated_column (" +
            " id int primary key," +
            " ts timestamp with time zone," +
            " gen_col as extract(year from ts) not null" +
            ") with (number_of_replicas=0)");
    execute("insert into generated_column (id, ts) values (1, '2015-11-18T11:11:00')");
    assertEquals(1, response.rowCount());
    refresh();

    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("\"gen_col\" must not be null");
    execute("update generated_column set gen_col=null where id=1");
}
 
Example 21
Source Project: crate   Source File: GroupByAggregateBreakerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void selectGroupByWithBreaking() throws Exception {
    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("CircuitBreakingException: [query] Data too large, data for ");
    // query takes 252 bytes of memory
    // 252b * 1.09 = 275b => should break with limit 256b
    execute("select region, count(*) from sys.summits group by 1");
}
 
Example 22
Source Project: crate   Source File: GroupByAggregateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGroupByUnknownResultColumn() throws Exception {
    this.setup.groupBySetup();
    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("'details_ignored['lol']' must appear in the GROUP BY clause");
    execute("select details_ignored['lol'] from characters group by race");
}
 
Example 23
Source Project: crate   Source File: ArithmeticIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSelectFailingArithmeticScalar() throws Exception {
    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("log(x, b): given arguments would result in: 'NaN'");

    execute("create table t (i integer, l long, d double) clustered into 1 shards with (number_of_replicas=0)");
    ensureYellow();
    execute("insert into t (i, l, d) values (1, 2, 90.5)");
    refresh();
    execute("select log(d, l) from t where log(d, -1) >= 0");
}
 
Example 24
Source Project: crate   Source File: ArithmeticIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSelectGroupByFailingArithmeticScalar() throws Exception {
    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("log(x, b): given arguments would result in: 'NaN'");

    execute("create table t (i integer, l long, d double) with (number_of_replicas=0)");
    ensureYellow();
    execute("insert into t (i, l, d) values (1, 2, 90.5), (0, 4, 100)");
    execute("refresh table t");

    execute("select log(d, l) from t where log(d, -1) >= 0 group by log(d, l)");
}
 
Example 25
Source Project: crate   Source File: SQLTypeMappingTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInvalidWhereClause() throws Exception {
    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("Cannot cast `129` of type `integer` to type `char`");

    setUpSimple();
    execute("delete from t1 where byte_field=129");
}
 
Example 26
Source Project: crate   Source File: SQLTypeMappingTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInvalidWhereInWhereClause() throws Exception {
    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("Cannot cast `[129]` of type `integer_array` to type `char_array`");

    setUpSimple();
    execute("update t1 set byte_field=0 where byte_field in (129)");
}
 
Example 27
Source Project: crate   Source File: DDLIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAlterTableWithRecordsAddGeneratedColumn() throws Exception {
    execute("create table t (id int) " +
            "clustered into 1 shards " +
            "with (number_of_replicas=0)");
    ensureYellow();
    execute("insert into t (id) values(1)");
    refresh();

    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("Cannot add a generated column to a table that isn't empty");
    execute("alter table t add column id_generated as (id + 1)");
}
 
Example 28
Source Project: crate   Source File: PrivilegesIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGrantWithCustomDefaultSchema() {
    executeAsSuperuser("create table doc.t1 (x int)");
    executeAsSuperuser("set search_path to 'custom_schema'");
    executeAsSuperuser("create table t2 (x int)");
    ensureYellow();

    executeAsSuperuser("grant dql on table t2 to "+ TEST_USERNAME);
    assertThat(response.rowCount(), is(1L));

    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("RelationUnknown: Relation 't1' unknown");
    executeAsSuperuser("grant dql on table t1 to "+ TEST_USERNAME);
}
 
Example 29
Source Project: crate   Source File: ShowIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testShowCrateSystemTable() throws Exception {
    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("The relation \"sys.shards\" doesn't support or allow SHOW CREATE " +
                                    "operations, as it is read-only.");
    execute("show create table sys.shards");
}
 
Example 30
Source Project: crate   Source File: ShowIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testShowCreateBlobTable() throws Exception {
    expectedException.expect(SQLActionException.class);
    expectedException.expectMessage("The relation \"blob.table_blob\" doesn't support or allow " +
                                    "SHOW CREATE operations.");
    execute("create blob table table_blob");
    execute("show create table blob.table_blob");
}