Exemple #1
0
        public void Will_not_save_when_flush_mode_is_never()
        {
            object id;

            using (var tx = new TransactionScope())
            {
                using (ISession s = Sfi.OpenSession())
                {
                    s.FlushMode = FlushMode.Manual;
                    id          = s.Save(new Nums {
                        NumA = 1, NumB = 2, ID = 5
                    });
                }
                tx.Complete();
            }

            using (ISession s = Sfi.OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    Nums nums = s.Get <Nums>(id);
                    Assert.IsNull(nums);
                    tx.Commit();
                }
        }
        private void QueryKeyFilterDescValueToCompare(out QueryKey qk, out QueryKey qk1, bool sameValue)
        {
            const string filterName = "DescriptionEqualAndValueGT";

            var f = new FilterImpl(Sfi.GetFilterDefinition(filterName));

            f.SetParameter("pDesc", "something").SetParameter("pValue", 10);
            var fk = new FilterKey(f);
            ISet <FilterKey> fks = new HashSet <FilterKey> {
                fk
            };

            qk = new QueryKey(Sfi, SqlAll, new QueryParameters(), fks, null);

            var f1 = new FilterImpl(Sfi.GetFilterDefinition(filterName));

            f1.SetParameter("pDesc", "something").SetParameter("pValue", sameValue ? 10 : 11);
            var fk1 = new FilterKey(f1);

            fks = new HashSet <FilterKey> {
                fk1
            };
            qk1 = new QueryKey(Sfi, SqlAll, new QueryParameters(), fks, null);
        }
Exemple #3
0
        protected override void OnSetUp()
        {
            using (var s = Sfi.OpenSession())
                using (s.BeginTransaction())
                {
                    var parent = new Employee
                    {
                        Id = 2,
                    };
                    var emp = new Employee
                    {
                        Id      = 1,
                        Amounts = new HashSet <Money>
                        {
                            new Money {
                                Amount = 9, Currency = "USD"
                            },
                            new Money {
                                Amount = 3, Currency = "EUR"
                            },
                        },
                        ManagedEmployees = new HashSet <ManagedEmployee>
                        {
                            new ManagedEmployee
                            {
                                Position = "parent",
                                Employee = parent
                            }
                        }
                    };
                    s.Save(parent);
                    s.Save(emp);

                    s.Transaction.Commit();
                }
        }
        public async Task StatelessSessionLoadsOneToOneRelatedObject_WithoutPropertyRefAsync()
        {
            var companyId = 0;

            using (ISession session = OpenSession())
            {
                using (ITransaction tx = session.BeginTransaction())
                {
                    var company = new CompanyO2O {
                        Name = "Test Company"
                    };
                    var address = new AddressO2O {
                        AddressLine1 = "Company Address"
                    };

                    address.SetCompany(company);

                    // Have to save the address to get the company to be saved as well
                    // Saving company doesn't save the address.
                    companyId = (int)await(session.SaveAsync(address));

                    await(tx.CommitAsync());
                }
            }


            using (var stateless = Sfi.OpenStatelessSession())
            {
                var loadedCompany = await(stateless.GetAsync <CompanyO2O>(companyId));

                Assert.That(loadedCompany, Is.Not.Null);
                Assert.That(loadedCompany.Name, Is.Not.Null);
                Assert.That(loadedCompany.Address, Is.Not.Null);
                Assert.That(loadedCompany.Address.AddressLine1, Is.Not.Null);
            }
        }
Exemple #5
0
        public async Task Will_not_save_when_flush_mode_is_neverAsync()
        {
            object id;

            using (var tx = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                using (ISession s = Sfi.OpenSession())
                {
                    s.FlushMode = FlushMode.Manual;
                    id          = await(s.SaveAsync(new Nums {
                        NumA = 1, NumB = 2, ID = 5
                    }));
                }
                tx.Complete();
            }

            using (ISession s = Sfi.OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    Nums nums = await(s.GetAsync <Nums>(id));
                    Assert.IsNull(nums);
                    await(tx.CommitAsync());
                }
        }
        public void SuppliedConnection()
        {
            Prepare();

            using (var originalConnection = Sfi.ConnectionProvider.GetConnection())
                using (var session = Sfi.WithOptions().Connection(originalConnection).OpenSession())
                {
                    var silly = new Silly("silly");
                    session.Save(silly);

                    // this will cause the connection manager to cycle through the aggressive Release logic;
                    // it should not Release the connection since we explicitly supplied it ourselves.
                    session.Flush();

                    Assert.IsTrue(originalConnection == session.Connection, "Different connections");

                    session.Delete(silly);
                    session.Flush();

                    Release(session);
                    originalConnection.Close();
                }
            Done();
        }
Exemple #7
0
        public void TwoTransactionScopesInsideOneSession()
        {
            IgnoreIfTransactionScopeInsideSessionIsNotSupported();

            var interceptor = new RecordingInterceptor();

            using (var session = Sfi.WithOptions().Interceptor(interceptor).OpenSession())
            {
                using (var scope = new TransactionScope())
                {
                    session.CreateCriteria <object>().List();
                    scope.Complete();
                }

                using (var scope = new TransactionScope())
                {
                    session.CreateCriteria <object>().List();
                    scope.Complete();
                }
            }
            Assert.AreEqual(2, interceptor.afterTransactionBeginCalled);
            Assert.AreEqual(2, interceptor.beforeTransactionCompletionCalled);
            Assert.AreEqual(2, interceptor.afterTransactionCompletionCalled);
        }
        public void UsingManyParametersAndQueries_DoesNotCauseParameterNameCollisions()
        {
            //GH-1357
            using (var s = OpenSession())
                using (var tx = s.BeginTransaction())
                {
                    var p1 = new Person {
                        Name = "Person name", Age = 15
                    };
                    var p2 = new Person {
                        Name = "Person name", Age = 5
                    };

                    s.Save(p1);
                    s.Save(p2);
                    tx.Commit();
                }
            using (var s = Sfi.OpenSession())
            {
                var list = new List <IFutureEnumerable <Person> >();
                for (var i = 0; i < 12; i++)
                {
                    var query = s.Query <Person>();
                    for (var j = 0; j < 12; j++)
                    {
                        query = query.Where(x => x.Age > j);
                    }
                    list.Add(query.WithOptions(x => x.SetCacheable(true)).ToFuture());
                }
                foreach (var query in list)
                {
                    var result = query.ToList();
                    Assert.That(result.Count, Is.EqualTo(1));
                }
            }
        }
Exemple #9
0
        public void CanUseFutureCriteria()
        {
            using (var s = Sfi.OpenSession())
            {
                IgnoreThisTestIfMultipleQueriesArentSupportedByDriver();

                var persons10 = s.QueryOver <Person>()
                                .Take(10)
                                .Future();
                var persons5 = s.QueryOver <Person>()
                               .Select(p => p.Id)
                               .Take(5)
                               .Future <int>();

                using (var logSpy = new SqlLogSpy())
                {
                    int actualPersons5Count = 0;
                    foreach (var person in persons5)
                    {
                        actualPersons5Count++;
                    }

                    int actualPersons10Count = 0;
                    foreach (var person in persons10)
                    {
                        actualPersons10Count++;
                    }

                    var events = logSpy.Appender.GetEvents();
                    Assert.AreEqual(1, events.Length);

                    Assert.That(actualPersons5Count, Is.EqualTo(1));
                    Assert.That(actualPersons10Count, Is.EqualTo(1));
                }
            }
        }
        public void CanGetMultiQueryFromSecondLevelCache()
        {
            CreateItems();
            //set the query in the cache
            DoMutiQueryAndAssert();

            var cacheHashtable  = GetHashTableUsedAsQueryCache(Sfi);
            var cachedListEntry = (IList) new ArrayList(cacheHashtable.Values)[0];
            var cachedQuery     = (IList)cachedListEntry[1];

            var firstQueryResults = (IList)cachedQuery[0];

            firstQueryResults.Clear();
            firstQueryResults.Add(3);
            firstQueryResults.Add(4);

            var secondQueryResults = (IList)cachedQuery[1];

            secondQueryResults[0] = 2L;

            using (var s = Sfi.OpenSession())
            {
                var multiQuery = s.CreateMultiQuery()
                                 .Add(s.CreateQuery("from Item i where i.Id > ?")
                                      .SetInt32(0, 50)
                                      .SetFirstResult(10))
                                 .Add(s.CreateQuery("select count(*) from Item i where i.Id > ?")
                                      .SetInt32(0, 50));
                multiQuery.SetCacheable(true);
                var results = multiQuery.List();
                var items   = (IList)results[0];
                Assert.AreEqual(2, items.Count);
                var count = (long)((IList)results[1])[0];
                Assert.AreEqual(2L, count);
            }
        }
        public async Task Can_evict_when_trying_to_evict_entity_from_another_sessionAsync()
        {
            using (var session1 = Sfi.OpenSession())
                using (var tx1 = session1.BeginTransaction())
                {
                    using (var session2 = Sfi.OpenSession())
                        using (var tx2 = session2.BeginTransaction())
                        {
                            var employee = await(session2.LoadAsync <Employee>(1));
                            Assert.IsFalse(session1.Contains(employee));
                            Assert.IsTrue(session2.Contains(employee));

                            await(session1.EvictAsync(employee));

                            Assert.IsFalse(session1.Contains(employee));

                            Assert.IsTrue(session2.Contains(employee));

                            await(tx2.CommitAsync());
                        }

                    await(tx1.CommitAsync());
                }
        }
        protected override void OnSetUp()
        {
            isContractPartiesInverse = Sfi.GetCollectionPersister(typeof(Contract).FullName + ".Parties").IsInverse;
            try
            {
                Sfi.GetEntityPersister(typeof(Party).FullName).GetPropertyType("Contract");
                isContractPartiesBidirectional = true;
            }
            catch (QueryException)
            {
                isContractPartiesBidirectional = false;
            }
            try
            {
                Sfi.GetEntityPersister(typeof(ContractVariation).FullName).GetPropertyType("Contract");
                isContractVariationsBidirectional = true;
            }
            catch (QueryException)
            {
                isContractVariationsBidirectional = false;
            }

            isContractVersioned = Sfi.GetEntityPersister(typeof(Contract).FullName).IsVersioned;
        }
 private async Task CreateDataAsync(CancellationToken cancellationToken = default(CancellationToken))
 {
     using (ISession session = Sfi.OpenSession())
         using (ITransaction tx = session.BeginTransaction())
         {
             Person root = new Person();
             await(session.SaveAsync(root, cancellationToken));
             for (int i = 0; i < 2; i++)
             {
                 Person child = new Person();
                 root.Children.Add(child);
                 child.Parent = root;
                 await(session.SaveAsync(child, cancellationToken));
                 for (int j = 0; j < 3; j++)
                 {
                     Person child2 = new Person();
                     child2.Parent = child;
                     child.Children.Add(child2);
                     await(session.SaveAsync(child2, cancellationToken));
                 }
             }
             await(tx.CommitAsync(cancellationToken));
         }
 }
Exemple #14
0
        public void Can_evict_when_trying_to_evict_entity_from_another_session()
        {
            using (var session1 = Sfi.OpenSession())
                using (var tx1 = session1.BeginTransaction())
                {
                    using (var session2 = Sfi.OpenSession())
                        using (var tx2 = session2.BeginTransaction())
                        {
                            var employee = session2.Load <Employee>(1);
                            Assert.IsFalse(session1.Contains(employee));
                            Assert.IsTrue(session2.Contains(employee));

                            session1.Evict(employee);

                            Assert.IsFalse(session1.Contains(employee));

                            Assert.IsTrue(session2.Contains(employee));

                            tx2.Commit();
                        }

                    tx1.Commit();
                }
        }
        public async Task ExceptionsInSynchronizationBeforeTransactionCompletionAbortTransactionAsync()
        {
            var c = new C {
                ID = 1, Value = "value"
            };

            var synchronization = new SynchronizationThatThrowsExceptionAtBeforeTransactionCompletion();

            using (ISession s = Sfi.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    t.RegisterSynchronization(synchronization);

                    await(s.SaveAsync(c));

                    Assert.ThrowsAsync <BadException>(() => t.CommitAsync());
                }

            using (ISession s = Sfi.OpenSession())
            {
                var objectInDb = await(s.GetAsync <C>(1));
                Assert.IsNull(objectInDb);
            }
        }
        public void CacheableRegionBeforeOtherClauses()
        {
            Sfi.Statistics.Clear();
            Sfi.EvictQueries();
            Sfi.EvictQueries("test");
            Sfi.EvictQueries("other");

            db.Customers
            .WithOptions(o => o.SetCacheable(true).SetCacheRegion("test"))
            .Where(c => c.ContactName != c.CompanyName).Take(1)
            .ToList();
            db.Customers
            .WithOptions(o => o.SetCacheable(true).SetCacheRegion("test"))
            .Where(c => c.ContactName != c.CompanyName).Take(1)
            .ToList();
            db.Customers
            .WithOptions(o => o.SetCacheable(true).SetCacheRegion("other"))
            .Where(c => c.ContactName != c.CompanyName).Take(1)
            .ToList();

            Assert.That(Sfi.Statistics.QueryExecutionCount, Is.EqualTo(2), "Unexpected execution count");
            Assert.That(Sfi.Statistics.QueryCachePutCount, Is.EqualTo(2), "Unexpected cache put count");
            Assert.That(Sfi.Statistics.QueryCacheHitCount, Is.EqualTo(1), "Unexpected cache hit count");
        }
Exemple #17
0
        public async Task CanGetMultiQueryFromSecondLevelCacheAsync()
        {
            await(CreateItemsAsync());
            //set the query in the cache
            await(DoMutiQueryAndAssertAsync());

            var cacheHashtable  = MultipleQueriesFixtureAsync.GetHashTableUsedAsQueryCache(Sfi);
            var cachedListEntry = (IList) new ArrayList(cacheHashtable.Values)[0];
            var cachedQuery     = (IList)cachedListEntry[1];

            var firstQueryResults = (IList)cachedQuery[0];

            firstQueryResults.Clear();
            firstQueryResults.Add(3);
            firstQueryResults.Add(4);

            var secondQueryResults = (IList)cachedQuery[1];

            secondQueryResults[0] = 2L;

            using (var s = Sfi.OpenSession())
            {
                var multiQuery = s.CreateMultiQuery()
                                 .Add(s.CreateSQLQuery("select * from ITEM where Id > ?").AddEntity(typeof(Item))
                                      .SetInt32(0, 50)
                                      .SetFirstResult(10))
                                 .Add(s.CreateQuery("select count(*) from Item i where i.Id > ?")
                                      .SetInt32(0, 50));
                multiQuery.SetCacheable(true);
                var results = await(multiQuery.ListAsync());
                var items   = (IList)results[0];
                Assert.AreEqual(2, items.Count);
                var count = (long)((IList)results[1])[0];
                Assert.AreEqual(2L, count);
            }
        }
        public void UsingCriteriaAndHql()
        {
            CreateData();

            using (SqlLogSpy spy = new SqlLogSpy())
                using (ISession session = Sfi.OpenSession())
                    using (ITransaction tx = session.BeginTransaction())
                    {
                        Person result = session.CreateQuery(@"
select p from Person p 
join fetch p.Children c 
join fetch c.Children gc
where p.Parent is null")
                                        .UniqueResult <Person>();

                        string hqlQuery = spy.Appender.GetEvents()[0].RenderedMessage;
                        Debug.WriteLine("HQL: " + hqlQuery);
                        Assertions(result);
                    }

            using (SqlLogSpy spy = new SqlLogSpy())
                using (ISession session = Sfi.OpenSession())
                    using (ITransaction tx = session.BeginTransaction())
                    {
                        Person result = session.CreateCriteria(typeof(Person))
                                        .Add(Restrictions.IsNull("Parent"))
                                        .SetFetchMode("Children", FetchMode.Join)
                                        .SetFetchMode("Children.Children", FetchMode.Join)
                                        .UniqueResult <Person>();
                        string criteriaQuery = spy.Appender.GetEvents()[0].RenderedMessage;
                        Debug.WriteLine("Criteria: " + criteriaQuery);
                        Assertions(result);
                    }

            DeleteData();
        }
        public void CanUseFutureQueryWithAnonymousType()
        {
            IgnoreThisTestIfMultipleQueriesArentSupportedByDriver();

            using (var s = Sfi.OpenSession())
            {
                var persons = s.Query <Person>()
                              .Select(p => new { Id = p.Id, Name = p.Name })
                              .ToFuture();
                var persons5 = s.Query <Person>()
                               .Select(p => new { Id = p.Id, Name = p.Name })
                               .Take(5)
                               .ToFuture();

                using (var logSpy = new SqlLogSpy())
                {
                    persons5.GetEnumerable().ToList();                     // initialize the enumerable
                    persons.GetEnumerable().ToList();

                    var events = logSpy.Appender.GetEvents();
                    Assert.AreEqual(1, events.Length);
                }
            }
        }
 private void CreateData()
 {
     using (ISession session = Sfi.OpenSession())
         using (ITransaction tx = session.BeginTransaction())
         {
             Person root = new Person();
             session.Save(root);
             for (int i = 0; i < 2; i++)
             {
                 Person child = new Person();
                 root.Children.Add(child);
                 child.Parent = root;
                 session.Save(child);
                 for (int j = 0; j < 3; j++)
                 {
                     Person child2 = new Person();
                     child2.Parent = child;
                     child.Children.Add(child2);
                     session.Save(child2);
                 }
             }
             tx.Commit();
         }
 }
Exemple #21
0
        public async Task UsingSqlFunctions_Concat_WithCastAsync()
        {
            if (Dialect is Oracle8iDialect)
            {
                Assert.Ignore("Not supported by the active dialect:{0}.", Dialect);
            }
            if (TestDialect.HasBrokenTypeInferenceOnSelectedParameters)
            {
                Assert.Ignore("Current dialect does not support this test");
            }

            using (ISession session = Sfi.OpenSession())
            {
                string result = await(session.CreateCriteria(typeof(Student))
                                      .SetProjection(Projections.SqlFunction("concat",
                                                                             NHibernateUtil.String,
                                                                             Projections.Cast(NHibernateUtil.String, Projections.Id()),
                                                                             Projections.Constant(" "),
                                                                             Projections.Property("Name")
                                                                             ))
                                      .UniqueResultAsync <string>());
                Assert.AreEqual("27 ayende", result);
            }
        }
        public void ToStringWithFilters()
        {
            string filterName = "DescriptionLike";
            var    f          = new FilterImpl(Sfi.GetFilterDefinition(filterName));

            f.SetParameter("pLike", "so%");
            var fk = new FilterKey(f);
            ISet <FilterKey> fks = new HashSet <FilterKey> {
                fk
            };
            var qk = new QueryKey(Sfi, SqlAll, new QueryParameters(), fks, null);

            Assert.That(qk.ToString(), Does.Contain($"filters: ['{fk}']"), "Like");

            filterName = "DescriptionEqualAndValueGT";
            f          = new FilterImpl(Sfi.GetFilterDefinition(filterName));
            f.SetParameter("pDesc", "something").SetParameter("pValue", 10);
            fk  = new FilterKey(f);
            fks = new HashSet <FilterKey> {
                fk
            };
            qk = new QueryKey(Sfi, SqlAll, new QueryParameters(), fks, null);
            Assert.That(qk.ToString(), Does.Contain($"filters: ['{fk}']"), "Value");
        }
Exemple #23
0
        protected virtual bool CheckDatabaseWasCleaned()
        {
            var allClassMetadata = Sfi.GetAllClassMetadata();

            if (allClassMetadata.Count == 0)
            {
                // Return early in the case of no mappings, also avoiding
                // a warning when executing the HQL below.
                return(true);
            }

            var explicitPolymorphismEntities = allClassMetadata.Values.Where(x => x is NHibernate.Persister.Entity.IQueryable queryable && queryable.IsExplicitPolymorphism).ToArray();

            //TODO: Maybe add explicit load query checks
            if (explicitPolymorphismEntities.Length == allClassMetadata.Count)
            {
                return(true);
            }

            bool empty;

            using (ISession s = OpenSession())
            {
                IList objects = s.CreateQuery("from System.Object o").List();
                empty = objects.Count == 0;
            }

            if (!empty)
            {
                log.Error("Test case didn't clean up the database after itself, re-creating the schema");
                DropSchema();
                CreateSchema();
            }

            return(empty);
        }
Exemple #24
0
        public async Task TestComponentAsync()
        {
            User u;

            using (ISession s = Sfi.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    u = new User("gavin", "secret", new Person("Gavin King", new DateTime(1999, 12, 31), "Karbarook Ave"));
                    await(s.PersistAsync(u));
                    await(s.FlushAsync());
                    u.Person.ChangeAddress("Phipps Place");
                    await(t.CommitAsync());
                }

            using (ISession s = Sfi.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    u = (User)await(s.GetAsync(typeof(User), "gavin"));
                    Assert.That(u.Person.Address, Is.EqualTo("Phipps Place"));
                    Assert.That(u.Person.PreviousAddress, Is.EqualTo("Karbarook Ave"));
                    Assert.That(u.Person.Yob, Is.EqualTo(u.Person.Dob.Year));
                    u.Password = "******";
                    await(t.CommitAsync());
                }

            using (ISession s = Sfi.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    u = (User)await(s.GetAsync(typeof(User), "gavin"));
                    Assert.That(u.Person.Address, Is.EqualTo("Phipps Place"));
                    Assert.That(u.Person.PreviousAddress, Is.EqualTo("Karbarook Ave"));
                    Assert.That(u.Password, Is.EqualTo("$ecret"));
                    await(s.DeleteAsync(u));
                    await(t.CommitAsync());
                }
        }
Exemple #25
0
        public void ExceptionsInSynchronizationBeforeTransactionCompletionAbortTransaction()
        {
            var c = new C {
                ID = 1, Value = "value"
            };

            var synchronization = new SynchronizationThatThrowsExceptionAtBeforeTransactionCompletion();

            using (ISession s = Sfi.OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    t.RegisterSynchronization(synchronization);

                    s.Save(c);

                    Assert.Throws <BadException>(t.Commit);
                }

            using (ISession s = Sfi.OpenSession())
            {
                var objectInDb = s.Get <C>(1);
                Assert.IsNull(objectInDb);
            }
        }
Exemple #26
0
 private void Cleanup()
 {
     Sfi?.Close();
     _sessionFactory = null;
     cfg             = null;
 }
        public async Task WillGetSessionIdFromSessionLogsConcurrentAsync()
        {
            if (!TestDialect.SupportsConcurrencyTests)
            {
                Assert.Ignore($"Dialect {Dialect} does not supports concurrency tests");
            }

            GlobalContext.Properties["sessionId"] = new SessionIdCapturer();

            // Do not use a ManualResetEventSlim, it does not support async and exhausts the task thread pool in the
            // async counterparts of this test. SemaphoreSlim has the async support and release the thread when waiting.
            var semaphore  = new SemaphoreSlim(0);
            var failures   = new ConcurrentBag <Exception>();
            var sessionIds = new ConcurrentDictionary <int, Guid>();

            using (var spy = new TextLogSpy("NHibernate.SQL", "%message | SessionId: %property{sessionId}"))
            {
                await(Task.WhenAll(
                          Enumerable.Range(1, 12 - 1).Select(async i =>
                {
                    if (i > 10)
                    {
                        // Give some time to threads for reaching the wait, having all of them ready to do most of their job concurrently.
                        await(Task.Delay(100));
                        semaphore.Release(10);
                        return;
                    }
                    try
                    {
                        using (var s = Sfi.OpenSession())
                        {
                            sessionIds.AddOrUpdate(
                                i,
                                s.GetSessionImplementation().SessionId,
                                (ti, old) => throw new InvalidOperationException(
                                    $"Thread number {ti} has already session id {old}, while attempting to set it to" +
                                    $" {s.GetSessionImplementation().SessionId}"));
                            await(semaphore.WaitAsync());

                            for (int j = 0; j < 10; j++)
                            {
                                await(s.GetAsync <Person>(i * 10 + j));                                         //will execute some sql
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        failures.Add(e);
                    }
                })));

                Assert.That(failures, Is.Empty, $"{failures.Count} task(s) failed.");

                var loggingEvent = spy.GetWholeLog();
                for (var i = 1; i < 11; i++)
                {
                    for (var j = 0; j < 10; j++)
                    {
                        var sessionId = sessionIds[i];
                        Assert.That(loggingEvent, Does.Contain($"p0 = {i * 10 + j} [Type: Int32 (0:0:0)] | SessionId: {sessionId}"));
                    }
                }
            }
        }
Exemple #28
0
        public async Task SimpleProjectionsAsync()
        {
            var transformer = new CustomTransformer();

            await(Sfi.EvictQueriesAsync());
            Sfi.Statistics.Clear();

            const string queryString = "select i.Name, i.Description from AnotherItem i where i.Name='widget'";

            object savedId;

            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    await(s.CreateQuery(queryString).SetCacheable(true).ListAsync());
                    var i = new AnotherItem {
                        Name = "widget"
                    };
                    savedId = await(s.SaveAsync(i));
                    await(tx.CommitAsync());
                }

            QueryStatistics  qs = Sfi.Statistics.GetQueryStatistics(queryString);
            EntityStatistics es = Sfi.Statistics.GetEntityStatistics(typeof(AnotherItem).FullName);

            Thread.Sleep(200);

            IList result;

            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    await(s.CreateQuery(queryString).SetCacheable(true).ListAsync());
                    await(tx.CommitAsync());
                }

            Assert.That(qs.CacheHitCount, Is.EqualTo(0));

            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    await(s.CreateQuery(queryString).SetCacheable(true).ListAsync());
                    await(tx.CommitAsync());
                }

            Assert.That(qs.CacheHitCount, Is.EqualTo(1));

            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    await(s.CreateQuery(queryString).SetCacheable(true).SetResultTransformer(transformer).ListAsync());
                    await(tx.CommitAsync());
                }

            Assert.That(qs.CacheHitCount, Is.EqualTo(2), "hit count should go up since the cache contains the result before the possible application of a resulttransformer");

            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    await(s.CreateQuery(queryString).SetCacheable(true).SetResultTransformer(transformer).ListAsync());
                    await(tx.CommitAsync());
                }

            Assert.That(qs.CacheHitCount, Is.EqualTo(3), "hit count should go up since we are using the same resulttransformer");
            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    result = await(s.CreateQuery(queryString).SetCacheable(true).ListAsync());
                    Assert.That(result.Count, Is.EqualTo(1));
                    var i = await(s.GetAsync <AnotherItem>(savedId));
                    i.Name = "Widget";
                    await(tx.CommitAsync());
                }

            Assert.That(qs.CacheHitCount, Is.EqualTo(4));
            Assert.That(qs.CacheMissCount, Is.EqualTo(2));

            Thread.Sleep(200);

            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    await(s.CreateQuery(queryString).SetCacheable(true).ListAsync());

                    var i = await(s.GetAsync <AnotherItem>(savedId));
                    Assert.That(i.Name, Is.EqualTo("Widget"));

                    await(s.DeleteAsync(i));
                    await(tx.CommitAsync());
                }

            Assert.That(qs.CacheHitCount, Is.EqualTo(4));
            Assert.That(qs.CacheMissCount, Is.EqualTo(3));
            Assert.That(qs.CachePutCount, Is.EqualTo(3));
            Assert.That(qs.ExecutionCount, Is.EqualTo(3));
            Assert.That(es.FetchCount, Is.EqualTo(0));             //check that it was being cached
        }
 /// <summary>
 /// <c>WithOptions</c> having already set up <c>AutoJoinTransaction()</c>
 /// according to the fixture <see cref="AutoJoinTransaction"/> property.
 /// </summary>
 /// <returns>A session builder.</returns>
 protected ISessionBuilder WithOptions()
 {
     return(Sfi.WithOptions().AutoJoinTransaction(AutoJoinTransaction));
 }
Exemple #30
0
        public async Task QueryCacheInvalidationAsync()
        {
            await(Sfi.EvictQueriesAsync());
            Sfi.Statistics.Clear();

            const string queryString = "from Item i where i.Name='widget'";

            object savedId = await(CreateItemAsync(queryString));

            QueryStatistics  qs = Sfi.Statistics.GetQueryStatistics(queryString);
            EntityStatistics es = Sfi.Statistics.GetEntityStatistics(typeof(Item).FullName);

            Thread.Sleep(200);

            IList result;

            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    result = await(s.CreateQuery(queryString).SetCacheable(true).ListAsync());
                    Assert.That(result.Count, Is.EqualTo(1));
                    await(tx.CommitAsync());
                }

            Assert.That(qs.CacheHitCount, Is.EqualTo(0));

            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    result = await(s.CreateQuery(queryString).SetCacheable(true).ListAsync());
                    Assert.That(result.Count, Is.EqualTo(1));
                    await(tx.CommitAsync());
                }

            Assert.That(qs.CacheHitCount, Is.EqualTo(1));
            Assert.That(es.FetchCount, Is.EqualTo(0));

            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    result = await(s.CreateQuery(queryString).SetCacheable(true).ListAsync());
                    Assert.That(result.Count, Is.EqualTo(1));
                    Assert.That(NHibernateUtil.IsInitialized(result[0]));
                    var i = (Item)result[0];
                    i.Name = "Widget";
                    await(tx.CommitAsync());
                }

            Assert.That(qs.CacheHitCount, Is.EqualTo(2));
            Assert.That(qs.CacheMissCount, Is.EqualTo(2));
            Assert.That(es.FetchCount, Is.EqualTo(0));

            Thread.Sleep(200);

            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    await(s.CreateQuery(queryString).SetCacheable(true).ListAsync());

                    var i = await(s.GetAsync <Item>(savedId));
                    Assert.That(i.Name, Is.EqualTo("Widget"));

                    await(s.DeleteAsync(i));
                    await(tx.CommitAsync());
                }

            Assert.That(qs.CacheHitCount, Is.EqualTo(2));
            Assert.That(qs.CacheMissCount, Is.EqualTo(3));
            Assert.That(qs.CachePutCount, Is.EqualTo(3));
            Assert.That(qs.ExecutionCount, Is.EqualTo(3));
            Assert.That(es.FetchCount, Is.EqualTo(0));             //check that it was being cached
        }