public ResultSet executeQuery(String cql, String extra) { if(isDryRun() && !cql.startsWith("SELECT")) { if(extra!=null)env.info().log("Would query" + extra + ": " + cql); } else { if(extra!=null)env.info().log("query" + extra + ": " + cql); try { return session.execute(cql); } catch (InvalidQueryException e) { if(extra==null) { env.info().log("query: " + cql); } throw e; } } return null; }
protected void createKeySpace() { try { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Checking for key-space: " + this.keySpace); } getSession().execute("USE " + this.keySpace); } catch (final InvalidQueryException e) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Creating key-space: " + this.keySpace, e); } else if (LOGGER.isInfoEnabled()) { LOGGER.info("Creating key-space: " + this.keySpace); } getSession().execute("CREATE KEYSPACE " + this.keySpace + " with replication = " + this.replicator); getSession().execute("USE " + this.keySpace); } }
protected void checkCassandraException(Exception e) { _mexceptions.incr(); if (e instanceof AlreadyExistsException || e instanceof AuthenticationException || e instanceof DriverException || e instanceof DriverInternalError || e instanceof InvalidConfigurationInQueryException || e instanceof InvalidQueryException || e instanceof InvalidTypeException || e instanceof QueryExecutionException || e instanceof QueryTimeoutException || e instanceof QueryValidationException || e instanceof ReadTimeoutException || e instanceof SyntaxError || e instanceof TraceRetrievalException || e instanceof TruncateException || e instanceof UnauthorizedException || e instanceof UnavailableException || e instanceof ReadTimeoutException || e instanceof WriteTimeoutException) { throw new ReportedFailedException(e); } else { throw new RuntimeException(e); } }
@Test public void runMigration_shouldStopOnFailure() throws Exception { String invalidMigrationStatement = "invalid migration"; when(session.execute(invalidMigrationStatement)).thenThrow(new InvalidQueryException("unit test")); try { client.runMigration(new Migration("001_initial_migration.cql", invalidMigrationStatement)); fail("Excepted exception"); } catch (InvalidQueryException ignored) { } verify(session, times(1)).execute(invalidMigrationStatement); ArgumentCaptor<BuiltStatement> captor = ArgumentCaptor.forClass(BuiltStatement.class); verify(session, times(2)).execute(captor.capture()); assertThat(captor.getAllValues()) .hasSize(2) .extracting(BuiltStatement::toString) .has(containsSubstr("UPDATE test.migrations SET status='FAILED'"), atIndex(1)) .has(containsSubstr("reason='unit test'"), atIndex(1)) .has(containsSubstr("IF status IN ('APPLYING','FAILED')"), atIndex(1)); }
@Test public void testCountersTable() throws Throwable { createTable("CREATE TABLE %s (" + "k int PRIMARY KEY, " + "count counter)"); execute("USE " + keyspace()); executeNet(protocolVersion, "USE " + keyspace()); try { createView("mv_counter", "CREATE MATERIALIZED VIEW %s AS SELECT * FROM %%s WHERE count IS NOT NULL AND k IS NOT NULL PRIMARY KEY (count,k)"); Assert.fail("MV on counter should fail"); } catch (InvalidQueryException e) { } }
@Test public void testDropTableWithMV() throws Throwable { createTable("CREATE TABLE %s (" + "a int," + "b int," + "c int," + "d int," + "PRIMARY KEY (a, b, c))"); executeNet(protocolVersion, "USE " + keyspace()); createView(keyspace() + ".mv1", "CREATE MATERIALIZED VIEW %s AS SELECT * FROM %%s WHERE b IS NOT NULL AND c IS NOT NULL PRIMARY KEY (a, b, c)"); try { executeNet(protocolVersion, "DROP TABLE " + keyspace() + ".mv1"); Assert.fail(); } catch (InvalidQueryException e) { Assert.assertEquals("Cannot use DROP TABLE on Materialized View", e.getMessage()); } }
@Override public CompletableFuture<ImmutableSet<? extends Batchable<?>>> onWrite(WriteQueryData queryData) { // this interceptor does not support where condition based queries if (!queryData.getWhereConditions().isEmpty()) { throw new InvalidQueryException("where condition based queries are not supported"); } if (queryData.hasKey(ACCOUNT_ID) && queryData.hasValueToMutate(KEY) && queryData.hasSetValuesToAddOrSet(EMAIL_IDX)) { List<Write> writes = Lists.newArrayList(); for (TupleValue tupleValue : queryData.getSetValuesToAddOrSet(EMAIL_IDX)) { writes.add(keyByEmailDao.writeWithKey(KeyByEmailColumns.EMAIL, tupleValue.getString(0), KeyByEmailColumns.CREATED, tupleValue.getLong(1)) .value(KeyByEmailColumns.KEY, queryData.getValueToMutate(KEY)) .value(KeyByEmailColumns.ACCOUNT_ID, queryData.getKey(ACCOUNT_ID)) .withConsistency(ConsistencyLevel.QUORUM)); } return CompletableFuture.completedFuture(ImmutableSet.copyOf(writes)); } else { return CompletableFuture.completedFuture(ImmutableSet.of()); } }
private Set<String> getTenants() { Set<String> tenants = new HashSet<>(); ResultSet resultset = session.execute("SELECT * FROM system_schema.keyspaces WHERE keyspace_name = 'hawkular_metrics';"); if (!resultset.iterator().hasNext()) { return tenants; } try { // An invalid query exception will occur if the table does not exists. // If the table does not exist, then no tenants have been stored yet so we just return the empty tenant set. ResultSet resultSet = session.execute("SELECT DISTINCT tenant_id,type from hawkular_metrics.metrics_idx;"); Iterator<Row> ri = resultSet.iterator(); while (ri.hasNext()) { Row row = ri.next(); String tenant = row.getString("tenant_id"); if (!tenant.startsWith("_") && !tenant.contains(":")) { tenants.add(tenant); } } } catch (InvalidQueryException iqe) { log.warn(iqe); } return tenants; }
@Test public void testDropKeyspace() throws Exception { // Set up a connection manager and build the cluster and keyspace ConnectionManager cm = getConnectionManager(); CKeyspaceDefinition definition = JsonUtil.objectFromJsonResource(CKeyspaceDefinition.class , this.getClass().getClassLoader(), "CKeyspaceTestData.js"); assertNotNull(definition); cm.buildKeyspace(definition, false); // Drop the keyspace cm.dropKeyspace(definition.getName()); // Make sure it is really dropped Session session = cm.getEmptySession(); boolean caught = false; try { session.execute("USE " + definition.getName() + ";"); } catch(InvalidQueryException e) { caught = true; } session.close(); assertTrue(caught); cm.teardown(); }
@Test public void testShouldReturnInvalidResult() throws Exception { String message = "This is an invalid result"; server.prime(when(query).then(invalid(message))); thrown.expect(InvalidQueryException.class); thrown.expectMessage(message); query(); }
/** * Checks if Cassandra keyspace absence error occurred. * * @param e Exception to check. * @return {@code true} in case of keyspace absence error. */ public static boolean isKeyspaceAbsenceError(Throwable e) { if (CassandraHelper.isKeyspaceAbsenceError(e)) { return true; } while (e != null) { if (e instanceof InvalidQueryException && KEYSPACE_EXIST_ERROR3.matcher(e.getMessage()).matches()) { return true; } e = e.getCause(); } return false; }
@Override public void onError(Throwable e) { logger.warn(e.getMessage(), e); if (e instanceof InvalidQueryException) { response.resume(Response.status(Response.Status.BAD_REQUEST).build()); } response.resume(e); }
private void deleteKeySpace(String keySpace) throws CassandraServiceException { LOGGER.info("Deleting KeySpace " + keySpace); try { session.execute("DROP KEYSPACE " + keySpace); } catch (InvalidQueryException e) { throw new CassandraServiceException("keyspace " + keySpace + " doesn't exists", e); } }
/** * Checks if Cassandra keyspace absence error occur. * * @param e Exception to check. * @return {@code true} in case of keyspace absence error. */ public static boolean isKeyspaceAbsenceError(Throwable e) { while (e != null) { if (e instanceof InvalidQueryException && (KEYSPACE_EXIST_ERROR1.matcher(e.getMessage()).matches() || KEYSPACE_EXIST_ERROR2.matcher(e.getMessage()).matches())) return true; e = e.getCause(); } return false; }
/** * Checks if Cassandra table absence error occur. * * @param e Exception to check. * @return {@code true} in case of table absence error. */ public static boolean isTableAbsenceError(Throwable e) { while (e != null) { if (e instanceof InvalidQueryException && (TABLE_EXIST_ERROR1.matcher(e.getMessage()).matches() || KEYSPACE_EXIST_ERROR1.matcher(e.getMessage()).matches() || KEYSPACE_EXIST_ERROR2.matcher(e.getMessage()).matches())) return true; if (e instanceof NoHostAvailableException && ((NoHostAvailableException) e).getErrors() != null) { NoHostAvailableException ex = (NoHostAvailableException)e; for (Map.Entry<InetSocketAddress, Throwable> entry : ex.getErrors().entrySet()) { //noinspection ThrowableResultOfMethodCallIgnored Throwable error = entry.getValue(); if (error instanceof DriverException && (error.getMessage().contains(TABLE_EXIST_ERROR2) || KEYSPACE_EXIST_ERROR3.matcher(error.getMessage()).matches())) return true; } } e = e.getCause(); } return false; }
/** * Checks if Cassandra error occur because of prepared statement created in one session was used in another session. * * @param e Exception to check. * @return {@code true} in case of invalid usage of prepared statement. */ public static boolean isPreparedStatementClusterError(Throwable e) { while (e != null) { if (e instanceof InvalidQueryException && e.getMessage().contains(PREP_STATEMENT_CLUSTER_INSTANCE_ERROR)) return true; e = e.getCause(); } return false; }
@Test public void testFunctionExecutionExceptionNet() throws Throwable { createTable("CREATE TABLE %s (key int primary key, dval double)"); execute("INSERT INTO %s (key, dval) VALUES (?, ?)", 1, 1d); String fName = createFunction(KEYSPACE_PER_TEST, "double", "CREATE OR REPLACE FUNCTION %s(val double) " + "RETURNS NULL ON NULL INPUT " + "RETURNS double " + "LANGUAGE JAVA\n" + "AS 'throw new RuntimeException();'"); for (int version : PROTOCOL_VERSIONS) { try { assertRowsNet(version, executeNet(version, "SELECT " + fName + "(dval) FROM %s WHERE key = 1")); Assert.fail(); } catch (com.datastax.driver.core.exceptions.FunctionExecutionException fee) { // Java driver neither throws FunctionExecutionException nor does it set the exception code correctly Assert.assertTrue(version >= Server.VERSION_4); } catch (InvalidQueryException e) { Assert.assertTrue(version < Server.VERSION_4); } } }
@Test(expected = InvalidQueryException.class) public void testOversizedBatch() { int SIZE_FOR_FAILURE = 2500; BatchStatement b = new BatchStatement(BatchStatement.Type.UNLOGGED); for (int i = 0; i < SIZE_FOR_FAILURE; i++) { b.add(noncounter.bind(i, "foobar")); } session.execute(b); }
@Test(expected = InvalidQueryException.class) public void testUDTinternalThatFails() { CassandraUtilsSelect select = cassandraUtils.filter(match("addres.point", "Paris")); select.count(); assertTrue("Selecting a type that is no matched must return an Exception", true); }
@Test(expected = InvalidQueryException.class) public void testUDToverUDTThatFails() { CassandraUtilsSelect select = cassandraUtils.filter(range("addres.point.inexistent").lower(-1.0).upper(-3.0)); select.count(); assertTrue("Selecting a inexistent type inside udt inside udt must return an Exception", true); }
@Override public CompletableFuture<ImmutableSet<? extends Batchable<?>>> onDelete(DeleteQueryData queryData) { // this interceptor does not support where condition based queries if (!queryData.getWhereConditions().isEmpty()) { throw new InvalidQueryException("where condition based queries are not supported"); } // resolve dependent records return keyByAccountDao.readWithKey(queryData.getKey()) .withConsistency(ConsistencyLevel.QUORUM) .executeAsync() .thenApply(optionalRecord -> optionalRecord.map(record -> getDeletions(record)).orElse(ImmutableSet.of())); }
/** * @param statement te statement to execute in an async manner * @return the resultset future */ public ListenableFuture<ResultSet> executeAsync(Statement statement) { try { return getSession().executeAsync(statement); } catch (InvalidQueryException | DriverInternalError e) { cleanUp(); LOG.warn("could not execute statement", e); return Futures.immediateFailedFuture(e); } }
private void alterEndpointProfileTable() { try { cassandraSession.execute("ALTER TABLE ep_profile ADD eps_cf_hash blob;"); } catch (InvalidQueryException ex) { LOG.warn("Failed to alter ep_profile table: {}", ex.getMessage()); } }
private void dropKeyspaceIfExists(Session localSession) { try { localSession.execute("drop keyspace " + TEST_KEYSPACE); } catch (InvalidQueryException ignored) { // doesn't exist } }
public void tearDown() { try { Session session = cassandraService.getCluster().connect(); CassandraInit.truncate(session, context); } catch (InvalidQueryException | ConnectionException e) { log.warn("failed to truncate {}", keyspace); } }
/** * Gets a prepared statement. Could be new, or from the cache. * * @param query The query to get the statement for. * @param session The session to create the statement in. * @return a PreparedStatement to use. */ public static PreparedStatement getPreparedStatement(String query, Session session) { // if (!established) // { // establishCache(); // } //StopWatch sw = new StopWatch(); //sw.start(); if (query == null || query.trim().equals("")) { throw new IllegalArgumentException("Query must be populated."); } if (session == null) { throw new IllegalArgumentException("Session cannot be null."); } query = query.trim(); Cache c = CacheFactory.getCache("preparedStatements"); Element e = null; // synchronized (LOCK) //{ e = c.get(query); if (e == null || e.getObjectValue() == null) { logger.debug("Creating new Prepared Statement for: " + query); try { e = new Element(query, session.prepare(query)); c.put(e); } catch (InvalidQueryException ex) { logger.error("Serious problem when attempting to prepare query: " + query + " This is likely a fatal application problem.", ex); throw ex;//this wasn't getting logged for some reason, so we will manually log ^^ } } else { if (logger.isTraceEnabled()) { PreparedStatement ps = (PreparedStatement) e.getObjectValue(); logger.trace("Pulling PreparedStatement from Cache: " + ps.getQueryString()); } } //} //sw.stop(); //logger.debug("Time to fetch prepared statement (" + query + "): " + sw.getTime()); return (PreparedStatement) e.getObjectValue(); }
@Test(expected = InvalidQueryException.class) public void testMixedInCounterBatch() { sendBatch(BatchStatement.Type.COUNTER, true, true); }
@Test(expected = InvalidQueryException.class) public void testMixedInLoggedBatch() { sendBatch(BatchStatement.Type.LOGGED, true, true); }
@Test(expected = InvalidQueryException.class) public void testMixedInUnLoggedBatch() { sendBatch(BatchStatement.Type.UNLOGGED, true, true); }
@Test(expected = InvalidQueryException.class) public void testNonCounterInCounterBatch() { sendBatch(BatchStatement.Type.COUNTER, false, true); }
@Test(expected = InvalidQueryException.class) public void testCounterInLoggedBatch() { sendBatch(BatchStatement.Type.LOGGED, true, false); }
@Test(expected = InvalidQueryException.class) public void matchQueryBlobTest3() { int n = cassandraUtils.query(match("blob_1", "3E0A161")).count(); assertEquals("Expected 0 results!", 0, n); }
@Test(expected = InvalidQueryException.class) public void matchQueryBlobTest4() { int n = cassandraUtils.query(match("blob_1", "3E0A1")).count(); assertEquals("Expected 0 results!", 0, n); }
@Test(expected = InvalidQueryException.class) public void matchQueryBooleanTest5() { int n = cassandraUtils.query(match("boolean_1", "else")).count(); assertEquals("Expected 0 results!", 0, n); }