List of usage examples for org.apache.cassandra.cql3 UntypedResultSet one
public abstract Row one();
From source file:org.elassandra.cluster.InternalCassandraClusterService.java
License:Apache License
public boolean processConditional(final ConsistencyLevel cl, final ConsistencyLevel serialCl, final String query, Object... values) throws RequestExecutionException, RequestValidationException, InvalidRequestException { try {/* ww w . j a v a 2 s . c o m*/ UntypedResultSet result = process(cl, serialCl, query, values); if (serialCl != null) { if (!result.isEmpty()) { Row row = result.one(); if (row.has("[applied]")) { return row.getBoolean("[applied]"); } } return false; } return true; } catch (Exception e) { logger.error("Failed to process query=" + query + " values=" + Arrays.toString(values), e); throw e; } }
From source file:org.elassandra.cluster.InternalCassandraClusterService.java
License:Apache License
public Pair<List<String>, List<String>> getUDTInfo(final String ksName, final String typeName) { try {/*from w w w. j a v a 2 s . c o m*/ UntypedResultSet result = QueryProcessor.executeInternal( "SELECT field_names, field_types FROM system.schema_usertypes WHERE keyspace_name = ? AND type_name = ?", new Object[] { ksName, typeName }); Row row = result.one(); if ((row != null) && row.has("field_names")) { List<String> field_names = row.getList("field_names", UTF8Type.instance); List<String> field_types = row.getList("field_types", UTF8Type.instance); return Pair.<List<String>, List<String>>create(field_names, field_types); } } catch (Exception e) { } return null; }
From source file:org.elassandra.cluster.InternalCassandraClusterService.java
License:Apache License
public static MapType<?, ?> getMapType(final String ksName, final String cfName, final String colName) { try {/*from w w w. j a v a2s. co m*/ UntypedResultSet result = QueryProcessor.executeInternal( "SELECT validator FROM system.schema_columns WHERE keyspace_name = ? AND columnfamily_name = ? AND column_name = ?", new Object[] { ksName, cfName, colName }); Row row = result.one(); if ((row != null) && row.has("validator")) { AbstractType<?> type = TypeParser.parse(row.getString("validator")); if (type instanceof MapType) { return (MapType<?, ?>) type; } } } catch (Exception e) { } return null; }
From source file:org.elassandra.cluster.InternalCassandraClusterService.java
License:Apache License
public Engine.GetResult fetchSourceInternal(final String ksName, String index, String type, String id) throws IOException { DocPrimaryKey docPk = parseElasticId(index, type, id); String[] columns = mappedColumns(index, type, docPk.isStaticDocument, true); UntypedResultSet result = fetchRowInternal(ksName, index, type, docPk, columns); if (!result.isEmpty()) { Map<String, Object> sourceMap = rowAsMap(index, type, result.one()); BytesReference source = XContentFactory.contentBuilder(XContentType.JSON).map(sourceMap).bytes(); Long timestamp = 0L;/*from w w w . jav a 2 s .com*/ if (sourceMap.get(TimestampFieldMapper.NAME) != null) { timestamp = (Long) sourceMap.get(TimestampFieldMapper.NAME); } Long ttl = 0L; if (sourceMap.get(TTLFieldMapper.NAME) != null) { ttl = (Long) sourceMap.get(TTLFieldMapper.NAME); } Translog.Source transloSource = new Translog.Source(source, (String) sourceMap.get(RoutingFieldMapper.NAME), (String) sourceMap.get(ParentFieldMapper.NAME), timestamp, ttl); return new Engine.GetResult(true, 1L, transloSource); } return new Engine.GetResult(false, -1, null); }
From source file:org.elassandra.cluster.InternalCassandraClusterService.java
License:Apache License
/** * Should only be used after a SCHEMA change. * @throws IOException //from ww w .j ava 2 s. c o m */ @Override public MetaData readMetaDataAsComment() throws NoPersistedMetaDataException { try { String query = String.format((Locale) null, "SELECT comment FROM system.schema_columnfamilies WHERE keyspace_name='%s' AND columnfamily_name='%s'", this.elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE); UntypedResultSet result = QueryProcessor.executeInternal(query); if (result.isEmpty()) throw new NoPersistedMetaDataException("Failed to read comment from " + elasticAdminKeyspaceName + "+" + ELASTIC_ADMIN_METADATA_TABLE); String metadataString = result.one().getString(0); logger.debug("Recover metadata from {}.{} = {}", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE, metadataString); return parseMetaDataString(metadataString); } catch (RequestValidationException | RequestExecutionException e) { throw new NoPersistedMetaDataException( "Failed to read comment from " + elasticAdminKeyspaceName + "+" + ELASTIC_ADMIN_METADATA_TABLE, e); } }
From source file:org.elassandra.cluster.InternalCassandraClusterService.java
License:Apache License
@Override public MetaData readMetaDataAsRow(ConsistencyLevel cl) throws NoPersistedMetaDataException { UntypedResultSet result; try {//from w w w . ja v a 2 s. c o m result = process(cl, selectMetadataQuery, DatabaseDescriptor.getClusterName()); Row row = result.one(); if (row != null && row.has("metadata")) { return parseMetaDataString(row.getString("metadata")); } } catch (UnavailableException e) { logger.warn("Cannot read metadata with consistency=" + cl, e); return null; } catch (Exception e) { throw new NoPersistedMetaDataException("Unexpected error", e); } throw new NoPersistedMetaDataException("Unexpected error"); }
From source file:org.elassandra.cluster.InternalCassandraClusterService.java
License:Apache License
/** * Create or update elastic_admin keyspace. * @throws IOException /*w w w. j a v a 2 s .c o m*/ */ @Override public void createOrUpdateElasticAdminKeyspace() { UntypedResultSet result = QueryProcessor.executeInternal(String.format((Locale) null, "SELECT strategy_class,strategy_options FROM system.schema_keyspaces WHERE keyspace_name='%s'", elasticAdminKeyspaceName)); logger.info(" elasticAdminMetadata exist={}", !result.isEmpty()); if (result.isEmpty()) { MetaData metadata = state().metaData(); try { String metaDataString = MetaData.Builder.toXContent(metadata); JSONObject replication = new JSONObject(); replication.put("class", NetworkTopologyStrategy.class.getName()); replication.put(DatabaseDescriptor.getLocalDataCenter(), Integer.toString(getLocalDataCenterSize())); String createKeyspace = String.format((Locale) null, "CREATE KEYSPACE IF NOT EXISTS \"%s\" WITH replication = %s;", elasticAdminKeyspaceName, replication.toJSONString().replaceAll("\"", "'")); logger.info(createKeyspace); process(ConsistencyLevel.LOCAL_ONE, createKeyspace); String createTable = String.format((Locale) null, "CREATE TABLE IF NOT EXISTS \"%s\".%s ( cluster_name text PRIMARY KEY, owner uuid, version bigint, metadata text) WITH comment='%s';", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE, MetaData.Builder.toXContent(metadata)); logger.info(createTable); process(ConsistencyLevel.LOCAL_ONE, createTable); // initialize a first row if needed process(ConsistencyLevel.LOCAL_ONE, insertMetadataQuery, DatabaseDescriptor.getClusterName(), UUID.fromString(StorageService.instance.getLocalHostId()), metadata.version(), metaDataString); logger.info("Succefully initialize {}.{} = {}", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE, metaDataString); writeMetaDataAsComment(metaDataString); } catch (Throwable e) { logger.error("Failed to initialize table {}.{}", e, elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE); } } else { Row row = result.one(); if (!NetworkTopologyStrategy.class.getName().equals(row.getString("strategy_class"))) { throw new ConfigurationException("Keyspace [" + this.elasticAdminKeyspaceName + "] should use " + NetworkTopologyStrategy.class.getName() + " replication strategy"); } JSONObject replication; try { replication = (JSONObject) new JSONParser().parse(row.getString("strategy_options")); int currentRF = -1; if (replication.get(DatabaseDescriptor.getLocalDataCenter()) != null) { currentRF = Integer .valueOf(replication.get(DatabaseDescriptor.getLocalDataCenter()).toString()); } int targetRF = getLocalDataCenterSize(); if (targetRF != currentRF) { replication.put(DatabaseDescriptor.getLocalDataCenter(), Integer.toString(targetRF)); replication.put("class", NetworkTopologyStrategy.class.getName()); try { String query = String.format((Locale) null, "ALTER KEYSPACE \"%s\" WITH replication = %s", elasticAdminKeyspaceName, replication.toJSONString().replaceAll("\"", "'")); process(ConsistencyLevel.LOCAL_ONE, query); logger.info(query); } catch (Throwable e) { logger.error("Failed to alter keyspace [{}]", e, this.elasticAdminKeyspaceName); throw e; } } else { logger.info("Keep unchanged keyspace={} datacenter={} RF={}", elasticAdminKeyspaceName, DatabaseDescriptor.getLocalDataCenter(), targetRF); } } catch (ParseException e1) { throw new ConfigurationException("Failed to update " + elasticAdminKeyspaceName, e1); } } }
From source file:org.elasticsearch.cassandra.cluster.InternalCassandraClusterService.java
License:Apache License
public MapType<?, ?> getMapType(final String ksName, final String cfName, final String colName) { try {//www. j a v a 2 s . c o m UntypedResultSet result = QueryProcessor.executeInternal( "SELECT validator FROM system.schema_columns WHERE columnfamily_name = ? AND column_name = ?", new Object[] { ksName, cfName, colName }); Row row = result.one(); if ((row != null) && row.has("validator")) { AbstractType<?> type = TypeParser.parse(row.getString("validator")); if (type instanceof MapType) { return (MapType<?, ?>) type; } } } catch (Exception e) { } return null; }
From source file:org.elasticsearch.cassandra.cluster.InternalCassandraClusterService.java
License:Apache License
@Override public String insertRow(final String ksName, final String cfName, Map<String, Object> map, String id, final boolean ifNotExists, final long ttl, final ConsistencyLevel cl, Long writetime, Boolean applied) throws Exception { CFMetaData metadata = getCFMetaData(ksName, cfName); // if the provided columns does not contains all the primary key columns, parse the _id to populate the columns in map. boolean buildId = true; ArrayNode array = SchemaService.Utils.jsonMapper.createArrayNode(); for (ColumnDefinition cd : Iterables.concat(metadata.partitionKeyColumns(), metadata.clusteringColumns())) { if (map.keySet().contains(cd.name.toString())) { SchemaService.Utils.addToJsonArray(cd.type, map.get(cd.name.toString()), array); } else {//from w ww .j a v a 2s.c om buildId = false; parseElasticId(ksName, cfName, id, map); } } if (buildId) { id = SchemaService.Utils.writeValueAsString(array); } StringBuilder questionsMarks = new StringBuilder(); StringBuilder columnNames = new StringBuilder(); Object[] values = new Object[map.size()]; int i = 0; for (Entry<String, Object> entry : map.entrySet()) { if (entry.getKey().equals("_token")) continue; if (columnNames.length() > 0) { columnNames.append(','); questionsMarks.append(','); } columnNames.append("\"").append(entry.getKey()).append("\""); questionsMarks.append('?'); values[i++] = entry.getValue(); } StringBuilder query = new StringBuilder(); query.append("INSERT INTO \"").append(ksName).append("\".\"").append(cfName).append("\" (") .append(columnNames.toString()).append(") VALUES (").append(questionsMarks.toString()).append(") "); if (ifNotExists) query.append("IF NOT EXISTS "); if (ttl > 0 || writetime > 0) query.append("USING "); if (ttl > 0) query.append("TTL ").append(Long.toString(ttl)); if (ttl > 0 && writetime > 0) query.append(" AND "); if (writetime > 0) query.append("TIMESTAMP ").append(Long.toString(writetime)); try { UntypedResultSet result = process(cl, (ifNotExists) ? ConsistencyLevel.LOCAL_SERIAL : null, query.toString(), values); if (ifNotExists) { if (!result.isEmpty()) { Row row = result.one(); if (row.has("[applied]")) { applied = row.getBoolean("[applied]"); } } } else { applied = true; } return id; } catch (Exception e) { logger.error("Failed to process query=" + query + " values=" + Arrays.toString(values), e); throw e; } }
From source file:org.elasticsearch.cassandra.cluster.InternalCassandraClusterService.java
License:Apache License
@Override public MetaData readMetaDataAsRow() throws NoPersistedMetaDataException { UntypedResultSet result; try {/* w ww . java 2 s . c o m*/ result = process(ConsistencyLevel.LOCAL_QUORUM, String.format("SELECT metadata FROM \"%s\".\"%s\" WHERE dc = ?", ELASTIC_ADMIN_KEYSPACE, metaDataTableName), DatabaseDescriptor.getLocalDataCenter()); } catch (RequestExecutionException | RequestValidationException e) { throw new NoPersistedMetaDataException(e); } Row row = result.one(); if (row != null && row.has("metadata")) { return parseMetaDataString(row.getString("metadata")); } throw new NoPersistedMetaDataException(); }