private Set<String> getTableMetadataNames(String schemaName) throws TableNotFoundException { MongoDatabase db = client.getDatabase(schemaName); MongoCursor<Document> cursor = db.getCollection(schemaCollection) .find().projection(new Document(TABLE_NAME_KEY, true)).iterator(); HashSet<String> names = new HashSet<>(); while (cursor.hasNext()) { names.add((cursor.next()).getString(TABLE_NAME_KEY)); } return names; }
private List<Document> guessTableFields(SchemaTableName schemaTableName) { String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); MongoDatabase db = client.getDatabase(schemaName); Document doc = db.getCollection(tableName).find().first(); if (doc == null) { // no records at the collection return ImmutableList.of(); } ImmutableList.Builder<Document> builder = ImmutableList.builder(); for (String key : doc.keySet()) { Object value = doc.get(key); Optional<TypeSignature> fieldType = guessFieldType(value); if (fieldType.isPresent()) { Document metadata = new Document(); metadata.append(FIELDS_NAME_KEY, key); metadata.append(FIELDS_TYPE_KEY, fieldType.get().toString()); metadata.append(FIELDS_HIDDEN_KEY, key.equals("_id") && fieldType.get().equals(OBJECT_ID.getTypeSignature())); builder.add(metadata); } else { log.debug("Unable to guess field type from %s : %s", value == null ? "null" : value.getClass().getName(), value); } } return builder.build(); }
@Override public void upgrade() { final FindIterable<Document> documentsWithMissingFields = collection.find(or(not(exists(ContentPack.FIELD_META_ID)), not(exists(ContentPack.FIELD_META_REVISION)))); for (Document document : documentsWithMissingFields) { final ObjectId objectId = document.getObjectId("_id"); LOG.debug("Found document with missing \"id\" or \"rev\" field with ID <{}>", objectId); final String id = document.get("id", objectId.toHexString()); final int rev = document.get("rev", 0); document.put("id", id); document.put("rev", rev); final UpdateResult updateResult = collection.replaceOne(eq("_id", objectId), document); if (updateResult.wasAcknowledged()) { LOG.debug("Successfully updated document with ID <{}>", objectId); } else { LOG.error("Failed to update document with ID <{}>", objectId); } } } }
private List<Document> getColumnMetadata(Document doc) { if (!doc.containsKey(FIELDS_KEY)) { return ImmutableList.of(); } return (List<Document>) doc.get(FIELDS_KEY); }
@Test public void simpleMongoDbTest() { MongoClient mongoClient = new MongoClient(mongo.getContainerIpAddress(), mongo.getMappedPort(MONGO_PORT)); MongoDatabase database = mongoClient.getDatabase("test"); MongoCollection<Document> collection = database.getCollection("testCollection"); Document doc = new Document("name", "foo") .append("value", 1); collection.insertOne(doc); Document doc2 = collection.find(new Document("name", "foo")).first(); assertEquals("A record can be inserted into and retrieved from MongoDB", 1, doc2.get("value")); }
MongoDatabase db = mongo.getDatabase("db" + dbName); MongoDatabase db = mongo.getDatabase("db" + dbName); MongoCollection<Document> collection = db.getCollection("movies" + dbName); MongoCollection<Document> movies = collection; InsertOneOptions insertOptions = new InsertOneOptions().bypassDocumentValidation(true); movies.insertOne(Document.parse("{ \"name\":\"Starter Wars\"}"), insertOptions); assertThat(collection.countDocuments()).isEqualTo(1); Bson filter = Filters.eq("name", "Starter Wars"); FindIterable<Document> movieResults = collection.find(filter); try (MongoCursor<Document> cursor = movieResults.iterator();) { assertThat(cursor.tryNext().getString("name")).isEqualTo("Starter Wars"); assertThat(cursor.tryNext()).isNull(); Bson filter = Filters.and(Filters.gt("ts", oplogStart), // start just after our last position Filters.exists("fromMigrate", false)); // skip internal movements across shards FindIterable<Document> results = mongo.getDatabase("local") .getCollection("oplog.rs") .find(filter) .sort(new Document("$natural", 1)) .oplogReplay(true) // tells Mongo to not rely on indexes .noCursorTimeout(true) // don't timeout waiting for events .cursorType(CursorType.TailableAwait); BsonTimestamp position = event.get("ts", BsonTimestamp.class); assert position != null; });
private Document getTableMetadata(SchemaTableName schemaTableName) throws TableNotFoundException { String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); MongoDatabase db = client.getDatabase(schemaName); MongoCollection<Document> schema = db.getCollection(schemaCollection); Document doc = schema .find(new Document(TABLE_NAME_KEY, tableName)).first(); if (doc == null) { if (!collectionExists(db, tableName)) { throw new TableNotFoundException(schemaTableName); } else { Document metadata = new Document(TABLE_NAME_KEY, tableName); metadata.append(FIELDS_KEY, guessTableFields(schemaTableName)); schema.createIndex(new Document(TABLE_NAME_KEY, 1), new IndexOptions().unique(true)); schema.insertOne(metadata); return metadata; } } return doc; }
/** * Use the given primary to read the oplog. * * @param primary the connection to the replica set's primary node; may not be null */ protected void readOplog(MongoClient primary) { BsonTimestamp oplogStart = source.lastOffsetTimestamp(replicaSet.replicaSetName()); logger.info("Reading oplog for '{}' primary {} starting at {}", replicaSet, primary.getAddress(), oplogStart); // Include none of the cluster-internal operations and only those events since the previous timestamp ... MongoCollection<Document> oplog = primary.getDatabase("local").getCollection("oplog.rs"); Bson filter = Filters.and(Filters.gt("ts", oplogStart), // start just after our last position Filters.exists("fromMigrate", false)); // skip internal movements across shards FindIterable<Document> results = oplog.find(filter) .sort(new Document("$natural", 1)) // force forwards collection scan .oplogReplay(true) // tells Mongo to not rely on indexes .cursorType(CursorType.TailableAwait); // tail and await new data // Read as much of the oplog as we can ... ServerAddress primaryAddress = primary.getAddress(); try (MongoCursor<Document> cursor = results.iterator()) { while (running.get() && cursor.hasNext()) { if (!handleOplogEvent(primaryAddress, cursor.next())) { // Something happened, and we're supposed to stop reading return; } } } }
MongoCursor<Document> cursor = null; try { MongoCollection<Document> collection = database.getCollection(table); Document scanRange = new Document("$gte", startkey); Document query = new Document("_id", scanRange); Document sort = new Document("_id", INCLUDE); collection.find(query).sort(sort).limit(recordcount); Document projection = new Document(); for (String fieldName : fields) { projection.put(fieldName, INCLUDE); findIterable.projection(projection); cursor = findIterable.iterator(); if (!cursor.hasNext()) { System.err.println("Nothing found in scan for key " + startkey); return Status.ERROR; while (cursor.hasNext()) { HashMap<String, ByteIterator> resultMap = new HashMap<String, ByteIterator>(); Document obj = cursor.next(); fillMap(resultMap, obj);
private void createLocksIndexIfNecessary() { String databaseName = CommonUtils.getApplication(this.endpoint).replaceAll("\\W", "_"); MongoDatabase database = this.mongoClient.getDatabase(databaseName); MongoCollection<Document> locks = database.getCollection(CONSTANTS_TB_LOCKS); ListIndexesIterable<Document> lockIndexList = locks.listIndexes(); boolean transactionIndexExists = false; MongoCursor<Document> lockCursor = null; try { lockCursor = lockIndexList.iterator(); while (transactionIndexExists == false && lockCursor.hasNext()) { Document document = lockCursor.next(); Boolean unique = document.getBoolean("unique"); Document key = (Document) document.get("key"); boolean globalExists = key.containsKey(CONSTANTS_FD_GLOBAL); boolean lengthEquals = key.size() == 1; transactionIndexExists = lengthEquals && globalExists; if (transactionIndexExists && (unique == null || unique == false)) { throw new IllegalStateException(); } } } finally { IOUtils.closeQuietly(lockCursor); } if (transactionIndexExists == false) { Document index = new Document(CONSTANTS_FD_GLOBAL, 1); locks.createIndex(index, new IndexOptions().unique(true)); } }
MongoDatabase db = mongo.getDatabase("dbA"); MongoCollection<Document> contacts = db.getCollection("contacts"); InsertOneOptions insertOptions = new InsertOneOptions().bypassDocumentValidation(true); contacts.insertOne(Document.parse("{ \"name\":\"Jon Snow\"}"), insertOptions); assertThat(db.getCollection("contacts").countDocuments()).isEqualTo(1); Bson filter = Filters.eq("name", "Jon Snow"); FindIterable<Document> movieResults = db.getCollection("contacts").find(filter); try (MongoCursor<Document> cursor = movieResults.iterator();) { assertThat(cursor.tryNext().getString("name")).isEqualTo("Jon Snow"); assertThat(cursor.tryNext()).isNull(); contacts.insertOne(Document.parse("{ \"name\":\"Sally Hamm\"}"), insertOptions); try (MongoCursor<Document> cursor = movieResults.iterator();) { while (cursor.hasNext()) { String name = cursor.next().getString("name"); foundNames.add(name); Struct value = (Struct) record.value(); String after = value.getString("after"); Document afterDoc = Document.parse(after); foundNames.add(afterDoc.getString("name")); Operation op = Operation.forCode(value.getString("op")); assertThat(op == Operation.READ || op == Operation.CREATE).isTrue(); Bson filter = Filters.eq("name", "Jon Snow"); FindIterable<Document> movieResults = db.getCollection("contacts").find(filter); try (MongoCursor<Document> cursor = movieResults.iterator();) {
/** * Obtain the current position of the oplog, and record it in the source. */ protected void recordCurrentOplogPosition() { primaryClient.execute("get oplog position", primary -> { MongoCollection<Document> oplog = primary.getDatabase("local").getCollection("oplog.rs"); Document last = oplog.find().sort(new Document("$natural", -1)).limit(1).first(); // may be null source.offsetStructForEvent(replicaSet.replicaSetName(), last); }); }
public void recover(TransactionRecoveryCallback callback) { MongoCursor<Document> transactionCursor = null; try { String application = CommonUtils.getApplication(this.endpoint); String databaseName = application.replaceAll("\\W", "_"); MongoDatabase mdb = this.mongoClient.getDatabase(databaseName); MongoCollection<Document> transactions = mdb.getCollection(CONSTANTS_TB_TRANSACTIONS); FindIterable<Document> transactionItr = transactions.find(Filters.eq("coordinator", true)); for (transactionCursor = transactionItr.iterator(); transactionCursor.hasNext();) { Document document = transactionCursor.next(); boolean error = document.getBoolean("error"); String targetApplication = document.getString("system"); long expectVersion = document.getLong("version"); long actualVersion = this.versionManager.getInstanceVersion(targetApplication); if (error == false && actualVersion > 0 && actualVersion <= expectVersion) { continue; // ignore } callback.recover(this.reconstructTransactionArchive(document)); } } catch (RuntimeException error) { logger.error("Error occurred while recovering transaction.", error); } catch (Exception error) { logger.error("Error occurred while recovering transaction.", error); } finally { IOUtils.closeQuietly(transactionCursor); } }
final Document query = getQuery(context, session, input); MongoCollection mongoCollection = clientService.getDatabase(database).getCollection(collection); FindIterable<Document> find = mongoCollection.find(query); if (context.getProperty(SORT).isSet()) { find = find.sort(Document.parse(context.getProperty(SORT).evaluateAttributeExpressions(input).getValue())); find = find.projection(Document.parse(context.getProperty(PROJECTION).evaluateAttributeExpressions(input).getValue())); find = find.limit(context.getProperty(LIMIT).evaluateAttributeExpressions(input).asInteger()); long count = 0L; writer.beginRecordSet(); while (cursor.hasNext()) { Document next = cursor.next(); if (next.get("_id") instanceof ObjectId) { next.put("_id", next.get("_id").toString());
/** * Add field use_raw_configuration_schema to endpointProfile that used to support devices using * SDK version 0.9.0 */ public void transform() { //mongo MongoClient client = new MongoClient(host); MongoDatabase database = client.getDatabase(dbName); MongoCollection<Document> endpointProfile = database.getCollection("endpoint_profile"); endpointProfile.updateMany(new Document(), eq("$set", eq("use_raw_schema", false))); //cassandra Cluster cluster = Cluster.builder().addContactPoint(host).build(); Session session = cluster.connect(dbName); session.execute("ALTER TABLE ep_profile ADD use_raw_schema boolean"); session.close(); cluster.close(); } }
private void createTableMetadata(SchemaTableName schemaTableName, List<MongoColumnHandle> columns) throws TableNotFoundException { String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); MongoDatabase db = client.getDatabase(schemaName); Document metadata = new Document(TABLE_NAME_KEY, tableName); ArrayList<Document> fields = new ArrayList<>(); if (!columns.stream().anyMatch(c -> c.getName().equals("_id"))) { fields.add(new MongoColumnHandle("_id", OBJECT_ID, true).getDocument()); } fields.addAll(columns.stream() .map(MongoColumnHandle::getDocument) .collect(toList())); metadata.append(FIELDS_KEY, fields); MongoCollection<Document> schema = db.getCollection(schemaCollection); schema.createIndex(new Document(TABLE_NAME_KEY, 1), new IndexOptions().unique(true)); schema.insertOne(metadata); }
private void markTransactionRollback(TransactionXid transactionXid) { try { byte[] global = transactionXid.getGlobalTransactionId(); String identifier = ByteUtils.byteArrayToString(global); String application = CommonUtils.getApplication(this.endpoint); String databaseName = application.replaceAll("\\W", "_"); MongoDatabase mdb = this.mongoClient.getDatabase(databaseName); MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_TRANSACTIONS); Document document = new Document(); document.append("$set", new Document("status", Status.STATUS_MARKED_ROLLBACK)); Bson globalFilter = Filters.eq(CONSTANTS_FD_GLOBAL, identifier); Bson statusFilter = Filters.eq("status", Status.STATUS_ACTIVE); collection.updateOne(Filters.and(globalFilter, statusFilter), document); } catch (RuntimeException error) { logger.error("Error occurred while setting the error flag.", error); } }
public int timingExecution(int batchSize) { String databaseName = CommonUtils.getApplication(this.endpoint).replaceAll("\\W", "_"); MongoDatabase mdb = this.mongoClient.getDatabase(databaseName); MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_REMOVEDRESES); MongoCursor<Document> cursor = null; try { cursor = collection.find().limit(batchSize).iterator(); for (; cursor.hasNext(); length++) { Document document = cursor.next(); String globalValue = document.getString(CONSTANTS_FD_GLOBAL); String branchValue = document.getString(CONSTANTS_FD_BRANCH); byte[] global = ByteUtils.stringToByteArray(globalValue); byte[] branch = ByteUtils.stringToByteArray(branchValue); TransactionXid branchXid = xidFactory.createBranchXid(globalXid, branch); String resourceId = document.getString("resource_id"); if (StringUtils.isBlank(resourceId)) { continue; byte[] branch = transactionXid.getBranchQualifier(); Bson globalFilter = Filters.eq(CONSTANTS_FD_GLOBAL, ByteUtils.byteArrayToString(global)); Bson branchFilter = Filters.eq(CONSTANTS_FD_BRANCH, ByteUtils.byteArrayToString(branch)); collection.deleteOne(Filters.and(globalFilter, branchFilter));
MongoDatabase db1 = mongo.getDatabase("dbit"); MongoCollection<Document> coll = db1.getCollection("arbitrary"); coll.drop(); Document doc = Document.parse("{\"a\": 1, \"b\": 2}"); InsertOneOptions insertOptions = new InsertOneOptions().bypassDocumentValidation(true); coll.insertOne(doc, insertOptions); doc = coll.find().first(); Testing.debug("Document: " + doc); id.set(doc.getObjectId("_id").toString()); Testing.debug("Document ID: " + id.get()); }); MongoDatabase db1 = mongo.getDatabase("dbit"); MongoCollection<Document> coll = db1.getCollection("arbitrary"); Document doc = coll.find().first(); Testing.debug("Document: " + doc); Document filter = Document.parse("{\"a\": 1}"); Document operation = Document.parse("{ \"$set\": { \"b\": 10 } }"); coll.updateOne(filter, operation); doc = coll.find().first(); Testing.debug("Document: " + doc); });