Example #1
0
		public void Bug()
		{
			if((Dialect is SQLiteDialect)==false)
				Assert.Ignore("NH-1347 is sqlite specific");

			using (ISession s = OpenSession())
			using (ITransaction tx = s.BeginTransaction())
			{
				s.Save(new A("1"));
				s.Save(new A("2"));
				s.Save(new A("3"));
				tx.Commit();
			}

			using(SqlLogSpy spy = new SqlLogSpy())
			using (ISession s = OpenSession())
			{
				A a = s.CreateCriteria(typeof (A))
					.AddOrder(Order.Asc("Name"))
					.SetMaxResults(1)
					.UniqueResult<A>();
				Assert.AreEqual("1", a.Name);
				Assert.IsTrue(
					spy.Appender.GetEvents()[0].MessageObject.ToString().Contains("limit")
					);
			}

			using (ISession s = OpenSession())
			using (ITransaction tx = s.BeginTransaction())
			{
				s.Delete("from A");
				tx.Commit();
			}
		}
        public void TwoFuturesRunInTwoRoundTrips()
        {
            using (var s = sessions.OpenSession())
            {
				IgnoreThisTestIfMultipleQueriesArentSupportedByDriver();

                using (var logSpy = new SqlLogSpy())
                {
                    var persons10 = s.CreateQuery("from Person")
                        .SetMaxResults(10)
                        .Future<Person>();

                    foreach (var person in persons10) { } // fire first future round-trip

                    var persons5 = s.CreateQuery("from Person")
                        .SetMaxResults(5)
                        .Future<int>();

                    foreach (var person in persons5) { } // fire second future round-trip

                    var events = logSpy.Appender.GetEvents();
                    Assert.AreEqual(2, events.Length);
                }
            }
        }
        public void CanCombineSingleFutureValueWithEnumerableFutures()
        {
            using (var s = sessions.OpenSession())
            {
				IgnoreThisTestIfMultipleQueriesArentSupportedByDriver();

                var persons = s.CreateQuery("from Person")
                    .SetMaxResults(10)
                    .Future<Person>();

                var personCount = s.CreateQuery("select count(*) from Person")
                    .FutureValue<long>();

                using (var logSpy = new SqlLogSpy())
                {
                    long count = personCount.Value;

                    foreach (var person in persons)
                    {
                    }

                    var events = logSpy.Appender.GetEvents();
                    Assert.AreEqual(1, events.Length);
                }
            }
        }
Example #4
0
        public void PropertyRefWithCompositeIdUpdateTest()
        {
            using (var spy = new SqlLogSpy())
            using (var session = OpenSession())
            using (session.BeginTransaction())
            {

                var direction1 = new Direction { Id1 = 1, Id2 = 1, GUID = Guid.NewGuid() };
                session.Save(direction1);
                
                var direction2 = new Direction { Id1 = 2, Id2 = 2, GUID = Guid.NewGuid() };
                session.Save(direction2);
                
                session.Flush();

                var directionReferrer = new DirectionReferrer
                                             {
                                                 GUID = Guid.NewGuid(),
                                                 Direction = direction1, 
                                             };

                session.Save(directionReferrer);

                directionReferrer.Direction = direction2;

                session.Update(directionReferrer);

                session.Flush();

                Console.WriteLine(spy.ToString());
                Assert.That(true);
            }
        }
		public void CanCombineSingleFutureValueWithEnumerableFutures()
		{
			using (var s = sessions.OpenSession())
			{
				IgnoreThisTestIfMultipleQueriesArentSupportedByDriver();

				var persons = s.CreateCriteria(typeof(Person))
					.SetMaxResults(10)
					.Future<Person>();

				var personCount = s.CreateCriteria(typeof(Person))
					.SetProjection(Projections.RowCount())
					.FutureValue<int>();

				using (var logSpy = new SqlLogSpy())
				{
					int count = personCount.Value;

					foreach (var person in persons)
					{

					}

					var events = logSpy.Appender.GetEvents();
					Assert.AreEqual(1, events.Length);
				}
			}
		}
Example #6
0
		public void DeleteWithoutUpdateVersion()
		{
			using (ISession s = OpenSession())
			using (ITransaction t = s.BeginTransaction())
			{
				s.Save(new ObjectA { Bs = new List<ObjectB> { new ObjectB(), new ObjectB() } });
				t.Commit();
			}

			using (var ls = new SqlLogSpy())
			{
				using (ISession s = OpenSession())
				using (ITransaction t = s.BeginTransaction())
				{
					var a = s.CreateCriteria<ObjectA>().UniqueResult<ObjectA>();
					s.Delete(a);
					t.Commit();
				}
				string wholeLog = ls.GetWholeLog();
				Assert.That(wholeLog, Is.Not.StringContaining("UPDATE ObjectA"));
				Assert.That(wholeLog, Is.StringContaining("UPDATE ObjectB"),"should create orphans");
			}

			using (ISession s = OpenSession())
			using (ITransaction t = s.BeginTransaction())
			{
				s.CreateQuery("delete from ObjectB").ExecuteUpdate();
				s.CreateQuery("delete from ObjectA").ExecuteUpdate();
				t.Commit();
			}
		}
Example #7
0
		public void Test()
		{
			int a_id;
			using(ISession s = OpenSession())
			using(ITransaction tx = s.BeginTransaction())
			{
				// Create an A and save it
				ClassA a = new ClassA();
				a.Name = "a1";
				s.Save(a);

				// Create a B and save it
				ClassB b = new ClassB();
				b.Id = new ClassBId("bbb", a);
				b.SomeProp = "Some property";
				s.Save(b);

				// Create a C and save it
				ClassC c = new ClassC();
				c.B = b;
				s.Save(c);

				tx.Commit();

				a_id = a.Id;
			}

			// Clear the cache
			sessions.Evict(typeof(ClassA));
			sessions.Evict(typeof(ClassB));
			sessions.Evict(typeof(ClassC));
			
			using(ISession s = OpenSession())
			using (ITransaction tx = s.BeginTransaction())
			{
				// Load a so we can use it to load b
				ClassA a = s.Get<ClassA>(a_id);

				// Load b so b will be in cache
				ClassB b = s.Get<ClassB>(new ClassBId("bbb", a));

				tx.Commit();
			}
			
			using(ISession s = OpenSession())
			using(ITransaction tx = s.BeginTransaction())
			{
				using (SqlLogSpy sqlLogSpy = new SqlLogSpy())
				{
					IList<ClassC> c_list = s.CreateCriteria(typeof (ClassC)).List<ClassC>();
					// make sure we initialize B
					NHibernateUtil.Initialize(c_list[0].B);

					Assert.AreEqual(1, sqlLogSpy.Appender.GetEvents().Length,
					                "Only one SQL should have been issued");
				}

				tx.Commit();
			}
		}
Example #8
0
		public void CanOverrideStringEnumGetValue()
		{
		    string paramPrefix = ((DriverBase) Sfi.ConnectionProvider.Driver).NamedPrefix;
			using (ISession s = OpenSession())
			using (ITransaction tx = s.BeginTransaction())
			{
				using (SqlLogSpy ls = new SqlLogSpy())
				{
					Person person = new Person() { Sex = Sex.Male };
					s.Save(person);

					string log = ls.GetWholeLog();
					Assert.IsTrue(log.Contains(paramPrefix + "p0 = 'M'"));
				}

				using (SqlLogSpy ls = new SqlLogSpy())
				{
					Person person =
						s.CreateQuery("from Person p where p.Sex = :personSex")
							.SetParameter("personSex", Sex.Female)
							.UniqueResult<Person>();

					Assert.That(person, Is.Null);

					string log = ls.GetWholeLog();
					Assert.IsTrue(log.Contains(paramPrefix + "p0 = 'F'"));
				}

				tx.Rollback();
			}
		}
        public void CanUseFutureQuery()
        {
            using (var s = sessions.OpenSession())
            {
				IgnoreThisTestIfMultipleQueriesArentSupportedByDriver();

                var persons10 = s.CreateQuery("from Person")
                    .SetMaxResults(10)
                    .Future<Person>();
                var persons5 = s.CreateQuery("from Person")
                    .SetMaxResults(5)
                    .Future<int>();

                using (var logSpy = new SqlLogSpy())
                {
                    foreach (var person in persons5)
                    {

                    }

                    foreach (var person in persons10)
                    {

                    }

                    var events = logSpy.Appender.GetEvents();
                    Assert.AreEqual(1, events.Length);
                }
            }
        }
Example #10
0
		public void Loking()
		{
			object savedId;
			using (ISession s = OpenSession())
			using (ITransaction t = s.BeginTransaction())
			{
				A a = new A("hunabKu");
				savedId = s.Save(a);
				t.Commit();
			}

			using (ISession s = OpenSession())
			using (ITransaction t = s.BeginTransaction())
			{
				A a = s.Get<A>(savedId);
				using (SqlLogSpy sqlLogSpy = new SqlLogSpy())
				{
					s.Lock(a, LockMode.Upgrade);
					string sql = sqlLogSpy.Appender.GetEvents()[0].RenderedMessage;
					Assert.Less(0, sql.IndexOf("with (updlock"));
				}
				t.Commit();
			}

			using (ISession s = OpenSession())
			using (ITransaction t = s.BeginTransaction())
			{
				s.Delete("from A");
				t.Commit();
			}
		}
Example #11
0
		public void ShouldNotRemoveLineBreaksFromSqlQueries()
		{
			using (var spy = new SqlLogSpy())
			using (var s = OpenSession())
			using (var t = s.BeginTransaction())
			{
				const string sql = @"
select Id
from Entity
where 1=1";
				var query = s.CreateSQLQuery(sql);
				Assert.DoesNotThrow(() => query.List());

				string renderedSql = spy.Appender.GetEvents()[0].RenderedMessage;

				Regex whitespaces = new Regex(@"\s+", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);

				Assert.AreEqual(
					string.Compare(
						whitespaces.Replace(sql, " ").Trim(),
						whitespaces.Replace(renderedSql, " ").Trim(),
						true
						),
					0
				);
			}
		}
		public void CanUseFutureCriteria()
		{
			using (var s = sessions.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));
				}
			}
		}
Example #13
0
		public void WhenPersistShouldNotFetchUninitializedCollection()
		{
			var companyId = CreateScenario();

			//Now in a second transaction i remove the address and persist Company: for a cascade option the Address will be removed
			using (var sl = new SqlLogSpy())
			{
				using (ISession session = sessions.OpenSession())
				{
					using (ITransaction tx = session.BeginTransaction())
					{
						var company = session.Get<Company>(companyId);
						company.Addresses.Count().Should().Be.EqualTo(1);
						company.RemoveAddress(company.Addresses.First()).Should().Be.EqualTo(true);

						//now this company will be saved and deleting the address.
						//BUT it should not try to load the BanckAccound collection!
						session.Persist(company);
						tx.Commit();
					}
				}
				var wholeMessage = sl.GetWholeLog();
				wholeMessage.Should().Not.Contain("BankAccount");
			}

			Cleanup(companyId);
		}
 public void ComparisonToConstantShouldBeInnerJoin()
 {
     using (var sqlLog = new SqlLogSpy())
     using (var session = OpenSession())
     {
         session.Query<MyBO>().Where(b => b.BO1.I1 == 1).ToList();
         var log = sqlLog.GetWholeLog();
         Assert.AreEqual(0, CountOuterJoins(log));
         Assert.AreEqual(1, CountInnerJoins(log));
     }
 }
 public void EqualsNullShouldBeOuterJoin()
 {
     using (var sqlLog = new SqlLogSpy())
     using (var session = OpenSession())
     {
         session.Query<MyBO>().Where(b => b.BO1.BO2 == null).ToList();
         var log = sqlLog.GetWholeLog();
         Assert.AreEqual(1, CountOuterJoins(log));
         Assert.AreEqual(0, CountInnerJoins(log));
     }
 }
		public void CommentsInQuery()
		{
			using (ISession s = OpenSession())
			{
				using (var sl = new SqlLogSpy())
				{
					s.CreateQuery("from Animal").SetComment("This is my query").List();
					string sql = sl.Appender.GetEvents()[0].RenderedMessage;
					Assert.That(sql.IndexOf("This is my query"), Is.GreaterThan(0));
				}
			}
		}
		public void WhenExecutedThroughSessionThenUseSubstitutions()
		{
			const string query = "from SimpleClass s where s.IntValue > pizza";
			using (var s = OpenSession())
			{
				using (SqlLogSpy sqlLogSpy = new SqlLogSpy())
				{
					s.CreateQuery(query).List();
					string sql = sqlLogSpy.Appender.GetEvents()[0].RenderedMessage;
					Assert.That(sql, Is.Not.StringContaining("pizza"));
				}
			}
		}
		public void WhenExecutedThroughSessionThenUseSubstitutionsWithString()
		{
			const string query = "from SimpleClass s where s.Description > calda";
			using (var s = OpenSession())
			{
				using (SqlLogSpy sqlLogSpy = new SqlLogSpy())
				{
					s.CreateQuery(query).List();
					string sql = sqlLogSpy.Appender.GetEvents()[0].RenderedMessage;
					sql.Should().Not.Contain("pizza").And.Contain("'bobrock'");
				}
			}
		}
Example #19
0
        public void SelectConditionalValuesTest()
        {
            using (var spy = new SqlLogSpy())
            using (var session = OpenSession())
            using (session.BeginTransaction())
            {
                var days = 33;

                var cat = new MyLovelyCat
                {
                    GUID = Guid.NewGuid(),
                    Birthdate = DateTime.Now.AddDays(-days),
                    Color = "Black",
                    Name = "Kitty",
                    Price = 0
                };
                session.Save(cat);
                
                session.Flush();

                var catInfo =
                    session.Query<MyLovelyCat>()
                        .Select(o => new
                        {
                            o.Color,
                            AliveDays = (int)(DateTime.Now - o.Birthdate).TotalDays,
                            o.Name,
                            o.Price,
                        })
                        .Single();

                //Console.WriteLine(spy.ToString());
                Assert.That(catInfo.AliveDays == days);

                var catInfo2 =
                    session.Query<MyLovelyCat>()
                        .Select(o => new
                        {
                            o.Color,
                            AliveDays = o.Price > 0 ? (DateTime.Now - o.Birthdate).TotalDays : 0,
                            o.Name,
                            o.Price,
                        })
                        .Single();

                //Console.WriteLine(spy.ToString());
                Assert.That(catInfo2.AliveDays == 0);

            }
        }
Example #20
0
		public void SelectAllAnimalsShouldPerformJoins()
		{
			using (var session = OpenSession())
			using (session.BeginTransaction())
			{
				using (var spy = new SqlLogSpy())
				{
					var list = session.CreateQuery("from Animal").List<Animal>();
					var count = list.Count();
					Assert.AreEqual(3, count);
					Assert.Greater(1, spy.GetWholeLog().Split(new[] {"inner join"}, StringSplitOptions.None).Count());
				}
			}
		}
Example #21
0
		public void OrderLinesWith2ImpliedJoinShouldProduce2JoinsInSql()
		{
			//NH-3003
			using (var spy = new SqlLogSpy())
			{
				var lines = (from l in db.OrderLines
							 where l.Order.Customer.CompanyName == "Vins et alcools Chevalier"
							 select l).ToList();

				Assert.AreEqual(10, lines.Count);
				var countJoins = CountJoins(spy);
				Assert.That(countJoins, Is.EqualTo(2));
			}
		}
Example #22
0
		public void IntercepSQL()
		{
			log.Debug("Retrive (in general this is not necessary since TestCase check for DB cleaned at the and of each test)");
			using (ISession s = OpenSession())
			{
                s.EnableFilter("excludeDeletedRows").SetParameter("deleted", "Y");
				using(SqlLogSpy spy = new SqlLogSpy())
				{
                    s.CreateQuery("FROM ChildEntity c WHERE c.Parent.Code = :parentCode").SetParameter("parentCode", 2).List<ChildEntity>();
					LoggingEvent[] le = spy.Appender.GetEvents();
					Assert.AreEqual(1, le.Length);
					log.Debug("The SQL executed was:" + le[0].MessageObject);
				}
			}
		}
Example #23
0
		public void Bug()
		{
			using (ISession s = OpenSession())
			{
				long? filter = null;
				using (var ls = new SqlLogSpy())
				{
					s.CreateQuery(@"SELECT c FROM xchild c WHERE (:filternull = true OR c.Parent.A < :filterval)")
						.SetParameter("filternull", !filter.HasValue)
						.SetParameter("filterval", filter.HasValue ? filter.Value : 0).List<xchild>();
					var message = ls.GetWholeLog();
					Assert.That(message, Text.Contains("xchild0_.ParentId=xparent1_.Id and (@p0=1 or xparent1_.A<@p1)"));
				}
			}
		}
Example #24
0
		public void ShouldNotContainJoinWhereNotRequired()
		{
			using (var session = OpenSession())
			{
				using (var ls = new SqlLogSpy())
				{
					ICriteria criteria = session.CreateCriteria(typeof(Entity1));
					criteria.CreateAlias("Entities2", "ent2", JoinType.InnerJoin);
					criteria.List<Entity1>();
					var sql = ls.GetWholeLog();
					var rx = new Regex(@"\bjoin\b");
					Assert.That(rx.Matches(sql).Count, Is.EqualTo(1));
				}
			}
		}
Example #25
0
		public void OrderLinesFilterByCustomerIdSelectCustomerIdShouldNotContainJoinWithCustomer()
		{
			//NH-2946
			using (var spy = new SqlLogSpy())
			{
				var lines = (from l in db.OrderLines
							 where l.Order.Customer.CustomerId == "VINET"
							 select l.Order.Customer.CustomerId).ToList();

				Assert.AreEqual(10, lines.Count);
				var countJoins = CountJoins(spy);
				Assert.That(countJoins, Is.EqualTo(1));
				Assert.That(Count(spy, "Customers"), Is.EqualTo(0));
			}
		}
Example #26
0
		public void Bug()
		{
			using (ISession s = OpenSession())
			{
				long? filter = null;
				using (var ls = new SqlLogSpy())
				{
					s.CreateQuery(@"SELECT c FROM xchild c WHERE (:filternull = true OR c.Parent.A < :filterval)")
						.SetParameter("filternull", !filter.HasValue)
						.SetParameter("filterval", filter.HasValue ? filter.Value : 0).List<xchild>();
					var message = ls.GetWholeLog();
				    string paramPrefix = ((DriverBase) Sfi.ConnectionProvider.Driver).NamedPrefix;
					Assert.That(message, Is.StringContaining("xchild0_.ParentId=xparent1_.Id and (" + paramPrefix + "p0=" + Dialect.ToBooleanValueString(true) + " or xparent1_.A<" + paramPrefix + "p1)"));
				}
			}
		}
Example #27
0
		public void OrderLinesWith2ImpliedJoinByIdShouldNotContainImpliedJoin()
		{
			//NH-2946 + NH-3003 = NH-2451
			using (var spy = new SqlLogSpy())
			{
				var lines = (from l in db.OrderLines
							 where l.Order.Customer.CustomerId == "VINET"
							 where l.Order.Customer.CompanyName == "Vins et alcools Chevalier"
							 select l).ToList();

				Assert.AreEqual(10, lines.Count);
				var countJoins = CountJoins(spy);
				Assert.That(countJoins, Is.EqualTo(2));
				Assert.That(Count(spy, "Orders"), Is.EqualTo(1));
			}
		}
		public void CanCahceDynamicLinq()
		{
			//dynamic orderby clause
			var users = db.Users
						  .Cacheable()
						  .Fetch(x => x.Role)
						  .OrderBy("RegisteredAt");

			users
			  .ToList();

			using (var log = new SqlLogSpy())
			{
				users.ToList();
				Assert.IsNullOrEmpty(log.GetWholeLog());
			}
		}
		public void InsertUsesStoredProc()
		{
			using (var spy = new SqlLogSpy())
			{
				Organization ifa;
				using (ISession s = OpenSession())
				using (ITransaction t = s.BeginTransaction())
				{
					ifa = new Organization("IFA");
					s.Save(ifa);
					t.Commit();
				}

				Assert.AreEqual(1, spy.Appender.GetEvents().Length, "Num loggedEvents");
				Assert.AreEqual(1, ifa.Id, "ifa.Id");
				Assert.AreEqual(GetExpectedInsertOrgLogStatement("IFA"), spy.Appender.GetEvents()[0].MessageObject, "Message 1");
				using (ISession s = OpenSession())
				using (ITransaction t = s.BeginTransaction())
				{
					s.Delete(ifa);
					t.Commit();
				}
			}

			using (var spy = new SqlLogSpy())
			{
				Organization efa;
				using (ISession s = OpenSession())
				using (ITransaction t = s.BeginTransaction())
				{
					efa = new Organization("EFA");
					s.Save(efa);
					t.Commit();
				}

				Assert.AreEqual(1, spy.Appender.GetEvents().Length, "Num loggedEvents");
				Assert.AreEqual(2, efa.Id, "efa.Id");
				Assert.AreEqual(GetExpectedInsertOrgLogStatement("EFA"), spy.Appender.GetEvents()[0].MessageObject, "Message 2");
				using (ISession s = OpenSession())
				using (ITransaction t = s.BeginTransaction())
				{
					s.Delete(efa);
					t.Commit();
				}
			}
		}
Example #30
0
		public void SaveCanOverrideStringEnumGetValue()
		{
			var paramPrefix = ((DriverBase) Sfi.ConnectionProvider.Driver).NamedPrefix;
			using (var ls = new SqlLogSpy())
			{
				using (var s = OpenSession())
				using (var t = s.BeginTransaction())
				{
					var person = new Person { Sex = Sex.Male };
					s.Save(person);

					t.Commit();
				}
				
				var log = ls.GetWholeLog();
				Assert.That(log.Contains(paramPrefix + "p0 = 'M'"), Is.True);
			}
		}
Example #31
0
        public async Task EntityJoinWithFetchesAsync()
        {
            using (var sqlLog = new SqlLogSpy())
                using (var session = OpenSession())
                {
                    EntityComplex entityComplex =
                        await(session
                              .CreateQuery("select ex " +
                                           "from EntityWithNoAssociation root " +
                                           "left join EntityComplex ex with root.Complex1Id = ex.Id " +
                                           "inner join fetch ex.SameTypeChild st")
                              .SetMaxResults(1)
                              .UniqueResultAsync <EntityComplex>());

                    Assert.That(entityComplex, Is.Not.Null);
                    Assert.That(NHibernateUtil.IsInitialized(entityComplex), Is.True);
                    Assert.That(entityComplex.SameTypeChild, Is.Not.Null);
                    Assert.That(NHibernateUtil.IsInitialized(entityComplex.SameTypeChild), Is.True);
                    Assert.That(sqlLog.Appender.GetEvents().Length, Is.EqualTo(1), "Only one SQL select is expected");
                }
        }
 public void MixOfJoinsForAssociatedAndNotAssociatedEntities()
 {
     using (var sqlLog = new SqlLogSpy())
         using (var session = OpenSession())
         {
             EntityComplex     root     = null;
             EntityComplex     ejLevel1 = null;
             EntitySimpleChild customChildForEjLevel1             = null;
             EntityComplex     entityComplexForEjLevel1           = null;
             EntitySimpleChild ejLevel2OnEntityComplexForEjLevel1 = null;
             var obj = session
                       .QueryOver(() => root)
                       .JoinEntityAlias(() => ejLevel1, Restrictions.Where(() => ejLevel1.Id == root.SameTypeChild.Id && root.Id != null), JoinType.LeftOuterJoin)
                       .JoinAlias(() => ejLevel1.Child1, () => customChildForEjLevel1, JoinType.InnerJoin)
                       .JoinAlias(() => ejLevel1.SameTypeChild, () => entityComplexForEjLevel1, JoinType.LeftOuterJoin)
                       .JoinEntityAlias(() => ejLevel2OnEntityComplexForEjLevel1, () => entityComplexForEjLevel1.Id == ejLevel2OnEntityComplexForEjLevel1.Id)
                       .Where(() => customChildForEjLevel1.Id != null && ejLevel2OnEntityComplexForEjLevel1.Id != null)
                       .Take(1)
                       .SingleOrDefault <object>();
         }
 }
        public async Task SelectModeChildFetchLoadsNotLoadedObjectAsync()
        {
            using (var sqlLog = new SqlLogSpy())
                using (var session = OpenSession())
                {
                    EntityComplex root = null;
                    root = await(session.QueryOver(() => root)
                                 .Fetch(SelectMode.ChildFetch, r => r)
                                 .JoinQueryOver(ec => ec.ChildrenList)
                                 .Fetch(SelectMode.Fetch, simpleChild => simpleChild)
                                 .Take(1)
                                 .SingleOrDefaultAsync());

                    Assert.That(root, Is.Not.Null, "root is not loaded");
                    Assert.That(NHibernateUtil.IsInitialized(root), Is.False, "root should not be initialized");
                    Assert.That(sqlLog.Appender.GetEvents(), Has.Length.EqualTo(1), "Only one SQL select is expected");
                    // The root was not initialized but its children collection is immediately initialized... A bit weird feature.
                    Assert.That(NHibernateUtil.IsInitialized(root.ChildrenList), Is.True, "root children should be initialized");
                    Assert.That(root.ChildrenList, Has.Count.EqualTo(1).And.None.Null, "Unexpected children collection content");
                }
        }
        public void CanQueryOverForAssociationInNotAssociatedEntity()
        {
            using (var sqlLog = new SqlLogSpy())
                using (var session = OpenSession())
                {
                    EntityComplex           ejComplex = null;
                    EntityWithNoAssociation root      = null;
                    root = session.QueryOver(() => root)
                           .JoinEntityQueryOver(() => ejComplex, () => root.Complex1Id == ejComplex.Id)
                           .JoinQueryOver(ej => ej.Child1)
                           .Take(1)
                           .SingleOrDefault();

                    ejComplex = session.Load <EntityComplex>(root.Complex1Id);

                    Assert.That(NHibernateUtil.IsInitialized(ejComplex), Is.True);
                    Assert.That(NHibernateUtil.IsInitialized(ejComplex.Child1), Is.True);
                    Assert.That(NHibernateUtil.IsInitialized(ejComplex.Child2), Is.False);
                    Assert.That(sqlLog.Appender.GetEvents().Length, Is.EqualTo(1), "Only one SQL select is expected");
                }
        }
        public void SelectModeChildFetchDeep_SingleDbRoundtrip_Aliased()
        {
            SkipFutureTestIfNotSupported();

            using (var sqlLog = new SqlLogSpy())
                using (var session = OpenSession())
                {
                    EntityComplex root       = null;
                    var           rootFuture = session
                                               .QueryOver(() => root)
                                               .Future();

                    session
                    .QueryOver(() => root)
                    .Fetch(SelectMode.ChildFetch, () => root)
                    .Fetch(SelectMode.Fetch, () => root.ChildrenList)
                    .Future();

                    session
                    .QueryOver(() => root)
                    .Fetch(SelectMode.ChildFetch, () => root, () => root.ChildrenList)
                    .Fetch(SelectMode.Fetch, () => root.ChildrenList[0].Children)
                    .Future();

                    session
                    .QueryOver(() => root)
                    .Fetch(SelectMode.JoinOnly, () => root.ChildrenList)
                    .Fetch(SelectMode.ChildFetch, () => root, () => root.ChildrenList[0].Children)
                    .Fetch(SelectMode.Fetch, () => root.ChildrenList[0].Children[0].Children)
                    .Future();

                    root = rootFuture.ToList().First(r => r.Id == _parentEntityComplexId);

                    Assert.That(root?.ChildrenList, Is.Not.Null);
                    Assert.That(NHibernateUtil.IsInitialized(root?.ChildrenList));
                    Assert.That(NHibernateUtil.IsInitialized(root?.ChildrenList[0].Children));
                    Assert.That(NHibernateUtil.IsInitialized(root?.ChildrenList[0].Children[0].Children));
                    Assert.That(sqlLog.Appender.GetEvents().Length, Is.EqualTo(1), "Only one SQL select is expected");
                }
        }
        public void CacheableFetchWithAliasedJoinFuture()
        {
            using (var session = OpenSession())
            {
                EntityComplex     alias  = null;
                EntitySimpleChild child1 = null;
                var list = session.QueryOver <EntityComplex>(() => alias)
                           .Where(ec => ec.Id == _parentEntityComplexId)
                           .JoinQueryOver(() => alias.Child1, () => child1)
                           .Fetch(SelectMode.Fetch, () => alias.ChildrenList)
                           .TransformUsing(Transformers.DistinctRootEntity)
                           .Cacheable()
                           .Future()
                           .GetEnumerable()
                           .ToList();
                EntityComplex value = null;
                Assert.DoesNotThrow(() => value = list[0]);
                Assert.That(value, Is.Not.Null);
            }

            using (var sqlLog = new SqlLogSpy())
                using (var session = OpenSession())
                {
                    EntityComplex     alias  = null;
                    EntitySimpleChild child1 = null;
                    var list = session.QueryOver <EntityComplex>(() => alias)
                               .Where(ec => ec.Id == _parentEntityComplexId)
                               .JoinQueryOver(() => alias.Child1, () => child1)
                               .Fetch(SelectMode.Fetch, () => alias.ChildrenList)
                               .TransformUsing(Transformers.DistinctRootEntity)
                               .Cacheable()
                               .Future()
                               .ToList();
                    EntityComplex value = null;
                    Assert.DoesNotThrow(() => value = list[0]);
                    Assert.That(value, Is.Not.Null);

                    Assert.That(sqlLog.Appender.GetEvents().Length, Is.EqualTo(0), "Query is expected to be retrieved from cache");
                }
        }
Example #37
0
        public void QueryWithFetchesAndAliasDoNotDuplicateJoin()
        {
            using (var s = OpenSession())
            {
                Cat parent = null;
                using (var spy = new SqlLogSpy())
                {
                    var list =
                        s
                        .QueryOver <Cat>()
                        .Fetch(SelectMode.Fetch, o => o.Parent)
                        .Fetch(SelectMode.Fetch, o => o.Parent.Parent)
                        .JoinAlias(o => o.Parent, () => parent)
                        .Where(x => parent.Age == 4)
                        .List();

                    // Two joins to Cat are expected: one for the immediate parent, and a second for the grand-parent.
                    // So checking if it does not contain three joins or more. (The regex uses "[\s\S]" instead of "."
                    // because the SQL is formatted by default and contains "\n" which are not matched by ".".)
                    Assert.That(spy.GetWholeLog(), Does.Not.Match(@"(?:\bjoin\s*Cat\b[\s\S]*){3,}").IgnoreCase);
                    Assert.That(list, Has.Count.EqualTo(2));
                    Assert.That(
                        NHibernateUtil.IsInitialized(list[0].Parent),
                        Is.True,
                        "first cat parent initialization status");
                    Assert.That(
                        NHibernateUtil.IsInitialized(list[1].Parent),
                        Is.True,
                        "second cat parent initialization status");
                    Assert.That(
                        NHibernateUtil.IsInitialized(list[0].Parent.Parent),
                        Is.True,
                        "first cat parent parent initialization status");
                    Assert.That(
                        NHibernateUtil.IsInitialized(list[1].Parent.Parent),
                        Is.True,
                        "second cat parent parent initialization status");
                }
            }
        }
Example #38
0
        public async Task SelectModeJoinOnlyEntityJoinAsync()
        {
            using (var sqlLog = new SqlLogSpy())
                using (var session = OpenSession())
                {
                    EntityComplex     parentJoin = null;
                    EntitySimpleChild rootChild  = null;
                    rootChild = await(session.QueryOver(() => rootChild)
                                      .JoinEntityQueryOver(() => parentJoin, Restrictions.Where(() => rootChild.ParentId == parentJoin.Id))
                                      .Fetch(SelectMode.JoinOnly, a => a)
                                      .Take(1)
                                      .SingleOrDefaultAsync());

                    parentJoin = await(session.LoadAsync <EntityComplex>(rootChild.ParentId));

                    Assert.That(rootChild, Is.Not.Null);
                    Assert.That(NHibernateUtil.IsInitialized(rootChild), Is.True);
                    Assert.That(rootChild.ParentId, Is.Not.Null);
                    Assert.That(NHibernateUtil.IsInitialized(parentJoin), Is.False, "Entity Join must not be initialized.");
                    Assert.That(sqlLog.Appender.GetEvents().Length, Is.EqualTo(1), "Only one SQL select is expected");
                }
        }
        public async Task MultipleEntitiesProjectionsAsync()
        {
            using (var sqlLog = new SqlLogSpy())
                using (var session = OpenSession())
                {
                    EntityComplex     root            = null;
                    EntitySimpleChild child1          = null;
                    EntitySimpleChild child2          = null;
                    EntityComplex     sameAsRootChild = null;
                    EntitySimpleChild nullListElem    = null;
                    var objects = await(session
                                        .QueryOver <EntityComplex>()
                                        .JoinAlias(ep => ep.Child1, () => child1)
                                        .JoinAlias(ep => ep.Child2, () => child2)
                                        .JoinAlias(ep => ep.SameTypeChild, () => sameAsRootChild)
                                        .JoinAlias(ep => ep.ChildrenList, () => nullListElem, JoinType.LeftOuterJoin)
                                        .Select(
                                            Projections.RootEntity(),
                                            Projections.Entity(() => child1),
                                            Projections.Entity(() => child2),
                                            Projections.Entity(() => sameAsRootChild),
                                            Projections.Entity(() => nullListElem)
                                            )
                                        .Take(1).SingleOrDefaultAsync <object[]>());

                    root            = (EntityComplex)objects[0];
                    child1          = (EntitySimpleChild)objects[1];
                    child2          = (EntitySimpleChild)objects[2];
                    sameAsRootChild = (EntityComplex)objects[3];
                    nullListElem    = (EntitySimpleChild)objects[4];

                    Assert.That(NHibernateUtil.IsInitialized(root), Is.True, "root must be initialized");
                    Assert.That(NHibernateUtil.IsInitialized(child1), Is.True, "child1 must be initialized");
                    Assert.That(NHibernateUtil.IsInitialized(child2), Is.True, "child2 must be initialized");
                    Assert.That(NHibernateUtil.IsInitialized(sameAsRootChild), Is.True, "sameAsRootChild must be initialized");
                    Assert.That(nullListElem, Is.Null, "nullListElem must be null");
                    Assert.That(sqlLog.Appender.GetEvents().Length, Is.EqualTo(1), "Only one SQL select is expected");
                }
        }
        public void NullLeftEntityJoinWithEntityProjection()
        {
            using (var sqlLog = new SqlLogSpy())
                using (var session = OpenSession())
                {
                    EntityComplex           ejLeftNull = null;
                    EntityWithNoAssociation root       = null;
                    var objs = session.QueryOver(() => root)
                               //add some non existent join condition
                               .JoinEntityAlias(() => ejLeftNull, () => ejLeftNull.Id == null, JoinType.LeftOuterJoin)
                               .Select((e) => root.AsEntity(), e => ejLeftNull.AsEntity())
                               .Take(1)
                               .SingleOrDefault <object[]>();
                    root       = (EntityWithNoAssociation)objs[0];
                    ejLeftNull = (EntityComplex)objs[1];

                    Assert.That(root, Is.Not.Null, "root should not be null (looks like left join didn't work)");
                    Assert.That(NHibernateUtil.IsInitialized(root), Is.True);
                    Assert.That(ejLeftNull, Is.Null, "Entity join should be null");
                    Assert.That(sqlLog.Appender.GetEvents().Length, Is.EqualTo(1), "Only one SQL select is expected");
                }
        }
Example #41
0
        public async Task NullableIntOverflowAsync()
        {
            var hasCast = Dialect.GetCastTypeName(NHibernateUtil.Int32.SqlType) !=
                          Dialect.GetCastTypeName(NHibernateUtil.Int64.SqlType);

            using (var session = OpenSession())
                using (session.BeginTransaction())
                    using (var sqlLog = new SqlLogSpy())
                    {
                        var groups = await(session.Query <TestClass>()
                                           .GroupBy(i => 1)
                                           .Select(g => new
                        {
                            s = g.Sum(i => (long)i.NullableInt32Prop)
                        })
                                           .ToListAsync());

                        Assert.That(FindAllOccurrences(sqlLog.GetWholeLog(), "cast"), Is.EqualTo(hasCast ? 1 : 0));
                        Assert.That(groups, Has.Count.EqualTo(1));
                        Assert.That(groups[0].s, Is.EqualTo((long)int.MaxValue * 2));
                    }
        }
Example #42
0
        public void SqlClientOneRoundTripForUpdateAndInsert()
        {
#if NETFX
            if (Sfi.Settings.BatcherFactory is SqlClientBatchingBatcherFactory == false)
            {
                Assert.Ignore("This test is for SqlClientBatchingBatcher only");
            }
#endif

            FillDb();

            using (var sqlLog = new SqlLogSpy())
                using (ISession s = Sfi.OpenSession())
                    using (ITransaction tx = s.BeginTransaction())
                    {
                        s.Save(new VerySimple
                        {
                            Name   = "test441",
                            Weight = 894
                        });

                        s.Save(new AlmostSimple
                        {
                            Name   = "test441",
                            Weight = 894
                        });

                        tx.Commit();

                        var log = sqlLog.GetWholeLog();
                        //log should only contain NHibernate.SQL once, because that means
                        //that we ony generated a single batch (NHibernate.SQL log will output
                        //once per batch)
                        Assert.AreEqual(0, log.IndexOf("NHibernate.SQL"), "log should start with NHibernate.SQL");
                        Assert.AreEqual(-1, log.IndexOf("NHibernate.SQL", "NHibernate.SQL".Length), "NHibernate.SQL should only appear once in the log");
                    }

            Cleanup();
        }
Example #43
0
        public async Task SelectModeChildFetchForMultipleCollections_SingleDbRoundtripAsync()
        {
            SkipFutureTestIfNotSupported();

            using (var sqlLog = new SqlLogSpy())
                using (var session = OpenSession())
                {
                    EntityComplex root       = null;
                    var           futureRoot = session
                                               .QueryOver(() => root)
                                               .Where(r => r.Id == _parentEntityComplexId)
                                               .FutureValue();

                    session
                    .QueryOver(() => root)
                    //Only ID is added to SELECT statement for root so it's index scan only
                    .Fetch(SelectMode.ChildFetch, ec => ec)
                    .Fetch(SelectMode.Fetch, ec => ec.ChildrenList)
                    .Where(r => r.Id == _parentEntityComplexId)
                    .Future();

                    session
                    .QueryOver(() => root)
                    .Fetch(SelectMode.ChildFetch, ec => ec)
                    .Fetch(SelectMode.Fetch, ec => ec.ChildrenListEmpty)
                    .Where(r => r.Id == _parentEntityComplexId)
                    .Future();

                    root = await(futureRoot.GetValueAsync());

                    Assert.That(root?.ChildrenList, Is.Not.Null);
                    Assert.That(root?.ChildrenListEmpty, Is.Not.Null);
                    Assert.That(NHibernateUtil.IsInitialized(root?.ChildrenList), "ChildrenList must be initialized");
                    Assert.That(NHibernateUtil.IsInitialized(root?.ChildrenListEmpty), "ChildrenListEmpty must be initialized");
                    Assert.That(root?.ChildrenList, Is.Not.Empty, "ChildrenList must not be empty");
                    Assert.That(root?.ChildrenListEmpty, Is.Empty, "ChildrenListEmpty must be empty");
                    Assert.That(sqlLog.Appender.GetEvents().Length, Is.EqualTo(1), "Only one SQL select is expected");
                }
        }
        public async Task MultipleEntitiesProjectionsToResultTransformerAsync()
        {
            using (var sqlLog = new SqlLogSpy())
                using (var session = OpenSession())
                {
                    MultipleEntitiesResult r = null;

                    EntitySimpleChild child1          = null;
                    EntitySimpleChild child2          = null;
                    EntityComplex     sameAsRootChild = null;
                    EntitySimpleChild nullListElem    = null;

                    r = await(session
                              .QueryOver <EntityComplex>()
                              .JoinAlias(ep => ep.Child1, () => child1)
                              .JoinAlias(ep => ep.Child2, () => child2)
                              .JoinAlias(ep => ep.SameTypeChild, () => sameAsRootChild)
                              .JoinAlias(ep => ep.ChildrenList, () => nullListElem, JoinType.LeftOuterJoin)
                              .Select(
                                  Projections.RootEntity().WithAlias(nameof(r.Root)),
                                  Projections.Entity(() => child1),
                                  Projections.Property(() => child2.Name).As(nameof(r.Name)),
                                  Projections.Entity(() => child2),
                                  Projections.Property(() => child1.Id),
                                  Projections.Entity(() => sameAsRootChild),
                                  Projections.Entity(() => nullListElem)
                                  )
                              .TransformUsing(Transformers.AliasToBean <MultipleEntitiesResult>())
                              .Take(1)
                              .SingleOrDefaultAsync <MultipleEntitiesResult>());

                    Assert.That(NHibernateUtil.IsInitialized(r.Root), Is.True, "Root must be initialized");
                    Assert.That(NHibernateUtil.IsInitialized(r.Child1), Is.True, "Child1 must be initialized");
                    Assert.That(NHibernateUtil.IsInitialized(r.Child2), Is.True, "Child2 must be initialized");
                    Assert.That(NHibernateUtil.IsInitialized(r.SameAsRootChild), Is.True, "SameAsRootChild must be initialized");
                    Assert.That(r.NullListElem, Is.Null, "NullListElem must be null");
                    Assert.That(sqlLog.Appender.GetEvents().Length, Is.EqualTo(1), "Only one SQL select is expected");
                }
        }
Example #45
0
        public async Task DLinqJoin9Async(bool useCrossJoin)
        {
            if (useCrossJoin && !Dialect.SupportsCrossJoin)
            {
                Assert.Ignore("Dialect does not support cross join.");
            }

            // The expected collection can be obtained from the below Linq to Objects query.
            //var expected =
            //	(from o in db.Orders.ToList()
            //	 from p in db.Products.ToList()
            //	 join d in db.OrderLines.ToList()
            //		on new {o.OrderId, p.ProductId} equals new {d.Order.OrderId, d.Product.ProductId}
            //		into details
            //	 from d in details
            //	 select new {o.OrderId, p.ProductId, d.UnitPrice}).ToList();

            using (var substitute = SubstituteDialect())
                using (var sqlSpy = new SqlLogSpy())
                {
                    ClearQueryPlanCache();
                    substitute.Value.SupportsCrossJoin.Returns(useCrossJoin);

                    var actual =
                        await((from o in db.Orders
                               from p in db.Products
                               join d in db.OrderLines
                               on new { o.OrderId, p.ProductId } equals new { d.Order.OrderId, d.Product.ProductId }
                               into details
                               from d in details
                               select new { o.OrderId, p.ProductId, d.UnitPrice }).ToListAsync());

                    var sql = sqlSpy.GetWholeLog();
                    Assert.That(actual.Count, Is.EqualTo(2155));
                    Assert.That(sql, Does.Contain(useCrossJoin ? "cross join" : "inner join"));
                    Assert.That(GetTotalOccurrences(sql, "inner join"), Is.EqualTo(useCrossJoin ? 1 : 2));
                }
        }
Example #46
0
        public void CanCombineCriteriaAndHqlInBatchAsFuture()
        {
            using (var session = OpenSession())
            {
                var batch = session
                            .CreateQueryBatch();

                var future1 = batch.AddAsFuture <int>(
                    session
                    .QueryOver <EntityComplex>()
                    .Where(x => x.Version >= 0)
                    .TransformUsing(new ListTransformerToInt()));

                var future2 = batch.AddAsFutureValue <Guid>(session.QueryOver <EntityComplex>().Where(x => x.Version >= 1).Select(x => x.Id));

                var future3 = batch.AddAsFuture(session.Query <EntityComplex>().Where(ec => ec.Version > 2));
                var future4 = batch.AddAsFutureValue(session.Query <EntityComplex>().Where(ec => ec.Version > 2), ec => ec.FirstOrDefault());

                var future5 = batch.AddAsFuture <EntitySimpleChild>(
                    session.CreateSQLQuery(
                        $"select * from {nameof(EntitySimpleChild)}")
                    .AddEntity(typeof(EntitySimpleChild)));

                using (var sqlLog = new SqlLogSpy())
                {
                    var future1List  = future1.GetEnumerable().ToList();
                    var future2Value = future2.Value;
                    var future3List  = future3.GetEnumerable().ToList();
                    var future4Value = future4.Value;
                    var future5List  = future5.GetEnumerable().ToList();

                    if (SupportsMultipleQueries)
                    {
                        Assert.That(sqlLog.Appender.GetEvents().Length, Is.EqualTo(1));
                    }
                }
            }
        }
Example #47
0
        public void Retrieving()
        {
            object savedId;

            using (ISession s = OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    A a = new A("hunabKu");
                    savedId = s.Save(a);
                    t.Commit();
                }

            using (ISession s = OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    using (SqlLogSpy sqlLogSpy = new SqlLogSpy())
                    {
                        s.Get <A>(savedId, LockMode.Upgrade);
                        string sql = sqlLogSpy.Appender.GetEvents()[0].RenderedMessage;
                        Assert.Less(0, sql.IndexOf(Dialect.ForUpdateString));
                    }
                    using (SqlLogSpy sqlLogSpy = new SqlLogSpy())
                    {
                        s.CreateQuery("from A a where a.Id= :pid").SetLockMode("a", LockMode.Upgrade).SetParameter("pid", savedId).
                        UniqueResult <A>();
                        string sql = sqlLogSpy.Appender.GetEvents()[0].RenderedMessage;
                        Assert.Less(0, sql.IndexOf(Dialect.ForUpdateString));
                    }
                    t.Commit();
                }

            using (ISession s = OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    s.Delete("from A");
                    t.Commit();
                }
        }
Example #48
0
        public async Task RetrievingAsync()
        {
            object savedId;

            using (ISession s = OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    A a = new A("hunabKu");
                    savedId = await(s.SaveAsync(a));
                    await(t.CommitAsync());
                }

            using (ISession s = OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    using (SqlLogSpy sqlLogSpy = new SqlLogSpy())
                    {
                        await(s.GetAsync <A>(savedId, LockMode.Upgrade));
                        string sql = sqlLogSpy.Appender.GetEvents()[0].RenderedMessage;
                        Assert.That(sql.IndexOf(Dialect.ForUpdateString, StringComparison.Ordinal), Is.GreaterThan(0));
                    }
                    using (SqlLogSpy sqlLogSpy = new SqlLogSpy())
                    {
                        await(s.CreateQuery("from A a where a.Id= :pid").SetLockMode("a", LockMode.Upgrade).SetParameter("pid", savedId).
                              UniqueResultAsync <A>());
                        string sql = sqlLogSpy.Appender.GetEvents()[0].RenderedMessage;
                        Assert.That(sql.IndexOf(Dialect.ForUpdateString, StringComparison.Ordinal), Is.GreaterThan(0));
                    }
                    await(t.CommitAsync());
                }

            using (ISession s = OpenSession())
                using (ITransaction t = s.BeginTransaction())
                {
                    await(s.DeleteAsync("from A"));
                    await(t.CommitAsync());
                }
        }
Example #49
0
        public async Task SelectModeFetchAsync()
        {
            using (var sqlLog = new SqlLogSpy())
                using (var session = OpenSession())
                {
                    var list = await(session.QueryOver <EntityComplex>()
                                     .Fetch(SelectMode.Fetch, ec => ec.Child1)
                                     .JoinQueryOver(ec => ec.ChildrenList, JoinType.InnerJoin)
                                     //now we can fetch inner joined collection
                                     .Fetch(SelectMode.Fetch, childrenList => childrenList)
                                     .TransformUsing(Transformers.DistinctRootEntity)
                                     .ListAsync());

                    var root = list.FirstOrDefault();
                    Assert.That(root, Is.Not.Null);
                    Assert.That(NHibernateUtil.IsInitialized(root), Is.True);
                    Assert.That(root.Child1, Is.Not.Null);
                    Assert.That(NHibernateUtil.IsInitialized(root.Child1), Is.True, "Entity must be initialized");
                    Assert.That(NHibernateUtil.IsInitialized(root.ChildrenList), Is.True, "ChildrenList Inner Joined collection must be initialized");

                    Assert.That(sqlLog.Appender.GetEvents().Length, Is.EqualTo(1), "Only one SQL select is expected");
                }
        }
Example #50
0
        public void CanFetchCollectionInBatch()
        {
            using (var sqlLog = new SqlLogSpy())
                using (var session = OpenSession())
                {
                    var batch = session.CreateQueryBatch();

                    var q1 = session.QueryOver <EntityComplex>()
                             .Where(x => x.Version >= 0);

                    batch.Add(q1);
                    batch.Add(session.Query <EntityComplex>().Fetch(c => c.ChildrenList));
                    batch.Execute();

                    var parent = session.Load <EntityComplex>(_parentId);
                    Assert.That(NHibernateUtil.IsInitialized(parent), Is.True);
                    Assert.That(NHibernateUtil.IsInitialized(parent.ChildrenList), Is.True);
                    if (SupportsMultipleQueries)
                    {
                        Assert.That(sqlLog.Appender.GetEvents().Length, Is.EqualTo(1));
                    }
                }
        }
Example #51
0
        public async Task MixOfJoinsForAssociatedAndNotAssociatedEntitiesAsync()
        {
#pragma warning disable CS8073 //The result of the expression is always 'false'
            using (var sqlLog = new SqlLogSpy())
                using (var session = OpenSession())
                {
                    EntityComplex     root     = null;
                    EntityComplex     ejLevel1 = null;
                    EntitySimpleChild customChildForEjLevel1             = null;
                    EntityComplex     entityComplexForEjLevel1           = null;
                    EntitySimpleChild ejLevel2OnEntityComplexForEjLevel1 = null;
                    var obj = await(session
                                    .QueryOver(() => root)
                                    .JoinEntityAlias(() => ejLevel1, Restrictions.Where(() => ejLevel1.Id == root.SameTypeChild.Id && root.Id != null), JoinType.LeftOuterJoin)
                                    .JoinAlias(() => ejLevel1.Child1, () => customChildForEjLevel1, JoinType.InnerJoin)
                                    .JoinAlias(() => ejLevel1.SameTypeChild, () => entityComplexForEjLevel1, JoinType.LeftOuterJoin)
                                    .JoinEntityAlias(() => ejLevel2OnEntityComplexForEjLevel1, () => entityComplexForEjLevel1.Id == ejLevel2OnEntityComplexForEjLevel1.Id)
                                    .Where(() => customChildForEjLevel1.Id != null && ejLevel2OnEntityComplexForEjLevel1.Id != null)
                                    .Take(1)
                                    .SingleOrDefaultAsync <object>());
                }
#pragma warning restore CS8073 //The result of the expression is always 'false'
        }
Example #52
0
        public void MultipleLinqJoinsWithSameProjectionNamesWithLeftJoinExtensionMethod()
        {
            using (var sqlSpy = new SqlLogSpy())
            {
                var orders = db.Orders
                             .LeftJoin(db.Orders, x => x.OrderId, x => x.OrderId - 1, (order, order1) => new { order, order1 })
                             .Select(x => new { First = x.order, Second = x.order1 })
                             .LeftJoin(db.Orders, x => x.First.OrderId, x => x.OrderId - 2, (order, order1) => new { order, order1 })
                             .Select(x => new
                {
                    FirstId  = x.order.First.OrderId,
                    SecondId = (int?)x.order.Second.OrderId,
                    ThirdId  = (int?)x.order1.OrderId
                })
                             .ToList();

                var sql = sqlSpy.GetWholeLog();
                Assert.That(orders.Count, Is.EqualTo(830));
                Assert.IsTrue(orders.Where(x => x.SecondId.HasValue && x.ThirdId.HasValue)
                              .All(x => x.FirstId == x.SecondId - 1 && x.SecondId == x.ThirdId - 1));
                Assert.That(GetTotalOccurrences(sql, "left outer join"), Is.EqualTo(2));
            }
        }
Example #53
0
        public async Task MultipleLinqJoinsWithSameProjectionNamesWithLeftJoinAsync()
        {
            using (var sqlSpy = new SqlLogSpy())
            {
                var orders = await(db.Orders
                                   .GroupJoin(db.Orders, x => x.OrderId, x => x.OrderId - 1, (order, order1) => new { order, order1 })
                                   .SelectMany(x => x.order1.DefaultIfEmpty(), (x, order1) => new { First = x.order, Second = order1 })
                                   .GroupJoin(db.Orders, x => x.First.OrderId, x => x.OrderId - 2, (order, order1) => new { order, order1 })
                                   .SelectMany(x => x.order1.DefaultIfEmpty(), (x, order1) => new
                {
                    FirstId  = x.order.First.OrderId,
                    SecondId = (int?)x.order.Second.OrderId,
                    ThirdId  = (int?)order1.OrderId
                })
                                   .ToListAsync());

                var sql = sqlSpy.GetWholeLog();
                Assert.That(orders.Count, Is.EqualTo(830));
                Assert.IsTrue(orders.Where(x => x.SecondId.HasValue && x.ThirdId.HasValue)
                              .All(x => x.FirstId == x.SecondId - 1 && x.SecondId == x.ThirdId - 1));
                Assert.That(GetTotalOccurrences(sql, "left outer join"), Is.EqualTo(2));
            }
        }
Example #54
0
 public void ShouldNotQueryLazyProperties_FetchSelect()
 {
     using (new FetchSelectScenario(Sfi))
     {
         using (ISession s = OpenSession())
         {
             using (ITransaction t = s.BeginTransaction())
             {
                 IList <Base1> items;
                 using (var ls = new SqlLogSpy())
                 {
                     items = s.CreateQuery("from Base1").List <Base1>();
                     Assert.That(ls.GetWholeLog(), Is.Not.StringContaining("LongContent"));
                 }
                 var item = (Derived1)items[0];
                 Assert.That(NHibernateUtil.IsPropertyInitialized(item, "LongContent"), Is.False);
                 string lc = item.LongContent;
                 Assert.That(lc, Is.Not.Null.And.Not.Empty);
                 Assert.That(NHibernateUtil.IsPropertyInitialized(item, "LongContent"), Is.True);
             }
         }
     }
 }
Example #55
0
 public async Task ShouldNotQueryLazyProperties_JoinedsubclassAsync()
 {
     using (new JoinedSubclassScenario(Sfi))
     {
         using (ISession s = OpenSession())
         {
             using (ITransaction t = s.BeginTransaction())
             {
                 IList <Base3> items;
                 using (var ls = new SqlLogSpy())
                 {
                     items = await(s.CreateQuery("from Base3").ListAsync <Base3>());
                     Assert.That(ls.GetWholeLog(), Does.Not.Contain("LongContent"));
                 }
                 var item = (Derived3)items[0];
                 Assert.That(NHibernateUtil.IsPropertyInitialized(item, "LongContent"), Is.False);
                 string lc = item.LongContent;
                 Assert.That(lc, Is.Not.Null.And.Not.Empty);
                 Assert.That(NHibernateUtil.IsPropertyInitialized(item, "LongContent"), Is.True);
             }
         }
     }
 }
Example #56
0
 public void ShouldNotQueryLazyProperties_Joinedsubclass()
 {
     using (new JoinedSubclassScenario(Sfi))
     {
         using (ISession s = OpenSession())
         {
             using (ITransaction t = s.BeginTransaction())
             {
                 IList <Base3> items;
                 using (var ls = new SqlLogSpy())
                 {
                     items = s.CreateQuery("from Base3").List <Base3>();
                     ls.GetWholeLog().Should().Not.Contain("LongContent");
                 }
                 var item = (Derived3)items[0];
                 NHibernateUtil.IsPropertyInitialized(item, "LongContent").Should().Be.False();
                 string lc = item.LongContent;
                 lc.Should().Not.Be.NullOrEmpty();
                 NHibernateUtil.IsPropertyInitialized(item, "LongContent").Should().Be.True();
             }
         }
     }
 }
        public void SelectModeFetchLazyPropertiesFetchGroup()
        {
            using (var sqlLog = new SqlLogSpy())
                using (var session = OpenSession())
                {
                    var root = session.QueryOver <EntityComplex>()
                               .Fetch(SelectMode.FetchLazyPropertyGroup, ec => ec.LazyProp, ec => ec.LazyProp2, ec => ec.SameTypeChild.LazyProp2)
                               .Where(ec => ec.Id == _parentEntityComplexId)
                               .SingleOrDefault();

                    Assert.That(root, Is.Not.Null);
                    Assert.That(NHibernateUtil.IsInitialized(root), Is.True);
                    Assert.That(root.LazyProp, Is.Not.Null);
                    Assert.That(NHibernateUtil.IsPropertyInitialized(root, nameof(root.LazyProp)), Is.True, "Lazy property must be fetched.");
                    Assert.That(NHibernateUtil.IsPropertyInitialized(root, nameof(root.LazyProp2)), Is.True, "Lazy property must be fetched.");
                    Assert.That(NHibernateUtil.IsInitialized(root.SameTypeChild), Is.True, "Object must be initialized.");
                    Assert.That(root.SameTypeChild, Is.Not.Null);
                    Assert.That(NHibernateUtil.IsPropertyInitialized(root.SameTypeChild, nameof(root.LazyProp2)), Is.True, "Lazy property must be fetched.");
                    Assert.That(NHibernateUtil.IsPropertyInitialized(root.SameTypeChild, nameof(root.LazyProp)), Is.False, "Property must be lazy.");

                    Assert.That(sqlLog.Appender.GetEvents().Length, Is.EqualTo(1), "Only one SQL select is expected");
                }
        }
        public async Task EntityProjectionLockModeAsync()
        {
            // For this test to succeed with SQL Anywhere, ansi_update_constraints must be off.
            // In I-SQL: set option ansi_update_constraints = 'Off'
            if (Dialect is Oracle8iDialect)
            {
                Assert.Ignore("Oracle is not supported due to #1352 bug (NH-3902)");
            }

            var upgradeHint = Dialect.ForUpdateString;

            if (string.IsNullOrEmpty(upgradeHint))
            {
                upgradeHint = Dialect.AppendLockHint(LockMode.Upgrade, string.Empty);
            }
            if (string.IsNullOrEmpty(upgradeHint))
            {
                Assert.Ignore($"Upgrade hint is not supported by dialect {Dialect.GetType().Name}");
            }

            using (var sqlLog = new SqlLogSpy())
                using (var session = OpenSession())
                {
                    EntitySimpleChild child1 = null;
                    child1 = await(session
                                   .QueryOver <EntityComplex>()
                                   .JoinAlias(ep => ep.Child1, () => child1)
                                   .Lock(() => child1).Upgrade
                                   .Select(Projections.Entity(() => child1))
                                   .Take(1).SingleOrDefaultAsync <EntitySimpleChild>());

                    Assert.That(child1, Is.Not.Null);
                    Assert.That(NHibernateUtil.IsInitialized(child1), Is.True, "Object must be initialized");
                    Assert.That(sqlLog.Appender.GetEvents().Length, Is.EqualTo(1), "Only one SQL select is expected");
                    Assert.That(sqlLog.Appender.GetEvents()[0].RenderedMessage, Does.Contain(upgradeHint));
                }
        }
Example #59
0
        public async Task CanUseFutureQueryWithAnonymousTypeAsync()
        {
            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())
                {
                    (await(persons5.GetEnumerableAsync())).ToList();                      // initialize the enumerable
                    (await(persons.GetEnumerableAsync())).ToList();

                    var events = logSpy.Appender.GetEvents();
                    Assert.AreEqual(1, events.Length);
                }
            }
        }
        public async Task WhenGetThenLoadOnlyNoLazyPlainPropertiesAsync()
        {
            using (ISession s = OpenSession())
            {
                Order order;
                using (var ls = new SqlLogSpy())
                {
                    order = await(s.GetAsync <Order>(1));
                    var logMessage = ls.GetWholeLog();
                    Assert.That(logMessage, Does.Not.Contain("ALazyProperty"));
                    Assert.That(logMessage, Does.Contain("NoLazyProperty"));
                }
                Assert.That(NHibernateUtil.IsPropertyInitialized(order, "NoLazyProperty"), Is.True);
                Assert.That(NHibernateUtil.IsPropertyInitialized(order, "ALazyProperty"), Is.False);

                using (var ls = new SqlLogSpy())
                {
                    var x          = order.ALazyProperty;
                    var logMessage = ls.GetWholeLog();
                    Assert.That(logMessage, Does.Contain("ALazyProperty"));
                }
                Assert.That(NHibernateUtil.IsPropertyInitialized(order, "ALazyProperty"), Is.True);
            }
        }