public static MongoCollectionSchema GetSchemaDocument(MongoDatabaseInfo databaseInfo, string collectionName, int maxSampleSize)
        {
            string key = $"{databaseInfo.Connection.Name}-{collectionName}";

            if (_docs.ContainsKey(key))
            {
                return(_docs[key]);
            }

            MongoCollection <BsonDocument> collection = databaseInfo.GetCollection(collectionName);
            long collectionSize = collection.Count();
            long sampleSize     = Math.Min(collectionSize, maxSampleSize);

            var cursor = collection.FindAll();

            cursor.SetSortOrder(SortBy.Descending("_id"));
            cursor.SetLimit((int)sampleSize);

            var docs = cursor.ToList();
            var doc  = new BsonDocumentBuilder().BuildDocument(docs);

            _docs.Add(key, new MongoCollectionSchema
            {
                SchemaDocument = doc,
                SampleSize     = sampleSize,
                CollectionSize = collectionSize
            });

            return(_docs[key]);
        }
Ejemplo n.º 2
0
        private MongoCollectionModelInfo GetModel(MongoDatabaseInfo databaseInfo, string collectionName)
        {
            MongoCollectionInfo collectionInfo = databaseInfo.GetCollectionInfo(collectionName);

            if (collectionInfo != null && collectionInfo.HasModel)
            {   // Model already exists for this collection.
                return(collectionInfo.Models[0]);
            }

            // Generate and save model code.
            var collection = databaseInfo.GetCollection(collectionName);
            var doc        = collection.FindOne();

            if (doc == null)
            {
                throw new Exception(
                          $"Collection '{collectionName}' is empty. Unable to determine schema from first document");
            }

            var schemaInfo = MongoCollectionSchemaStore.GetSchemaDocument(databaseInfo, collectionName);
            var classes    = new BsonDocumentConverter().ToCSharpClassDeclarations(schemaInfo.SchemaDocument, collectionName);

            var sb = new StringBuilder();

            foreach (var classSyntax in classes)
            {
                sb.AppendLine(classSyntax);
            }

            string modelCode = sb.ToString();

            MongoCollectionModelInfo newModel = databaseInfo.SetCollectionModel(collectionName, modelCode, "Doc0", true, (int)schemaInfo.SampleSize, schemaInfo.SamplePercent);

            Settings.Instance.Save();

            return(newModel);
        }