/** * Convert the given Cassandra driver exception to a corresponding ConnectorException if possible, otherwise * return a generic ConnectorException. * * @param de The Cassandra driver exception * @param name The fully qualified name of the resource which was attempting to be accessed or modified at time of * error * @return A connector exception wrapping the DriverException */ public ConnectorException toConnectorException( @Nonnull @NonNull final DriverException de, @Nonnull @NonNull final QualifiedName name ) { if (de instanceof AlreadyExistsException) { final AlreadyExistsException ae = (AlreadyExistsException) de; if (ae.wasTableCreation()) { return new TableAlreadyExistsException(name, ae); } else { return new DatabaseAlreadyExistsException(name, ae); } } else { return new ConnectorException(de.getMessage(), de); } }
private void createPolygeneStateTable( String tableName ) { try { session.execute( "CREATE TABLE " + tableName + "(\n" + " " + IDENTITY_COLUMN + " text,\n" + " " + VERSION_COLUMN + " text,\n" + " " + TYPE_COLUMN + " text,\n" + " " + APP_VERSION_COLUMN + " text,\n" + " " + STORE_VERSION_COLUMN + " text,\n" + " " + LASTMODIFIED_COLUMN + " timestamp,\n" + " " + USECASE_COLUMN + " text,\n" + " " + PROPERTIES_COLUMN + " map<text,text>,\n" + " " + ASSOCIATIONS_COLUMN + " map<text,text>,\n" + " " + MANYASSOCIATIONS_COLUMN + " map<text,text>,\n" + " " + NAMEDASSOCIATIONS_COLUMN + " map<text,text>,\n" + " PRIMARY KEY ( " + IDENTITY_COLUMN + " )\n" + " )" ); } catch( AlreadyExistsException e ) { // This is OK, as we try to create on every connect(). } }
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 schemaUpdatesTableShouldNotBeCreatedIfExists() throws Exception { //given cluster.connect("system").execute("CREATE KEYSPACE " + TEST_KEYSPACE + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1 };"); Session session = cluster.connect(TEST_KEYSPACE); SessionContext sessionContext = new SessionContext(session, ConsistencyLevel.ALL, ConsistencyLevel.ALL, clusterHealth); SchemaUpdates schemaUpdates = new SchemaUpdates(sessionContext, TEST_KEYSPACE); //when schemaUpdates.initialise(); try { schemaUpdates.initialise(); } catch (AlreadyExistsException exception) { fail("Expected " + SCHEMA_UPDATES_TABLE + " table creation to be attempted only once."); } //then KeyspaceMetadata keyspaceMetadata = cluster.getMetadata().getKeyspace(TEST_KEYSPACE); assertThat(keyspaceMetadata.getTable(SCHEMA_UPDATES_TABLE)).as("table should have been created").isNotNull(); }
private void createTableIfNecessary( RetentionTable table, KeyspaceMetadata metadata ) { for ( TableMetadata meta : metadata.getTables()) { log.debug( "Comparing " + meta.getName() + " with " + table.tableName() ); if ( meta.getName().equalsIgnoreCase( table.tableName() )) { return; } } StringBuilder query = new StringBuilder(); query.append( "CREATE TABLE " ).append( table.tableName() ).append( " (" ); query.append( COL_NAME ).append( " text, " ); query.append( COL_TIME ).append( " bigint, " ); query.append( COL_VALUE ).append( " double, " ); query.append( "PRIMARY KEY (" ).append( COL_NAME ).append( ", " ).append( COL_TIME ).append( ")"); query.append( ");" ); log.debug( "Creating table with query: <" + query.toString() + ">"); try { session.execute( query.toString() ); } catch( AlreadyExistsException e ) { // Some other gatherer might have already created the same table. } }
public void createTable(String tableName, List<ColumnNameTypeValue> columns, String timestampColumnName) { StringBuilder sb = new StringBuilder(); for (Entry<String, String> entry : getStreamFieldsAndTypes(columns).entrySet()) { sb.append(addQuotes(entry.getKey())); sb.append(" "); sb.append(entry.getValue()); sb.append(","); } try { session.execute(String .format("CREATE TABLE %s.%s (%s timeuuid, %s PRIMARY KEY (%s)) WITH compression = {'sstable_compression': ''}", STREAMING.STREAMING_KEYSPACE_NAME, addQuotes(tableName), addQuotes(timestampColumnName), sb.toString(), addQuotes(timestampColumnName))); } catch (AlreadyExistsException e) { log.info("Stream table {} already exists", tableName); } }
/** * Creates the schema for the table holding <code>AclObjectIdentity</code> representations. */ public void createAoisTable() { try { session.execute("CREATE TABLE " + KEYSPACE + ".aois (" + "id varchar PRIMARY KEY," + "objId varchar," + "objClass varchar," + "isInheriting boolean," + "owner varchar," + "isOwnerPrincipal boolean," + "parentObjId varchar," + "parentObjClass varchar" + ");"); } catch (AlreadyExistsException e) { LOG.warn(e); } }
/** * Creates the schema for the table holding <code>AclEntry</code> representations. */ public void createAclsTable() { try { session.execute("CREATE TABLE " + KEYSPACE + ".acls (" + "id varchar," + "sid varchar," + "aclOrder int," + "mask int," + "isSidPrincipal boolean," + "isGranting boolean," + "isAuditSuccess boolean," + "isAuditFailure boolean," + "PRIMARY KEY (id, sid, aclOrder)" + ");"); } catch (AlreadyExistsException e) { LOG.warn(e); } }
@Test public void testShouldReturnAlreadyExistsKeyspace() throws Exception { String keyspace = "ks"; server.prime(when(query).then(alreadyExists(keyspace))); thrown.expect(AlreadyExistsException.class); thrown.expectMessage(containsString(keyspace)); query(); }
@Test public void testShouldReturnAlreadyExistsTable() throws Exception { String keyspace = "ks"; String table = "tbl"; server.prime(when(query).then(alreadyExists(keyspace, table))); thrown.expect(AlreadyExistsException.class); thrown.expectMessage(containsString(keyspace + "." + table)); query(); }
private void createKeyspace(KeyValuePersistenceSettings settings) { if (settings.getKeyspace() == null || settings.getKeyspace().trim().isEmpty()) { throw new IllegalArgumentException("Keyspace name should be specified"); } int attempt = 0; Throwable error = null; String errorMsg = "Failed to create Cassandra keyspace '" + settings.getKeyspace() + "'"; RandomSleeper sleeper = newSleeper(); String statement = settings.getKeyspaceDDLStatement(); while (attempt < CQL_EXECUTION_ATTEMPTS_COUNT) { try { session().execute(statement); return; } catch (AlreadyExistsException ignored) { return; } catch (Throwable e) { if (!CassandraHelper.isHostsAvailabilityError(e)) { throw new IgniteException(errorMsg, e); } handleHostsAvailabilityError(e, attempt, errorMsg); error = e; } sleeper.sleep(); attempt++; } throw new IgniteException(errorMsg, error); }
private void createTable(KeyValuePersistenceSettings settings) { String fullName = settings.getKeyspace() + "." + settings.getTable(); int attempt = 0; Throwable error = null; String errorMsg = "Failed to create Cassandra table '" + fullName + "'"; RandomSleeper sleeper = newSleeper(); while (attempt < CQL_EXECUTION_ATTEMPTS_COUNT) { try { session().execute(settings.getTableDDLStatement()); createTableIndexes(settings); return; } catch (AlreadyExistsException ignored) { return; } catch (Throwable e) { if (!CassandraHelper.isHostsAvailabilityError(e) && !CassandraHelperEx.isKeyspaceAbsenceError(e)) { throw new IgniteException(errorMsg, e); } if (CassandraHelperEx.isKeyspaceAbsenceError(e)) { log.warning("Failed to create Cassandra table '" + fullName + "' cause appropriate keyspace doesn't exist. Keyspace will be created automatically.", e); createKeyspace(settings); } else if (CassandraHelper.isHostsAvailabilityError(e)) { handleHostsAvailabilityError(e, attempt, errorMsg); } error = e; } sleeper.sleep(); attempt++; } throw new IgniteException(errorMsg, error); }
/** * Creates Cassandra keyspace. * * @param settings Persistence settings. */ private void createKeyspace(KeyValuePersistenceSettings settings) { int attempt = 0; Throwable error = null; String errorMsg = "Failed to create Cassandra keyspace '" + settings.getKeyspace() + "'"; while (attempt < CQL_EXECUTION_ATTEMPTS_COUNT) { try { log.info("-----------------------------------------------------------------------"); log.info("Creating Cassandra keyspace '" + settings.getKeyspace() + "'"); log.info("-----------------------------------------------------------------------\n\n" + settings.getKeyspaceDDLStatement() + "\n"); log.info("-----------------------------------------------------------------------"); session().execute(settings.getKeyspaceDDLStatement()); log.info("Cassandra keyspace '" + settings.getKeyspace() + "' was successfully created"); return; } catch (AlreadyExistsException ignored) { log.info("Cassandra keyspace '" + settings.getKeyspace() + "' already exist"); return; } catch (Throwable e) { if (!CassandraHelper.isHostsAvailabilityError(e)) throw new IgniteException(errorMsg, e); handleHostsAvailabilityError(e, attempt, errorMsg); error = e; } attempt++; } throw new IgniteException(errorMsg, error); }
public void createKeyspace(String keyspaceName, Integer replication) { try { session.execute("CREATE KEYSPACE " + keyspaceName + " WITH replication " + "= {'class':'SimpleStrategy', " + "'replication_factor':" + replication.toString() + "};"); } catch (AlreadyExistsException e) { System.out.println("Keyspace " + keyspaceName + " already exists -- ignoring!"); } }
/** * * @param keyspaceName Name of keyspace to get/create * @param keyspace The keyspace to use as a template for replication information * @return true if keyspace existed previously, false if it was created */ private boolean createKeyspaceIfNotExists(String keyspaceName, CKeyspaceDefinition keyspace, boolean alterIfExists) { Preconditions.checkNotNull(keyspace, "A template keyspace must be supplied for replication information"); Session session = cluster.connect(); //First try to create the new keyspace StringBuilder sb = new StringBuilder(); sb.append(keyspaceName); sb.append(" WITH replication = { 'class' : '"); sb.append(keyspace.getReplicationClass()); sb.append("'"); for(String key : keyspace.getReplicationFactors().keySet()) { sb.append(", '"); sb.append(key); sb.append("' : "); sb.append(keyspace.getReplicationFactors().get(key)); } sb.append("};"); try { String cql = "CREATE KEYSPACE " + sb.toString(); session.execute(cql); session.close(); logger.debug("Successfully created keyspace {}", keyspaceName); return false; } catch(AlreadyExistsException e) { logger.debug("Keyspace {} already exists", keyspaceName); // If the keyspace already existed, alter it to match the definition if(alterIfExists) { try { session.execute("ALTER KEYSPACE " + sb.toString()); } catch(Exception e2) { logger.error("Unable to alter keyspace {}", keyspaceName, e2); } } session.close(); return true; } }
/** * Creates the schema for the table holding <code>AclObjectIdentity</code> children. */ public void createChilrenTable() { try { session.execute("CREATE TABLE " + KEYSPACE + ".children (" + "id varchar," + "childId varchar," + "objId varchar," + "objClass varchar," + "PRIMARY KEY (id, childId)" + ");"); } catch (AlreadyExistsException e) { LOG.warn(e); } }
/** * Creates the schema for the 'SpringSecurityAclCassandra' keyspace. */ public void createKeyspace() { try { session.execute("CREATE KEYSPACE " + KEYSPACE + " WITH replication " + "= {'class':'" + replicationStrategy + "', 'replication_factor':" + replicationFactor + "};"); } catch (AlreadyExistsException e) { LOG.warn(e); } }
@Override public void run() { Cluster cluster = null; Session session = null; Scanner read = null; try { // Send TASK_RUNNING sendStatus(driver, Protos.TaskState.TASK_RUNNING, "Started restoring schema"); cluster = Cluster.builder().addContactPoint(daemon.getProbe().getEndpoint()).build(); session = cluster.connect(); read = new Scanner(backupStorageDriver.downloadSchema(context)); read.useDelimiter(";"); while (read.hasNext()) { try { String cqlStmt = read.next().trim(); if (cqlStmt.isEmpty()) continue; cqlStmt += ";"; session.execute(cqlStmt); } catch (AlreadyExistsException e) { LOGGER.info("Schema already exists: {}", e.toString()); } } // Send TASK_FINISHED sendStatus(driver, Protos.TaskState.TASK_FINISHED, "Finished restoring schema"); } catch (Throwable t) { // Send TASK_FAILED final String errorMessage = "Failed restoring schema. Reason: " + t; LOGGER.error(errorMessage); sendStatus(driver, Protos.TaskState.TASK_FAILED, errorMessage); } finally { if (read != null) read.close(); if (session != null) session.close(); if (cluster != null) cluster.close(); } }
/** * Creates Cassandra table. * * @param settings Persistence settings. */ private void createTable(String table, KeyValuePersistenceSettings settings) { int attempt = 0; Throwable error = null; String tableFullName = settings.getKeyspace() + "." + table; String errorMsg = "Failed to create Cassandra table '" + tableFullName + "'"; while (attempt < CQL_EXECUTION_ATTEMPTS_COUNT) { try { log.info("-----------------------------------------------------------------------"); log.info("Creating Cassandra table '" + tableFullName + "'"); log.info("-----------------------------------------------------------------------\n\n" + settings.getTableDDLStatement(table) + "\n"); log.info("-----------------------------------------------------------------------"); session().execute(settings.getTableDDLStatement(table)); log.info("Cassandra table '" + tableFullName + "' was successfully created"); return; } catch (AlreadyExistsException ignored) { log.info("Cassandra table '" + tableFullName + "' already exist"); return; } catch (Throwable e) { if (!CassandraHelper.isHostsAvailabilityError(e) && !CassandraHelper.isKeyspaceAbsenceError(e)) throw new IgniteException(errorMsg, e); if (CassandraHelper.isKeyspaceAbsenceError(e)) { log.warning("Failed to create Cassandra table '" + tableFullName + "' cause appropriate keyspace doesn't exist", e); createKeyspace(settings); } else if (CassandraHelper.isHostsAvailabilityError(e)) handleHostsAvailabilityError(e, attempt, errorMsg); error = e; } attempt++; } throw new IgniteException(errorMsg, error); }