Java 类com.datastax.driver.core.KeyspaceMetadata 实例源码

项目:spring-data-examples    文件:UserDefinedTypeIntegrationTest.java   
/**
 * Insert a row with a raw User-defined type.
 */
@Test
public void insertRawUdt() {

    KeyspaceMetadata keyspaceMetadata = adminOperations.getKeyspaceMetadata();
    UserType address = keyspaceMetadata.getUserType("address");

    UDTValue udtValue = address.newValue();
    udtValue.setString("street", "308 Negra Arroyo Lane");
    udtValue.setString("zip", "87104");
    udtValue.setString("city", "Albuquerque");

    Person person = new Person();
    person.setId(42);
    person.setFirstname("Walter");
    person.setLastname("White");

    person.setAlternative(udtValue);

    operations.insert(person);

    Person loaded = operations.selectOne("SELECT * FROM person WHERE id = 42", Person.class);

    assertThat(loaded.getAlternative().getString("zip")).isEqualTo("87104");
}
项目:metacat    文件:CassandraConnectorTableService.java   
/**
 * {@inheritDoc}
 */
@Override
public TableInfo get(@Nonnull @NonNull final ConnectorRequestContext context,
                     @Nonnull @NonNull final QualifiedName name) {
    final String keyspace = name.getDatabaseName();
    final String table = name.getTableName();
    log.debug("Attempting to get metadata for Cassandra table {}.{} for request {}", keyspace, table, context);
    try {
        final KeyspaceMetadata keyspaceMetadata = this.getCluster().getMetadata().getKeyspace(keyspace);
        if (keyspaceMetadata == null) {
            throw new DatabaseNotFoundException(name);
        }
        final TableMetadata tableMetadata = keyspaceMetadata.getTable(table);
        if (tableMetadata == null) {
            throw new TableNotFoundException(name);
        }

        final TableInfo tableInfo = this.getTableInfo(name, tableMetadata);
        log.debug("Successfully got metadata for Cassandra table {}.{} for request {}", keyspace, table, context);
        return tableInfo;
    } catch (final DriverException de) {
        log.error(de.getMessage(), de);
        throw this.getExceptionMapper().toConnectorException(de, name);
    }
}
项目:metacat    文件:CassandraConnectorDatabaseService.java   
/**
 * {@inheritDoc}
 */
@Override
public DatabaseInfo get(
    @Nonnull @NonNull final ConnectorRequestContext context,
    @Nonnull @NonNull final QualifiedName name
) {
    final String keyspace = name.getDatabaseName();
    log.debug("Attempting to get keyspace metadata for keyspace {} for request {}", keyspace, context);
    try {
        final KeyspaceMetadata keyspaceMetadata = this.getCluster().getMetadata().getKeyspace(keyspace);
        if (keyspaceMetadata == null) {
            throw new DatabaseNotFoundException(name);
        }

        log.debug("Successfully found the keyspace metadata for {} for request {}", name, context);
        return DatabaseInfo.builder().name(name).build();
    } catch (final DriverException de) {
        log.error(de.getMessage(), de);
        throw this.getExceptionMapper().toConnectorException(de, name);
    }
}
项目:para-dao-cassandra    文件:CassandraUtils.java   
/**
 * Checks if the main table exists in the database.
 * @param appid name of the {@link com.erudika.para.core.App}
 * @return true if the table exists
 */
public static boolean existsTable(String appid) {
    if (StringUtils.isBlank(appid)) {
        return false;
    }
    if (cluster == null) {
        throw new IllegalStateException("Cassandra client not initialized.");
    }
    try {
        KeyspaceMetadata ks = cluster.getMetadata().getKeyspace(DBNAME);
        TableMetadata table = ks.getTable(getTableNameForAppid(appid));
        return table != null && table.getName() != null;
    } catch (Exception e) {
        return false;
    }
}
项目:zipkin    文件:DefaultSessionFactory.java   
private static void initializeUDTs(Session session) {
  Schema.ensureExists(DEFAULT_KEYSPACE + "_udts", session);
  MappingManager mapping = new MappingManager(session);

  // The UDTs are hardcoded against the zipkin keyspace.
  // If a different keyspace is being used the codecs must be re-applied to this different keyspace
  TypeCodec<TraceIdUDT> traceIdCodec = mapping.udtCodec(TraceIdUDT.class);
  TypeCodec<EndpointUDT> endpointCodec = mapping.udtCodec(EndpointUDT.class);
  TypeCodec<AnnotationUDT> annoCodec = mapping.udtCodec(AnnotationUDT.class);
  TypeCodec<BinaryAnnotationUDT> bAnnoCodec = mapping.udtCodec(BinaryAnnotationUDT.class);

  KeyspaceMetadata keyspace =
      session.getCluster().getMetadata().getKeyspace(session.getLoggedKeyspace());

  session.getCluster().getConfiguration().getCodecRegistry()
      .register(
          new TypeCodecImpl(keyspace.getUserType("trace_id"), TraceIdUDT.class, traceIdCodec))
      .register(
          new TypeCodecImpl(keyspace.getUserType("endpoint"), EndpointUDT.class, endpointCodec))
      .register(
          new TypeCodecImpl(keyspace.getUserType("annotation"), AnnotationUDT.class, annoCodec))
      .register(
          new TypeCodecImpl(keyspace.getUserType("binary_annotation"), BinaryAnnotationUDT.class,
              bAnnoCodec));
}
项目:zipkin    文件:Schema.java   
static Metadata readMetadata(Session session) {
  KeyspaceMetadata keyspaceMetadata = getKeyspaceMetadata(session);

  Map<String, String> replication = keyspaceMetadata.getReplication();
  if ("SimpleStrategy".equals(replication.get("class")) && "1".equals(
      replication.get("replication_factor"))) {
    LOG.warn("running with RF=1, this is not suitable for production. Optimal is 3+");
  }
  String compactionClass =
      keyspaceMetadata.getTable("traces").getOptions().getCompaction().get("class");
  boolean hasDefaultTtl = hasUpgrade1_defaultTtl(keyspaceMetadata);
  if (!hasDefaultTtl) {
    LOG.warn("schema lacks default ttls: apply {}, or set CassandraStorage.ensureSchema=true",
        UPGRADE_1);
  }
  return new Metadata(compactionClass, hasDefaultTtl);
}
项目:music    文件:MusicClient.java   
public boolean insertRow(String tablename, Map<String, Object> valuesMap, Map<String, String> consistencyInfo, JsonInsert insObj) throws Exception {
    // Note: https://docs.datastax.com/en/cql/3.0/cql/cql_reference/insert_r.html
    String[] parts = tablename.split("\\.");
    KeyspaceMetadata ks = cluster.getMetadata().getKeyspace(parts[0]);
    TableMetadata tableInfo =  ks.getTable(parts[1]);

    StringBuilder fields = new StringBuilder();
    StringBuilder values = new StringBuilder();
    String prefix = "";
    for (String key : valuesMap.keySet()) {
        fields.append(prefix).append(key);
        Object valueObj  = valuesMap.get(key);
        DataType colType = tableInfo.getColumn(key).getType();
        values.append(prefix).append(convertToSqlDataType(colType, valueObj));
        prefix = ", ";
    }

    String suffix = getTTLSuffix(insObj);
    String query = String.format("INSERT INTO %s (%s) VALUES (%s)%s;", tablename, fields.toString(), values.toString(), suffix);
    LOG.debug(query);

    String consistency = extractConsistencyInfo(tablename, consistencyInfo);
    executeCreateQuery(query, consistency);
    return false;
}
项目:brein-time-utilities    文件:CassandraIntervalCollectionPersistor.java   
protected void createColumnFamily() {
    final String ks = getKeySpace();
    final String cf = getColumnFamily();

    final KeyspaceMetadata keySpaceMeta = this.cluster.getMetadata().getKeyspace(ks);
    final TableMetadata tableMetadata = keySpaceMeta.getTable(cf);

    // check if the table exists
    if (tableMetadata != null) {
        return;
    }

    final String stmt = String.format("CREATE TABLE %s (\n" +
            "  " + KEY_COLUMN + " text,\n" +
            "  " + COLL_COLUMN + " blob,\n" +
            "  PRIMARY KEY (" + KEY_COLUMN + ")\n" +
            ");", cf);

    getSession().execute(stmt);
}
项目:camunda-engine-cassandra    文件:CassandraProcessEngineConfiguration.java   
protected void initCassandraClient() {
  if(keyspace == null) {
    keyspace = DEFAULT_KEYSPACE;
  }

  if(cluster == null) {
    cluster = Cluster.builder()
      .addContactPoint(cassandraContactPoint)
      .withTimestampGenerator(new AtomicMonotonicTimestampGenerator())
      .build();
    hasOpenedCluster = true;
  }

  // make sure the keyspace exists (create it with default replication settings otherwise)
  KeyspaceMetadata existingKeyspace = cluster.getMetadata().getKeyspace("camunda");
  if(existingKeyspace == null) {
    final Session session = cluster.connect();
    session.execute(String.format("CREATE keyspace %s WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : " + replicationFactor + " };", keyspace));
    session.close();
  }

  if(session == null) {
    session = cluster.connect(keyspace);
  }
}
项目:presto    文件:CassandraSession.java   
private TableMetadata getTableMetadata(SchemaTableName schemaTableName)
{
    String schemaName = schemaTableName.getSchemaName();
    String tableName = schemaTableName.getTableName();

    KeyspaceMetadata keyspaceMetadata = getCheckedKeyspaceMetadata(schemaName);
    TableMetadata tableMetadata = keyspaceMetadata.getTable(tableName);
    if (tableMetadata != null) {
        return tableMetadata;
    }

    for (TableMetadata table : keyspaceMetadata.getTables()) {
        if (table.getName().equalsIgnoreCase(tableName)) {
            return table;
        }
    }
    throw new TableNotFoundException(schemaTableName);
}
项目:cqlmigrate    文件:SchemaUpdatesTest.java   
@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();
}
项目:cassandra-jdbc-wrapper    文件:MetadataResultSets.java   
public  CassandraMetadataResultSet makeSchemas(CassandraStatement statement, String schemaPattern) throws SQLException
{

    // TABLE_SCHEM String => schema name
    // TABLE_CATALOG String => catalog name (may be null)

    final ArrayList<MetadataRow> schemas = Lists.newArrayList();
    List<KeyspaceMetadata> keyspaces = statement.connection.getClusterMetadata().getKeyspaces();

    for(KeyspaceMetadata keyspace:keyspaces){
        if ("%".equals(schemaPattern)) schemaPattern = null;
        if((schemaPattern==null?keyspace.getName():schemaPattern).equals(keyspace.getName())){
            MetadataRow row = new MetadataRow().addEntry("TABLE_SCHEM", keyspace.getName()).addEntry("TABLE_CATALOG", statement.connection.getCatalog());
            schemas.add(row);
        }

    }

    CassandraMetadataResultSet result = new CassandraMetadataResultSet(statement,new MetadataResultSet().setRows(schemas));
    return result;

}
项目:Simba    文件:CassandraHandler.java   
public List<Column> getSchema(String keySpace, String tableName) {
    Metadata m = session.getCluster().getMetadata();
    KeyspaceMetadata km = m.getKeyspace(keySpace);
    if (km == null)
        return null;
    TableMetadata tm = km.getTable(tableName);
    if (tm == null)
        return null;
    // build schema
    List<Column> columns = new LinkedList<Column>();
    for (ColumnMetadata cm : tm.getColumns()) {
        if (!meta.contains(cm.getName()))
            columns.add(Column.newBuilder().setName(cm.getName())
                    .setType(toSimbaType(cm.getType().toString())).build());
    }

    return columns;

}
项目:bifroest    文件:PersistentCassandraDrain.java   
@Override
public void output( Collection<Metric> metrics ) {
    if( metrics.size() == 0 ) {
        return;
    }

    Map<RetentionTable, BatchStatement> stms = LazyMap.<RetentionTable, BatchStatement>lazyMap( new HashMap<>(), () -> new BatchStatement() );
    for ( Metric metric : metrics ) {
        insertMetricIntoBatch( metric, stms );
    }
    KeyspaceMetadata metadata = cluster.getMetadata().getKeyspace( keyspace );
    for (RetentionTable table : stms.keySet()) {
        createTableIfNecessary( table, metadata );
    }
    for ( BatchStatement batch : stms.values() ) {
        try {
            session.execute( batch );
        } catch ( WriteTimeoutException e ) {
            log.info( "WriteTimeoutException while sending Metrics to cassandra." );
            log.info( e.getMessage() );
            log.info( "According to http://www.datastax.com/dev/blog/how-cassandra-deals-with-replica-failure, this is harmless" );
        }
    }
    EventBusManager.fire( new DrainMetricOutputEvent( ( new PersistentCassandraDrainFactory<>().handledType() ), metrics.size() ) );
}
项目:bifroest    文件:PersistentCassandraDrain.java   
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.
    }
}
项目:glowroot    文件:SchemaUpgrade.java   
private static @Nullable Integer getSchemaVersion(Session session, KeyspaceMetadata keyspace)
        throws Exception {
    ResultSet results =
            session.execute("select schema_version from schema_version where one = 1");
    Row row = results.one();
    if (row != null) {
        return row.getInt(0);
    }
    TableMetadata agentTable = keyspace.getTable("agent");
    if (agentTable != null && agentTable.getColumn("system_info") != null) {
        // special case, this is glowroot version 0.9.1, the only version supporting upgrades
        // prior to schema_version table
        return 1;
    }
    // new installation
    return null;
}
项目:glowroot    文件:SyntheticResultDaoIT.java   
@BeforeClass
public static void setUp() throws Exception {
    SharedSetupRunListener.startCassandra();
    cluster = Clusters.newCluster();
    session = new Session(cluster.newSession());
    session.createKeyspaceIfNotExists("glowroot_unit_tests");
    session.execute("use glowroot_unit_tests");
    KeyspaceMetadata keyspaceMetadata =
            cluster.getMetadata().getKeyspace("glowroot_unit_tests");

    clusterManager = ClusterManager.create();
    CentralConfigDao centralConfigDao = new CentralConfigDao(session, clusterManager);
    AgentConfigDao agentConfigDao = new AgentConfigDao(session, clusterManager);
    UserDao userDao = new UserDao(session, keyspaceMetadata, clusterManager);
    RoleDao roleDao = new RoleDao(session, keyspaceMetadata, clusterManager);
    ConfigRepositoryImpl configRepository =
            new ConfigRepositoryImpl(centralConfigDao, agentConfigDao, userDao, roleDao, "");
    syntheticResultDao =
            new SyntheticResultDaoImpl(session, configRepository, Clock.systemClock());
}
项目:glowroot    文件:AggregateDaoIT.java   
@BeforeClass
public static void setUp() throws Exception {
    SharedSetupRunListener.startCassandra();
    cluster = Clusters.newCluster();
    session = new Session(cluster.newSession());
    session.createKeyspaceIfNotExists("glowroot_unit_tests");
    session.execute("use glowroot_unit_tests");
    KeyspaceMetadata keyspaceMetadata =
            cluster.getMetadata().getKeyspace("glowroot_unit_tests");

    clusterManager = ClusterManager.create();
    CentralConfigDao centralConfigDao = new CentralConfigDao(session, clusterManager);
    agentConfigDao = new AgentConfigDao(session, clusterManager);
    UserDao userDao = new UserDao(session, keyspaceMetadata, clusterManager);
    RoleDao roleDao = new RoleDao(session, keyspaceMetadata, clusterManager);
    ConfigRepositoryImpl configRepository =
            new ConfigRepositoryImpl(centralConfigDao, agentConfigDao, userDao, roleDao, "");
    TransactionTypeDao transactionTypeDao =
            new TransactionTypeDao(session, configRepository, clusterManager);
    FullQueryTextDao fullQueryTextDao = new FullQueryTextDao(session, configRepository);
    agentDao = new AgentDao(session, agentConfigDao, configRepository, Clock.systemClock());
    aggregateDao = new AggregateDaoWithV09Support(ImmutableSet.of(), 0, 0, Clock.systemClock(),
            new AggregateDaoImpl(session, agentDao, transactionTypeDao, fullQueryTextDao,
                    configRepository, Clock.systemClock()));
}
项目:glowroot    文件:GaugeValueDaoIT.java   
@BeforeClass
public static void setUp() throws Exception {
    SharedSetupRunListener.startCassandra();
    cluster = Clusters.newCluster();
    session = new Session(cluster.newSession());
    session.createKeyspaceIfNotExists("glowroot_unit_tests");
    session.execute("use glowroot_unit_tests");
    KeyspaceMetadata keyspaceMetadata =
            cluster.getMetadata().getKeyspace("glowroot_unit_tests");

    clusterManager = ClusterManager.create();
    CentralConfigDao centralConfigDao = new CentralConfigDao(session, clusterManager);
    agentConfigDao = new AgentConfigDao(session, clusterManager);
    UserDao userDao = new UserDao(session, keyspaceMetadata, clusterManager);
    RoleDao roleDao = new RoleDao(session, keyspaceMetadata, clusterManager);
    ConfigRepositoryImpl configRepository = new ConfigRepositoryImpl(centralConfigDao,
            agentConfigDao, userDao, roleDao, "");
    gaugeValueDao = new GaugeValueDaoWithV09Support(ImmutableSet.of(), 0, Clock.systemClock(),
            new GaugeValueDaoImpl(session, configRepository, Clock.systemClock()));
}
项目:glowroot    文件:ConfigRepositoryIT.java   
@BeforeClass
public static void setUp() throws Exception {
    SharedSetupRunListener.startCassandra();
    cluster = Clusters.newCluster();
    session = new Session(cluster.newSession());
    session.createKeyspaceIfNotExists("glowroot_unit_tests");
    session.execute("use glowroot_unit_tests");
    session.execute("drop table if exists agent_config");
    session.execute("drop table if exists user");
    session.execute("drop table if exists role");
    session.execute("drop table if exists central_config");
    session.execute("drop table if exists agent");
    KeyspaceMetadata keyspaceMetadata =
            cluster.getMetadata().getKeyspace("glowroot_unit_tests");

    clusterManager = ClusterManager.create();
    CentralConfigDao centralConfigDao = new CentralConfigDao(session, clusterManager);
    agentConfigDao = new AgentConfigDao(session, clusterManager);
    UserDao userDao = new UserDao(session, keyspaceMetadata, clusterManager);
    RoleDao roleDao = new RoleDao(session, keyspaceMetadata, clusterManager);
    configRepository =
            new ConfigRepositoryImpl(centralConfigDao, agentConfigDao, userDao, roleDao, "");
}
项目:ingestion    文件:TestCassandraTable.java   
private void mockTableMetadata() {
  final ColumnMetadata idColumn = mock(ColumnMetadata.class);
  when(idColumn.getName()).thenReturn("id");
  when(idColumn.getType()).thenReturn(DataType.cint());

  final ColumnMetadata textColumn = mock(ColumnMetadata.class);
  when(textColumn.getName()).thenReturn("text_col");
  when(textColumn.getType()).thenReturn(DataType.text());

  final KeyspaceMetadata keyspaceMetadata = mock(KeyspaceMetadata.class);
  when(keyspaceMetadata.getName()).thenReturn("my_keyspace");

  when(tableMetadata.getName()).thenReturn("my_table");
  when(tableMetadata.getColumns()).thenReturn(ImmutableList.of(idColumn, textColumn));
  when(tableMetadata.getKeyspace()).thenReturn(keyspaceMetadata);
  when(tableMetadata.getPrimaryKey()).thenReturn(ImmutableList.of(idColumn));
}
项目:hecuba    文件:DataStaxBasedSharedHecubaClientManager.java   
private String getKeyColumn(String columnFamily) {
    KeyspaceMetadata keyspaceMetadata = session.getCluster().getMetadata().getKeyspace(keyspace);
    TableMetadata tableMetadata = keyspaceMetadata.getTable(columnFamily);

    if (tableMetadata == null) {
        return null;
    }

    for (String key : new String[] { "\"KEY\"", "key" }) {
        if (tableMetadata.getColumn(key) != null) {
            return key;
        }
    }

    return null;
}
项目:memnon    文件:JsonMarshaller.java   
@SuppressWarnings("unchecked")
public static JSONArray marshallKeyspaces(List<KeyspaceMetadata> keyspaces, boolean flatten)
        throws UnsupportedEncodingException {
    JSONArray keyspaceJson = new JSONArray();
    if (flatten) {
        for (KeyspaceMetadata keyspace : keyspaces) {
            for (TableMetadata table : keyspace.getTables()) {
                JSONObject json = new JSONObject();
                json.put("keyspace", keyspace.getName());
                json.put("columnFamily", table.getName());
                keyspaceJson.add(json);
            }
        }
    } 
    return keyspaceJson;
}
项目:izettle-toolbox    文件:SchemaVersionUpdaterWithDatastaxDriver.java   
private void ensureTableExists() {
    KeyspaceMetadata keyspaceMetadata =
        session.getCluster().getMetadata().getKeyspace(session.getLoggedKeyspace());
    TableMetadata tableMetadata = keyspaceMetadata.getTable(TABLE_NAME);

    if (tableMetadata != null) {
        LOG.debug("Versioning column family already exists, skipping creation.");
        ensureTableSchema(tableMetadata);
        return;
    }

    LOG.info("Creating versioning column family.");
    session.execute(
        "CREATE TABLE " + TABLE_NAME + " ("
            + "key text PRIMARY KEY,"
            + "executed timestamp"
            + ");");

    LOG.debug("Versioning column family created.");
}
项目:izettle-toolbox    文件:SchemaVersionUpdaterWithDatastaxDriverTest.java   
@Test
public void doNotApplyScriptAlreadyApplied() throws IOException, URISyntaxException {
    load("dataset-empty.yaml");

    Session session = getSession();
    createSchemaMigrationTable(session);
    session.execute(QueryBuilder.insertInto(TABLE_NAME)
        .value("key", "0003-before-the-big-bang.cql")
        .value("executed", new Date())
    );

    SchemaVersionUpdaterWithDatastaxDriver updater = new SchemaVersionUpdaterWithDatastaxDriver(session);
    updater.applyFromResources(SchemaVersionUpdaterWithDatastaxDriverTest.class, "migrations");

    KeyspaceMetadata keyspaceMetadata =
        session.getCluster().getMetadata().getKeyspace(session.getLoggedKeyspace());
    assertThat(keyspaceMetadata.getTable("galaxies")).isNull();
}
项目:metamodel    文件:CassandraDataContext.java   
/**
 * Performs an analysis of the given keyspace in a Cassandra cluster
 * {@link Cluster} instance and detects the cassandra types structure based
 * on the metadata provided by the datastax cassandra java client.
 *
 * @see #detectTable(TableMetadata)
 *
 * @param cluster
 *            the cluster to inspect
 * @param keyspaceName
 * @return a mutable schema instance, useful for further fine tuning by the
 *         user.
 */
public static SimpleTableDef[] detectSchema(Cluster cluster, String keyspaceName) {
    final Metadata metadata = cluster.getMetadata();
    final KeyspaceMetadata keyspace = metadata.getKeyspace(keyspaceName);
    if (keyspace == null) {
        throw new IllegalArgumentException("Keyspace '" + keyspaceName + "' does not exist in the database");
    }
    final Collection<TableMetadata> tables = keyspace.getTables();
    final SimpleTableDef[] result = new SimpleTableDef[tables.size()];
    int i = 0;
    for (final TableMetadata tableMetaData : tables) {
        final SimpleTableDef table = detectTable(tableMetaData);
        result[i] = table;
        i++;
    }
    return result;
}
项目:state-channels    文件:DatabaseCleaner.java   
public void clean() {
    log.info("Cleaning all tables");
    for (KeyspaceMetadata keyspaceMetadata : session.getCluster().getMetadata().getKeyspaces()) {
        String keyspace = keyspaceMetadata.getName();
        if (keyspace.startsWith("system")) {
            continue;
        }
        for (TableMetadata metadata : keyspaceMetadata.getTables()) {
            String statement = "TRUNCATE TABLE " + keyspace + "." + metadata.getName();
            session.execute(statement);
        }
    }
}
项目:metacat    文件:CassandraConnectorDatabaseService.java   
/**
 * {@inheritDoc}
 */
@Override
public List<QualifiedName> listViewNames(
    @Nonnull @NonNull final ConnectorRequestContext context,
    @Nonnull @NonNull final QualifiedName databaseName
) {
    final String catalogName = databaseName.getCatalogName();
    final String keyspace = databaseName.getDatabaseName();
    log.debug("Attempting to get materialized view names for keyspace {} due to request {}", keyspace, context);
    try {
        final KeyspaceMetadata keyspaceMetadata = this.getCluster().getMetadata().getKeyspace(keyspace);
        if (keyspaceMetadata == null) {
            throw new DatabaseNotFoundException(databaseName);
        }

        final ImmutableList.Builder<QualifiedName> viewsBuilder = ImmutableList.builder();
        for (final MaterializedViewMetadata view : keyspaceMetadata.getMaterializedViews()) {
            viewsBuilder.add(
                QualifiedName.ofView(catalogName, keyspace, view.getBaseTable().getName(), view.getName())
            );
        }

        final List<QualifiedName> views = viewsBuilder.build();
        log.debug("Successfully found {} views for keyspace {} due to request {}", views.size(), keyspace, context);
        return views;
    } catch (final DriverException de) {
        log.error(de.getMessage(), de);
        throw this.getExceptionMapper().toConnectorException(de, databaseName);
    }
}
项目:metacat    文件:CassandraConnectorDatabaseService.java   
/**
 * {@inheritDoc}
 */
@Override
public List<QualifiedName> listNames(
    @Nonnull @NonNull final ConnectorRequestContext context,
    @Nonnull @NonNull final QualifiedName name,
    @Nullable final QualifiedName prefix,
    @Nullable final Sort sort,
    @Nullable final Pageable pageable
) {
    log.debug("Attempting to list keyspaces for request {}", context);
    try {
        final List<QualifiedName> names = Lists.newArrayList();
        for (final KeyspaceMetadata keyspace : this.getCluster().getMetadata().getKeyspaces()) {
            final String keyspaceName = keyspace.getName();
            if (prefix != null && !keyspaceName.startsWith(prefix.getDatabaseName())) {
                continue;
            }
            names.add(QualifiedName.ofDatabase(name.getCatalogName(), keyspaceName));
        }

        if (sort != null) {
            // We can only really sort by the database name at this level so ignore SortBy field
            final Comparator<QualifiedName> comparator = Comparator.comparing(QualifiedName::getDatabaseName);
            ConnectorUtils.sort(names, sort, comparator);
        }

        final List<QualifiedName> results = ConnectorUtils.paginate(names, pageable);
        log.debug("Finished listing keyspaces for request {}", context);
        return results;
    } catch (final DriverException de) {
        log.error(de.getMessage(), de);
        throw this.getExceptionMapper().toConnectorException(de, name);
    }
}
项目:zipkin    文件:Schema.java   
static Metadata readMetadata(Session session) {
  KeyspaceMetadata keyspaceMetadata = getKeyspaceMetadata(session);

  Map<String, String> replication = keyspaceMetadata.getReplication();
  if ("SimpleStrategy".equals(replication.get("class")) && "1".equals(
      replication.get("replication_factor"))) {
    LOG.warn("running with RF=1, this is not suitable for production. Optimal is 3+");
  }
  String compactionClass =
      keyspaceMetadata.getTable("traces").getOptions().getCompaction().get("class");

  return new Metadata(compactionClass);
}
项目:zipkin    文件:Schema.java   
static KeyspaceMetadata getKeyspaceMetadata(Session session) {
  String keyspace = session.getLoggedKeyspace();
  Cluster cluster = session.getCluster();
  KeyspaceMetadata keyspaceMetadata = cluster.getMetadata().getKeyspace(keyspace);

  if (keyspaceMetadata == null) {
    throw new IllegalStateException(String.format(
        "Cannot read keyspace metadata for give keyspace: %s and cluster: %s",
        keyspace, cluster.getClusterName()));
  }
  return keyspaceMetadata;
}
项目:zipkin    文件:Schema.java   
static KeyspaceMetadata ensureExists(String keyspace, Session session) {
  KeyspaceMetadata result = session.getCluster().getMetadata().getKeyspace(keyspace);
  if (result == null || result.getTable("traces") == null) {
    LOG.info("Installing schema {}", SCHEMA_RESOURCE);
    applyCqlFile(keyspace, session, SCHEMA_RESOURCE);
    // refresh metadata since we've installed the schema
    result = session.getCluster().getMetadata().getKeyspace(keyspace);
  }
  return result;
}
项目:zipkin    文件:EnsureSchemaTest.java   
@Test public void installsTablesWhenMissing() {
  session.execute("CREATE KEYSPACE " + keyspace
      + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'};");

  Schema.ensureExists(keyspace, session);

  KeyspaceMetadata metadata = session.getCluster().getMetadata().getKeyspace(keyspace);
  assertThat(metadata).isNotNull();
}
项目:zipkin    文件:Schema.java   
static KeyspaceMetadata getKeyspaceMetadata(Session session) {
  String keyspace = session.getLoggedKeyspace();
  Cluster cluster = session.getCluster();
  KeyspaceMetadata keyspaceMetadata = cluster.getMetadata().getKeyspace(keyspace);

  if (keyspaceMetadata == null) {
    throw new IllegalStateException(String.format(
        "Cannot read keyspace metadata for give keyspace: %s and cluster: %s",
        keyspace, cluster.getClusterName()));
  }
  return keyspaceMetadata;
}
项目:zipkin    文件:Schema.java   
static void ensureExists(String keyspace, Session session) {
  KeyspaceMetadata keyspaceMetadata = session.getCluster().getMetadata().getKeyspace(keyspace);
  if (keyspaceMetadata == null || keyspaceMetadata.getTable("traces") == null) {
    LOG.info("Installing schema {}", SCHEMA);
    applyCqlFile(keyspace, session, SCHEMA);
    // refresh metadata since we've installed the schema
    keyspaceMetadata = session.getCluster().getMetadata().getKeyspace(keyspace);
  }
  if (!hasUpgrade1_defaultTtl(keyspaceMetadata)) {
    LOG.info("Upgrading schema {}", UPGRADE_1);
    applyCqlFile(keyspace, session, UPGRADE_1);
  }
}
项目:zipkin    文件:EnsureSchemaTest.java   
@Test public void installsKeyspaceWhenMissing() {
  Schema.ensureExists(keyspace, session);

  KeyspaceMetadata metadata = session.getCluster().getMetadata().getKeyspace(keyspace);
  assertThat(metadata).isNotNull();
  assertThat(Schema.hasUpgrade1_defaultTtl(metadata)).isTrue();
}
项目:zipkin    文件:EnsureSchemaTest.java   
@Test public void installsTablesWhenMissing() {
  session.execute("CREATE KEYSPACE " + keyspace
      + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'};");

  Schema.ensureExists(keyspace, session);

  KeyspaceMetadata metadata = session.getCluster().getMetadata().getKeyspace(keyspace);
  assertThat(metadata).isNotNull();
  assertThat(Schema.hasUpgrade1_defaultTtl(metadata)).isTrue();
}
项目:zipkin    文件:EnsureSchemaTest.java   
@Test public void upgradesOldSchema() {
  Schema.applyCqlFile(keyspace, session, "/cassandra-schema-cql3-original.txt");

  Schema.ensureExists(keyspace, session);

  KeyspaceMetadata metadata = session.getCluster().getMetadata().getKeyspace(keyspace);
  assertThat(metadata).isNotNull();
  assertThat(Schema.hasUpgrade1_defaultTtl(metadata)).isTrue();
}
项目:dcos-cassandra-service    文件:BackupSchema.java   
@Override
public void run() {
    Cluster cluster = null;

    try {
        // Send TASK_RUNNING
        sendStatus(driver, Protos.TaskState.TASK_RUNNING,
                "Started taking schema backup");

        cluster = Cluster.builder().addContactPoint(daemon.getProbe().getEndpoint()).build();
        final List<String> keyspaces = StorageUtil.filterSystemKeyspaces(daemon.getNonSystemKeySpaces());

        if (keyspaces.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (String keyspace : keyspaces) {
                LOGGER.info("Taking schema backup for keyspace: {}", keyspace);
                KeyspaceMetadata ksm = cluster.getMetadata().getKeyspace(keyspace);
                sb.append(ksm.exportAsString()).append(System.getProperty("line.separator"));
            }
            backupStorageDriver.uploadSchema(context, sb.toString());
        }

        // Send TASK_FINISHED
        sendStatus(driver, Protos.TaskState.TASK_FINISHED,
                "Finished taking schema backup for keyspaces: " + keyspaces);
    } catch (Throwable t){
        LOGGER.error("Schema backup failed. Reason: ", t);
        sendStatus(driver, Protos.TaskState.TASK_FAILED, t.getMessage());
    } finally {
        if (cluster != null)
            cluster.close();
    }
}
项目:cassandra-CQL-exporter    文件:DatabaseValidator.java   
static void validateTableName(String tableName, KeyspaceMetadata keyspace) {
    if (!Strings.isNullOrEmpty(tableName)) {
        TableMetadata table = keyspace.getTable(tableName);
        if (table == null) {
            throw new IllegalArgumentException("table \"" + tableName + "\" does not existed!");
        }
    }
}