You can subscribe to this list here.
2004 |
Jan
|
Feb
|
Mar
|
Apr
(248) |
May
(82) |
Jun
(90) |
Jul
(177) |
Aug
(253) |
Sep
(157) |
Oct
(151) |
Nov
(143) |
Dec
(278) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2005 |
Jan
(152) |
Feb
(107) |
Mar
(177) |
Apr
(133) |
May
(259) |
Jun
(81) |
Jul
(119) |
Aug
(306) |
Sep
(416) |
Oct
(240) |
Nov
(329) |
Dec
(206) |
2006 |
Jan
(466) |
Feb
(382) |
Mar
(153) |
Apr
(162) |
May
(133) |
Jun
(21) |
Jul
(18) |
Aug
(37) |
Sep
(97) |
Oct
(114) |
Nov
(110) |
Dec
(28) |
2007 |
Jan
(74) |
Feb
(65) |
Mar
(49) |
Apr
(76) |
May
(43) |
Jun
(15) |
Jul
(68) |
Aug
(55) |
Sep
(63) |
Oct
(59) |
Nov
(70) |
Dec
(66) |
2008 |
Jan
(71) |
Feb
(60) |
Mar
(120) |
Apr
(31) |
May
(48) |
Jun
(81) |
Jul
(107) |
Aug
(51) |
Sep
(80) |
Oct
(83) |
Nov
(83) |
Dec
(79) |
2009 |
Jan
(83) |
Feb
(110) |
Mar
(97) |
Apr
(91) |
May
(291) |
Jun
(250) |
Jul
(197) |
Aug
(58) |
Sep
(54) |
Oct
(122) |
Nov
(68) |
Dec
(34) |
2010 |
Jan
(50) |
Feb
(17) |
Mar
(63) |
Apr
(61) |
May
(84) |
Jun
(81) |
Jul
(138) |
Aug
(144) |
Sep
(78) |
Oct
(26) |
Nov
(30) |
Dec
(61) |
2011 |
Jan
(33) |
Feb
(35) |
Mar
(166) |
Apr
(221) |
May
(109) |
Jun
(76) |
Jul
(27) |
Aug
(37) |
Sep
(1) |
Oct
(4) |
Nov
(2) |
Dec
(1) |
2012 |
Jan
|
Feb
|
Mar
(2) |
Apr
(2) |
May
|
Jun
|
Jul
(1) |
Aug
|
Sep
(1) |
Oct
|
Nov
(1) |
Dec
|
2013 |
Jan
|
Feb
(1) |
Mar
|
Apr
|
May
|
Jun
|
Jul
(1) |
Aug
(1) |
Sep
(3) |
Oct
(2) |
Nov
|
Dec
(1) |
2014 |
Jan
(1) |
Feb
(1) |
Mar
(3) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <aye...@us...> - 2009-01-05 14:13:22
|
Revision: 3978 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3978&view=rev Author: ayenderahien Date: 2009-01-05 14:13:16 +0000 (Mon, 05 Jan 2009) Log Message: ----------- Adding test to see that generated stats and 2nd level cache works together Modified Paths: -------------- trunk/nhibernate/src/NHibernate.Test/Stats/SessionStatsFixture.cs Property Changed: ---------------- trunk/nhibernate/lib/net/2.0/ Property changes on: trunk/nhibernate/lib/net/2.0 ___________________________________________________________________ Added: svn:ignore + NHibernate.dll Modified: trunk/nhibernate/src/NHibernate.Test/Stats/SessionStatsFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Stats/SessionStatsFixture.cs 2009-01-05 12:57:44 UTC (rev 3977) +++ trunk/nhibernate/src/NHibernate.Test/Stats/SessionStatsFixture.cs 2009-01-05 14:13:16 UTC (rev 3978) @@ -5,6 +5,8 @@ namespace NHibernate.Test.Stats { + using Criterion; + [TestFixture] public class SessionStatsFixture : TestCase { @@ -38,6 +40,32 @@ } [Test] + public void Can_use_cached_query_that_return_no_results() + { + Assert.IsTrue(sessions.Settings.IsQueryCacheEnabled); + + using(ISession s = OpenSession()) + { + IList list = s.CreateCriteria(typeof (Country)) + .Add(Restrictions.Eq("Name", "Narnia")) + .SetCacheable(true) + .List(); + + Assert.AreEqual(0, list.Count); + } + + using (ISession s = OpenSession()) + { + IList list = s.CreateCriteria(typeof(Country)) + .Add(Restrictions.Eq("Name", "Narnia")) + .SetCacheable(true) + .List(); + + Assert.AreEqual(0, list.Count); + } + } + + [Test] public void SessionStatistics() { ISession s = OpenSession(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <aye...@us...> - 2009-01-05 12:57:56
|
Revision: 3977 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3977&view=rev Author: ayenderahien Date: 2009-01-05 12:57:44 +0000 (Mon, 05 Jan 2009) Log Message: ----------- Fixing NH-1632 and NH-754 Modified Paths: -------------- trunk/nhibernate/src/NHibernate/AdoNet/ConnectionManager.cs trunk/nhibernate/src/NHibernate/Impl/AbstractSessionImpl.cs trunk/nhibernate/src/NHibernate/Impl/SessionImpl.cs trunk/nhibernate/src/NHibernate/Impl/StatelessSessionImpl.cs trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1632/ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1632/Fixture.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1632/Mappings.hbm.xml trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1632/Model.cs Modified: trunk/nhibernate/src/NHibernate/AdoNet/ConnectionManager.cs =================================================================== --- trunk/nhibernate/src/NHibernate/AdoNet/ConnectionManager.cs 2009-01-05 10:54:05 UTC (rev 3976) +++ trunk/nhibernate/src/NHibernate/AdoNet/ConnectionManager.cs 2009-01-05 12:57:44 UTC (rev 3977) @@ -44,6 +44,8 @@ [NonSerialized] private bool isFlushing; + private bool flushingFromDtcTransaction; + public ConnectionManager( ISessionImplementor session, IDbConnection suppliedConnection, @@ -256,7 +258,7 @@ private void AggressiveRelease() { - if (ownConnection) + if (ownConnection && flushingFromDtcTransaction == false) { log.Debug("aggressively releasing database connection"); if (connection != null) @@ -388,5 +390,29 @@ { get { return batcher; } } + + public IDisposable FlushingFromDtcTransaction + { + get + { + flushingFromDtcTransaction = true; + return new StopFlushingFromDtcTransaction(this); + } + } + + private class StopFlushingFromDtcTransaction : IDisposable + { + private readonly ConnectionManager manager; + + public StopFlushingFromDtcTransaction(ConnectionManager manager) + { + this.manager = manager; + } + + public void Dispose() + { + manager.flushingFromDtcTransaction = false; + } + } } } Modified: trunk/nhibernate/src/NHibernate/Impl/AbstractSessionImpl.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Impl/AbstractSessionImpl.cs 2009-01-05 10:54:05 UTC (rev 3976) +++ trunk/nhibernate/src/NHibernate/Impl/AbstractSessionImpl.cs 2009-01-05 12:57:44 UTC (rev 3977) @@ -26,7 +26,16 @@ private bool closed = false; private System.Transactions.Transaction ambientTransation; private bool isAlreadyDisposed; + protected bool shouldCloseSessionOnDtcTransactionCompleted; + protected bool TakingPartInDtcTransaction + { + get + { + return ambientTransation != null; + } + } + internal AbstractSessionImpl() { } protected internal AbstractSessionImpl(ISessionFactoryImplementor factory) @@ -246,7 +255,8 @@ BeforeTransactionCompletion(null); if (FlushMode != FlushMode.Never) { - Flush(); + using (ConnectionManager.FlushingFromDtcTransaction) + Flush(); } preparingEnlistment.Prepared(); } @@ -282,10 +292,14 @@ { bool wasSuccessful = e.Transaction.TransactionInformation.Status == TransactionStatus.Committed; AfterTransactionCompletion(wasSuccessful, null); + if (shouldCloseSessionOnDtcTransactionCompleted) + Dispose(true); }; ambientTransation.EnlistVolatile(this, EnlistmentOptions.None); } + protected abstract void Dispose(bool disposing); + #endregion } } Modified: trunk/nhibernate/src/NHibernate/Impl/SessionImpl.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Impl/SessionImpl.cs 2009-01-05 10:54:05 UTC (rev 3976) +++ trunk/nhibernate/src/NHibernate/Impl/SessionImpl.cs 2009-01-05 12:57:44 UTC (rev 3977) @@ -1363,6 +1363,11 @@ public void Dispose() { log.Debug("running ISession.Dispose()"); + if (TakingPartInDtcTransaction) + { + shouldCloseSessionOnDtcTransactionCompleted = true; + return; + } Dispose(true); } @@ -1375,7 +1380,7 @@ /// If this Session is being Finalized (<c>isDisposing==false</c>) then make sure not /// to call any methods that could potentially bring this Session back to life. /// </remarks> - private void Dispose(bool isDisposing) + protected override void Dispose(bool isDisposing) { if (IsAlreadyDisposed) { Modified: trunk/nhibernate/src/NHibernate/Impl/StatelessSessionImpl.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Impl/StatelessSessionImpl.cs 2009-01-05 10:54:05 UTC (rev 3976) +++ trunk/nhibernate/src/NHibernate/Impl/StatelessSessionImpl.cs 2009-01-05 12:57:44 UTC (rev 3977) @@ -731,10 +731,15 @@ public void Dispose() { log.Debug("running IStatelessSession.Dispose()"); + if(TakingPartInDtcTransaction) + { + shouldCloseSessionOnDtcTransactionCompleted = true; + return; + } Dispose(true); } - private void Dispose(bool isDisposing) + protected override void Dispose(bool isDisposing) { if (_isAlreadyDisposed) { Copied: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1632/Fixture.cs (from rev 3965, trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1621/Fixture.cs) =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1632/Fixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1632/Fixture.cs 2009-01-05 12:57:44 UTC (rev 3977) @@ -0,0 +1,148 @@ +using NUnit.Framework; +using NUnit.Framework.SyntaxHelpers; + +namespace NHibernate.Test.NHSpecificTest.NH1632 +{ + using System.Transactions; + + [TestFixture] + public class Fixture : BugTestCase + { + public override string BugNumber + { + get { return "NH1632"; } + } + + [Test] + public void Dispose_session_inside_transaction_scope() + { + ISession s; + + using (var tx = new TransactionScope()) + { + using (s = sessions.OpenSession()) + { + + } + tx.Complete(); + } + + Assert.IsFalse(s.IsOpen); + } + + [Test] + public void When_committing_transaction_scope_will_commit_transaction() + { + object id; + using (var tx = new TransactionScope()) + { + using (ISession s = sessions.OpenSession()) + { + id = s.Save(new Nums { NumA = 1, NumB = 2, ID = 5 }); + } + tx.Complete(); + } + + using (ISession s = sessions.OpenSession()) + using (ITransaction tx = s.BeginTransaction()) + { + Nums nums = s.Get<Nums>(id); + Assert.IsNotNull(nums); + s.Delete(nums); + + tx.Commit(); + } + } + + [Test] + public void Will_not_save_when_flush_mode_is_never() + { + object id; + using (var tx = new TransactionScope()) + { + using (ISession s = sessions.OpenSession()) + { + s.FlushMode = FlushMode.Never; + id = s.Save(new Nums { NumA = 1, NumB = 2, ID = 5 }); + } + tx.Complete(); + } + + using (ISession s = sessions.OpenSession()) + using (ITransaction tx = s.BeginTransaction()) + { + Nums nums = s.Get<Nums>(id); + Assert.IsNull(nums); + tx.Commit(); + } + } + + [Test] + public void When_using_two_sessions_with_explicit_flush() + { + object id1, id2; + using (var tx = new TransactionScope()) + { + using (ISession s1 = sessions.OpenSession()) + using (ISession s2 = sessions.OpenSession()) + { + + id1 = s1.Save(new Nums { NumA = 1, NumB = 2, ID = 5 }); + s1.Flush(); + + id2 = s2.Save(new Nums { NumA = 1, NumB = 2, ID = 6 }); + s2.Flush(); + + tx.Complete(); + } + } + + using (ISession s = sessions.OpenSession()) + using (ITransaction tx = s.BeginTransaction()) + { + Nums nums = s.Get<Nums>(id1); + Assert.IsNotNull(nums); + s.Delete(nums); + + nums = s.Get<Nums>(id2); + Assert.IsNotNull(nums); + s.Delete(nums); + + tx.Commit(); + } + } + + [Test] + public void When_using_two_sessions() + { + object id1, id2; + using (var tx = new TransactionScope()) + { + using (ISession s1 = sessions.OpenSession()) + using (ISession s2 = sessions.OpenSession()) + { + + id1 = s1.Save(new Nums { NumA = 1, NumB = 2, ID = 5 }); + + id2 = s2.Save(new Nums { NumA = 1, NumB = 2, ID = 6 }); + + tx.Complete(); + } + } + + using (ISession s = sessions.OpenSession()) + using (ITransaction tx = s.BeginTransaction()) + { + Nums nums = s.Get<Nums>(id1); + Assert.IsNotNull(nums); + s.Delete(nums); + + nums = s.Get<Nums>(id2); + Assert.IsNotNull(nums); + s.Delete(nums); + + tx.Commit(); + } + } + } +} Property changes on: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1632/Fixture.cs ___________________________________________________________________ Added: svn:mergeinfo + Copied: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1632/Mappings.hbm.xml (from rev 3965, trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1621/Mappings.hbm.xml) =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1632/Mappings.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1632/Mappings.hbm.xml 2009-01-05 12:57:44 UTC (rev 3977) @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="utf-8" ?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" + namespace="NHibernate.Test.NHSpecificTest.NH1632" + assembly="NHibernate.Test" +> + <class name="Nums" table="nums"> + <id name="ID"> + <generator class="assigned"/> + </id> + <property name="NumA"/> + <property name="NumB"/> + <property name="Sum" access="readonly"/> + </class> +</hibernate-mapping> Property changes on: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1632/Mappings.hbm.xml ___________________________________________________________________ Added: svn:mergeinfo + Copied: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1632/Model.cs (from rev 3965, trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1621/Model.cs) =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1632/Model.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1632/Model.cs 2009-01-05 12:57:44 UTC (rev 3977) @@ -0,0 +1,17 @@ +namespace NHibernate.Test.NHSpecificTest.NH1632 +{ + public class Nums + { + public virtual int ID { get; set; } + + public virtual int NumA { get; set; } + public virtual int NumB { get; set; } + public virtual int Sum + { + get + { + return NumA + NumB; + } + } + } +} Property changes on: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1632/Model.cs ___________________________________________________________________ Added: svn:mergeinfo + Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2009-01-05 10:54:05 UTC (rev 3976) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2009-01-05 12:57:44 UTC (rev 3977) @@ -567,6 +567,8 @@ <Compile Include="NHSpecificTest\NH1612\Person.cs" /> <Compile Include="NHSpecificTest\NH1621\Fixture.cs" /> <Compile Include="NHSpecificTest\NH1621\Model.cs" /> + <Compile Include="NHSpecificTest\NH1632\Fixture.cs" /> + <Compile Include="NHSpecificTest\NH1632\Model.cs" /> <Compile Include="NHSpecificTest\NH280\Fixture.cs" /> <Compile Include="NHSpecificTest\NH280\Foo.cs" /> <Compile Include="NHSpecificTest\NH1018\Employee.cs" /> @@ -1588,6 +1590,11 @@ <EmbeddedResource Include="Cascade\JobBatch.hbm.xml" /> <EmbeddedResource Include="Deletetransient\Person.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> + <EmbeddedResource Include="NHSpecificTest\NH1632\Mappings.hbm.xml" /> + + + + <EmbeddedResource Include="NHSpecificTest\NH1612\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1549\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1521\AclassWithSpecific.hbm.xml" /> @@ -1699,4 +1706,4 @@ if exist "$(ProjectDir)hibernate.cfg.xml" (copy "$(ProjectDir)hibernate.cfg.xml" "hibernate.cfg.xml") copy /y "..\..\..\NHibernate.DomainModel\ABC.hbm.xml" "ABC.hbm.xml"</PostBuildEvent> </PropertyGroup> -</Project> \ No newline at end of file +</Project> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <aye...@us...> - 2009-01-05 10:54:09
|
Revision: 3976 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3976&view=rev Author: ayenderahien Date: 2009-01-05 10:54:05 +0000 (Mon, 05 Jan 2009) Log Message: ----------- Adding more information about caching to debug log Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Cache/StandardQueryCache.cs trunk/nhibernate/src/NHibernate/Event/Default/DefaultInitializeCollectionEventListener.cs trunk/nhibernate/src/NHibernate/Event/Default/DefaultLoadEventListener.cs Modified: trunk/nhibernate/src/NHibernate/Cache/StandardQueryCache.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cache/StandardQueryCache.cs 2009-01-05 00:13:13 UTC (rev 3975) +++ trunk/nhibernate/src/NHibernate/Cache/StandardQueryCache.cs 2009-01-05 10:54:05 UTC (rev 3976) @@ -70,7 +70,7 @@ if (log.IsDebugEnabled) { - log.Debug("caching query results in region: " + regionName); + log.DebugFormat("caching query results in region: '{0}'; {1}", regionName, key); } IList cacheable = new List<object>(result.Count + 1); @@ -95,23 +95,23 @@ { if (log.IsDebugEnabled) { - log.Debug("checking cached query results in region: " + regionName); + log.DebugFormat("checking cached query results in region: '{0}'; {1}", regionName, key); } IList cacheable = (IList)queryCache.Get(key); if (cacheable == null) { - log.Debug("query results were not found in cache"); + log.DebugFormat("query results were not found in cache: {0}", key); return null; } long timestamp = (long)cacheable[0]; - log.Debug("Checking query spaces for up-to-dateness [" + spaces + "]"); + log.DebugFormat("Checking query spaces for up-to-dateness [{0}]", spaces); if (!isNaturalKeyLookup && !IsUpToDate(spaces, timestamp)) { - log.Debug("cached query results were not up to date"); + log.DebugFormat("cached query results were not up to date for: {0}", key); return null; } - log.Debug("returning cached query results"); + log.DebugFormat("returning cached query results for: {0}", key); for (int i = 1; i < cacheable.Count; i++) { if (returnTypes.Length == 1) Modified: trunk/nhibernate/src/NHibernate/Event/Default/DefaultInitializeCollectionEventListener.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Event/Default/DefaultInitializeCollectionEventListener.cs 2009-01-05 00:13:13 UTC (rev 3975) +++ trunk/nhibernate/src/NHibernate/Event/Default/DefaultInitializeCollectionEventListener.cs 2009-01-05 10:54:05 UTC (rev 3976) @@ -88,10 +88,12 @@ if (ce == null) { factory.StatisticsImplementor.SecondLevelCacheMiss(persister.Cache.RegionName); + log.DebugFormat("Collection cache miss: {0}", ck); } else { factory.StatisticsImplementor.SecondLevelCacheHit(persister.Cache.RegionName); + log.DebugFormat("Collection cache hit: {0}", ck); } } Modified: trunk/nhibernate/src/NHibernate/Event/Default/DefaultLoadEventListener.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Event/Default/DefaultLoadEventListener.cs 2009-01-05 00:13:13 UTC (rev 3975) +++ trunk/nhibernate/src/NHibernate/Event/Default/DefaultLoadEventListener.cs 2009-01-05 10:54:05 UTC (rev 3976) @@ -415,9 +415,15 @@ if (factory.Statistics.IsStatisticsEnabled) { if (ce == null) + { factory.StatisticsImplementor.SecondLevelCacheMiss(persister.Cache.RegionName); + log.DebugFormat("Entity cache miss: {0}", ck); + } else + { factory.StatisticsImplementor.SecondLevelCacheHit(persister.Cache.RegionName); + log.DebugFormat("Entity cache hit: {0}", ck); + } } if (ce != null) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <te...@us...> - 2009-01-05 00:13:17
|
Revision: 3975 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3975&view=rev Author: tehlike Date: 2009-01-05 00:13:13 +0000 (Mon, 05 Jan 2009) Log Message: ----------- Fix for NH-1575 by Ryan Scott Modified Paths: -------------- trunk/nhibernate/src/NHibernate/SqlCommand/SqlString.cs trunk/nhibernate/src/NHibernate.Test/SqlCommandTest/SqlStringFixture.cs Modified: trunk/nhibernate/src/NHibernate/SqlCommand/SqlString.cs =================================================================== --- trunk/nhibernate/src/NHibernate/SqlCommand/SqlString.cs 2009-01-03 17:26:30 UTC (rev 3974) +++ trunk/nhibernate/src/NHibernate/SqlCommand/SqlString.cs 2009-01-05 00:13:13 UTC (rev 3975) @@ -24,7 +24,11 @@ private readonly object[] sqlParts; public static readonly SqlString Empty = new SqlString(new object[0]); - public static readonly SqlString Parameter = new SqlString(SqlCommand.Parameter.Placeholder); + + public static SqlString Parameter + { + get { return new SqlString(SqlCommand.Parameter.Placeholder); } + } public SqlString(string sqlPart) { Modified: trunk/nhibernate/src/NHibernate.Test/SqlCommandTest/SqlStringFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/SqlCommandTest/SqlStringFixture.cs 2009-01-03 17:26:30 UTC (rev 3974) +++ trunk/nhibernate/src/NHibernate.Test/SqlCommandTest/SqlStringFixture.cs 2009-01-05 00:13:13 UTC (rev 3975) @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using NHibernate.SqlCommand; using NUnit.Framework; @@ -359,5 +360,23 @@ Assert.AreEqual(" from table where (col = test) and id in (select id from foo order by bar)", sql.GetSubselectString().ToString()); } + [Test] + public void ParameterPropertyShouldReturnNewInstances() + { + Parameter[] parameters1 = new Parameter[1]; + Parameter[] parameters2 = new Parameter[1]; + + SqlString parameterString1 = SqlString.Parameter; + parameterString1.Parts.CopyTo(parameters1, 0); + + SqlString parameterString2 = SqlString.Parameter; + parameterString2.Parts.CopyTo(parameters2, 0); + + Assert.AreEqual(parameterString1, parameterString2); + Assert.AreNotSame(parameterString1, parameterString2); + + parameters1[0].OriginalPositionInQuery = 231; + Assert.IsNull(parameters2[0].OriginalPositionInQuery); + } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2009-01-03 17:26:41
|
Revision: 3974 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3974&view=rev Author: fabiomaulo Date: 2009-01-03 17:26:30 +0000 (Sat, 03 Jan 2009) Log Message: ----------- Fix NH-1612 (thanks to Gerke Geurts) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Loader/Custom/CustomLoader.cs trunk/nhibernate/src/NHibernate/Loader/Custom/Sql/SQLQueryParser.cs trunk/nhibernate/src/NHibernate/Loader/GeneratedCollectionAliases.cs trunk/nhibernate/src/NHibernate/Loader/Loader.cs trunk/nhibernate/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs trunk/nhibernate/src/NHibernate.Test/App.config trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Mappings.hbm.xml trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/NativeSqlCollectionLoaderFixture.cs Modified: trunk/nhibernate/src/NHibernate/Loader/Custom/CustomLoader.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Loader/Custom/CustomLoader.cs 2009-01-02 18:52:54 UTC (rev 3973) +++ trunk/nhibernate/src/NHibernate/Loader/Custom/CustomLoader.cs 2009-01-03 17:26:30 UTC (rev 3974) @@ -369,7 +369,7 @@ { object[] resultRow; // NH Different behavior (patched in NH-1612 to solve Hibernate issue HHH-2831). - if (!hasScalars && hasTransformer) + if (!hasScalars && (hasTransformer || data.Length == 0)) { resultRow = data; } Modified: trunk/nhibernate/src/NHibernate/Loader/Custom/Sql/SQLQueryParser.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Loader/Custom/Sql/SQLQueryParser.cs 2009-01-02 18:52:54 UTC (rev 3973) +++ trunk/nhibernate/src/NHibernate/Loader/Custom/Sql/SQLQueryParser.cs 2009-01-03 17:26:30 UTC (rev 3974) @@ -131,6 +131,7 @@ ISqlLoadableCollection collectionPersister = context.GetCollectionPersisterByAlias(aliasName); string collectionSuffix = context.GetCollectionSuffixByAlias(aliasName); + // NH Different behavior for NH-1612 if ("*".Equals(propertyName)) { if (fieldResults.Count != 0) @@ -140,37 +141,50 @@ string selectFragment = collectionPersister.SelectFragment(aliasName, collectionSuffix); aliasesFound++; - return selectFragment + ", " + ResolveProperties(aliasName, propertyName); + + // Collection may just contain elements and no entities, in which case resolution of + // collection properties is enough. + return collectionPersister.ElementType.IsEntityType + ? selectFragment + ", " + ResolveProperties(aliasName, "*") + : selectFragment; } - else if ("element.*".Equals(propertyName)) + + if (propertyName.StartsWith("element.")) { - return ResolveProperties(aliasName, "*"); - } - else - { - string[] columnAliases; + string elementPropertyName = propertyName.Substring("element.".Length); - // Let return-propertys override whatever the persister has for aliases. - if (!fieldResults.TryGetValue(propertyName,out columnAliases)) + if (collectionPersister.ElementType.IsEntityType) { - columnAliases = collectionPersister.GetCollectionPropertyColumnAliases(propertyName, collectionSuffix); + return ResolveProperties(aliasName, elementPropertyName); } - - if (columnAliases == null || columnAliases.Length == 0) + else if (elementPropertyName == "*") { - throw new QueryException("No column name found for property [" + propertyName + "] for alias [" + aliasName + "]", - originalQueryString); + throw new QueryException("Using element.* syntax is only supported for entity elements."); } - if (columnAliases.Length != 1) - { - // TODO: better error message since we actually support composites if names are explicitly listed. - throw new QueryException( - "SQL queries only support properties mapped to a single column - property [" + propertyName + "] is mapped to " - + columnAliases.Length + " columns.", originalQueryString); - } - aliasesFound++; - return columnAliases[0]; } + + string[] columnAliases; + + // Let return-propertys override whatever the persister has for aliases. + if (!fieldResults.TryGetValue(propertyName, out columnAliases)) + { + columnAliases = collectionPersister.GetCollectionPropertyColumnAliases(propertyName, collectionSuffix); + } + + if (columnAliases == null || columnAliases.Length == 0) + { + throw new QueryException("No column name found for property [" + propertyName + "] for alias [" + aliasName + "]", + originalQueryString); + } + if (columnAliases.Length != 1) + { + // TODO: better error message since we actually support composites if names are explicitly listed. + throw new QueryException( + "SQL queries only support properties mapped to a single column - property [" + propertyName + "] is mapped to " + + columnAliases.Length + " columns.", originalQueryString); + } + aliasesFound++; + return columnAliases[0]; } private string ResolveProperties(string aliasName, string propertyName) Modified: trunk/nhibernate/src/NHibernate/Loader/GeneratedCollectionAliases.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Loader/GeneratedCollectionAliases.cs 2009-01-02 18:52:54 UTC (rev 3973) +++ trunk/nhibernate/src/NHibernate/Loader/GeneratedCollectionAliases.cs 2009-01-03 17:26:30 UTC (rev 3974) @@ -18,7 +18,7 @@ private readonly IDictionary<string, string[]> userProvidedAliases; public GeneratedCollectionAliases(IDictionary<string, string[]> userProvidedAliases, ICollectionPersister persister, - string suffix) + string suffix) { this.suffix = suffix; this.userProvidedAliases = userProvidedAliases; @@ -27,7 +27,11 @@ indexAliases = GetUserProvidedAliases("index", persister.GetIndexColumnAliases(suffix)); - elementAliases = GetUserProvidedAliases("element", persister.GetElementColumnAliases(suffix)); + // NH-1612: Add aliases for all composite element properties to support access + // to individual composite element properties in <return-property> elements. + elementAliases = persister.ElementType.IsComponentType + ? GetUserProvidedCompositeElementAliases(persister.GetElementColumnAliases(suffix)) + : GetUserProvidedAliases("element", persister.GetElementColumnAliases(suffix)); identifierAlias = GetUserProvidedAlias("id", persister.GetIdentifierColumnAlias(suffix)); } @@ -35,6 +39,20 @@ public GeneratedCollectionAliases(ICollectionPersister persister, string str) : this(new CollectionHelper.EmptyMapClass<string, string[]>(), persister, str) {} + private string[] GetUserProvidedCompositeElementAliases(string[] defaultAliases) + { + var aliases = new List<string>(); + foreach (KeyValuePair<string, string[]> userProvidedAlias in userProvidedAliases) + { + if (userProvidedAlias.Key.StartsWith("element.")) + { + aliases.AddRange(userProvidedAlias.Value); + } + } + + return aliases.Count > 0 ? aliases.ToArray() : defaultAliases; + } + /// <summary> /// Returns the suffixed result-set column-aliases for columns making up the key for this collection (i.e., its FK to /// its owner). Modified: trunk/nhibernate/src/NHibernate/Loader/Loader.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Loader/Loader.cs 2009-01-02 18:52:54 UTC (rev 3973) +++ trunk/nhibernate/src/NHibernate/Loader/Loader.cs 2009-01-03 17:26:30 UTC (rev 3974) @@ -392,11 +392,11 @@ int entitySpan = EntityPersisters.Length; List<object> hydratedObjects = entitySpan == 0 ? null : new List<object>(entitySpan * 10); - + IDbCommand st = PrepareQueryCommand(queryParameters, false, session); - IDataReader rs = - GetResultSet(st, queryParameters.HasAutoDiscoverScalarTypes, queryParameters.Callable, selection, session); + IDataReader rs = GetResultSet(st, queryParameters.HasAutoDiscoverScalarTypes, queryParameters.Callable, selection, + session); // would be great to move all this below here into another method that could also be used // from the new scrolling stuff. @@ -428,9 +428,8 @@ log.Debug("result set row: " + count); } - object result = - GetRowFromResultSet(rs, session, queryParameters, lockModeArray, optionalObjectKey, hydratedObjects, keys, - returnProxies); + object result = GetRowFromResultSet(rs, session, queryParameters, lockModeArray, optionalObjectKey, hydratedObjects, + keys, returnProxies); results.Add(result); if (createSubselects) @@ -445,11 +444,11 @@ log.Debug(string.Format("done processing result set ({0} rows)", count)); } } - catch(Exception e) - { - e.Data["actual-sql-query"] = st.CommandText; - throw; - } + catch (Exception e) + { + e.Data["actual-sql-query"] = st.CommandText; + throw; + } finally { session.Batcher.CloseCommand(st, rs); Modified: trunk/nhibernate/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs 2009-01-02 18:52:54 UTC (rev 3973) +++ trunk/nhibernate/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs 2009-01-03 17:26:30 UTC (rev 3974) @@ -1386,8 +1386,7 @@ public string[] GetCollectionPropertyColumnAliases(string propertyName, string suffix) { object aliases; - collectionPropertyColumnAliases.TryGetValue(propertyName, out aliases); - if (aliases == null) + if (!collectionPropertyColumnAliases.TryGetValue(propertyName, out aliases)) { return null; } @@ -1425,13 +1424,29 @@ if (type.IsComponentType) { - IAbstractComponentType ct = (IAbstractComponentType) type; + // NH-1612: Recursively add column aliases for nested components to support the selection + // of individual component properties in native SQL queries. This also seems to provide + // a more complete solution to HHH-1019 (http://opensource.atlassian.com/projects/hibernate/browse/HHH-1019) + // because it works for <load-collection> and <return-join>. + int columnIndex = 0; + + var ct = (IAbstractComponentType) type; string[] propertyNames = ct.PropertyNames; - for (int i = 0; i < propertyNames.Length; i++) + for (int propertyIndex = 0; propertyIndex < propertyNames.Length; propertyIndex++) { - string name = propertyNames[i]; - collectionPropertyColumnAliases[aliasName + "." + name] = columnAliases[i]; - collectionPropertyColumnNames[aliasName + "." + name] = columnNames[i]; + string name = propertyNames[propertyIndex]; + IType propertyType = ct.Subtypes[propertyIndex]; + int propertyColSpan = propertyType.IsComponentType + ? ((IAbstractComponentType) propertyType).PropertyNames.Length + : 1; + + var propertyColumnAliases = new string[propertyColSpan]; + var propertyColumnNames = new string[propertyColSpan]; + System.Array.Copy(columnAliases, columnIndex, propertyColumnAliases, 0, propertyColSpan); + System.Array.Copy(columnNames, columnIndex, propertyColumnNames, 0, propertyColSpan); + InitCollectionPropertyMap(aliasName + "." + name, propertyType, propertyColumnAliases, propertyColumnNames); + + columnIndex += propertyColSpan; } } } Modified: trunk/nhibernate/src/NHibernate.Test/App.config =================================================================== --- trunk/nhibernate/src/NHibernate.Test/App.config 2009-01-02 18:52:54 UTC (rev 3973) +++ trunk/nhibernate/src/NHibernate.Test/App.config 2009-01-03 17:26:30 UTC (rev 3974) @@ -123,7 +123,7 @@ </logger> <logger name="NHibernate.SQL"> - <level value="OFF" /> + <level value="DEBUG" /> </logger> <logger name="NHibernate.Tool.hbm2ddl.SchemaExport"> Modified: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Mappings.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Mappings.hbm.xml 2009-01-02 18:52:54 UTC (rev 3973) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Mappings.hbm.xml 2009-01-03 17:26:30 UTC (rev 3974) @@ -75,7 +75,7 @@ <sql-query name="AreaStatisticsLoader" xml:space="preserve"> <load-collection role="Area.Statistics" alias="s"> - <return-property name="key" column="code" /> + <return-property name="key" column="area_code" /> <return-property name="index" column="year" /> <return-property name="element.CitizenCount" column="citizen_count" /> <return-property name="element.GDP"> Modified: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/NativeSqlCollectionLoaderFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/NativeSqlCollectionLoaderFixture.cs 2009-01-02 18:52:54 UTC (rev 3973) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/NativeSqlCollectionLoaderFixture.cs 2009-01-03 17:26:30 UTC (rev 3974) @@ -5,7 +5,7 @@ namespace NHibernate.Test.NHSpecificTest.NH1612 { - [TestFixture, Ignore("Not fixed yet.")] + [TestFixture] public class NativeSqlCollectionLoaderFixture : BugTestCase { #region Tests - <return-join> @@ -18,16 +18,8 @@ Assert.That(country, Is.Not.Null); Assert.That(country.Routes, Is.EquivalentTo(routes)); - - // cleanup - using (ISession session = OpenSession()) - { - using (ITransaction tx = session.BeginTransaction()) - { - session.Delete(country); - tx.Commit(); - } - } + + Cleanup(); } [Test] @@ -37,15 +29,7 @@ Country country = LoadCountryWithNativeSQL(CreateCountry(routes), "LoadCountryRoutesWithCustomAliases"); Assert.That(country, Is.Not.Null); Assert.That(country.Routes, Is.EquivalentTo(routes)); - // cleanup - using (ISession session = OpenSession()) - { - using (ITransaction tx = session.BeginTransaction()) - { - session.Delete(country); - tx.Commit(); - } - } + Cleanup(); } [Test] @@ -57,15 +41,7 @@ Assert.That(country, Is.Not.Null); Assert.That((ICollection) country.Statistics.Keys, Is.EquivalentTo((ICollection) stats.Keys), "Keys"); Assert.That((ICollection) country.Statistics.Values, Is.EquivalentTo((ICollection) stats.Values), "Elements"); - // cleanup - using (ISession session = OpenSession()) - { - using (ITransaction tx = session.BeginTransaction()) - { - session.Delete(country); - tx.Commit(); - } - } + CleanupWithPersons(); } [Test] @@ -77,6 +53,7 @@ Assert.That(country, Is.Not.Null); Assert.That((ICollection) country.Statistics.Keys, Is.EquivalentTo((ICollection) stats.Keys), "Keys"); Assert.That((ICollection) country.Statistics.Values, Is.EquivalentTo((ICollection) stats.Values), "Elements"); + CleanupWithPersons(); } [Test] @@ -88,40 +65,81 @@ Assert.That(country, Is.Not.Null); Assert.That((ICollection) country.Statistics.Keys, Is.EquivalentTo((ICollection) stats.Keys), "Keys"); Assert.That((ICollection) country.Statistics.Values, Is.EquivalentTo((ICollection) stats.Values), "Elements"); + + CleanupWithPersons(); } [Test] public void LoadEntitiesWithWithSimpleHbmAliasInjection() { City[] cities = CreateCities(); - Country country = LoadCountryWithNativeSQL(CreateCountry(cities), "LoadCountryCitiesWithSimpleHbmAliasInjection"); - Assert.That(country, Is.Not.Null); - Assert.That(country.Cities, Is.EquivalentTo(cities)); + Country country = CreateCountry(cities); + Save(country); + using (ISession session = OpenSession()) + { + var c = + session.GetNamedQuery("LoadCountryCitiesWithSimpleHbmAliasInjection").SetString("country_code", country.Code). + UniqueResult<Country>(); + Assert.That(c, Is.Not.Null); + Assert.That(c.Cities, Is.EquivalentTo(cities)); + } + CleanupWithCities(); } [Test] public void LoadEntitiesWithComplexHbmAliasInjection() { City[] cities = CreateCities(); - Country country = LoadCountryWithNativeSQL(CreateCountry(cities), "LoadCountryCitiesWithComplexHbmAliasInjection"); - Assert.That(country, Is.Not.Null); - Assert.That(country.Cities, Is.EquivalentTo(cities)); + Country country = CreateCountry(cities); + Save(country); + using (ISession session = OpenSession()) + { + var c = + session.GetNamedQuery("LoadCountryCitiesWithComplexHbmAliasInjection").SetString("country_code", country.Code). + UniqueResult<Country>(); + Assert.That(c, Is.Not.Null); + Assert.That(c.Cities, Is.EquivalentTo(cities)); + } + CleanupWithCities(); } [Test] public void LoadEntitiesWithExplicitColumnMappings() { City[] cities = CreateCities(); - Country country = LoadCountryWithNativeSQL(CreateCountry(cities), "LoadCountryCitiesWithCustomAliases"); - Assert.That(country, Is.Not.Null); - Assert.That(country.Cities, Is.EquivalentTo(cities)); + Country country = CreateCountry(cities); + Save(country); + using (ISession session = OpenSession()) + { + var c = + session.GetNamedQuery("LoadCountryCitiesWithCustomAliases").SetString("country_code", country.Code). + UniqueResult<Country>(); + Assert.That(c, Is.Not.Null); + Assert.That(c.Cities, Is.EquivalentTo(cities)); + } + + // cleanup + CleanupWithCities(); } - [Test, ExpectedException(typeof (QueryException))] + [Test] public void NativeQueryWithUnresolvedHbmAliasInjection() { IDictionary<int, AreaStatistics> stats = CreateStatistics(); - LoadCountryWithNativeSQL(CreateCountry(stats), "LoadAreaStatisticsWithFaultyHbmAliasInjection"); + try + { + LoadCountryWithNativeSQL(CreateCountry(stats), "LoadAreaStatisticsWithFaultyHbmAliasInjection"); + Assert.Fail("Expected exception"); + } + catch(QueryException) + { + // ok + } + finally + { + // cleanup + CleanupWithPersons(); + } } private Country LoadCountryWithNativeSQL(Country country, string queryName) @@ -151,10 +169,14 @@ { string[] routes = CreateRoutes(); Country country = CreateCountry(routes); - Country c = SaveAndReload(country); - Assert.That(c, Is.Not.Null, "country"); - Assert.That(c.Routes, Is.EquivalentTo(routes), "country.Routes"); - + Save(country); + using (ISession session = OpenSession()) + { + var c = session.Get<Country>(country.Code); + Assert.That(c, Is.Not.Null, "country"); + Assert.That(c.Routes, Is.EquivalentTo(routes), "country.Routes"); + } + Cleanup(); } [Test] @@ -162,10 +184,15 @@ { IDictionary<int, AreaStatistics> stats = CreateStatistics(); Country country = CreateCountry(stats); - Area a = SaveAndReload(country); - Assert.That(a, Is.Not.Null, "area"); - Assert.That((ICollection)a.Statistics.Keys, Is.EquivalentTo((ICollection)stats.Keys), "area.Keys"); - Assert.That((ICollection)a.Statistics.Values, Is.EquivalentTo((ICollection)stats.Values), "area.Elements"); + Save(country); + using (ISession session = OpenSession()) + { + var a = session.Get<Area>(country.Code); + Assert.That(a, Is.Not.Null, "area"); + Assert.That((ICollection) a.Statistics.Keys, Is.EquivalentTo((ICollection) stats.Keys), "area.Keys"); + Assert.That((ICollection) a.Statistics.Values, Is.EquivalentTo((ICollection) stats.Values), "area.Elements"); + } + CleanupWithPersons(); } [Test] @@ -173,15 +200,19 @@ { City[] cities = CreateCities(); Country country = CreateCountry(cities); - Country c = SaveAndReload(country); - Assert.That(c, Is.Not.Null, "country"); - Assert.That(c.Cities, Is.EquivalentTo(cities), "country.Cities"); + Save(country); + using (ISession session = OpenSession()) + { + var c = session.Get<Country>(country.Code); + + Assert.That(c, Is.Not.Null, "country"); + Assert.That(c.Cities, Is.EquivalentTo(cities), "country.Cities"); + } + CleanupWithCities(); } - private TArea SaveAndReload<TArea>(TArea area) where TArea : Area + private void Save<TArea>(TArea area) where TArea : Area { - //Ensure country is saved and session cache is empty to force from now on the reload of all - //persistence objects from the database. using (ISession session = OpenSession()) { using (ITransaction tx = session.BeginTransaction()) @@ -189,12 +220,7 @@ session.Save(area); tx.Commit(); } - } - using (ISession session = OpenSession()) - { - return session.Get<TArea>(area.Code); - } } #endregion @@ -261,6 +287,48 @@ #endregion + #region cleanup + + private void Cleanup() + { + using (ISession session = OpenSession()) + { + using (ITransaction tx = session.BeginTransaction()) + { + session.Delete("from Country"); + tx.Commit(); + } + } + } + + private void CleanupWithPersons() + { + using (ISession session = OpenSession()) + { + using (ITransaction tx = session.BeginTransaction()) + { + session.Delete("from Person"); + session.Delete("from Country"); + tx.Commit(); + } + } + } + + private void CleanupWithCities() + { + using (ISession session = OpenSession()) + { + using (ITransaction tx = session.BeginTransaction()) + { + session.Delete("from City"); + session.Delete("from Country"); + tx.Commit(); + } + } + } + + #endregion + #region Factory methods private static Country CreateCountry() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2009-01-02 18:52:58
|
Revision: 3973 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3973&view=rev Author: fabiomaulo Date: 2009-01-02 18:52:54 +0000 (Fri, 02 Jan 2009) Log Message: ----------- Commented the possible breaking change generated by fix of NH-1633 Modified Paths: -------------- trunk/nhibernate/releasenotes.txt Modified: trunk/nhibernate/releasenotes.txt =================================================================== --- trunk/nhibernate/releasenotes.txt 2009-01-02 18:41:32 UTC (rev 3972) +++ trunk/nhibernate/releasenotes.txt 2009-01-02 18:52:54 UTC (rev 3973) @@ -13,6 +13,9 @@ ##### Initialization time ##### * The ProxyValidator check for "internal virtual" (to be intercepted by proxy need "protected internal virtual") * The session-factory configuration property "proxyfactory.factory_class" is mandatory; You must choose one of the availables NHibernate.ByteCode + + ##### Breaking Changes ##### + * see NH-1633 if you are using SQL native queries Build 2.0.1.GA This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2009-01-02 18:41:36
|
Revision: 3972 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3972&view=rev Author: fabiomaulo Date: 2009-01-02 18:41:32 +0000 (Fri, 02 Jan 2009) Log Message: ----------- - Fix test case - Minor refactoring Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Engine/ResultSetMappingDefinition.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Mappings.hbm.xml Modified: trunk/nhibernate/src/NHibernate/Engine/ResultSetMappingDefinition.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Engine/ResultSetMappingDefinition.cs 2009-01-02 18:37:13 UTC (rev 3971) +++ trunk/nhibernate/src/NHibernate/Engine/ResultSetMappingDefinition.cs 2009-01-02 18:41:32 UTC (rev 3972) @@ -1,4 +1,3 @@ -using System.Collections; using System.Collections.Generic; using NHibernate.Engine.Query.Sql; @@ -8,7 +7,7 @@ public class ResultSetMappingDefinition { private readonly string name; - private readonly IList<INativeSQLQueryReturn> queryReturns = new List<INativeSQLQueryReturn>(); + private readonly List<INativeSQLQueryReturn> queryReturns = new List<INativeSQLQueryReturn>(); public ResultSetMappingDefinition(string name) { @@ -22,14 +21,15 @@ public void AddQueryReturn(INativeSQLQueryReturn queryReturn) { - queryReturns.Add(queryReturn); + if (queryReturn != null) + { + queryReturns.Add(queryReturn); + } } public INativeSQLQueryReturn[] GetQueryReturns() { - INativeSQLQueryReturn[] result = new INativeSQLQueryReturn[queryReturns.Count]; - queryReturns.CopyTo(result, 0); - return result; + return queryReturns.ToArray(); } } } \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Mappings.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Mappings.hbm.xml 2009-01-02 18:37:13 UTC (rev 3971) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Mappings.hbm.xml 2009-01-02 18:41:32 UTC (rev 3972) @@ -73,7 +73,7 @@ AND ci.area_type = 'CI' </sql-query> - <sql-query name="CountryStatisticsLoader" xml:space="preserve"> + <sql-query name="AreaStatisticsLoader" xml:space="preserve"> <load-collection role="Area.Statistics" alias="s"> <return-property name="key" column="code" /> <return-property name="index" column="year" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2009-01-02 18:37:17
|
Revision: 3971 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3971&view=rev Author: fabiomaulo Date: 2009-01-02 18:37:13 +0000 (Fri, 02 Jan 2009) Log Message: ----------- Fix NH-1633 Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Loader/Custom/CustomLoader.cs trunk/nhibernate/src/NHibernate.Test/Extralazy/ExtraLazyFixture.cs Modified: trunk/nhibernate/src/NHibernate/Loader/Custom/CustomLoader.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Loader/Custom/CustomLoader.cs 2009-01-02 14:41:58 UTC (rev 3970) +++ trunk/nhibernate/src/NHibernate/Loader/Custom/CustomLoader.cs 2009-01-02 18:37:13 UTC (rev 3971) @@ -368,7 +368,8 @@ public object BuildResultRow(object[] data, IDataReader resultSet, bool hasTransformer, ISessionImplementor session) { object[] resultRow; - if (!hasScalars) + // NH Different behavior (patched in NH-1612 to solve Hibernate issue HHH-2831). + if (!hasScalars && hasTransformer) { resultRow = data; } Modified: trunk/nhibernate/src/NHibernate.Test/Extralazy/ExtraLazyFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Extralazy/ExtraLazyFixture.cs 2009-01-02 14:41:58 UTC (rev 3970) +++ trunk/nhibernate/src/NHibernate.Test/Extralazy/ExtraLazyFixture.cs 2009-01-02 18:37:13 UTC (rev 3971) @@ -214,7 +214,8 @@ IList results = s.GetNamedQuery("UserSessionData").SetParameter("uname", "%in").List(); Assert.AreEqual(2, results.Count); - gavin = (User) ((object[]) results[0])[0]; + // NH Different behavior : NH1612, HHH-2831 + gavin = (User)results[0]; Assert.AreEqual("gavin", gavin.Name); Assert.AreEqual(2, gavin.Session.Count); t.Commit(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2009-01-02 14:42:01
|
Revision: 3970 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3970&view=rev Author: fabiomaulo Date: 2009-01-02 14:41:58 +0000 (Fri, 02 Jan 2009) Log Message: ----------- Little bug-fix (caused by generic dictionary usage) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs Modified: trunk/nhibernate/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs 2009-01-02 14:37:21 UTC (rev 3969) +++ trunk/nhibernate/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs 2009-01-02 14:41:58 UTC (rev 3970) @@ -1385,14 +1385,15 @@ public string[] GetCollectionPropertyColumnAliases(string propertyName, string suffix) { - string[] rawAliases = (string[]) collectionPropertyColumnAliases[propertyName]; - - if (rawAliases == null) + object aliases; + collectionPropertyColumnAliases.TryGetValue(propertyName, out aliases); + if (aliases == null) { return null; } + var rawAliases = (string[]) aliases; - string[] result = new string[rawAliases.Length]; + var result = new string[rawAliases.Length]; for (int i = 0; i < rawAliases.Length; i++) { result[i] = new Alias(suffix).ToUnquotedAliasString(rawAliases[i], dialect); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2009-01-02 14:37:29
|
Revision: 3969 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3969&view=rev Author: fabiomaulo Date: 2009-01-02 14:37:21 +0000 (Fri, 02 Jan 2009) Log Message: ----------- Test for NH-1612 Modified Paths: -------------- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Area.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/AreaStatistics.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/City.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Country.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Mappings.hbm.xml trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/MonetaryValue.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/NativeSqlCollectionLoaderFixture.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Person.cs Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Area.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Area.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Area.cs 2009-01-02 14:37:21 UTC (rev 3969) @@ -0,0 +1,42 @@ +using System.Collections.Generic; + +namespace NHibernate.Test.NHSpecificTest.NH1612 +{ + public abstract class Area + { + public virtual string Code { get; private set; } + public virtual string Name { get; private set; } + public virtual int Version { get; private set; } + public virtual IDictionary<int, AreaStatistics> Statistics { get; private set; } + + protected Area() {} + + protected Area(string code, string name) + { + Code = code; + Name = name; + Statistics = new Dictionary<int, AreaStatistics>(); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(this, obj)) + { + return true; + } + + var other = obj as Area; + if (ReferenceEquals(obj, null)) + { + return false; + } + + return GetType() == other.GetType() && Code == other.Code; + } + + public override int GetHashCode() + { + return (Code ?? string.Empty).GetHashCode() ^ GetType().GetHashCode(); + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/AreaStatistics.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/AreaStatistics.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/AreaStatistics.cs 2009-01-02 14:37:21 UTC (rev 3969) @@ -0,0 +1,59 @@ +using System.Text; + +namespace NHibernate.Test.NHSpecificTest.NH1612 +{ + public class AreaStatistics + { + public virtual MonetaryValue? GDP { get; set; } + public virtual int? CitizenCount { get; set; } + public virtual Person Reporter { get; set; } + + public override bool Equals(object obj) + { + if (ReferenceEquals(this, obj)) + { + return true; + } + + var other = obj as AreaStatistics; + if (ReferenceEquals(other, null)) + { + return false; + } + + return CitizenCount == other.CitizenCount && GDP == other.GDP && Reporter == other.Reporter; + } + + public override int GetHashCode() + { + return (CitizenCount ?? 0) ^ GDP.GetHashCode() ^ (Reporter != null ? Reporter.GetHashCode() : 0); + } + + public override string ToString() + { + var sb = new StringBuilder(); + if (CitizenCount.HasValue) + { + sb.Append("CitizenCount: ").Append(CitizenCount); + } + if (GDP.HasValue) + { + if (sb.Length > 0) + { + sb.Append("; "); + } + sb.Append("GDP: ").Append(GDP); + } + if (Reporter != null) + { + if (sb.Length > 0) + { + sb.Append("; "); + } + sb.Append("Reporter: ").Append(Reporter.Name); + } + + return sb.ToString(); + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/City.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/City.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/City.cs 2009-01-02 14:37:21 UTC (rev 3969) @@ -0,0 +1,24 @@ +namespace NHibernate.Test.NHSpecificTest.NH1612 +{ + public class City : Area + { + public virtual Country Country { get; private set; } + + protected City() {} + + public City(string code, string name) : base(code, name) {} + + public virtual void SetParent(Country country) + { + if (Country != null) + { + Country.Cities.Remove(this); + } + Country = country; + if (country != null) + { + country.Cities.Add(this); + } + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Country.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Country.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Country.cs 2009-01-02 14:37:21 UTC (rev 3969) @@ -0,0 +1,18 @@ +using System.Collections.Generic; + +namespace NHibernate.Test.NHSpecificTest.NH1612 +{ + public class Country : Area + { + public virtual IList<string> Routes { get; private set; } + public virtual IList<City> Cities { get; private set; } + + protected Country() {} + + public Country(string code, string name) : base(code, name) + { + Routes = new List<string>(); + Cities = new List<City>(); + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Mappings.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Mappings.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Mappings.hbm.xml 2009-01-02 14:37:21 UTC (rev 3969) @@ -0,0 +1,306 @@ +<?xml version="1.0" encoding="utf-8" ?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" + assembly="NHibernate.Test" + namespace="NHibernate.Test.NHSpecificTest.NH1612" + default-cascade="save-update"> + + <class name="Area" table="areas"> + <id name="Code" column="code" type="String" length="3"> + <generator class="assigned"/> + </id> + <discriminator column="area_type" type="String" length="2" not-null="true" /> + <version name="Version" column="version" type="Int32" generated="never" unsaved-value="0" /> + <property name="Name" column="name" type="String" length="50" not-null="true" /> + <map name="Statistics" table="stats"> + <key column="area_code" /> + <index column="year" type="Int32" /> + <composite-element class="AreaStatistics"> + <property name="CitizenCount" column="citizen_count" type="Int32" /> + <nested-composite-element name="GDP" class="MonetaryValue"> + <property name="CurrencySymbol" column="gdp_currency" type="String" length="3" /> + <property name="Amount" column="gdp_amount" type="double" not-null="false" /> + </nested-composite-element> + <many-to-one name="Reporter" column="reporter_id" class="Person" /> + </composite-element> + <loader query-ref="AreaStatisticsLoader" /> + </map> + + <subclass name="Country" discriminator-value="CO"> + <list name="Routes" table="routes" generic="true"> + <key column="country_code" /> + <index column="route_no" /> + <element column="name" type="String" length="50" /> + <loader query-ref="CountryRouteLoader" /> + </list> + + <bag name="Cities" table="cities" inverse="true" generic="true"> + <key column="country_code" /> + <one-to-many class="City" /> + <loader query-ref="CountryCityLoader" /> + </bag> + </subclass> + + <subclass name="City" discriminator-value="CI"> + <!-- Cascading saves disabled, because it causes exceptions --> + <many-to-one name="Country" column="country_code" class="Country" /> + </subclass> + </class> + + <class name="Person" table="persons"> + <id name="PersonId" column="id"> + <generator class="assigned" /> + </id> + <version name="Version" column="version" type="Int32" generated="never" unsaved-value="0" /> + <property name="Name" type="String" length="100" /> + </class> + + <!-- + Collection loaders + --> + + <sql-query name="CountryRouteLoader" xml:space="preserve"> + <load-collection role="Country.Routes" alias="r" /> + SELECT {r.*} + FROM routes r + WHERE r.country_code = :country_code + </sql-query> + + <sql-query name="CountryCityLoader" xml:space="preserve"> + <load-collection role="Country.Cities" alias="ci" /> + SELECT {ci.*} + FROM areas ci + WHERE ci.country_code = :country_code + AND ci.area_type = 'CI' + </sql-query> + + <sql-query name="CountryStatisticsLoader" xml:space="preserve"> + <load-collection role="Area.Statistics" alias="s"> + <return-property name="key" column="code" /> + <return-property name="index" column="year" /> + <return-property name="element.CitizenCount" column="citizen_count" /> + <return-property name="element.GDP"> + <return-column name="gdp_currency" /> + <return-column name="gdp_amount" /> + </return-property> + <return-property name="element.Reporter" column="reporter_id" /> + </load-collection> + SELECT area_code + , year + , citizen_count + , gdp_currency + , gdp_amount + , reporter_id + FROM stats + WHERE area_code = :area_code + </sql-query> + + + <!-- + Entity queries with non-lazy loading of collections + --> + + <sql-query name="LoadCountryRoutesWithSimpleHbmAliasInjection" xml:space="preserve"> + <return class="Country" alias="c" /> + <return-join alias="r" property="c.Routes" /> + SELECT {c.*} + , {r.*} + FROM areas c + LEFT OUTER JOIN routes r + ON c.code = r.country_code + WHERE c.code = :country_code + </sql-query> + + <sql-query name="LoadCountryRoutesWithCustomAliases" xml:space="preserve"> + <return class="Country" alias="c"> + <return-property name="id" column="code" /> + <return-property name="Version" column="version" /> + <return-property name="Name" column="country_name" /> + </return> + <return-join property="c.Routes" alias="r"> + <return-property name="key" column="country_code" /> + <return-property name="index" column="route_no" /> + <return-property name="element" column="route_name" /> + </return-join> + SELECT c.code + , c.version + , c.name AS country_name + , r.country_code + , r.route_no + , r.name AS route_name + FROM areas c + LEFT OUTER JOIN routes r + ON c.code = r.country_code + WHERE c.code = :country_code + </sql-query> + + <sql-query name="LoadCountryCitiesWithSimpleHbmAliasInjection" xml:space="preserve"> + <return class="Country" alias="co" /> + <return-join property="co.Cities" alias="ci" /> + SELECT {co.*} + , {ci.*} + FROM areas co + LEFT OUTER JOIN areas ci + ON ci.country_code = co.code + AND ci.area_type = 'CI' + WHERE co.code = :country_code + AND co.area_type = 'CO' + </sql-query> + + <sql-query name="LoadCountryCitiesWithComplexHbmAliasInjection" xml:space="preserve"> + <return class="Country" alias="co" /> + <return-join property="co.Cities" alias="ci" /> + SELECT co.code AS {co.id} + , co.version AS {co.Version} + , co.name AS {co.Name} + , ci.country_code AS {ci.key} + , ci.code AS {ci.element} + , ci.code AS {ci.element.id} + , ci.version AS {ci.element.Version} + , ci.name AS {ci.element.Name} + , ci.country_code AS {ci.element.Country} + FROM areas co + LEFT OUTER JOIN areas ci + ON ci.country_code = co.code + AND ci.area_type = 'CI' + WHERE co.code = :country_code + AND co.area_type = 'CO' + </sql-query> + + <sql-query name="LoadCountryCitiesWithCustomAliases" xml:space="preserve"> + <return class="Country" alias="co"> + <return-property name="id" column="country_code" /> + <return-property name="Version" column="country_version" /> + <return-property name="Name" column="country_name" /> + </return> + <return-join property="co.Cities" alias="ci"> + <return-property name="key" column="country_code" /> + <return-property name="element" column="city_code" /> + <return-property name="element.id" column="city_code" /> + <return-property name="element.Version" column="city_version" /> + <return-property name="element.Name" column="city_name" /> + <return-property name="element.Country" column="country_name" /> + </return-join> + SELECT co.code AS country_code + , co.version AS country_version + , co.name AS country_name + , ci.code AS city_code + , ci.version AS city_version + , ci.name AS city_name + FROM areas co + LEFT OUTER JOIN areas ci + ON ci.country_code = co.code + AND ci.area_type = 'CI' + WHERE co.code = :country_code + AND co.area_type = 'CO' + </sql-query> + + <sql-query name="LoadAreaStatisticsWithSimpleHbmAliasInjection" xml:space="preserve"> + <return class="Area" alias="a" /> + <return-join property="a.Statistics" alias="s" /> + SELECT {a.*} + , {s.*} + FROM areas a + LEFT OUTER JOIN stats s + ON a.code = s.area_code + WHERE a.code = :country_code + </sql-query> + + <sql-query name="LoadAreaStatisticsWithComplexHbmAliasInjection" xml:space="preserve"> + <return class="Area" alias="a" /> + <return-join property="a.Statistics" alias="s" /> + SELECT a.code AS {a.id} + , a.area_type AS {a.class} + , a.version AS {a.Version} + , a.name AS {a.Name} + , s.area_code AS {s.key} + , s.year AS {s.index} + , s.citizen_count AS {s.element.CitizenCount} + , s.gdp_currency AS {s.element.GDP.CurrencySymbol} + , s.gdp_amount AS {s.element.GDP.Amount} + , s.reporter_id AS {s.element.Reporter} + FROM areas a + LEFT OUTER JOIN stats s + ON a.code = s.area_code + WHERE a.code = :country_code + </sql-query> + + <sql-query name="LoadAreaStatisticsWithCustomAliases" xml:space="preserve"> + <return class="Area" alias="a"> + <return-discriminator column="area_type" /> + <return-property name="id" column="code" /> + <return-property name="Version" column="version" /> + <return-property name="Name" column="name" /> + </return> + <return-join property="a.Statistics" alias="s"> + <return-property name="key" column="code" /> + <return-property name="index" column="year" /> + <return-property name="element.CitizenCount" column="citizen_count" /> + <return-property name="element.GDP"> + <return-column name="gdp_currency" /> + <return-column name="gdp_amount" /> + </return-property> + <return-property name="element.Reporter" column="reporter_id" /> + </return-join> + SELECT a.code + , a.area_type + , a.version + , a.name + , s.year + , s.citizen_count + , s.gdp_currency + , s.gdp_amount + , s.reporter_id + FROM areas a + LEFT OUTER JOIN stats s + ON a.code = s.area_code + WHERE a.code = :country_code + </sql-query> + + <sql-query name="LoadAreaStatisticsWithFaultyHbmAliasInjection" xml:space="preserve"> + <return class="Area" alias="a" /> + <return-join property="a.Statistics" alias="s" /> + SELECT a.code AS {a.id} + , a.area_type AS {a.class} + , a.version AS {a.Version} + , a.name AS {a.Name} + , s.area_code AS {s.key} + , s.year AS {s.index} + , s.citizen_count AS {s.element.CitizenCountMisspelled} + , s.gdp_currency AS {s.element.GDP.CurrencySymbol} + , s.gdp_amount AS {s.element.GDP.Amount} + FROM areas a + LEFT OUTER JOIN stats s + ON a.code = s.area_code + WHERE a.code = :country_code + </sql-query> + + + <!-- + Update queries + --> + + <sql-query name="UpdateQueryWithoutResults"> + -- NOP + </sql-query> + + + <!-- + Scalar queries + --> + + <sql-query name="ScalarQueryWithDefinedResultset"> + <return-scalar column="result" type="Int32" /> + SELECT 2 AS result + </sql-query> + + <sql-query name="ScalarQueryWithDefinedResultsetButNoResults"> + <!-- Pathetic case, query declares resultset but does not deliver the goods --> + <return-scalar column="dummy" type="Int32" /> + <return class="Area" alias="a" /> + -- NOP + </sql-query> + + <sql-query name="ScalarQueryWithUndefinedResultset"> + SELECT 1 + </sql-query> +</hibernate-mapping> Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/MonetaryValue.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/MonetaryValue.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/MonetaryValue.cs 2009-01-02 14:37:21 UTC (rev 3969) @@ -0,0 +1,51 @@ +namespace NHibernate.Test.NHSpecificTest.NH1612 +{ + public struct MonetaryValue + { + private string _currencySymbol; + private double _amount; + + public MonetaryValue(string currencySymbol, double amount) + { + _currencySymbol = currencySymbol; + _amount = amount; + } + + public string CurrencySymbol + { + get { return _currencySymbol; } + private set { _currencySymbol = value; } + } + + public double Amount + { + get { return _amount; } + private set { _amount = value; } + } + + public static bool operator ==(MonetaryValue left, MonetaryValue right) + { + return left._currencySymbol == right._currencySymbol && left._amount == right._amount; + } + + public static bool operator !=(MonetaryValue left, MonetaryValue right) + { + return !(left == right); + } + + public override bool Equals(object obj) + { + return obj is MonetaryValue ? this == (MonetaryValue) obj : false; + } + + public override int GetHashCode() + { + return (_currencySymbol ?? string.Empty).GetHashCode() ^ _amount.GetHashCode(); + } + + public override string ToString() + { + return string.Format("{0} {1}", _currencySymbol, _amount); + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/NativeSqlCollectionLoaderFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/NativeSqlCollectionLoaderFixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/NativeSqlCollectionLoaderFixture.cs 2009-01-02 14:37:21 UTC (rev 3969) @@ -0,0 +1,335 @@ +using System.Collections; +using System.Collections.Generic; +using NUnit.Framework; +using NUnit.Framework.SyntaxHelpers; + +namespace NHibernate.Test.NHSpecificTest.NH1612 +{ + [TestFixture, Ignore("Not fixed yet.")] + public class NativeSqlCollectionLoaderFixture : BugTestCase + { + #region Tests - <return-join> + + [Test] + public void LoadElementsWithWithSimpleHbmAliasInjection() + { + string[] routes = CreateRoutes(); + Country country = LoadCountryWithNativeSQL(CreateCountry(routes), "LoadCountryRoutesWithSimpleHbmAliasInjection"); + + Assert.That(country, Is.Not.Null); + Assert.That(country.Routes, Is.EquivalentTo(routes)); + + // cleanup + using (ISession session = OpenSession()) + { + using (ITransaction tx = session.BeginTransaction()) + { + session.Delete(country); + tx.Commit(); + } + } + } + + [Test] + public void LoadElementsWithExplicitColumnMappings() + { + string[] routes = CreateRoutes(); + Country country = LoadCountryWithNativeSQL(CreateCountry(routes), "LoadCountryRoutesWithCustomAliases"); + Assert.That(country, Is.Not.Null); + Assert.That(country.Routes, Is.EquivalentTo(routes)); + // cleanup + using (ISession session = OpenSession()) + { + using (ITransaction tx = session.BeginTransaction()) + { + session.Delete(country); + tx.Commit(); + } + } + } + + [Test] + public void LoadCompositeElementsWithWithSimpleHbmAliasInjection() + { + IDictionary<int, AreaStatistics> stats = CreateStatistics(); + Country country = LoadCountryWithNativeSQL(CreateCountry(stats), "LoadAreaStatisticsWithSimpleHbmAliasInjection"); + + Assert.That(country, Is.Not.Null); + Assert.That((ICollection) country.Statistics.Keys, Is.EquivalentTo((ICollection) stats.Keys), "Keys"); + Assert.That((ICollection) country.Statistics.Values, Is.EquivalentTo((ICollection) stats.Values), "Elements"); + // cleanup + using (ISession session = OpenSession()) + { + using (ITransaction tx = session.BeginTransaction()) + { + session.Delete(country); + tx.Commit(); + } + } + } + + [Test] + public void LoadCompositeElementsWithWithComplexHbmAliasInjection() + { + IDictionary<int, AreaStatistics> stats = CreateStatistics(); + Country country = LoadCountryWithNativeSQL(CreateCountry(stats), "LoadAreaStatisticsWithComplexHbmAliasInjection"); + + Assert.That(country, Is.Not.Null); + Assert.That((ICollection) country.Statistics.Keys, Is.EquivalentTo((ICollection) stats.Keys), "Keys"); + Assert.That((ICollection) country.Statistics.Values, Is.EquivalentTo((ICollection) stats.Values), "Elements"); + } + + [Test] + public void LoadCompositeElementsWithWithCustomAliases() + { + IDictionary<int, AreaStatistics> stats = CreateStatistics(); + Country country = LoadCountryWithNativeSQL(CreateCountry(stats), "LoadAreaStatisticsWithCustomAliases"); + + Assert.That(country, Is.Not.Null); + Assert.That((ICollection) country.Statistics.Keys, Is.EquivalentTo((ICollection) stats.Keys), "Keys"); + Assert.That((ICollection) country.Statistics.Values, Is.EquivalentTo((ICollection) stats.Values), "Elements"); + } + + [Test] + public void LoadEntitiesWithWithSimpleHbmAliasInjection() + { + City[] cities = CreateCities(); + Country country = LoadCountryWithNativeSQL(CreateCountry(cities), "LoadCountryCitiesWithSimpleHbmAliasInjection"); + Assert.That(country, Is.Not.Null); + Assert.That(country.Cities, Is.EquivalentTo(cities)); + } + + [Test] + public void LoadEntitiesWithComplexHbmAliasInjection() + { + City[] cities = CreateCities(); + Country country = LoadCountryWithNativeSQL(CreateCountry(cities), "LoadCountryCitiesWithComplexHbmAliasInjection"); + Assert.That(country, Is.Not.Null); + Assert.That(country.Cities, Is.EquivalentTo(cities)); + } + + [Test] + public void LoadEntitiesWithExplicitColumnMappings() + { + City[] cities = CreateCities(); + Country country = LoadCountryWithNativeSQL(CreateCountry(cities), "LoadCountryCitiesWithCustomAliases"); + Assert.That(country, Is.Not.Null); + Assert.That(country.Cities, Is.EquivalentTo(cities)); + } + + [Test, ExpectedException(typeof (QueryException))] + public void NativeQueryWithUnresolvedHbmAliasInjection() + { + IDictionary<int, AreaStatistics> stats = CreateStatistics(); + LoadCountryWithNativeSQL(CreateCountry(stats), "LoadAreaStatisticsWithFaultyHbmAliasInjection"); + } + + private Country LoadCountryWithNativeSQL(Country country, string queryName) + { + // Ensure country is saved and session cache is empty to force from now on the reload of all + // persistence objects from the database. + using (ISession session = OpenSession()) + { + using (ITransaction tx = session.BeginTransaction()) + { + session.Save(country); + tx.Commit(); + } + } + using (ISession session = OpenSession()) + { + return session.GetNamedQuery(queryName).SetString("country_code", country.Code).UniqueResult<Country>(); + } + } + + #endregion + + #region Tests - <load-collection> + + [Test] + public void LoadElementCollectionWithCustomLoader() + { + string[] routes = CreateRoutes(); + Country country = CreateCountry(routes); + Country c = SaveAndReload(country); + Assert.That(c, Is.Not.Null, "country"); + Assert.That(c.Routes, Is.EquivalentTo(routes), "country.Routes"); + + } + + [Test] + public void LoadCompositeElementCollectionWithCustomLoader() + { + IDictionary<int, AreaStatistics> stats = CreateStatistics(); + Country country = CreateCountry(stats); + Area a = SaveAndReload(country); + Assert.That(a, Is.Not.Null, "area"); + Assert.That((ICollection)a.Statistics.Keys, Is.EquivalentTo((ICollection)stats.Keys), "area.Keys"); + Assert.That((ICollection)a.Statistics.Values, Is.EquivalentTo((ICollection)stats.Values), "area.Elements"); + } + + [Test] + public void LoadEntityCollectionWithCustomLoader() + { + City[] cities = CreateCities(); + Country country = CreateCountry(cities); + Country c = SaveAndReload(country); + Assert.That(c, Is.Not.Null, "country"); + Assert.That(c.Cities, Is.EquivalentTo(cities), "country.Cities"); + } + + private TArea SaveAndReload<TArea>(TArea area) where TArea : Area + { + //Ensure country is saved and session cache is empty to force from now on the reload of all + //persistence objects from the database. + using (ISession session = OpenSession()) + { + using (ITransaction tx = session.BeginTransaction()) + { + session.Save(area); + tx.Commit(); + } + + } + using (ISession session = OpenSession()) + { + return session.Get<TArea>(area.Code); + } + } + + #endregion + + #region Tests - corner cases to verify backwards compatibility of NH-1612 patch + + [Test] + public void NativeUpdateQueryWithoutResults() + { + using (ISession session = OpenSession()) + { + using (ITransaction tx = session.BeginTransaction()) + { + session.GetNamedQuery("UpdateQueryWithoutResults").ExecuteUpdate(); + tx.Commit(); + } + } + } + + [Test] + public void NativeScalarQueryWithoutResults() + { + using (ISession session = OpenSession()) + { + using (ITransaction tx = session.BeginTransaction()) + { + // Native SQL Query outcome is not validated against <return-*> + // resultset declarations. + session.GetNamedQuery("ScalarQueryWithDefinedResultsetButNoResults").ExecuteUpdate(); + tx.Commit(); + } + } + } + + [Test] + public void NativeScalarQueryWithUndefinedResultset() + { + using (ISession session = OpenSession()) + { + using (session.BeginTransaction()) + { + // Native SQL Query outcome is not validated against <return-*> + // resultset declarations. + var result = session.GetNamedQuery("ScalarQueryWithUndefinedResultset").UniqueResult<int>(); + Assert.That(result, Is.EqualTo(1)); + } + } + } + + [Test] + public void NativeScalarQueryWithDefinedResultset() + { + using (ISession session = OpenSession()) + { + using (session.BeginTransaction()) + { + // Native SQL Query outcome is not validated against <return-*> + // resultset declarations. + var result = session.GetNamedQuery("ScalarQueryWithDefinedResultset").UniqueResult<int>(); + Assert.That(result, Is.EqualTo(2)); + } + } + } + + #endregion + + #region Factory methods + + private static Country CreateCountry() + { + const string COUNTRY_CODE = "WL"; + const string COUNTRY_NAME = "Wonderland"; + return new Country(COUNTRY_CODE, COUNTRY_NAME); + } + + private static Country CreateCountry(params string[] routes) + { + Country country = CreateCountry(); + foreach (var route in routes) + { + country.Routes.Add(route); + } + return country; + } + + private static Country CreateCountry(params City[] cities) + { + Country country = CreateCountry(); + foreach (var city in cities) + { + city.SetParent(country); + } + return country; + } + + private static Country CreateCountry(IDictionary<int, AreaStatistics> statistics) + { + Country country = CreateCountry(); + foreach (var pair in statistics) + { + country.Statistics.Add(pair); + } + return country; + } + + private static string[] CreateRoutes() + { + return new[] {"Yellow Road", "Muddy Path"}; + } + + private static City[] CreateCities() + { + return new[] {new City("EMR", "Emerald City"), new City("GLD", "Golden Town"), new City("NTH", "North End")}; + } + + private static IDictionary<int, AreaStatistics> CreateStatistics() + { + var archimedes = new Person("Archimedes"); + var archibald = new Person("Archibald"); + var amy = new Person("Amy"); + return new Dictionary<int, AreaStatistics> + { + { + 1850, + new AreaStatistics {CitizenCount = 10000, GDP = new MonetaryValue("USD", 20000), Reporter = archimedes} + }, + { + 1900, + new AreaStatistics {CitizenCount = 20000, GDP = new MonetaryValue("USD", 50000), Reporter = archibald} + }, + {1950, new AreaStatistics {CitizenCount = 40000, GDP = new MonetaryValue("USD", 125000)}}, + {2000, new AreaStatistics {CitizenCount = 80000, GDP = new MonetaryValue("USD", 500000), Reporter = amy}}, + }; + } + + #endregion + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Person.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Person.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1612/Person.cs 2009-01-02 14:37:21 UTC (rev 3969) @@ -0,0 +1,52 @@ +using System; + +namespace NHibernate.Test.NHSpecificTest.NH1612 +{ + public class Person + { + public virtual Guid PersonId { get; private set; } + public virtual string Name { get; private set; } + public virtual int Version { get; private set; } + + protected Person() {} + + public Person(string name) + { + PersonId = Guid.NewGuid(); + Name = name; + } + + public static bool operator ==(Person left, Person right) + { + if (ReferenceEquals(left, right)) + { + return true; + } + if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) + { + return true; + } + return left.PersonId == right.PersonId; + } + + public static bool operator !=(Person left, Person right) + { + return !(left == right); + } + + public override bool Equals(object obj) + { + return this == (Person) obj; + } + + public override int GetHashCode() + { + return PersonId.GetHashCode(); + } + + public override string ToString() + { + return Name; + } + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-12-30 19:41:26 UTC (rev 3968) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2009-01-02 14:37:21 UTC (rev 3969) @@ -558,6 +558,13 @@ <Compile Include="NHSpecificTest\NH1594\A.cs" /> <Compile Include="NHSpecificTest\NH1594\Fixture.cs" /> <Compile Include="NHSpecificTest\NH1608\Fixture.cs" /> + <Compile Include="NHSpecificTest\NH1612\Area.cs" /> + <Compile Include="NHSpecificTest\NH1612\AreaStatistics.cs" /> + <Compile Include="NHSpecificTest\NH1612\City.cs" /> + <Compile Include="NHSpecificTest\NH1612\Country.cs" /> + <Compile Include="NHSpecificTest\NH1612\MonetaryValue.cs" /> + <Compile Include="NHSpecificTest\NH1612\NativeSqlCollectionLoaderFixture.cs" /> + <Compile Include="NHSpecificTest\NH1612\Person.cs" /> <Compile Include="NHSpecificTest\NH1621\Fixture.cs" /> <Compile Include="NHSpecificTest\NH1621\Model.cs" /> <Compile Include="NHSpecificTest\NH280\Fixture.cs" /> @@ -1581,6 +1588,7 @@ <EmbeddedResource Include="Cascade\JobBatch.hbm.xml" /> <EmbeddedResource Include="Deletetransient\Person.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> + <EmbeddedResource Include="NHSpecificTest\NH1612\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1549\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1521\AclassWithSpecific.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1521\AclassWithNothing.hbm.xml" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <dav...@us...> - 2008-12-30 19:41:36
|
Revision: 3968 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3968&view=rev Author: davybrion Date: 2008-12-30 19:41:26 +0000 (Tue, 30 Dec 2008) Log Message: ----------- fix for NH-1609 Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Dialect/Dialect.cs trunk/nhibernate/src/NHibernate/Driver/DriverBase.cs trunk/nhibernate/src/NHibernate/Driver/IDriver.cs trunk/nhibernate/src/NHibernate/Driver/SqlStringFormatter.cs trunk/nhibernate/src/NHibernate/Impl/MultiCriteriaImpl.cs trunk/nhibernate/src/NHibernate/Impl/MultiQueryImpl.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1609/Fixture.cs Modified: trunk/nhibernate/src/NHibernate/Dialect/Dialect.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/Dialect.cs 2008-12-28 22:20:58 UTC (rev 3967) +++ trunk/nhibernate/src/NHibernate/Dialect/Dialect.cs 2008-12-30 19:41:26 UTC (rev 3968) @@ -989,14 +989,6 @@ } /// <summary> - /// How we separate the queries when we use multiply queries. - /// </summary> - public virtual string MultipleQueriesSeparator - { - get { return ";"; } - } - - /// <summary> /// The syntax used to drop a foreign key constraint from a table. /// </summary> /// <param name="constraintName">The name of the foreign key constraint to drop.</param> Modified: trunk/nhibernate/src/NHibernate/Driver/DriverBase.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Driver/DriverBase.cs 2008-12-28 22:20:58 UTC (rev 3967) +++ trunk/nhibernate/src/NHibernate/Driver/DriverBase.cs 2008-12-30 19:41:26 UTC (rev 3968) @@ -166,7 +166,7 @@ private void SetCommandText(IDbCommand cmd, SqlString sqlString) { - SqlStringFormatter formatter = new SqlStringFormatter(this); + SqlStringFormatter formatter = new SqlStringFormatter(this, MultipleQueriesSeparator); formatter.Format(sqlString); cmd.CommandText = formatter.GetFormattedText(); } @@ -227,5 +227,10 @@ { get { return false; } } + + public virtual string MultipleQueriesSeparator + { + get { return ";"; } + } } } \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Driver/IDriver.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Driver/IDriver.cs 2008-12-28 22:20:58 UTC (rev 3967) +++ trunk/nhibernate/src/NHibernate/Driver/IDriver.cs 2008-12-30 19:41:26 UTC (rev 3968) @@ -66,6 +66,11 @@ bool SupportsMultipleQueries { get; } /// <summary> + /// How we separate the queries when we use multiply queries. + /// </summary> + string MultipleQueriesSeparator { get; } + + /// <summary> /// Generates an IDbCommand from the SqlString according to the requirements of the DataProvider. /// </summary> /// <param name="type">The <see cref="CommandType"/> of the command to generate.</param> Modified: trunk/nhibernate/src/NHibernate/Driver/SqlStringFormatter.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Driver/SqlStringFormatter.cs 2008-12-28 22:20:58 UTC (rev 3967) +++ trunk/nhibernate/src/NHibernate/Driver/SqlStringFormatter.cs 2008-12-30 19:41:26 UTC (rev 3968) @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Text; using NHibernate.SqlCommand; @@ -6,17 +7,23 @@ { public class SqlStringFormatter : ISqlStringVisitor { - private StringBuilder result = new StringBuilder(); + private readonly StringBuilder result = new StringBuilder(); private int parameterIndex = 0; - private ISqlParameterFormatter formatter; + private readonly ISqlParameterFormatter formatter; + private readonly string multipleQueriesSeparator; - public SqlStringFormatter(ISqlParameterFormatter formatter) + private readonly Dictionary<int, int> queryIndexToNumberOfPreceedingParameters = new Dictionary<int, int>(); + private readonly Dictionary<int, int> parameterIndexToQueryIndex = new Dictionary<int, int>(); + + public SqlStringFormatter(ISqlParameterFormatter formatter, string multipleQueriesSeparator) { this.formatter = formatter; + this.multipleQueriesSeparator = multipleQueriesSeparator; } public void Format(SqlString text) { + DetermineNumberOfPreceedingParametersForEachQuery(text); text.Visit(this); } @@ -37,10 +44,62 @@ void ISqlStringVisitor.Parameter(Parameter parameter) { - string name = formatter.GetParameterName( - parameter.OriginalPositionInQuery ?? parameterIndex); + string name; + + if (queryIndexToNumberOfPreceedingParameters.Count == 0) + { + // there's only one query... no need to worry about indexes of parameters of previous queries + name = formatter.GetParameterName(parameter.OriginalPositionInQuery ?? parameterIndex); + } + else + { + // multiple queries... in case the parameters were switched around (for SQL paging for instance) we need + // to keep the number of preceeding parameters (in previous queries of the batch) into account + if (parameter.OriginalPositionInQuery != null) + { + name = formatter.GetParameterName(GetNumberOfPreceedingParameters() + parameter.OriginalPositionInQuery.Value); + } + else + { + name = formatter.GetParameterName(parameterIndex); + } + } + parameterIndex++; result.Append(name); } + + private int GetNumberOfPreceedingParameters() + { + int queryIndex = parameterIndexToQueryIndex[parameterIndex]; + return queryIndexToNumberOfPreceedingParameters[queryIndex]; + } + + private void DetermineNumberOfPreceedingParametersForEachQuery(SqlString text) + { + int currentParameterIndex = 0; + int currentQueryParameterCount = 0; + int currentQueryIndex = 0; + + foreach (object part in text.Parts) + { + if (part.ToString().Equals(multipleQueriesSeparator)) + { + queryIndexToNumberOfPreceedingParameters[currentQueryIndex] = currentParameterIndex - currentQueryParameterCount; + currentQueryParameterCount = 0; + currentQueryIndex++; + continue; + } + + Parameter parameter = part as Parameter; + + if (parameter != null) + { + parameterIndexToQueryIndex[currentParameterIndex] = currentQueryIndex; + currentQueryParameterCount++; + currentParameterIndex++; + } + } + } } } Modified: trunk/nhibernate/src/NHibernate/Impl/MultiCriteriaImpl.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Impl/MultiCriteriaImpl.cs 2008-12-28 22:20:58 UTC (rev 3967) +++ trunk/nhibernate/src/NHibernate/Impl/MultiCriteriaImpl.cs 2008-12-30 19:41:26 UTC (rev 3968) @@ -174,7 +174,7 @@ parameters.Add(queryParameters); SqlCommandInfo commandInfo = loader.GetQueryStringAndTypes(session, queryParameters); sqlString = sqlString.Append(commandInfo.Text) - .Append(dialect.MultipleQueriesSeparator) + .Append(session.Factory.ConnectionProvider.Driver.MultipleQueriesSeparator) .Append(Environment.NewLine); types.AddRange(commandInfo.ParameterTypes); } Modified: trunk/nhibernate/src/NHibernate/Impl/MultiQueryImpl.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Impl/MultiQueryImpl.cs 2008-12-28 22:20:58 UTC (rev 3967) +++ trunk/nhibernate/src/NHibernate/Impl/MultiQueryImpl.cs 2008-12-30 19:41:26 UTC (rev 3968) @@ -581,7 +581,7 @@ parameters.Add(queryParameters); queryParameters = GetFilteredQueryParameters(queryParameters, translator); SqlCommandInfo commandInfo = translator.GetQueryStringAndTypes(session, queryParameters); - sqlString = sqlString.Append(commandInfo.Text).Append(dialect.MultipleQueriesSeparator).Append(Environment.NewLine); + sqlString = sqlString.Append(commandInfo.Text).Append(session.Factory.ConnectionProvider.Driver.MultipleQueriesSeparator).Append(Environment.NewLine); types.AddRange(commandInfo.ParameterTypes); } } Modified: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1609/Fixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1609/Fixture.cs 2008-12-28 22:20:58 UTC (rev 3967) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1609/Fixture.cs 2008-12-30 19:41:26 UTC (rev 3968) @@ -8,7 +8,6 @@ namespace NHibernate.Test.NHSpecificTest.NH1609 { [TestFixture] - [Ignore("not fixed yet")] public class Fixture : BugTestCase { [Test] This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: T. T. <te...@gm...> - 2008-12-28 22:35:51
|
I am not sure if SF allows but some SVN providers allows you to change history logs. You may try. Tuna Toksöz http://tunatoksoz.com Typos included to enhance the readers attention! On Mon, Dec 29, 2008 at 12:27 AM, Davy Brion <ra...@da...> wrote: > yeah sorry, forgot to add the commit message.... this commit fixed NH-1549 > and NH-1590 > > > On Sun, Dec 28, 2008 at 11:23 PM, Tuna Toksöz <te...@gm...> wrote: > >> Commit log? >> >> >> Tuna Toksöz >> http://tunatoksoz.com >> >> Typos included to enhance the readers attention! >> >> >> >> >> On Mon, Dec 29, 2008 at 12:20 AM, <dav...@us...>wrote: >> >>> Revision: 3967 >>> >>> http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3967&view=rev >>> Author: davybrion >>> Date: 2008-12-28 22:20:58 +0000 (Sun, 28 Dec 2008) >>> >>> Log Message: >>> ----------- >>> >>> >>> Modified Paths: >>> -------------- >>> trunk/nhibernate/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs >>> trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs >>> trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj >>> >>> trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs >>> >>> Added Paths: >>> ----------- >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ >>> >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs >>> >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/EntityInt32.cs >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Fixture.cs >>> >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Mappings.hbm.xml >>> >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs >>> >>> Modified: >>> trunk/nhibernate/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs >>> =================================================================== >>> --- trunk/nhibernate/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs >>> 2008-12-27 19:53:57 UTC (rev 3966) >>> +++ trunk/nhibernate/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs >>> 2008-12-28 22:20:58 UTC (rev 3967) >>> @@ -62,7 +62,7 @@ >>> /// underlying proxied object is needed then it returns >>> the result <see cref="AbstractLazyInitializer.InvokeImplementation"/> >>> /// which indicates that the Proxy will need to forward to >>> the real implementation. >>> /// </returns> >>> - public virtual object Invoke(MethodBase method, object[] >>> args, object proxy) >>> + public virtual object Invoke(MethodInfo method, object[] >>> args, object proxy) >>> { >>> string methodName = method.Name; >>> int paramCount = method.GetParameters().Length; >>> @@ -73,7 +73,7 @@ >>> { >>> return >>> IdentityEqualityComparer.GetHashCode(proxy); >>> } >>> - else if (IsUninitialized && >>> method.Equals(getIdentifierMethod)) >>> + else if (IsUninitialized && >>> IsEqualToIdentifierMethod(method)) >>> { >>> return Identifier; >>> } >>> @@ -135,5 +135,18 @@ >>> return InvokeImplementation; >>> } >>> >>> + private bool IsEqualToIdentifierMethod(MethodInfo method) >>> + { >>> + if (getIdentifierMethod != null) >>> + { >>> + // in the case of inherited identifier >>> methods (from a base class or an iterface) the >>> + // passed in MethodBase object is not >>> equal to the getIdentifierMethod instance that we >>> + // have... but if their names and return >>> types are identical, then it is the correct >>> + // identifier method >>> + return >>> method.Name.Equals(getIdentifierMethod.Name) && >>> method.ReturnType.Equals(getIdentifierMethod.ReturnType); >>> + } >>> + >>> + return false; >>> + } >>> } >>> } >>> >>> Modified: trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs >>> =================================================================== >>> --- trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs >>> 2008-12-27 19:53:57 UTC (rev 3966) >>> +++ trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs >>> 2008-12-28 22:20:58 UTC (rev 3967) >>> @@ -19,7 +19,7 @@ >>> private static readonly ILog log = >>> LogManager.GetLogger(typeof(ReflectHelper)); >>> >>> public static BindingFlags AnyVisibilityInstance = >>> BindingFlags.Instance | BindingFlags.Public | >>> - >>> BindingFlags.NonPublic; >>> + >>> BindingFlags.NonPublic; >>> >>> private ReflectHelper() >>> { >>> @@ -29,7 +29,7 @@ >>> private static System.Type[] NoClasses = >>> System.Type.EmptyTypes; >>> >>> private static readonly MethodInfo >>> Exception_InternalPreserveStackTrace = >>> - typeof >>> (Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | >>> BindingFlags.NonPublic); >>> + >>> typeof(Exception).GetMethod("InternalPreserveStackTrace", >>> BindingFlags.Instance | BindingFlags.NonPublic); >>> >>> /// <summary> >>> /// Determine if the specified <see cref="System.Type"/> >>> overrides the >>> @@ -41,7 +41,7 @@ >>> { >>> try >>> { >>> - MethodInfo equals = >>> clazz.GetMethod("Equals", new System.Type[] {typeof(object)}); >>> + MethodInfo equals = >>> clazz.GetMethod("Equals", new System.Type[] { typeof(object) }); >>> if (equals == null) >>> { >>> return false; >>> @@ -127,7 +127,7 @@ >>> System.Type heuristicClass = propertyClass; >>> >>> if (propertyClass.IsGenericType >>> - && >>> propertyClass.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) >>> + && >>> propertyClass.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) >>> { >>> heuristicClass = >>> propertyClass.GetGenericArguments()[0]; >>> } >>> @@ -292,15 +292,15 @@ >>> >>> public static bool TryLoadAssembly(string assemblyName) >>> { >>> - if(string.IsNullOrEmpty(assemblyName)) >>> + if (string.IsNullOrEmpty(assemblyName)) >>> return false; >>> >>> - bool result= true; >>> + bool result = true; >>> try >>> { >>> Assembly.Load(assemblyName); >>> } >>> - catch(Exception) >>> + catch (Exception) >>> { >>> result = false; >>> } >>> @@ -446,7 +446,7 @@ >>> /// <returns>The unwrapped exception.</returns> >>> public static Exception >>> UnwrapTargetInvocationException(TargetInvocationException ex) >>> { >>> - >>> Exception_InternalPreserveStackTrace.Invoke(ex.InnerException, new Object[] >>> {}); >>> + >>> Exception_InternalPreserveStackTrace.Invoke(ex.InnerException, new Object[] >>> { }); >>> return ex.InnerException; >>> } >>> >>> @@ -472,14 +472,7 @@ >>> } >>> >>> System.Type[] tps = GetMethodSignature(method); >>> - try >>> - { >>> - return type.GetMethod(method.Name, >>> defaultBindingFlags, null, tps, null); >>> - } >>> - catch (Exception) >>> - { >>> - return null; >>> - } >>> + return SafeGetMethod(type, method, tps); >>> } >>> >>> /// <summary> >>> @@ -493,6 +486,8 @@ >>> /// </remarks> >>> public static MethodInfo >>> TryGetMethod(IEnumerable<System.Type> types, MethodInfo method) >>> { >>> + var bindingFlags = BindingFlags.Instance | >>> BindingFlags.Public | BindingFlags.NonPublic; >>> + >>> // This method will be used when we support >>> multiple proxy interfaces. >>> if (types == null) >>> { >>> @@ -505,21 +500,16 @@ >>> >>> System.Type[] tps = GetMethodSignature(method); >>> MethodInfo result = null; >>> + >>> foreach (var type in types) >>> { >>> - try >>> + result = SafeGetMethod(type, method, >>> tps); >>> + if (result != null) >>> { >>> - result = >>> type.GetMethod(method.Name, defaultBindingFlags, null, tps, null); >>> - if (result != null) >>> - { >>> - return result; >>> - } >>> + return result; >>> } >>> - catch (Exception) >>> - { >>> - return null; >>> - } >>> } >>> + >>> return result; >>> } >>> >>> @@ -533,5 +523,19 @@ >>> } >>> return tps; >>> } >>> + >>> + private static MethodInfo SafeGetMethod(System.Type type, >>> MethodInfo method, System.Type[] tps) >>> + { >>> + var bindingFlags = BindingFlags.Instance | >>> BindingFlags.Public | BindingFlags.NonPublic; >>> + >>> + try >>> + { >>> + return type.GetMethod(method.Name, >>> bindingFlags, null, tps, null); >>> + } >>> + catch (Exception) >>> + { >>> + return null; >>> + } >>> + } >>> } >>> } >>> >>> Added: >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs >>> =================================================================== >>> --- >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs >>> (rev 0) >>> +++ >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs >>> 2008-12-28 22:20:58 UTC (rev 3967) >>> @@ -0,0 +1,15 @@ >>> +using System; >>> + >>> +namespace NHibernate.Test.NHSpecificTest.NH1549 >>> +{ >>> + public class CategoryWithInheritedId : EntityInt32 >>> + { >>> + public virtual string Name { get; set; } >>> + } >>> + >>> + public class CategoryWithId >>> + { >>> + public virtual int Id { get; set; } >>> + public virtual string Name { get; set; } >>> + } >>> +} >>> \ No newline at end of file >>> >>> >>> Property changes on: >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs >>> ___________________________________________________________________ >>> Added: svn:mergeinfo >>> + >>> >>> Added: >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/EntityInt32.cs >>> =================================================================== >>> --- >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/EntityInt32.cs >>> (rev 0) >>> +++ >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/EntityInt32.cs >>> 2008-12-28 22:20:58 UTC (rev 3967) >>> @@ -0,0 +1,7 @@ >>> +namespace NHibernate.Test.NHSpecificTest.NH1549 >>> +{ >>> + public abstract class EntityInt32 >>> + { >>> + public virtual int Id { get; set; } >>> + } >>> +} >>> \ No newline at end of file >>> >>> Added: >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Fixture.cs >>> =================================================================== >>> --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Fixture.cs >>> (rev 0) >>> +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Fixture.cs >>> 2008-12-28 22:20:58 UTC (rev 3967) >>> @@ -0,0 +1,93 @@ >>> +using NUnit.Framework; >>> + >>> +namespace NHibernate.Test.NHSpecificTest.NH1549 >>> +{ >>> + [TestFixture] >>> + public class Fixture : BugTestCase >>> + { >>> + /// <summary> >>> + /// Verifies that an entity with a base class containing >>> the id property >>> + /// can have the id accessed without loading the entity >>> + /// </summary> >>> + [Test] >>> + public void CanLoadForEntitiesWithInheritedIds() >>> + { >>> + //create some related products >>> + var category = new CategoryWithInheritedId {Name >>> = "Fruit"}; >>> + var product = new ProductWithInheritedId >>> {CategoryWithInheritedId = category}; >>> + >>> + using (ISession session = OpenSession()) >>> + { >>> + using (ITransaction trans = >>> session.BeginTransaction()) >>> + { >>> + session.Save(category); >>> + session.Save(product); >>> + trans.Commit(); >>> + } >>> + } >>> + >>> + ProductWithInheritedId >>> restoredProductWithInheritedId; >>> + >>> + //restore the product from the db in another >>> session so that >>> + //the association is a proxy >>> + using (ISession session = OpenSession()) >>> + { >>> + restoredProductWithInheritedId = >>> session.Get<ProductWithInheritedId>(product.Id); >>> + } >>> + >>> + //verify that the category is a proxy >>> + >>> Assert.IsFalse(NHibernateUtil.IsInitialized(restoredProductWithInheritedId.CategoryWithInheritedId)); >>> + >>> + //we should be able to access the id of the >>> category outside of the session >>> + Assert.AreEqual(category.Id, >>> restoredProductWithInheritedId.CategoryWithInheritedId.Id); >>> + } >>> + >>> + [Test] >>> + public void CanLoadForEntitiesWithTheirOwnIds() >>> + { >>> + //create some related products >>> + var category = new CategoryWithId { Name = >>> "Fruit" }; >>> + var product = new ProductWithId { CategoryWithId >>> = category }; >>> + >>> + using (ISession session = OpenSession()) >>> + { >>> + using (ITransaction trans = >>> session.BeginTransaction()) >>> + { >>> + session.Save(category); >>> + session.Save(product); >>> + trans.Commit(); >>> + } >>> + } >>> + >>> + ProductWithId restoredProductWithInheritedId; >>> + >>> + //restore the product from the db in another >>> session so that >>> + //the association is a proxy >>> + using (ISession session = OpenSession()) >>> + { >>> + restoredProductWithInheritedId = >>> session.Get<ProductWithId>(product.Id); >>> + } >>> + >>> + //verify that the category is a proxy >>> + >>> Assert.IsFalse(NHibernateUtil.IsInitialized(restoredProductWithInheritedId.CategoryWithId)); >>> + >>> + //we should be able to access the id of the >>> category outside of the session >>> + Assert.AreEqual(category.Id, >>> restoredProductWithInheritedId.CategoryWithId.Id); >>> + } >>> + >>> + protected override void OnTearDown() >>> + { >>> + using (ISession session = OpenSession()) { >>> + >>> + using (ITransaction trans = >>> session.BeginTransaction()) >>> + { >>> + session.Delete("from >>> ProductWithId"); >>> + session.Delete("from >>> CategoryWithId"); >>> + session.Delete("from >>> ProductWithInheritedId"); >>> + session.Delete("from >>> CategoryWithInheritedId"); >>> + trans.Commit(); >>> + } >>> + } >>> + } >>> + } >>> +} >>> \ No newline at end of file >>> >>> Added: >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Mappings.hbm.xml >>> =================================================================== >>> --- >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Mappings.hbm.xml >>> (rev 0) >>> +++ >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Mappings.hbm.xml >>> 2008-12-28 22:20:58 UTC (rev 3967) >>> @@ -0,0 +1,35 @@ >>> +<?xml version="1.0" encoding="utf-8" ?> >>> +<hibernate-mapping >>> + xmlns="urn:nhibernate-mapping-2.2" >>> + namespace="NHibernate.Test.NHSpecificTest.NH1549" >>> + assembly="NHibernate.Test"> >>> + >>> + <class name="CategoryWithInheritedId"> >>> + <id name="Id" type="System.Int32"> >>> + <generator class="native" /> >>> + </id> >>> + <property name="Name" /> >>> + </class> >>> + >>> + <class name="ProductWithInheritedId" lazy="false"> >>> + <id name="Id" type="System.Int32"> >>> + <generator class="native" /> >>> + </id> >>> + <many-to-one name="CategoryWithInheritedId"/> >>> + </class> >>> + >>> + <class name="CategoryWithId"> >>> + <id name="Id" type="System.Int32"> >>> + <generator class="native" /> >>> + </id> >>> + <property name="Name" /> >>> + </class> >>> + >>> + <class name="ProductWithId" lazy="false"> >>> + <id name="Id" type="System.Int32"> >>> + <generator class="native" /> >>> + </id> >>> + <many-to-one name="CategoryWithId"/> >>> + </class> >>> + >>> +</hibernate-mapping> >>> >>> Added: >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs >>> =================================================================== >>> --- >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs >>> (rev 0) >>> +++ >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs >>> 2008-12-28 22:20:58 UTC (rev 3967) >>> @@ -0,0 +1,15 @@ >>> +using System; >>> + >>> +namespace NHibernate.Test.NHSpecificTest.NH1549 >>> +{ >>> + public class ProductWithInheritedId : EntityInt32 >>> + { >>> + public CategoryWithInheritedId CategoryWithInheritedId { >>> get; set; } >>> + } >>> + >>> + public class ProductWithId >>> + { >>> + public virtual int Id { get; set; } >>> + public CategoryWithId CategoryWithId { get; set; } >>> + } >>> +} >>> \ No newline at end of file >>> >>> >>> Property changes on: >>> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs >>> ___________________________________________________________________ >>> Added: svn:mergeinfo >>> + >>> >>> Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj >>> =================================================================== >>> --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj >>> 2008-12-27 19:53:57 UTC (rev 3966) >>> +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj >>> 2008-12-28 22:20:58 UTC (rev 3967) >>> @@ -378,6 +378,10 @@ >>> <Compile Include="NHSpecificTest\NH1274ExportExclude\Person.cs" /> >>> <Compile Include="NHSpecificTest\NH1443\Fixture.cs" /> >>> <Compile Include="NHSpecificTest\NH1521\Fixture.cs" /> >>> + <Compile Include="NHSpecificTest\NH1549\CategoryWithInheritedId.cs" >>> /> >>> + <Compile Include="NHSpecificTest\NH1549\EntityInt32.cs" /> >>> + <Compile Include="NHSpecificTest\NH1549\Fixture.cs" /> >>> + <Compile Include="NHSpecificTest\NH1549\ProductWithInheritedId.cs" >>> /> >>> <Compile Include="NHSpecificTest\NH1605\Fixture.cs" /> >>> <Compile Include="NHSpecificTest\NH1609\Entities.cs" /> >>> <Compile Include="NHSpecificTest\NH1609\Fixture.cs" /> >>> @@ -1577,6 +1581,7 @@ >>> <EmbeddedResource Include="Cascade\JobBatch.hbm.xml" /> >>> <EmbeddedResource Include="Deletetransient\Person.hbm.xml" /> >>> <Content Include="DynamicEntity\package.html" /> >>> + <EmbeddedResource Include="NHSpecificTest\NH1549\Mappings.hbm.xml" >>> /> >>> <EmbeddedResource >>> Include="NHSpecificTest\NH1521\AclassWithSpecific.hbm.xml" /> >>> <EmbeddedResource >>> Include="NHSpecificTest\NH1521\AclassWithNothing.hbm.xml" /> >>> <EmbeddedResource >>> Include="NHSpecificTest\NH1521\AclassWithDefault.hbm.xml" /> >>> >>> Modified: >>> trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs >>> =================================================================== >>> --- >>> trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs >>> 2008-12-27 19:53:57 UTC (rev 3966) >>> +++ >>> trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs >>> 2008-12-28 22:20:58 UTC (rev 3967) >>> @@ -56,11 +56,13 @@ >>> [Test] >>> public void TryGetMethod() >>> { >>> - const BindingFlags bf = BindingFlags.Instance | >>> BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; >>> - MethodInfo mig = typeof >>> (MyBaseImplementation).GetMethod("get_Id", bf); >>> + //const BindingFlags bf = BindingFlags.Instance | >>> BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; >>> + const BindingFlags bf = BindingFlags.Instance | >>> BindingFlags.Public | BindingFlags.NonPublic; >>> + MethodInfo mig = >>> typeof(MyBaseImplementation).GetMethod("get_Id", bf); >>> MethodInfo mis = >>> typeof(MyBaseImplementation).GetMethod("set_Id", bf); >>> MethodInfo mng = >>> typeof(MyBaseImplementation).GetMethod("get_Name", bf); >>> MethodInfo mns = >>> typeof(MyBaseImplementation).GetMethod("set_Name", bf); >>> + >>> >>> Assert.That(ReflectHelper.TryGetMethod(typeof(IMyBaseInterface), mig), >>> Is.Not.Null); >>> >>> Assert.That(ReflectHelper.TryGetMethod(typeof(IMyBaseInterface), mis), >>> Is.Null); >>> >>> Assert.That(ReflectHelper.TryGetMethod(typeof(IMyBaseInterface), mng), >>> Is.Not.Null); >>> @@ -78,6 +80,20 @@ >>> Assert.That(ReflectHelper.TryGetMethod(new[] { >>> typeof(IMyBaseInterface), typeof(IMyInterface) }, mns), Is.Not.Null); >>> Assert.That(ReflectHelper.TryGetMethod(new[] { >>> typeof(IMyBaseInterface), typeof(IMyInterface) }, mdg), Is.Not.Null); >>> Assert.That(ReflectHelper.TryGetMethod(new[] { >>> typeof(IMyBaseInterface), typeof(IMyInterface) }, mds), Is.Null); >>> + >>> + MethodInfo mdig = >>> typeof(MyDerivedImplementation).GetMethod("get_Id", bf); >>> + MethodInfo mdis = >>> typeof(MyDerivedImplementation).GetMethod("set_Id", bf); >>> + MethodInfo mdng = >>> typeof(MyDerivedImplementation).GetMethod("get_Name", bf); >>> + MethodInfo mdns = >>> typeof(MyDerivedImplementation).GetMethod("set_Name", bf); >>> + MethodInfo mddg = >>> typeof(MyDerivedImplementation).GetMethod("get_Description", bf); >>> + MethodInfo mdds = >>> typeof(MyDerivedImplementation).GetMethod("set_Description", bf); >>> + >>> + Assert.That(ReflectHelper.TryGetMethod(new[] { >>> typeof(IMyBaseInterface), typeof(IMyInterface) }, mdig), Is.Not.Null); >>> + Assert.That(ReflectHelper.TryGetMethod(new[] { >>> typeof(IMyBaseInterface), typeof(IMyInterface) }, mdis), Is.Null); >>> + Assert.That(ReflectHelper.TryGetMethod(new[] { >>> typeof(IMyBaseInterface), typeof(IMyInterface) }, mdng), Is.Not.Null); >>> + Assert.That(ReflectHelper.TryGetMethod(new[] { >>> typeof(IMyBaseInterface), typeof(IMyInterface) }, mdns), Is.Not.Null); >>> + Assert.That(ReflectHelper.TryGetMethod(new[] { >>> typeof(IMyBaseInterface), typeof(IMyInterface) }, mddg), Is.Not.Null); >>> + Assert.That(ReflectHelper.TryGetMethod(new[] { >>> typeof(IMyBaseInterface), typeof(IMyInterface) }, mdds), Is.Null); >>> } >>> } >>> >>> @@ -115,11 +131,15 @@ >>> public string Name { get; set; } >>> } >>> >>> + public class MyDerivedImplementation : MyBaseImplementation, >>> IMyInterface >>> + { >>> + public string Description { get; set; } >>> + } >>> + >>> public class MyImplementation: IMyInterface >>> { >>> public int Id{ get; set; } >>> public string Name { get; set; } >>> public string Description { get; set; } >>> } >>> - >>> } >>> \ No newline at end of file >>> >>> >>> This was sent by the SourceForge.net collaborative development platform, >>> the world's largest Open Source development site. >>> >>> >>> ------------------------------------------------------------------------------ >>> _______________________________________________ >>> Nhibernate-commit mailing list >>> Nhi...@li... >>> https://lists.sourceforge.net/lists/listinfo/nhibernate-commit >>> >> >> >> >> ------------------------------------------------------------------------------ >> >> _______________________________________________ >> Nhibernate-commit mailing list >> Nhi...@li... >> https://lists.sourceforge.net/lists/listinfo/nhibernate-commit >> >> > > > -- > Davy Brion > http://davybrion.com > > > ------------------------------------------------------------------------------ > > _______________________________________________ > Nhibernate-commit mailing list > Nhi...@li... > https://lists.sourceforge.net/lists/listinfo/nhibernate-commit > > |
From: Davy B. <ra...@da...> - 2008-12-28 22:33:43
|
yeah sorry, forgot to add the commit message.... this commit fixed NH-1549 and NH-1590 On Sun, Dec 28, 2008 at 11:23 PM, Tuna Toksöz <te...@gm...> wrote: > Commit log? > > > Tuna Toksöz > http://tunatoksoz.com > > Typos included to enhance the readers attention! > > > > > On Mon, Dec 29, 2008 at 12:20 AM, <dav...@us...> wrote: > >> Revision: 3967 >> >> http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3967&view=rev >> Author: davybrion >> Date: 2008-12-28 22:20:58 +0000 (Sun, 28 Dec 2008) >> >> Log Message: >> ----------- >> >> >> Modified Paths: >> -------------- >> trunk/nhibernate/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs >> trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs >> trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj >> >> trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs >> >> Added Paths: >> ----------- >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ >> >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs >> >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/EntityInt32.cs >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Fixture.cs >> >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Mappings.hbm.xml >> >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs >> >> Modified: >> trunk/nhibernate/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs >> =================================================================== >> --- trunk/nhibernate/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs >> 2008-12-27 19:53:57 UTC (rev 3966) >> +++ trunk/nhibernate/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs >> 2008-12-28 22:20:58 UTC (rev 3967) >> @@ -62,7 +62,7 @@ >> /// underlying proxied object is needed then it returns the >> result <see cref="AbstractLazyInitializer.InvokeImplementation"/> >> /// which indicates that the Proxy will need to forward to >> the real implementation. >> /// </returns> >> - public virtual object Invoke(MethodBase method, object[] >> args, object proxy) >> + public virtual object Invoke(MethodInfo method, object[] >> args, object proxy) >> { >> string methodName = method.Name; >> int paramCount = method.GetParameters().Length; >> @@ -73,7 +73,7 @@ >> { >> return >> IdentityEqualityComparer.GetHashCode(proxy); >> } >> - else if (IsUninitialized && >> method.Equals(getIdentifierMethod)) >> + else if (IsUninitialized && >> IsEqualToIdentifierMethod(method)) >> { >> return Identifier; >> } >> @@ -135,5 +135,18 @@ >> return InvokeImplementation; >> } >> >> + private bool IsEqualToIdentifierMethod(MethodInfo method) >> + { >> + if (getIdentifierMethod != null) >> + { >> + // in the case of inherited identifier >> methods (from a base class or an iterface) the >> + // passed in MethodBase object is not >> equal to the getIdentifierMethod instance that we >> + // have... but if their names and return >> types are identical, then it is the correct >> + // identifier method >> + return >> method.Name.Equals(getIdentifierMethod.Name) && >> method.ReturnType.Equals(getIdentifierMethod.ReturnType); >> + } >> + >> + return false; >> + } >> } >> } >> >> Modified: trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs >> =================================================================== >> --- trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs 2008-12-27 >> 19:53:57 UTC (rev 3966) >> +++ trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs 2008-12-28 >> 22:20:58 UTC (rev 3967) >> @@ -19,7 +19,7 @@ >> private static readonly ILog log = >> LogManager.GetLogger(typeof(ReflectHelper)); >> >> public static BindingFlags AnyVisibilityInstance = >> BindingFlags.Instance | BindingFlags.Public | >> - >> BindingFlags.NonPublic; >> + >> BindingFlags.NonPublic; >> >> private ReflectHelper() >> { >> @@ -29,7 +29,7 @@ >> private static System.Type[] NoClasses = >> System.Type.EmptyTypes; >> >> private static readonly MethodInfo >> Exception_InternalPreserveStackTrace = >> - typeof >> (Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | >> BindingFlags.NonPublic); >> + >> typeof(Exception).GetMethod("InternalPreserveStackTrace", >> BindingFlags.Instance | BindingFlags.NonPublic); >> >> /// <summary> >> /// Determine if the specified <see cref="System.Type"/> >> overrides the >> @@ -41,7 +41,7 @@ >> { >> try >> { >> - MethodInfo equals = >> clazz.GetMethod("Equals", new System.Type[] {typeof(object)}); >> + MethodInfo equals = >> clazz.GetMethod("Equals", new System.Type[] { typeof(object) }); >> if (equals == null) >> { >> return false; >> @@ -127,7 +127,7 @@ >> System.Type heuristicClass = propertyClass; >> >> if (propertyClass.IsGenericType >> - && >> propertyClass.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) >> + && >> propertyClass.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) >> { >> heuristicClass = >> propertyClass.GetGenericArguments()[0]; >> } >> @@ -292,15 +292,15 @@ >> >> public static bool TryLoadAssembly(string assemblyName) >> { >> - if(string.IsNullOrEmpty(assemblyName)) >> + if (string.IsNullOrEmpty(assemblyName)) >> return false; >> >> - bool result= true; >> + bool result = true; >> try >> { >> Assembly.Load(assemblyName); >> } >> - catch(Exception) >> + catch (Exception) >> { >> result = false; >> } >> @@ -446,7 +446,7 @@ >> /// <returns>The unwrapped exception.</returns> >> public static Exception >> UnwrapTargetInvocationException(TargetInvocationException ex) >> { >> - >> Exception_InternalPreserveStackTrace.Invoke(ex.InnerException, new Object[] >> {}); >> + >> Exception_InternalPreserveStackTrace.Invoke(ex.InnerException, new Object[] >> { }); >> return ex.InnerException; >> } >> >> @@ -472,14 +472,7 @@ >> } >> >> System.Type[] tps = GetMethodSignature(method); >> - try >> - { >> - return type.GetMethod(method.Name, >> defaultBindingFlags, null, tps, null); >> - } >> - catch (Exception) >> - { >> - return null; >> - } >> + return SafeGetMethod(type, method, tps); >> } >> >> /// <summary> >> @@ -493,6 +486,8 @@ >> /// </remarks> >> public static MethodInfo >> TryGetMethod(IEnumerable<System.Type> types, MethodInfo method) >> { >> + var bindingFlags = BindingFlags.Instance | >> BindingFlags.Public | BindingFlags.NonPublic; >> + >> // This method will be used when we support >> multiple proxy interfaces. >> if (types == null) >> { >> @@ -505,21 +500,16 @@ >> >> System.Type[] tps = GetMethodSignature(method); >> MethodInfo result = null; >> + >> foreach (var type in types) >> { >> - try >> + result = SafeGetMethod(type, method, tps); >> + if (result != null) >> { >> - result = >> type.GetMethod(method.Name, defaultBindingFlags, null, tps, null); >> - if (result != null) >> - { >> - return result; >> - } >> + return result; >> } >> - catch (Exception) >> - { >> - return null; >> - } >> } >> + >> return result; >> } >> >> @@ -533,5 +523,19 @@ >> } >> return tps; >> } >> + >> + private static MethodInfo SafeGetMethod(System.Type type, >> MethodInfo method, System.Type[] tps) >> + { >> + var bindingFlags = BindingFlags.Instance | >> BindingFlags.Public | BindingFlags.NonPublic; >> + >> + try >> + { >> + return type.GetMethod(method.Name, >> bindingFlags, null, tps, null); >> + } >> + catch (Exception) >> + { >> + return null; >> + } >> + } >> } >> } >> >> Added: >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs >> =================================================================== >> --- >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs >> (rev 0) >> +++ >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs >> 2008-12-28 22:20:58 UTC (rev 3967) >> @@ -0,0 +1,15 @@ >> +using System; >> + >> +namespace NHibernate.Test.NHSpecificTest.NH1549 >> +{ >> + public class CategoryWithInheritedId : EntityInt32 >> + { >> + public virtual string Name { get; set; } >> + } >> + >> + public class CategoryWithId >> + { >> + public virtual int Id { get; set; } >> + public virtual string Name { get; set; } >> + } >> +} >> \ No newline at end of file >> >> >> Property changes on: >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs >> ___________________________________________________________________ >> Added: svn:mergeinfo >> + >> >> Added: >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/EntityInt32.cs >> =================================================================== >> --- >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/EntityInt32.cs >> (rev 0) >> +++ >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/EntityInt32.cs >> 2008-12-28 22:20:58 UTC (rev 3967) >> @@ -0,0 +1,7 @@ >> +namespace NHibernate.Test.NHSpecificTest.NH1549 >> +{ >> + public abstract class EntityInt32 >> + { >> + public virtual int Id { get; set; } >> + } >> +} >> \ No newline at end of file >> >> Added: >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Fixture.cs >> =================================================================== >> --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Fixture.cs >> (rev 0) >> +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Fixture.cs >> 2008-12-28 22:20:58 UTC (rev 3967) >> @@ -0,0 +1,93 @@ >> +using NUnit.Framework; >> + >> +namespace NHibernate.Test.NHSpecificTest.NH1549 >> +{ >> + [TestFixture] >> + public class Fixture : BugTestCase >> + { >> + /// <summary> >> + /// Verifies that an entity with a base class containing >> the id property >> + /// can have the id accessed without loading the entity >> + /// </summary> >> + [Test] >> + public void CanLoadForEntitiesWithInheritedIds() >> + { >> + //create some related products >> + var category = new CategoryWithInheritedId {Name = >> "Fruit"}; >> + var product = new ProductWithInheritedId >> {CategoryWithInheritedId = category}; >> + >> + using (ISession session = OpenSession()) >> + { >> + using (ITransaction trans = >> session.BeginTransaction()) >> + { >> + session.Save(category); >> + session.Save(product); >> + trans.Commit(); >> + } >> + } >> + >> + ProductWithInheritedId >> restoredProductWithInheritedId; >> + >> + //restore the product from the db in another >> session so that >> + //the association is a proxy >> + using (ISession session = OpenSession()) >> + { >> + restoredProductWithInheritedId = >> session.Get<ProductWithInheritedId>(product.Id); >> + } >> + >> + //verify that the category is a proxy >> + >> Assert.IsFalse(NHibernateUtil.IsInitialized(restoredProductWithInheritedId.CategoryWithInheritedId)); >> + >> + //we should be able to access the id of the >> category outside of the session >> + Assert.AreEqual(category.Id, >> restoredProductWithInheritedId.CategoryWithInheritedId.Id); >> + } >> + >> + [Test] >> + public void CanLoadForEntitiesWithTheirOwnIds() >> + { >> + //create some related products >> + var category = new CategoryWithId { Name = "Fruit" >> }; >> + var product = new ProductWithId { CategoryWithId = >> category }; >> + >> + using (ISession session = OpenSession()) >> + { >> + using (ITransaction trans = >> session.BeginTransaction()) >> + { >> + session.Save(category); >> + session.Save(product); >> + trans.Commit(); >> + } >> + } >> + >> + ProductWithId restoredProductWithInheritedId; >> + >> + //restore the product from the db in another >> session so that >> + //the association is a proxy >> + using (ISession session = OpenSession()) >> + { >> + restoredProductWithInheritedId = >> session.Get<ProductWithId>(product.Id); >> + } >> + >> + //verify that the category is a proxy >> + >> Assert.IsFalse(NHibernateUtil.IsInitialized(restoredProductWithInheritedId.CategoryWithId)); >> + >> + //we should be able to access the id of the >> category outside of the session >> + Assert.AreEqual(category.Id, >> restoredProductWithInheritedId.CategoryWithId.Id); >> + } >> + >> + protected override void OnTearDown() >> + { >> + using (ISession session = OpenSession()) { >> + >> + using (ITransaction trans = >> session.BeginTransaction()) >> + { >> + session.Delete("from >> ProductWithId"); >> + session.Delete("from >> CategoryWithId"); >> + session.Delete("from >> ProductWithInheritedId"); >> + session.Delete("from >> CategoryWithInheritedId"); >> + trans.Commit(); >> + } >> + } >> + } >> + } >> +} >> \ No newline at end of file >> >> Added: >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Mappings.hbm.xml >> =================================================================== >> --- >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Mappings.hbm.xml >> (rev 0) >> +++ >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Mappings.hbm.xml >> 2008-12-28 22:20:58 UTC (rev 3967) >> @@ -0,0 +1,35 @@ >> +<?xml version="1.0" encoding="utf-8" ?> >> +<hibernate-mapping >> + xmlns="urn:nhibernate-mapping-2.2" >> + namespace="NHibernate.Test.NHSpecificTest.NH1549" >> + assembly="NHibernate.Test"> >> + >> + <class name="CategoryWithInheritedId"> >> + <id name="Id" type="System.Int32"> >> + <generator class="native" /> >> + </id> >> + <property name="Name" /> >> + </class> >> + >> + <class name="ProductWithInheritedId" lazy="false"> >> + <id name="Id" type="System.Int32"> >> + <generator class="native" /> >> + </id> >> + <many-to-one name="CategoryWithInheritedId"/> >> + </class> >> + >> + <class name="CategoryWithId"> >> + <id name="Id" type="System.Int32"> >> + <generator class="native" /> >> + </id> >> + <property name="Name" /> >> + </class> >> + >> + <class name="ProductWithId" lazy="false"> >> + <id name="Id" type="System.Int32"> >> + <generator class="native" /> >> + </id> >> + <many-to-one name="CategoryWithId"/> >> + </class> >> + >> +</hibernate-mapping> >> >> Added: >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs >> =================================================================== >> --- >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs >> (rev 0) >> +++ >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs >> 2008-12-28 22:20:58 UTC (rev 3967) >> @@ -0,0 +1,15 @@ >> +using System; >> + >> +namespace NHibernate.Test.NHSpecificTest.NH1549 >> +{ >> + public class ProductWithInheritedId : EntityInt32 >> + { >> + public CategoryWithInheritedId CategoryWithInheritedId { >> get; set; } >> + } >> + >> + public class ProductWithId >> + { >> + public virtual int Id { get; set; } >> + public CategoryWithId CategoryWithId { get; set; } >> + } >> +} >> \ No newline at end of file >> >> >> Property changes on: >> trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs >> ___________________________________________________________________ >> Added: svn:mergeinfo >> + >> >> Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj >> =================================================================== >> --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-12-27 >> 19:53:57 UTC (rev 3966) >> +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-12-28 >> 22:20:58 UTC (rev 3967) >> @@ -378,6 +378,10 @@ >> <Compile Include="NHSpecificTest\NH1274ExportExclude\Person.cs" /> >> <Compile Include="NHSpecificTest\NH1443\Fixture.cs" /> >> <Compile Include="NHSpecificTest\NH1521\Fixture.cs" /> >> + <Compile Include="NHSpecificTest\NH1549\CategoryWithInheritedId.cs" >> /> >> + <Compile Include="NHSpecificTest\NH1549\EntityInt32.cs" /> >> + <Compile Include="NHSpecificTest\NH1549\Fixture.cs" /> >> + <Compile Include="NHSpecificTest\NH1549\ProductWithInheritedId.cs" /> >> <Compile Include="NHSpecificTest\NH1605\Fixture.cs" /> >> <Compile Include="NHSpecificTest\NH1609\Entities.cs" /> >> <Compile Include="NHSpecificTest\NH1609\Fixture.cs" /> >> @@ -1577,6 +1581,7 @@ >> <EmbeddedResource Include="Cascade\JobBatch.hbm.xml" /> >> <EmbeddedResource Include="Deletetransient\Person.hbm.xml" /> >> <Content Include="DynamicEntity\package.html" /> >> + <EmbeddedResource Include="NHSpecificTest\NH1549\Mappings.hbm.xml" /> >> <EmbeddedResource >> Include="NHSpecificTest\NH1521\AclassWithSpecific.hbm.xml" /> >> <EmbeddedResource >> Include="NHSpecificTest\NH1521\AclassWithNothing.hbm.xml" /> >> <EmbeddedResource >> Include="NHSpecificTest\NH1521\AclassWithDefault.hbm.xml" /> >> >> Modified: >> trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs >> =================================================================== >> --- >> trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs >> 2008-12-27 19:53:57 UTC (rev 3966) >> +++ >> trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs >> 2008-12-28 22:20:58 UTC (rev 3967) >> @@ -56,11 +56,13 @@ >> [Test] >> public void TryGetMethod() >> { >> - const BindingFlags bf = BindingFlags.Instance | >> BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; >> - MethodInfo mig = typeof >> (MyBaseImplementation).GetMethod("get_Id", bf); >> + //const BindingFlags bf = BindingFlags.Instance | >> BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; >> + const BindingFlags bf = BindingFlags.Instance | >> BindingFlags.Public | BindingFlags.NonPublic; >> + MethodInfo mig = >> typeof(MyBaseImplementation).GetMethod("get_Id", bf); >> MethodInfo mis = >> typeof(MyBaseImplementation).GetMethod("set_Id", bf); >> MethodInfo mng = >> typeof(MyBaseImplementation).GetMethod("get_Name", bf); >> MethodInfo mns = >> typeof(MyBaseImplementation).GetMethod("set_Name", bf); >> + >> >> Assert.That(ReflectHelper.TryGetMethod(typeof(IMyBaseInterface), mig), >> Is.Not.Null); >> >> Assert.That(ReflectHelper.TryGetMethod(typeof(IMyBaseInterface), mis), >> Is.Null); >> >> Assert.That(ReflectHelper.TryGetMethod(typeof(IMyBaseInterface), mng), >> Is.Not.Null); >> @@ -78,6 +80,20 @@ >> Assert.That(ReflectHelper.TryGetMethod(new[] { >> typeof(IMyBaseInterface), typeof(IMyInterface) }, mns), Is.Not.Null); >> Assert.That(ReflectHelper.TryGetMethod(new[] { >> typeof(IMyBaseInterface), typeof(IMyInterface) }, mdg), Is.Not.Null); >> Assert.That(ReflectHelper.TryGetMethod(new[] { >> typeof(IMyBaseInterface), typeof(IMyInterface) }, mds), Is.Null); >> + >> + MethodInfo mdig = >> typeof(MyDerivedImplementation).GetMethod("get_Id", bf); >> + MethodInfo mdis = >> typeof(MyDerivedImplementation).GetMethod("set_Id", bf); >> + MethodInfo mdng = >> typeof(MyDerivedImplementation).GetMethod("get_Name", bf); >> + MethodInfo mdns = >> typeof(MyDerivedImplementation).GetMethod("set_Name", bf); >> + MethodInfo mddg = >> typeof(MyDerivedImplementation).GetMethod("get_Description", bf); >> + MethodInfo mdds = >> typeof(MyDerivedImplementation).GetMethod("set_Description", bf); >> + >> + Assert.That(ReflectHelper.TryGetMethod(new[] { >> typeof(IMyBaseInterface), typeof(IMyInterface) }, mdig), Is.Not.Null); >> + Assert.That(ReflectHelper.TryGetMethod(new[] { >> typeof(IMyBaseInterface), typeof(IMyInterface) }, mdis), Is.Null); >> + Assert.That(ReflectHelper.TryGetMethod(new[] { >> typeof(IMyBaseInterface), typeof(IMyInterface) }, mdng), Is.Not.Null); >> + Assert.That(ReflectHelper.TryGetMethod(new[] { >> typeof(IMyBaseInterface), typeof(IMyInterface) }, mdns), Is.Not.Null); >> + Assert.That(ReflectHelper.TryGetMethod(new[] { >> typeof(IMyBaseInterface), typeof(IMyInterface) }, mddg), Is.Not.Null); >> + Assert.That(ReflectHelper.TryGetMethod(new[] { >> typeof(IMyBaseInterface), typeof(IMyInterface) }, mdds), Is.Null); >> } >> } >> >> @@ -115,11 +131,15 @@ >> public string Name { get; set; } >> } >> >> + public class MyDerivedImplementation : MyBaseImplementation, >> IMyInterface >> + { >> + public string Description { get; set; } >> + } >> + >> public class MyImplementation: IMyInterface >> { >> public int Id{ get; set; } >> public string Name { get; set; } >> public string Description { get; set; } >> } >> - >> } >> \ No newline at end of file >> >> >> This was sent by the SourceForge.net collaborative development platform, >> the world's largest Open Source development site. >> >> >> ------------------------------------------------------------------------------ >> _______________________________________________ >> Nhibernate-commit mailing list >> Nhi...@li... >> https://lists.sourceforge.net/lists/listinfo/nhibernate-commit >> > > > > ------------------------------------------------------------------------------ > > _______________________________________________ > Nhibernate-commit mailing list > Nhi...@li... > https://lists.sourceforge.net/lists/listinfo/nhibernate-commit > > -- Davy Brion http://davybrion.com |
From: T. T. <te...@gm...> - 2008-12-28 22:23:28
|
Commit log? Tuna Toksöz http://tunatoksoz.com Typos included to enhance the readers attention! On Mon, Dec 29, 2008 at 12:20 AM, <dav...@us...> wrote: > Revision: 3967 > > http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3967&view=rev > Author: davybrion > Date: 2008-12-28 22:20:58 +0000 (Sun, 28 Dec 2008) > > Log Message: > ----------- > > > Modified Paths: > -------------- > trunk/nhibernate/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs > trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs > trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj > trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs > > Added Paths: > ----------- > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ > > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs > > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/EntityInt32.cs > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Fixture.cs > > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Mappings.hbm.xml > > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs > > Modified: > trunk/nhibernate/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs > =================================================================== > --- trunk/nhibernate/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs > 2008-12-27 19:53:57 UTC (rev 3966) > +++ trunk/nhibernate/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs > 2008-12-28 22:20:58 UTC (rev 3967) > @@ -62,7 +62,7 @@ > /// underlying proxied object is needed then it returns the > result <see cref="AbstractLazyInitializer.InvokeImplementation"/> > /// which indicates that the Proxy will need to forward to > the real implementation. > /// </returns> > - public virtual object Invoke(MethodBase method, object[] > args, object proxy) > + public virtual object Invoke(MethodInfo method, object[] > args, object proxy) > { > string methodName = method.Name; > int paramCount = method.GetParameters().Length; > @@ -73,7 +73,7 @@ > { > return > IdentityEqualityComparer.GetHashCode(proxy); > } > - else if (IsUninitialized && > method.Equals(getIdentifierMethod)) > + else if (IsUninitialized && > IsEqualToIdentifierMethod(method)) > { > return Identifier; > } > @@ -135,5 +135,18 @@ > return InvokeImplementation; > } > > + private bool IsEqualToIdentifierMethod(MethodInfo method) > + { > + if (getIdentifierMethod != null) > + { > + // in the case of inherited identifier > methods (from a base class or an iterface) the > + // passed in MethodBase object is not equal > to the getIdentifierMethod instance that we > + // have... but if their names and return > types are identical, then it is the correct > + // identifier method > + return > method.Name.Equals(getIdentifierMethod.Name) && > method.ReturnType.Equals(getIdentifierMethod.ReturnType); > + } > + > + return false; > + } > } > } > > Modified: trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs > =================================================================== > --- trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs 2008-12-27 > 19:53:57 UTC (rev 3966) > +++ trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs 2008-12-28 > 22:20:58 UTC (rev 3967) > @@ -19,7 +19,7 @@ > private static readonly ILog log = > LogManager.GetLogger(typeof(ReflectHelper)); > > public static BindingFlags AnyVisibilityInstance = > BindingFlags.Instance | BindingFlags.Public | > - > BindingFlags.NonPublic; > + > BindingFlags.NonPublic; > > private ReflectHelper() > { > @@ -29,7 +29,7 @@ > private static System.Type[] NoClasses = > System.Type.EmptyTypes; > > private static readonly MethodInfo > Exception_InternalPreserveStackTrace = > - typeof > (Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | > BindingFlags.NonPublic); > + > typeof(Exception).GetMethod("InternalPreserveStackTrace", > BindingFlags.Instance | BindingFlags.NonPublic); > > /// <summary> > /// Determine if the specified <see cref="System.Type"/> > overrides the > @@ -41,7 +41,7 @@ > { > try > { > - MethodInfo equals = > clazz.GetMethod("Equals", new System.Type[] {typeof(object)}); > + MethodInfo equals = > clazz.GetMethod("Equals", new System.Type[] { typeof(object) }); > if (equals == null) > { > return false; > @@ -127,7 +127,7 @@ > System.Type heuristicClass = propertyClass; > > if (propertyClass.IsGenericType > - && > propertyClass.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) > + && > propertyClass.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) > { > heuristicClass = > propertyClass.GetGenericArguments()[0]; > } > @@ -292,15 +292,15 @@ > > public static bool TryLoadAssembly(string assemblyName) > { > - if(string.IsNullOrEmpty(assemblyName)) > + if (string.IsNullOrEmpty(assemblyName)) > return false; > > - bool result= true; > + bool result = true; > try > { > Assembly.Load(assemblyName); > } > - catch(Exception) > + catch (Exception) > { > result = false; > } > @@ -446,7 +446,7 @@ > /// <returns>The unwrapped exception.</returns> > public static Exception > UnwrapTargetInvocationException(TargetInvocationException ex) > { > - > Exception_InternalPreserveStackTrace.Invoke(ex.InnerException, new Object[] > {}); > + > Exception_InternalPreserveStackTrace.Invoke(ex.InnerException, new Object[] > { }); > return ex.InnerException; > } > > @@ -472,14 +472,7 @@ > } > > System.Type[] tps = GetMethodSignature(method); > - try > - { > - return type.GetMethod(method.Name, > defaultBindingFlags, null, tps, null); > - } > - catch (Exception) > - { > - return null; > - } > + return SafeGetMethod(type, method, tps); > } > > /// <summary> > @@ -493,6 +486,8 @@ > /// </remarks> > public static MethodInfo > TryGetMethod(IEnumerable<System.Type> types, MethodInfo method) > { > + var bindingFlags = BindingFlags.Instance | > BindingFlags.Public | BindingFlags.NonPublic; > + > // This method will be used when we support multiple > proxy interfaces. > if (types == null) > { > @@ -505,21 +500,16 @@ > > System.Type[] tps = GetMethodSignature(method); > MethodInfo result = null; > + > foreach (var type in types) > { > - try > + result = SafeGetMethod(type, method, tps); > + if (result != null) > { > - result = > type.GetMethod(method.Name, defaultBindingFlags, null, tps, null); > - if (result != null) > - { > - return result; > - } > + return result; > } > - catch (Exception) > - { > - return null; > - } > } > + > return result; > } > > @@ -533,5 +523,19 @@ > } > return tps; > } > + > + private static MethodInfo SafeGetMethod(System.Type type, > MethodInfo method, System.Type[] tps) > + { > + var bindingFlags = BindingFlags.Instance | > BindingFlags.Public | BindingFlags.NonPublic; > + > + try > + { > + return type.GetMethod(method.Name, > bindingFlags, null, tps, null); > + } > + catch (Exception) > + { > + return null; > + } > + } > } > } > > Added: > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs > =================================================================== > --- > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs > (rev 0) > +++ > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs > 2008-12-28 22:20:58 UTC (rev 3967) > @@ -0,0 +1,15 @@ > +using System; > + > +namespace NHibernate.Test.NHSpecificTest.NH1549 > +{ > + public class CategoryWithInheritedId : EntityInt32 > + { > + public virtual string Name { get; set; } > + } > + > + public class CategoryWithId > + { > + public virtual int Id { get; set; } > + public virtual string Name { get; set; } > + } > +} > \ No newline at end of file > > > Property changes on: > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs > ___________________________________________________________________ > Added: svn:mergeinfo > + > > Added: > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/EntityInt32.cs > =================================================================== > --- > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/EntityInt32.cs > (rev 0) > +++ > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/EntityInt32.cs > 2008-12-28 22:20:58 UTC (rev 3967) > @@ -0,0 +1,7 @@ > +namespace NHibernate.Test.NHSpecificTest.NH1549 > +{ > + public abstract class EntityInt32 > + { > + public virtual int Id { get; set; } > + } > +} > \ No newline at end of file > > Added: > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Fixture.cs > =================================================================== > --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Fixture.cs > (rev 0) > +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Fixture.cs > 2008-12-28 22:20:58 UTC (rev 3967) > @@ -0,0 +1,93 @@ > +using NUnit.Framework; > + > +namespace NHibernate.Test.NHSpecificTest.NH1549 > +{ > + [TestFixture] > + public class Fixture : BugTestCase > + { > + /// <summary> > + /// Verifies that an entity with a base class containing > the id property > + /// can have the id accessed without loading the entity > + /// </summary> > + [Test] > + public void CanLoadForEntitiesWithInheritedIds() > + { > + //create some related products > + var category = new CategoryWithInheritedId {Name = > "Fruit"}; > + var product = new ProductWithInheritedId > {CategoryWithInheritedId = category}; > + > + using (ISession session = OpenSession()) > + { > + using (ITransaction trans = > session.BeginTransaction()) > + { > + session.Save(category); > + session.Save(product); > + trans.Commit(); > + } > + } > + > + ProductWithInheritedId > restoredProductWithInheritedId; > + > + //restore the product from the db in another > session so that > + //the association is a proxy > + using (ISession session = OpenSession()) > + { > + restoredProductWithInheritedId = > session.Get<ProductWithInheritedId>(product.Id); > + } > + > + //verify that the category is a proxy > + > Assert.IsFalse(NHibernateUtil.IsInitialized(restoredProductWithInheritedId.CategoryWithInheritedId)); > + > + //we should be able to access the id of the > category outside of the session > + Assert.AreEqual(category.Id, > restoredProductWithInheritedId.CategoryWithInheritedId.Id); > + } > + > + [Test] > + public void CanLoadForEntitiesWithTheirOwnIds() > + { > + //create some related products > + var category = new CategoryWithId { Name = "Fruit" > }; > + var product = new ProductWithId { CategoryWithId = > category }; > + > + using (ISession session = OpenSession()) > + { > + using (ITransaction trans = > session.BeginTransaction()) > + { > + session.Save(category); > + session.Save(product); > + trans.Commit(); > + } > + } > + > + ProductWithId restoredProductWithInheritedId; > + > + //restore the product from the db in another > session so that > + //the association is a proxy > + using (ISession session = OpenSession()) > + { > + restoredProductWithInheritedId = > session.Get<ProductWithId>(product.Id); > + } > + > + //verify that the category is a proxy > + > Assert.IsFalse(NHibernateUtil.IsInitialized(restoredProductWithInheritedId.CategoryWithId)); > + > + //we should be able to access the id of the > category outside of the session > + Assert.AreEqual(category.Id, > restoredProductWithInheritedId.CategoryWithId.Id); > + } > + > + protected override void OnTearDown() > + { > + using (ISession session = OpenSession()) { > + > + using (ITransaction trans = > session.BeginTransaction()) > + { > + session.Delete("from > ProductWithId"); > + session.Delete("from > CategoryWithId"); > + session.Delete("from > ProductWithInheritedId"); > + session.Delete("from > CategoryWithInheritedId"); > + trans.Commit(); > + } > + } > + } > + } > +} > \ No newline at end of file > > Added: > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Mappings.hbm.xml > =================================================================== > --- > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Mappings.hbm.xml > (rev 0) > +++ > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Mappings.hbm.xml > 2008-12-28 22:20:58 UTC (rev 3967) > @@ -0,0 +1,35 @@ > +<?xml version="1.0" encoding="utf-8" ?> > +<hibernate-mapping > + xmlns="urn:nhibernate-mapping-2.2" > + namespace="NHibernate.Test.NHSpecificTest.NH1549" > + assembly="NHibernate.Test"> > + > + <class name="CategoryWithInheritedId"> > + <id name="Id" type="System.Int32"> > + <generator class="native" /> > + </id> > + <property name="Name" /> > + </class> > + > + <class name="ProductWithInheritedId" lazy="false"> > + <id name="Id" type="System.Int32"> > + <generator class="native" /> > + </id> > + <many-to-one name="CategoryWithInheritedId"/> > + </class> > + > + <class name="CategoryWithId"> > + <id name="Id" type="System.Int32"> > + <generator class="native" /> > + </id> > + <property name="Name" /> > + </class> > + > + <class name="ProductWithId" lazy="false"> > + <id name="Id" type="System.Int32"> > + <generator class="native" /> > + </id> > + <many-to-one name="CategoryWithId"/> > + </class> > + > +</hibernate-mapping> > > Added: > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs > =================================================================== > --- > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs > (rev 0) > +++ > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs > 2008-12-28 22:20:58 UTC (rev 3967) > @@ -0,0 +1,15 @@ > +using System; > + > +namespace NHibernate.Test.NHSpecificTest.NH1549 > +{ > + public class ProductWithInheritedId : EntityInt32 > + { > + public CategoryWithInheritedId CategoryWithInheritedId { > get; set; } > + } > + > + public class ProductWithId > + { > + public virtual int Id { get; set; } > + public CategoryWithId CategoryWithId { get; set; } > + } > +} > \ No newline at end of file > > > Property changes on: > trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs > ___________________________________________________________________ > Added: svn:mergeinfo > + > > Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj > =================================================================== > --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-12-27 > 19:53:57 UTC (rev 3966) > +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-12-28 > 22:20:58 UTC (rev 3967) > @@ -378,6 +378,10 @@ > <Compile Include="NHSpecificTest\NH1274ExportExclude\Person.cs" /> > <Compile Include="NHSpecificTest\NH1443\Fixture.cs" /> > <Compile Include="NHSpecificTest\NH1521\Fixture.cs" /> > + <Compile Include="NHSpecificTest\NH1549\CategoryWithInheritedId.cs" /> > + <Compile Include="NHSpecificTest\NH1549\EntityInt32.cs" /> > + <Compile Include="NHSpecificTest\NH1549\Fixture.cs" /> > + <Compile Include="NHSpecificTest\NH1549\ProductWithInheritedId.cs" /> > <Compile Include="NHSpecificTest\NH1605\Fixture.cs" /> > <Compile Include="NHSpecificTest\NH1609\Entities.cs" /> > <Compile Include="NHSpecificTest\NH1609\Fixture.cs" /> > @@ -1577,6 +1581,7 @@ > <EmbeddedResource Include="Cascade\JobBatch.hbm.xml" /> > <EmbeddedResource Include="Deletetransient\Person.hbm.xml" /> > <Content Include="DynamicEntity\package.html" /> > + <EmbeddedResource Include="NHSpecificTest\NH1549\Mappings.hbm.xml" /> > <EmbeddedResource > Include="NHSpecificTest\NH1521\AclassWithSpecific.hbm.xml" /> > <EmbeddedResource > Include="NHSpecificTest\NH1521\AclassWithNothing.hbm.xml" /> > <EmbeddedResource > Include="NHSpecificTest\NH1521\AclassWithDefault.hbm.xml" /> > > Modified: > trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs > =================================================================== > --- > trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs > 2008-12-27 19:53:57 UTC (rev 3966) > +++ > trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs > 2008-12-28 22:20:58 UTC (rev 3967) > @@ -56,11 +56,13 @@ > [Test] > public void TryGetMethod() > { > - const BindingFlags bf = BindingFlags.Instance | > BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; > - MethodInfo mig = typeof > (MyBaseImplementation).GetMethod("get_Id", bf); > + //const BindingFlags bf = BindingFlags.Instance | > BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; > + const BindingFlags bf = BindingFlags.Instance | > BindingFlags.Public | BindingFlags.NonPublic; > + MethodInfo mig = > typeof(MyBaseImplementation).GetMethod("get_Id", bf); > MethodInfo mis = > typeof(MyBaseImplementation).GetMethod("set_Id", bf); > MethodInfo mng = > typeof(MyBaseImplementation).GetMethod("get_Name", bf); > MethodInfo mns = > typeof(MyBaseImplementation).GetMethod("set_Name", bf); > + > > Assert.That(ReflectHelper.TryGetMethod(typeof(IMyBaseInterface), mig), > Is.Not.Null); > > Assert.That(ReflectHelper.TryGetMethod(typeof(IMyBaseInterface), mis), > Is.Null); > > Assert.That(ReflectHelper.TryGetMethod(typeof(IMyBaseInterface), mng), > Is.Not.Null); > @@ -78,6 +80,20 @@ > Assert.That(ReflectHelper.TryGetMethod(new[] { > typeof(IMyBaseInterface), typeof(IMyInterface) }, mns), Is.Not.Null); > Assert.That(ReflectHelper.TryGetMethod(new[] { > typeof(IMyBaseInterface), typeof(IMyInterface) }, mdg), Is.Not.Null); > Assert.That(ReflectHelper.TryGetMethod(new[] { > typeof(IMyBaseInterface), typeof(IMyInterface) }, mds), Is.Null); > + > + MethodInfo mdig = > typeof(MyDerivedImplementation).GetMethod("get_Id", bf); > + MethodInfo mdis = > typeof(MyDerivedImplementation).GetMethod("set_Id", bf); > + MethodInfo mdng = > typeof(MyDerivedImplementation).GetMethod("get_Name", bf); > + MethodInfo mdns = > typeof(MyDerivedImplementation).GetMethod("set_Name", bf); > + MethodInfo mddg = > typeof(MyDerivedImplementation).GetMethod("get_Description", bf); > + MethodInfo mdds = > typeof(MyDerivedImplementation).GetMethod("set_Description", bf); > + > + Assert.That(ReflectHelper.TryGetMethod(new[] { > typeof(IMyBaseInterface), typeof(IMyInterface) }, mdig), Is.Not.Null); > + Assert.That(ReflectHelper.TryGetMethod(new[] { > typeof(IMyBaseInterface), typeof(IMyInterface) }, mdis), Is.Null); > + Assert.That(ReflectHelper.TryGetMethod(new[] { > typeof(IMyBaseInterface), typeof(IMyInterface) }, mdng), Is.Not.Null); > + Assert.That(ReflectHelper.TryGetMethod(new[] { > typeof(IMyBaseInterface), typeof(IMyInterface) }, mdns), Is.Not.Null); > + Assert.That(ReflectHelper.TryGetMethod(new[] { > typeof(IMyBaseInterface), typeof(IMyInterface) }, mddg), Is.Not.Null); > + Assert.That(ReflectHelper.TryGetMethod(new[] { > typeof(IMyBaseInterface), typeof(IMyInterface) }, mdds), Is.Null); > } > } > > @@ -115,11 +131,15 @@ > public string Name { get; set; } > } > > + public class MyDerivedImplementation : MyBaseImplementation, > IMyInterface > + { > + public string Description { get; set; } > + } > + > public class MyImplementation: IMyInterface > { > public int Id{ get; set; } > public string Name { get; set; } > public string Description { get; set; } > } > - > } > \ No newline at end of file > > > This was sent by the SourceForge.net collaborative development platform, > the world's largest Open Source development site. > > > ------------------------------------------------------------------------------ > _______________________________________________ > Nhibernate-commit mailing list > Nhi...@li... > https://lists.sourceforge.net/lists/listinfo/nhibernate-commit > |
From: <dav...@us...> - 2008-12-28 22:21:02
|
Revision: 3967 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3967&view=rev Author: davybrion Date: 2008-12-28 22:20:58 +0000 (Sun, 28 Dec 2008) Log Message: ----------- Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/EntityInt32.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Fixture.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Mappings.hbm.xml trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs Modified: trunk/nhibernate/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs 2008-12-27 19:53:57 UTC (rev 3966) +++ trunk/nhibernate/src/NHibernate/Proxy/Poco/BasicLazyInitializer.cs 2008-12-28 22:20:58 UTC (rev 3967) @@ -62,7 +62,7 @@ /// underlying proxied object is needed then it returns the result <see cref="AbstractLazyInitializer.InvokeImplementation"/> /// which indicates that the Proxy will need to forward to the real implementation. /// </returns> - public virtual object Invoke(MethodBase method, object[] args, object proxy) + public virtual object Invoke(MethodInfo method, object[] args, object proxy) { string methodName = method.Name; int paramCount = method.GetParameters().Length; @@ -73,7 +73,7 @@ { return IdentityEqualityComparer.GetHashCode(proxy); } - else if (IsUninitialized && method.Equals(getIdentifierMethod)) + else if (IsUninitialized && IsEqualToIdentifierMethod(method)) { return Identifier; } @@ -135,5 +135,18 @@ return InvokeImplementation; } + private bool IsEqualToIdentifierMethod(MethodInfo method) + { + if (getIdentifierMethod != null) + { + // in the case of inherited identifier methods (from a base class or an iterface) the + // passed in MethodBase object is not equal to the getIdentifierMethod instance that we + // have... but if their names and return types are identical, then it is the correct + // identifier method + return method.Name.Equals(getIdentifierMethod.Name) && method.ReturnType.Equals(getIdentifierMethod.ReturnType); + } + + return false; + } } } Modified: trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs 2008-12-27 19:53:57 UTC (rev 3966) +++ trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs 2008-12-28 22:20:58 UTC (rev 3967) @@ -19,7 +19,7 @@ private static readonly ILog log = LogManager.GetLogger(typeof(ReflectHelper)); public static BindingFlags AnyVisibilityInstance = BindingFlags.Instance | BindingFlags.Public | - BindingFlags.NonPublic; + BindingFlags.NonPublic; private ReflectHelper() { @@ -29,7 +29,7 @@ private static System.Type[] NoClasses = System.Type.EmptyTypes; private static readonly MethodInfo Exception_InternalPreserveStackTrace = - typeof (Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic); + typeof(Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic); /// <summary> /// Determine if the specified <see cref="System.Type"/> overrides the @@ -41,7 +41,7 @@ { try { - MethodInfo equals = clazz.GetMethod("Equals", new System.Type[] {typeof(object)}); + MethodInfo equals = clazz.GetMethod("Equals", new System.Type[] { typeof(object) }); if (equals == null) { return false; @@ -127,7 +127,7 @@ System.Type heuristicClass = propertyClass; if (propertyClass.IsGenericType - && propertyClass.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) + && propertyClass.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { heuristicClass = propertyClass.GetGenericArguments()[0]; } @@ -292,15 +292,15 @@ public static bool TryLoadAssembly(string assemblyName) { - if(string.IsNullOrEmpty(assemblyName)) + if (string.IsNullOrEmpty(assemblyName)) return false; - bool result= true; + bool result = true; try { Assembly.Load(assemblyName); } - catch(Exception) + catch (Exception) { result = false; } @@ -446,7 +446,7 @@ /// <returns>The unwrapped exception.</returns> public static Exception UnwrapTargetInvocationException(TargetInvocationException ex) { - Exception_InternalPreserveStackTrace.Invoke(ex.InnerException, new Object[] {}); + Exception_InternalPreserveStackTrace.Invoke(ex.InnerException, new Object[] { }); return ex.InnerException; } @@ -472,14 +472,7 @@ } System.Type[] tps = GetMethodSignature(method); - try - { - return type.GetMethod(method.Name, defaultBindingFlags, null, tps, null); - } - catch (Exception) - { - return null; - } + return SafeGetMethod(type, method, tps); } /// <summary> @@ -493,6 +486,8 @@ /// </remarks> public static MethodInfo TryGetMethod(IEnumerable<System.Type> types, MethodInfo method) { + var bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + // This method will be used when we support multiple proxy interfaces. if (types == null) { @@ -505,21 +500,16 @@ System.Type[] tps = GetMethodSignature(method); MethodInfo result = null; + foreach (var type in types) { - try + result = SafeGetMethod(type, method, tps); + if (result != null) { - result = type.GetMethod(method.Name, defaultBindingFlags, null, tps, null); - if (result != null) - { - return result; - } + return result; } - catch (Exception) - { - return null; - } } + return result; } @@ -533,5 +523,19 @@ } return tps; } + + private static MethodInfo SafeGetMethod(System.Type type, MethodInfo method, System.Type[] tps) + { + var bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + + try + { + return type.GetMethod(method.Name, bindingFlags, null, tps, null); + } + catch (Exception) + { + return null; + } + } } } Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs 2008-12-28 22:20:58 UTC (rev 3967) @@ -0,0 +1,15 @@ +using System; + +namespace NHibernate.Test.NHSpecificTest.NH1549 +{ + public class CategoryWithInheritedId : EntityInt32 + { + public virtual string Name { get; set; } + } + + public class CategoryWithId + { + public virtual int Id { get; set; } + public virtual string Name { get; set; } + } +} \ No newline at end of file Property changes on: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/CategoryWithInheritedId.cs ___________________________________________________________________ Added: svn:mergeinfo + Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/EntityInt32.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/EntityInt32.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/EntityInt32.cs 2008-12-28 22:20:58 UTC (rev 3967) @@ -0,0 +1,7 @@ +namespace NHibernate.Test.NHSpecificTest.NH1549 +{ + public abstract class EntityInt32 + { + public virtual int Id { get; set; } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Fixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Fixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Fixture.cs 2008-12-28 22:20:58 UTC (rev 3967) @@ -0,0 +1,93 @@ +using NUnit.Framework; + +namespace NHibernate.Test.NHSpecificTest.NH1549 +{ + [TestFixture] + public class Fixture : BugTestCase + { + /// <summary> + /// Verifies that an entity with a base class containing the id property + /// can have the id accessed without loading the entity + /// </summary> + [Test] + public void CanLoadForEntitiesWithInheritedIds() + { + //create some related products + var category = new CategoryWithInheritedId {Name = "Fruit"}; + var product = new ProductWithInheritedId {CategoryWithInheritedId = category}; + + using (ISession session = OpenSession()) + { + using (ITransaction trans = session.BeginTransaction()) + { + session.Save(category); + session.Save(product); + trans.Commit(); + } + } + + ProductWithInheritedId restoredProductWithInheritedId; + + //restore the product from the db in another session so that + //the association is a proxy + using (ISession session = OpenSession()) + { + restoredProductWithInheritedId = session.Get<ProductWithInheritedId>(product.Id); + } + + //verify that the category is a proxy + Assert.IsFalse(NHibernateUtil.IsInitialized(restoredProductWithInheritedId.CategoryWithInheritedId)); + + //we should be able to access the id of the category outside of the session + Assert.AreEqual(category.Id, restoredProductWithInheritedId.CategoryWithInheritedId.Id); + } + + [Test] + public void CanLoadForEntitiesWithTheirOwnIds() + { + //create some related products + var category = new CategoryWithId { Name = "Fruit" }; + var product = new ProductWithId { CategoryWithId = category }; + + using (ISession session = OpenSession()) + { + using (ITransaction trans = session.BeginTransaction()) + { + session.Save(category); + session.Save(product); + trans.Commit(); + } + } + + ProductWithId restoredProductWithInheritedId; + + //restore the product from the db in another session so that + //the association is a proxy + using (ISession session = OpenSession()) + { + restoredProductWithInheritedId = session.Get<ProductWithId>(product.Id); + } + + //verify that the category is a proxy + Assert.IsFalse(NHibernateUtil.IsInitialized(restoredProductWithInheritedId.CategoryWithId)); + + //we should be able to access the id of the category outside of the session + Assert.AreEqual(category.Id, restoredProductWithInheritedId.CategoryWithId.Id); + } + + protected override void OnTearDown() + { + using (ISession session = OpenSession()) { + + using (ITransaction trans = session.BeginTransaction()) + { + session.Delete("from ProductWithId"); + session.Delete("from CategoryWithId"); + session.Delete("from ProductWithInheritedId"); + session.Delete("from CategoryWithInheritedId"); + trans.Commit(); + } + } + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Mappings.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Mappings.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/Mappings.hbm.xml 2008-12-28 22:20:58 UTC (rev 3967) @@ -0,0 +1,35 @@ +<?xml version="1.0" encoding="utf-8" ?> +<hibernate-mapping + xmlns="urn:nhibernate-mapping-2.2" + namespace="NHibernate.Test.NHSpecificTest.NH1549" + assembly="NHibernate.Test"> + + <class name="CategoryWithInheritedId"> + <id name="Id" type="System.Int32"> + <generator class="native" /> + </id> + <property name="Name" /> + </class> + + <class name="ProductWithInheritedId" lazy="false"> + <id name="Id" type="System.Int32"> + <generator class="native" /> + </id> + <many-to-one name="CategoryWithInheritedId"/> + </class> + + <class name="CategoryWithId"> + <id name="Id" type="System.Int32"> + <generator class="native" /> + </id> + <property name="Name" /> + </class> + + <class name="ProductWithId" lazy="false"> + <id name="Id" type="System.Int32"> + <generator class="native" /> + </id> + <many-to-one name="CategoryWithId"/> + </class> + +</hibernate-mapping> Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs 2008-12-28 22:20:58 UTC (rev 3967) @@ -0,0 +1,15 @@ +using System; + +namespace NHibernate.Test.NHSpecificTest.NH1549 +{ + public class ProductWithInheritedId : EntityInt32 + { + public CategoryWithInheritedId CategoryWithInheritedId { get; set; } + } + + public class ProductWithId + { + public virtual int Id { get; set; } + public CategoryWithId CategoryWithId { get; set; } + } +} \ No newline at end of file Property changes on: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1549/ProductWithInheritedId.cs ___________________________________________________________________ Added: svn:mergeinfo + Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-12-27 19:53:57 UTC (rev 3966) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-12-28 22:20:58 UTC (rev 3967) @@ -378,6 +378,10 @@ <Compile Include="NHSpecificTest\NH1274ExportExclude\Person.cs" /> <Compile Include="NHSpecificTest\NH1443\Fixture.cs" /> <Compile Include="NHSpecificTest\NH1521\Fixture.cs" /> + <Compile Include="NHSpecificTest\NH1549\CategoryWithInheritedId.cs" /> + <Compile Include="NHSpecificTest\NH1549\EntityInt32.cs" /> + <Compile Include="NHSpecificTest\NH1549\Fixture.cs" /> + <Compile Include="NHSpecificTest\NH1549\ProductWithInheritedId.cs" /> <Compile Include="NHSpecificTest\NH1605\Fixture.cs" /> <Compile Include="NHSpecificTest\NH1609\Entities.cs" /> <Compile Include="NHSpecificTest\NH1609\Fixture.cs" /> @@ -1577,6 +1581,7 @@ <EmbeddedResource Include="Cascade\JobBatch.hbm.xml" /> <EmbeddedResource Include="Deletetransient\Person.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> + <EmbeddedResource Include="NHSpecificTest\NH1549\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1521\AclassWithSpecific.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1521\AclassWithNothing.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1521\AclassWithDefault.hbm.xml" /> Modified: trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs 2008-12-27 19:53:57 UTC (rev 3966) +++ trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectHelperFixture.cs 2008-12-28 22:20:58 UTC (rev 3967) @@ -56,11 +56,13 @@ [Test] public void TryGetMethod() { - const BindingFlags bf = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; - MethodInfo mig = typeof (MyBaseImplementation).GetMethod("get_Id", bf); + //const BindingFlags bf = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + const BindingFlags bf = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + MethodInfo mig = typeof(MyBaseImplementation).GetMethod("get_Id", bf); MethodInfo mis = typeof(MyBaseImplementation).GetMethod("set_Id", bf); MethodInfo mng = typeof(MyBaseImplementation).GetMethod("get_Name", bf); MethodInfo mns = typeof(MyBaseImplementation).GetMethod("set_Name", bf); + Assert.That(ReflectHelper.TryGetMethod(typeof(IMyBaseInterface), mig), Is.Not.Null); Assert.That(ReflectHelper.TryGetMethod(typeof(IMyBaseInterface), mis), Is.Null); Assert.That(ReflectHelper.TryGetMethod(typeof(IMyBaseInterface), mng), Is.Not.Null); @@ -78,6 +80,20 @@ Assert.That(ReflectHelper.TryGetMethod(new[] { typeof(IMyBaseInterface), typeof(IMyInterface) }, mns), Is.Not.Null); Assert.That(ReflectHelper.TryGetMethod(new[] { typeof(IMyBaseInterface), typeof(IMyInterface) }, mdg), Is.Not.Null); Assert.That(ReflectHelper.TryGetMethod(new[] { typeof(IMyBaseInterface), typeof(IMyInterface) }, mds), Is.Null); + + MethodInfo mdig = typeof(MyDerivedImplementation).GetMethod("get_Id", bf); + MethodInfo mdis = typeof(MyDerivedImplementation).GetMethod("set_Id", bf); + MethodInfo mdng = typeof(MyDerivedImplementation).GetMethod("get_Name", bf); + MethodInfo mdns = typeof(MyDerivedImplementation).GetMethod("set_Name", bf); + MethodInfo mddg = typeof(MyDerivedImplementation).GetMethod("get_Description", bf); + MethodInfo mdds = typeof(MyDerivedImplementation).GetMethod("set_Description", bf); + + Assert.That(ReflectHelper.TryGetMethod(new[] { typeof(IMyBaseInterface), typeof(IMyInterface) }, mdig), Is.Not.Null); + Assert.That(ReflectHelper.TryGetMethod(new[] { typeof(IMyBaseInterface), typeof(IMyInterface) }, mdis), Is.Null); + Assert.That(ReflectHelper.TryGetMethod(new[] { typeof(IMyBaseInterface), typeof(IMyInterface) }, mdng), Is.Not.Null); + Assert.That(ReflectHelper.TryGetMethod(new[] { typeof(IMyBaseInterface), typeof(IMyInterface) }, mdns), Is.Not.Null); + Assert.That(ReflectHelper.TryGetMethod(new[] { typeof(IMyBaseInterface), typeof(IMyInterface) }, mddg), Is.Not.Null); + Assert.That(ReflectHelper.TryGetMethod(new[] { typeof(IMyBaseInterface), typeof(IMyInterface) }, mdds), Is.Null); } } @@ -115,11 +131,15 @@ public string Name { get; set; } } + public class MyDerivedImplementation : MyBaseImplementation, IMyInterface + { + public string Description { get; set; } + } + public class MyImplementation: IMyInterface { public int Id{ get; set; } public string Name { get; set; } public string Description { get; set; } } - } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <dav...@us...> - 2008-12-27 19:54:04
|
Revision: 3966 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3966&view=rev Author: davybrion Date: 2008-12-27 19:53:57 +0000 (Sat, 27 Dec 2008) Log Message: ----------- added tests to verify that NH-1521 was indeed fixed by the fix for NH-1443 Modified Paths: -------------- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/AclassWithDefault.hbm.xml trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/AclassWithNothing.hbm.xml trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/AclassWithSpecific.hbm.xml trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/Fixture.cs Copied: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/AclassWithDefault.hbm.xml (from rev 3965, trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1443/AclassWithDefault.hbm.xml) =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/AclassWithDefault.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/AclassWithDefault.hbm.xml 2008-12-27 19:53:57 UTC (rev 3966) @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="utf-8" ?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" + namespace="NHibernate.Test.NHSpecificTest.NH1521" + assembly="NHibernate.Test" + catalog="nhibernate" + schema="dbo"> + + <class name="Aclass"> + <id name="Id"> + <generator class="native"/> + </id> + </class> +</hibernate-mapping> Property changes on: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/AclassWithDefault.hbm.xml ___________________________________________________________________ Added: svn:mergeinfo + Copied: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/AclassWithNothing.hbm.xml (from rev 3965, trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1443/AclassWithNothing.hbm.xml) =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/AclassWithNothing.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/AclassWithNothing.hbm.xml 2008-12-27 19:53:57 UTC (rev 3966) @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="utf-8" ?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" + namespace="NHibernate.Test.NHSpecificTest.NH1521" + assembly="NHibernate.Test"> + + <class name="Aclass"> + <id name="Id"> + <generator class="native"/> + </id> + </class> +</hibernate-mapping> Copied: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/AclassWithSpecific.hbm.xml (from rev 3965, trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1443/AclassWithSpecific.hbm.xml) =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/AclassWithSpecific.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/AclassWithSpecific.hbm.xml 2008-12-27 19:53:57 UTC (rev 3966) @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="utf-8" ?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" + namespace="NHibernate.Test.NHSpecificTest.NH1521" + assembly="NHibernate.Test" + catalog="somethingDifferent" + schema="somethingDifferent"> + + <class name="Aclass" catalog="nhibernate" schema="dbo"> + <id name="Id"> + <generator class="native"/> + </id> + </class> +</hibernate-mapping> Property changes on: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/AclassWithSpecific.hbm.xml ___________________________________________________________________ Added: svn:mergeinfo + Copied: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/Fixture.cs (from rev 3965, trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1443/Fixture.cs) =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/Fixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/Fixture.cs 2008-12-27 19:53:57 UTC (rev 3966) @@ -0,0 +1,62 @@ +using System.Text; +using NHibernate.Cfg; +using NHibernate.Tool.hbm2ddl; +using NUnit.Framework; +using NUnit.Framework.SyntaxHelpers; + +namespace NHibernate.Test.NHSpecificTest.NH1521 +{ + [TestFixture] + public class Fixture + { + private static void AssertThatCheckOnTableExistenceIsCorrect(Configuration configuration) + { + var su = new SchemaExport(configuration); + var sb = new StringBuilder(500); + su.Execute(x => sb.AppendLine(x), false, false, true); + string script = sb.ToString(); + Assert.That(script, Text.Contains("if exists (select * from dbo.sysobjects where id = object_id(N'nhibernate.dbo.Aclass') and OBJECTPROPERTY(id, N'IsUserTable') = 1)")); + } + + [Test] + public void TestForClassWithDefaultSchema() + { + Configuration cfg = TestConfigurationHelper.GetDefaultConfiguration(); + cfg.AddResource("NHibernate.Test.NHSpecificTest.NH1521.AclassWithNothing.hbm.xml", GetType().Assembly); + cfg.SetProperty(Environment.DefaultCatalog, "nhibernate"); + cfg.SetProperty(Environment.DefaultSchema, "dbo"); + AssertThatCheckOnTableExistenceIsCorrect(cfg); + } + + [Test] + public void WithDefaultValuesInMapping() + { + Configuration cfg = TestConfigurationHelper.GetDefaultConfiguration(); + cfg.AddResource("NHibernate.Test.NHSpecificTest.NH1521.AclassWithDefault.hbm.xml", GetType().Assembly); + AssertThatCheckOnTableExistenceIsCorrect(cfg); + } + + [Test] + public void WithSpecificValuesInMapping() + { + Configuration cfg = TestConfigurationHelper.GetDefaultConfiguration(); + cfg.AddResource("NHibernate.Test.NHSpecificTest.NH1521.AclassWithSpecific.hbm.xml", GetType().Assembly); + AssertThatCheckOnTableExistenceIsCorrect(cfg); + } + + [Test] + public void WithDefaultValuesInConfigurationPriorityToMapping() + { + Configuration cfg = TestConfigurationHelper.GetDefaultConfiguration(); + cfg.AddResource("NHibernate.Test.NHSpecificTest.NH1521.AclassWithDefault.hbm.xml", GetType().Assembly); + cfg.SetProperty(Environment.DefaultCatalog, "somethingDifferent"); + cfg.SetProperty(Environment.DefaultSchema, "somethingDifferent"); + AssertThatCheckOnTableExistenceIsCorrect(cfg); + } + } + + public class Aclass + { + public int Id { get; set; } + } +} \ No newline at end of file Property changes on: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1521/Fixture.cs ___________________________________________________________________ Added: svn:mergeinfo + Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-12-25 19:57:53 UTC (rev 3965) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-12-27 19:53:57 UTC (rev 3966) @@ -377,6 +377,7 @@ <Compile Include="NHSpecificTest\NH1274ExportExclude\NH1274ExportExcludeFixture.cs" /> <Compile Include="NHSpecificTest\NH1274ExportExclude\Person.cs" /> <Compile Include="NHSpecificTest\NH1443\Fixture.cs" /> + <Compile Include="NHSpecificTest\NH1521\Fixture.cs" /> <Compile Include="NHSpecificTest\NH1605\Fixture.cs" /> <Compile Include="NHSpecificTest\NH1609\Entities.cs" /> <Compile Include="NHSpecificTest\NH1609\Fixture.cs" /> @@ -1576,6 +1577,9 @@ <EmbeddedResource Include="Cascade\JobBatch.hbm.xml" /> <EmbeddedResource Include="Deletetransient\Person.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> + <EmbeddedResource Include="NHSpecificTest\NH1521\AclassWithSpecific.hbm.xml" /> + <EmbeddedResource Include="NHSpecificTest\NH1521\AclassWithNothing.hbm.xml" /> + <EmbeddedResource Include="NHSpecificTest\NH1521\AclassWithDefault.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1621\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1609\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1605\Mappings.hbm.xml" /> @@ -1682,4 +1686,4 @@ if exist "$(ProjectDir)hibernate.cfg.xml" (copy "$(ProjectDir)hibernate.cfg.xml" "hibernate.cfg.xml") copy /y "..\..\..\NHibernate.DomainModel\ABC.hbm.xml" "ABC.hbm.xml"</PostBuildEvent> </PropertyGroup> -</Project> +</Project> \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: T. T. <te...@gm...> - 2008-12-26 11:00:49
|
Is it logical/possible to move subversion commits to a google group,or moderate members of current one? Tuna Toksöz http://tunatoksoz.com Typos included to enhance the readers attention! |
From: <dav...@us...> - 2008-12-25 19:57:58
|
Revision: 3965 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3965&view=rev Author: davybrion Date: 2008-12-25 19:57:53 +0000 (Thu, 25 Dec 2008) Log Message: ----------- applying patch from Germ?\195?\161n Schuager for NH-1621 Modified Paths: -------------- trunk/nhibernate/src/NHibernate/NHibernate.csproj trunk/nhibernate/src/NHibernate/Properties/PropertyAccessorFactory.cs trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate/Properties/ReadonlyAccessor.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1621/ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1621/Fixture.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1621/Mappings.hbm.xml trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1621/Model.cs trunk/nhibernate/src/NHibernate.Test/PropertyTest/ReadonlyAccessorFixture.cs Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-12-17 06:50:00 UTC (rev 3964) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-12-25 19:57:53 UTC (rev 3965) @@ -840,6 +840,7 @@ <Compile Include="Proxy\Map\MapProxyFactory.cs" /> <Compile Include="Proxy\Poco\BasicLazyInitializer.cs" /> <Compile Include="QueryParameterException.cs" /> + <Compile Include="Properties\ReadonlyAccessor.cs" /> <Compile Include="SessionException.cs" /> <Compile Include="SqlCommand\InformixJoinFragment.cs" /> <Compile Include="SqlCommand\SubselectClauseExtractor.cs" /> @@ -1150,4 +1151,4 @@ <Target Name="AfterBuild"> </Target> --> -</Project> \ No newline at end of file +</Project> Modified: trunk/nhibernate/src/NHibernate/Properties/PropertyAccessorFactory.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Properties/PropertyAccessorFactory.cs 2008-12-17 06:50:00 UTC (rev 3964) +++ trunk/nhibernate/src/NHibernate/Properties/PropertyAccessorFactory.cs 2008-12-25 19:57:53 UTC (rev 3965) @@ -23,6 +23,7 @@ accessors["property"] = new BasicPropertyAccessor(); accessors["field"] = new FieldAccessor(); accessors["backfield"] = new FieldAccessor(new BackFieldStrategy()); + accessors["readonly"] = new ReadOnlyAccessor(); accessors["field.camelcase"] = new FieldAccessor(new CamelCaseStrategy()); accessors["field.camelcase-underscore"] = new FieldAccessor(new CamelCaseUnderscoreStrategy()); accessors["field.lowercase"] = new FieldAccessor(new LowerCaseStrategy()); @@ -84,6 +85,14 @@ /// allows users of the Class to get the value of the Id but not set the value. /// </description> /// </item> + /// <item> + /// <term>readonly</term> + /// <description> + /// The <c>name</c> attribute is the name of the Property. NHibernate will use the + /// Property's get method to retrieve the value but will never set the value back in the domain. + /// This is used for read-only calculated properties with only a get method. + /// </description> + /// </item> /// <item> /// <term>Assembly Qualified Name</term> /// <description> Added: trunk/nhibernate/src/NHibernate/Properties/ReadonlyAccessor.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Properties/ReadonlyAccessor.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Properties/ReadonlyAccessor.cs 2008-12-25 19:57:53 UTC (rev 3965) @@ -0,0 +1,76 @@ +using System.Reflection; + +namespace NHibernate.Properties +{ + /// <summary> + /// Access the mapped property through a Property <c>get</c> to get the value + /// and do nothing to set the value. + /// </summary> + /// <remarks> + /// This is useful to allow calculated properties in the domain that will never + /// be recovered from the DB but can be used for querying. + /// </remarks> + public class ReadOnlyAccessor : IPropertyAccessor + { + /// <summary> + /// Initializes a new instance of <see cref="ReadOnlyAccessor"/>. + /// </summary> + public ReadOnlyAccessor() + { + } + + #region IPropertyAccessor Members + + /// <summary> + /// Creates an <see cref="BasicPropertyAccessor.BasicGetter"/> to <c>get</c> the value from the Property. + /// </summary> + /// <param name="type">The <see cref="System.Type"/> to find the Property in.</param> + /// <param name="propertyName">The name of the mapped Property to get.</param> + /// <returns> + /// The <see cref="BasicPropertyAccessor.BasicGetter"/> to use to get the value of the Property from an + /// instance of the <see cref="System.Type"/>.</returns> + /// <exception cref="PropertyNotFoundException" > + /// Thrown when a Property specified by the <c>propertyName</c> could not + /// be found in the <see cref="System.Type"/>. + /// </exception> + public IGetter GetGetter(System.Type type, string propertyName) + { + BasicPropertyAccessor.BasicGetter result = BasicPropertyAccessor.GetGetterOrNull(type, propertyName); + if (result == null) + { + throw new PropertyNotFoundException(type, propertyName, "getter"); + } + return result; + } + + /// <summary> + /// Create a <see cref="NoopAccessor.NoopSetter"/> to do nothing when trying to + /// se the value of the mapped Property + /// </summary> + /// <param name="type">The <see cref="System.Type"/> to find the mapped Property in.</param> + /// <param name="propertyName">The name of the mapped Property to set.</param> + /// <returns> + /// An instance of <see cref="NoopAccessor.NoopSetter"/>. + /// </returns> + public ISetter GetSetter(System.Type type, string propertyName) + { + return new NoopSetter(); + } + + public bool CanAccessThroughReflectionOptimizer + { + get { return true; } + } + + #endregion + + private class NoopSetter : ISetter + { + public void Set(object target, object value) {} + + public string PropertyName { get { return null; } } + + public MethodInfo Method { get { return null; } } + } + } +} Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1621/Fixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1621/Fixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1621/Fixture.cs 2008-12-25 19:57:53 UTC (rev 3965) @@ -0,0 +1,44 @@ +using NUnit.Framework; +using NUnit.Framework.SyntaxHelpers; + +namespace NHibernate.Test.NHSpecificTest.NH1621 +{ + [TestFixture] + public class Fixture : BugTestCase + { + ISession session; + + public override string BugNumber + { + get { return "NH1621"; } + } + + [Test] + public void QueryUsingReadonlyProperty() + { + using (session = OpenSession()) + { + Nums nums1 = new Nums {ID = 1, NumA = 1, NumB = 2}; + session.Save(nums1); + + Nums nums2 = new Nums {ID = 2, NumA = 2, NumB = 2 }; + session.Save(nums2); + + Nums nums3 = new Nums {ID = 3, NumA = 5, NumB = 2 }; + session.Save(nums3); + + session.Flush(); + session.Clear(); + + var nums = session.CreateQuery("from Nums b where b.Sum > 4").List<Nums>(); + + Assert.That(nums, Has.Count(1)); + Assert.That(nums[0].Sum, Is.EqualTo(7)); + + session.Delete("from Nums"); + session.Flush(); + session.Close(); + } + } + } +} Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1621/Mappings.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1621/Mappings.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1621/Mappings.hbm.xml 2008-12-25 19:57:53 UTC (rev 3965) @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="utf-8" ?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" + namespace="NHibernate.Test.NHSpecificTest.NH1621" + assembly="NHibernate.Test" +> + <class name="Nums" table="nums"> + <id name="ID"> + <generator class="assigned"/> + </id> + <property name="NumA"/> + <property name="NumB"/> + <property name="Sum" access="readonly"/> + </class> +</hibernate-mapping> Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1621/Model.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1621/Model.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1621/Model.cs 2008-12-25 19:57:53 UTC (rev 3965) @@ -0,0 +1,17 @@ +namespace NHibernate.Test.NHSpecificTest.NH1621 +{ + public class Nums + { + public virtual int ID { get; set; } + + public virtual int NumA { get; set; } + public virtual int NumB { get; set; } + public virtual int Sum + { + get + { + return NumA + NumB; + } + } + } +} Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-12-17 06:50:00 UTC (rev 3964) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-12-25 19:57:53 UTC (rev 3965) @@ -553,6 +553,8 @@ <Compile Include="NHSpecificTest\NH1594\A.cs" /> <Compile Include="NHSpecificTest\NH1594\Fixture.cs" /> <Compile Include="NHSpecificTest\NH1608\Fixture.cs" /> + <Compile Include="NHSpecificTest\NH1621\Fixture.cs" /> + <Compile Include="NHSpecificTest\NH1621\Model.cs" /> <Compile Include="NHSpecificTest\NH280\Fixture.cs" /> <Compile Include="NHSpecificTest\NH280\Foo.cs" /> <Compile Include="NHSpecificTest\NH1018\Employee.cs" /> @@ -825,6 +827,7 @@ <Compile Include="PropertyRef\KeyPropertyRefFixture.cs" /> <Compile Include="PropertyTest\BackFieldAccessorFixture.cs" /> <Compile Include="PropertyTest\BasicSetterExceptionFixture.cs" /> + <Compile Include="PropertyTest\ReadonlyAccessorFixture.cs" /> <Compile Include="PropertyTest\FieldAccessorFixture.cs" /> <Compile Include="PropertyTest\FieldCamelCaseFixture.cs" /> <Compile Include="PropertyTest\FieldCamelCaseUnderscoreFixture.cs" /> @@ -1573,6 +1576,7 @@ <EmbeddedResource Include="Cascade\JobBatch.hbm.xml" /> <EmbeddedResource Include="Deletetransient\Person.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> + <EmbeddedResource Include="NHSpecificTest\NH1621\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1609\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1605\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1443\AclassWithSpecific.hbm.xml" /> @@ -1678,4 +1682,4 @@ if exist "$(ProjectDir)hibernate.cfg.xml" (copy "$(ProjectDir)hibernate.cfg.xml" "hibernate.cfg.xml") copy /y "..\..\..\NHibernate.DomainModel\ABC.hbm.xml" "ABC.hbm.xml"</PostBuildEvent> </PropertyGroup> -</Project> \ No newline at end of file +</Project> Added: trunk/nhibernate/src/NHibernate.Test/PropertyTest/ReadonlyAccessorFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/PropertyTest/ReadonlyAccessorFixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/PropertyTest/ReadonlyAccessorFixture.cs 2008-12-25 19:57:53 UTC (rev 3965) @@ -0,0 +1,39 @@ +using NHibernate.Properties; +using NUnit.Framework; +using NUnit.Framework.SyntaxHelpers; + +namespace NHibernate.Test.PropertyTest +{ + [TestFixture] + public class ReadonlyAccessorFixture + { + [Test] + public void GetValue() + { + var accessor = PropertyAccessorFactory.GetPropertyAccessor("readonly"); + var getter = accessor.GetGetter(typeof(Calculation), "Sum"); + + Assert.That(getter.Get(new Calculation()), Is.EqualTo(2)); + } + + [Test] + public void SetValue() + { + var accessor = PropertyAccessorFactory.GetPropertyAccessor("readonly"); + var getter = accessor.GetGetter(typeof(Calculation), "Sum"); + var setter = accessor.GetSetter(typeof(Calculation), "Sum"); + + var i = new Calculation(); + Assert.That(getter.Get(i), Is.EqualTo(2)); + setter.Set(i, 1); + Assert.That(getter.Get(i), Is.EqualTo(2)); + } + } + + public class Calculation + { + public Calculation() { } + + public int Sum { get { return 1 + 1; } } + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: Threets S. <ri...@we...> - 2008-12-18 15:37:49
|
New Christmas pleasurre :) http://cid-5f91858e52ffbd77.spaces.live.com/blog/cns!5F91858E52FFBD77!106.entry Further speech, and hetty held on her way. Another the strong arms that bore her so easily. Why, at its western end. This plateau stood out, a the gong. James, will you carry this tray into time had fully come, would be on the right side,. |
From: <dav...@us...> - 2008-12-17 06:50:04
|
Revision: 3964 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3964&view=rev Author: davybrion Date: 2008-12-17 06:50:00 +0000 (Wed, 17 Dec 2008) Log Message: ----------- Testfixture for NH-1609 Modified Paths: -------------- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1609/ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1609/Entities.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1609/Fixture.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1609/Mappings.hbm.xml Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1609/Entities.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1609/Entities.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1609/Entities.cs 2008-12-17 06:50:00 UTC (rev 3964) @@ -0,0 +1,19 @@ +namespace NHibernate.Test.NHSpecificTest.NH1609 +{ + public class EntityA + { + public virtual long Id { get; set; } + } + + public class EntityB + { + public virtual long Id { get; set; } + public virtual EntityA A { get; set; } + public virtual EntityC C { get; set; } + } + + public class EntityC + { + public virtual long Id { get; set; } + } +} Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1609/Fixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1609/Fixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1609/Fixture.cs 2008-12-17 06:50:00 UTC (rev 3964) @@ -0,0 +1,75 @@ +using System.Collections; + +using NHibernate.Criterion; +using NHibernate.Test.NHSpecificTest.NH1609; + +using NUnit.Framework; + +namespace NHibernate.Test.NHSpecificTest.NH1609 +{ + [TestFixture] + [Ignore("not fixed yet")] + public class Fixture : BugTestCase + { + [Test] + public void Test() + { + using (ISession session = sessions.OpenSession()) + using (ITransaction transaction = session.BeginTransaction()) + { + EntityA a1 = CreateEntityA(session); + EntityA a2 = CreateEntityA(session); + EntityC c = CreateEntityC(session); + EntityB b = CreateEntityB(session, a1, c); + + // make sure the created entities are no longer in the session + session.Clear(); + + IMultiCriteria multi = session.CreateMultiCriteria(); + + // the first query is a simple select by id on EntityA + multi.Add(session.CreateCriteria(typeof(EntityA)).Add(Restrictions.Eq("Id", a1.Id))); + // the second query is also a simple select by id on EntityB + multi.Add(session.CreateCriteria(typeof(EntityA)).Add(Restrictions.Eq("Id", a2.Id))); + // the final query selects the first element (using SetFirstResult and SetMaxResults) for each EntityB where B.A.Id = a1.Id and B.C.Id = c.Id + // the problem is that the paged query uses parameters @p0 and @p1 instead of @p2 and @p3 + multi.Add( + session.CreateCriteria(typeof(EntityB)) + .Add(Restrictions.Eq("A.Id", a1.Id)) + .Add(Restrictions.Eq("C.Id", c.Id)) + .SetFirstResult(0) + .SetMaxResults(1)); + + var results = multi.List(); + + Assert.AreEqual(1, ((IList)results[0]).Count); + Assert.AreEqual(1, ((IList)results[1]).Count); + Assert.AreEqual(1, ((IList)results[2]).Count); + } + } + + private EntityA CreateEntityA(ISession session) + { + EntityA a = new EntityA(); + session.Save(a); + session.Flush(); + return a; + } + + private EntityC CreateEntityC(ISession session) + { + EntityC c = new EntityC(); + session.Save(c); + session.Flush(); + return c; + } + + private EntityB CreateEntityB(ISession session, EntityA a, EntityC c) + { + EntityB b = new EntityB { A = a, C = c }; + session.Save(b); + session.Flush(); + return b; + } + } +} Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1609/Mappings.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1609/Mappings.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1609/Mappings.hbm.xml 2008-12-17 06:50:00 UTC (rev 3964) @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="utf-8" ?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" + assembly="NHibernate.Test" + namespace="NHibernate.Test.NHSpecificTest.NH1609"> + + <class name="EntityA" table="EntityA"> + <id name="Id" column="Id" type="long"> + <generator class="identity"/> + </id> + </class> + + <class name="EntityB" table="EntityB"> + <id name="Id" column="Id" type="long"> + <generator class="identity"/> + </id> + + <many-to-one name="A" column="AId" class="EntityA" /> + <many-to-one name="C" column="CId" class="EntityC" /> + + </class> + + <class name="EntityC" table="EntityC"> + <id name="Id" column="Id" type="long"> + <generator class="identity" /> + </id> + </class> + +</hibernate-mapping> Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-12-16 21:53:58 UTC (rev 3963) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-12-17 06:50:00 UTC (rev 3964) @@ -378,6 +378,8 @@ <Compile Include="NHSpecificTest\NH1274ExportExclude\Person.cs" /> <Compile Include="NHSpecificTest\NH1443\Fixture.cs" /> <Compile Include="NHSpecificTest\NH1605\Fixture.cs" /> + <Compile Include="NHSpecificTest\NH1609\Entities.cs" /> + <Compile Include="NHSpecificTest\NH1609\Fixture.cs" /> <Compile Include="NHSpecificTest\NH1611OneToOneIdentity\Adjunct.cs" /> <Compile Include="NHSpecificTest\NH1611OneToOneIdentity\NH1611OneToOneIdentityFixture.cs" /> <Compile Include="NHSpecificTest\NH1611OneToOneIdentity\Primary.cs" /> @@ -1571,6 +1573,7 @@ <EmbeddedResource Include="Cascade\JobBatch.hbm.xml" /> <EmbeddedResource Include="Deletetransient\Person.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> + <EmbeddedResource Include="NHSpecificTest\NH1609\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1605\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1443\AclassWithSpecific.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1443\AclassWithDefault.hbm.xml" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-12-16 22:39:01
|
Revision: 3963 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3963&view=rev Author: fabiomaulo Date: 2008-12-16 21:53:58 +0000 (Tue, 16 Dec 2008) Log Message: ----------- Fix NH-1605 Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/ResultSetMappingBinder.cs trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1605/ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1605/Fixture.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1605/Mappings.hbm.xml Modified: trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/ResultSetMappingBinder.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/ResultSetMappingBinder.cs 2008-12-16 21:00:05 UTC (rev 3962) +++ trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/ResultSetMappingBinder.cs 2008-12-16 21:53:58 UTC (rev 3963) @@ -73,10 +73,23 @@ return null; } - private static INativeSQLQueryReturn CreateScalarReturn(HbmReturnScalar returnScalarSchema) + private INativeSQLQueryReturn CreateScalarReturn(HbmReturnScalar returnScalarSchema) { - IType type = TypeFactory.HeuristicType(returnScalarSchema.type, null); + string typeName; + IDictionary<string, string> parameters = null; + TypeDef typeDef = mappings.GetTypeDef(returnScalarSchema.type); + if (typeDef != null) + { + typeName = typeDef.TypeClass; + parameters = typeDef.Parameters; + } + else + { + typeName = returnScalarSchema.type; + } + IType type = TypeFactory.HeuristicType(typeName, (IDictionary) parameters); + if (type == null) throw new MappingException("could not interpret type: " + returnScalarSchema.type); Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1605/Fixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1605/Fixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1605/Fixture.cs 2008-12-16 21:53:58 UTC (rev 3963) @@ -0,0 +1,32 @@ +using System.Reflection; +using NHibernate.Cfg; +using NUnit.Framework; + +namespace NHibernate.Test.NHSpecificTest.NH1605 +{ + [TestFixture] + public class Fixture + { + [Test] + public void SupportTypedefInReturnScalarElements() + { + var cfg = new Configuration(); + Assembly assembly = Assembly.GetExecutingAssembly(); + cfg.AddResource("NHibernate.Test.NHSpecificTest.NH1605.Mappings.hbm.xml", assembly); + using (cfg.BuildSessionFactory()) {} + } + } + + public enum CapitalCities + { + Amsterdam, + Berlin, + Cairo, + Dublin + } + + public class Country + { + public virtual CapitalCities CapitalCity { get; set; } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1605/Mappings.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1605/Mappings.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1605/Mappings.hbm.xml 2008-12-16 21:53:58 UTC (rev 3963) @@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="utf-8" ?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" + assembly="NHibernate.Test" + namespace="NHibernate.Test.NHSpecificTest.NH1605"> + + <typedef name="CapitalCityString" class="NHibernate.Type.EnumStringType`1[[NHibernate.Test.NHSpecificTest.NH1605.CapitalCities, NHibernate.Test]], NHibernate" /> + + <class name="Country"> + <id type="int"> + <generator class="native"/> + </id> + <property name="CapitalCity" type="CapitalCityString" /> + </class> + + <sql-query name="Country-GetCapital"> + <return-scalar column="CapitalCity" type="CapitalCityString" /> + -- Custom SQL omitted + </sql-query> +</hibernate-mapping> Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-12-16 21:00:05 UTC (rev 3962) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-12-16 21:53:58 UTC (rev 3963) @@ -377,6 +377,7 @@ <Compile Include="NHSpecificTest\NH1274ExportExclude\NH1274ExportExcludeFixture.cs" /> <Compile Include="NHSpecificTest\NH1274ExportExclude\Person.cs" /> <Compile Include="NHSpecificTest\NH1443\Fixture.cs" /> + <Compile Include="NHSpecificTest\NH1605\Fixture.cs" /> <Compile Include="NHSpecificTest\NH1611OneToOneIdentity\Adjunct.cs" /> <Compile Include="NHSpecificTest\NH1611OneToOneIdentity\NH1611OneToOneIdentityFixture.cs" /> <Compile Include="NHSpecificTest\NH1611OneToOneIdentity\Primary.cs" /> @@ -1570,6 +1571,7 @@ <EmbeddedResource Include="Cascade\JobBatch.hbm.xml" /> <EmbeddedResource Include="Deletetransient\Person.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> + <EmbeddedResource Include="NHSpecificTest\NH1605\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1443\AclassWithSpecific.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1443\AclassWithDefault.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1443\AclassWithNothing.hbm.xml" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-12-16 21:00:09
|
Revision: 3962 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3962&view=rev Author: fabiomaulo Date: 2008-12-16 21:00:05 +0000 (Tue, 16 Dec 2008) Log Message: ----------- Fix NH-1606 by Sergey Cherkasov Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Dialect/OracleDialect.cs Modified: trunk/nhibernate/src/NHibernate/Dialect/OracleDialect.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/OracleDialect.cs 2008-12-16 20:54:13 UTC (rev 3961) +++ trunk/nhibernate/src/NHibernate/Dialect/OracleDialect.cs 2008-12-16 21:00:05 UTC (rev 3962) @@ -1,3 +1,4 @@ +using System.Data; using NHibernate.SqlCommand; namespace NHibernate.Dialect @@ -7,11 +8,11 @@ /// </summary> public class OracleDialect : Oracle9Dialect { - /// <summary></summary> - public OracleDialect() : base() + public OracleDialect() { + RegisterColumnType(DbType.DateTime, "DATE"); } - + /// <summary></summary> public override JoinFragment CreateOuterJoinFragment() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-12-16 20:54:18
|
Revision: 3961 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3961&view=rev Author: fabiomaulo Date: 2008-12-16 20:54:13 +0000 (Tue, 16 Dec 2008) Log Message: ----------- Fix NH-1614 by Giovanni Bismondo Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Dialect/MySQL5Dialect.cs trunk/nhibernate/src/NHibernate/Dialect/MySQLDialect.cs Modified: trunk/nhibernate/src/NHibernate/Dialect/MySQL5Dialect.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/MySQL5Dialect.cs 2008-12-16 20:44:19 UTC (rev 3960) +++ trunk/nhibernate/src/NHibernate/Dialect/MySQL5Dialect.cs 2008-12-16 20:54:13 UTC (rev 3961) @@ -4,14 +4,38 @@ { internal class MySQL5Dialect : MySQLDialect { + //Reference 5.x + //Numeric: + //http://dev.mysql.com/doc/refman/5.0/en/numeric-type-overview.html + //Date and time: + //http://dev.mysql.com/doc/refman/5.0/en/date-and-time-type-overview.html + //String: + //http://dev.mysql.com/doc/refman/5.0/en/string-type-overview.html + //default: + //http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html + public override bool SupportsVariableLimit { - get { return false; } + get + { + //note: why false? + return false; + } } + public override bool SupportsSubSelects + { + get + { + //subquery in mysql? yes! From 4.1! + //http://dev.mysql.com/doc/refman/5.1/en/subqueries.html + return true; + } + } + public override SqlString GetLimitString(SqlString querySqlString, int offset, int limit) { - SqlStringBuilder pagingBuilder = new SqlStringBuilder(); + var pagingBuilder = new SqlStringBuilder(); pagingBuilder.Add(querySqlString); pagingBuilder.Add(" limit "); @@ -23,7 +47,6 @@ pagingBuilder.Add(limit.ToString()); - return pagingBuilder.ToSqlString(); } } Modified: trunk/nhibernate/src/NHibernate/Dialect/MySQLDialect.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/MySQLDialect.cs 2008-12-16 20:44:19 UTC (rev 3960) +++ trunk/nhibernate/src/NHibernate/Dialect/MySQLDialect.cs 2008-12-16 20:54:13 UTC (rev 3961) @@ -29,9 +29,19 @@ /// </remarks> public class MySQLDialect : Dialect { - /// <summary></summary> - public MySQLDialect() : base() + public MySQLDialect() { + //Reference 3-4.x + //Numeric: + //http://dev.mysql.com/doc/refman/4.1/en/numeric-type-overview.html + //Date and time: + //http://dev.mysql.com/doc/refman/4.1/en/date-and-time-type-overview.html + //String: + //http://dev.mysql.com/doc/refman/5.0/en/string-type-overview.html + //default: + //http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html + + //string type RegisterColumnType(DbType.AnsiStringFixedLength, "CHAR(255)"); RegisterColumnType(DbType.AnsiStringFixedLength, 255, "CHAR($l)"); RegisterColumnType(DbType.AnsiStringFixedLength, 65535, "TEXT"); @@ -40,33 +50,58 @@ RegisterColumnType(DbType.AnsiString, 255, "VARCHAR($l)"); RegisterColumnType(DbType.AnsiString, 65535, "TEXT"); RegisterColumnType(DbType.AnsiString, 16777215, "MEDIUMTEXT"); + RegisterColumnType(DbType.StringFixedLength, "CHAR(255)"); + RegisterColumnType(DbType.StringFixedLength, 255, "CHAR($l)"); + RegisterColumnType(DbType.StringFixedLength, 65535, "TEXT"); + RegisterColumnType(DbType.StringFixedLength, 16777215, "MEDIUMTEXT"); + RegisterColumnType(DbType.String, "VARCHAR(255)"); + RegisterColumnType(DbType.String, 255, "VARCHAR($l)"); + RegisterColumnType(DbType.String, 65535, "TEXT"); + RegisterColumnType(DbType.String, 16777215, "MEDIUMTEXT"); + //todo: future: add compatibility with decimal??? + //An unpacked fixed-point number. Behaves like a CHAR column; + //\x93unpacked\x94 means the number is stored as a string, using one character for each digit of the value. + //M is the total number of digits and D is the number of digits after the decimal point + //DECIMAL[(M[,D])] [UNSIGNED] [ZEROFILL] + + //binary type: RegisterColumnType(DbType.Binary, "LONGBLOB"); RegisterColumnType(DbType.Binary, 127, "TINYBLOB"); RegisterColumnType(DbType.Binary, 65535, "BLOB"); RegisterColumnType(DbType.Binary, 16777215, "MEDIUMBLOB"); - RegisterColumnType(DbType.Boolean, "TINYINT(1)"); + + //Numeric type: + RegisterColumnType(DbType.Boolean, "TINYINT(1)"); // SELECT IF(0, 'true', 'false'); RegisterColumnType(DbType.Byte, "TINYINT UNSIGNED"); RegisterColumnType(DbType.Currency, "MONEY"); - RegisterColumnType(DbType.Date, "DATE"); - RegisterColumnType(DbType.DateTime, "DATETIME"); RegisterColumnType(DbType.Decimal, "NUMERIC(19,5)"); RegisterColumnType(DbType.Decimal, 19, "NUMERIC(19, $l)"); RegisterColumnType(DbType.Double, "DOUBLE"); - RegisterColumnType(DbType.Guid, "VARCHAR(40)"); + //The signed range is -32768 to 32767. The unsigned range is 0 to 65535. RegisterColumnType(DbType.Int16, "SMALLINT"); - RegisterColumnType(DbType.Int32, "INTEGER"); + RegisterColumnType(DbType.Int32, "INTEGER"); //alias INT + //As of MySQL 4.1, SERIAL is an alias for BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE. RegisterColumnType(DbType.Int64, "BIGINT"); + //!!! + //Using FLOAT might give you some unexpected problems because all calculations in MySQL are done with double precision RegisterColumnType(DbType.Single, "FLOAT"); - RegisterColumnType(DbType.StringFixedLength, "CHAR(255)"); - RegisterColumnType(DbType.StringFixedLength, 255, "CHAR($l)"); - RegisterColumnType(DbType.StringFixedLength, 65535, "TEXT"); - RegisterColumnType(DbType.StringFixedLength, 16777215, "MEDIUMTEXT"); - RegisterColumnType(DbType.String, "VARCHAR(255)"); - RegisterColumnType(DbType.String, 255, "VARCHAR($l)"); - RegisterColumnType(DbType.String, 65535, "TEXT"); - RegisterColumnType(DbType.String, 16777215, "MEDIUMTEXT"); + RegisterColumnType(DbType.Byte, 1, "BIT"); //Like TinyInt(i) + RegisterColumnType(DbType.SByte, "TINYINT"); + + //UNSINGED Numeric type: + RegisterColumnType(DbType.UInt16, "SMALLINT UNSIGNED"); + RegisterColumnType(DbType.UInt32, "INTEGER UNSIGNED"); + RegisterColumnType(DbType.UInt64, "BIGINT UNSIGNED"); + //there are no other DbType unsigned...but mysql support Float unsigned, double unsigned, etc.. + + //Date and time type: + RegisterColumnType(DbType.Date, "DATE"); + RegisterColumnType(DbType.DateTime, "DATETIME"); RegisterColumnType(DbType.Time, "TIME"); + //special: + RegisterColumnType(DbType.Guid, "VARCHAR(40)"); + DefaultProperties[Environment.ConnectionDriver] = "NHibernate.Driver.MySqlDataDriver"; } @@ -123,6 +158,11 @@ get { return true; } } + public override bool SupportsSubSelects + { + get { return false; } + } + /// <summary> /// /// </summary> @@ -131,7 +171,7 @@ /// <returns></returns> public override SqlString GetLimitString(SqlString querySqlString, bool hasOffset) { - SqlStringBuilder pagingBuilder = new SqlStringBuilder(); + var pagingBuilder = new SqlStringBuilder(); pagingBuilder.Add(querySqlString); pagingBuilder.Add(" limit "); pagingBuilder.Add(Parameter.Placeholder); @@ -141,27 +181,18 @@ pagingBuilder.Add(", "); pagingBuilder.Add(Parameter.Placeholder); } - return pagingBuilder.ToSqlString(); } public override string GetAddForeignKeyConstraintString(string constraintName, string[] foreignKey, - string referencedTable, string[] primaryKey, bool referencesPrimaryKey) + string referencedTable, string[] primaryKey, + bool referencesPrimaryKey) { string cols = String.Join(StringHelper.CommaSpace, foreignKey); - return new StringBuilder(30) - .Append(" add index (") - .Append(cols) - .Append("), add constraint ") - .Append(constraintName) - .Append(" foreign key (") - .Append(cols) - .Append(") references ") - .Append(referencedTable) - .Append(" (") - .Append(String.Join(StringHelper.CommaSpace, primaryKey)) - .Append(')') - .ToString(); + return + new StringBuilder(30).Append(" add index (").Append(cols).Append("), add constraint ").Append(constraintName).Append + (" foreign key (").Append(cols).Append(") references ").Append(referencedTable).Append(" (").Append( + String.Join(StringHelper.CommaSpace, primaryKey)).Append(')').ToString(); } /// <summary> @@ -193,11 +224,5 @@ { return " drop index " + constraintName; } - - public override bool SupportsSubSelects - { - // TODO: newer MySQLs actually support subselects - get { return false; } - } } } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-12-16 20:44:25
|
Revision: 3960 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3960&view=rev Author: fabiomaulo Date: 2008-12-16 20:44:19 +0000 (Tue, 16 Dec 2008) Log Message: ----------- - Minor refactoring - bugfix in exception message Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs trunk/nhibernate/src/NHibernate/Mapping/Table.cs Modified: trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs 2008-12-16 20:16:16 UTC (rev 3959) +++ trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs 2008-12-16 20:44:19 UTC (rev 3960) @@ -2031,7 +2031,7 @@ string key = generator.GeneratorKey(); if (!databaseMetadata.IsSequence(key) && !databaseMetadata.IsTable(key)) { - throw new HibernateException(string.Format("Missing sequence or table: ", key)); + throw new HibernateException(string.Format("Missing sequence or table: "+ key)); } } } Modified: trunk/nhibernate/src/NHibernate/Mapping/Table.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Mapping/Table.cs 2008-12-16 20:16:16 UTC (rev 3959) +++ trunk/nhibernate/src/NHibernate/Mapping/Table.cs 2008-12-16 20:44:19 UTC (rev 3960) @@ -1,7 +1,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Data; using System.Text; using NHibernate.Dialect.Schema; using NHibernate.Engine; @@ -14,9 +13,9 @@ { None = 0, Drop = 1, - Update= 2, - Export= 4, - Validate= 8, + Update = 2, + Export = 4, + Validate = 8, All = Drop | Update | Export | Validate } @@ -26,78 +25,25 @@ [Serializable] public class Table : IRelationalModel { - internal class ForeignKeyKey: IEqualityComparer<ForeignKeyKey> - { - internal string referencedClassName; - internal List<Column> columns; - internal List<Column> referencedColumns; - - internal ForeignKeyKey(IEnumerable<Column> columns, string referencedClassName, IEnumerable<Column> referencedColumns) - { - this.referencedClassName = referencedClassName; - this.columns = new List<Column>(columns); - if (referencedColumns != null) - this.referencedColumns = new List<Column>(referencedColumns); - else - this.referencedColumns = new List<Column>(); - } - - public override int GetHashCode() - { - return GetHashCode(this); - } - - public override bool Equals(object other) - { - ForeignKeyKey that = other as ForeignKeyKey; - if (that != null) - return Equals(this, that); - else - return false; - } - - #region IEqualityComparer<ForeignKeyKey> Members - - public bool Equals(ForeignKeyKey x, ForeignKeyKey y) - { - // NH : Different implementation to prevent NH930 (look test) - return //y.referencedClassName.Equals(x.referencedClassName) && - CollectionHelper.CollectionEquals<Column>(y.columns, x.columns) && - CollectionHelper.CollectionEquals<Column>(y.referencedColumns, x.referencedColumns); - } - - public int GetHashCode(ForeignKeyKey obj) - { - int result = CollectionHelper.GetHashCode(obj.columns) ^ CollectionHelper.GetHashCode(obj.referencedColumns); - return result; - } - - #endregion - } - - private string name; - private string schema; - private string catalog; - + private static int tableCounter; + private readonly List<string> checkConstraints = new List<string>(); private readonly LinkedHashMap<string, Column> columns = new LinkedHashMap<string, Column>(); - private IKeyValue idValue; - private PrimaryKey primaryKey; - private readonly Dictionary<string, Index> indexes = new Dictionary<string, Index>(); private readonly Dictionary<ForeignKeyKey, ForeignKey> foreignKeys = new Dictionary<ForeignKeyKey, ForeignKey>(); - private readonly Dictionary<string, UniqueKey> uniqueKeys = new Dictionary<string, UniqueKey>(); + private readonly Dictionary<string, Index> indexes = new Dictionary<string, Index>(); private readonly int uniqueInteger; - private bool quoted; - private static int tableCounter = 0; - private readonly List<string> checkConstraints = new List<string>(); - private bool isAbstract; - private bool hasDenormalizedTables = false; + private readonly Dictionary<string, UniqueKey> uniqueKeys = new Dictionary<string, UniqueKey>(); + private string catalog; private string comment; - private string subselect; - private string rowId; + private bool hasDenormalizedTables; + private IKeyValue idValue; + private bool isAbstract; private bool isSchemaQuoted; + private string name; + private bool quoted; + private string schema; private SchemaAction schemaActions = SchemaAction.All; + private string subselect; - /// <summary> /// Initializes a new instance of <see cref="Table"/>. /// </summary> @@ -106,43 +52,12 @@ uniqueInteger = tableCounter++; } - public Table(string name) - : this() + public Table(string name) : this() { Name = name; } /// <summary> - /// Gets the schema qualified name of the Table. - /// </summary> - /// <param name="dialect">The <see cref="Dialect"/> that knows how to Quote the Table name.</param> - /// <returns>The name of the table qualified with the schema if one is specified.</returns> - public string GetQualifiedName(Dialect.Dialect dialect) - { - return GetQualifiedName(dialect, null, null); - } - - /// <summary> - /// Gets the schema qualified name of the Table using the specified qualifier - /// </summary> - /// <param name="dialect">The <see cref="Dialect"/> that knows how to Quote the Table name.</param> - /// <param name="defaultCatalog">The catalog name.</param> - /// <param name="defaultSchema">The schema name.</param> - /// <returns>A String representing the Qualified name.</returns> - /// <remarks>If this were used with MSSQL it would return a dbo.table_name.</remarks> - public virtual string GetQualifiedName(Dialect.Dialect dialect, string defaultCatalog, string defaultSchema) - { - if (!string.IsNullOrEmpty(subselect)) - { - return "( " + subselect + " )"; - } - string quotedName = GetQuotedName(dialect); - string usedSchema = schema == null ? defaultSchema : GetQuotedSchema(dialect); - string usedCatalog = catalog ?? defaultCatalog; - return dialect.Qualify(usedCatalog, usedSchema, quotedName); - } - - /// <summary> /// Gets or sets the name of the Table in the database. /// </summary> /// <value> @@ -177,102 +92,7 @@ } } - /// <summary> returns quoted name as it would be in the mapping file.</summary> - public string GetQuotedName() - { - return quoted ? "`" + name + "`" : name; - } - /// <summary> - /// Gets the name of this Table in quoted form if it is necessary. - /// </summary> - /// <param name="dialect"> - /// The <see cref="Dialect.Dialect"/> that knows how to quote the Table name. - /// </param> - /// <returns> - /// The Table name in a form that is safe to use inside of a SQL statement. - /// Quoted if it needs to be, not quoted if it does not need to be. - /// </returns> - public string GetQuotedName(Dialect.Dialect dialect) - { - return IsQuoted ? - dialect.QuoteForTableName(name) : - name; - } - - /// <summary> returns quoted name as it is in the mapping file.</summary> - public string GetQuotedSchema() - { - return IsSchemaQuoted ? "`" + schema + "`" : schema; - } - - public string GetQuotedSchema(Dialect.Dialect dialect) - { - return IsSchemaQuoted ? dialect.OpenQuote + schema + dialect.CloseQuote : schema; - } - - /// <summary> - /// Gets the schema for this table in quoted form if it is necessary. - /// </summary> - /// <param name="dialect"> - /// The <see cref="Dialect.Dialect" /> that knows how to quote the table name. - /// </param> - /// <returns> - /// The schema name for this table in a form that is safe to use inside - /// of a SQL statement. Quoted if it needs to be, not quoted if it does not need to be. - /// </returns> - public string GetQuotedSchemaName(Dialect.Dialect dialect) - { - if (schema == null) - { - return null; - } - - if (schema.StartsWith("`")) - { - return dialect.QuoteForSchemaName(schema.Substring(1, schema.Length - 2)); - } - - return schema; - } - - /// <summary> - /// Gets the <see cref="Column"/> at the specified index. - /// </summary> - /// <param name="n">The index of the Column to get.</param> - /// <returns> - /// The <see cref="Column"/> at the specified index. - /// </returns> - public Column GetColumn(int n) - { - IEnumerator<Column> iter = columns.Values.GetEnumerator(); - for (int i = 0; i < n; i++) - { - iter.MoveNext(); - } - return iter.Current; - } - - /// <summary> - /// Adds the <see cref="Column"/> to the <see cref="ICollection"/> of - /// Columns that are part of the Table. - /// </summary> - /// <param name="column">The <see cref="Column"/> to include in the Table.</param> - public void AddColumn(Column column) - { - Column old = GetColumn(column); - if (old == null) - { - columns[column.CanonicalName] = column; - column.uniqueInteger = columns.Count; - } - else - { - column.uniqueInteger = old.uniqueInteger; - } - } - - /// <summary> /// Gets the number of columns that this Table contains. /// </summary> /// <value> @@ -335,67 +155,168 @@ get { return uniqueKeys.Values; } } - public string[] SqlAlterStrings(Dialect.Dialect dialect, IMapping p, ITableMetadata tableInfo, string defaultCatalog, string defaultSchema) + /// <summary> + /// Gets or sets the <see cref="PrimaryKey"/> of the Table. + /// </summary> + /// <value>The <see cref="PrimaryKey"/> of the Table.</value> + public virtual PrimaryKey PrimaryKey { get; set; } + + /// <summary> + /// Gets or sets the schema the table is in. + /// </summary> + /// <value> + /// The schema the table is in or <see langword="null" /> if no schema is specified. + /// </value> + public string Schema { - StringBuilder root = new StringBuilder("alter table ") - .Append(GetQualifiedName(dialect, defaultCatalog, defaultSchema)) - .Append(' ') - .Append(dialect.AddColumnString); + get { return schema; } + set + { + if (value != null && value[0] == '`') + { + isSchemaQuoted = true; + schema = value.Substring(1, value.Length - 2); + } + else + { + schema = value; + } + } + } - List<string> results = new List<string>(ColumnSpan); + /// <summary> + /// Gets the unique number of the Table. + /// </summary> + /// <value>The unique number of the Table.</value> + public int UniqueInteger + { + get { return uniqueInteger; } + } - foreach (Column column in ColumnIterator) + /// <summary> + /// Gets or sets if the column needs to be quoted in SQL statements. + /// </summary> + /// <value><see langword="true" /> if the column is quoted.</value> + public bool IsQuoted + { + get { return quoted; } + set { quoted = value; } + } + + public IEnumerable<string> CheckConstraintsIterator + { + get { return checkConstraints; } + } + + public bool IsAbstractUnionTable + { + get { return HasDenormalizedTables && isAbstract; } + } + + public bool HasDenormalizedTables + { + get { return hasDenormalizedTables; } + } + + public bool IsAbstract + { + get { return isAbstract; } + set { isAbstract = value; } + } + + internal IDictionary<string, UniqueKey> UniqueKeys + { + get { - IColumnMetadata columnInfo = tableInfo.GetColumnMetadata(column.Name); - if (columnInfo != null) - continue; - - // the column doesnt exist at all. - StringBuilder alter = new StringBuilder(root.ToString()) - .Append(' ') - .Append(column.GetQuotedName(dialect)) - .Append(' ') - .Append(column.GetSqlType(dialect, p)); - - string defaultValue = column.DefaultValue; - if (!string.IsNullOrEmpty(defaultValue)) + if (uniqueKeys.Count > 1) + { + //deduplicate unique constraints sharing the same columns + //this is needed by Hibernate Annotations since it creates automagically + // unique constraints for the user + var finalUniqueKeys = new Dictionary<string, UniqueKey>(uniqueKeys.Count); + foreach (var entry in uniqueKeys) { - alter.Append(" default ").Append(defaultValue); - - if (column.IsNullable) + UniqueKey uk = entry.Value; + IList<Column> _columns = uk.Columns; + bool skip = false; + var tempUks = new Dictionary<string, UniqueKey>(finalUniqueKeys); + foreach (var tUk in tempUks) { - alter.Append(dialect.NullColumnString); + UniqueKey currentUk = tUk.Value; + if (AreSameColumns(currentUk.Columns, _columns)) + { + skip = true; + break; + } } - else + if (!skip) { - alter.Append(" not null"); + finalUniqueKeys[entry.Key] = uk; } } - - bool useUniqueConstraint = column.Unique && dialect.SupportsUnique - && (!column.IsNullable || dialect.SupportsNotNullUnique); - if (useUniqueConstraint) - { - alter.Append(" unique"); + return finalUniqueKeys; } - - if (column.HasCheckConstraint && dialect.SupportsColumnCheck) + else { - alter.Append(" check(").Append(column.CheckConstraint).Append(") "); + return uniqueKeys; } + } + } - string columnComment = column.Comment; - if (columnComment != null) - { - alter.Append(dialect.GetColumnComment(columnComment)); - } + public bool HasPrimaryKey + { + get { return PrimaryKey != null; } + } - results.Add(alter.ToString()); - } + public string Catalog + { + get { return catalog; } + set { catalog = value; } + } - return results.ToArray(); + public string Comment + { + get { return comment; } + set { comment = value; } } + public string Subselect + { + get { return subselect; } + set { subselect = value; } + } + + public IKeyValue IdentifierValue + { + get { return idValue; } + set { idValue = value; } + } + + public bool IsSubselect + { + get { return !string.IsNullOrEmpty(subselect); } + } + + public bool IsPhysicalTable + { + get { return !IsSubselect && !IsAbstractUnionTable; } + } + + public SchemaAction SchemaActions + { + get { return schemaActions; } + set { schemaActions = value; } + } + + public string RowId { get; set; } + + public bool IsSchemaQuoted + { + get { return isSchemaQuoted; } + } + + #region IRelationalModel Members + /// <summary> /// Generates the SQL string to create this Table in the database. /// </summary> @@ -409,13 +330,9 @@ /// </returns> public string SqlCreateString(Dialect.Dialect dialect, IMapping p, string defaultCatalog, string defaultSchema) { - StringBuilder buf = new StringBuilder(HasPrimaryKey - ? - dialect.CreateTableString - : dialect.CreateMultisetTableString) - .Append(' ') - .Append(GetQualifiedName(dialect, defaultCatalog, defaultSchema)) - .Append(" ("); + StringBuilder buf = + new StringBuilder(HasPrimaryKey ? dialect.CreateTableString : dialect.CreateMultisetTableString).Append(' ').Append( + GetQualifiedName(dialect, defaultCatalog, defaultSchema)).Append(" ("); bool identityColumn = idValue != null && idValue.IsIdentityColumn(dialect); @@ -439,8 +356,7 @@ } commaNeeded = true; - buf.Append(col.GetQuotedName(dialect)) - .Append(' '); + buf.Append(col.GetQuotedName(dialect)).Append(' '); if (identityColumn && col.GetQuotedName(dialect).Equals(pkname)) { @@ -449,14 +365,13 @@ { buf.Append(col.GetSqlType(dialect, p)); } - buf.Append(' ') - .Append(dialect.GetIdentityColumnString(col.GetSqlTypeCode(p).DbType)); + buf.Append(' ').Append(dialect.GetIdentityColumnString(col.GetSqlTypeCode(p).DbType)); } else { buf.Append(col.GetSqlType(dialect, p)); - if(string.IsNullOrEmpty(col.DefaultValue)==false) + if (!string.IsNullOrEmpty(col.DefaultValue)) { buf.Append(" default ").Append(col.DefaultValue).Append(" "); } @@ -484,14 +399,12 @@ } } - if(col.HasCheckConstraint && dialect.SupportsColumnCheck) + if (col.HasCheckConstraint && dialect.SupportsColumnCheck) { - buf.Append(" check( ") - .Append(col.CheckConstraint) - .Append(") "); + buf.Append(" check( ").Append(col.CheckConstraint).Append(") "); } - if(string.IsNullOrEmpty(col.Comment)==false) + if (string.IsNullOrEmpty(col.Comment) == false) { buf.Append(dialect.GetColumnComment(col.Comment)); } @@ -505,20 +418,18 @@ { buf.Append(',').Append(uk.SqlConstraintString(dialect)); } - - if(dialect.SupportsTableCheck) + + if (dialect.SupportsTableCheck) { foreach (string checkConstraint in checkConstraints) { - buf.Append(", check (") - .Append(checkConstraint) - .Append(") "); + buf.Append(", check (").Append(checkConstraint).Append(") "); } } buf.Append(StringHelper.ClosedParen); - if(string.IsNullOrEmpty(comment)==false) + if (string.IsNullOrEmpty(comment) == false) { buf.Append(dialect.GetTableComment(comment)); } @@ -541,28 +452,204 @@ return dialect.GetDropTableString(GetQualifiedName(dialect, defaultCatalog, defaultSchema)); } + #endregion + /// <summary> - /// Gets or sets the <see cref="PrimaryKey"/> of the Table. + /// Gets the schema qualified name of the Table. /// </summary> - /// <value>The <see cref="PrimaryKey"/> of the Table.</value> - public virtual PrimaryKey PrimaryKey + /// <param name="dialect">The <see cref="Dialect"/> that knows how to Quote the Table name.</param> + /// <returns>The name of the table qualified with the schema if one is specified.</returns> + public string GetQualifiedName(Dialect.Dialect dialect) { - get { return primaryKey; } - set { primaryKey = value; } + return GetQualifiedName(dialect, null, null); } /// <summary> + /// Gets the schema qualified name of the Table using the specified qualifier + /// </summary> + /// <param name="dialect">The <see cref="Dialect"/> that knows how to Quote the Table name.</param> + /// <param name="defaultCatalog">The catalog name.</param> + /// <param name="defaultSchema">The schema name.</param> + /// <returns>A String representing the Qualified name.</returns> + /// <remarks>If this were used with MSSQL it would return a dbo.table_name.</remarks> + public virtual string GetQualifiedName(Dialect.Dialect dialect, string defaultCatalog, string defaultSchema) + { + if (!string.IsNullOrEmpty(subselect)) + { + return "( " + subselect + " )"; + } + string quotedName = GetQuotedName(dialect); + string usedSchema = schema == null ? defaultSchema : GetQuotedSchema(dialect); + string usedCatalog = catalog ?? defaultCatalog; + return dialect.Qualify(usedCatalog, usedSchema, quotedName); + } + + /// <summary> returns quoted name as it would be in the mapping file.</summary> + public string GetQuotedName() + { + return quoted ? "`" + name + "`" : name; + } + + /// <summary> + /// Gets the name of this Table in quoted form if it is necessary. + /// </summary> + /// <param name="dialect"> + /// The <see cref="Dialect.Dialect"/> that knows how to quote the Table name. + /// </param> + /// <returns> + /// The Table name in a form that is safe to use inside of a SQL statement. + /// Quoted if it needs to be, not quoted if it does not need to be. + /// </returns> + public string GetQuotedName(Dialect.Dialect dialect) + { + return IsQuoted ? dialect.QuoteForTableName(name) : name; + } + + /// <summary> returns quoted name as it is in the mapping file.</summary> + public string GetQuotedSchema() + { + return IsSchemaQuoted ? "`" + schema + "`" : schema; + } + + public string GetQuotedSchema(Dialect.Dialect dialect) + { + return IsSchemaQuoted ? dialect.OpenQuote + schema + dialect.CloseQuote : schema; + } + + /// <summary> + /// Gets the schema for this table in quoted form if it is necessary. + /// </summary> + /// <param name="dialect"> + /// The <see cref="Dialect.Dialect" /> that knows how to quote the table name. + /// </param> + /// <returns> + /// The schema name for this table in a form that is safe to use inside + /// of a SQL statement. Quoted if it needs to be, not quoted if it does not need to be. + /// </returns> + public string GetQuotedSchemaName(Dialect.Dialect dialect) + { + if (schema == null) + { + return null; + } + + if (schema.StartsWith("`")) + { + return dialect.QuoteForSchemaName(schema.Substring(1, schema.Length - 2)); + } + + return schema; + } + + /// <summary> + /// Gets the <see cref="Column"/> at the specified index. + /// </summary> + /// <param name="n">The index of the Column to get.</param> + /// <returns> + /// The <see cref="Column"/> at the specified index. + /// </returns> + public Column GetColumn(int n) + { + IEnumerator<Column> iter = columns.Values.GetEnumerator(); + for (int i = 0; i < n; i++) + { + iter.MoveNext(); + } + return iter.Current; + } + + /// <summary> + /// Adds the <see cref="Column"/> to the <see cref="ICollection"/> of + /// Columns that are part of the Table. + /// </summary> + /// <param name="column">The <see cref="Column"/> to include in the Table.</param> + public void AddColumn(Column column) + { + Column old = GetColumn(column); + if (old == null) + { + columns[column.CanonicalName] = column; + column.uniqueInteger = columns.Count; + } + else + { + column.uniqueInteger = old.uniqueInteger; + } + } + + public string[] SqlAlterStrings(Dialect.Dialect dialect, IMapping p, ITableMetadata tableInfo, string defaultCatalog, + string defaultSchema) + { + StringBuilder root = + new StringBuilder("alter table ").Append(GetQualifiedName(dialect, defaultCatalog, defaultSchema)).Append(' '). + Append(dialect.AddColumnString); + + var results = new List<string>(ColumnSpan); + + foreach (Column column in ColumnIterator) + { + IColumnMetadata columnInfo = tableInfo.GetColumnMetadata(column.Name); + if (columnInfo != null) + { + continue; + } + + // the column doesnt exist at all. + StringBuilder alter = + new StringBuilder(root.ToString()).Append(' ').Append(column.GetQuotedName(dialect)).Append(' ').Append( + column.GetSqlType(dialect, p)); + + string defaultValue = column.DefaultValue; + if (!string.IsNullOrEmpty(defaultValue)) + { + alter.Append(" default ").Append(defaultValue); + + if (column.IsNullable) + { + alter.Append(dialect.NullColumnString); + } + else + { + alter.Append(" not null"); + } + } + + bool useUniqueConstraint = column.Unique && dialect.SupportsUnique + && (!column.IsNullable || dialect.SupportsNotNullUnique); + if (useUniqueConstraint) + { + alter.Append(" unique"); + } + + if (column.HasCheckConstraint && dialect.SupportsColumnCheck) + { + alter.Append(" check(").Append(column.CheckConstraint).Append(") "); + } + + string columnComment = column.Comment; + if (columnComment != null) + { + alter.Append(dialect.GetColumnComment(columnComment)); + } + + results.Add(alter.ToString()); + } + + return results.ToArray(); + } + + /// <summary> /// Gets the <see cref="Index"/> identified by the name. /// </summary> - /// <param name="name">The name of the <see cref="Index"/> to get.</param> + /// <param name="indexName">The name of the <see cref="Index"/> to get.</param> /// <returns> /// The <see cref="Index"/> identified by the name. If the <see cref="Index"/> /// identified by the name does not exist then it is created. /// </returns> - public Index GetIndex(string name) + public Index GetIndex(string indexName) { Index result; - indexes.TryGetValue(name, out result); + indexes.TryGetValue(indexName, out result); return result; } @@ -593,15 +680,15 @@ /// <summary> /// Gets the <see cref="UniqueKey"/> identified by the name. /// </summary> - /// <param name="name">The name of the <see cref="UniqueKey"/> to get.</param> + /// <param name="keyName">The name of the <see cref="UniqueKey"/> to get.</param> /// <returns> /// The <see cref="UniqueKey"/> identified by the name. If the <see cref="UniqueKey"/> /// identified by the name does not exist then it is created. /// </returns> - public UniqueKey GetUniqueKey(string name) + public UniqueKey GetUniqueKey(string keyName) { UniqueKey result; - uniqueKeys.TryGetValue(name, out result); + uniqueKeys.TryGetValue(keyName, out result); return result; } @@ -630,9 +717,7 @@ return uk; } - public virtual void CreateForeignKeys() - { - } + public virtual void CreateForeignKeys() {} public virtual ForeignKey CreateForeignKey(string keyName, IEnumerable<Column> keyColumns, string referencedEntityName) { @@ -654,13 +739,13 @@ /// one already exists for the columns then it will return an /// existing <see cref="ForeignKey"/>. /// </remarks> - public virtual ForeignKey CreateForeignKey(string keyName, IEnumerable<Column> keyColumns, - string referencedEntityName, IEnumerable<Column> referencedColumns) + public virtual ForeignKey CreateForeignKey(string keyName, IEnumerable<Column> keyColumns, string referencedEntityName, + IEnumerable<Column> referencedColumns) { IEnumerable<Column> kCols = keyColumns; IEnumerable<Column> refCols = referencedColumns; - ForeignKeyKey key = new ForeignKeyKey(kCols, referencedEntityName, refCols); + var key = new ForeignKeyKey(kCols, referencedEntityName, refCols); ForeignKey fk; foreignKeys.TryGetValue(key, out fk); @@ -707,13 +792,13 @@ /// Generates a unique string for an <see cref="ICollection"/> of /// <see cref="Column"/> objects. /// </summary> - /// <param name="columns">An <see cref="ICollection"/> of <see cref="Column"/> objects.</param> + /// <param name="uniqueColumns">An <see cref="ICollection"/> of <see cref="Column"/> objects.</param> /// <returns> /// An unique string for the <see cref="Column"/> objects. /// </returns> - public string UniqueColumnString(IEnumerable columns) + public string UniqueColumnString(IEnumerable uniqueColumns) { - return UniqueColumnString(columns, null); + return UniqueColumnString(uniqueColumns, null); } public string UniqueColumnString(IEnumerable iterator, string referencedEntityName) @@ -721,7 +806,9 @@ // NH Different implementation (NH-1339) int result = 37; if (referencedEntityName != null) + { result ^= referencedEntityName.GetHashCode(); + } foreach (object o in iterator) { @@ -731,57 +818,15 @@ } /// <summary> - /// Gets or sets the schema the table is in. - /// </summary> - /// <value> - /// The schema the table is in or <see langword="null" /> if no schema is specified. - /// </value> - public string Schema - { - get{return schema;} - set - { - if (value != null && value[0] == '`') - { - isSchemaQuoted = true; - schema = value.Substring(1, value.Length - 2); - } - else - { - schema = value; - } - } - } - - /// <summary> - /// Gets the unique number of the Table. - /// </summary> - /// <value>The unique number of the Table.</value> - public int UniqueInteger - { - get { return uniqueInteger; } - } - - /// <summary> /// Sets the Identifier of the Table. /// </summary> - /// <param name="idValue">The <see cref="SimpleValue"/> that represents the Identifier.</param> - public void SetIdentifierValue(SimpleValue idValue) + /// <param name="identifierValue">The <see cref="SimpleValue"/> that represents the Identifier.</param> + public void SetIdentifierValue(SimpleValue identifierValue) { - this.idValue = idValue; + idValue = identifierValue; } /// <summary> - /// Gets or sets if the column needs to be quoted in SQL statements. - /// </summary> - /// <value><see langword="true" /> if the column is quoted.</value> - public bool IsQuoted - { - get { return quoted; } - set { quoted = value; } - } - - /// <summary> /// /// </summary> /// <param name="constraint"></param> @@ -790,32 +835,11 @@ checkConstraints.Add(constraint); } - public IEnumerable<string> CheckConstraintsIterator - { - get { return checkConstraints; } - } - - public bool IsAbstractUnionTable - { - get { return HasDenormalizedTables && isAbstract; } - } - - public bool HasDenormalizedTables - { - get { return hasDenormalizedTables; } - } - internal void SetHasDenormalizedTables() { hasDenormalizedTables = true; } - public bool IsAbstract - { - get { return isAbstract; } - set { isAbstract = value; } - } - public virtual bool ContainsColumn(Column column) { return columns.ContainsValue(column); @@ -830,7 +854,9 @@ public virtual Column GetColumn(Column column) { if (column == null) + { return null; + } Column result; columns.TryGetValue(column.CanonicalName, out result); @@ -838,131 +864,39 @@ return column.Equals(result) ? result : null; } - internal IDictionary<string, UniqueKey> UniqueKeys - { - get - { - if (uniqueKeys.Count > 1) - { - //deduplicate unique constraints sharing the same columns - //this is needed by Hibernate Annotations since it creates automagically - // unique constraints for the user - Dictionary<string, UniqueKey> finalUniqueKeys = new Dictionary<string, UniqueKey>(uniqueKeys.Count); - foreach (KeyValuePair<string, UniqueKey> entry in uniqueKeys) - { - UniqueKey uk = entry.Value; - IList<Column> _columns = uk.Columns; - bool skip = false; - Dictionary<string, UniqueKey> tempUks = new Dictionary<string, UniqueKey>(finalUniqueKeys); - foreach (KeyValuePair<string, UniqueKey> tUk in tempUks) - { - UniqueKey currentUk = tUk.Value; - if (AreSameColumns(currentUk.Columns, _columns)) - { - skip = true; - break; - } - } - if (!skip) - finalUniqueKeys[entry.Key] = uk; - } - return finalUniqueKeys; - } - else - { - return uniqueKeys; - } - } - } - private static bool AreSameColumns(ICollection<Column> col1, ICollection<Column> col2) { - if(col1.Count!=col2.Count) + if (col1.Count != col2.Count) + { return false; - bool result= true; + } foreach (Column column in col1) { - if(!col2.Contains(column)) + if (!col2.Contains(column)) + { return false; + } } foreach (Column column in col2) { if (!col1.Contains(column)) + { return false; + } } - return result; + return true; } - public bool HasPrimaryKey - { - get { return PrimaryKey != null; } - } - - public string Catalog - { - get { return catalog; } - set { catalog = value; } - } - - public string Comment - { - get { return comment; } - set { comment = value; } - } - - public string Subselect - { - get { return subselect; } - set { subselect = value; } - } - - public IKeyValue IdentifierValue - { - get { return idValue; } - set { idValue = value; } - } - - public bool IsSubselect - { - get { return !string.IsNullOrEmpty(subselect); } - } - - public bool IsPhysicalTable - { - get { return !IsSubselect && !IsAbstractUnionTable; } - } - - public SchemaAction SchemaActions - { - get { return schemaActions; } - set { schemaActions = value; } - } - - public string RowId - { - get { return rowId; } - set { rowId = value; } - } - - public bool IsSchemaQuoted - { - get { return isSchemaQuoted; } - } - public virtual string[] SqlCommentStrings(Dialect.Dialect dialect, string defaultCatalog, string defaultSchema) { - List<string> comments = new List<string>(); + var comments = new List<string>(); if (dialect.SupportsCommentOn) { string tableName = GetQualifiedName(dialect, defaultCatalog, defaultSchema); if (!string.IsNullOrEmpty(comment)) { - StringBuilder buf = new StringBuilder() - .Append("comment on table ") - .Append(tableName) - .Append(" is '") - .Append(comment) - .Append("'"); + StringBuilder buf = + new StringBuilder().Append("comment on table ").Append(tableName).Append(" is '").Append(comment).Append("'"); comments.Add(buf.ToString()); } foreach (Column column in ColumnIterator) @@ -970,13 +904,9 @@ string columnComment = column.Comment; if (columnComment != null) { - StringBuilder buf = new StringBuilder() - .Append("comment on column ") - .Append(tableName) - .Append('.') - .Append(column.GetQuotedName(dialect)) - .Append(" is '") - .Append(columnComment).Append("'"); + StringBuilder buf = + new StringBuilder().Append("comment on column ").Append(tableName).Append('.').Append( + column.GetQuotedName(dialect)).Append(" is '").Append(columnComment).Append("'"); comments.Add(buf.ToString()); } } @@ -986,19 +916,17 @@ public virtual string SqlTemporaryTableCreateString(Dialect.Dialect dialect, IMapping mapping) { - StringBuilder buffer = new StringBuilder(dialect.CreateTemporaryTableString) - .Append(' ') - .Append(name) - .Append(" ("); + StringBuilder buffer = new StringBuilder(dialect.CreateTemporaryTableString).Append(' ').Append(name).Append(" ("); bool commaNeeded = false; foreach (Column column in ColumnIterator) { - buffer.Append(column.GetQuotedName(dialect)) - .Append(' '); + buffer.Append(column.GetQuotedName(dialect)).Append(' '); buffer.Append(column.GetSqlType(dialect, mapping)); if (commaNeeded) + { buffer.Append(StringHelper.CommaSpace); + } commaNeeded = true; if (column.IsNullable) @@ -1018,9 +946,7 @@ public override string ToString() { - StringBuilder buf = new StringBuilder() - .Append(GetType().FullName) - .Append('('); + StringBuilder buf = new StringBuilder().Append(GetType().FullName).Append('('); if (Catalog != null) { buf.Append(Catalog + "."); @@ -1035,37 +961,36 @@ public void ValidateColumns(Dialect.Dialect dialect, IMapping mapping, ITableMetadata tableInfo) { - var iter = this.ColumnIterator; - foreach (var column in iter) + IEnumerable<Column> iter = ColumnIterator; + foreach (Column column in iter) { + IColumnMetadata columnInfo = tableInfo.GetColumnMetadata(column.Name); - var columnInfo = tableInfo.GetColumnMetadata(column.Name); - if (columnInfo == null) + { throw new HibernateException(string.Format("Missing column: {0} in {1}", column.Name, - Table.Qualify(tableInfo.Catalog, tableInfo.Schema, tableInfo.Name))); + Qualify(tableInfo.Catalog, tableInfo.Schema, tableInfo.Name))); + } else { //TODO: Add new method to ColumnMetadata :getTypeCode - bool typesMatch = column.GetSqlType(dialect, mapping).ToLower() - .StartsWith(columnInfo.TypeName.ToLower()) - ; //|| columnInfo.get() == column.GetSqlTypeCode(mapping); + bool typesMatch = column.GetSqlType(dialect, mapping).ToLower().StartsWith(columnInfo.TypeName.ToLower()); + //|| columnInfo.get() == column.GetSqlTypeCode(mapping); if (!typesMatch) { - throw new HibernateException( - string.Format("Wrong column type in {0} for column {1}. Found: {2}, Expected {3}", - Table.Qualify(tableInfo.Catalog, tableInfo.Schema, tableInfo.Name), - column.Name, columnInfo.TypeName.ToLower(), column.GetSqlType(dialect, mapping))); + throw new HibernateException(string.Format("Wrong column type in {0} for column {1}. Found: {2}, Expected {3}", + Qualify(tableInfo.Catalog, tableInfo.Schema, tableInfo.Name), + column.Name, columnInfo.TypeName.ToLower(), + column.GetSqlType(dialect, mapping))); } } } - } public static string Qualify(string catalog, string schema, string table) { - StringBuilder qualifiedName = new StringBuilder(100); + var qualifiedName = new StringBuilder(100); if (catalog != null) { qualifiedName.Append(catalog).Append('.'); @@ -1076,5 +1001,66 @@ } return qualifiedName.Append(table).ToString(); } + + #region Nested type: ForeignKeyKey + + internal class ForeignKeyKey : IEqualityComparer<ForeignKeyKey> + { + internal List<Column> columns; + internal string referencedClassName; + internal List<Column> referencedColumns; + + internal ForeignKeyKey(IEnumerable<Column> columns, string referencedClassName, IEnumerable<Column> referencedColumns) + { + this.referencedClassName = referencedClassName; + this.columns = new List<Column>(columns); + if (referencedColumns != null) + { + this.referencedColumns = new List<Column>(referencedColumns); + } + else + { + this.referencedColumns = new List<Column>(); + } + } + + #region IEqualityComparer<ForeignKeyKey> Members + + public bool Equals(ForeignKeyKey x, ForeignKeyKey y) + { + // NH : Different implementation to prevent NH930 (look test) + return //y.referencedClassName.Equals(x.referencedClassName) && + CollectionHelper.CollectionEquals<Column>(y.columns, x.columns) + && CollectionHelper.CollectionEquals<Column>(y.referencedColumns, x.referencedColumns); + } + + public int GetHashCode(ForeignKeyKey obj) + { + int result = CollectionHelper.GetHashCode(obj.columns) ^ CollectionHelper.GetHashCode(obj.referencedColumns); + return result; + } + + #endregion + + public override int GetHashCode() + { + return GetHashCode(this); + } + + public override bool Equals(object other) + { + var that = other as ForeignKeyKey; + if (that != null) + { + return Equals(this, that); + } + else + { + return false; + } + } + } + + #endregion } -} +} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-12-16 20:16:20
|
Revision: 3959 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3959&view=rev Author: fabiomaulo Date: 2008-12-16 20:16:16 +0000 (Tue, 16 Dec 2008) Log Message: ----------- Refactoring of SchemaAction matters Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs trunk/nhibernate/src/NHibernate/Cfg/Mappings.cs trunk/nhibernate/src/NHibernate/Mapping/Table.cs trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaExport.cs trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaUpdate.cs trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaValidator.cs Modified: trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs 2008-12-16 18:39:12 UTC (rev 3958) +++ trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs 2008-12-16 20:16:16 UTC (rev 3959) @@ -671,11 +671,11 @@ { foreach (var table in TableMappings) { - if (table.IsPhysicalTable && table.SchemaDrop) + if (table.IsPhysicalTable && IncludeAction(table.SchemaActions, SchemaAction.Drop)) { foreach (var fk in table.ForeignKeyIterator) { - if (fk.HasPhysicalConstraint && fk.ReferencedTable.SchemaDrop) + if (fk.HasPhysicalConstraint && IncludeAction(fk.ReferencedTable.SchemaActions, SchemaAction.Drop)) { script.Add(fk.SqlDropString(dialect, defaultCatalog, defaultSchema)); } @@ -686,7 +686,7 @@ foreach (var table in TableMappings) { - if (table.IsPhysicalTable && table.SchemaDrop) + if (table.IsPhysicalTable && IncludeAction(table.SchemaActions, SchemaAction.Drop)) { script.Add(table.SqlDropString(dialect, defaultCatalog, defaultSchema)); } @@ -708,6 +708,11 @@ return script.ToArray(); } + public static bool IncludeAction(SchemaAction actionsSource, SchemaAction includedAction) + { + return (actionsSource & includedAction) != SchemaAction.None; + } + /// <summary> /// Generate DDL for creating tables /// </summary> @@ -723,7 +728,7 @@ foreach (var table in TableMappings) { - if (table.IsPhysicalTable && table.SchemaExport) + if (table.IsPhysicalTable && IncludeAction(table.SchemaActions, SchemaAction.Export)) { script.Add(table.SqlCreateString(dialect, mapping, defaultCatalog, defaultSchema)); script.AddRange(table.SqlCommentStrings(dialect, defaultCatalog, defaultSchema)); @@ -732,7 +737,7 @@ foreach (var table in TableMappings) { - if (table.IsPhysicalTable && table.SchemaExport) + if (table.IsPhysicalTable && IncludeAction(table.SchemaActions, SchemaAction.Export)) { if (!dialect.SupportsUniqueConstraintInCreateAlterTable) { @@ -755,7 +760,7 @@ { foreach (var fk in table.ForeignKeyIterator) { - if (fk.HasPhysicalConstraint && fk.ReferencedTable.SchemaExport) + if (fk.HasPhysicalConstraint && IncludeAction(fk.ReferencedTable.SchemaActions, SchemaAction.Export)) { script.Add(fk.SqlCreateString(dialect, mapping, defaultCatalog, defaultSchema)); } @@ -1920,7 +1925,7 @@ var script = new List<string>(50); foreach (var table in TableMappings) { - if (table.IsPhysicalTable && table.SchemaUpdate) + if (table.IsPhysicalTable && IncludeAction(table.SchemaActions, SchemaAction.Update)) { ITableMetadata tableInfo = databaseMetadata.GetTableMetadata(table.Name, table.Schema ?? defaultSchema, table.Catalog ?? defaultCatalog, table.IsQuoted); @@ -1941,7 +1946,7 @@ foreach (var table in TableMappings) { - if (table.IsPhysicalTable && table.SchemaUpdate) + if (table.IsPhysicalTable && IncludeAction(table.SchemaActions, SchemaAction.Update)) { ITableMetadata tableInfo = databaseMetadata.GetTableMetadata(table.Name, table.Schema, table.Catalog, table.IsQuoted); @@ -1950,7 +1955,7 @@ { foreach (var fk in table.ForeignKeyIterator) { - if (fk.HasPhysicalConstraint && fk.ReferencedTable.SchemaUpdate) + if (fk.HasPhysicalConstraint && IncludeAction(fk.ReferencedTable.SchemaActions, SchemaAction.Update)) { bool create = tableInfo == null || @@ -1997,10 +2002,10 @@ string defaultCatalog = PropertiesHelper.GetString(Environment.DefaultCatalog, properties, null); string defaultSchema = PropertiesHelper.GetString(Environment.DefaultSchema, properties, null); - var iter = this.TableMappings; + var iter = TableMappings; foreach (var table in iter) { - if (table.IsPhysicalTable && table.SchemaValidate) + if (table.IsPhysicalTable && IncludeAction(table.SchemaActions, SchemaAction.Validate)) { /*NH Different Implementation : TableMetadata tableInfo = databaseMetadata.getTableMetadata( @@ -2011,7 +2016,7 @@ ITableMetadata tableInfo = databaseMetadata.GetTableMetadata( table.Name, table.Schema??defaultSchema, - table.Catalog,//??defaultCatalog, + table.Catalog??defaultCatalog, table.IsQuoted); if (tableInfo == null) throw new HibernateException("Missing table: " + table.Name); Modified: trunk/nhibernate/src/NHibernate/Cfg/Mappings.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/Mappings.cs 2008-12-16 18:39:12 UTC (rev 3958) +++ trunk/nhibernate/src/NHibernate/Cfg/Mappings.cs 2008-12-16 20:16:16 UTC (rev 3959) @@ -258,10 +258,7 @@ table.Schema = schema; table.Catalog = catalog; table.Subselect = subselect; - table.SchemaDrop = SchemaActionRequested(schemaAction, "drop"); - table.SchemaUpdate = SchemaActionRequested(schemaAction, "update"); - table.SchemaExport = SchemaActionRequested(schemaAction, "export"); - table.SchemaValidate = SchemaActionRequested(schemaAction, "validate"); + table.SchemaActions = GetSchemaActions(schemaAction); tables[key] = table; } else @@ -273,9 +270,46 @@ return table; } - private static bool SchemaActionRequested(string schemaAction, string check) + private static SchemaAction GetSchemaActions(string schemaAction) { - return string.IsNullOrEmpty(schemaAction) || schemaAction.Contains("all") || schemaAction.Contains(check); + if (string.IsNullOrEmpty(schemaAction)) + { + return SchemaAction.All; + } + else + { + SchemaAction sa = SchemaAction.None; + string[] acts = schemaAction.Split(new[] {',', ' '}); + foreach (var s in acts) + { + switch (s.ToLowerInvariant()) + { + case "": + case "all": + sa |= SchemaAction.All; + break; + case "drop": + sa |= SchemaAction.Drop; + break; + case "update": + sa |= SchemaAction.Update; + break; + case "export": + sa |= SchemaAction.Export; + break; + case "validate": + sa |= SchemaAction.Validate; + break; + case "none": + sa |= SchemaAction.None; + break; + default: + throw new MappingException( + string.Format("Invalid schema-export value; Expected(all drop update export validate none), Found ({0})", s)); + } + } + return sa; + } } public Table AddDenormalizedTable(string schema, string catalog, string name, bool isAbstract, string subselect, Table includedTable) Modified: trunk/nhibernate/src/NHibernate/Mapping/Table.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Mapping/Table.cs 2008-12-16 18:39:12 UTC (rev 3958) +++ trunk/nhibernate/src/NHibernate/Mapping/Table.cs 2008-12-16 20:16:16 UTC (rev 3959) @@ -9,6 +9,17 @@ namespace NHibernate.Mapping { + [Flags] + public enum SchemaAction + { + None = 0, + Drop = 1, + Update= 2, + Export= 4, + Validate= 8, + All = Drop | Update | Export | Validate + } + /// <summary> /// Represents a Table in a database that an object gets mapped against. /// </summary> @@ -84,10 +95,7 @@ private string subselect; private string rowId; private bool isSchemaQuoted; - private bool schemaDrop = true; - private bool schemaUpdate = true; - private bool schemaExport = true; - private bool schemaValidate = true; + private SchemaAction schemaActions = SchemaAction.All; /// <summary> @@ -924,30 +932,12 @@ get { return !IsSubselect && !IsAbstractUnionTable; } } - public bool SchemaDrop + public SchemaAction SchemaActions { - get { return schemaDrop; } - set { schemaDrop = value; } + get { return schemaActions; } + set { schemaActions = value; } } - public bool SchemaUpdate - { - get { return schemaUpdate; } - set { schemaUpdate = value; } - } - - public bool SchemaExport - { - get { return schemaExport; } - set { schemaExport = value; } - } - - public bool SchemaValidate - { - get { return schemaValidate; } - set { schemaValidate = value; } - } - public string RowId { get { return rowId; } Modified: trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaExport.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaExport.cs 2008-12-16 18:39:12 UTC (rev 3958) +++ trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaExport.cs 2008-12-16 20:16:16 UTC (rev 3959) @@ -19,23 +19,19 @@ /// </remarks> public class SchemaExport { - private readonly string[] dropSQL; - private readonly string[] createSQL; + private static readonly ILog log = LogManager.GetLogger(typeof (SchemaExport)); private readonly IDictionary<string, string> connectionProperties; - private string outputFile = null; + private readonly string[] createSQL; private readonly Dialect.Dialect dialect; - private string delimiter = null; + private readonly string[] dropSQL; + private string delimiter; + private string outputFile; - private static readonly ILog log = LogManager.GetLogger(typeof(SchemaExport)); - /// <summary> /// Create a schema exported for a given Configuration /// </summary> /// <param name="cfg">The NHibernate Configuration to generate the schema from.</param> - public SchemaExport(Configuration cfg) - : this(cfg, cfg.Properties) - { - } + public SchemaExport(Configuration cfg) : this(cfg, cfg.Properties) {} /// <summary> /// Create a schema exporter for the given Configuration, with the given @@ -107,7 +103,7 @@ } private void Execute(Action<string> scriptAction, bool export, bool format, bool throwOnError, TextWriter exportOutput, - IDbCommand statement, string sql) + IDbCommand statement, string sql) { try { @@ -169,8 +165,8 @@ /// This overload is provided mainly to enable use of in memory databases. /// It does NOT close the given connection! /// </remarks> - public void Execute(bool script, bool export, bool justDrop, bool format, - IDbConnection connection, TextWriter exportOutput) + public void Execute(bool script, bool export, bool justDrop, bool format, IDbConnection connection, + TextWriter exportOutput) { if (script) { @@ -182,8 +178,8 @@ } } - public void Execute(Action<string> scriptAction, bool export, bool justDrop, bool format, - IDbConnection connection, TextWriter exportOutput) + public void Execute(Action<string> scriptAction, bool export, bool justDrop, bool format, IDbConnection connection, + TextWriter exportOutput) { IDbCommand statement = null; @@ -236,10 +232,8 @@ } } } - } - /// <summary> /// Executes the Export of the Schema. /// </summary> @@ -261,21 +255,22 @@ Execute(null, export, justDrop, format); } } + public void Execute(Action<string> scriptAction, bool export, bool justDrop, bool format) { IDbConnection connection = null; StreamWriter fileOutput = null; IConnectionProvider connectionProvider = null; - Dictionary<string, string> props = new Dictionary<string, string>(); - foreach (KeyValuePair<string, string> de in dialect.DefaultProperties) + var props = new Dictionary<string, string>(); + foreach (var de in dialect.DefaultProperties) { props[de.Key] = de.Value; } if (connectionProperties != null) { - foreach (KeyValuePair<string, string> de in connectionProperties) + foreach (var de in connectionProperties) { props[de.Key] = de.Value; } @@ -314,7 +309,6 @@ connectionProvider.Dispose(); } } - } /// <summary> @@ -350,8 +344,8 @@ if (StringHelper.StartsWithCaseInsensitive(sql, "create table")) { - StringBuilder result = new StringBuilder(60); - StringTokenizer tokens = new StringTokenizer(sql, "(,)", true); + var result = new StringBuilder(60); + var tokens = new StringTokenizer(sql, "(,)", true); int depth = 0; Modified: trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaUpdate.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaUpdate.cs 2008-12-16 18:39:12 UTC (rev 3958) +++ trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaUpdate.cs 2008-12-16 20:16:16 UTC (rev 3959) @@ -8,26 +8,22 @@ namespace NHibernate.Tool.hbm2ddl { - public class SchemaUpdate { - private static readonly ILog log = LogManager.GetLogger(typeof(SchemaUpdate)); - private readonly IConnectionHelper connectionHelper; + private static readonly ILog log = LogManager.GetLogger(typeof (SchemaUpdate)); private readonly Configuration configuration; + private readonly IConnectionHelper connectionHelper; private readonly Dialect.Dialect dialect; private readonly List<Exception> exceptions; - public SchemaUpdate(Configuration cfg) - : this(cfg, cfg.Properties) - { - } + public SchemaUpdate(Configuration cfg) : this(cfg, cfg.Properties) {} public SchemaUpdate(Configuration cfg, IDictionary<string, string> connectionProperties) { configuration = cfg; - dialect = NHibernate.Dialect.Dialect.GetDialect(connectionProperties); - Dictionary<string, string> props = new Dictionary<string, string>(dialect.DefaultProperties); - foreach (KeyValuePair<string, string> prop in connectionProperties) + dialect = Dialect.Dialect.GetDialect(connectionProperties); + var props = new Dictionary<string, string>(dialect.DefaultProperties); + foreach (var prop in connectionProperties) { props[prop.Key] = prop.Value; } @@ -39,17 +35,24 @@ { configuration = cfg; dialect = settings.Dialect; - connectionHelper = new SuppliedConnectionProviderConnectionHelper( - settings.ConnectionProvider - ); + connectionHelper = new SuppliedConnectionProviderConnectionHelper(settings.ConnectionProvider); exceptions = new List<Exception>(); } + /// <summary> + /// Returns a List of all Exceptions which occured during the export. + /// </summary> + /// <returns></returns> + public IList<Exception> Exceptions + { + get { return exceptions; } + } + public static void Main(string[] args) { try { - Configuration cfg = new Configuration(); + var cfg = new Configuration(); bool script = true; // If true then execute db updates, otherwise just generate and display updates @@ -80,8 +83,7 @@ else if (args[i].StartsWith("--naming=")) { cfg.SetNamingStrategy( - (INamingStrategy)Activator.CreateInstance(ReflectHelper.ClassForName(args[i].Substring(9))) - ); + (INamingStrategy) Activator.CreateInstance(ReflectHelper.ClassForName(args[i].Substring(9)))); } } else @@ -204,14 +206,5 @@ } } } - - /// <summary> - /// Returns a List of all Exceptions which occured during the export. - /// </summary> - /// <returns></returns> - public IList<Exception> Exceptions - { - get { return exceptions; } - } } -} +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaValidator.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaValidator.cs 2008-12-16 18:39:12 UTC (rev 3958) +++ trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaValidator.cs 2008-12-16 20:16:16 UTC (rev 3959) @@ -1,11 +1,7 @@ using System; using System.Collections.Generic; -using System.Data; using System.Data.Common; -using System.Data.SqlClient; -using System.Text; using log4net; -using log4net.Repository.Hierarchy; using NHibernate.Cfg; using NHibernate.Util; @@ -13,30 +9,28 @@ { public class SchemaValidator { - - private static readonly ILog log = LogManager.GetLogger(typeof(SchemaValidator)); - private readonly IConnectionHelper connectionHelper; + private static readonly ILog log = LogManager.GetLogger(typeof (SchemaValidator)); private readonly Configuration configuration; - private Dialect.Dialect dialect; + private readonly IConnectionHelper connectionHelper; + private readonly Dialect.Dialect dialect; - public SchemaValidator(Configuration cfg) : - this(cfg, cfg.Properties) - { - } + public SchemaValidator(Configuration cfg) : this(cfg, cfg.Properties) {} public SchemaValidator(Configuration cfg, IDictionary<string, string> connectionProperties) { - this.configuration = cfg; + configuration = cfg; dialect = Dialect.Dialect.GetDialect(connectionProperties); IDictionary<string, string> props = new Dictionary<string, string>(dialect.DefaultProperties); foreach (var prop in connectionProperties) + { props[prop.Key] = prop.Value; + } connectionHelper = new ManagedProviderConnectionHelper(props); } public SchemaValidator(Configuration cfg, Settings settings) { - this.configuration = cfg; + configuration = cfg; dialect = settings.Dialect; connectionHelper = new SuppliedConnectionProviderConnectionHelper(settings.ConnectionProvider); } @@ -45,33 +39,33 @@ { try { - Configuration cfg = new Configuration(); + var cfg = new Configuration(); - String propFile = null; + //string propFile = null; for (int i = 0; i < args.Length; i++) { if (args[i].StartsWith("--")) { - if (args[i].StartsWith("--properties=")) + //if (args[i].StartsWith("--properties=")) + //{ + // propFile = args[i].Substring(13); + //} + //else + if (args[i].StartsWith("--config=")) { - propFile = args[i].Substring(13); - } - else if (args[i].StartsWith("--config=")) - { cfg.Configure(args[i].Substring(9)); } else if (args[i].StartsWith("--naming=")) { cfg.SetNamingStrategy( - (INamingStrategy)Activator.CreateInstance(ReflectHelper.ClassForName(args[i].Substring(9)))); + (INamingStrategy) Activator.CreateInstance(ReflectHelper.ClassForName(args[i].Substring(9)))); } } else { cfg.AddFile(args[i]); } - } /* NH: No props file for .NET if ( propFile != null ) { @@ -93,32 +87,31 @@ /** * Perform the validations. */ + public void Validate() { log.Info("Running schema validator"); - DbConnection connection = null; try { - DatabaseMetadata meta; try { log.Info("fetching database metadata"); connectionHelper.Prepare(); - connection = connectionHelper.Connection; + DbConnection connection = connectionHelper.Connection; meta = new DatabaseMetadata(connection, dialect, false); } catch (Exception sqle) { log.Error("could not get database metadata", sqle); - throw sqle; + throw; } configuration.ValidateSchema(dialect, meta); } catch (Exception e) { log.Error("could not complete schema validation", e); - throw e; + throw; } finally { @@ -130,8 +123,7 @@ { log.Error("Error closing connection", e); } - } } } -} +} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |