public void GetDocumentId_When_Id_Field_DoesNotExist_Throw_KeyAttributeMissingException()
 {
     var route = new Route();
     var bucket = new Mock<IBucket>();
     var ctx = new BucketContext(bucket.Object);
     Assert.Throws<KeyAttributeMissingException>(()=>ctx.GetDocumentId(route));
 }
        public void CreateQueryRequest_Any_ReturnsQueryWrappedInQueryRequest()
        {
            // Arrange

            var bucket = new Mock<IBucket>();
            bucket.Setup(m => m.Name).Returns("default");
            bucket.Setup(m => m.Configuration).Returns(new BucketConfiguration()
            {
                PoolConfiguration = new PoolConfiguration(new ClientConfiguration())
            });

            var context = new BucketContext(bucket.Object);
            var query = context.Query<Brewery>();

            // Act

            var result = LinqQueryRequest.CreateQueryRequest(query, p => p.Any(q => q.Name == "name"));

            // Assert

            const string queryStr = "SELECT true as result FROM `default` as `Extent1` WHERE (`Extent1`.`name` = 'name') LIMIT 1";

            Assert.NotNull(result);
            Assert.AreEqual(queryStr, result.GetOriginalStatement());
            Assert.True(result.ScalarResultBehavior.ResultExtractionRequired);
            Assert.AreEqual(false, result.ScalarResultBehavior.NoRowsResult);
        }
        public void BeginChangeTracking_DoesNotClear_Modified_List()
        {
            var db = new BucketContext(ClusterHelper.GetBucket("beer-sample"));

            db.BeginChangeTracking();

            var query = from x in db.Query<Beer>()
                        where x.Type == "beer"
                        select x;

            db.BeginChangeTracking();

            var context = db as IChangeTrackableContext;

            Assert.AreEqual(0, context.ModifiedCount);

            var brewery = query.First();
            brewery.Abv = 10;

            Assert.AreEqual(1, context.ModifiedCount);

            db.BeginChangeTracking();

            Assert.AreEqual(1, context.ModifiedCount);
        }
 public void GetDocumentId_When_DocId_Exists_Use_It()
 {
     var beer = new Beer {Name = "beer1"};
     var bucket = new Mock<IBucket>();
     var ctx = new BucketContext(bucket.Object);
     var id = ctx.GetDocumentId(beer);
     Assert.AreEqual("beer1", id);
 }
예제 #5
0
        internal virtual void InitTest(Settings settings)
        {
            s3 = new S3Service()
            {
                AccessKeyID = settings.AccessKeyID,
                SecretAccessKey = settings.SecretAccessKey
            };

            bucket = new BucketContext() { BucketName = settings.TestBucketName, Service = s3 };
        }
 public void Remove_When_Write_Is_Not_Succesful_Throw_CouchbaseWriteException()
 {
     var beer = new Beer();
        var bucket = new Mock<IBucket>();
        var result = new Mock<IOperationResult<Beer>>();
        result.Setup(x => x.Success).Returns(false);
        bucket.Setup(x => x.Remove(It.IsAny<string>())).Returns(result.Object);
        var ctx = new BucketContext(bucket.Object);
        Assert.Throws<CouchbaseWriteException>(() => ctx.Remove(beer));
 }
 public void Save_When_KeyAttribute_Is_Not_Defined_Throw_DocumentIdMissingException()
 {
     var brewery = new Brewery();
        var bucket = new Mock<IBucket>();
        var result = new Mock<IOperationResult<Brewery>>();
        result.Setup(x => x.Status).Returns(ResponseStatus.Success);
        bucket.Setup(x => x.Upsert(It.IsAny<string>(), It.IsAny<Brewery>())).Returns(result.Object);
        var ctx = new BucketContext(bucket.Object);
        Assert.Throws<KeyAttributeMissingException>(()=>ctx.Save(brewery));
 }
 public void Remove_When_Write_Is_Succesful_Return_Success()
 {
     var beer = new Beer();
        var bucket = new Mock<IBucket>();
        var result = new Mock<IOperationResult<Beer>>();
        result.Setup(x => x.Status).Returns(ResponseStatus.Success);
        result.Setup(x => x.Success).Returns(true);
        bucket.Setup(x => x.Remove(It.IsAny<string>())).Returns(result.Object);
        var ctx = new BucketContext(bucket.Object);
        ctx.Remove(beer);
 }
        public async Task ExecuteAsync_WithAvg_ReturnsAvg()
        {
            var bucket = ClusterHelper.GetBucket("beer-sample");
            var context = new BucketContext(bucket);

            var beers = from b in context.Query<Beer>()
                        select b;

            var result = await beers.ExecuteAsync(p => p.Average(q => q.Abv));
            Console.WriteLine(result);
        }
예제 #10
0
        public void Test_Basic_Query()
        {
            var db = new BucketContext(ClusterHelper.GetBucket("beer-sample"));
            var query = from x in db.Query<Beer>()
                where x.Type == "beer"
                select x;

            foreach (var beer in query)
            {
                Console.WriteLine(beer.Name);
            }
        }
        public async Task ExecuteAsync_Any_ReturnsTrue()
        {
            var bucket = ClusterHelper.GetBucket("beer-sample");
            var context = new BucketContext(bucket);

            var beers = from b in context.Query<Beer>()
                        where b.Type == "beer" && b.Name == "21A IPA"
                        select b;

            var result = await beers.ExecuteAsync(p => p.Any());

            Assert.True(result);
        }
        public async Task ExecuteAsync_FirstOrDefaultNoValues_ReturnsDefault()
        {
            var bucket = ClusterHelper.GetBucket("beer-sample");
            var context = new BucketContext(bucket);

            var beers = from b in context.Query<Beer>()
                        where b.Name == "abcdefg"
                        select b.Abv;

            var result = await beers.ExecuteAsync(p => p.FirstOrDefault());

            Assert.AreEqual(0M, result);
        }
        public async Task ExecuteAsync_First_ReturnsFirst()
        {
            var bucket = ClusterHelper.GetBucket("beer-sample");
            var context = new BucketContext(bucket);

            var beers = from b in context.Query<Beer>()
                        select b;

            var result = await beers.ExecuteAsync(p => p.First());

            Assert.NotNull(result);
            Console.WriteLine(result.Name);
        }
        public async Task ExecuteAsync_NoParameters_ReturnsList()
        {
            var bucket = ClusterHelper.GetBucket("beer-sample");
            var context = new BucketContext(bucket);

            var beers = from b in context.Query<Beer>()
                select b;

            var results = (await beers.Take(1).ExecuteAsync()).ToList();
            Assert.AreEqual(1, results.Count);

            foreach (var beer in results)
            {
                Console.WriteLine(beer.Name);
            }
        }
        public void Query_DisableProxyGeneration_ReturnsNoProxy()
        {
            var db = new BucketContext(ClusterHelper.GetBucket("beer-sample"));

            const string documentId = "21st_amendment_brewery_cafe-21a_ipa";

            var query = from x in db.Query<Beer>().UseKeys(new[] { documentId })
                        where x.Type == "beer"
                        select x;

            var beer = query.First();

            // ReSharper disable once SuspiciousTypeConversion.Global
            var status = beer as ITrackedDocumentNode;

            Assert.Null(status);
        }
        public void AddToMutationState_DefaultToken_DoesNothing()
        {
            // Arrange

            var bucket = new Mock<IBucket>();
            bucket.SetupGet(m => m.Name).Returns("default");

            var db = new BucketContext(bucket.Object);

            // Act

            db.AddToMutationState(new MutationToken("default", -1, -1, 1));

            // Assert

            Assert.IsNull(db.MutationState);
        }
예제 #17
0
        static void Main(string[] args)
        {
            var config = new ClientConfiguration
            {
                Servers = new List<Uri> { new Uri("http://localhost:8091") }
            };

            ClusterHelper.Initialize(config);
            var db = new BucketContext(ClusterHelper.GetBucket("beer-sample"));
            var query = from b in db.Query<Beer>()
                        select b;

            foreach (var beer in query)
            {
                Console.WriteLine(beer.Type + ": " + beer.Name);
            }
            Console.Read();
            ClusterHelper.Close();
        }
        public void Query_EnableProxyGenerationAddAddress_FlagAsDirty()
        {
            var db = new BucketContext(ClusterHelper.GetBucket("beer-sample"))
            {
                EnableChangeTracking = true
            };

            var query = from x in db.Query<Brewery>()
                        where x.Type == "brewery" && x.Address.Any()
                        select x;

            var brewery = query.First();
            var addresses = brewery.Address;

            addresses.Add("Test");

            // ReSharper disable once SuspiciousTypeConversion.Global
            var status = addresses as ITrackedDocumentNode;

            Assert.NotNull(status);
            Assert.IsTrue(status.IsDirty);
        }
예제 #19
0
        public void AggregateTests_GroupBy()
        {
            var bucket = ClusterHelper.GetBucket("beer-sample");
            var context = new BucketContext(bucket);

            var breweries =
                from beer in context.Query<Beer>()
                where beer.Type == "beer"
                group beer by beer.BreweryId
                into g
                orderby g.Key
                select new {breweryid = g.Key, count = g.Count(), avgAbv = g.Average(p => p.Abv)};

            var results = breweries.Take(1).ToList();
            Assert.AreEqual(1, results.Count);

            foreach (var brewery in results)
            {
                Console.WriteLine("Brewery {0} has {1} beers with {2:f2} average ABV", brewery.breweryid, brewery.count,
                    brewery.avgAbv);
            }
        }
예제 #20
0
        public void AggregateTests_JoinBeforeGroupByAndMultipartKey()
        {
            var bucket = ClusterHelper.GetBucket("beer-sample");
            var context = new BucketContext(bucket);

            var breweries =
                from beer in context.Query<Beer>()
                join brewery in context.Query<Brewery>() on beer.BreweryId equals N1QlFunctions.Key(brewery)
                where beer.Type == "beer"
                group beer by new {breweryid = beer.BreweryId, breweryName = brewery.Name}
                into g
                select new {g.Key.breweryName, count = g.Count(), avgAbv = g.Average(p => p.Abv)};

            var results = breweries.Take(1).ToList();
            Assert.AreEqual(1, results.Count);

            foreach (var brewery in results)
            {
                Console.WriteLine("Brewery {0} has {1} beers with {2:f2} average ABV", brewery.breweryName,
                    brewery.count, brewery.avgAbv);
            }
        }
예제 #21
0
        public void AggregateTests_OrderByAggregate()
        {
            using (var cluster = new Cluster(TestConfigurations.DefaultConfig()))
            {
                using (var bucket = cluster.OpenBucket("beer-sample"))
                {
                    var context = new BucketContext(bucket);

                    var breweries =
                        from beer in context.Query <Beer>()
                        where beer.Type == "beer"
                        group beer by beer.BreweryId
                        into g
                        orderby g.Count() descending
                        select new { breweryid = g.Key, count = g.Count(), avgAbv = g.Average(p => p.Abv) };

                    foreach (var brewery in breweries)
                    {
                        Console.WriteLine("Brewery {0} has {1} beers with {2:f2} average ABV", brewery.breweryid, brewery.count, brewery.avgAbv);
                    }
                }
            }
        }
        public void Query_EnableProxyGenerationChangesInSubDocuments_FlagAsDirty()
        {
            var db = new BucketContext(ClusterHelper.GetBucket("beer-sample"))
            {
                EnableChangeTracking = true
            };

            var query = from x in db.Query<Brewery>()
                        where x.Type == "brewery" && N1QlFunctions.IsValued(x.Geo)
                        select x;

            var beer = query.First();

            // ReSharper disable once SuspiciousTypeConversion.Global
            var status = beer as ITrackedDocumentNode;

            Assert.NotNull(status);
            Assert.False(status.IsDirty);

            beer.Geo.Latitude = 90M;

            Assert.True(status.IsDirty);
        }
예제 #23
0
        public void JoinTests_LeftJoin_Prefiltered()
        {
            using (var cluster = new Cluster(TestConfigurations.DefaultConfig()))
            {
                using (var bucket = cluster.OpenBucket("beer-sample"))
                {
                    var context = new BucketContext(bucket);

                    var beers = from beer in context.Query <Beer>().Where(p => p.Type == "beer")
                                join breweryGroup in context.Query <Brewery>().Where(p => p.Type == "brewery")
                                on beer.BreweryId equals N1QlFunctions.Key(breweryGroup) into bg
                                from brewery in bg.DefaultIfEmpty()
                                    where beer.Abv > 4
                                orderby brewery.Name, beer.Name
                        select new { beer.Name, beer.Abv, BreweryName = brewery.Name };

                    foreach (var b in beers.Take(10))
                    {
                        Console.WriteLine("Beer {0} with ABV {1} is from {2}", b.Name, b.Abv, b.BreweryName);
                    }
                }
            }
        }
        public void Query_EnableProxyGenerationChangesInSubDocuments_FlagAsDirty()
        {
            var db = new BucketContext(ClusterHelper.GetBucket("beer-sample"))
            {
                EnableChangeTracking = true
            };

            var query = from x in db.Query <Brewery>()
                        where x.Type == "brewery" && N1QlFunctions.IsValued(x.Geo)
                        select x;

            var beer = query.First();

            // ReSharper disable once SuspiciousTypeConversion.Global
            var status = beer as ITrackedDocumentNode;

            Assert.NotNull(status);
            Assert.False(status.IsDirty);

            beer.Geo.Latitude = 90M;

            Assert.True(status.IsDirty);
        }
예제 #25
0
        public static List <Order> GetDocumentDataOrderByCompany(string userName)
        {
            _bucket = ClusterHelper.GetBucket("beer-sample");
            var    db  = new BucketContext(ClusterHelper.GetBucket("beer-sample"));
            string str = "SELECT c FROM `beer-sample` as c where email ='" + userName + "'";

            var user = _bucket.Query <dynamic>(str);

            if (user.Rows.Count > 0)
            {
                string companyName = user.Rows[0]["c"]["employee"]["company"]["companyName"].ToString();

                var query = from b in db.Query <Order>()
                            where b.Type == "Order" //&& b.Company.CompanyName == companyName//user.Rows[0].Employee.Company.CompanyName
                            select b;

                var rs = query.ToList();
                return(rs);
            }

            return(new List <Order>());
            //return query.FirstOrDefault();
        }
예제 #26
0
        public void AggregateTests_Having()
        {
            var context = new BucketContext(TestSetup.Bucket);

            var breweries =
                from beer in context.Query <Beer>()
                where beer.Type == "beer"
                group beer by beer.BreweryId
                into g
                where g.Count() >= 5
                orderby g.Key
                select new { breweryid = g.Key, count = g.Count(), avgAbv = g.Average(p => p.Abv) };

            var results = breweries.Take(1).ToList();

            Assert.AreEqual(1, results.Count);

            foreach (var brewery in results)
            {
                Console.WriteLine("Brewery {0} has {1} beers with {2:f2} average ABV", brewery.breweryid, brewery.count,
                                  brewery.avgAbv);
            }
        }
        public void Query_EnableProxyGenerationChanges_FlagAsDirty()
        {
            var db = new BucketContext(ClusterHelper.GetBucket("beer-sample"))
            {
                EnableChangeTracking = true
            };

            var query = from x in db.Query <Beer>()
                        where x.Type == "beer"
                        select x;

            var beer = query.First();

            // ReSharper disable once SuspiciousTypeConversion.Global
            var status = beer as ITrackedDocumentNode;

            Assert.NotNull(status);
            Assert.False(status.IsDirty);

            beer.Name = "New Name";

            Assert.True(status.IsDirty);
        }
예제 #28
0
        public void AggregateTests_JoinBeforeGroupByAndMultipartKey()
        {
            using (var cluster = new Cluster(TestConfigurations.DefaultConfig()))
            {
                using (var bucket = cluster.OpenBucket("beer-sample"))
                {
                    var context = new BucketContext(bucket);

                    var breweries =
                        from beer in context.Query <Beer>()
                        join brewery in context.Query <Brewery>() on beer.BreweryId equals N1QlFunctions.Key(brewery)
                            where beer.Type == "beer"
                        group beer by new { breweryid = beer.BreweryId, breweryName = brewery.Name }
                    into g
                        select new { g.Key.breweryName, count = g.Count(), avgAbv = g.Average(p => p.Abv) };

                    foreach (var brewery in breweries)
                    {
                        Console.WriteLine("Brewery {0} has {1} beers with {2:f2} average ABV", brewery.breweryName, brewery.count, brewery.avgAbv);
                    }
                }
            }
        }
예제 #29
0
        public async Task NestTests_Nest_IndexJoinPrefiltered()
        {
            var context = new BucketContext(TestSetup.Bucket);

            await EnsureIndexExists(context.Bucket, "brewery_id", "brewery_id");

            var breweries = from brewery in context.Query <Brewery>()
                            join beer in context.Query <BeerFiltered>() on N1QlFunctions.Key(brewery) equals beer.BreweryId into beers
                                where brewery.Type == "brewery"
                            select new { name = brewery.Name, beers };

            var results = breweries.Take(1).ToList();

            Assert.AreEqual(1, results.Count());

            foreach (var brewery in results)
            {
                foreach (var beer in brewery.beers)
                {
                    Console.WriteLine("Beer {0} with ABV {1} is from {2}", beer.Name, beer.Abv, brewery.name);
                }
            }
        }
예제 #30
0
        public void AggregateTests_GroupBy()
        {
            using (var cluster = new Cluster(TestConfigurations.DefaultConfig()))
            {
                using (var bucket = cluster.OpenBucket("beer-sample"))
                {
                    var context = new BucketContext(bucket);

                    var breweries =
                        from beer in context.Query<Beer>()
                        where beer.Type == "beer"
                        group beer by beer.BreweryId
                        into g
                        orderby g.Key
                        select new { breweryid = g.Key, count = g.Count(), avgAbv = g.Average(p => p.Abv)};

                    foreach (var brewery in breweries)
                    {
                        Console.WriteLine("Brewery {0} has {1} beers with {2:f2} average ABV", brewery.breweryid, brewery.count, brewery.avgAbv);
                    }
                }
            }
        }
예제 #31
0
        public async Task UseHashAndIndex_SelectDocuments()
        {
            var context = new BucketContext(_travelSample);

            var query =
                from route in context.Query <Route>()
                join airport in context.Query <Airport>()
                .UseHash(HashHintType.Build)
                .UseIndex("def_faa")
                .Where(p => p.Type == "airport")
                on route.DestinationAirport equals airport.Faa
                where route.Type == "route"
                select new { airport.AirportName, route.Airline };

            var results = await query.Take(1).ToListAsync();

            Assert.AreEqual(1, results.Count);

            foreach (var b in results)
            {
                Console.WriteLine("Route for airline {0} goes to {1}", b.Airline, b.AirportName);
            }
        }
예제 #32
0
        public void AggregateTests_JoinBeforeGroupByAndMultipartKey()
        {
            using (var cluster = new Cluster(TestConfigurations.DefaultConfig()))
            {
                using (var bucket = cluster.OpenBucket("beer-sample"))
                {
                    var context = new BucketContext(bucket);

                    var breweries =
                        from beer in context.Query<Beer>()
                        join brewery in context.Query<Brewery>() on beer.BreweryId equals N1QlFunctions.Key(brewery)
                        where beer.Type == "beer"
                        group beer by new { breweryid = beer.BreweryId, breweryName = brewery.Name }
                        into g
                        select new { g.Key.breweryName, count = g.Count(), avgAbv = g.Average(p => p.Abv) };

                    foreach (var brewery in breweries)
                    {
                        Console.WriteLine("Brewery {0} has {1} beers with {2:f2} average ABV", brewery.breweryName, brewery.count, brewery.avgAbv);
                    }
                }
            }
        }
예제 #33
0
        public override void PersistList(string key)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            QueueCommand(() =>
            {
                BucketContext context = new BucketContext(bucket);
                IList <string> ids    = context.Query <List>()
                                        .Where(l => l.DocumentType == DocumentTypes.List && l.Key == key)
                                        .Select(l => l.Id)
                                        .ToList();

                foreach (string id in ids)
                {
                    bucket.MutateIn <List>(id)
                    .Remove(s => s.ExpireOn)
                    .Execute();
                }
            });
        }
예제 #34
0
        public override void TrimList(string key, int keepStartingFrom, int keepEndingAt)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(nameof(key));
            }

            QueueCommand(() =>
            {
                keepEndingAt += 1 - keepStartingFrom;

                BucketContext context = new BucketContext(bucket);
                string[] ids          = context.Query <List>()
                                        .Where(l => l.DocumentType == DocumentTypes.List && l.Key == key)
                                        .OrderByDescending(l => l.CreatedOn)
                                        .Skip(keepStartingFrom)
                                        .Take(keepEndingAt)
                                        .Select(l => l.Id)
                                        .ToArray();

                bucket.Remove(ids, TimeSpan.FromSeconds(30));
            });
        }
        public async Task <MembershipTableData> ReadAll()
        {
            BucketContext b            = new BucketContext(bucket);
            var           readAllQuery = new QueryRequest("select meta(membership).id from membership");

            readAllQuery.ScanConsistency(ScanConsistency.RequestPlus);
            readAllQuery.Metrics(false);
            var ids = await bucket.QueryAsync <JObject>(readAllQuery).ConfigureAwait(false);

            var idStrings = ids.Rows.Select(x => x["id"].ToString()).ToArray();
            IDictionary <string, IOperationResult <CouchBaseSiloRegistration> > actuals = await Task.Run
                                                                                              (() => bucket.Get <CouchBaseSiloRegistration>(idStrings));//has no async version with batch reads

            List <Tuple <MembershipEntry, string> > entries = new List <Tuple <MembershipEntry, string> >();

            foreach (var actualRow in actuals.Values)
            {
                //var actualRow = await bucket.GetAsync<CouchBaseSiloRegistration>(r["id"].ToString());
                entries.Add(
                    CouchbaseSiloRegistrationmUtility.ToMembershipEntry(actualRow.Value, actualRow.Cas.ToString()));
            }
            return(new MembershipTableData(entries, new TableVersion(0, "0")));
        }
예제 #36
0
        public override void PersistHash(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(nameof(key));
            }

            QueueCommand(() =>
            {
                BucketContext context = new BucketContext(bucket);
                IList <string> ids    = context.Query <Hash>()
                                        .Where(s => s.DocumentType == DocumentTypes.Hash && s.Key == key)
                                        .Select(h => h.Id)
                                        .ToList();

                foreach (string id in ids)
                {
                    bucket.MutateIn <Hash>(id)
                    .Remove(s => s.ExpireOn)
                    .Execute();
                }
            });
        }
예제 #37
0
        public void Save_Updates_Duplicate_Document_In_Modified_List()
        {
            //arrange
            var bucket = new Mock <IBucket>();

            bucket.Setup(x => x.Configuration).Returns(new ClientConfiguration().BucketConfigs.First().Value);

            var ctx = new BucketContext(bucket.Object);

            ctx.BeginChangeTracking();

            var beer = new Beer
            {
                Name = "doc1" //key field
            };

            //act
            ctx.Save(beer);
            ctx.Save(beer);

            //assert
            Assert.AreEqual(1, ctx.ModifiedCount);
        }
예제 #38
0
        public async Task Map2PocoTests_Simple_Projections_TypeFilterRuntime()
        {
            var configuration = TestConfigurations.DefaultConfig(linqConfig =>
            {
                linqConfig.DocumentFilterManager.SetFilter(new BreweryFilter());
            });

            await using var cluster = await Couchbase.Cluster.ConnectAsync(configuration);

            await cluster.WaitUntilReadyAsync(TimeSpan.FromSeconds(10));

            var bucket = await cluster.BucketAsync("beer-sample");

            await EnsurePrimaryIndexExists(bucket);

            var context = new BucketContext(bucket);

            var breweries = (from b in context.Query <Brewery>()
                             select new { type = b.Type })
                            .AsEnumerable();

            Assert.True(breweries.All(p => p.type == "brewery"));
        }
예제 #39
0
        public void SubmitChanges_NewDoc_WithConsistencyCheck_UsesInsert()
        {
            //arrange

            var fakeResult = new Mock <IOperationResult <object> >();

            fakeResult.Setup(m => m.Status).Returns(ResponseStatus.Success);
            fakeResult.Setup(m => m.Success).Returns(true);

            var bucket = new Mock <IBucket>();

            bucket.Setup(x => x.Configuration).Returns(new ClientConfiguration().BucketConfigs.First().Value);
            bucket
            .Setup(x => x.Upsert(It.IsAny <string>(), It.IsAny <object>()))
            .Returns(fakeResult.Object);
            bucket
            .Setup(x => x.Insert(It.IsAny <string>(), It.IsAny <object>()))
            .Returns(fakeResult.Object);

            var ctx = new BucketContext(bucket.Object);

            ctx.BeginChangeTracking();

            var beer = new Beer()
            {
                Name = "Test"
            };

            ctx.Save(beer);

            //act
            ctx.SubmitChanges(new SaveOptions());

            //assert
            bucket.Verify(x => x.Upsert(It.IsAny <string>(), It.IsAny <object>()), Times.Never);
            bucket.Verify(x => x.Insert(It.IsAny <string>(), It.IsAny <object>()), Times.Once);
        }
        public override void SetRangeInHash(string key, IEnumerable <KeyValuePair <string, string> > keyValuePairs)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (keyValuePairs == null)
            {
                throw new ArgumentNullException(nameof(keyValuePairs));
            }

            Hash[] sources = keyValuePairs.Select(k => new Hash
            {
                Key   = key,
                Field = k.Key,
                Value = k.Value.TryParseToEpoch()
            }).ToArray();

            BucketContext     context = new BucketContext(bucket);
            IQueryable <Hash> hashes  = context.Query <Hash>()
                                        .Where(h => h.DocumentType == DocumentTypes.Hash && h.Key == key);

            foreach (Hash source in sources)
            {
                var hash = hashes.SingleOrDefault(h => h.Field == source.Field);
                if (hash != null)
                {
                    bucket.MutateIn <Hash>(hash.Id)
                    .Upsert(h => h.Value, source.Value, true)
                    .Execute();
                }
                else
                {
                    bucket.Insert(source.Id, source);
                }
            }
        }
예제 #41
0
        public override void RemoveFromList(string key, string value)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentNullException(nameof(value));
            }

            QueueCommand(() =>
            {
                BucketContext context = new BucketContext(bucket);
                IList <string> ids    = context.Query <List>()
                                        .Where(s => s.DocumentType == DocumentTypes.List && s.Key == key)
                                        .AsEnumerable()
                                        .Where(s => s.Value == value)
                                        .Select(l => l.Id)
                                        .ToList();

                bucket.Remove(ids, TimeSpan.FromSeconds(30));
            });
        }
        public void AddToMutationState_FirstRealTokenThenNull_DoesNothing()
        {
            // Arrange

            var bucket = new Mock<IBucket>();
            bucket.SetupGet(m => m.Name).Returns("default");

            var db = new BucketContext(bucket.Object);

            var token = new MutationToken("default", 1, 2, 3);
            db.AddToMutationState(token);

            // Act

            db.AddToMutationState(null);

            // Assert

            Assert.IsNotNull(db.MutationState);

            var tokens = MutationStateToList(db.MutationState);
            Assert.AreEqual(1, tokens.Count);
            Assert.Contains(token, tokens);
        }
예제 #43
0
        protected Task WaitUntilProjected(Expression <Func <ProductDocument, bool> > filter)
        {
            var taskCompletionSource = new TaskCompletionSource <ProductDocument>();

            ProductDocument doc;

            do
            {
                using (var bucket = _getBucket())
                {
                    try
                    {
                        doc = new BucketContext(bucket).Query <ProductDocument>().FirstOrDefault(filter);
                        taskCompletionSource.SetResult(doc);
                    }
                    catch (Exception ex)
                    {
                        doc = null;
                    }
                }
            } while (doc == null);

            return(taskCompletionSource.Task);
        }
예제 #44
0
        public void EndChangeTracking_WhenCalled_ModifiedList()
        {
            //arrange
            var bucket = new Mock <IBucket>();

            bucket.Setup(x => x.Configuration).Returns(new ClientConfiguration().BucketConfigs.First().Value);

            var ctx = new BucketContext(bucket.Object);

            ctx.BeginChangeTracking();

            var beer = new Beer
            {
                Name = "doc1" //key field
            };

            ctx.Save(beer);

            //act
            ctx.EndChangeTracking();

            //assert
            Assert.AreEqual(0, ctx.ModifiedCount);
        }
예제 #45
0
        public void GetDocumentId_DocumentProxyVirtualA_UsesMetadataNotProperty()
        {
            //arrange
            var document = (VirtualKeyA)DocumentProxyManager.Default.CreateProxy(typeof(VirtualKeyA));

            document.A = "Key1";

            // ReSharper disable once SuspiciousTypeConversion.Global
            var trackedDoc = (ITrackedDocumentNode)document;

            trackedDoc.Metadata = new DocumentMetadata()
            {
                Id = "Key2"
            };

            var bucket = new Mock <IBucket>();
            var ctx    = new BucketContext(bucket.Object);

            //act
            var result = ctx.GetDocumentId(document);

            //assert
            Assert.AreEqual("Key2", result);
        }
        public void CreateQueryRequest_ScanConsistency_HasSetting()
        {
            // Arrange

            var bucket = new Mock <IBucket>();

            bucket.Setup(m => m.Name).Returns("default");
            bucket.Setup(m => m.Configuration).Returns(new BucketConfiguration()
            {
                PoolConfiguration = new PoolConfiguration(new ClientConfiguration())
            });

            var context = new BucketContext(bucket.Object);
            var query   = context.Query <Brewery>().ScanConsistency(ScanConsistency.RequestPlus).Where(p => p.Name == "name");

            // Act

            var result = LinqQueryRequest.CreateQueryRequest(query);

            // Assert

            Assert.NotNull(result);
            Assert.AreEqual("request_plus", result.GetFormValues()["scan_consistency"]);
        }
예제 #47
0
        public async Task Query()
        {
            // Ensure that the database starts out empty.

            couchbase.Clear();

            await Assert.ThrowsAsync <CouchbaseKeyValueResponseException>(async() => await bucket.GetSafeAsync <string>("jack"));

            await Assert.ThrowsAsync <CouchbaseKeyValueResponseException>(async() => await bucket.GetSafeAsync <string>("jill"));

            // Write a couple documents and then query for them.  Note
            // that we're explicitly using [RequestPlus] consistency
            // and we're doing a synchronous query.

            await bucket.UpsertSafeAsync("jack", new TestDoc()
            {
                Name = "Jack", Age = 11
            });

            await bucket.UpsertSafeAsync("jill", new TestDoc()
            {
                Name = "Jill", Age = 12
            });

            var context = new BucketContext(bucket);

            // Note that we're explicitly using [RequestPlus] consistency
            // and we're doing a synchronous query.

            var query =
                from doc in context.Query <TestDoc>()
                .ScanConsistency(Couchbase.N1QL.ScanConsistency.RequestPlus)
                select doc;

            var results = query.ToList();

            Assert.Equal(2, results.Count);
            Assert.Single(results.Where(doc => doc.Name == "Jack"));
            Assert.Single(results.Where(doc => doc.Name == "Jill"));

            // Use Couchbase [IQueryable<T>.ExecuteAsync()] to execute the query
            // and enable result streaming from the server.

            query =
                from doc in context.Query <TestDoc>()
                .ScanConsistency(Couchbase.N1QL.ScanConsistency.RequestPlus)
                .UseStreaming(true)
                select doc;

            await query.ExecuteAsync();

            results = query.ToList();

            Assert.Equal(2, results.Count);
            Assert.Single(results.Where(doc => doc.Name == "Jack"));
            Assert.Single(results.Where(doc => doc.Name == "Jill"));

            // Do a string based query using the [QueryAsync()] extension
            // method which throws an exception on errors.  Note that this doesn't
            // appear to be compatible with streaming (Rows is NULL).

            var queryRequest = new QueryRequest($"select {bucket.Name}.* from {bucket.Name}")
                               .ScanConsistency(ScanConsistency.RequestPlus);

            var queryResult = await bucket.QueryAsync <TestDoc>(queryRequest);

            var rows = queryResult.Rows;

            Assert.Equal(2, rows.Count);
            Assert.Single(rows.Where(doc => doc.Name == "Jack"));
            Assert.Single(rows.Where(doc => doc.Name == "Jill"));

            // Do a string based query using the [QuerySafeAsync()] extension
            // method which throws an exception on errors.  Note that this doesn't
            // appear to be compatible with streaming (the result is NULL).

            queryRequest = new QueryRequest($"select {bucket.Name}.* from {bucket.Name}")
                           .ScanConsistency(ScanConsistency.RequestPlus);

            results = await bucket.QuerySafeAsync <TestDoc>(queryRequest);

            Assert.Equal(2, results.Count);
            Assert.Single(results.Where(doc => doc.Name == "Jack"));
            Assert.Single(results.Where(doc => doc.Name == "Jill"));
        }
        public void SubmitChanges_WhenCalled_DoesNotClearTrackedList()
        {
            //arrange
            var bucket = new Mock<IBucket>();
            bucket.Setup(x => x.Configuration).Returns(new ClientConfiguration().BucketConfigs.First().Value);

            var ctx = new BucketContext(bucket.Object);
            ctx.BeginChangeTracking();

            var beer = new Beer
            {
                Name = "doc1" //key field
            };

            ctx.Save(beer);

            //act
            ctx.SubmitChanges();

            //assert
            Assert.AreEqual(1, ctx.TrackedCount);
        }
        public void SubmitChanges_Removes_Document_From_Modified_List()
        {
            //arrange
            var bucket = new Mock<IBucket>();
            bucket.Setup(x => x.Configuration).Returns(new ClientConfiguration().BucketConfigs.First().Value);

            var ctx = new BucketContext(bucket.Object);
            ctx.BeginChangeTracking();

            var beer = new Beer
            {
                Name = "doc1" //key field
            };

            ctx.Save(beer);

            //act
            ctx.SubmitChanges();

            //assert
            Assert.AreEqual(0, ctx.ModifiedCount);
        }
        public void Save_When_Write_Is_Succesful_Return_Success()
        {
            //arrange
            var beer = new Beer();
            var bucket = new Mock<IBucket>();
            var result = new Mock<IOperationResult<Beer>>();
            result.Setup(x => x.Status).Returns(ResponseStatus.Success);
            result.Setup(x => x.Success).Returns(true);
            bucket.Setup(x => x.Upsert(It.IsAny<string>(), It.IsAny<Beer>())).Returns(result.Object);
            var ctx = new BucketContext(bucket.Object);

            //act
            ctx.Save(beer);

            //assert - does not throw exception
        }
        public void Save_WhenChangeTrackingEnabled_AddsToTrackedList()
        {
            //arrange
            var bucket = new Mock<IBucket>();
            bucket.Setup(x => x.Configuration).Returns(new ClientConfiguration().BucketConfigs.First().Value);

            var ctx = new BucketContext(bucket.Object);
            ctx.BeginChangeTracking();

            var beer = new Beer
            {
                Name = "doc1" //key field
            };

            ctx.Save(beer);

            Assert.AreEqual(1, ctx.TrackedCount);
        }
        public void ResetMutationState_NoState_StillNull()
        {
            // Arrange

            var bucket = new Mock<IBucket>();
            bucket.SetupGet(m => m.Name).Returns("default");

            var db = new BucketContext(bucket.Object);
            Assert.Null(db.MutationState);

            // Act

            db.ResetMutationState();

            // Assert

            Assert.Null(db.MutationState);
        }
        public void ResetMutationState_HasState_SetsToNull()
        {
            // Arrange

            var bucket = new Mock<IBucket>();
            bucket.SetupGet(m => m.Name).Returns("default");

            var db = new BucketContext(bucket.Object);

            db.AddToMutationState(new MutationToken("default", 1, 2, 3));
            Assert.NotNull(db.MutationState);

            // Act

            db.ResetMutationState();

            // Assert

            Assert.Null(db.MutationState);
        }
예제 #54
0
 public WorkBucket <Resource, BucketContext> AddBucket(string name, int nbThreads, BucketContext context)
 {
     return(WorkDispatcher.AddBucket(name, nbThreads, context));
 }
예제 #55
0
 protected override void BeginUow()
 {
     Bucket  = _cluster.OpenBucket();
     Session = new BucketContext(Bucket);
     Session.BeginChangeTracking();
 }
예제 #56
0
 public UserRepository(IBucketProvider bucketProvider)
 {
     _bucket        = bucketProvider.GetBucket("user_profile");
     _bucketContext = new BucketContext(_bucket);
 }
        public void Fill(BucketContext bucketContext)
        {
            Debug.Assert(ContextType.IsInstanceOfType(bucketContext));

            Initialize(bucketContext);
        }
        public void Execute(CancellationToken cancellationToken)
        {
            using (new CouchbaseDistributedLock(DISTRIBUTED_LOCK_KEY, defaultLockTimeout, storage))
            {
                logger.Trace("Aggregating records in 'Counter' table.");

                using (IBucket bucket = storage.Client.OpenBucket(storage.Options.DefaultBucket))
                {
                    // context
                    BucketContext context = new BucketContext(bucket);

                    List <Counter> rawCounters = context.Query <Counter>()
                                                 .Where(c => c.DocumentType == DocumentTypes.Counter && c.Type == CounterTypes.Raw)
                                                 .ToList();

                    Dictionary <string, (int Value, int?ExpireOn, List <Counter> Counters)> counters = rawCounters.GroupBy(c => c.Key)
                                                                                                       .ToDictionary(k => k.Key, v => (Value: v.Sum(c => c.Value), ExpireOn: v.Max(c => c.ExpireOn), Counters: v.ToList()));

                    foreach (string key in counters.Keys)
                    {
                        cancellationToken.ThrowIfCancellationRequested();

                        if (counters.TryGetValue(key, out var data))
                        {
                            Counter aggregated;
                            string  id = $"{key}:{CounterTypes.Aggregate}".GenerateHash();
                            IOperationResult <Counter> operation = bucket.Get <Counter>(id, TimeSpan.FromMinutes(1));

                            if (operation.Success == false && operation.Value == null)
                            {
                                aggregated = new Counter
                                {
                                    Id       = id,
                                    Key      = key,
                                    Type     = CounterTypes.Aggregate,
                                    Value    = data.Value,
                                    ExpireOn = data.ExpireOn
                                };
                            }
                            else if (operation.Success && operation.Value.Type == CounterTypes.Aggregate)
                            {
                                aggregated          = operation.Value;
                                aggregated.Value   += data.Value;
                                aggregated.ExpireOn = new[] { aggregated.ExpireOn, data.ExpireOn }.Max();
                            }
                            else
                            {
                                logger.Warn($"Document with ID: {id} is a {operation.Value.Type.ToString()} type");
                                continue;
                            }

                            IOperationResult <Counter> result = bucket.Upsert(aggregated.Id, aggregated);
                            if (result.Success)
                            {
                                IList <string> ids = data.Counters
                                                     .Select(counter => counter.Id)
                                                     .ToList();

                                bucket.Remove(ids, new ParallelOptions {
                                    CancellationToken = cancellationToken
                                }, TimeSpan.FromMinutes(1));
                                logger.Trace($"Total {ids.Count} records from the 'Counter:{aggregated.Key}' were aggregated.");
                            }
                        }
                    }
                }

                logger.Trace("Records from the 'Counter' table aggregated.");
            }

            cancellationToken.WaitHandle.WaitOne(storage.Options.CountersAggregateInterval);
        }
예제 #59
0
 public ContactsController(BucketContext bucketContext)
 {
     _bucketContext = bucketContext;
 }