private void checkIfRowExsits(String table, byte[] rowKey, String colName) { Clause rkClause = QueryBuilder.eq("id", ByteBuffer.wrap(rowKey)); Clause cnClause = QueryBuilder.eq("colname", colName); try { Query query = QueryBuilder.select().all().from(keys, table).where(rkClause).and(cnClause); ResultSet resultSet = session.execute(query); if (resultSet.isExhausted()) return; else { Query delQuery = QueryBuilder.delete().from(keys, table).where(rkClause).and(cnClause); session.execute(delQuery); } } catch (Exception e) { System.out.println(" Exception:" + e.getMessage()); } }
private void remove(Remove action, MetaLookup ormSession) { String colFamily = action.getColFamily().getColumnFamily(); String table = lookupOrCreate(colFamily, ormSession); if (action.getAction() == null) throw new IllegalArgumentException("action param is missing ActionEnum so we know to remove entire row or just columns in the row"); switch (action.getAction()) { case REMOVE_ENTIRE_ROW: Clause eqClause = QueryBuilder.eq("id", ByteBuffer.wrap(action.getRowKey())); Query query = QueryBuilder.delete().from(keys, table).where(eqClause); session.execute(query); break; case REMOVE_COLUMNS_FROM_ROW: removeColumns(action, table); break; default: throw new RuntimeException("bug, unknown remove action=" + action.getAction()); } }
public boolean findIndexRow(String table, String rowKey, byte[] key, Object indValue) { Select selectQuery = QueryBuilder.select().all().from(keys, table).allowFiltering(); Where selectWhere = selectQuery.where(); Clause rkClause = QueryBuilder.eq("id", rowKey); selectWhere.and(rkClause); Clause indClause = null; if (indValue != null) { indClause = QueryBuilder.eq("colname", indValue); } else { if (table.equalsIgnoreCase("IntegerIndice")) { indClause = QueryBuilder.eq("colname", ByteBuffer.wrap(new byte[0])); } else { indClause = QueryBuilder.eq("colname", ""); } } selectWhere.and(indClause); Clause keyClause = QueryBuilder.eq("colvalue", ByteBuffer.wrap(key)); selectWhere.and(keyClause); Query query = selectWhere.limit(1); ResultSet resultSet = session.execute(query); return !resultSet.isExhausted(); }
public int getVersion(String keyspace, String table, ConsistencyLevel level) { int version = -1; // Build SELECT query Query query = QueryBuilder.select(VERSION) .from((keyspace == null) ? keyspaceName : keyspace, table) .setConsistencyLevel(level); ResultSet result = executeQuery(query); if (result.isExhausted()) { return -1; } for (Row row : result) { int tmp = row.getInt(VERSION); if (version < tmp) { version = tmp; } } return version; }
@Test(groups = {"system"}) public void testAsyncExecution() throws Exception { loadDataUsingBoundStatements(); Query query = QueryBuilder.select().all().from("simplex", "songs"); ResultSetFuture results = session.executeAsync(query); for (Row row : results.getUninterruptibly()) { String artist = row.getString("artist"); String title = row.getString("title"); String album = row.getString("album"); assertEquals(title, "La Petite Tonkinoise'"); assertEquals(album, "Bye Bye Blackbird'"); assertEquals(artist, "Joséphine Baker"); if (LOG.isDebugEnabled()) { LOG.debug(String.format("%s: %s / %s\n", artist, title, album)); } } }
private void loadCache(boolean reverse) { if (cachedRows != null && cachedRows.hasNext()) return; // There are more rows so return and the code will return // the next result from cache ResultSet resultSet = null; if (needToGetBatch) { if (batchListener != null) batchListener.beforeFetchingNextBatch(); String rowKeyString = StandardConverters.convertFromBytes(String.class, rowKey); Select selectQuery = QueryBuilder.select().all().from(keySpace, indTable).allowFiltering(); Where whereClause = Cql3Util.createRowQuery(from, to, columnMeta, selectQuery, rowKeyString, indTable); Query query = null; if (batchSize != null) query = whereClause.limit(batchSize); else query = whereClause.disableTracing(); resultSet = session.execute(query); // Need to see where we use this batchListener if (batchListener != null && batchSize != null) batchListener.afterFetchingNextBatch(batchSize); List<com.datastax.driver.core.Row> finalRes = new ArrayList<com.datastax.driver.core.Row>(); fillinCache(finalRes, resultSet); needToGetBatch = false; if (reverse) { while (cachedRows.hasNext()) cachedRows.next(); } } }
@Override public List<Future<ResultSet>> start() { List<Future<ResultSet>> futures = new ArrayList<Future<ResultSet>>(); String rowKeyString = StandardConverters.convertFromBytes(String.class, rowKey); for (byte[] val : values) { Select selectQuery = QueryBuilder.select().all().from(keySpace, indTable).allowFiltering(); Where selectWhere = selectQuery.where(); Clause rkClause = QueryBuilder.eq("id", rowKeyString); selectWhere.and(rkClause); Object value = null; value = columnMeta.getStorageType().convertFromNoSql(val); value = Cql3Util.checkForBooleanAndNull(value, indTable, columnMeta); Clause valClause = QueryBuilder.eq("colname", value); selectWhere.and(valClause); Query query = selectWhere.disableTracing(); Future future = session.executeAsync(query); futures.add(future); } return futures; }
private void removeIndex(RemoveIndex action, MetaLookup ormSession) { String colFamily = action.getIndexCfName(); if (colFamily.equalsIgnoreCase("BytesIndice")) return; String table = lookupOrCreate(colFamily, ormSession); String rowKey = StandardConverters.convertFromBytes(String.class, action.getRowKey()); IndexColumn column = action.getColumn(); byte[] fk = column.getPrimaryKey(); byte[] indexedValue = action.getColumn().getIndexedValue(); Object indValue = null; if (table.equalsIgnoreCase("StringIndice")) indValue = StandardConverters.convertFromBytes(String.class, indexedValue); else if (table.equalsIgnoreCase("IntegerIndice")) indValue = StandardConverters.convertFromBytes(Long.class, indexedValue); else if (table.equalsIgnoreCase("DecimalIndice")) indValue = StandardConverters.convertFromBytes(Float.class, indexedValue); boolean exists = findIndexRow(table, rowKey, fk, indValue); if (!exists) { if (log.isInfoEnabled()) log.info("Index: " + column.toString() + " already removed."); } else { Clause eqClause = QueryBuilder.eq("id", rowKey); Clause indClause = null; if (indValue != null) { indClause = QueryBuilder.eq("colname", indValue); } else { if (table.equalsIgnoreCase("IntegerIndice")) { indClause = QueryBuilder.eq("colname", ByteBuffer.wrap(new byte[0])); } else { indClause = QueryBuilder.eq("colname", ""); } } Clause fkClause = QueryBuilder.eq("colvalue", ByteBuffer.wrap(fk)); Query query = QueryBuilder.delete().from(keys, table).where(eqClause).and(indClause).and(fkClause); session.execute(query); } }
public void putSubscription(String keyspace, String tableName, String rowKey, ByteBuffer subscription, ConsistencyLevel level) { Query query = QueryBuilder.update(keyspace, tableName) .with(QueryBuilder.append("subscriptions", subscription)) .where(QueryBuilder.eq(KEY, UUID.fromString(rowKey))) .setConsistencyLevel(level); session.execute(query); }
public void setTableConsistencyLevel(String rowKey, SimbaConsistency.Type consistencyLevel) { Query query = QueryBuilder.insertInto("simbastore", "metadata") .value(KEY, rowKey).value("consistency", consistencyLevel) .setConsistencyLevel(ConsistencyLevel.ALL); session.execute(query); }
public ResultSet getRowWithTracing(String keyspace, String table, String key, ConsistencyLevel level) { Query select = QueryBuilder.select().all().from(keyspace, table) .where(QueryBuilder.eq(KEY, key)).setConsistencyLevel(level) .enableTracing(); ResultSet results = session.execute(select); ExecutionInfo executionInfo = results.getExecutionInfo(); System.out.printf("Host (queried): %s\n", executionInfo .getQueriedHost().toString()); for (Host host : executionInfo.getTriedHosts()) { System.out.printf("Host (tried): %s\n", host.toString()); } QueryTrace queryTrace = executionInfo.getQueryTrace(); System.out.printf("Trace id: %s\n\n", queryTrace.getTraceId()); System.out.printf("%-38s | %-12s | %-10s | %-12s\n", "activity", "timestamp", "source", "source_elapsed"); System.out .println("---------------------------------------+--------------+------------+--------------"); for (QueryTrace.Event event : queryTrace.getEvents()) { System.out.printf("%38s | %12s | %10s | %12s\n", event.getDescription(), new Date(event.getTimestamp()), event.getSource(), event.getSourceElapsedMicros()); } select.disableTracing(); return results; }
public ResultSet getRow(String keyspace, String table, String key, ConsistencyLevel level) { Long start = System.nanoTime(); // LOG.debug("GET ROW START\n"); Query query = QueryBuilder.select().all().from(keyspace, table) .where(QueryBuilder.eq(KEY, key)).setConsistencyLevel(level); LOG.debug(query.toString()); ResultSet result = executeQuery(query); IOStats.getRow(((double) System.nanoTime() - (double) start) / 1000000); return result; }
public ResultSet getTableConsistencyLevel(String rowKey) { Query query = QueryBuilder.select().all() .from("simbastore", "metadata") .where(QueryBuilder.eq(KEY, rowKey)) .setConsistencyLevel(ConsistencyLevel.ONE); ResultSet result = executeQuery(query); return result; }
@Override public void writeToPath(K rowKey, Path path, Object structuredValue, BatchContext batchContext) { Batch batch = validateAndGetBatch(batchContext); validateArgs(rowKey, path); Object simplifiedStructure = writeMapper.convertValue(structuredValue, Object.class); Map<Path,Object> pathMap = Collections.singletonMap(path, simplifiedStructure); Map<Path,Object> objectMap = Decomposer.get().decompose(pathMap); batch = batchContext == null ? batch() : batch; List<Object> bindArguments = batchContext == null ? new ArrayList<Object>() : ((CqlBatchContext)batchContext).getBindArguments(); Statement insertStatement = insertInto(tableName) .value(partitionKeyColumnName, bindMarker()) .value(pathColumnName, bindMarker()) .value(valueColumnName, bindMarker()) .using(timestamp(getCurrentMicros())); insertStatement.setConsistencyLevel(defaultConsistencyLevel); for (Map.Entry<Path,Object> entry : objectMap.entrySet()) { batch.add(insertStatement); String stringValue = StructureConverter.get().toString(entry.getValue()); bindArguments.add(rowKey); bindArguments.add(entry.getKey().toString()); bindArguments.add(stringValue); } if (batchContext == null) { Query boundStatement = session.prepare(batch.getQueryString()).bind(bindArguments.toArray()); boundStatement.setConsistencyLevel(defaultConsistencyLevel); session.execute(boundStatement); } }
private void removeColumnImpl(byte[] rowKey, String table, String colName) { Clause eqClause = QueryBuilder.eq("id",ByteBuffer.wrap(rowKey)); Clause eqColClause = QueryBuilder.eq("colname", colName); Query query = QueryBuilder.delete().from(keys, table).where(eqClause).and(eqColClause); session.execute(query); }
private void fetchMoreResultsImpl() { if (subList != null) { if (pointer < subList.size()) { return; } else if (batchSize == null) { return; } else if (subList.size() < batchSize) { return; } } pointer = -1; if (batchListener != null) batchListener.beforeFetchingNextBatch(); if (subList != null) return; if (batchListener != null) batchListener.beforeFetchingNextBatch(); columnNameType = sliceInfo.getColumnNameType(); ResultSet resultSet = null; Clause rkClause = QueryBuilder.eq("id", ByteBuffer.wrap(rowKey)); Query query = null; query = QueryBuilder.select().all().from(keys, table).where(rkClause).disableTracing(); subList = new ArrayList<com.datastax.driver.core.Row>(); try { resultSet = session.execute(query); if (resultSet == null) { return; } else { if (BigInteger.class.equals(columnNameType)) { intColumnSlice(resultSet); } else if (BigDecimal.class.equals(columnNameType)) { decimalColumnSlice(resultSet); } else if (String.class.equals(columnNameType)) { stringColumSlice(resultSet); } else throw new UnsupportedOperationException("Type " + columnNameType.getName() + " is not allowed for ColumnSlice"); } if (batchListener != null) batchListener.afterFetchingNextBatch(2); } catch (Exception e) { e.printStackTrace(); } }
public void putRowWithTracing(String keyspace, String tableName, String rowKey, Integer version, List<ColumnData> values, ConsistencyLevel level) { StringBuilder command = new StringBuilder(); StringBuilder vals = new StringBuilder(); command.append("INSERT INTO ") .append((keyspace == null) ? keyspaceName : keyspace) .append(".").append(tableName).append(" (").append(KEY) .append(",").append(VERSION).append(",").append(DELETED) .append(","); ColumnData pair = values.get(0); command.append(pair.getColumn()); vals.append(pair.getValue()); for (int i = 1; i < values.size(); i++) { pair = values.get(i); command.append(",").append(pair.getColumn()); vals.append(",").append(pair.getValue()); } command.append(") VALUES (").append("'" + rowKey + "',") .append(version + ",").append("false,").append(vals.toString()) .append(");"); LOG.debug(command.toString()); SimpleStatement ss = new SimpleStatement(command.toString()); Query insert = QueryBuilder.batch(ss).setConsistencyLevel(level) .enableTracing(); ResultSet results = session.execute(insert); ExecutionInfo executionInfo = results.getExecutionInfo(); System.out.printf("Host (queried): %s\n", executionInfo .getQueriedHost().toString()); for (Host host : executionInfo.getTriedHosts()) { System.out.printf("Host (tried): %s\n", host.toString()); } QueryTrace queryTrace = executionInfo.getQueryTrace(); System.out.printf("Trace id: %s\n\n", queryTrace.getTraceId()); System.out.printf("%-38s | %-12s | %-10s | %-12s\n", "activity", "timestamp", "source", "source_elapsed"); System.out .println("---------------------------------------+--------------+------------+--------------"); for (QueryTrace.Event event : queryTrace.getEvents()) { System.out.printf("%38s | %12s | %10s | %12s\n", event.getDescription(), new Date(event.getTimestamp()), event.getSource(), event.getSourceElapsedMicros()); } insert.disableTracing(); }
private ResultSet executeStatement(String keyspace, Query statement) { if (LOG.isDebugEnabled()) LOG.debug("On [" + keyspace + "], executing [" + statement + "] "); return getSession(keyspace).execute(statement); }
private void verifyConsistency(int numberOfInvocations) { verify(session, times(numberOfInvocations)).execute(queryCaptor.capture()); for (Query q : queryCaptor.getAllValues()) { assertEquals(q.getConsistencyLevel(), ConsistencyLevel.QUORUM); } }