Example #1
0
        /// <summary>
        /// Run an include action in each document returned by Find(), FindById(), FindOne() and All() methods to load DbRef documents
        /// Returns a new Collection with this action included
        /// </summary>
        public ILiteCollection <T> Include(BsonExpression keySelector)
        {
            if (string.IsNullOrEmpty(keySelector))
            {
                throw new ArgumentNullException(nameof(keySelector));
            }

            // cloning this collection and adding this include
            var newcol = new LiteCollection <T>(_collection, _autoId, _engine, _mapper);

            newcol._includes.AddRange(_includes);
            newcol._includes.Add(keySelector);

            return(newcol);
        }
Example #2
0
        /// <summary>
        /// Run an include action in each document returned by Find(), FindById(), FindOne() and All() methods. Useful for load reference documents when nedded.
        /// Returns a new Collection with this action included
        /// </summary>
        public LiteCollection <T> Include(Action <T> action)
        {
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            var col = new LiteCollection <T>(this.Database, Name);

            col._pageID = _pageID;
            col._includes.AddRange(_includes);

            col._includes.Add(action);

            return(col);
        }
Example #3
0
        /// <summary>
        ///     Run an include action in each document returned by Find(), FindById(), FindOne() and All() methods to load DbRef
        ///     documents
        ///     Returns a new Collection with this action included
        /// </summary>

        /*public LiteCollection<T> Include<K>(Expression<Func<T, K>> dbref)
         * {
         *  if (dbref == null) throw new ArgumentNullException("dbref");
         *  var path = _visitor.GetBsonField(dbref);
         *  _includes.Add(path);
         *  return this;
         * }*/
        /*private IEnumerable<Action<BsonDocument>> StartInclude()
         * {
         *  foreach (var path in _includes)
         *  {
         *      yield return delegate(BsonDocument bson)
         *      {
         *          var value = bson.Get(path);
         *
         *          if (value.IsNull) return;
         *
         *          // if property value is an array, populate all values
         *          if (value.IsArray)
         *          {
         *              var array = value.AsArray;
         *              if (array.Count == 0) return;
         *
         *              // all doc refs in an array must be same collection, lets take first only
         *              var col = new LiteCollection<BsonDocument>(array[0].AsDocument["$ref"], _engine, _mapper, _log);
         *              col._includes.AddRange(_includes);
         *              for (var i = 0; i < array.Count; i++)
         *              {
         *                  array[i] = col.FindById(array[i].AsDocument["$id"]);
         *              }
         *          }
         *          else
         *          {
         *              // for BsonDocument, get property value e update with full object refence
         *              var doc = value.AsDocument;
         *              var col = new LiteCollection<BsonDocument>(doc["$ref"], _engine, _mapper, _log);
         *              col._includes.AddRange(_includes);
         *              bson.Set(path, col.FindById(doc["$id"]));
         *          }
         *      };
         *  }
         * }*/
        private IEnumerable <Action <BsonDocument> > StartInclude()
        {
            yield return(delegate(BsonDocument bson)
            {
                var keys = bson.Keys.ToArray();
                foreach (var key in keys)
                {
                    var value = bson.Get(key);
                    if (value.IsNull)
                    {
                        continue;
                    }

                    if (value.IsArray)
                    {
                        var array = value.AsArray;
                        if (array.Count == 0)
                        {
                            continue;
                        }
                        if (!array[0].IsDocument)
                        {
                            continue;
                        }
                        if (!array[0].AsDocument.ContainsKey("$ref"))
                        {
                            continue;
                        }
                        var col = new LiteCollection <BsonDocument>(array[0].AsDocument["$ref"], _engine, _mapper, _log);
                        for (var i = 0; i < array.Count; i++)
                        {
                            array[i] = col.FindById(array[i].AsDocument["$id"]);
                        }
                    }
                    else if (value.IsDocument)
                    {
                        var doc = value.AsDocument;
                        if (!doc.ContainsKey("$ref"))
                        {
                            continue;
                        }
                        var col = new LiteCollection <BsonDocument>(doc["$ref"], _engine, _mapper, _log);
                        bson.Set(key, col.FindById(doc["$id"]));
                    }
                }
            });
        }
Example #4
0
        /// <summary>
        /// Find witch index will be used and run Execute method - define ExecuteMode here
        /// </summary>
        internal virtual IEnumerable <IndexNode> Run <T>(LiteCollection <T> collection)
            where T : new()
        {
            // get collection page - no collection, no results
            var col = collection.GetCollectionPage(false);

            // no collection just returns an empty list of indexnode
            if (col == null)
            {
                return(new List <IndexNode>());
            }

            // get index
            var index = col.GetIndex(this.Field);

            // if index not found, lets check if type T has [BsonIndex]
            if (index == null && typeof(T) != typeof(BsonDocument))
            {
                var options = collection.Database.Mapper.GetIndexFromAttribute <T>(this.Field);

                // create a new index
                if (options != null)
                {
                    collection.EnsureIndex(this.Field, options);

                    index = col.GetIndex(this.Field);
                }
            }

            if (index == null)
            {
                this.ExecuteMode = QueryExecuteMode.FullScan;

                // normalize query values before run full scan
                this.NormalizeValues(new IndexOptions());

                // if there is no index, returns all index nodes - will be used Full Scan
                return(collection.Database.Indexer.FindAll(col.PK, Query.Ascending));
            }
            else
            {
                this.ExecuteMode = QueryExecuteMode.IndexSeek;

                // execute query to get all IndexNodes
                return(this.ExecuteIndex(collection.Database.Indexer, index));
            }
        }
Example #5
0
        /// <summary>
        /// Run an include action in each document returned by Find(), FindById(), FindOne() and All() methods to load DbRef documents
        /// Returns a new Collection with this action included
        /// </summary>
        /// <param name="paths">Property paths to include.</param>
        public LiteCollection <T> Include(string[] paths)
        {
            if (paths == null)
            {
                throw new ArgumentNullException(nameof(paths));
            }

            // cloning this collection and adding this include
            var newcol = new LiteCollection <T>(_name, _engine, _mapper, _log);

            newcol._includes.AddRange(_includes);

            // add all paths that are not null nor empty due to previous check
            newcol._includes.AddRange(paths.Where(x => !String.IsNullOrEmpty(x)));

            return(newcol);
        }
Example #6
0
        /// <summary>
        /// Run an include action in each document returned by Find(), FindById(), FindOne() and All() methods to load DbRef documents
        /// Returns a new Collection with this action included
        /// </summary>
        public LiteCollection <T> Include(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }

            Action <BsonDocument> action = bson => ResolveReferences(bson, path.Split('.'), 0);

            // cloning this collection and adding this include
            var newcol = new LiteCollection <T>(_name, _engine, _mapper, _log);

            newcol._includes.AddRange(_includes);
            newcol._includes.Add(action);

            return(newcol);
        }
Example #7
0
        public static T Single <T>(this LiteCollection <T> col)
            where T : new()
        {
            var count = col.Count();

            if (count == 1)
            {
                return(col.Find(Query.All()).First());
            }
            else if (count > 1)
            {
                throw new LiteException("集合内不止一个元素!");
            }
            else
            {
                throw new LiteException("集合内没有任何元素!");
            }
        }
Example #8
0
        /// <summary>
        /// Find witch index will be used and run Execute method - define ExecuteMode here
        /// </summary>
        internal virtual IEnumerable <IndexNode> Run <T>(LiteCollection <T> collection)
            where T : new()
        {
            // get collection page - no collection, no results
            var col = collection.GetCollectionPage(false);

            // no collection just returns an empty list of indexnode
            if (col == null)
            {
                return(new List <IndexNode>());
            }

            // get index
            var index = col.GetIndex(this.Field);

            // if index not found, lets check if type T has [BsonIndex]
            if (index == null && typeof(T) != typeof(BsonDocument))
            {
                var options = collection.Database.Mapper.GetIndexFromAttribute <T>(this.Field);

                // create a new index using BsonIndex options
                if (options != null)
                {
                    collection.EnsureIndex(this.Field, options);

                    index = col.GetIndex(this.Field);
                }
            }

            // if no index, let's auto create an index with default index options
            if (index == null)
            {
                collection.EnsureIndex(this.Field);

                index = col.GetIndex(this.Field);
            }

            // execute query to get all IndexNodes
            return(this.ExecuteIndex(collection.Database.Indexer, index));
        }
Example #9
0
        /// <summary>
        /// Set new Id in entity class if entity needs one
        /// </summary>
        public void SetAutoId(object entity, LiteCollection <BsonDocument> col)
        {
            // if object is BsonDocument, add _id as ObjectId
            if (entity is BsonDocument)
            {
                var doc = entity as BsonDocument;
                if (!doc.RawValue.ContainsKey("_id"))
                {
                    doc["_id"] = ObjectId.NewObjectId();
                }
                return;
            }

            // get fields mapper
            var mapper = GetPropertyMapper(entity.GetType());

            // it's not best way because is scan all properties - but Id propably is first field :)
            var id = mapper.Select(x => x.Value).FirstOrDefault(x => x.FieldName == "_id");

            // if not id or no autoId = true
            if (id == null || id.AutoId == false)
            {
                return;
            }

            AutoId autoId;

            if (_autoId.TryGetValue(id.PropertyType, out autoId))
            {
                var value = id.Getter(entity);

                if (value == null || autoId.IsEmpty(value) == true)
                {
                    var newId = autoId.NewId(col);

                    id.Setter(entity, newId);
                }
            }
        }
Example #10
0
        /// <summary>
        /// Set new Id in entity class if entity needs one
        /// </summary>
        public virtual void SetAutoId(object entity, LiteCollection <BsonDocument> col)
        {
            // if object is BsonDocument, add _id as ObjectId
            if (entity is BsonDocument)
            {
                var doc = entity as BsonDocument;
                if (!doc.RawValue.ContainsKey("_id"))
                {
                    doc["_id"] = ObjectId.NewObjectId();
                }
                return;
            }

            // get fields mapper
            var mapper = this.GetEntityMapper(entity.GetType());

            var id = mapper.Id;

            // if not id or no autoId = true
            if (id == null || id.AutoId == false)
            {
                return;
            }

            AutoId autoId;

            if (_autoId.TryGetValue(id.DataType, out autoId))
            {
                var value = id.Getter(entity);

                if (value == null || autoId.IsEmpty(value) == true)
                {
                    var newId = autoId.NewId(col);

                    id.Setter(entity, newId);
                }
            }
        }
Example #11
0
 public static bool Any <T>(this LiteCollection <T> col)
     where T : new()
 {
     return(col.Count() > 0);
 }
Example #12
0
 /// <summary>
 /// Include DBRef path in result query execution
 /// </summary>
 public LiteQueryable <T> Include(string path)
 {
     _collection = _collection.Include(path);
     return(this);
 }
 public static async Task <bool> ExistsAsync <T>(this LiteCollection <T> collection, Query query)
 {
     return(await Task.Run(() => collection.Exists(query)));
 }
 public static async Task <BsonValue> MinAsync <T>(this LiteCollection <T> collection, string field)
 {
     return(await Task.Run(() => collection.Min(field)));
 }
Example #15
0
 /// <summary>
 /// Include DBRef field in result query execution
 /// </summary>
 public LiteQueryable <T> Include <K>(Expression <Func <T, K> > dbref)
 {
     _collection = _collection.Include(dbref);
     return(this);
 }
Example #16
0
 internal void SetReference(BsonValue fileId, LiteCollection <LiteFileInfo <TFileId> > files, LiteCollection <BsonDocument> chunks)
 {
     _fileId = fileId;
     _files  = files;
     _chunks = chunks;
 }
 public static async Task <long> LongCountAsync <T>(this LiteCollection <T> collection, Expression <Func <T, bool> > predicate)
 {
     return(await Task.Run(() => collection.LongCount(predicate)));
 }
 public static async Task <IEnumerable <T> > FindAsync <T>(this LiteCollection <T> collection, Expression <Func <T, bool> > predicate, int skip = 0, int limit = int.MaxValue)
 {
     return(await Task.Run(() => collection.Find(predicate, skip, limit)));
 }
 public static async Task <bool> DropIndexAsync <T>(this LiteCollection <T> collection, string field)
 {
     return(await Task.Run(() => collection.DropIndex(field)));
 }
 public static async Task <IEnumerable <T> > FindAsync <T>(this LiteCollection <T> collection, Query query, int skip = 0, int limit = int.MaxValue)
 {
     return(await Task.Run(() => collection.Find(query, skip, limit)));
 }
 public static async Task <BsonValue> MaxAsync <T, K>(this LiteCollection <T> collection, Expression <Func <T, K> > property)
 {
     return(await Task.Run(() => collection.Max(property)));
 }
 public static async Task <BsonValue> MaxAsync <T>(this LiteCollection <T> collection)
 {
     return(await Task.Run(() => collection.Max()));
 }
Example #23
0
 public static bool Any <T>(this LiteCollection <T> col, Expression <Func <T, bool> > predicate)
     where T : new()
 {
     return(col.Count(predicate) > 0);
 }
Example #24
0
 internal LiteQueryable(LiteCollection <T> collection)
 {
     _collection = collection;
     _foreach    = new List <Action <T, int> >();
     _query      = null;
 }
 public static async Task <T> FindByIdAsync <T>(this LiteCollection <T> collection, BsonValue id)
 {
     return(await Task.Run(() => collection.FindById(id)));
 }
 public static async Task <bool> ExistsAsync <T>(this LiteCollection <T> collection, Expression <Func <T, bool> > predicate)
 {
     return(await Task.Run(() => collection.Exists(predicate)));
 }
 public static async Task <int> CountAsync <T>(this LiteCollection <T> collection)
 {
     return(await Task.Run(() => collection.Count()));
 }
 public static async Task <long> LongCountAsync <T>(this LiteCollection <T> collection, Query query)
 {
     return(await Task.Run(() => collection.LongCount(query)));
 }
Example #29
0
 public LiteStorage(LiteDatabase db, string filesCollection, string chunksCollection)
 {
     _db     = db;
     _files  = db.GetCollection <LiteFileInfo <TFileId> >(filesCollection);
     _chunks = db.GetCollection(chunksCollection);
 }
 public static async Task <IEnumerable <T> > FindAllAsync <T>(this LiteCollection <T> collection)
 {
     return(await Task.Run(() => collection.FindAll()));
 }