From: <te...@us...> - 2008-11-02 22:03:07
|
Revision: 3885 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3885&view=rev Author: tehlike Date: 2008-11-02 22:02:59 +0000 (Sun, 02 Nov 2008) Log Message: ----------- Adding overload for ConstantProjection(object,IType) (Fix NH-1447) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Criterion/ConstantProjection.cs trunk/nhibernate/src/NHibernate/Criterion/Projections.cs trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1447/ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1447/Fixture.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1447/Mappings.hbm.xml trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1447/Person.cs Modified: trunk/nhibernate/src/NHibernate/Criterion/ConstantProjection.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Criterion/ConstantProjection.cs 2008-11-02 18:28:25 UTC (rev 3884) +++ trunk/nhibernate/src/NHibernate/Criterion/ConstantProjection.cs 2008-11-02 22:02:59 UTC (rev 3885) @@ -13,12 +13,18 @@ public class ConstantProjection : SimpleProjection { private readonly object value; - - public ConstantProjection(object value) + private readonly IType type; + public ConstantProjection(object value):this(value,NHibernateUtil.GuessType(value.GetType())) { + + } + public ConstantProjection(object value,IType type) + { this.value = value; + this.type = type; } + public override bool IsAggregate { get { return false; } @@ -36,7 +42,7 @@ public override SqlString ToSqlString(ICriteria criteria, int position, ICriteriaQuery criteriaQuery, IDictionary<string, IFilter> enabledFilters) { - criteriaQuery.AddUsedTypedValues(new TypedValue[] { new TypedValue(NHibernateUtil.GuessType(value), value, EntityMode.Poco) }); + criteriaQuery.AddUsedTypedValues(new TypedValue[] { new TypedValue(type, value, EntityMode.Poco) }); return new SqlStringBuilder() .AddParameter() .Add(" as ") @@ -46,12 +52,12 @@ public override IType[] GetTypes(ICriteria criteria, ICriteriaQuery criteriaQuery) { - return new IType[] {NHibernateUtil.GuessType(value)}; + return new IType[] { type }; } public override TypedValue[] GetTypedValues(ICriteria criteria, ICriteriaQuery criteriaQuery) { - return new TypedValue[] {new TypedValue(NHibernateUtil.GuessType(value), value, EntityMode.Poco)}; + return new TypedValue[] { new TypedValue(type, value, EntityMode.Poco) }; } } } Modified: trunk/nhibernate/src/NHibernate/Criterion/Projections.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Criterion/Projections.cs 2008-11-02 18:28:25 UTC (rev 3884) +++ trunk/nhibernate/src/NHibernate/Criterion/Projections.cs 2008-11-02 22:02:59 UTC (rev 3885) @@ -253,6 +253,15 @@ return new ConstantProjection(obj); } + /// <summary> + /// Return a constant value + /// </summary> + /// <param name="obj">The obj.</param> + /// <returns></returns> + public static IProjection Constant(object obj,IType type) + { + return new ConstantProjection(obj,type); + } /// <summary> Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1447/Fixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1447/Fixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1447/Fixture.cs 2008-11-02 22:02:59 UTC (rev 3885) @@ -0,0 +1,50 @@ +using System.Collections.Generic; +using NHibernate.Criterion; +using NHibernate.Dialect.Function; +using NUnit.Framework; + +namespace NHibernate.Test.NHSpecificTest.NH1447 +{ + [TestFixture] + public class Fixture : BugTestCase + { + protected override void OnTearDown() + { + base.OnTearDown(); + using (ISession session = OpenSession()) + { + using (ITransaction tx = session.BeginTransaction()) + { + session.Delete("from Person"); + tx.Commit(); + } + } + } + + protected override void OnSetUp() + { + using (ISession s = OpenSession()) + { + using (ITransaction tx = s.BeginTransaction()) + { + var e1 = new Person("Tuna Toksoz",false); + var e2 = new Person("Oguz Kurumlu", true); + s.Save(e1); + tx.Commit(); + } + } + } + + [Test] + public void CanQueryByConstantProjectionWithType() + { + using (ISession s = OpenSession()) + { + ICriteria c = s.CreateCriteria(typeof (Person)) + .Add(Restrictions.EqProperty("WantsNewsletter", Projections.Constant(false,NHibernateUtil.Boolean))); + IList<Person> list = c.List<Person>(); + Assert.AreEqual(1, list.Count); + } + } + } +} Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1447/Mappings.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1447/Mappings.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1447/Mappings.hbm.xml 2008-11-02 22:02:59 UTC (rev 3885) @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="utf-8" ?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" + assembly="NHibernate.Test" + namespace="NHibernate.Test.NHSpecificTest.NH1447"> + + <class name="Person" lazy="false"> + <id name="Id"> + <generator class="native" /> + </id> + <property name="Name"/> + <property name="WantsNewsletter" type="Boolean"/> + </class> +</hibernate-mapping> Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1447/Person.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1447/Person.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1447/Person.cs 2008-11-02 22:02:59 UTC (rev 3885) @@ -0,0 +1,39 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; + +namespace NHibernate.Test.NHSpecificTest.NH1447 +{ + public class Person + { + public Person() + { + + } + + public Person(string name, bool isPerfect) + { + this.Name = name; + this.WantsNewsletter = isPerfect; + } + + public virtual int Id + { get; + set; + } + + public virtual string Name + { + get; + set; + } + public virtual bool WantsNewsletter + { + get; + set; + } + + } + +} Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-11-02 18:28:25 UTC (rev 3884) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-11-02 22:02:59 UTC (rev 3885) @@ -493,6 +493,8 @@ <Compile Include="NHSpecificTest\NH1419\Blog.cs" /> <Compile Include="NHSpecificTest\NH1419\Entry.cs" /> <Compile Include="NHSpecificTest\NH1419\Fixture.cs" /> + <Compile Include="NHSpecificTest\NH1447\Fixture.cs" /> + <Compile Include="NHSpecificTest\NH1447\Person.cs" /> <Compile Include="NHSpecificTest\NH1464\Fixture.cs" /> <Compile Include="NHSpecificTest\NH1483\BaseClass.cs" /> <Compile Include="NHSpecificTest\NH1483\Fixture.cs" /> @@ -1511,6 +1513,7 @@ <EmbeddedResource Include="Cascade\JobBatch.hbm.xml" /> <EmbeddedResource Include="Deletetransient\Person.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> + <EmbeddedResource Include="NHSpecificTest\NH1447\Mappings.hbm.xml" /> <EmbeddedResource Include="TypesTest\EnumCharClass.hbm.xml" /> <EmbeddedResource Include="Extendshbm\packageentitynamesWithColl.hbm.xml" /> <EmbeddedResource Include="Extendshbm\entitynamesWithColl.hbm.xml" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-11-04 12:08:39
|
Revision: 3888 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3888&view=rev Author: fabiomaulo Date: 2008-11-04 12:08:34 +0000 (Tue, 04 Nov 2008) Log Message: ----------- Fix NH-871 (new select generator) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Id/IdentifierGeneratorFactory.cs trunk/nhibernate/src/NHibernate/Id/Insert/AbstractSelectingDelegate.cs trunk/nhibernate/src/NHibernate/NHibernate.csproj trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate/Id/SelectGenerator.cs trunk/nhibernate/src/NHibernate.Test/Generatedkeys/Select/ trunk/nhibernate/src/NHibernate.Test/Generatedkeys/Select/MyEntity.cs trunk/nhibernate/src/NHibernate.Test/Generatedkeys/Select/MyEntity.hbm.xml trunk/nhibernate/src/NHibernate.Test/Generatedkeys/Select/SelectGeneratorTest.cs Modified: trunk/nhibernate/src/NHibernate/Id/IdentifierGeneratorFactory.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Id/IdentifierGeneratorFactory.cs 2008-11-02 22:55:51 UTC (rev 3887) +++ trunk/nhibernate/src/NHibernate/Id/IdentifierGeneratorFactory.cs 2008-11-04 12:08:34 UTC (rev 3888) @@ -165,6 +165,7 @@ idgenerators.Add("foreign", typeof(ForeignGenerator)); idgenerators.Add("guid", typeof(GuidGenerator)); idgenerators.Add("guid.comb", typeof(GuidCombGenerator)); + idgenerators.Add("select", typeof(SelectGenerator)); } private IdentifierGeneratorFactory() Modified: trunk/nhibernate/src/NHibernate/Id/Insert/AbstractSelectingDelegate.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Id/Insert/AbstractSelectingDelegate.cs 2008-11-02 22:55:51 UTC (rev 3887) +++ trunk/nhibernate/src/NHibernate/Id/Insert/AbstractSelectingDelegate.cs 2008-11-04 12:08:34 UTC (rev 3888) @@ -51,7 +51,7 @@ try { //fetch the generated id in a separate query - IDbCommand idSelect = session.Batcher.PrepareCommand(CommandType.Text, selectSQL, SqlTypeFactory.NoTypes); + IDbCommand idSelect = session.Batcher.PrepareCommand(CommandType.Text, selectSQL, ParametersTypes); try { BindParameters(session, idSelect, binder.Entity); @@ -91,10 +91,22 @@ /// <returns> The generated identifier </returns> protected internal abstract object GetResult(ISessionImplementor session, IDataReader rs, object entity); - /// <summary> Bind any required parameter values into the SQL command {@link #getSelectSQL}. </summary> + /// <summary> Bind any required parameter values into the SQL command <see cref="SelectSQL"/>. </summary> /// <param name="session">The session </param> - /// <param name="ps">The prepared {@link #getSelectSQL SQL} command </param> + /// <param name="ps">The prepared <see cref="SelectSQL"/> command </param> /// <param name="entity">The entity being saved. </param> - protected internal virtual void BindParameters(ISessionImplementor session, IDbCommand ps, object entity) {} + protected internal virtual void BindParameters(ISessionImplementor session, IDbCommand ps, object entity) { } + + #region NH Specific + + /// <summary> + /// Types of any required parameter values into the SQL command <see cref="SelectSQL"/>. + /// </summary> + protected internal virtual SqlType[] ParametersTypes + { + get { return SqlTypeFactory.NoTypes; } + } + + #endregion } } \ No newline at end of file Added: trunk/nhibernate/src/NHibernate/Id/SelectGenerator.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Id/SelectGenerator.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Id/SelectGenerator.cs 2008-11-04 12:08:34 UTC (rev 3888) @@ -0,0 +1,126 @@ +using System.Collections.Generic; +using System.Data; +using NHibernate.Engine; +using NHibernate.Id.Insert; +using NHibernate.Persister.Entity; +using NHibernate.SqlCommand; +using NHibernate.SqlTypes; +using NHibernate.Type; + +namespace NHibernate.Id +{ + /// <summary> + /// A generator that selects the just inserted row to determine the identifier + /// value assigned by the database. The correct row is located using a unique key. + /// </summary> + /// <remarks>One mapping parameter is required: key (unless a natural-id is defined in the mapping).</remarks> + public class SelectGenerator : AbstractPostInsertGenerator, IConfigurable + { + private string uniqueKeyPropertyName; + + #region Overrides of AbstractPostInsertGenerator + + public override IInsertGeneratedIdentifierDelegate GetInsertGeneratedIdentifierDelegate( + IPostInsertIdentityPersister persister, ISessionFactoryImplementor factory, bool isGetGeneratedKeysEnabled) + { + return new SelectGeneratorDelegate(persister, factory, uniqueKeyPropertyName); + } + + #endregion + + #region Implementation of IConfigurable + + public void Configure(IType type, IDictionary<string, string> parms, Dialect.Dialect dialect) + { + parms.TryGetValue("key", out uniqueKeyPropertyName); + } + + #endregion + + private static string DetermineNameOfPropertyToUse(IEntityPersister persister, string supplied) + { + if (supplied != null) + { + return supplied; + } + int[] naturalIdPropertyIndices = persister.NaturalIdentifierProperties; + if (naturalIdPropertyIndices == null) + { + throw new IdentifierGenerationException("no natural-id property defined; need to specify [key] in " + + "generator parameters"); + } + if (naturalIdPropertyIndices.Length > 1) + { + throw new IdentifierGenerationException("select generator does not currently support composite " + + "natural-id properties; need to specify [key] in generator parameters"); + } + ValueInclusion inclusion = persister.PropertyInsertGenerationInclusions[naturalIdPropertyIndices[0]]; + if (inclusion != ValueInclusion.None) + { + throw new IdentifierGenerationException("natural-id also defined as insert-generated; need to specify [key] " + + "in generator parameters"); + } + return persister.PropertyNames[naturalIdPropertyIndices[0]]; + } + + #region Nested type: SelectGeneratorDelegate + + /// <summary> The delegate for the select generation strategy.</summary> + public class SelectGeneratorDelegate : AbstractSelectingDelegate + { + private readonly ISessionFactoryImplementor factory; + private readonly SqlString idSelectString; + private readonly IType idType; + private readonly IPostInsertIdentityPersister persister; + + private readonly string uniqueKeyPropertyName; + private readonly IType uniqueKeyType; + + internal SelectGeneratorDelegate(IPostInsertIdentityPersister persister, ISessionFactoryImplementor factory, + string suppliedUniqueKeyPropertyName) : base(persister) + { + this.persister = persister; + this.factory = factory; + uniqueKeyPropertyName = DetermineNameOfPropertyToUse((IEntityPersister) persister, suppliedUniqueKeyPropertyName); + + idSelectString = persister.GetSelectByUniqueKeyString(uniqueKeyPropertyName); + uniqueKeyType = ((IEntityPersister) persister).GetPropertyType(uniqueKeyPropertyName); + idType = persister.IdentifierType; + } + + protected internal override SqlString SelectSQL + { + get { return idSelectString; } + } + + protected internal override SqlType[] ParametersTypes + { + get { return uniqueKeyType.SqlTypes(factory); } + } + + public override IdentifierGeneratingInsert PrepareIdentifierGeneratingInsert() + { + return new IdentifierGeneratingInsert(factory); + } + + protected internal override void BindParameters(ISessionImplementor session, IDbCommand ps, object entity) + { + object uniqueKeyValue = ((IEntityPersister) persister).GetPropertyValue(entity, uniqueKeyPropertyName, + session.EntityMode); + uniqueKeyType.NullSafeSet(ps, uniqueKeyValue, 0, session); + } + + protected internal override object GetResult(ISessionImplementor session, IDataReader rs, object entity) + { + if (!rs.Read()) + { + throw new IdentifierGenerationException("the inserted row could not be located by the unique key: " + + uniqueKeyPropertyName); + } + return idType.NullSafeGet(rs, persister.RootTableKeyColumnNames, session, entity); + } + } + + #endregion + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-02 22:55:51 UTC (rev 3887) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-04 12:08:34 UTC (rev 3888) @@ -440,6 +440,7 @@ <Compile Include="AdoNet\ResultSetWrapper.cs" /> <Compile Include="AdoNet\SqlClientBatchingBatcherFactory.cs" /> <Compile Include="AdoNet\TooManyRowsAffectedException.cs" /> + <Compile Include="Id\SelectGenerator.cs" /> <Compile Include="Properties\BackFieldStrategy.cs" /> <Compile Include="Bytecode\CodeDom\BytecodeProviderImpl.cs" /> <Compile Include="Bytecode\IAccessOptimizer.cs" /> Added: trunk/nhibernate/src/NHibernate.Test/Generatedkeys/Select/MyEntity.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Generatedkeys/Select/MyEntity.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/Generatedkeys/Select/MyEntity.cs 2008-11-04 12:08:34 UTC (rev 3888) @@ -0,0 +1,25 @@ +namespace NHibernate.Test.Generatedkeys.Select +{ + public class MyEntity + { + private int id; + private string name; + protected MyEntity() {} + + public MyEntity(string name) + { + this.name = name; + } + + public virtual int Id + { + get { return id; } + } + + public virtual string Name + { + get { return name; } + set { name = value; } + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/Generatedkeys/Select/MyEntity.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Generatedkeys/Select/MyEntity.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/Generatedkeys/Select/MyEntity.hbm.xml 2008-11-04 12:08:34 UTC (rev 3888) @@ -0,0 +1,43 @@ +<?xml version="1.0"?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" + assembly="NHibernate.Test" + namespace="NHibernate.Test.Generatedkeys.Select" + default-access="field"> + + <class name="MyEntity" table="my_entity"> + + <id name="id"> + <generator class="select"/> + </id> + <natural-id> + <property name="name"/> + </natural-id> + </class> + + <database-object> + <create> +CREATE GENERATOR MYGENERATOR; + </create> + <drop> +DROP GENERATOR MYGENERATOR; + </drop> + <dialect-scope name="NHibernate.Dialect.FirebirdDialect"/> + </database-object> + + <database-object> + <create> +CREATE TRIGGER my_entity_BI FOR my_entity +ACTIVE BEFORE INSERT +POSITION 0 +AS +BEGIN +NEW.ID = GEN_ID (MYGENERATOR, 1); +END + </create> + <drop> +DROP TRIGGER my_entity_BI; + </drop> + <dialect-scope name="NHibernate.Dialect.FirebirdDialect"/> + </database-object> + +</hibernate-mapping> \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/Generatedkeys/Select/SelectGeneratorTest.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Generatedkeys/Select/SelectGeneratorTest.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/Generatedkeys/Select/SelectGeneratorTest.cs 2008-11-04 12:08:34 UTC (rev 3888) @@ -0,0 +1,42 @@ +using System.Collections; +using NUnit.Framework; + +namespace NHibernate.Test.Generatedkeys.Select +{ + [TestFixture] + public class SelectGeneratorTest: TestCase + { + protected override IList Mappings + { + get { return new[] { "Generatedkeys.Select.MyEntity.hbm.xml" }; } + } + + protected override string MappingsAssembly + { + get { return "NHibernate.Test"; } + } + + protected override bool AppliesTo(Dialect.Dialect dialect) + { + return dialect is Dialect.FirebirdDialect; + } + + [Test] + public void GetGeneratedKeysSupport() + { + ISession session = OpenSession(); + session.BeginTransaction(); + + MyEntity e = new MyEntity("entity-1"); + session.Save(e); + + // this insert should happen immediately! + Assert.AreEqual(1, e.Id, "id not generated through forced insertion"); + + session.Delete(e); + session.Transaction.Commit(); + session.Close(); + } + + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-11-02 22:55:51 UTC (rev 3887) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-11-04 12:08:34 UTC (rev 3888) @@ -243,6 +243,8 @@ <Compile Include="Generatedkeys\Identity\MyChild.cs" /> <Compile Include="Generatedkeys\Identity\MyEntity.cs" /> <Compile Include="Generatedkeys\Identity\MySibling.cs" /> + <Compile Include="Generatedkeys\Select\MyEntity.cs" /> + <Compile Include="Generatedkeys\Select\SelectGeneratorTest.cs" /> <Compile Include="GeneratedTest\AbstractGeneratedPropertyTest.cs" /> <Compile Include="GeneratedTest\Component.cs" /> <Compile Include="GeneratedTest\ComponentOwner.cs" /> @@ -1515,6 +1517,7 @@ <EmbeddedResource Include="Cascade\JobBatch.hbm.xml" /> <EmbeddedResource Include="Deletetransient\Person.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> + <EmbeddedResource Include="Generatedkeys\Select\MyEntity.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1478\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1447\Mappings.hbm.xml" /> <EmbeddedResource Include="TypesTest\EnumCharClass.hbm.xml" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <te...@us...> - 2008-11-07 07:37:41
|
Revision: 3892 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3892&view=rev Author: tehlike Date: 2008-11-07 07:37:36 +0000 (Fri, 07 Nov 2008) Log Message: ----------- Implementing AbstractEnumType for enum bases. Also fixes NH-1232 Modified Paths: -------------- trunk/nhibernate/src/NHibernate/NHibernate.csproj trunk/nhibernate/src/NHibernate/Type/EnumCharType.cs trunk/nhibernate/src/NHibernate/Type/EnumStringType.cs trunk/nhibernate/src/NHibernate/Type/PersistentEnumType.cs trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate/Type/AbstractEnumType.cs trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/ trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/Bar.cs trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/Baz.cs trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/Colors.cs trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/EnumDiscriminator.hbm.xml trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/EnumDiscriminatorFixture.cs trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/Foo.cs Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-07 04:49:41 UTC (rev 3891) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-07 07:37:36 UTC (rev 3892) @@ -1046,6 +1046,7 @@ <Compile Include="Tuple\VersionProperty.cs" /> <Compile Include="TypeMismatchException.cs" /> <Compile Include="Type\AbstractBynaryType.cs" /> + <Compile Include="Type\AbstractEnumType.cs" /> <Compile Include="Type\AbstractStringType.cs" /> <Compile Include="Type\AnsiCharType.cs" /> <Compile Include="Type\AnyType.cs" /> Added: trunk/nhibernate/src/NHibernate/Type/AbstractEnumType.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Type/AbstractEnumType.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Type/AbstractEnumType.cs 2008-11-07 07:37:36 UTC (rev 3892) @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Text; +using NHibernate.SqlTypes; + +namespace NHibernate.Type +{ + + /// <summary> + /// Base class for enum types. + /// </summary> + [Serializable] + public abstract class AbstractEnumType : PrimitiveType, IDiscriminatorType + { + protected AbstractEnumType(SqlType sqlType,System.Type enumType) + : base(sqlType) + { + if (enumType.IsEnum) + { + this.enumType = enumType; + } + else + { + throw new MappingException(enumType.Name + " did not inherit from System.Enum"); + } + defaultValue = Enum.GetValues(enumType).GetValue(0); + } + + private readonly object defaultValue; + private readonly System.Type enumType; + + public override System.Type ReturnedClass + { + get { return enumType; } + } + + + #region IIdentifierType Members + + public object StringToObject(string xml) + { + return Enum.Parse(enumType, xml); + } + + #endregion + + + public override object FromStringValue(string xml) + { + return StringToObject(xml); + } + + public override System.Type PrimitiveClass + { + get { return this.enumType; } + } + + public override object DefaultValue + { + get { return defaultValue; } + } + } +} Modified: trunk/nhibernate/src/NHibernate/Type/EnumCharType.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Type/EnumCharType.cs 2008-11-07 04:49:41 UTC (rev 3891) +++ trunk/nhibernate/src/NHibernate/Type/EnumCharType.cs 2008-11-07 07:37:36 UTC (rev 3892) @@ -6,21 +6,12 @@ namespace NHibernate.Type { [Serializable] - public class EnumCharType<T> : ImmutableType, IDiscriminatorType + public class EnumCharType<T> : AbstractEnumType { - public EnumCharType() : base(new StringFixedLengthSqlType(1)) + public EnumCharType() : base(new StringFixedLengthSqlType(1),typeof(T)) { - if (typeof(T).IsEnum) - { - this.enumClass = typeof(T); - } - else - { - throw new MappingException(enumClass.Name + " did not inherit from System.Enum"); - } } - private readonly System.Type enumClass; public virtual object GetInstance(object code) { @@ -34,13 +25,13 @@ } else { - throw new HibernateException(string.Format("Can't Parse {0} as {1}", code, enumClass.Name)); + throw new HibernateException(string.Format("Can't Parse {0} as {1}", code, ReturnedClass.Name)); } } private object GetInstanceFromString(String s) { - if (s.Length == 0) throw new HibernateException(string.Format("Can't Parse empty string as {0}", enumClass.Name)); + if (s.Length == 0) throw new HibernateException(string.Format("Can't Parse empty string as {0}", this.ReturnedClass.Name)); if (s.Length == 1) { @@ -52,17 +43,17 @@ //Name of enum value e.g. "Red" try { - return Enum.Parse(enumClass, s, false); + return Enum.Parse(this.ReturnedClass, s, false); } catch (ArgumentException) { try { - return Enum.Parse(enumClass, s, true); + return Enum.Parse(this.ReturnedClass, s, true); } catch (ArgumentException ae) { - throw new HibernateException(string.Format("Can't Parse {0} as {1}", s, enumClass.Name), ae); + throw new HibernateException(string.Format("Can't Parse {0} as {1}", s, this.ReturnedClass.Name), ae); } } } @@ -72,13 +63,13 @@ { Object instance; - instance = Enum.ToObject(enumClass, c); - if (Enum.IsDefined(enumClass, instance)) return instance; + instance = Enum.ToObject(this.ReturnedClass, c); + if (Enum.IsDefined(this.ReturnedClass, instance)) return instance; - instance = Enum.ToObject(enumClass, Alternate(c)); - if (Enum.IsDefined(enumClass, instance)) return instance; + instance = Enum.ToObject(this.ReturnedClass, Alternate(c)); + if (Enum.IsDefined(this.ReturnedClass, instance)) return instance; - throw new HibernateException(string.Format("Can't Parse {0} as {1}", c, enumClass.Name)); + throw new HibernateException(string.Format("Can't Parse {0} as {1}", c, this.ReturnedClass.Name)); } private Char Alternate(Char c) @@ -103,10 +94,6 @@ } } - public override System.Type ReturnedClass - { - get { return enumClass; } - } public override void Set(IDbCommand cmd, object value, int index) { @@ -141,7 +128,7 @@ public override string Name { - get { return "enumchar - " + enumClass.Name; } + get { return "enumchar - " + this.ReturnedClass.Name; } } public override string ToString(object value) @@ -166,17 +153,13 @@ return (value == null) ? null : GetValue(value); } - public virtual object StringToObject(string xml) - { - return (string.IsNullOrEmpty(xml)) ? null : FromStringValue(xml); - } public override object FromStringValue(string xml) { return GetInstance(xml); } - public virtual string ObjectToSQLString(object value, Dialect.Dialect dialect) + public override string ObjectToSQLString(object value, Dialect.Dialect dialect) { return '\'' + GetValue(value).ToString() + '\''; } Modified: trunk/nhibernate/src/NHibernate/Type/EnumStringType.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Type/EnumStringType.cs 2008-11-07 04:49:41 UTC (rev 3891) +++ trunk/nhibernate/src/NHibernate/Type/EnumStringType.cs 2008-11-07 07:37:36 UTC (rev 3892) @@ -62,9 +62,8 @@ /// </para> /// </remarks> [Serializable] - public abstract class EnumStringType : ImmutableType, IDiscriminatorType + public abstract class EnumStringType : AbstractEnumType { - private readonly System.Type enumClass; /// <summary> /// Hardcoding of <c>255</c> for the maximum length @@ -91,16 +90,9 @@ /// <param name="enumClass">The <see cref="System.Type"/> of the Enum.</param> /// <param name="length">The length of the string that can be written to the column.</param> protected EnumStringType(System.Type enumClass, int length) - : base(SqlTypeFactory.GetString(length)) + :base(SqlTypeFactory.GetString(length),enumClass) { - if (enumClass.IsEnum) - { - this.enumClass = enumClass; - } - else - { - throw new MappingException(enumClass.Name + " did not inherit from System.Enum"); - } + } /// <summary> @@ -113,11 +105,11 @@ //code is an named constants defined for the enumeration. try { - return Enum.Parse(enumClass, code as string, true); + return StringToObject(code as string); } catch (ArgumentException ae) { - throw new HibernateException(string.Format("Can't Parse {0} as {1}", code, enumClass.Name), ae); + throw new HibernateException(string.Format("Can't Parse {0} as {1}", code, this.ReturnedClass.Name), ae); } } @@ -135,14 +127,6 @@ /// <summary> /// /// </summary> - public override System.Type ReturnedClass - { - get { return enumClass; } - } - - /// <summary> - /// - /// </summary> /// <param name="cmd"></param> /// <param name="value"></param> /// <param name="index"></param> @@ -155,7 +139,7 @@ } else { - par.Value = Enum.Format(this.enumClass, value, "G"); + par.Value = Enum.Format(this.ReturnedClass, value, "G"); } } @@ -200,7 +184,7 @@ /// </remarks> public override string Name { - get { return "enumstring - " + enumClass.Name; } + get { return "enumstring - " + this.ReturnedClass.Name; } } /// <summary> @@ -237,23 +221,9 @@ return (value == null) ? null : GetValue(value); } - /// <summary> - /// - /// </summary> - /// <param name="xml"></param> - /// <returns></returns> - public object StringToObject(string xml) - { - return (string.IsNullOrEmpty(xml)) ? null : FromStringValue(xml); - } - public override object FromStringValue(string xml) + public override string ObjectToSQLString(object value, Dialect.Dialect dialect) { - return GetInstance(xml); - } - - public string ObjectToSQLString(object value, Dialect.Dialect dialect) - { return GetValue(value).ToString(); } } Modified: trunk/nhibernate/src/NHibernate/Type/PersistentEnumType.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Type/PersistentEnumType.cs 2008-11-07 04:49:41 UTC (rev 3891) +++ trunk/nhibernate/src/NHibernate/Type/PersistentEnumType.cs 2008-11-07 07:37:36 UTC (rev 3892) @@ -10,7 +10,7 @@ /// PersistentEnumType /// </summary> [Serializable] - public class PersistentEnumType : PrimitiveType + public class PersistentEnumType : AbstractEnumType { #region Converters @@ -160,19 +160,11 @@ } private static readonly Dictionary<System.Type, IEnumConverter> converters; - private readonly System.Type enumClass; private readonly IEnumConverter converter; - private readonly object defaultValue; - public PersistentEnumType(System.Type enumClass) : base(GetEnumCoverter(enumClass).SqlType) + public PersistentEnumType(System.Type enumClass) : base(GetEnumCoverter(enumClass).SqlType,enumClass) { - if (!enumClass.IsEnum) - { - throw new MappingException(enumClass.Name + " did not inherit from System.Enum"); - } converter = GetEnumCoverter(enumClass); - this.enumClass = enumClass; - defaultValue = Enum.GetValues(enumClass).GetValue(0); } public static IEnumConverter GetEnumCoverter(System.Type enumClass) @@ -207,7 +199,7 @@ { try { - return converter.ToObject(enumClass, code); + return converter.ToObject(this.ReturnedClass, code); } catch (ArgumentException ae) { @@ -230,10 +222,6 @@ return converter.ToEnumValue(code); } - public override System.Type ReturnedClass - { - get { return enumClass; } - } public override void Set(IDbCommand cmd, object value, int index) { @@ -248,7 +236,7 @@ public override string Name { - get { return enumClass.FullName; } + get { return ReturnedClass.FullName; } } public override string ToString(object value) @@ -283,22 +271,13 @@ return false; } - return ((PersistentEnumType) obj).enumClass == enumClass; + return ((PersistentEnumType)obj).ReturnedClass == ReturnedClass; } public override int GetHashCode() { - return enumClass.GetHashCode(); + return ReturnedClass.GetHashCode(); } - public override System.Type PrimitiveClass - { - get { return enumClass; } - } - - public override object DefaultValue - { - get { return defaultValue; } - } } } Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-11-07 04:49:41 UTC (rev 3891) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-11-07 07:37:36 UTC (rev 3892) @@ -858,6 +858,11 @@ <Compile Include="SubclassFilterTest\DiscrimSubclassFilterTest.cs" /> <Compile Include="SubclassFilterTest\Employee.cs" /> <Compile Include="SubclassFilterTest\Person.cs" /> + <Compile Include="Subclass\EnumDiscriminator\Bar.cs" /> + <Compile Include="Subclass\EnumDiscriminator\Baz.cs" /> + <Compile Include="Subclass\EnumDiscriminator\Colors.cs" /> + <Compile Include="Subclass\EnumDiscriminator\EnumDiscriminatorFixture.cs" /> + <Compile Include="Subclass\EnumDiscriminator\Foo.cs" /> <Compile Include="Subclass\SubclassAssert.cs" /> <Compile Include="Subclass\SubclassBase.cs" /> <Compile Include="Subclass\SubclassExtendsFixture.cs" /> @@ -1517,6 +1522,7 @@ <EmbeddedResource Include="Cascade\JobBatch.hbm.xml" /> <EmbeddedResource Include="Deletetransient\Person.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> + <EmbeddedResource Include="Subclass\EnumDiscriminator\EnumDiscriminator.hbm.xml" /> <EmbeddedResource Include="Generatedkeys\Select\MyEntity.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1478\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1447\Mappings.hbm.xml" /> Added: trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/Bar.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/Bar.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/Bar.cs 2008-11-07 07:37:36 UTC (rev 3892) @@ -0,0 +1,4 @@ +namespace NHibernate.Test.Subclass.EnumDiscriminator +{ + public class Bar : Foo {} +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/Baz.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/Baz.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/Baz.cs 2008-11-07 07:37:36 UTC (rev 3892) @@ -0,0 +1,22 @@ +using System; + +namespace NHibernate.Test.Subclass.EnumDiscriminator +{ + public class Baz + { + private Int64 id; + private Colors color; + + public virtual Int64 Id + { + get { return id; } + set { id = value; } + } + + public virtual Colors Color + { + get { return color; } + set { color = value; } + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/Colors.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/Colors.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/Colors.cs 2008-11-07 07:37:36 UTC (rev 3892) @@ -0,0 +1,9 @@ +namespace NHibernate.Test.Subclass.EnumDiscriminator +{ + public enum Colors + { + Red, + Green, + Blue + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/EnumDiscriminator.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/EnumDiscriminator.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/EnumDiscriminator.hbm.xml 2008-11-07 07:37:36 UTC (rev 3892) @@ -0,0 +1,17 @@ +<?xml version="1.0"?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false" namespace="NHibernate.Test.Subclass.EnumDiscriminator" assembly="NHibernate.Test"> + <class name="Foo" table="subclass_enumdiscriminator" discriminator-value="Green"> + <id name="Id" type="Int64"> + <generator class="assigned"/> + </id> + <discriminator column="Color" type="NHibernate.Test.Subclass.EnumDiscriminator.Colors, NHibernate.Test"/> + <subclass name="Bar" discriminator-value="Blue"/> + </class> + + <class name="Baz" table="subclass_enumdiscriminator"> + <id name="Id" type="Int64"> + <generator class="assigned"/> + </id> + <property name="Color"/> + </class> +</hibernate-mapping> Added: trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/EnumDiscriminatorFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/EnumDiscriminatorFixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/EnumDiscriminatorFixture.cs 2008-11-07 07:37:36 UTC (rev 3892) @@ -0,0 +1,74 @@ +using System; +using System.Collections; +using NUnit.Framework; + +namespace NHibernate.Test.Subclass.EnumDiscriminator +{ + [TestFixture] + public class EnumDiscriminatorFixture : TestCase + { + protected override string MappingsAssembly + { + get { return "NHibernate.Test"; } + } + + protected override IList Mappings + { + get { return new String[] {"Subclass.EnumDiscriminator.EnumDiscriminator.hbm.xml"}; } + } + + [Test] + public void PersistsDefaultDiscriminatorValue() + { + Foo foo = new Foo(); + foo.Id = 1; + + using (ISession s = OpenSession()) + { + s.Save(foo); + s.Flush(); + } + + using (ISession s = OpenSession()) + { + Baz baz = s.Load<Baz>(1L); + Assert.AreEqual(Colors.Green, baz.Color); + } + } + + [Test] + public void CanConvertOneTypeToAnother() + { + Foo foo = new Foo(); + foo.Id = 1; + + using (ISession s = OpenSession()) + { + s.Save(foo); + s.Flush(); + } + + using (ISession s = OpenSession()) + { + Baz baz = s.Load<Baz>(1L); + baz.Color = Colors.Blue; + s.Save(baz); + s.Flush(); + } + + using (ISession s = OpenSession()) + { + Bar bar = s.Load<Bar>(1L); + } + } + + protected override void OnTearDown() + { + using (ISession s = OpenSession()) + { + s.Delete("from Baz"); + s.Flush(); + } + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/Foo.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/Foo.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/Subclass/EnumDiscriminator/Foo.cs 2008-11-07 07:37:36 UTC (rev 3892) @@ -0,0 +1,15 @@ +using System; + +namespace NHibernate.Test.Subclass.EnumDiscriminator +{ + public class Foo + { + private Int64 id; + + public long Id + { + get { return id; } + set { id = value; } + } + } +} \ 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-11-08 15:15:00
|
Revision: 3896 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3896&view=rev Author: fabiomaulo Date: 2008-11-08 15:14:52 +0000 (Sat, 08 Nov 2008) Log Message: ----------- - Removed default ProxyFactoryFactory. - Improv Exceptions related with ProxyFactoryFactory Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Bytecode/CodeDom/BytecodeProviderImpl.cs trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs trunk/nhibernate/src/NHibernate/Bytecode/NullBytecodeProvider.cs trunk/nhibernate/src/NHibernate/Cfg/Environment.cs trunk/nhibernate/src/NHibernate/NHibernate.csproj trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate/Bytecode/HibernateByteCodeException.cs trunk/nhibernate/src/NHibernate/Bytecode/ProxyFactoryFactoryNotConfiguredException.cs trunk/nhibernate/src/NHibernate/Bytecode/UnableToLoadProxyFactoryFactoryException.cs trunk/nhibernate/src/NHibernate.Test/Bytecode/ trunk/nhibernate/src/NHibernate.Test/Bytecode/Lightweight/ trunk/nhibernate/src/NHibernate.Test/Bytecode/Lightweight/BytecodeProviderFixture.cs trunk/nhibernate/src/NHibernate.Test/Bytecode/WrongProxyFactoryFactory.cs Modified: trunk/nhibernate/src/NHibernate/Bytecode/CodeDom/BytecodeProviderImpl.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Bytecode/CodeDom/BytecodeProviderImpl.cs 2008-11-07 22:40:43 UTC (rev 3895) +++ trunk/nhibernate/src/NHibernate/Bytecode/CodeDom/BytecodeProviderImpl.cs 2008-11-08 15:14:52 UTC (rev 3896) @@ -31,11 +31,11 @@ } catch (Exception e) { - throw new HibernateException("Failed to create an instance of '" + proxyFactoryFactory.FullName + "'!", e); + throw new HibernateByteCodeException("Failed to create an instance of '" + proxyFactoryFactory.FullName + "'!", e); } } - throw new HibernateException("The ProxyFactoryFactory was not configured. Initialize the 'proxyfactory.factory_class' property of the session-factory section."); + throw new ProxyFactoryFactoryNotConfiguredException(); } } @@ -61,15 +61,14 @@ { pffc = ReflectHelper.ClassForName(typeName); } - catch (HibernateException he) + catch (Exception he) { - throw new HibernateException("Unable to load type '" + typeName + "' during configuration of proxy factory class.", - he); + throw new UnableToLoadProxyFactoryFactoryException(typeName, he); } if (typeof (IProxyFactoryFactory).IsAssignableFrom(pffc) == false) { - var he = new HibernateException(pffc.FullName + " does not implement " + typeof (IProxyFactoryFactory).FullName); + var he = new HibernateByteCodeException(pffc.FullName + " does not implement " + typeof(IProxyFactoryFactory).FullName); throw he; } proxyFactoryFactory = pffc; Added: trunk/nhibernate/src/NHibernate/Bytecode/HibernateByteCodeException.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Bytecode/HibernateByteCodeException.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Bytecode/HibernateByteCodeException.cs 2008-11-08 15:14:52 UTC (rev 3896) @@ -0,0 +1,15 @@ +using System; +using System.Runtime.Serialization; + +namespace NHibernate.Bytecode +{ + [Serializable] + public class HibernateByteCodeException : HibernateException + { + public HibernateByteCodeException() {} + public HibernateByteCodeException(string message) : base(message) {} + public HibernateByteCodeException(string message, Exception inner) : base(message, inner) {} + + protected HibernateByteCodeException(SerializationInfo info, StreamingContext context) : base(info, context) {} + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs 2008-11-07 22:40:43 UTC (rev 3895) +++ trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs 2008-11-08 15:14:52 UTC (rev 3896) @@ -30,10 +30,10 @@ } catch (Exception e) { - throw new HibernateException("Failed to create an instance of '" + proxyFactoryFactory.FullName + "'!", e); + throw new HibernateByteCodeException("Failed to create an instance of '" + proxyFactoryFactory.FullName + "'!", e); } } - throw new HibernateException("The ProxyFactoryFactory was not configured. Initialize the 'proxyfactory.factory_class' property of the session-factory section."); + throw new ProxyFactoryFactoryNotConfiguredException(); } } @@ -60,15 +60,14 @@ { pffc = ReflectHelper.ClassForName(typeName); } - catch (HibernateException he) + catch (Exception he) { - throw new HibernateException("Unable to load type '" + typeName + "' during configuration of proxy factory class.", - he); + throw new UnableToLoadProxyFactoryFactoryException(typeName, he); } if (typeof (IProxyFactoryFactory).IsAssignableFrom(pffc) == false) { - var he = new HibernateException(pffc.FullName + " does not implement " + typeof (IProxyFactoryFactory).FullName); + var he = new HibernateByteCodeException(pffc.FullName + " does not implement " + typeof(IProxyFactoryFactory).FullName); throw he; } proxyFactoryFactory = pffc; Modified: trunk/nhibernate/src/NHibernate/Bytecode/NullBytecodeProvider.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Bytecode/NullBytecodeProvider.cs 2008-11-07 22:40:43 UTC (rev 3895) +++ trunk/nhibernate/src/NHibernate/Bytecode/NullBytecodeProvider.cs 2008-11-08 15:14:52 UTC (rev 3896) @@ -26,10 +26,10 @@ } catch (Exception e) { - throw new HibernateException("Failed to create an instance of '" + proxyFactoryFactory.FullName + "'!", e); + throw new HibernateByteCodeException("Failed to create an instance of '" + proxyFactoryFactory.FullName + "'!", e); } } - throw new HibernateException("The ProxyFactoryFactory was not configured. Initialize the 'proxyfactory.factory_class' property of the session-factory section."); + throw new ProxyFactoryFactoryNotConfiguredException(); } } @@ -49,15 +49,14 @@ { pffc = ReflectHelper.ClassForName(typeName); } - catch (HibernateException he) + catch (Exception he) { - throw new HibernateException("Unable to load type '" + typeName + "' during configuration of proxy factory class.", - he); + throw new UnableToLoadProxyFactoryFactoryException(typeName, he); } if (typeof (IProxyFactoryFactory).IsAssignableFrom(pffc) == false) { - var he = new HibernateException(pffc.FullName + " does not implement " + typeof (IProxyFactoryFactory).FullName); + var he = new HibernateByteCodeException(pffc.FullName + " does not implement " + typeof(IProxyFactoryFactory).FullName); throw he; } proxyFactoryFactory = pffc; Added: trunk/nhibernate/src/NHibernate/Bytecode/ProxyFactoryFactoryNotConfiguredException.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Bytecode/ProxyFactoryFactoryNotConfiguredException.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Bytecode/ProxyFactoryFactoryNotConfiguredException.cs 2008-11-08 15:14:52 UTC (rev 3896) @@ -0,0 +1,29 @@ +using System; +using System.Runtime.Serialization; + +namespace NHibernate.Bytecode +{ + + [Serializable] + public class ProxyFactoryFactoryNotConfiguredException : HibernateByteCodeException + { + public ProxyFactoryFactoryNotConfiguredException() {} + + protected ProxyFactoryFactoryNotConfiguredException(SerializationInfo info, + StreamingContext context) : base(info, context) {} + + public override string Message + { + get + { + const string msg = @"The ProxyFactoryFactory was not configured. +Initialize 'proxyfactory.factory_class' property of the session-factory configuration section with one of the available NHibernate.ByteCode providers. +Example: +<property name='proxyfactory.factory_class'>NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property> +Example: +<property name='proxyfactory.factory_class'>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>"; + return msg; + } + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate/Bytecode/UnableToLoadProxyFactoryFactoryException.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Bytecode/UnableToLoadProxyFactoryFactoryException.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Bytecode/UnableToLoadProxyFactoryFactoryException.cs 2008-11-08 15:14:52 UTC (rev 3896) @@ -0,0 +1,37 @@ +using System; +using System.Runtime.Serialization; + +namespace NHibernate.Bytecode +{ + [Serializable] + public class UnableToLoadProxyFactoryFactoryException : HibernateByteCodeException + { + private readonly string typeName; + public UnableToLoadProxyFactoryFactoryException(string typeName, Exception inner) + : base("", inner) + { + this.typeName = typeName; + } + + protected UnableToLoadProxyFactoryFactoryException(SerializationInfo info, + StreamingContext context) : base(info, context) {} + public override string Message + { + get + { + const string causes = @" +Possible causes are: +- The NHibernate.Bytecode provider assembly was not deployed. +- The typeName used to initialize the 'proxyfactory.factory_class' property of the session-factory section is not well formed. + +Solution: +Confirm that your deployment folder contains one of the following assemblies: +NHibernate.ByteCode.LinFu.dll +NHibernate.ByteCode.Castle.dll"; + string msg = "Unable to load type '" + typeName + "' during configuration of proxy factory class." + causes; + + return msg; + } + } + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Cfg/Environment.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/Environment.cs 2008-11-07 22:40:43 UTC (rev 3895) +++ trunk/nhibernate/src/NHibernate/Cfg/Environment.cs 2008-11-08 15:14:52 UTC (rev 3896) @@ -178,7 +178,6 @@ GlobalProperties = new Dictionary<string, string>(); GlobalProperties[PropertyUseReflectionOptimizer] = bool.TrueString; - SetDefaultProxyFactoryFactory(); LoadGlobalPropertiesFromAppConfig(); VerifyProperties(GlobalProperties); @@ -191,12 +190,6 @@ } } - private static void SetDefaultProxyFactoryFactory() - { - // maitaining the optionality of set the proxyfactory.factory_class property - GlobalProperties[ProxyFactoryFactoryClass] = "NHibernate.ProxyGenerators.CastleDynamicProxy.ProxyFactoryFactory, NHibernate.ProxyGenerators.CastleDynamicProxy"; - } - private static void LoadGlobalPropertiesFromAppConfig() { object config = ConfigurationManager.GetSection(CfgXmlHelper.CfgSectionName); @@ -252,8 +245,6 @@ { GlobalProperties[PropertyUseReflectionOptimizer] = savedUseReflectionOptimizer; } - - SetDefaultProxyFactoryFactory(); } /// <summary> Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-07 22:40:43 UTC (rev 3895) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-08 15:14:52 UTC (rev 3896) @@ -440,6 +440,9 @@ <Compile Include="AdoNet\ResultSetWrapper.cs" /> <Compile Include="AdoNet\SqlClientBatchingBatcherFactory.cs" /> <Compile Include="AdoNet\TooManyRowsAffectedException.cs" /> + <Compile Include="Bytecode\HibernateByteCodeException.cs" /> + <Compile Include="Bytecode\ProxyFactoryFactoryNotConfiguredException.cs" /> + <Compile Include="Bytecode\UnableToLoadProxyFactoryFactoryException.cs" /> <Compile Include="Id\SelectGenerator.cs" /> <Compile Include="Properties\BackFieldStrategy.cs" /> <Compile Include="Bytecode\CodeDom\BytecodeProviderImpl.cs" /> Added: trunk/nhibernate/src/NHibernate.Test/Bytecode/Lightweight/BytecodeProviderFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Bytecode/Lightweight/BytecodeProviderFixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/Bytecode/Lightweight/BytecodeProviderFixture.cs 2008-11-08 15:14:52 UTC (rev 3896) @@ -0,0 +1,76 @@ +using NHibernate.Bytecode; +using NHibernate.Bytecode.Lightweight; +using NUnit.Framework; +using NUnit.Framework.SyntaxHelpers; + +namespace NHibernate.Test.Bytecode.Lightweight +{ + [TestFixture] + public class BytecodeProviderFixture + { + [Test] + public void NotConfiguredProxyFactoryFactory() + { + try + { + var bcp = new BytecodeProviderImpl(); + IProxyFactoryFactory p = bcp.ProxyFactoryFactory; + Assert.Fail(); + } + catch (HibernateByteCodeException e) + { + Assert.That(e.Message, Text.StartsWith("The ProxyFactoryFactory was not configured")); + Assert.That(e.Message, Text.Contains("Example")); + } + } + + [Test] + public void UnableToLoadProxyFactoryFactory() + { + try + { + var bcp = new BytecodeProviderImpl(); + bcp.SetProxyFactoryFactory("whatever"); + Assert.Fail(); + } + catch (HibernateByteCodeException e) + { + Assert.That(e.Message, Text.StartsWith("Unable to load type")); + Assert.That(e.Message, Text.Contains("Possible causes")); + Assert.That(e.Message, Text.Contains("Confirm that your deployment folder contains")); + } + } + + [Test] + public void DoesNotImplementProxyFactoryFactory() + { + try + { + var bcp = new BytecodeProviderImpl(); + bcp.SetProxyFactoryFactory(GetType().AssemblyQualifiedName); + Assert.Fail(); + } + catch (HibernateByteCodeException e) + { + Assert.That(e.Message, + Is.EqualTo(GetType().FullName + " does not implement " + typeof(IProxyFactoryFactory).FullName)); + } + } + + [Test] + public void CantCreateProxyFactoryFactory() + { + try + { + var bcp = new BytecodeProviderImpl(); + bcp.SetProxyFactoryFactory(typeof(WrongProxyFactoryFactory).AssemblyQualifiedName); + IProxyFactoryFactory p = bcp.ProxyFactoryFactory; + Assert.Fail(); + } + catch (HibernateByteCodeException e) + { + Assert.That(e.Message,Text.StartsWith("Failed to create an instance of")); + } + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/Bytecode/WrongProxyFactoryFactory.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Bytecode/WrongProxyFactoryFactory.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/Bytecode/WrongProxyFactoryFactory.cs 2008-11-08 15:14:52 UTC (rev 3896) @@ -0,0 +1,27 @@ +using NHibernate.Bytecode; +using NHibernate.Proxy; + +namespace NHibernate.Test.Bytecode +{ + public class WrongProxyFactoryFactory : IProxyFactoryFactory + { + public WrongProxyFactoryFactory() + { + throw new System.Exception(); + } + + #region Implementation of IProxyFactoryFactory + + public IProxyFactory BuildProxyFactory() + { + throw new System.NotImplementedException(); + } + + public IProxyValidator ProxyValidator + { + get { throw new System.NotImplementedException(); } + } + + #endregion + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-11-07 22:40:43 UTC (rev 3895) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-11-08 15:14:52 UTC (rev 3896) @@ -77,6 +77,8 @@ <Compile Include="AssemblyInfo.cs" /> <Compile Include="Assertions\InheritedAreMarkedSerializable.cs" /> <Compile Include="Assertions\IsSerializable.cs" /> + <Compile Include="Bytecode\Lightweight\BytecodeProviderFixture.cs" /> + <Compile Include="Bytecode\WrongProxyFactoryFactory.cs" /> <Compile Include="CacheTest\CacheFixture.cs" /> <Compile Include="CacheTest\QueryCacheFixture.cs" /> <Compile Include="CacheTest\TimestamperFixture.cs" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-11-08 15:24:34
|
Revision: 3897 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3897&view=rev Author: fabiomaulo Date: 2008-11-08 15:24:29 +0000 (Sat, 08 Nov 2008) Log Message: ----------- Fix NH-1550 (by Jaroslav Mart?\195?\161sek) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Dialect/Oracle9Dialect.cs trunk/nhibernate/src/NHibernate.Test/Legacy/SQLFunctionsTest.cs Modified: trunk/nhibernate/src/NHibernate/Dialect/Oracle9Dialect.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/Oracle9Dialect.cs 2008-11-08 15:14:52 UTC (rev 3896) +++ trunk/nhibernate/src/NHibernate/Dialect/Oracle9Dialect.cs 2008-11-08 15:24:29 UTC (rev 3897) @@ -103,6 +103,8 @@ RegisterFunction("upper", new StandardSQLFunction("upper")); RegisterFunction("ascii", new StandardSQLFunction("ascii", NHibernateUtil.Int32)); RegisterFunction("length", new StandardSQLFunction("length", NHibernateUtil.Int64)); + RegisterFunction("left", new SQLFunctionTemplate(NHibernateUtil.String, "substr(?1, 1, ?2)")); + RegisterFunction("right", new SQLFunctionTemplate(NHibernateUtil.String, "substr(?1, -?2)")); RegisterFunction("to_char", new StandardSQLFunction("to_char", NHibernateUtil.String)); RegisterFunction("to_date", new StandardSQLFunction("to_date", NHibernateUtil.Timestamp)); @@ -189,32 +191,30 @@ get { return true; } } + public override bool SupportsVariableLimit + { + get { return false; } + } + public override SqlString GetLimitString(SqlString querySqlString, int offset, int limit) { SqlStringBuilder pagingBuilder = new SqlStringBuilder(); var hasOffset = offset > 0; - if (hasOffset) - { - pagingBuilder.Add("select * from ( select row_.*, rownum rownum_ from ( "); - } - else - { - pagingBuilder.Add("select * from ( "); - } + pagingBuilder.Add("SELECT * FROM ("); pagingBuilder.Add(querySqlString); if (hasOffset) { - pagingBuilder.Add(" ) row_ where rownum <= "); + pagingBuilder.Add(") WHERE rownum BETWEEN "); pagingBuilder.Add(offset.ToString()); - pagingBuilder.Add(" ) where rownum_ > "); + pagingBuilder.Add(" AND "); pagingBuilder.Add((limit + offset).ToString()); } else { - pagingBuilder.Add(" ) where rownum <= "); - pagingBuilder.Add(offset.ToString()); + pagingBuilder.Add(") WHERE rownum <= "); + pagingBuilder.Add(limit.ToString()); } return pagingBuilder.ToSqlString(); Modified: trunk/nhibernate/src/NHibernate.Test/Legacy/SQLFunctionsTest.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Legacy/SQLFunctionsTest.cs 2008-11-08 15:14:52 UTC (rev 3896) +++ trunk/nhibernate/src/NHibernate.Test/Legacy/SQLFunctionsTest.cs 2008-11-08 15:24:29 UTC (rev 3897) @@ -76,9 +76,17 @@ rset = s.CreateQuery("select abs(round(s.Pay)) from s in class Simple").List(); Assert.AreEqual(46f, rset[0], "abs(round(-45.8)) result was incorrect"); + rset = s.CreateQuery("select left('abc', 2), right('abc', 2) from s in class Simple").List(); + row = (object[]) rset[0]; + Assert.AreEqual("ab", row[0], "Left function is broken."); + Assert.AreEqual("bc", row[1], "Right function is broken."); + // Test a larger depth 3 function example - Not a useful combo other than for testing Assert.AreEqual(1, - s.CreateQuery("select trunc(round(sysdate)) from s in class Simple").List().Count); + s.CreateQuery("select trunc(round(length('A'))) from s in class Simple").List().Count); + // NOTE: In Oracle this will fail as the translator will expect two columns in return + //Assert.AreEqual(1, + // s.CreateQuery("select trunc(round(sysdate)) from s in class Simple").List().Count); // Test the oracle standard NVL funtion as a test of multi-param functions... // NOTE: commented out for NH, since Pay is a value type and will never be null @@ -577,4 +585,4 @@ } } } -} \ 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-11-08 16:09:57
|
Revision: 3899 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3899&view=rev Author: fabiomaulo Date: 2008-11-08 16:09:54 +0000 (Sat, 08 Nov 2008) Log Message: ----------- Fix NH-1562 (schema update for SQLite by Mark Junker) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Dialect/SQLiteDialect.cs trunk/nhibernate/src/NHibernate/NHibernate.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate/Dialect/Schema/SQLiteMetaData.cs Modified: trunk/nhibernate/src/NHibernate/Dialect/SQLiteDialect.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/SQLiteDialect.cs 2008-11-08 15:58:07 UTC (rev 3898) +++ trunk/nhibernate/src/NHibernate/Dialect/SQLiteDialect.cs 2008-11-08 16:09:54 UTC (rev 3899) @@ -2,6 +2,7 @@ using System.Text; using NHibernate.SqlCommand; using NHibernate.Util; +using System.Data.Common; namespace NHibernate.Dialect { @@ -34,6 +35,7 @@ RegisterColumnType(DbType.Double, "NUMERIC"); RegisterColumnType(DbType.Single, "NUMERIC"); RegisterColumnType(DbType.VarNumeric, "NUMERIC"); + RegisterColumnType(DbType.AnsiString, "TEXT"); RegisterColumnType(DbType.String, "TEXT"); RegisterColumnType(DbType.AnsiStringFixedLength, "TEXT"); RegisterColumnType(DbType.StringFixedLength, "TEXT"); @@ -44,6 +46,19 @@ RegisterColumnType(DbType.Guid, "UNIQUEIDENTIFIER"); } + public override Schema.IDataBaseSchema GetDataBaseSchema(DbConnection connection) + { + return new Schema.SQLiteDataBaseMetaData(connection); + } + + public override string AddColumnString + { + get + { + return "add column"; + } + } + public override string IdentitySelectString { get { return "select last_insert_rowid()"; } Added: trunk/nhibernate/src/NHibernate/Dialect/Schema/SQLiteMetaData.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/Schema/SQLiteMetaData.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Dialect/Schema/SQLiteMetaData.cs 2008-11-08 16:09:54 UTC (rev 3899) @@ -0,0 +1,102 @@ +using System; +using System.Data; +using System.Data.Common; + +namespace NHibernate.Dialect.Schema +{ + public class SQLiteDataBaseMetaData : AbstractDataBaseSchema + { + public SQLiteDataBaseMetaData(DbConnection connection) : base(connection) {} + + public override ITableMetadata GetTableMetadata(DataRow rs, bool extras) + { + return new SQLiteTableMetaData(rs, this, extras); + } + } + + public class SQLiteTableMetaData : AbstractTableMetadata + { + public SQLiteTableMetaData(DataRow rs, IDataBaseSchema meta, bool extras) : base(rs, meta, extras) {} + + protected override IColumnMetadata GetColumnMetadata(DataRow rs) + { + return new SQLiteColumnMetaData(rs); + } + + protected override string GetColumnName(DataRow rs) + { + return Convert.ToString(rs["COLUMN_NAME"]); + } + + protected override string GetConstraintName(DataRow rs) + { + throw new NotImplementedException(); + } + + protected override IForeignKeyMetadata GetForeignKeyMetadata(DataRow rs) + { + return new SQLiteForeignKeyMetaData(rs); + } + + protected override IIndexMetadata GetIndexMetadata(DataRow rs) + { + return new SQLiteIndexMetaData(rs); + } + + protected override string GetIndexName(DataRow rs) + { + return Convert.ToString(rs["INDEX_NAME"]); + } + + protected override void ParseTableInfo(DataRow rs) + { + Catalog = Convert.ToString(rs["TABLE_CATALOG"]); + Schema = Convert.ToString(rs["TABLE_SCHEMA"]); + if (string.IsNullOrEmpty(Catalog)) + { + Catalog = null; + } + if (string.IsNullOrEmpty(Schema)) + { + Schema = null; + } + Name = Convert.ToString(rs["TABLE_NAME"]); + } + } + + public class SQLiteColumnMetaData : AbstractColumnMetaData + { + public SQLiteColumnMetaData(DataRow rs) : base(rs) + { + Name = Convert.ToString(rs["COLUMN_NAME"]); + object objValue = rs["CHARACTER_MAXIMUM_LENGTH"]; + if (objValue != DBNull.Value) + { + ColumnSize = Convert.ToInt32(objValue); + } + objValue = rs["NUMERIC_PRECISION"]; + if (objValue != DBNull.Value) + { + NumericalPrecision = Convert.ToInt32(objValue); + } + Nullable = Convert.ToString(rs["IS_NULLABLE"]); + TypeName = Convert.ToString(rs["DATA_TYPE"]); + } + } + + public class SQLiteIndexMetaData : AbstractIndexMetadata + { + public SQLiteIndexMetaData(DataRow rs) : base(rs) + { + Name = Convert.ToString(rs["INDEX_NAME"]); + } + } + + public class SQLiteForeignKeyMetaData : AbstractForeignKeyMetadata + { + public SQLiteForeignKeyMetaData(DataRow rs) : base(rs) + { + Name = Convert.ToString(rs["CONSTRAINT_NAME"]); + } + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-08 15:58:07 UTC (rev 3898) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-08 16:09:54 UTC (rev 3899) @@ -443,6 +443,7 @@ <Compile Include="Bytecode\HibernateByteCodeException.cs" /> <Compile Include="Bytecode\ProxyFactoryFactoryNotConfiguredException.cs" /> <Compile Include="Bytecode\UnableToLoadProxyFactoryFactoryException.cs" /> + <Compile Include="Dialect\Schema\SQLiteMetaData.cs" /> <Compile Include="Id\SelectGenerator.cs" /> <Compile Include="Properties\BackFieldStrategy.cs" /> <Compile Include="Bytecode\CodeDom\BytecodeProviderImpl.cs" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-11-08 17:07:58
|
Revision: 3901 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3901&view=rev Author: fabiomaulo Date: 2008-11-08 17:07:55 +0000 (Sat, 08 Nov 2008) Log Message: ----------- Fix NH-1561 by Mark Junker (with modifications) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Dialect/Schema/AbstractDataBaseSchema.cs trunk/nhibernate/src/NHibernate/NHibernate.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate/Dialect/Schema/SybaseAnywhereMetaData.cs trunk/nhibernate/src/NHibernate/Dialect/SybaseASA10Dialect.cs trunk/nhibernate/src/NHibernate/Dialect/SybaseASA9Dialect.cs Modified: trunk/nhibernate/src/NHibernate/Dialect/Schema/AbstractDataBaseSchema.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/Schema/AbstractDataBaseSchema.cs 2008-11-08 16:15:12 UTC (rev 3900) +++ trunk/nhibernate/src/NHibernate/Dialect/Schema/AbstractDataBaseSchema.cs 2008-11-08 17:07:55 UTC (rev 3901) @@ -20,6 +20,11 @@ this.connection = connection; } + protected DbConnection Connection + { + get { return connection; } + } + #region IDataBaseSchema Members public virtual bool StoresMixedCaseQuotedIdentifiers Added: trunk/nhibernate/src/NHibernate/Dialect/Schema/SybaseAnywhereMetaData.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/Schema/SybaseAnywhereMetaData.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Dialect/Schema/SybaseAnywhereMetaData.cs 2008-11-08 17:07:55 UTC (rev 3901) @@ -0,0 +1,139 @@ +using System; +using System.Data; +using System.Data.Common; + +namespace NHibernate.Dialect.Schema +{ + // Metadata for connections using the iAnywhere.Data.SQLAnywhere ADO.NET provider + public class SybaseAnywhereDataBaseMetaData : AbstractDataBaseSchema + { + public SybaseAnywhereDataBaseMetaData(DbConnection pObjConnection) : base(pObjConnection) {} + + public override ITableMetadata GetTableMetadata(DataRow rs, bool extras) + { + return new SybaseAnywhereTableMetaData(rs, this, extras); + } + + public override DataTable GetTables(string catalog, string schemaPattern, string tableNamePattern, string[] types) + { + var restrictions = new[] {schemaPattern, tableNamePattern, null}; + DataTable objTbl = Connection.GetSchema("Tables", restrictions); + return objTbl; + } + + public override DataTable GetIndexInfo(string catalog, string schemaPattern, string tableName) + { + var restrictions = new[] {schemaPattern, tableName, null}; + DataTable objTbl = Connection.GetSchema("Indexes", restrictions); + return objTbl; + } + + public override DataTable GetIndexColumns(string catalog, string schemaPattern, string tableName, string indexName) + { + var restrictions = new[] {schemaPattern, tableName, indexName, null}; + DataTable objTbl = Connection.GetSchema("IndexColumns", restrictions); + return objTbl; + } + + public override DataTable GetColumns(string catalog, string schemaPattern, string tableNamePattern, + string columnNamePattern) + { + var restrictions = new[] {schemaPattern, tableNamePattern, null}; + DataTable objTbl = Connection.GetSchema("Columns", restrictions); + return objTbl; + } + + public override DataTable GetForeignKeys(string catalog, string schema, string table) + { + var restrictions = new[] {schema, table, null}; + DataTable objTbl = Connection.GetSchema("ForeignKeys", restrictions); + return objTbl; + } + } + + public class SybaseAnywhereTableMetaData : AbstractTableMetadata + { + public SybaseAnywhereTableMetaData(DataRow rs, IDataBaseSchema meta, bool extras) : base(rs, meta, extras) {} + + protected override IColumnMetadata GetColumnMetadata(DataRow rs) + { + return new SybaseAnywhereColumnMetaData(rs); + } + + protected override string GetColumnName(DataRow rs) + { + return Convert.ToString(rs["COLUMN_NAME"]); + } + + protected override string GetConstraintName(DataRow rs) + { + // There is no thing like a constraint name for ASA9 - so + // we just use the column name here ... + return Convert.ToString(rs["COLUMN_NAME"]); + } + + protected override IForeignKeyMetadata GetForeignKeyMetadata(DataRow rs) + { + return new SybaseAnywhereForeignKeyMetaData(rs); + } + + protected override IIndexMetadata GetIndexMetadata(DataRow rs) + { + return new SybaseAnywhereIndexMetaData(rs); + } + + protected override string GetIndexName(DataRow rs) + { + return (string) rs["INDEX_NAME"]; + } + + protected override void ParseTableInfo(DataRow rs) + { + Catalog = null; + Schema = Convert.ToString(rs["TABLE_SCHEMA"]); + if (string.IsNullOrEmpty(Schema)) + { + Schema = null; + } + Name = Convert.ToString(rs["TABLE_NAME"]); + } + } + + public class SybaseAnywhereColumnMetaData : AbstractColumnMetaData + { + public SybaseAnywhereColumnMetaData(DataRow rs) : base(rs) + { + Name = Convert.ToString(rs["COLUMN_NAME"]); + object objValue = rs["COLUMN_SIZE"]; + if (objValue != DBNull.Value) + { + ColumnSize = Convert.ToInt32(objValue); + } + objValue = rs["PRECISION"]; + if (objValue != DBNull.Value) + { + NumericalPrecision = Convert.ToInt32(objValue); + } + Nullable = Convert.ToString(rs["IS_NULLABLE"]); + TypeName = Convert.ToString(rs["DATA_TYPE"]); + } + } + + public class SybaseAnywhereIndexMetaData : AbstractIndexMetadata + { + public SybaseAnywhereIndexMetaData(DataRow rs) : base(rs) + { + Name = (string) rs["INDEX_NAME"]; + } + } + + public class SybaseAnywhereForeignKeyMetaData : AbstractForeignKeyMetadata + { + public SybaseAnywhereForeignKeyMetaData(DataRow rs) : base(rs) + { + // There is no thing like a constraint name for ASA9 - so + // we just use the column name here ... + Name = (string) rs["COLUMN_NAME"]; + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate/Dialect/SybaseASA10Dialect.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/SybaseASA10Dialect.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Dialect/SybaseASA10Dialect.cs 2008-11-08 17:07:55 UTC (rev 3901) @@ -0,0 +1,15 @@ +using System.Data; + +namespace NHibernate.Dialect +{ + public class SybaseASA10Dialect : SybaseASA9Dialect + { + public SybaseASA10Dialect() + { + RegisterColumnType(DbType.StringFixedLength, 255, "NCHAR($l)"); + RegisterColumnType(DbType.String, 1073741823, "LONG NVARCHAR"); + RegisterColumnType(DbType.String, 255, "NVARCHAR($l)"); + RegisterColumnType(DbType.String, "LONG NVARCHAR"); + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate/Dialect/SybaseASA9Dialect.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/SybaseASA9Dialect.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Dialect/SybaseASA9Dialect.cs 2008-11-08 17:07:55 UTC (rev 3901) @@ -0,0 +1,91 @@ +using System.Data; +using System.Data.Common; +using NHibernate.Dialect.Function; +using NHibernate.Dialect.Schema; +using NHibernate.SqlCommand; + +namespace NHibernate.Dialect +{ + public class SybaseASA9Dialect : SybaseAnywhereDialect + { + public SybaseASA9Dialect() + { + RegisterColumnType(DbType.AnsiStringFixedLength, 255, "CHAR($l)"); + RegisterColumnType(DbType.AnsiString, "VARCHAR(255)"); + RegisterColumnType(DbType.AnsiString, 255, "VARCHAR($l)"); + RegisterColumnType(DbType.AnsiString, 2147483647, "LONG VARCHAR"); // should use the IType.ClobType + RegisterColumnType(DbType.Binary, "BINARY(255)"); + RegisterColumnType(DbType.Binary, 2147483647, "LONG BINARY"); // should use the IType.BlobType + RegisterColumnType(DbType.Boolean, "BIT"); + RegisterColumnType(DbType.Byte, "SMALLINT"); + RegisterColumnType(DbType.Currency, "DECIMAL(18,4)"); + RegisterColumnType(DbType.Date, "DATE"); + RegisterColumnType(DbType.DateTime, "TIMESTAMP"); + RegisterColumnType(DbType.Decimal, "DECIMAL(18,5)"); // NUMERIC(18,5) is equivalent to DECIMAL(18,5) + RegisterColumnType(DbType.Decimal, 18, "DECIMAL(18,$l)"); + RegisterColumnType(DbType.Double, "DOUBLE"); + RegisterColumnType(DbType.Guid, "CHAR(16)"); + RegisterColumnType(DbType.Int16, "SMALLINT"); + RegisterColumnType(DbType.Int32, "INTEGER"); + RegisterColumnType(DbType.Int64, "BIGINT"); + RegisterColumnType(DbType.Single, "FLOAT"); + RegisterColumnType(DbType.StringFixedLength, 255, "CHAR($l)"); + RegisterColumnType(DbType.String, 1073741823, "LONG VARCHAR"); + RegisterColumnType(DbType.String, 255, "VARCHAR($l)"); + RegisterColumnType(DbType.String, "LONG VARCHAR"); + RegisterColumnType(DbType.Time, "TIME"); + RegisterColumnType(DbType.SByte, "SMALLINT"); + RegisterColumnType(DbType.UInt16, "UNSIGNED SMALLINT"); + RegisterColumnType(DbType.UInt32, "UNSIGNED INT"); + RegisterColumnType(DbType.UInt64, "UNSIGNED BIGINT"); + RegisterColumnType(DbType.VarNumeric, "NUMERIC($l)"); + //RegisterColumnType(DbType.Xml, "TEXT"); + + // Override standard HQL function + RegisterFunction("current_timestamp", new StandardSQLFunction("current_timestamp")); + RegisterFunction("length", new StandardSafeSQLFunction("length", NHibernateUtil.String, 1)); + RegisterFunction("substring", new AnsiSubstringFunction()); + RegisterFunction("nullif", new StandardSafeSQLFunction("nullif", 2)); + RegisterFunction("lower", new StandardSafeSQLFunction("lower", NHibernateUtil.String, 1)); + RegisterFunction("upper", new StandardSafeSQLFunction("upper", NHibernateUtil.String, 1)); + ; + RegisterFunction("now", new StandardSQLFunction("now")); + } + + public override bool SupportsLimit + { + get { return true; } + } + + public override bool SupportsVariableLimit + { + get { return false; } + } + + public override SqlString GetLimitString(SqlString querySqlString, int offset, int limit) + { + int intSelectInsertPoint = GetAfterSelectInsertPoint(querySqlString); + string strLimit = string.Format(" TOP {0} START AT {1}", limit, offset + 1); + return querySqlString.Insert(intSelectInsertPoint, strLimit); + } + + public override IDataBaseSchema GetDataBaseSchema(DbConnection connection) + { + return new SybaseAnywhereDataBaseMetaData(connection); + } + + private static int GetAfterSelectInsertPoint(SqlString sql) + { + string[] arrSelectStrings = {"select distinct", "select all", "select"}; + for (int i = 0; i != arrSelectStrings.Length; ++i) + { + string strSelect = arrSelectStrings[i]; + if (sql.StartsWithCaseInsensitive(strSelect)) + { + return strSelect.Length; + } + } + return 0; + } + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-08 16:15:12 UTC (rev 3900) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-08 17:07:55 UTC (rev 3901) @@ -444,6 +444,9 @@ <Compile Include="Bytecode\ProxyFactoryFactoryNotConfiguredException.cs" /> <Compile Include="Bytecode\UnableToLoadProxyFactoryFactoryException.cs" /> <Compile Include="Dialect\Schema\SQLiteMetaData.cs" /> + <Compile Include="Dialect\Schema\SybaseAnywhereMetaData.cs" /> + <Compile Include="Dialect\SybaseASA10Dialect.cs" /> + <Compile Include="Dialect\SybaseASA9Dialect.cs" /> <Compile Include="Id\SelectGenerator.cs" /> <Compile Include="Properties\BackFieldStrategy.cs" /> <Compile Include="Bytecode\CodeDom\BytecodeProviderImpl.cs" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-11-08 21:21:02
|
Revision: 3902 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3902&view=rev Author: fabiomaulo Date: 2008-11-08 21:20:57 +0000 (Sat, 08 Nov 2008) Log Message: ----------- Improv: ignore transient entities when on session.Refresh Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Event/Default/DefaultRefreshEventListener.cs trunk/nhibernate/src/NHibernate.Test/Cascade/RefreshFixture.cs Modified: trunk/nhibernate/src/NHibernate/Event/Default/DefaultRefreshEventListener.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Event/Default/DefaultRefreshEventListener.cs 2008-11-08 17:07:55 UTC (rev 3901) +++ trunk/nhibernate/src/NHibernate/Event/Default/DefaultRefreshEventListener.cs 2008-11-08 21:20:57 UTC (rev 3902) @@ -97,8 +97,10 @@ source.FetchProfile = "refresh"; object result = persister.Load(id, obj, @event.LockMode, source); source.FetchProfile = previousFetchProfile; - - UnresolvableObjectException.ThrowIfNull(result, id, persister.EntityName); + // NH Different behavior : we are ignoring transient entities without throw any kind of exception + // because a transient entity is "self refreshed" + if (!ForeignKeys.IsTransient(persister.EntityName, obj, result == null, @event.Session)) + UnresolvableObjectException.ThrowIfNull(result, id, persister.EntityName); } // Evict collections from the factory-level cache Modified: trunk/nhibernate/src/NHibernate.Test/Cascade/RefreshFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Cascade/RefreshFixture.cs 2008-11-08 17:07:55 UTC (rev 3901) +++ trunk/nhibernate/src/NHibernate.Test/Cascade/RefreshFixture.cs 2008-11-08 21:20:57 UTC (rev 3902) @@ -16,7 +16,7 @@ protected override IList Mappings { - get { return new string[] { "Cascade.Job.hbm.xml", "Cascade.JobBatch.hbm.xml" }; } + get { return new[] { "Cascade.Job.hbm.xml", "Cascade.JobBatch.hbm.xml" }; } } [Test] @@ -57,5 +57,58 @@ session.Transaction.Enlist(cmd); cmd.ExecuteNonQuery(); } + + [Test] + public void RefreshIgnoringTransient() + { + // No exception expected + ISession session = OpenSession(); + ITransaction txn = session.BeginTransaction(); + + var batch = new JobBatch(DateTime.Now); + session.Refresh(batch); + + txn.Rollback(); + session.Close(); + } + + [Test] + public void RefreshIgnoringTransientInCollection() + { + ISession session = OpenSession(); + ITransaction txn = session.BeginTransaction(); + + var batch = new JobBatch(DateTime.Now); + batch.CreateJob().ProcessingInstructions = "Just do it!"; + session.Persist(batch); + session.Flush(); + + batch.CreateJob().ProcessingInstructions = "I know you can do it!"; + session.Refresh(batch); + Assert.That(batch.Jobs.Count == 1); + + txn.Rollback(); + session.Close(); + } + + [Test] + public void RefreshNotIgnoringTransientByUnsavedValue() + { + ISession session = OpenSession(); + ITransaction txn = session.BeginTransaction(); + + var batch = new JobBatch { BatchDate = DateTime.Now, Id = 1 }; + try + { + session.Refresh(batch); + } + catch (UnresolvableObjectException) + { + // as expected + txn.Rollback(); + session.Close(); + } + } + } } \ 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-11-08 21:55:40
|
Revision: 3903 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3903&view=rev Author: fabiomaulo Date: 2008-11-08 21:31:30 +0000 (Sat, 08 Nov 2008) Log Message: ----------- Little refactoring Modified Paths: -------------- trunk/nhibernate/src/NHibernate/NHibernate.csproj trunk/nhibernate/src/NHibernate/Type/EnumStringType.cs Removed Paths: ------------- trunk/nhibernate/src/NHibernate/Type/EnumStringType`1.cs Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-08 21:20:57 UTC (rev 3902) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-08 21:31:30 UTC (rev 3903) @@ -1063,7 +1063,6 @@ <Compile Include="Type\CustomCollectionType.cs" /> <Compile Include="Type\EmbeddedComponentType.cs" /> <Compile Include="Type\EnumCharType.cs" /> - <Compile Include="Type\EnumStringType`1.cs" /> <Compile Include="Type\GenericOrderedSetType.cs" /> <Compile Include="Type\ICacheAssembler.cs" /> <Compile Include="Type\OrderedSetType.cs" /> Modified: trunk/nhibernate/src/NHibernate/Type/EnumStringType.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Type/EnumStringType.cs 2008-11-08 21:20:57 UTC (rev 3902) +++ trunk/nhibernate/src/NHibernate/Type/EnumStringType.cs 2008-11-08 21:31:30 UTC (rev 3903) @@ -2,7 +2,6 @@ using System.Data; using NHibernate.Engine; using NHibernate.SqlTypes; -using NHibernate.Util; namespace NHibernate.Type { @@ -64,7 +63,6 @@ [Serializable] public abstract class EnumStringType : AbstractEnumType { - /// <summary> /// Hardcoding of <c>255</c> for the maximum length /// of the Enum name that will be saved to the db. @@ -79,20 +77,27 @@ /// Initializes a new instance of <see cref="EnumStringType"/>. /// </summary> /// <param name="enumClass">The <see cref="System.Type"/> of the Enum.</param> - protected EnumStringType(System.Type enumClass) - : this(enumClass, MaxLengthForEnumString) - { - } + protected EnumStringType(System.Type enumClass) : this(enumClass, MaxLengthForEnumString) {} /// <summary> /// Initializes a new instance of <see cref="EnumStringType"/>. /// </summary> /// <param name="enumClass">The <see cref="System.Type"/> of the Enum.</param> /// <param name="length">The length of the string that can be written to the column.</param> - protected EnumStringType(System.Type enumClass, int length) - :base(SqlTypeFactory.GetString(length),enumClass) - { + protected EnumStringType(System.Type enumClass, int length) : base(SqlTypeFactory.GetString(length), enumClass) {} + /// <summary> + /// + /// </summary> + /// <remarks> + /// This appends <c>enumstring - </c> to the beginning of the underlying + /// enums name so that <see cref="System.Enum"/> could still be stored + /// using the underlying value through the <see cref="PersistentEnumType"/> + /// also. + /// </remarks> + public override string Name + { + get { return "enumstring - " + ReturnedClass.Name; } } /// <summary> @@ -109,7 +114,7 @@ } catch (ArgumentException ae) { - throw new HibernateException(string.Format("Can't Parse {0} as {1}", code, this.ReturnedClass.Name), ae); + throw new HibernateException(string.Format("Can't Parse {0} as {1}", code, ReturnedClass.Name), ae); } } @@ -132,14 +137,14 @@ /// <param name="index"></param> public override void Set(IDbCommand cmd, object value, int index) { - IDataParameter par = (IDataParameter) cmd.Parameters[index]; + var par = (IDataParameter) cmd.Parameters[index]; if (value == null) { par.Value = DBNull.Value; } else { - par.Value = Enum.Format(this.ReturnedClass, value, "G"); + par.Value = Enum.Format(ReturnedClass, value, "G"); } } @@ -176,20 +181,6 @@ /// <summary> /// /// </summary> - /// <remarks> - /// This appends <c>enumstring - </c> to the beginning of the underlying - /// enums name so that <see cref="System.Enum"/> could still be stored - /// using the underlying value through the <see cref="PersistentEnumType"/> - /// also. - /// </remarks> - public override string Name - { - get { return "enumstring - " + this.ReturnedClass.Name; } - } - - /// <summary> - /// - /// </summary> /// <param name="value"></param> /// <returns></returns> public override string ToString(object value) @@ -221,10 +212,15 @@ return (value == null) ? null : GetValue(value); } - public override string ObjectToSQLString(object value, Dialect.Dialect dialect) { return GetValue(value).ToString(); } } + + [Serializable] + public class EnumStringType<T> : EnumStringType + { + public EnumStringType() : base(typeof (T)) {} + } } \ No newline at end of file Deleted: trunk/nhibernate/src/NHibernate/Type/EnumStringType`1.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Type/EnumStringType`1.cs 2008-11-08 21:20:57 UTC (rev 3902) +++ trunk/nhibernate/src/NHibernate/Type/EnumStringType`1.cs 2008-11-08 21:31:30 UTC (rev 3903) @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace NHibernate.Type -{ - [Serializable] - public class EnumStringType<T> : EnumStringType - { - public EnumStringType():base(typeof(T)) - { - - } - } -} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-11-10 13:31:03
|
Revision: 3904 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3904&view=rev Author: fabiomaulo Date: 2008-11-10 13:31:01 +0000 (Mon, 10 Nov 2008) Log Message: ----------- Revert patch NH-1155 because are breaking all dialect with SupportsVariableLimit=true. Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Engine/SubselectFetch.cs trunk/nhibernate/src/NHibernate/Loader/Loader.cs trunk/nhibernate/src/NHibernate.Test/Criteria/CriteriaQueryTest.cs trunk/nhibernate/src/NHibernate.Test/SubselectFetchTest/SubselectFetchFixture.cs Modified: trunk/nhibernate/src/NHibernate/Engine/SubselectFetch.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Engine/SubselectFetch.cs 2008-11-08 21:31:30 UTC (rev 3903) +++ trunk/nhibernate/src/NHibernate/Engine/SubselectFetch.cs 2008-11-10 13:31:01 UTC (rev 3904) @@ -8,23 +8,21 @@ { public class SubselectFetch { - private readonly ISet<EntityKey> resultingEntityKeys; - private readonly SqlString queryString; private readonly string alias; - private readonly Dialect.Dialect dialect; private readonly ILoadable loadable; - private readonly QueryParameters queryParameters; private readonly IDictionary<string, int[]> namedParameterLocMap; + private readonly QueryParameters queryParameters; + private readonly SqlString queryString; + private readonly ISet<EntityKey> resultingEntityKeys; - public SubselectFetch(string alias, Dialect.Dialect dialect, ILoadable loadable, QueryParameters queryParameters, - ISet<EntityKey> resultingEntityKeys, IDictionary<string, int[]> namedParameterLocMap) + public SubselectFetch(string alias, ILoadable loadable, QueryParameters queryParameters, + ISet<EntityKey> resultingEntityKeys, IDictionary<string, int[]> namedParameterLocMap) { this.resultingEntityKeys = resultingEntityKeys; this.queryParameters = queryParameters; this.namedParameterLocMap = namedParameterLocMap; this.loadable = loadable; this.alias = alias; - this.dialect = dialect; queryString = queryParameters.FilteredSQL.GetSubselectString(); } @@ -39,6 +37,11 @@ get { return resultingEntityKeys; } } + public IDictionary<string, int[]> NamedParameterLocMap + { + get { return namedParameterLocMap; } + } + public SqlString ToSubselectString(string ukname) { string[] joinColumns = ukname == null @@ -47,39 +50,12 @@ SqlString sqlString = new SqlStringBuilder().Add("select ").Add(StringHelper.Join(", ", joinColumns)).Add(queryString).ToSqlString(); - - RowSelection selection = queryParameters.RowSelection; - - bool useLimit = Loader.Loader.UseLimit(selection, dialect); - bool hasFirstRow = Loader.Loader.GetFirstRow(selection) > 0; - bool useOffset = hasFirstRow && useLimit && dialect.SupportsLimitOffset; - - if ((useLimit || hasFirstRow) == false) - { - return sqlString; - } - - sqlString = AppendOrderByIfNeeded(sqlString); - - return - dialect.GetLimitString(sqlString.Trim(), useOffset ? Loader.Loader.GetFirstRow(selection) : 0, - Loader.Loader.GetMaxOrLimit(dialect, selection)); + return sqlString; } - private SqlString AppendOrderByIfNeeded(SqlString sqlString) - { - SqlString orderByOrEmpty = queryParameters.FilteredSQL.SubstringStartingWithLast("order by"); - return sqlString.Append(orderByOrEmpty); - } - public override string ToString() { return "SubselectFetch(" + queryString + ')'; } - - public IDictionary<string, int[]> NamedParameterLocMap - { - get { return namedParameterLocMap; } - } } } \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Loader/Loader.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Loader/Loader.cs 2008-11-08 21:31:30 UTC (rev 3903) +++ trunk/nhibernate/src/NHibernate/Loader/Loader.cs 2008-11-10 13:31:01 UTC (rev 3904) @@ -516,7 +516,7 @@ if (rowKeys[i] != null && loadables[i].HasSubselectLoadableCollections) { SubselectFetch subselectFetch = - new SubselectFetch(aliases[i], factory.Dialect, loadables[i], queryParameters, keySets[i], namedParameterLocMap); + new SubselectFetch(aliases[i], loadables[i], queryParameters, keySets[i], namedParameterLocMap); session.PersistenceContext.BatchFetchQueue.AddSubselect(rowKeys[i], subselectFetch); } Modified: trunk/nhibernate/src/NHibernate.Test/Criteria/CriteriaQueryTest.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Criteria/CriteriaQueryTest.cs 2008-11-08 21:31:30 UTC (rev 3903) +++ trunk/nhibernate/src/NHibernate.Test/Criteria/CriteriaQueryTest.cs 2008-11-10 13:31:01 UTC (rev 3904) @@ -431,7 +431,7 @@ s.Close(); } - [Test] + [Test, Ignore("Not supported.")] public void NH_1155_ShouldNotLoadAllChildrenInPagedSubSelect() { if (this.Dialect.GetType().Equals((typeof(MsSql2000Dialect)))) Modified: trunk/nhibernate/src/NHibernate.Test/SubselectFetchTest/SubselectFetchFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/SubselectFetchTest/SubselectFetchFixture.cs 2008-11-08 21:31:30 UTC (rev 3903) +++ trunk/nhibernate/src/NHibernate.Test/SubselectFetchTest/SubselectFetchFixture.cs 2008-11-10 13:31:01 UTC (rev 3904) @@ -248,7 +248,7 @@ Assert.AreEqual(3, sessions.Statistics.PrepareStatementCount); r = (Parent) s.Get(typeof(Parent), r.Name); - Assert.IsFalse(NHibernateUtil.IsInitialized(r.Children)); + Assert.IsTrue(NHibernateUtil.IsInitialized(r.Children)); // The test for True is the test of H3.2 Assert.IsFalse(NHibernateUtil.IsInitialized(r.MoreChildren)); Assert.AreEqual(r.Children.Count, 1); Assert.AreEqual(r.MoreChildren.Count, 0); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <te...@us...> - 2008-11-13 18:08:12
|
Revision: 3908 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3908&view=rev Author: tehlike Date: 2008-11-13 18:08:08 +0000 (Thu, 13 Nov 2008) Log Message: ----------- Minor. Modified Paths: -------------- trunk/nhibernate/src/NHibernate/NHibernate.csproj trunk/nhibernate/src/NHibernate/Type/BinaryType.cs Added Paths: ----------- trunk/nhibernate/src/NHibernate/Type/AbstractBinaryType.cs Removed Paths: ------------- trunk/nhibernate/src/NHibernate/Type/AbstractBynaryType.cs Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-12 02:40:14 UTC (rev 3907) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-13 18:08:08 UTC (rev 3908) @@ -1052,7 +1052,7 @@ <Compile Include="Tuple\StandardProperty.cs" /> <Compile Include="Tuple\VersionProperty.cs" /> <Compile Include="TypeMismatchException.cs" /> - <Compile Include="Type\AbstractBynaryType.cs" /> + <Compile Include="Type\AbstractBinaryType.cs" /> <Compile Include="Type\AbstractEnumType.cs" /> <Compile Include="Type\AbstractStringType.cs" /> <Compile Include="Type\AnsiCharType.cs" /> Copied: trunk/nhibernate/src/NHibernate/Type/AbstractBinaryType.cs (from rev 3907, trunk/nhibernate/src/NHibernate/Type/AbstractBynaryType.cs) =================================================================== --- trunk/nhibernate/src/NHibernate/Type/AbstractBinaryType.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Type/AbstractBinaryType.cs 2008-11-13 18:08:08 UTC (rev 3908) @@ -0,0 +1,179 @@ +using System; +using System.Collections; +using System.Data; +using System.Text; +using NHibernate.Engine; +using NHibernate.SqlTypes; +using NHibernate.Util; + +namespace NHibernate.Type +{ + /// <summary> Logic to bind stream of byte into a VARBINARY </summary> + [Serializable] + public abstract class AbstractBinaryType : MutableType, IVersionType, IComparer + { + internal AbstractBinaryType() : this(new BinarySqlType()) + { + } + + internal AbstractBinaryType(BinarySqlType sqlType) + : base(sqlType) + { + } + + + #region IVersionType Members + // Note : simply returns null for seed() and next() as the only known + // application of binary types for versioning is for use with the + // TIMESTAMP datatype supported by Sybase and SQL Server, which + // are completely db-generated values... + + public object Next(object current, ISessionImplementor session) + { + return current; + } + + public object Seed(ISessionImplementor session) + { + return null; + } + + public override bool IsEqual(object x, object y) + { + if (x == y) + return true; + + if (x == null || y == null) + return false; + + return CollectionHelper.CollectionEquals<byte>(ToInternalFormat(x), ToInternalFormat(y)); + } + + public IComparer Comparator + { + get { return this; } + } + + #endregion + + #region IComparer Members + + public virtual int Compare(object x, object y) + { + return Compare(x, y, null); + } + + #endregion + + public abstract override string Name { get;} + + /// <summary> Convert the byte[] into the expected object type</summary> + protected internal abstract object ToExternalFormat(byte[] bytes); + + /// <summary> Convert the object into the internal byte[] representation</summary> + protected internal abstract byte[] ToInternalFormat(object bytes); + + public override void Set(IDbCommand cmd, object value, int index) + { + byte[] internalValue = ToInternalFormat(value); + ((IDataParameter)cmd.Parameters[index]).Value = internalValue; + } + + public override object Get(IDataReader rs, int index) + { + int length = (int)rs.GetBytes(index, 0, null, 0, 0); + byte[] buffer = new byte[length]; + + int offset = 0; + + while (length - offset > 0) + { + int countRead = (int)rs.GetBytes(index, offset, buffer, offset, length - offset); + offset += countRead; + + if (countRead == 0) + { + // Should never happen + throw new AssertionFailure("Error in BinaryType.Get, IDataRecord.GetBytes read zero bytes"); + } + } + return ToExternalFormat(buffer); + } + + public override object Get(IDataReader rs, string name) + { + return Get(rs, rs.GetOrdinal(name)); + } + + public override int GetHashCode(object x, EntityMode entityMode) + { + byte[] bytes = ToInternalFormat(x); + int hashCode = 1; + unchecked + { + for (int j = 0; j < bytes.Length; j++) + { + hashCode = 31 * hashCode + bytes[j]; + } + } + return hashCode; + } + + public override int Compare(object x, object y, EntityMode? entityMode) + { + byte[] xbytes = ToInternalFormat(x); + byte[] ybytes = ToInternalFormat(y); + if (xbytes.Length < ybytes.Length) + return -1; + if (xbytes.Length > ybytes.Length) + return 1; + for (int i = 0; i < xbytes.Length; i++) + { + if (xbytes[i] < ybytes[i]) + return -1; + if (xbytes[i] > ybytes[i]) + return 1; + } + return 0; + } + + public override string ToString(object val) + { + // convert to HEX string + byte[] bytes = ToInternalFormat(val); + StringBuilder buf = new StringBuilder(); + for (int i = 0; i < bytes.Length; i++) + { + String hexStr = Convert.ToString(bytes[i] - Byte.MinValue, 16); + if (hexStr.Length == 1) + buf.Append('0'); + buf.Append(hexStr); + } + return buf.ToString(); + } + + public override object DeepCopyNotNull(object value) + { + byte[] bytes = ToInternalFormat(value); + byte[] result = new byte[bytes.Length]; + Array.Copy(bytes, 0, result, 0, bytes.Length); + return ToExternalFormat(result); + } + + public override object FromStringValue(string xml) + { + if (xml == null) + return null; + if (xml.Length % 2 != 0) + throw new ArgumentException("The string is not a valid xml representation of a binary content."); + + byte[] bytes = new byte[xml.Length / 2]; + for (int i = 0; i < bytes.Length; i++) + { + string hexStr = xml.Substring(i * 2, ((i + 1) * 2) - (i * 2)); + bytes[i] = (byte)(Convert.ToInt32(hexStr, 16) + Byte.MinValue); + } + return ToExternalFormat(bytes); + } + } +} Property changes on: trunk/nhibernate/src/NHibernate/Type/AbstractBinaryType.cs ___________________________________________________________________ Added: svn:mergeinfo + Deleted: trunk/nhibernate/src/NHibernate/Type/AbstractBynaryType.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Type/AbstractBynaryType.cs 2008-11-12 02:40:14 UTC (rev 3907) +++ trunk/nhibernate/src/NHibernate/Type/AbstractBynaryType.cs 2008-11-13 18:08:08 UTC (rev 3908) @@ -1,179 +0,0 @@ -using System; -using System.Collections; -using System.Data; -using System.Text; -using NHibernate.Engine; -using NHibernate.SqlTypes; -using NHibernate.Util; - -namespace NHibernate.Type -{ - /// <summary> Logic to bind stream of byte into a VARBINARY </summary> - [Serializable] - public abstract class AbstractBynaryType : MutableType, IVersionType, IComparer - { - internal AbstractBynaryType() : this(new BinarySqlType()) - { - } - - internal AbstractBynaryType(BinarySqlType sqlType) - : base(sqlType) - { - } - - - #region IVersionType Members - // Note : simply returns null for seed() and next() as the only known - // application of binary types for versioning is for use with the - // TIMESTAMP datatype supported by Sybase and SQL Server, which - // are completely db-generated values... - - public object Next(object current, ISessionImplementor session) - { - return current; - } - - public object Seed(ISessionImplementor session) - { - return null; - } - - public override bool IsEqual(object x, object y) - { - if (x == y) - return true; - - if (x == null || y == null) - return false; - - return CollectionHelper.CollectionEquals<byte>(ToInternalFormat(x), ToInternalFormat(y)); - } - - public IComparer Comparator - { - get { return this; } - } - - #endregion - - #region IComparer Members - - public virtual int Compare(object x, object y) - { - return Compare(x, y, null); - } - - #endregion - - public abstract override string Name { get;} - - /// <summary> Convert the byte[] into the expected object type</summary> - protected internal abstract object ToExternalFormat(byte[] bytes); - - /// <summary> Convert the object into the internal byte[] representation</summary> - protected internal abstract byte[] ToInternalFormat(object bytes); - - public override void Set(IDbCommand cmd, object value, int index) - { - byte[] internalValue = ToInternalFormat(value); - ((IDataParameter)cmd.Parameters[index]).Value = internalValue; - } - - public override object Get(IDataReader rs, int index) - { - int length = (int)rs.GetBytes(index, 0, null, 0, 0); - byte[] buffer = new byte[length]; - - int offset = 0; - - while (length - offset > 0) - { - int countRead = (int)rs.GetBytes(index, offset, buffer, offset, length - offset); - offset += countRead; - - if (countRead == 0) - { - // Should never happen - throw new AssertionFailure("Error in BinaryType.Get, IDataRecord.GetBytes read zero bytes"); - } - } - return ToExternalFormat(buffer); - } - - public override object Get(IDataReader rs, string name) - { - return Get(rs, rs.GetOrdinal(name)); - } - - public override int GetHashCode(object x, EntityMode entityMode) - { - byte[] bytes = ToInternalFormat(x); - int hashCode = 1; - unchecked - { - for (int j = 0; j < bytes.Length; j++) - { - hashCode = 31 * hashCode + bytes[j]; - } - } - return hashCode; - } - - public override int Compare(object x, object y, EntityMode? entityMode) - { - byte[] xbytes = ToInternalFormat(x); - byte[] ybytes = ToInternalFormat(y); - if (xbytes.Length < ybytes.Length) - return -1; - if (xbytes.Length > ybytes.Length) - return 1; - for (int i = 0; i < xbytes.Length; i++) - { - if (xbytes[i] < ybytes[i]) - return -1; - if (xbytes[i] > ybytes[i]) - return 1; - } - return 0; - } - - public override string ToString(object val) - { - // convert to HEX string - byte[] bytes = ToInternalFormat(val); - StringBuilder buf = new StringBuilder(); - for (int i = 0; i < bytes.Length; i++) - { - String hexStr = Convert.ToString(bytes[i] - Byte.MinValue, 16); - if (hexStr.Length == 1) - buf.Append('0'); - buf.Append(hexStr); - } - return buf.ToString(); - } - - public override object DeepCopyNotNull(object value) - { - byte[] bytes = ToInternalFormat(value); - byte[] result = new byte[bytes.Length]; - Array.Copy(bytes, 0, result, 0, bytes.Length); - return ToExternalFormat(result); - } - - public override object FromStringValue(string xml) - { - if (xml == null) - return null; - if (xml.Length % 2 != 0) - throw new ArgumentException("The string is not a valid xml representation of a binary content."); - - byte[] bytes = new byte[xml.Length / 2]; - for (int i = 0; i < bytes.Length; i++) - { - string hexStr = xml.Substring(i * 2, ((i + 1) * 2) - (i * 2)); - bytes[i] = (byte)(Convert.ToInt32(hexStr, 16) + Byte.MinValue); - } - return ToExternalFormat(bytes); - } - } -} Modified: trunk/nhibernate/src/NHibernate/Type/BinaryType.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Type/BinaryType.cs 2008-11-12 02:40:14 UTC (rev 3907) +++ trunk/nhibernate/src/NHibernate/Type/BinaryType.cs 2008-11-13 18:08:08 UTC (rev 3908) @@ -7,7 +7,7 @@ /// BinaryType. /// </summary> [Serializable] - public class BinaryType : AbstractBynaryType + public class BinaryType : AbstractBinaryType { internal BinaryType() : this(new BinarySqlType()) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <te...@us...> - 2008-11-16 22:23:03
|
Revision: 3912 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3912&view=rev Author: tehlike Date: 2008-11-16 22:22:59 +0000 (Sun, 16 Nov 2008) Log Message: ----------- Implementation for SchemaValidator with its test (which means partial implementation of hbm2ddl.verify) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs trunk/nhibernate/src/NHibernate/Mapping/Table.cs trunk/nhibernate/src/NHibernate/NHibernate.csproj trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaValidator.cs trunk/nhibernate/src/NHibernate.Test/Tools/ trunk/nhibernate/src/NHibernate.Test/Tools/hbm2ddl/ trunk/nhibernate/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/ trunk/nhibernate/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/1_Version.hbm.xml trunk/nhibernate/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/2_Version.hbm.xml trunk/nhibernate/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/SchemaValidateFixture.cs trunk/nhibernate/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/Version.cs Modified: trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs 2008-11-15 19:44:59 UTC (rev 3911) +++ trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs 2008-11-16 22:22:59 UTC (rev 3912) @@ -1981,6 +1981,47 @@ return script.ToArray(); } + public void ValidateSchema(Dialect.Dialect dialect, DatabaseMetadata databaseMetadata) + { + SecondPassCompile(); + + string defaultCatalog = PropertiesHelper.GetString(Environment.DefaultCatalog, properties, null); + string defaultSchema = PropertiesHelper.GetString(Environment.DefaultSchema, properties, null); + + var iter = this.TableMappings; + foreach (var table in iter) + { + if (table.IsPhysicalTable) + { + /*NH Different Implementation : + TableMetadata tableInfo = databaseMetadata.getTableMetadata( + table.getName(), + ( table.getSchema() == null ) ? defaultSchema : table.getSchema(), + ( table.getCatalog() == null ) ? defaultCatalog : table.getCatalog(), + table.isQuoted());*/ + ITableMetadata tableInfo = databaseMetadata.GetTableMetadata( + table.Name, + table.Schema??defaultSchema, + table.Catalog,//??defaultCatalog, + table.IsQuoted); + if (tableInfo == null) + throw new HibernateException("Missing table: " + table.Name); + else + table.ValidateColumns(dialect, mapping, tableInfo); + } + } + + var persistenceIdentifierGenerators = IterateGenerators(dialect); + foreach (var generator in persistenceIdentifierGenerators) + { + string key = generator.GeneratorKey(); + if (!databaseMetadata.IsSequence(key) && !databaseMetadata.IsTable(key)) + { + throw new HibernateException(string.Format("Missing sequence or table: ", key)); + } + } + } + private IEnumerable<IPersistentIdentifierGenerator> IterateGenerators(Dialect.Dialect dialect) { var generators = new Dictionary<string, IPersistentIdentifierGenerator>(); Modified: trunk/nhibernate/src/NHibernate/Mapping/Table.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Mapping/Table.cs 2008-11-15 19:44:59 UTC (rev 3911) +++ trunk/nhibernate/src/NHibernate/Mapping/Table.cs 2008-11-16 22:22:59 UTC (rev 3912) @@ -1018,9 +1018,34 @@ return buf.ToString(); } - public void ValidateColumns(Dialect.Dialect dialect, IMapping mapping, DataTable tableInfo) + public void ValidateColumns(Dialect.Dialect dialect, IMapping mapping, ITableMetadata tableInfo) { - throw new NotSupportedException(); + var iter = this.ColumnIterator; + foreach (var column in iter) + { + + 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))); + + else + { + //TODO: Add new method to ColumnMetadata :getTypeCode + 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))); + } + } + } + } public static string Qualify(string catalog, string schema, string table) Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-15 19:44:59 UTC (rev 3911) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-16 22:22:59 UTC (rev 3912) @@ -1020,6 +1020,7 @@ <Compile Include="Tool\hbm2ddl\ManagedProviderConnectionHelper.cs" /> <Compile Include="Dialect\Schema\AbstractDataBaseSchema.cs" /> <Compile Include="Tool\hbm2ddl\SchemaUpdate.cs" /> + <Compile Include="Tool\hbm2ddl\SchemaValidator.cs" /> <Compile Include="Tool\hbm2ddl\SuppliedConnectionHelper.cs" /> <Compile Include="Tool\hbm2ddl\SuppliedConnectionProviderConnectionHelper.cs" /> <Compile Include="Transaction\AdoNetTransactionFactory.cs" /> Added: trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaValidator.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaValidator.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaValidator.cs 2008-11-16 22:22:59 UTC (rev 3912) @@ -0,0 +1,137 @@ +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; + +namespace NHibernate.Tool.hbm2ddl +{ + public class SchemaValidator + { + + private static readonly ILog log = LogManager.GetLogger(typeof(SchemaValidator)); + private readonly IConnectionHelper connectionHelper; + private readonly Configuration configuration; + private Dialect.Dialect dialect; + + public SchemaValidator(Configuration cfg) : + this(cfg, cfg.Properties) + { + } + + public SchemaValidator(Configuration cfg, IDictionary<string, string> connectionProperties) + { + this.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; + dialect = settings.Dialect; + connectionHelper = new SuppliedConnectionProviderConnectionHelper(settings.ConnectionProvider); + } + + public static void Main(string[] args) + { + try + { + Configuration cfg = new Configuration(); + + String propFile = null; + + for (int i = 0; i < args.Length; i++) + { + if (args[i].StartsWith("--")) + { + if (args[i].StartsWith("--properties=")) + { + 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)))); + } + } + else + { + cfg.AddFile(args[i]); + } + + } + /* NH: No props file for .NET + if ( propFile != null ) { + Properties props = new Properties(); + props.putAll( cfg.getProperties() ); + props.load( new FileInputStream( propFile ) ); + cfg.setProperties( props ); + } + */ + new SchemaValidator(cfg).Validate(); + } + catch (Exception e) + { + log.Error("Error running schema update", e); + Console.WriteLine(e); + } + } + + /** + * 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; + meta = new DatabaseMetadata(connection, dialect, false); + } + catch (Exception sqle) + { + log.Error("could not get database metadata", sqle); + throw sqle; + } + configuration.ValidateSchema(dialect, meta); + } + catch (Exception e) + { + log.Error("could not complete schema validation", e); + throw e; + } + finally + { + try + { + connectionHelper.Release(); + } + catch (Exception e) + { + log.Error("Error closing connection", e); + } + + } + } + } +} Property changes on: trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaValidator.cs ___________________________________________________________________ Added: svn:mergeinfo + Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-11-15 19:44:59 UTC (rev 3911) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-11-16 22:22:59 UTC (rev 3912) @@ -887,6 +887,8 @@ <Compile Include="TestCase.cs" /> <Compile Include="TestConfigurationHelper.cs" /> <Compile Include="TestTestCase.cs" /> + <Compile Include="Tools\hbm2ddl\SchemaValidator\SchemaValidateFixture.cs" /> + <Compile Include="Tools\hbm2ddl\SchemaValidator\Version.cs" /> <Compile Include="TransactionTest\TransactionFixture.cs" /> <Compile Include="TransactionTest\TransactionNotificationFixture.cs" /> <Compile Include="TypeParameters\DefaultValueIntegerType.cs" /> @@ -1535,6 +1537,8 @@ <EmbeddedResource Include="Cascade\JobBatch.hbm.xml" /> <EmbeddedResource Include="Deletetransient\Person.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> + <EmbeddedResource Include="Tools\hbm2ddl\SchemaValidator\2_Version.hbm.xml" /> + <EmbeddedResource Include="Tools\hbm2ddl\SchemaValidator\1_Version.hbm.xml" /> <EmbeddedResource Include="TypesTest\GenericEnumStringClass.hbm.xml" /> <EmbeddedResource Include="Operations\Competition.hbm.xml" /> <EmbeddedResource Include="Operations\Employer.hbm.xml" /> Added: trunk/nhibernate/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/1_Version.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/1_Version.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/1_Version.hbm.xml 2008-11-16 22:22:59 UTC (rev 3912) @@ -0,0 +1,18 @@ +<?xml version="1.0"?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" + namespace="NHibernate.Test.Tools.hbm2ddl.SchemaValidator" + assembly="NHibernate.Test"> + + <class name="Version"> + <id name="Id"> + <generator class="NHibernate.Id.TableHiLoGenerator"> + <param name="table">uid_table</param> + <param name="column">next_hi_value_column</param> + </generator> + </id> + <property name="Description"/> + <many-to-one name="Previous"/> + </class> + +</hibernate-mapping> + Added: trunk/nhibernate/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/2_Version.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/2_Version.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/2_Version.hbm.xml 2008-11-16 22:22:59 UTC (rev 3912) @@ -0,0 +1,18 @@ +<?xml version="1.0"?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" + namespace="NHibernate.Test.Tools.hbm2ddl.SchemaValidator" + assembly="NHibernate.Test"> + + <class name="Version"> + <id name="Id"> + <generator class="NHibernate.Id.TableHiLoGenerator"> + <param name="table">uid_table</param> + <param name="column">next_hi_value_column</param> + </generator> + </id> + <property name="Description"/> + <property name="Name"/> + </class> + +</hibernate-mapping> + Added: trunk/nhibernate/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/SchemaValidateFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/SchemaValidateFixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/SchemaValidateFixture.cs 2008-11-16 22:22:59 UTC (rev 3912) @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Text; +using NHibernate.Cfg; +using NHibernate.Tool.hbm2ddl; +using NUnit.Framework; + +namespace NHibernate.Test.Tools.hbm2ddl.SchemaValidator +{ + [TestFixture] + public class SchemaValidateFixture + { + [Test] + public void ShouldVerifySameTable() + { + string resource1 = "NHibernate.Test.Tools.hbm2ddl.SchemaValidator.1_Version.hbm.xml"; + Configuration v1cfg = TestConfigurationHelper.GetDefaultConfiguration(); + using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource1)) + new NHibernate.Tool.hbm2ddl.SchemaExport(v1cfg).Execute(true,true,false,true); + + var v1schemaValidator = new NHibernate.Tool.hbm2ddl.SchemaValidator((v1cfg)); + v1schemaValidator.Validate(); + + } + + [Test] + [ExpectedException(typeof(HibernateException), ExpectedMessage = "Missing column: Name in nhibernate.dbo.Version")] + public void ShouldNotVerifyModifiedTable() + { + string resource1 = "NHibernate.Test.Tools.hbm2ddl.SchemaValidator.1_Version.hbm.xml"; + string resource2 = "NHibernate.Test.Tools.hbm2ddl.SchemaValidator.2_Version.hbm.xml"; + Configuration v1cfg = TestConfigurationHelper.GetDefaultConfiguration(); + Configuration v2cfg = TestConfigurationHelper.GetDefaultConfiguration(); + using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource1)) + v1cfg.AddInputStream(stream); + using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource2)) + v2cfg.AddInputStream(stream); + new NHibernate.Tool.hbm2ddl.SchemaExport(v1cfg).Execute(true, true, false, true); + var v2schemaValidator = new NHibernate.Tool.hbm2ddl.SchemaValidator((v2cfg)); + v2schemaValidator.Validate(); + } + } +} Added: trunk/nhibernate/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/Version.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/Version.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/Tools/hbm2ddl/SchemaValidator/Version.cs 2008-11-16 22:22:59 UTC (rev 3912) @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace NHibernate.Test.Tools.hbm2ddl.SchemaValidator +{ + public class Version + { + private int id; + private string name; + private string description; + private Version previous; + + public virtual int Id + { + get { return id; } + set { id = value; } + } + + public virtual string Name + { + get { return name; } + set { name = value; } + } + + public virtual string Description + { + get { return description; } + set { description = value; } + } + + + public virtual Version Previous + { + get { return previous; } + set { previous = value; } + } + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-11-17 20:42:18
|
Revision: 3915 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3915&view=rev Author: fabiomaulo Date: 2008-11-17 20:42:16 +0000 (Mon, 17 Nov 2008) Log Message: ----------- fix NH-1573 Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Cfg/MappingSchema/Hbm.generated.cs trunk/nhibernate/src/NHibernate/Loader/Loader.cs trunk/nhibernate/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs trunk/nhibernate/src/NHibernate/nhibernate-mapping.xsd Modified: trunk/nhibernate/src/NHibernate/Cfg/MappingSchema/Hbm.generated.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/MappingSchema/Hbm.generated.cs 2008-11-17 13:59:23 UTC (rev 3914) +++ trunk/nhibernate/src/NHibernate/Cfg/MappingSchema/Hbm.generated.cs 2008-11-17 20:42:16 UTC (rev 3915) @@ -1353,11 +1353,11 @@ /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] - public bool collable; + public bool callable; /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool collableSpecified; + public bool callableSpecified; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] Modified: trunk/nhibernate/src/NHibernate/Loader/Loader.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Loader/Loader.cs 2008-11-17 13:59:23 UTC (rev 3914) +++ trunk/nhibernate/src/NHibernate/Loader/Loader.cs 2008-11-17 20:42:16 UTC (rev 3915) @@ -1111,7 +1111,7 @@ sqlString = PreprocessSQL(sqlString, queryParameters, dialect); - // TODO NH: Collable for SP -> PrepareCallableQueryCommand + // TODO NH: Callable for SP -> PrepareCallableQueryCommand IDbCommand command = session.Batcher.PrepareQueryCommand(CommandType.Text, sqlString, GetParameterTypes(queryParameters, useLimit, useOffset)); @@ -1347,7 +1347,7 @@ try { log.Info(st.CommandText); - // TODO NH: Collable + // TODO NH: Callable rs = session.Batcher.ExecuteReader(st); rs = WrapResultSetIfEnabled(rs, session); Modified: trunk/nhibernate/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs 2008-11-17 13:59:23 UTC (rev 3914) +++ trunk/nhibernate/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs 2008-11-17 20:42:16 UTC (rev 3915) @@ -1866,7 +1866,7 @@ public abstract bool IsOneToMany { get; } protected object PerformInsert(object ownerId, IPersistentCollection collection, IExpectation expectation, - object entry, int index, bool useBatch, bool collable, ISessionImplementor session) + object entry, int index, bool useBatch, bool callable, ISessionImplementor session) { object entryId = null; int offset = 0; Modified: trunk/nhibernate/src/NHibernate/nhibernate-mapping.xsd =================================================================== --- trunk/nhibernate/src/NHibernate/nhibernate-mapping.xsd 2008-11-17 13:59:23 UTC (rev 3914) +++ trunk/nhibernate/src/NHibernate/nhibernate-mapping.xsd 2008-11-17 20:42:16 UTC (rev 3915) @@ -1669,7 +1669,7 @@ </xs:restriction> </xs:simpleType> <xs:complexType name="customSQL" mixed="true"> - <xs:attribute name="collable" type="xs:boolean" /> + <xs:attribute name="callable" type="xs:boolean" /> <xs:attribute name="check" type="customSQLCheck" use="optional" /> </xs:complexType> <xs:simpleType name="versionGeneration"> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-11-17 21:38:37
|
Revision: 3916 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3916&view=rev Author: fabiomaulo Date: 2008-11-17 21:34:20 +0000 (Mon, 17 Nov 2008) Log Message: ----------- fix NH-1570 Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Dialect/MsSql2005Dialect.cs trunk/nhibernate/src/NHibernate.Test/DialectTest/MsSql2005DialectFixture.cs Modified: trunk/nhibernate/src/NHibernate/Dialect/MsSql2005Dialect.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/MsSql2005Dialect.cs 2008-11-17 20:42:16 UTC (rev 3915) +++ trunk/nhibernate/src/NHibernate/Dialect/MsSql2005Dialect.cs 2008-11-17 21:34:20 UTC (rev 3916) @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Data; using System.Text; -using System.Text.RegularExpressions; using NHibernate.Mapping; using NHibernate.SqlCommand; using NHibernate.Util; @@ -44,24 +43,24 @@ /// </remarks> public override SqlString GetLimitString(SqlString querySqlString, int offset, int last) { - // we have to do this in order to support parameters in order clause, the foramt - // that sql 2005 uses for paging means that we move the parameters around, which means, - // that positions are lost, so we record them before making any changes. - // NH-1528 - int parameterPositon = 0; - foreach (var part in querySqlString.Parts) - { - Parameter param = part as Parameter; - if (param == null) - continue; - param.OriginalPositionInQuery = parameterPositon; - parameterPositon += 1; - } + // we have to do this in order to support parameters in order clause, the foramt + // that sql 2005 uses for paging means that we move the parameters around, which means, + // that positions are lost, so we record them before making any changes. + // NH-1528 + int parameterPositon = 0; + foreach (var part in querySqlString.Parts) + { + Parameter param = part as Parameter; + if (param == null) + continue; + param.OriginalPositionInQuery = parameterPositon; + parameterPositon += 1; + } int fromIndex = GetFromIndex(querySqlString); SqlString select = querySqlString.Substring(0, fromIndex); - List<SqlString> columnsOrAliases; - Dictionary<SqlString, SqlString> aliasToColumn; + List<SqlString> columnsOrAliases; + Dictionary<SqlString, SqlString> aliasToColumn; ExtractColumnOrAliasNames(select, out columnsOrAliases, out aliasToColumn); int orderIndex = querySqlString.LastIndexOfCaseInsensitive(" order by "); @@ -71,13 +70,13 @@ { from = querySqlString.Substring(fromIndex, orderIndex - fromIndex).Trim(); SqlString orderBy = querySqlString.Substring(orderIndex).Trim(); - sortExpressions = orderBy.Substring(9).Split(","); + sortExpressions = orderBy.Substring(9).Split(","); } else { from = querySqlString.Substring(fromIndex).Trim(); // Use dummy sort to avoid errors - sortExpressions = new SqlString[] { new SqlString("CURRENT_TIMESTAMP"), }; + sortExpressions = new[] { new SqlString("CURRENT_TIMESTAMP"), }; } SqlStringBuilder result = @@ -99,7 +98,7 @@ } for (int i = 0; i < sortExpressions.Length; i++) { - SqlString sortExpression = RemoveSortOrderDirection(sortExpressions[i]); + SqlString sortExpression = RemoveSortOrderDirection(sortExpressions[i]); if (!columnsOrAliases.Contains(sortExpression)) { result.Add(", query.__hibernate_sort_expr_").Add(i.ToString()).Add("__"); @@ -132,13 +131,14 @@ return result.ToSqlString(); } - private static SqlString RemoveSortOrderDirection(SqlString sortExpression) + private static SqlString RemoveSortOrderDirection(SqlString sortExpression) { - if (sortExpression.EndsWithCaseInsensitive("asc")) - return sortExpression.Substring(0, sortExpression.Length - 3).Trim(); - if (sortExpression.EndsWithCaseInsensitive("desc")) - return sortExpression.Substring(0, sortExpression.Length - 4).Trim(); - return sortExpression.Trim(); + SqlString trimmedExpression = sortExpression.Trim(); + if (trimmedExpression.EndsWithCaseInsensitive("asc")) + return trimmedExpression.Substring(0, trimmedExpression.Length - 3).Trim(); + if (trimmedExpression.EndsWithCaseInsensitive("desc")) + return trimmedExpression.Substring(0, trimmedExpression.Length - 4).Trim(); + return trimmedExpression.Trim(); } private static void AppendSortExpressions(ICollection<SqlString> columnsOrAliases, SqlString[] sortExpressions, @@ -167,7 +167,7 @@ } } - private int GetFromIndex(SqlString querySqlString) + private static int GetFromIndex(SqlString querySqlString) { string subselect = querySqlString.GetSubselectString().ToString(); int fromIndex = querySqlString.IndexOfCaseInsensitive(subselect); @@ -178,11 +178,11 @@ return fromIndex; } - private static void ExtractColumnOrAliasNames(SqlString select, out List<SqlString> columnsOrAliases, - out Dictionary<SqlString, SqlString> aliasToColumn) + private static void ExtractColumnOrAliasNames(SqlString select, out List<SqlString> columnsOrAliases, + out Dictionary<SqlString, SqlString> aliasToColumn) { - columnsOrAliases = new List<SqlString>(); - aliasToColumn = new Dictionary<SqlString, SqlString>(); + columnsOrAliases = new List<SqlString>(); + aliasToColumn = new Dictionary<SqlString, SqlString>(); IList<string> tokens = new QuotedAndParenthesisStringTokenizer(select.ToString()).GetTokens(); int index = 0; @@ -240,7 +240,7 @@ } columnsOrAliases.Add(new SqlString(alias)); - aliasToColumn[new SqlString(alias)] = new SqlString(token); + aliasToColumn[new SqlString(alias)] = new SqlString(token); } } @@ -442,4 +442,4 @@ } } } -} \ No newline at end of file +} Modified: trunk/nhibernate/src/NHibernate.Test/DialectTest/MsSql2005DialectFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/DialectTest/MsSql2005DialectFixture.cs 2008-11-17 20:42:16 UTC (rev 3915) +++ trunk/nhibernate/src/NHibernate.Test/DialectTest/MsSql2005DialectFixture.cs 2008-11-17 21:34:20 UTC (rev 3916) @@ -15,8 +15,13 @@ { MsSql2005Dialect d = new MsSql2005Dialect(); - SqlString str = d.GetLimitString(new SqlString("SELECT fish.id FROM fish"), 0, 10); + SqlString str = d.GetLimitString(new SqlString("select distinct c.Contact_Id as Contact1_19_0_, c._Rating as Rating2_19_0_ from dbo.Contact c where COALESCE(c.Rating, 0) > 0 order by c.Rating desc , c.Last_Name , c.First_Name"), 0, 10); Assert.AreEqual( + "SELECT TOP 10 Contact1_19_0_, Rating2_19_0_ FROM (SELECT ROW_NUMBER() OVER(ORDER BY __hibernate_sort_expr_0__ DESC, __hibernate_sort_expr_1__, __hibernate_sort_expr_2__) as row, query.Contact1_19_0_, query.Rating2_19_0_, query.__hibernate_sort_expr_0__, query.__hibernate_sort_expr_1__, query.__hibernate_sort_expr_2__ FROM (select distinct c.Contact_Id as Contact1_19_0_, c._Rating as Rating2_19_0_, c.Rating as __hibernate_sort_expr_0__, c.Last_Name as __hibernate_sort_expr_1__, c.First_Name as __hibernate_sort_expr_2__ from dbo.Contact c where COALESCE(c.Rating, 0) > 0) query ) page WHERE page.row > 0 ORDER BY __hibernate_sort_expr_0__ DESC, __hibernate_sort_expr_1__, __hibernate_sort_expr_2__", + str.ToString()); + + str = d.GetLimitString(new SqlString("SELECT fish.id FROM fish"), 0, 10); + Assert.AreEqual( "SELECT TOP 10 id FROM (SELECT ROW_NUMBER() OVER(ORDER BY __hibernate_sort_expr_0__) as row, query.id, query.__hibernate_sort_expr_0__ FROM (SELECT fish.id, CURRENT_TIMESTAMP as __hibernate_sort_expr_0__ FROM fish) query ) page WHERE page.row > 0 ORDER BY __hibernate_sort_expr_0__", str.ToString()); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <dav...@us...> - 2008-11-24 19:31:59
|
Revision: 3922 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3922&view=rev Author: davybrion Date: 2008-11-24 19:31:52 +0000 (Mon, 24 Nov 2008) Log Message: ----------- minor cleanup, mostly replacing hashtables with dictionaries where it was safe to do so Modified Paths: -------------- trunk/nhibernate/src/NHibernate/AdoNet/OracleDataClientBatchingBatcher.cs trunk/nhibernate/src/NHibernate/Criterion/Projections.cs trunk/nhibernate/src/NHibernate/Dialect/Function/NoArgSQLFunction.cs trunk/nhibernate/src/NHibernate/Id/Enhanced/SequenceStructure.cs trunk/nhibernate/src/NHibernate/Impl/Printer.cs trunk/nhibernate/src/NHibernate/Impl/SessionFactoryObjectFactory.cs trunk/nhibernate/src/NHibernate/Loader/Custom/Sql/SQLQueryReturnProcessor.cs trunk/nhibernate/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs trunk/nhibernate/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs trunk/nhibernate/src/NHibernate/SqlCommand/SelectFragment.cs trunk/nhibernate/src/NHibernate/Type/ComponentType.cs trunk/nhibernate/src/NHibernate.Test/ConnectionTest/ThreadLocalCurrentSessionTest.cs trunk/nhibernate/src/NHibernate.Test/Naturalid/Immutable/ImmutableNaturalIdFixture.cs Modified: trunk/nhibernate/src/NHibernate/AdoNet/OracleDataClientBatchingBatcher.cs =================================================================== --- trunk/nhibernate/src/NHibernate/AdoNet/OracleDataClientBatchingBatcher.cs 2008-11-24 12:59:36 UTC (rev 3921) +++ trunk/nhibernate/src/NHibernate/AdoNet/OracleDataClientBatchingBatcher.cs 2008-11-24 19:31:52 UTC (rev 3922) @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Collections.Generic; using System.Data; using System.Reflection; @@ -15,8 +16,8 @@ private int countOfCommands = 0; private int totalExpectedRowsAffected; private IDbCommand currentBatch; - private Hashtable parameterValueArrayHashTable; - private Hashtable parameterIsAllNullsHashTable; + private IDictionary<string, ArrayList> parameterValueArrayHashTable; + private IDictionary<string, bool> parameterIsAllNullsHashTable; public OracleDataClientBatchingBatcher(ConnectionManager connectionManager, IInterceptor interceptor) @@ -36,10 +37,10 @@ { // use first command as the batching command currentBatch = CurrentCommand; - parameterValueArrayHashTable = new Hashtable(); + parameterValueArrayHashTable = new Dictionary<string, ArrayList>(); //oracle does not allow array containing all null values - // so this HashTable is keeping track if all values are null or not - parameterIsAllNullsHashTable = new Hashtable(); + // so this Dictionary is keeping track if all values are null or not + parameterIsAllNullsHashTable = new Dictionary<string, bool>(); } else { @@ -57,7 +58,7 @@ } else { - parameterValueArray = parameterValueArrayHashTable[currentParameter.ParameterName] as ArrayList; + parameterValueArray = parameterValueArrayHashTable[currentParameter.ParameterName]; } if (currentParameter.Value != DBNull.Value) @@ -73,8 +74,6 @@ { DoExecuteBatch(currentBatch); } - - } protected override void DoExecuteBatch(IDbCommand ps) @@ -90,7 +89,7 @@ foreach (IDataParameter currentParameter in currentBatch.Parameters) { - ArrayList parameterValueArray = parameterValueArrayHashTable[currentParameter.ParameterName] as ArrayList; + ArrayList parameterValueArray = parameterValueArrayHashTable[currentParameter.ParameterName]; currentParameter.Value = parameterValueArray.ToArray(); arraySize = parameterValueArray.Count; } Modified: trunk/nhibernate/src/NHibernate/Criterion/Projections.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Criterion/Projections.cs 2008-11-24 12:59:36 UTC (rev 3921) +++ trunk/nhibernate/src/NHibernate/Criterion/Projections.cs 2008-11-24 19:31:52 UTC (rev 3922) @@ -257,8 +257,9 @@ /// Return a constant value /// </summary> /// <param name="obj">The obj.</param> + /// <param name="type"></param> /// <returns></returns> - public static IProjection Constant(object obj,IType type) + public static IProjection Constant(object obj, IType type) { return new ConstantProjection(obj,type); } Modified: trunk/nhibernate/src/NHibernate/Dialect/Function/NoArgSQLFunction.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/Function/NoArgSQLFunction.cs 2008-11-24 12:59:36 UTC (rev 3921) +++ trunk/nhibernate/src/NHibernate/Dialect/Function/NoArgSQLFunction.cs 2008-11-24 19:31:52 UTC (rev 3922) @@ -58,13 +58,13 @@ { throw new QueryException("function takes no arguments: " + name); } - SqlStringBuilder buf = new SqlStringBuilder(2); - buf.Add(name); + if (hasParenthesesIfNoArguments) { - buf.Add("()"); + return new SqlString(name + "()"); } - return buf.ToSqlString(); + + return new SqlString(name); } #endregion Modified: trunk/nhibernate/src/NHibernate/Id/Enhanced/SequenceStructure.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Id/Enhanced/SequenceStructure.cs 2008-11-24 12:59:36 UTC (rev 3921) +++ trunk/nhibernate/src/NHibernate/Id/Enhanced/SequenceStructure.cs 2008-11-24 19:31:52 UTC (rev 3922) @@ -113,7 +113,7 @@ { rs.Close(); } - catch (Exception ignore) + catch { // intentionally empty } Modified: trunk/nhibernate/src/NHibernate/Impl/Printer.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Impl/Printer.cs 2008-11-24 12:59:36 UTC (rev 3921) +++ trunk/nhibernate/src/NHibernate/Impl/Printer.cs 2008-11-24 19:31:52 UTC (rev 3922) @@ -27,7 +27,7 @@ return entity.GetType().FullName; } - IDictionary result = new Hashtable(); + IDictionary<string, string> result = new Dictionary<string, string>(); if (cm.HasIdentifierProperty) { @@ -49,7 +49,8 @@ public string ToString(IType[] types, object[] values) { - IList list = new ArrayList(types.Length); + List<string> list = new List<string>(types.Length); + for (int i = 0; i < types.Length; i++) { if (types[i] != null) @@ -62,7 +63,7 @@ public string ToString(IDictionary<string, TypedValue> namedTypedValues) { - IDictionary result = new Hashtable(namedTypedValues.Count); + IDictionary<string, string> result = new Dictionary<string, string>(namedTypedValues.Count); foreach (KeyValuePair<string, TypedValue> me in namedTypedValues) { Modified: trunk/nhibernate/src/NHibernate/Impl/SessionFactoryObjectFactory.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Impl/SessionFactoryObjectFactory.cs 2008-11-24 12:59:36 UTC (rev 3921) +++ trunk/nhibernate/src/NHibernate/Impl/SessionFactoryObjectFactory.cs 2008-11-24 19:31:52 UTC (rev 3922) @@ -28,8 +28,8 @@ private static readonly ILog log; // in h2.0.3 these use a class called "FastHashMap" - private static readonly Hashtable Instances = new Hashtable(); - private static readonly Hashtable NamedInstances = new Hashtable(); + private static readonly IDictionary<string, ISessionFactory> Instances = new Dictionary<string, ISessionFactory>(); + private static readonly IDictionary<string, ISessionFactory> NamedInstances = new Dictionary<string, ISessionFactory>(); /// <summary></summary> static SessionFactoryObjectFactory() @@ -54,13 +54,13 @@ { if (log.IsDebugEnabled) { - string nameMsg = ((name != null && name.Length > 0) ? name : "unnamed"); + string nameMsg = ((!string.IsNullOrEmpty(name)) ? name : "unnamed"); log.Debug("registered: " + uid + "(" + nameMsg + ")"); } Instances[uid] = instance; - if (name != null && name.Length > 0) + if (!string.IsNullOrEmpty(name)) { log.Info("Factory name:" + name); NamedInstances[name] = instance; @@ -79,7 +79,7 @@ /// <param name="properties">The configured properties for the ISessionFactory.</param> public static void RemoveInstance(string uid, string name, IDictionary<string, string> properties) { - if (name != null && name.Length > 0) + if (!string.IsNullOrEmpty(name)) { log.Info("unbinding factory: " + name); @@ -97,7 +97,7 @@ public static ISessionFactory GetNamedInstance(string name) { log.Debug("lookup: name=" + name); - ISessionFactory factory = NamedInstances[name] as ISessionFactory; + ISessionFactory factory = NamedInstances[name]; if (factory == null) { log.Warn("Not found: " + name); @@ -113,7 +113,7 @@ public static ISessionFactory GetInstance(string uid) { log.Debug("lookup: uid=" + uid); - ISessionFactory factory = Instances[uid] as ISessionFactory; + ISessionFactory factory = Instances[uid]; if (factory == null) { log.Warn("Not found: " + uid); Modified: trunk/nhibernate/src/NHibernate/Loader/Custom/Sql/SQLQueryReturnProcessor.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Loader/Custom/Sql/SQLQueryReturnProcessor.cs 2008-11-24 12:59:36 UTC (rev 3921) +++ trunk/nhibernate/src/NHibernate/Loader/Custom/Sql/SQLQueryReturnProcessor.cs 2008-11-24 19:31:52 UTC (rev 3922) @@ -293,7 +293,7 @@ public IList GenerateCustomReturns(bool queryHadAliases) { IList customReturns = new ArrayList(); - IDictionary customReturnsByAlias = new Hashtable(); + IDictionary<string, object> customReturnsByAlias = new Dictionary<string, object>(); for (int i = 0; i < queryReturns.Length; i++) { if (queryReturns[i] is NativeSQLQueryScalarReturn) Modified: trunk/nhibernate/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs 2008-11-24 12:59:36 UTC (rev 3921) +++ trunk/nhibernate/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs 2008-11-24 19:31:52 UTC (rev 3922) @@ -160,8 +160,8 @@ private readonly string[] spaces; - private readonly IDictionary collectionPropertyColumnAliases = new Hashtable(); - private readonly IDictionary collectionPropertyColumnNames = new Hashtable(); + private readonly IDictionary<string, object> collectionPropertyColumnAliases = new Dictionary<string, object>(); + private readonly IDictionary<string, object> collectionPropertyColumnNames = new Dictionary<string, object>(); private static readonly ILog log = LogManager.GetLogger(typeof (ICollectionPersister)); Modified: trunk/nhibernate/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs 2008-11-24 12:59:36 UTC (rev 3921) +++ trunk/nhibernate/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs 2008-11-24 19:31:52 UTC (rev 3922) @@ -204,7 +204,7 @@ #endregion - private readonly Hashtable uniqueKeyLoaders = new Hashtable(); + private readonly Dictionary<string, EntityLoader> uniqueKeyLoaders = new Dictionary<string, EntityLoader>(); private readonly Dictionary<LockMode, ILockingStrategy> lockers = new Dictionary<LockMode, ILockingStrategy>(); private readonly Dictionary<string, IUniqueEntityLoader> loaders = new Dictionary<string, IUniqueEntityLoader>(); @@ -1996,12 +1996,10 @@ if (useStaticLoader) { - return (EntityLoader)uniqueKeyLoaders[propertyName]; + return uniqueKeyLoaders[propertyName]; } - else - { - return CreateUniqueKeyLoader(propertyMapping.ToType(propertyName), propertyMapping.ToColumns(propertyName), enabledFilters); - } + + return CreateUniqueKeyLoader(propertyMapping.ToType(propertyName), propertyMapping.ToColumns(propertyName), enabledFilters); } public int GetPropertyIndex(string propertyName) Modified: trunk/nhibernate/src/NHibernate/SqlCommand/SelectFragment.cs =================================================================== --- trunk/nhibernate/src/NHibernate/SqlCommand/SelectFragment.cs 2008-11-24 12:59:36 UTC (rev 3921) +++ trunk/nhibernate/src/NHibernate/SqlCommand/SelectFragment.cs 2008-11-24 19:31:52 UTC (rev 3922) @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Collections.Generic; using System.Text; using Iesi.Collections; using NHibernate.Util; @@ -12,8 +13,8 @@ public class SelectFragment { private string suffix; - private IList columns = new ArrayList(); - private IList columnAliases = new ArrayList(); + private IList<string> columns = new List<string>(); + private IList<string> columnAliases = new List<string>(); private Dialect.Dialect dialect; private string[] usedAliases; private string extraSelectList; @@ -57,7 +58,7 @@ public SelectFragment AddColumn(string tableAlias, string columnName, string columnAlias) { - if (tableAlias == null || tableAlias.Length == 0) + if (string.IsNullOrEmpty(tableAlias)) { columns.Add(columnName); } @@ -140,8 +141,8 @@ bool found = false; for (int i = 0; i < columns.Count; i++) { - string col = columns[i] as string; - string columnAlias = columnAliases[i] as string; + string col = columns[i]; + string columnAlias = columnAliases[i]; if (columnsUnique.Add(columnAlias)) { Modified: trunk/nhibernate/src/NHibernate/Type/ComponentType.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Type/ComponentType.cs 2008-11-24 12:59:36 UTC (rev 3921) +++ trunk/nhibernate/src/NHibernate/Type/ComponentType.cs 2008-11-24 19:31:52 UTC (rev 3922) @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Collections.Generic; using System.Data; using System.Reflection; using System.Xml; @@ -311,7 +312,7 @@ { return "null"; } - IDictionary result = new Hashtable(); + IDictionary<string, string> result = new Dictionary<string, string>(); EntityMode? entityMode = tuplizerMapping.GuessEntityMode(value); if (!entityMode.HasValue) { Modified: trunk/nhibernate/src/NHibernate.Test/ConnectionTest/ThreadLocalCurrentSessionTest.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/ConnectionTest/ThreadLocalCurrentSessionTest.cs 2008-11-24 12:59:36 UTC (rev 3921) +++ trunk/nhibernate/src/NHibernate.Test/ConnectionTest/ThreadLocalCurrentSessionTest.cs 2008-11-24 19:31:52 UTC (rev 3922) @@ -59,7 +59,7 @@ session.CreateQuery("from Silly"); Assert.Fail("method other than beginTransaction{} allowed"); } - catch (HibernateException e) + catch (HibernateException) { // ok } Modified: trunk/nhibernate/src/NHibernate.Test/Naturalid/Immutable/ImmutableNaturalIdFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Naturalid/Immutable/ImmutableNaturalIdFixture.cs 2008-11-24 12:59:36 UTC (rev 3921) +++ trunk/nhibernate/src/NHibernate.Test/Naturalid/Immutable/ImmutableNaturalIdFixture.cs 2008-11-24 19:31:52 UTC (rev 3922) @@ -73,7 +73,7 @@ s.Flush(); Assert.Fail(); } - catch (HibernateException he) {} + catch (HibernateException) {} u.UserName = "steve"; s.Delete(u); t.Commit(); @@ -82,63 +82,63 @@ [Test] public void NaturalIdCache() - { - ISession s = OpenSession(); - s.BeginTransaction(); - User u = new User("steve", "superSecret"); - s.Persist(u); - s.Transaction.Commit(); - s.Close(); - - sessions.Statistics.Clear(); - - s = OpenSession(); - s.BeginTransaction(); + { + ISession s = OpenSession(); + s.BeginTransaction(); + User u = new User("steve", "superSecret"); + s.Persist(u); + s.Transaction.Commit(); + s.Close(); + + sessions.Statistics.Clear(); + + s = OpenSession(); + s.BeginTransaction(); u = (User) s.CreateCriteria(typeof (User)).Add(Restrictions.NaturalId().Set("UserName", "steve")).SetCacheable(true). UniqueResult(); - Assert.That(u, Is.Not.Null); - s.Transaction.Commit(); + Assert.That(u, Is.Not.Null); + s.Transaction.Commit(); s.Close(); Assert.AreEqual(1, sessions.Statistics.QueryExecutionCount); Assert.AreEqual(0, sessions.Statistics.QueryCacheHitCount); - Assert.AreEqual(1, sessions.Statistics.QueryCachePutCount); - - s = OpenSession(); - s.BeginTransaction(); - User v = new User("gavin", "supsup"); - s.Persist(v); - s.Transaction.Commit(); - s.Close(); - - sessions.Statistics.Clear(); - - s = OpenSession(); - s.BeginTransaction(); + Assert.AreEqual(1, sessions.Statistics.QueryCachePutCount); + + s = OpenSession(); + s.BeginTransaction(); + User v = new User("gavin", "supsup"); + s.Persist(v); + s.Transaction.Commit(); + s.Close(); + + sessions.Statistics.Clear(); + + s = OpenSession(); + s.BeginTransaction(); u = (User) s.CreateCriteria(typeof(User)).Add(Restrictions.NaturalId().Set("UserName", "steve")).SetCacheable(true). UniqueResult(); Assert.That(u, Is.Not.Null); Assert.AreEqual(0, sessions.Statistics.QueryExecutionCount); - Assert.AreEqual(1, sessions.Statistics.QueryCacheHitCount); + Assert.AreEqual(1, sessions.Statistics.QueryCacheHitCount); u = (User) s.CreateCriteria(typeof(User)).Add(Restrictions.NaturalId().Set("UserName", "steve")).SetCacheable(true). UniqueResult(); Assert.That(u, Is.Not.Null); Assert.AreEqual(0, sessions.Statistics.QueryExecutionCount); - Assert.AreEqual(2, sessions.Statistics.QueryCacheHitCount); - s.Transaction.Commit(); - s.Close(); - - s = OpenSession(); - s.BeginTransaction(); - s.Delete("from User"); - s.Transaction.Commit(); - s.Close(); + Assert.AreEqual(2, sessions.Statistics.QueryCacheHitCount); + s.Transaction.Commit(); + s.Close(); + + s = OpenSession(); + s.BeginTransaction(); + s.Delete("from User"); + s.Transaction.Commit(); + s.Close(); } } } \ 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-13 22:00:37
|
Davy, one more thing I noticed while i was in jira. Hashtable returns null when a key is not found, but a dictionary throws KeyNotFoundException. [Fact] public void Dictionary_throws_exception_when_key_not_found() { IDictionary<string, string> dictionary = new Dictionary<string, string>(); Assert.Throws<KeyNotFoundException>(delegate { var v = dictionary["dummykey"]; }); } [Fact] public void Hashtable_returns_null_when_key_not_found() { Hashtable hashTable=new Hashtable(); Assert.Null(hashTable["dummykey"]); } On Mon, Nov 24, 2008 at 9:31 PM, <dav...@us...> wrote: > + private IDictionary<string, ArrayList> > parameterValueArrayHashTable; > + private IDictionary<string, bool> > parameterIsAllNullsHashTable; > -- Tuna Toksöz http://tunatoksoz.com Typos included to enhance the readers attention! |
From: <fab...@us...> - 2008-11-25 22:00:04
|
Revision: 3928 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3928&view=rev Author: fabiomaulo Date: 2008-11-25 21:50:57 +0000 (Tue, 25 Nov 2008) Log Message: ----------- Fix NH-1586 (Informix drive by Robert Sosnowski) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/NHibernate.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate/Driver/IfxDriver.cs Added: trunk/nhibernate/src/NHibernate/Driver/IfxDriver.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Driver/IfxDriver.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Driver/IfxDriver.cs 2008-11-25 21:50:57 UTC (rev 3928) @@ -0,0 +1,37 @@ +namespace NHibernate.Driver +{ + /// <summary> + /// A NHibernate Driver for using the Informix DataProvider + /// </summary> + public class IfxDriver : ReflectionBasedDriver + { + /// <summary> + /// Initializes a new instance of the <see cref="IfxDriver"/> class. + /// </summary> + /// <exception cref="HibernateException"> + /// Thrown when the <c>IBM.Data.Informix</c> assembly can not be loaded. + /// </exception> + public IfxDriver() + : base( + "IBM.Data.Informix", + "IBM.Data.Informix.IfxConnection", + "IBM.Data.Informix.IfxCommand") + { + } + + public override bool UseNamedPrefixInSql + { + get { return false; } + } + + public override bool UseNamedPrefixInParameter + { + get { return false; } + } + + public override string NamedPrefix + { + get { return ":"; } + } + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-25 21:46:24 UTC (rev 3927) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-25 21:50:57 UTC (rev 3928) @@ -447,6 +447,7 @@ <Compile Include="Dialect\Schema\SybaseAnywhereMetaData.cs" /> <Compile Include="Dialect\SybaseASA10Dialect.cs" /> <Compile Include="Dialect\SybaseASA9Dialect.cs" /> + <Compile Include="Driver\IfxDriver.cs" /> <Compile Include="Id\SelectGenerator.cs" /> <Compile Include="Properties\BackFieldStrategy.cs" /> <Compile Include="Bytecode\CodeDom\BytecodeProviderImpl.cs" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-11-25 22:00:05
|
Revision: 3927 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3927&view=rev Author: fabiomaulo Date: 2008-11-25 21:46:24 +0000 (Tue, 25 Nov 2008) Log Message: ----------- Fix NH-1587 Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Tuple/Entity/AbstractEntityTuplizer.cs trunk/nhibernate/src/NHibernate/Tuple/Entity/DynamicMapEntityTuplizer.cs trunk/nhibernate/src/NHibernate/Tuple/Entity/PocoEntityTuplizer.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1587/Fixture.cs Modified: trunk/nhibernate/src/NHibernate/Tuple/Entity/AbstractEntityTuplizer.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Tuple/Entity/AbstractEntityTuplizer.cs 2008-11-25 21:31:27 UTC (rev 3926) +++ trunk/nhibernate/src/NHibernate/Tuple/Entity/AbstractEntityTuplizer.cs 2008-11-25 21:46:24 UTC (rev 3927) @@ -23,7 +23,7 @@ protected internal IGetter[] getters; protected internal ISetter[] setters; protected internal bool hasCustomAccessors; - private readonly IInstantiator instantiator; + protected IInstantiator instantiator; private readonly IProxyFactory proxyFactory; private readonly IAbstractComponentType identifierMapperType; @@ -67,7 +67,8 @@ } hasCustomAccessors = foundCustomAccessor; - instantiator = BuildInstantiator(mappingInfo); + //NH-1587 + //instantiator = BuildInstantiator(mappingInfo); if (entityMetamodel.IsLazy) { Modified: trunk/nhibernate/src/NHibernate/Tuple/Entity/DynamicMapEntityTuplizer.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Tuple/Entity/DynamicMapEntityTuplizer.cs 2008-11-25 21:31:27 UTC (rev 3926) +++ trunk/nhibernate/src/NHibernate/Tuple/Entity/DynamicMapEntityTuplizer.cs 2008-11-25 21:46:24 UTC (rev 3927) @@ -14,7 +14,11 @@ private static readonly ILog log = LogManager.GetLogger(typeof(PocoEntityTuplizer)); internal DynamicMapEntityTuplizer(EntityMetamodel entityMetamodel, PersistentClass mappingInfo) - : base(entityMetamodel, mappingInfo) {} + : base(entityMetamodel, mappingInfo) + { + // NH different behavior fo NH-1587 + instantiator = BuildInstantiator(mappingInfo); + } public override System.Type ConcreteProxyClass { Modified: trunk/nhibernate/src/NHibernate/Tuple/Entity/PocoEntityTuplizer.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Tuple/Entity/PocoEntityTuplizer.cs 2008-11-25 21:31:27 UTC (rev 3926) +++ trunk/nhibernate/src/NHibernate/Tuple/Entity/PocoEntityTuplizer.cs 2008-11-25 21:46:24 UTC (rev 3927) @@ -40,13 +40,16 @@ lazyPropertyNames.Add(property.Name); } - if (hasCustomAccessors || !Cfg.Environment.UseReflectionOptimizer) + if (Cfg.Environment.UseReflectionOptimizer) { - optimizer = null; + // NH different behavior fo NH-1587 + optimizer = Cfg.Environment.BytecodeProvider.GetReflectionOptimizer(mappedClass, getters, setters); } - else + instantiator = BuildInstantiator(mappedEntity); + + if (hasCustomAccessors) { - optimizer = Cfg.Environment.BytecodeProvider.GetReflectionOptimizer(mappedClass, getters, setters); + optimizer = null; } proxyValidator = Cfg.Environment.BytecodeProvider.ProxyFactoryFactory.ProxyValidator; @@ -81,10 +84,12 @@ { if (optimizer == null) { + log.Debug("Create Instantiator without optimizer for:" + persistentClass.MappedClass.FullName); return new PocoInstantiator(persistentClass, null); } else { + log.Debug("Create Instantiator using optimizer for:" + persistentClass.MappedClass.FullName); return new PocoInstantiator(persistentClass, optimizer.InstantiationOptimizer); } } Modified: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1587/Fixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1587/Fixture.cs 2008-11-25 21:31:27 UTC (rev 3926) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1587/Fixture.cs 2008-11-25 21:46:24 UTC (rev 3927) @@ -8,7 +8,7 @@ [TestFixture] public class Fixture { - [Test, Ignore("Not fixed yet")] + [Test] public void Bug() { XmlConfigurator.Configure(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <dav...@us...> - 2008-11-26 22:38:54
|
Revision: 3934 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3934&view=rev Author: davybrion Date: 2008-11-26 22:38:49 +0000 (Wed, 26 Nov 2008) Log Message: ----------- various minor cleanups Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Action/CollectionRecreateAction.cs trunk/nhibernate/src/NHibernate/Action/CollectionRemoveAction.cs trunk/nhibernate/src/NHibernate/Action/CollectionUpdateAction.cs trunk/nhibernate/src/NHibernate/Action/EntityDeleteAction.cs trunk/nhibernate/src/NHibernate/Action/EntityIdentityInsertAction.cs trunk/nhibernate/src/NHibernate/Action/EntityInsertAction.cs trunk/nhibernate/src/NHibernate/Action/EntityUpdateAction.cs trunk/nhibernate/src/NHibernate/AdoNet/OracleDataClientBatchingBatcher.cs trunk/nhibernate/src/NHibernate/Cache/StandardQueryCache.cs trunk/nhibernate/src/NHibernate/Collection/AbstractPersistentCollection.cs trunk/nhibernate/src/NHibernate/Collection/Generic/PersistentGenericMap.cs trunk/nhibernate/src/NHibernate/Collection/PersistentArrayHolder.cs trunk/nhibernate/src/NHibernate/Collection/PersistentBag.cs trunk/nhibernate/src/NHibernate/Collection/PersistentIdentifierBag.cs trunk/nhibernate/src/NHibernate/Collection/PersistentList.cs trunk/nhibernate/src/NHibernate/Collection/PersistentMap.cs trunk/nhibernate/src/NHibernate/Collection/PersistentSet.cs trunk/nhibernate/src/NHibernate/Criterion/InExpression.cs trunk/nhibernate/src/NHibernate/Criterion/Junction.cs trunk/nhibernate/src/NHibernate/Dialect/Function/AnsiTrimEmulationFunction.cs trunk/nhibernate/src/NHibernate/Driver/NDataReader.cs trunk/nhibernate/src/NHibernate/Engine/JoinSequence.cs trunk/nhibernate/src/NHibernate/Engine/Query/HQLQueryPlan.cs trunk/nhibernate/src/NHibernate/Engine/Query/NativeSQLQueryPlan.cs trunk/nhibernate/src/NHibernate/Engine/QueryParameters.cs trunk/nhibernate/src/NHibernate/Engine/ResultSetMappingDefinition.cs trunk/nhibernate/src/NHibernate/Hql/Classic/PathExpressionParser.cs trunk/nhibernate/src/NHibernate/Hql/Classic/QueryTranslator.cs trunk/nhibernate/src/NHibernate/Impl/MultiCriteriaImpl.cs trunk/nhibernate/src/NHibernate/Loader/Loader.cs trunk/nhibernate/src/NHibernate/SqlCommand/SqlStringBuilder.cs Modified: trunk/nhibernate/src/NHibernate/Action/CollectionRecreateAction.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Action/CollectionRecreateAction.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Action/CollectionRecreateAction.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -24,8 +24,7 @@ Stopwatch stopwatch = null; if (statsEnabled) { - stopwatch = new Stopwatch(); - stopwatch.Start(); + stopwatch = Stopwatch.StartNew(); } IPersistentCollection collection = Collection; Modified: trunk/nhibernate/src/NHibernate/Action/CollectionRemoveAction.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Action/CollectionRemoveAction.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Action/CollectionRemoveAction.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -61,8 +61,7 @@ Stopwatch stopwatch = null; if (statsEnabled) { - stopwatch = new Stopwatch(); - stopwatch.Start(); + stopwatch = Stopwatch.StartNew(); } PreRemove(); Modified: trunk/nhibernate/src/NHibernate/Action/CollectionUpdateAction.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Action/CollectionUpdateAction.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Action/CollectionUpdateAction.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -34,8 +34,7 @@ Stopwatch stopwatch = null; if (statsEnabled) { - stopwatch = new Stopwatch(); - stopwatch.Start(); + stopwatch = Stopwatch.StartNew(); } PreUpdate(); Modified: trunk/nhibernate/src/NHibernate/Action/EntityDeleteAction.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Action/EntityDeleteAction.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Action/EntityDeleteAction.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -39,8 +39,7 @@ Stopwatch stopwatch = null; if (statsEnabled) { - stopwatch = new Stopwatch(); - stopwatch.Start(); + stopwatch = Stopwatch.StartNew(); } bool veto = PreDelete(); Modified: trunk/nhibernate/src/NHibernate/Action/EntityIdentityInsertAction.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Action/EntityIdentityInsertAction.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Action/EntityIdentityInsertAction.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -62,8 +62,7 @@ Stopwatch stopwatch = null; if (statsEnabled) { - stopwatch = new Stopwatch(); - stopwatch.Start(); + stopwatch = Stopwatch.StartNew(); } bool veto = PreInsert(); Modified: trunk/nhibernate/src/NHibernate/Action/EntityInsertAction.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Action/EntityInsertAction.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Action/EntityInsertAction.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -46,8 +46,7 @@ Stopwatch stopwatch = null; if (statsEnabled) { - stopwatch = new Stopwatch(); - stopwatch.Start(); + stopwatch = Stopwatch.StartNew(); } bool veto = PreInsert(); Modified: trunk/nhibernate/src/NHibernate/Action/EntityUpdateAction.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Action/EntityUpdateAction.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Action/EntityUpdateAction.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -51,8 +51,7 @@ Stopwatch stopwatch = null; if (statsEnabled) { - stopwatch = new Stopwatch(); - stopwatch.Start(); + stopwatch = Stopwatch.StartNew(); } bool veto = PreUpdate(); Modified: trunk/nhibernate/src/NHibernate/AdoNet/OracleDataClientBatchingBatcher.cs =================================================================== --- trunk/nhibernate/src/NHibernate/AdoNet/OracleDataClientBatchingBatcher.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/AdoNet/OracleDataClientBatchingBatcher.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -16,7 +16,7 @@ private int countOfCommands = 0; private int totalExpectedRowsAffected; private IDbCommand currentBatch; - private IDictionary<string, ArrayList> parameterValueArrayHashTable; + private IDictionary<string, List<object>> parameterValueListHashTable; private IDictionary<string, bool> parameterIsAllNullsHashTable; @@ -37,7 +37,7 @@ { // use first command as the batching command currentBatch = CurrentCommand; - parameterValueArrayHashTable = new Dictionary<string, ArrayList>(); + parameterValueListHashTable = new Dictionary<string, List<object>>(); //oracle does not allow array containing all null values // so this Dictionary is keeping track if all values are null or not parameterIsAllNullsHashTable = new Dictionary<string, bool>(); @@ -47,25 +47,25 @@ firstOnBatch = false; } - ArrayList parameterValueArray; + List<object> parameterValueList; foreach (IDataParameter currentParameter in CurrentCommand.Parameters) { if (firstOnBatch) { - parameterValueArray = new ArrayList(); - parameterValueArrayHashTable.Add(currentParameter.ParameterName, parameterValueArray); + parameterValueList = new List<object>(); + parameterValueListHashTable.Add(currentParameter.ParameterName, parameterValueList); parameterIsAllNullsHashTable.Add(currentParameter.ParameterName, true); } else { - parameterValueArray = parameterValueArrayHashTable[currentParameter.ParameterName]; + parameterValueList = parameterValueListHashTable[currentParameter.ParameterName]; } if (currentParameter.Value != DBNull.Value) { parameterIsAllNullsHashTable[currentParameter.ParameterName] = false; } - parameterValueArray.Add(currentParameter.Value); + parameterValueList.Add(currentParameter.Value); } countOfCommands++; @@ -89,7 +89,7 @@ foreach (IDataParameter currentParameter in currentBatch.Parameters) { - ArrayList parameterValueArray = parameterValueArrayHashTable[currentParameter.ParameterName]; + List<object> parameterValueArray = parameterValueListHashTable[currentParameter.ParameterName]; currentParameter.Value = parameterValueArray.ToArray(); arraySize = parameterValueArray.Count; } @@ -104,7 +104,7 @@ totalExpectedRowsAffected = 0; currentBatch = null; - parameterValueArrayHashTable = null; + parameterValueListHashTable = null; } } Modified: trunk/nhibernate/src/NHibernate/Cache/StandardQueryCache.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cache/StandardQueryCache.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Cache/StandardQueryCache.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -65,31 +65,29 @@ { return false; } - else + + long ts = session.Timestamp; + + if (log.IsDebugEnabled) { - long ts = session.Timestamp; + log.Debug("caching query results in region: " + regionName); + } - if (log.IsDebugEnabled) + IList cacheable = new List<object>(result.Count + 1); + cacheable.Add(ts); + for (int i = 0; i < result.Count; i++) + { + if (returnTypes.Length == 1) { - log.Debug("caching query results in region: " + regionName); + cacheable.Add(returnTypes[0].Disassemble(result[i], session, null)); } - - IList cacheable = new ArrayList(result.Count + 1); - cacheable.Add(ts); - for (int i = 0; i < result.Count; i++) + else { - if (returnTypes.Length == 1) - { - cacheable.Add(returnTypes[0].Disassemble(result[i], session, null)); - } - else - { - cacheable.Add(TypeFactory.Disassemble((object[]) result[i], returnTypes, null, session, null)); - } + cacheable.Add(TypeFactory.Disassemble((object[]) result[i], returnTypes, null, session, null)); } - queryCache.Put(key, cacheable); - return true; } + queryCache.Put(key, cacheable); + return true; } public IList Get(QueryKey key, ICacheAssembler[] returnTypes, bool isNaturalKeyLookup, ISet<string> spaces, @@ -125,7 +123,7 @@ TypeFactory.BeforeAssemble((object[])cacheable[i], returnTypes, session); } } - IList result = new ArrayList(cacheable.Count - 1); + IList result = new List<object>(cacheable.Count - 1); for (int i = 1; i < cacheable.Count; i++) { try @@ -151,10 +149,8 @@ queryCache.Remove(key); return null; } - else - { - throw; - } + + throw; } } return result; Modified: trunk/nhibernate/src/NHibernate/Collection/AbstractPersistentCollection.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Collection/AbstractPersistentCollection.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Collection/AbstractPersistentCollection.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -646,8 +646,8 @@ { if (HasQueuedOperations) { - ArrayList additions = new ArrayList(operationQueue.Count); - ArrayList removals = new ArrayList(operationQueue.Count); + List<object> additions = new List<object>(operationQueue.Count); + List<object> removals = new List<object>(operationQueue.Count); for (int i = 0; i < operationQueue.Count; i++) { IDelayedOperation op = operationQueue[i]; @@ -662,10 +662,8 @@ } return GetOrphans(removals, additions, entityName, session); } - else - { - return CollectionHelper.EmptyCollection; - } + + return CollectionHelper.EmptyCollection; } /// <summary> @@ -707,7 +705,7 @@ IType idType = session.Factory.GetEntityPersister(entityName).IdentifierType; // create the collection holding the orphans - ArrayList res = new ArrayList(); + List<object> res = new List<object>(); // collect EntityIdentifier(s) of the *current* elements - add them into a HashSet for fast access HashedSet<TypedValue> currentIds = new HashedSet<TypedValue>(); @@ -740,7 +738,7 @@ IType idType = session.Factory.GetEntityPersister(entityName).IdentifierType; object idOfCurrent = ForeignKeys.GetEntityIdentifierIfNotUnsaved(entityName, obj, session); - ArrayList toRemove = new ArrayList(list.Count); + List<object> toRemove = new List<object>(list.Count); foreach (object current in list) { if (current == null) Modified: trunk/nhibernate/src/NHibernate/Collection/Generic/PersistentGenericMap.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Collection/Generic/PersistentGenericMap.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Collection/Generic/PersistentGenericMap.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -50,7 +50,7 @@ public override IEnumerable GetDeletes(ICollectionPersister persister, bool indexIsFormula) { - IList deletes = new ArrayList(); + IList deletes = new List<object>(); IDictionary<TKey, TValue> sn = (IDictionary<TKey, TValue>)GetSnapshot(); foreach (KeyValuePair<TKey, TValue> e in sn) { Modified: trunk/nhibernate/src/NHibernate/Collection/PersistentArrayHolder.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Collection/PersistentArrayHolder.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Collection/PersistentArrayHolder.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Collections.Generic; using System.Data; using System.Diagnostics; using log4net; @@ -29,7 +30,7 @@ /// A temporary list that holds the objects while the PersistentArrayHolder is being /// populated from the database. /// </summary> - [NonSerialized] private ArrayList tempList; + [NonSerialized] private List<object> tempList; public PersistentArrayHolder(ISessionImplementor session, object array) : base(session) { @@ -97,7 +98,7 @@ { object[] sn = (object[]) snapshot; object[] arr = (object[]) array; - ArrayList result = new ArrayList(sn); + List<object> result = new List<object>(sn); for (int i = 0; i < sn.Length; i++) { IdentityRemove(result, arr[i], entityName, Session); @@ -165,7 +166,7 @@ public override void BeginRead() { base.BeginRead(); - tempList = new ArrayList(); + tempList = new List<object>(); } /// <summary> @@ -223,7 +224,7 @@ public override IEnumerable GetDeletes(ICollectionPersister persister, bool indexIsFormula) { - IList deletes = new ArrayList(); + IList deletes = new List<object>(); Array sn = (Array) GetSnapshot(); int snSize = sn.Length; int arraySize = array.Length; Modified: trunk/nhibernate/src/NHibernate/Collection/PersistentBag.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Collection/PersistentBag.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Collection/PersistentBag.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Collections.Generic; using System.Data; using System.Diagnostics; using NHibernate.DebugHelpers; @@ -134,7 +135,7 @@ public override ICollection GetSnapshot(ICollectionPersister persister) { EntityMode entityMode = Session.EntityMode; - ArrayList clonedList = new ArrayList(bag.Count); + List<object> clonedList = new List<object>(bag.Count); foreach (object current in bag) { clonedList.Add(persister.ElementType.DeepCopy(current, entityMode, persister.Factory)); @@ -210,7 +211,7 @@ { IType elementType = persister.ElementType; EntityMode entityMode = Session.EntityMode; - ArrayList deletes = new ArrayList(); + List<object> deletes = new List<object>(); IList sn = (IList) GetSnapshot(); int i = 0; foreach (object old in sn) @@ -440,7 +441,7 @@ if (persister.IsOneToMany && HasQueuedOperations) { int additionStartFrom = bag.Count; - IList additionQueue = new ArrayList(additionStartFrom); + IList additionQueue = new List<object>(additionStartFrom); foreach (object o in QueuedAdditionIterator) { if (o != null) Modified: trunk/nhibernate/src/NHibernate/Collection/PersistentIdentifierBag.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Collection/PersistentIdentifierBag.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Collection/PersistentIdentifierBag.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -95,7 +95,7 @@ public override void BeforeInitialize(ICollectionPersister persister, int anticipatedSize) { identifiers = anticipatedSize <= 0 ? new Dictionary<int, object>() : new Dictionary<int, object>(anticipatedSize + 1); - values = anticipatedSize <= 0 ? new ArrayList() : new ArrayList(anticipatedSize); + values = anticipatedSize <= 0 ? new List<object>() : new List<object>(anticipatedSize); } public override object Disassemble(ICollectionPersister persister) Modified: trunk/nhibernate/src/NHibernate/Collection/PersistentList.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Collection/PersistentList.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Collection/PersistentList.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Collections.Generic; using System.Data; using System.Diagnostics; using NHibernate.DebugHelpers; @@ -54,7 +55,7 @@ { EntityMode entityMode = Session.EntityMode; - ArrayList clonedList = new ArrayList(list.Count); + List<object> clonedList = new List<object>(list.Count); foreach (object current in list) { object deepCopy = persister.ElementType.DeepCopy(current, entityMode, persister.Factory); @@ -164,7 +165,7 @@ public override IEnumerable GetDeletes(ICollectionPersister persister, bool indexIsFormula) { - IList deletes = new ArrayList(); + IList deletes = new List<object>(); IList sn = (IList) GetSnapshot(); int end; if (sn.Count > list.Count) Modified: trunk/nhibernate/src/NHibernate/Collection/PersistentMap.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Collection/PersistentMap.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Collection/PersistentMap.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Collections.Generic; using System.Data; using System.Diagnostics; using NHibernate.DebugHelpers; @@ -152,7 +153,7 @@ public override IEnumerable GetDeletes(ICollectionPersister persister, bool indexIsFormula) { - IList deletes = new ArrayList(); + IList deletes = new List<object>(); IDictionary sn = (IDictionary) GetSnapshot(); foreach (DictionaryEntry e in sn) { Modified: trunk/nhibernate/src/NHibernate/Collection/PersistentSet.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Collection/PersistentSet.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Collection/PersistentSet.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Collections.Generic; using System.Data; using System.Diagnostics; using Iesi.Collections; @@ -102,15 +103,13 @@ { return false; } - else + + foreach (object obj in set) { - foreach (object obj in set) + object oldValue = snapshot[obj]; + if (oldValue == null || elementType.IsDirty(oldValue, obj, Session)) { - object oldValue = snapshot[obj]; - if (oldValue == null || elementType.IsDirty(oldValue, obj, Session)) - { - return false; - } + return false; } } @@ -177,7 +176,7 @@ public override void BeginRead() { base.BeginRead(); - tempList = new ArrayList(); + tempList = new List<object>(); } /// <summary> @@ -214,7 +213,7 @@ { IType elementType = persister.ElementType; IDictionary sn = (IDictionary) GetSnapshot(); - ArrayList deletes = new ArrayList(sn.Count); + List<object> deletes = new List<object>(sn.Count); foreach (object obj in sn.Keys) { if (!set.Contains(obj)) Modified: trunk/nhibernate/src/NHibernate/Criterion/InExpression.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Criterion/InExpression.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Criterion/InExpression.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -115,7 +115,7 @@ public override TypedValue[] GetTypedValues(ICriteria criteria, ICriteriaQuery criteriaQuery) { - ArrayList list = new ArrayList(); + List<TypedValue> list = new List<TypedValue>(); IType type; if (_projection == null) { @@ -158,7 +158,7 @@ } } - return (TypedValue[]) list.ToArray(typeof (TypedValue)); + return list.ToArray(); } public object[] Values Modified: trunk/nhibernate/src/NHibernate/Criterion/Junction.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Criterion/Junction.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Criterion/Junction.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -14,7 +14,7 @@ [Serializable] public abstract class Junction : AbstractCriterion { - private IList _criteria = new ArrayList(); + private readonly IList<ICriterion> criteria = new List<ICriterion>(); /// <summary> /// Adds an <see cref="ICriterion"/> to the list of <see cref="ICriterion"/>s @@ -26,7 +26,7 @@ /// </returns> public Junction Add(ICriterion criterion) { - _criteria.Add(criterion); + criteria.Add(criterion); return this; } @@ -39,7 +39,7 @@ { ArrayList typedValues = new ArrayList(); - foreach (ICriterion criterion in _criteria) + foreach (ICriterion criterion in this.criteria) { TypedValue[] subvalues = criterion.GetTypedValues(criteria, criteriaQuery); ArrayHelper.AddAll(typedValues, subvalues); @@ -56,7 +56,7 @@ public override SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery, IDictionary<string, IFilter> enabledFilters) { - if (_criteria.Count == 0) + if (this.criteria.Count == 0) { return EmptyExpression; } @@ -66,15 +66,13 @@ sqlBuilder.Add("("); - for (int i = 0; i < _criteria.Count - 1; i++) + for (int i = 0; i < this.criteria.Count - 1; i++) { - sqlBuilder.Add( - ((ICriterion) _criteria[i]).ToSqlString(criteria, criteriaQuery, enabledFilters)); + sqlBuilder.Add(this.criteria[i].ToSqlString(criteria, criteriaQuery, enabledFilters)); sqlBuilder.Add(Op); } - sqlBuilder.Add( - ((ICriterion) _criteria[_criteria.Count - 1]).ToSqlString(criteria, criteriaQuery, enabledFilters)); + sqlBuilder.Add(this.criteria[this.criteria.Count - 1].ToSqlString(criteria, criteriaQuery, enabledFilters)); sqlBuilder.Add(")"); @@ -84,7 +82,7 @@ public override string ToString() { - return '(' + StringHelper.Join(Op, _criteria) + ')'; + return '(' + StringHelper.Join(Op, criteria) + ')'; } public override IProjection[] GetProjections() Modified: trunk/nhibernate/src/NHibernate/Dialect/Function/AnsiTrimEmulationFunction.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/Function/AnsiTrimEmulationFunction.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Dialect/Function/AnsiTrimEmulationFunction.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -1,5 +1,7 @@ using System; using System.Collections; +using System.Collections.Generic; + using NHibernate.Engine; using NHibernate.SqlCommand; using NHibernate.Type; @@ -95,101 +97,96 @@ // so we trim leading and trailing spaces return BothSpaceTrim.Render(args, factory); } - else if (StringHelper.EqualsCaseInsensitive("from", firstArg)) + + if (StringHelper.EqualsCaseInsensitive("from", firstArg)) { // we have the form: trim(from trimSource). // This is functionally equivalent to trim(trimSource) return BothSpaceTrimFrom.Render(args, factory); } + + // otherwise, a trim-specification and/or a trim-character + // have been specified; we need to decide which options + // are present and "do the right thing" + bool leading = true; // should leading trim-characters be trimmed? + bool trailing = true; // should trailing trim-characters be trimmed? + string trimCharacter = null; // the trim-character + object trimSource = null; // the trim-source + + // potentialTrimCharacterArgIndex = 1 assumes that a + // trim-specification has been specified. we handle the + // exception to that explicitly + int potentialTrimCharacterArgIndex = 1; + if (StringHelper.EqualsCaseInsensitive("leading", firstArg)) + { + trailing = false; + } + else if (StringHelper.EqualsCaseInsensitive("trailing", firstArg)) + { + leading = false; + } + else if (StringHelper.EqualsCaseInsensitive("both", firstArg)) + { + } else { - // otherwise, a trim-specification and/or a trim-character - // have been specified; we need to decide which options - // are present and "do the right thing" - bool leading = true; // should leading trim-characters be trimmed? - bool trailing = true; // should trailing trim-characters be trimmed? - string trimCharacter = null; // the trim-character - object trimSource = null; // the trim-source + potentialTrimCharacterArgIndex = 0; + } - // potentialTrimCharacterArgIndex = 1 assumes that a - // trim-specification has been specified. we handle the - // exception to that explicitly - int potentialTrimCharacterArgIndex = 1; - if (StringHelper.EqualsCaseInsensitive("leading", firstArg)) + object potentialTrimCharacter = args[potentialTrimCharacterArgIndex]; + if (StringHelper.EqualsCaseInsensitive("from", potentialTrimCharacter.ToString())) + { + trimCharacter = "' '"; + trimSource = args[potentialTrimCharacterArgIndex + 1]; + } + else if (potentialTrimCharacterArgIndex + 1 >= args.Count) + { + trimCharacter = "' '"; + trimSource = potentialTrimCharacter; + } + else + { + trimCharacter = potentialTrimCharacter.ToString(); + if (StringHelper.EqualsCaseInsensitive("from", args[potentialTrimCharacterArgIndex + 1].ToString())) { - trailing = false; + trimSource = args[potentialTrimCharacterArgIndex + 2]; } - else if (StringHelper.EqualsCaseInsensitive("trailing", firstArg)) - { - leading = false; - } - else if (StringHelper.EqualsCaseInsensitive("both", firstArg)) - { - } else { - potentialTrimCharacterArgIndex = 0; - } - - object potentialTrimCharacter = args[potentialTrimCharacterArgIndex]; - if (StringHelper.EqualsCaseInsensitive("from", potentialTrimCharacter.ToString())) - { - trimCharacter = "' '"; trimSource = args[potentialTrimCharacterArgIndex + 1]; } - else if (potentialTrimCharacterArgIndex + 1 >= args.Count) - { - trimCharacter = "' '"; - trimSource = potentialTrimCharacter; - } - else - { - trimCharacter = potentialTrimCharacter.ToString(); - if (StringHelper.EqualsCaseInsensitive("from", args[potentialTrimCharacterArgIndex + 1].ToString())) - { - trimSource = args[potentialTrimCharacterArgIndex + 2]; - } - else - { - trimSource = args[potentialTrimCharacterArgIndex + 1]; - } - } + } - IList argsToUse = new ArrayList(); - argsToUse.Add(trimSource); - argsToUse.Add(trimCharacter); + IList argsToUse = new List<object>(); + argsToUse.Add(trimSource); + argsToUse.Add(trimCharacter); - if (trimCharacter.Equals("' '")) + if (trimCharacter.Equals("' '")) + { + if (leading && trailing) { - if (leading && trailing) - { - return BothSpaceTrim.Render(argsToUse, factory); - } - else if (leading) - { - return LeadingSpaceTrim.Render(argsToUse, factory); - } - else - { - return TrailingSpaceTrim.Render(argsToUse, factory); - } + return BothSpaceTrim.Render(argsToUse, factory); } - else + + if (leading) { - if (leading && trailing) - { - return BothTrim.Render(argsToUse, factory); - } - else if (leading) - { - return LeadingTrim.Render(argsToUse, factory); - } - else - { - return TrailingTrim.Render(argsToUse, factory); - } + return LeadingSpaceTrim.Render(argsToUse, factory); } + + return TrailingSpaceTrim.Render(argsToUse, factory); } + + if (leading && trailing) + { + return BothTrim.Render(argsToUse, factory); + } + + if (leading) + { + return LeadingTrim.Render(argsToUse, factory); + } + + return TrailingTrim.Render(argsToUse, factory); } #endregion Modified: trunk/nhibernate/src/NHibernate/Driver/NDataReader.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Driver/NDataReader.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Driver/NDataReader.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -501,7 +501,7 @@ { schemaTable = reader.GetSchemaTable(); - ArrayList recordsList = new ArrayList(); + List<object[]> recordsList = new List<object[]>(); int rowIndex = 0; // if we are in the middle of processing the reader then don't bother @@ -533,7 +533,7 @@ isMidstream = false; } - records = (object[][]) recordsList.ToArray(typeof(object[])); + records = recordsList.ToArray(); } /// <summary> Modified: trunk/nhibernate/src/NHibernate/Engine/JoinSequence.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Engine/JoinSequence.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Engine/JoinSequence.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -12,7 +12,7 @@ public class JoinSequence { private readonly ISessionFactoryImplementor factory; - private readonly ArrayList joins = new ArrayList(); + private readonly List<Join> joins = new List<Join>(); private bool useThetaStyle = false; private readonly SqlStringBuilder conditions = new SqlStringBuilder(); private string rootAlias; @@ -162,7 +162,7 @@ for (int i = 0; i < joins.Count; i++) { - Join join = (Join) joins[i]; + Join join = joins[i]; string on = join.AssociationType.GetOnCondition(join.Alias, factory, enabledFilters); string condition; if (last != null && Modified: trunk/nhibernate/src/NHibernate/Engine/Query/HQLQueryPlan.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Engine/Query/HQLQueryPlan.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Engine/Query/HQLQueryPlan.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -218,7 +218,7 @@ queryParametersToUse = queryParameters; } - IList combinedResults = results ?? new ArrayList(); + IList combinedResults = results ?? new List<object>(); IdentitySet distinction = new IdentitySet(); int includedCount = -1; for (int i = 0; i < translators.Length; i++) Modified: trunk/nhibernate/src/NHibernate/Engine/Query/NativeSQLQueryPlan.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Engine/Query/NativeSQLQueryPlan.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Engine/Query/NativeSQLQueryPlan.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -177,7 +177,7 @@ private SqlType[] GetParameterTypes(QueryParameters parameters, ISessionImplementor session) { - ArrayList paramTypeList = new ArrayList(); + List<IType> paramTypeList = new List<IType>(); int span = 0; foreach (IType type in parameters.FilteredPositionalParameterTypes) @@ -207,7 +207,7 @@ return ConvertITypesToSqlTypes(paramTypeList, span, session); } - private static SqlType[] ConvertITypesToSqlTypes(ArrayList nhTypes, int totalSpan, ISessionImplementor session) + private static SqlType[] ConvertITypesToSqlTypes(IList<IType> nhTypes, int totalSpan, ISessionImplementor session) { SqlType[] result = new SqlType[totalSpan]; Modified: trunk/nhibernate/src/NHibernate/Engine/QueryParameters.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Engine/QueryParameters.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Engine/QueryParameters.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -292,8 +292,8 @@ SqlStringBuilder result = new SqlStringBuilder(); - IList parameters = new ArrayList(); - IList parameterTypes = new ArrayList(); + List<object> parameters = new List<object>(); + List<IType> parameterTypes = new List<IType>(); int parameterCount = 0; // keep track of the positional parameter foreach (object part in sql.Parts) @@ -367,8 +367,8 @@ } } - processedPositionalParameterValues = ((ArrayList)parameters).ToArray(); - processedPositionalParameterTypes = (IType[])((ArrayList)parameterTypes).ToArray(typeof(IType)); + processedPositionalParameterValues = parameters.ToArray(); + processedPositionalParameterTypes = parameterTypes.ToArray(); processedSQL = result.ToSqlString(); } } Modified: trunk/nhibernate/src/NHibernate/Engine/ResultSetMappingDefinition.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Engine/ResultSetMappingDefinition.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Engine/ResultSetMappingDefinition.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -1,4 +1,6 @@ using System.Collections; +using System.Collections.Generic; + using NHibernate.Engine.Query.Sql; namespace NHibernate.Engine @@ -6,7 +8,7 @@ public class ResultSetMappingDefinition { private readonly string name; - private readonly IList queryReturns = new ArrayList(); + private readonly IList<INativeSQLQueryReturn> queryReturns = new List<INativeSQLQueryReturn>(); public ResultSetMappingDefinition(string name) { Modified: trunk/nhibernate/src/NHibernate/Hql/Classic/PathExpressionParser.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Hql/Classic/PathExpressionParser.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Hql/Classic/PathExpressionParser.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -469,12 +469,12 @@ } private bool expectingCollectionIndex; - private ArrayList collectionElements = new ArrayList(); + private readonly List<CollectionElement> collectionElements = new List<CollectionElement>(); /// <summary></summary> public CollectionElement LastCollectionElement() { - CollectionElement ce = (CollectionElement) collectionElements[collectionElements.Count - 1]; + CollectionElement ce = collectionElements[collectionElements.Count - 1]; collectionElements.RemoveAt(collectionElements.Count - 1); return ce; //remove last } @@ -482,7 +482,7 @@ /// <summary></summary> public void SetLastCollectionElementIndexValue(SqlString value) { - ((CollectionElement) collectionElements[collectionElements.Count - 1]).IndexValue.Add(value); //getlast + collectionElements[collectionElements.Count - 1].IndexValue.Add(value); //getlast } /// <summary></summary> @@ -569,11 +569,9 @@ { return AddFromCollection(q); } - else - { - q.AddFrom(currentName, joinSequence); - return currentName; - } + + q.AddFrom(currentName, joinSequence); + return currentName; } /// <summary> @@ -615,12 +613,10 @@ currentPropertyMapping = new CollectionPropertyMapping(collectionPersister); return elementName; } - else - { - // collection of values - q.AddFromCollection(collectionName, collectionRole, joinSequence); - return collectionName; - } + + // collection of values + q.AddFromCollection(collectionName, collectionRole, joinSequence); + return collectionName; } /// <summary></summary> Modified: trunk/nhibernate/src/NHibernate/Hql/Classic/QueryTranslator.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Hql/Classic/QueryTranslator.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Hql/Classic/QueryTranslator.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -1072,7 +1072,7 @@ ExtractFunctionClause(tokens, ref tokenIdx); // The function render simply translate its name for a specific dialect. - return func.Render(new ArrayList(), Factory); + return func.Render(new List<object>(), Factory); } functionTokens = ExtractFunctionClause(tokens, ref tokenIdx); @@ -1080,7 +1080,7 @@ if (fg == null) fg = new CommonGrammar(); - IList args = new ArrayList(); + IList args = new List<object>(); SqlStringBuilder argBuf = new SqlStringBuilder(); // Extract args splitting first 2 token because are: FuncName( // last token is ')' Modified: trunk/nhibernate/src/NHibernate/Impl/MultiCriteriaImpl.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Impl/MultiCriteriaImpl.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Impl/MultiCriteriaImpl.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -95,7 +95,7 @@ ISet filterKeys = FilterKey.CreateFilterKeys(session.EnabledFilters, session.EntityMode); ISet<string> querySpaces = new HashedSet<string>(); - ArrayList resultTypesList = new ArrayList(); + List<IType[]> resultTypesList = new List<IType[]>(); int[] maxRows = new int[loaders.Count]; int[] firstRows = new int[loaders.Count]; for (int i = 0; i < loaders.Count; i++) @@ -159,7 +159,7 @@ private IList DoList() { - ArrayList results = new ArrayList(); + List<IList> results = new List<IList>(); GetResultsFromDatabase(results); return results; } Modified: trunk/nhibernate/src/NHibernate/Loader/Loader.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Loader/Loader.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/Loader/Loader.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -255,7 +255,7 @@ bool returnProxies) { int entitySpan = EntityPersisters.Length; - IList hydratedObjects = entitySpan == 0 ? null : new ArrayList(entitySpan); + IList hydratedObjects = entitySpan == 0 ? null : new List<object>(entitySpan); object result; try @@ -391,7 +391,7 @@ int entitySpan = EntityPersisters.Length; - ArrayList hydratedObjects = entitySpan == 0 ? null : new ArrayList(entitySpan * 10); + List<object> hydratedObjects = entitySpan == 0 ? null : new List<object>(entitySpan * 10); IDbCommand st = PrepareQueryCommand(queryParameters, false, session); @@ -408,7 +408,7 @@ bool createSubselects = IsSubselectLoadingEnabled; List<EntityKey[]> subselectResultKeys = createSubselects ? new List<EntityKey[]>() : null; - IList results = new ArrayList(); + IList results = new List<object>(); try { @@ -1764,7 +1764,7 @@ return new SqlCommandInfo(sqlString, GetParameterTypes(parameters, useLimit, useOffset)); } - protected SqlType[] ConvertITypesToSqlTypes(ArrayList nhTypes, int totalSpan) + protected SqlType[] ConvertITypesToSqlTypes(List<IType> nhTypes, int totalSpan) { SqlType[] result = new SqlType[totalSpan]; @@ -1782,7 +1782,7 @@ /// <returns><see cref="IList" /> of <see cref="IType" /></returns> protected SqlType[] GetParameterTypes(QueryParameters parameters, bool addLimit, bool addOffset) { - ArrayList paramTypeList = new ArrayList(); + List<IType> paramTypeList = new List<IType>(); int span = 0; foreach (IType type in parameters.FilteredPositionalParameterTypes) Modified: trunk/nhibernate/src/NHibernate/SqlCommand/SqlStringBuilder.cs =================================================================== --- trunk/nhibernate/src/NHibernate/SqlCommand/SqlStringBuilder.cs 2008-11-26 13:50:31 UTC (rev 3933) +++ trunk/nhibernate/src/NHibernate/SqlCommand/SqlStringBuilder.cs 2008-11-26 22:38:49 UTC (rev 3934) @@ -1,5 +1,7 @@ using System; using System.Collections; +using System.Collections.Generic; + using NHibernate.Util; namespace NHibernate.SqlCommand @@ -30,7 +32,7 @@ public class SqlStringBuilder : ISqlStringBuilder { // this holds the strings and parameters that make up the full sql statement. - private ArrayList sqlParts; + private List<object> sqlParts; private AddingSqlStringVisitor addingVisitor; @@ -59,7 +61,7 @@ /// <param name="partsCapacity">The number of parts expected.</param> public SqlStringBuilder(int partsCapacity) { - sqlParts = new ArrayList(partsCapacity); + sqlParts = new List<object>(partsCapacity); } /// <summary> @@ -68,7 +70,7 @@ /// <param name="sqlString">The SqlString to modify.</param> public SqlStringBuilder(SqlString sqlString) { - sqlParts = new ArrayList(sqlString.Count); + sqlParts = new List<object>(sqlString.Count); Add(sqlString); } @@ -311,7 +313,7 @@ /// <returns>The SqlString that was built.</returns> public SqlString ToSqlString() { - return new SqlString((object[]) sqlParts.ToArray(typeof(object))); + return new SqlString(sqlParts.ToArray()); } public override string ToString() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <te...@us...> - 2008-11-27 19:58:07
|
Revision: 3935 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3935&view=rev Author: tehlike Date: 2008-11-27 19:58:01 +0000 (Thu, 27 Nov 2008) Log Message: ----------- Fix NH-1578 Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Criterion/NotExpression.cs trunk/nhibernate/src/NHibernate.Test/ExpressionTest/NotExpressionFixture.cs Modified: trunk/nhibernate/src/NHibernate/Criterion/NotExpression.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Criterion/NotExpression.cs 2008-11-26 22:38:49 UTC (rev 3934) +++ trunk/nhibernate/src/NHibernate/Criterion/NotExpression.cs 2008-11-27 19:58:01 UTC (rev 3935) @@ -28,24 +28,10 @@ { //TODO: set default capacity SqlStringBuilder builder = new SqlStringBuilder(); - - bool needsParens = criteriaQuery.Factory.Dialect is MySQLDialect; - if (needsParens) - { - builder.Add("not ("); - } - else - { - builder.Add("not "); - } - + builder.Add("not ("); builder.Add(_criterion.ToSqlString(criteria, criteriaQuery, enabledFilters)); + builder.Add(")"); - if (needsParens) - { - builder.Add(")"); - } - return builder.ToSqlString(); } @@ -56,7 +42,7 @@ public override string ToString() { - return "not " + _criterion.ToString(); + return string.Format("not ({0})", _criterion.ToString()); } public override IProjection[] GetProjections() Modified: trunk/nhibernate/src/NHibernate.Test/ExpressionTest/NotExpressionFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/ExpressionTest/NotExpressionFixture.cs 2008-11-26 22:38:49 UTC (rev 3934) +++ trunk/nhibernate/src/NHibernate.Test/ExpressionTest/NotExpressionFixture.cs 2008-11-27 19:58:01 UTC (rev 3935) @@ -23,12 +23,8 @@ CreateObjects(typeof(Simple), session); SqlString sqlString = notExpression.ToSqlString(criteria, criteriaQuery, new CollectionHelper.EmptyMapClass<string, IFilter>()); - string expectedSql = dialect is MySQLDialect ? - "not (sql_alias.address = ?)" : - "not sql_alias.address = ?"; - + string expectedSql = "not (sql_alias.address = ?)"; CompareSqlStrings(sqlString, expectedSql, 1); - session.Close(); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <te...@us...> - 2008-11-27 20:12:38
|
Revision: 3936 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3936&view=rev Author: tehlike Date: 2008-11-27 20:12:33 +0000 (Thu, 27 Nov 2008) Log Message: ----------- Fix for NH-1591 by Henry Concei?\195?\167?\195?\163o with tests added. Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Criterion/DetachedCriteria.cs trunk/nhibernate/src/NHibernate.Test/Criteria/CriteriaQueryTest.cs Modified: trunk/nhibernate/src/NHibernate/Criterion/DetachedCriteria.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Criterion/DetachedCriteria.cs 2008-11-27 19:58:01 UTC (rev 3935) +++ trunk/nhibernate/src/NHibernate/Criterion/DetachedCriteria.cs 2008-11-27 20:12:33 UTC (rev 3936) @@ -166,6 +166,18 @@ return this; } + public DetachedCriteria SetCacheRegion(string region) + { + criteria.SetCacheRegion(region); + return this; + } + + public DetachedCriteria SetCacheable(bool cacheable) + { + criteria.SetCacheable(cacheable); + return this; + } + public DetachedCriteria SetProjection(IProjection projection) { criteria.SetProjection(projection); Modified: trunk/nhibernate/src/NHibernate.Test/Criteria/CriteriaQueryTest.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Criteria/CriteriaQueryTest.cs 2008-11-27 19:58:01 UTC (rev 3935) +++ trunk/nhibernate/src/NHibernate.Test/Criteria/CriteriaQueryTest.cs 2008-11-27 20:12:33 UTC (rev 3936) @@ -7,6 +7,7 @@ using NHibernate.Type; using NHibernate.Util; using NUnit.Framework; +using NUnit.Framework.SyntaxHelpers; namespace NHibernate.Test.Criteria { @@ -1589,7 +1590,35 @@ t.Commit(); session.Close(); } + [Test] + public void CacheDetachedCriteria() + { + using (ISession session = OpenSession()) + { + bool current = sessions.Statistics.IsStatisticsEnabled; + sessions.Statistics.IsStatisticsEnabled = true; + sessions.Statistics.Clear(); + DetachedCriteria dc = DetachedCriteria.For(typeof (Student)) + .Add(Property.ForName("Name").Eq("Gavin King")) + .SetProjection(Property.ForName("StudentNumber")) + .SetCacheable(true); + Assert.That(sessions.Statistics.QueryCacheMissCount,Is.EqualTo(0)); + Assert.That(sessions.Statistics.QueryCacheHitCount, Is.EqualTo(0)); + dc.GetExecutableCriteria(session).List(); + Assert.That(sessions.Statistics.QueryCacheMissCount, Is.EqualTo(1)); + dc = DetachedCriteria.For(typeof(Student)) + .Add(Property.ForName("Name").Eq("Gavin King")) + .SetProjection(Property.ForName("StudentNumber")) + .SetCacheable(true); + dc.GetExecutableCriteria(session).List(); + + Assert.That(sessions.Statistics.QueryCacheMissCount, Is.EqualTo(1)); + Assert.That(sessions.Statistics.QueryCacheHitCount, Is.EqualTo(1)); + sessions.Statistics.IsStatisticsEnabled = false; + } + + } [Test] public void PropertyWithFormulaAndPagingTest() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <dav...@us...> - 2008-11-29 18:07:26
|
Revision: 3937 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3937&view=rev Author: davybrion Date: 2008-11-29 18:07:21 +0000 (Sat, 29 Nov 2008) Log Message: ----------- applied patch from Jon Stelly for NH-1579 Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Persister/Entity/SingleTableEntityPersister.cs trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Apple.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Cart.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Entity.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Fruit.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Mappings.hbm.xml trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/NH1579Fixture.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Orange.cs Modified: trunk/nhibernate/src/NHibernate/Persister/Entity/SingleTableEntityPersister.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Persister/Entity/SingleTableEntityPersister.cs 2008-11-27 20:12:33 UTC (rev 3936) +++ trunk/nhibernate/src/NHibernate/Persister/Entity/SingleTableEntityPersister.cs 2008-11-29 18:07:21 UTC (rev 3937) @@ -522,7 +522,8 @@ public override string OneToManyFilterFragment(string alias) { - return forceDiscriminator ? DiscriminatorFilterFragment(alias) : string.Empty; + //Previous code was checking forceDiscriminator value here, which caused issues with collection loading. + return DiscriminatorFilterFragment(alias); } private string DiscriminatorFilterFragment(string alias) Property changes on: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579 ___________________________________________________________________ Added: bugtraq:url + http://jira.nhibernate.org/browse/%BUGID% Added: bugtraq:logregex + NH-\d+ Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Apple.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Apple.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Apple.cs 2008-11-29 18:07:21 UTC (rev 3937) @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace NHibernate.Test.NHSpecificTest.NH1579 +{ + public class Apple : Fruit + { + public Apple(Entity container) + : base(container) + { + } + + protected Apple() + { + } + } +} Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Cart.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Cart.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Cart.cs 2008-11-29 18:07:21 UTC (rev 3937) @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace NHibernate.Test.NHSpecificTest.NH1579 +{ + public class Cart : Entity + { + public Cart(string vendorName) + { + if (String.IsNullOrEmpty(vendorName)) + throw new ArgumentNullException("vendorName"); + + VendorName = vendorName; + EnsureCollections(); + } + + private void EnsureCollections() + { + if(Apples == null) + Apples = new List<Apple>(); + if(Oranges == null) + Oranges = new List<Orange>(); + } + + protected Cart() + { + } + + public string VendorName { get; set; } + public IList<Apple> Apples { get; set; } + public IList<Orange> Oranges { get; set; } + } +} Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Entity.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Entity.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Entity.cs 2008-11-29 18:07:21 UTC (rev 3937) @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace NHibernate.Test.NHSpecificTest.NH1579 +{ + public abstract class Entity + { + public Entity() + { + } + + public Guid ID { get; private set; } + } +} Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Fruit.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Fruit.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Fruit.cs 2008-11-29 18:07:21 UTC (rev 3937) @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace NHibernate.Test.NHSpecificTest.NH1579 +{ + public abstract class Fruit : Entity + { + public Fruit(Entity container) + { + if (container == null) + throw new ArgumentNullException("container"); + Container = container; + } + + protected Fruit() + { + } + + public Entity Container { get; private set; } + + } +} Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Mappings.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Mappings.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Mappings.hbm.xml 2008-11-29 18:07:21 UTC (rev 3937) @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="utf-8" ?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="NHibernate.Test.NHSpecificTest.NH1579" assembly="NHibernate.Test" default-lazy="false"> + <class name="Entity" abstract="true" table="Entities"> + <id name="ID"> + <generator class="guid.comb" /> + </id> + <discriminator column="EntityType" length="64"/> + </class> + + <subclass name="Fruit" abstract="true" discriminator-value="Fruit" extends="NHibernate.Test.NHSpecificTest.NH1579.Entity, NHibernate.Test"> + <many-to-one name="Container" column="ContainerID" /> + </subclass> + <subclass name="Apple" discriminator-value="Apple" extends="NHibernate.Test.NHSpecificTest.NH1579.Fruit, NHibernate.Test"/> + <subclass name="Orange" discriminator-value="Orange" extends="NHibernate.Test.NHSpecificTest.NH1579.Fruit, NHibernate.Test"/> + + <subclass name="Cart" discriminator-value="Cart" extends="NHibernate.Test.NHSpecificTest.NH1579.Entity, NHibernate.Test"> + <property name="VendorName" length="128"/> + <bag name="Apples" cascade="all-delete-orphan" inverse="true"> + <key column="ContainerID"/> + <one-to-many class="NHibernate.Test.NHSpecificTest.NH1579.Apple, NHibernate.Test"/> + </bag> + <bag name="Oranges" cascade="all-delete-orphan" inverse="true"> + <key column="ContainerID"/> + <one-to-many class="NHibernate.Test.NHSpecificTest.NH1579.Orange, NHibernate.Test"/> + </bag> + </subclass> +</hibernate-mapping> Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/NH1579Fixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/NH1579Fixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/NH1579Fixture.cs 2008-11-29 18:07:21 UTC (rev 3937) @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Text; + +using NUnit.Framework; + +namespace NHibernate.Test.NHSpecificTest.NH1579 +{ + [TestFixture] + public class NH1579Fixture : BugTestCase + { + [Test] + public void Test() + { + Cart cart = new Cart("Fred"); + Apple apple = new Apple(cart); + Orange orange = new Orange(cart); + cart.Apples.Add(apple); + cart.Oranges.Add(orange); + + using (ISession session = OpenSession()) + { + using (ITransaction tx = session.BeginTransaction()) + { + session.Save(cart); + tx.Commit(); + } + } + + using (ISession session = OpenSession()) + { + IQuery query = session.CreateQuery("FROM Fruit f WHERE f.Container.id = :containerID"); + query.SetGuid("containerID", cart.ID); + IList<Fruit> fruit = query.List<Fruit>(); + Assert.AreEqual(2, fruit.Count); + } + + using (ISession session = OpenSession()) + { + using (ITransaction tx = session.BeginTransaction()) + { + session.Delete("FROM Entity"); + tx.Commit(); + } + } + } + } +} Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Orange.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Orange.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Orange.cs 2008-11-29 18:07:21 UTC (rev 3937) @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace NHibernate.Test.NHSpecificTest.NH1579 +{ + public class Orange : Fruit + { + public Orange(Entity container) + : base(container) + { + } + + protected Orange() + { + } + } +} Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-11-27 20:12:33 UTC (rev 3936) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-11-29 18:07:21 UTC (rev 3937) @@ -524,6 +524,12 @@ <Compile Include="NHSpecificTest\NH1556\Patient.cs" /> <Compile Include="NHSpecificTest\NH1556\Product.cs" /> <Compile Include="NHSpecificTest\NH1556\ProductIdentifier.cs" /> + <Compile Include="NHSpecificTest\NH1579\Apple.cs" /> + <Compile Include="NHSpecificTest\NH1579\Cart.cs" /> + <Compile Include="NHSpecificTest\NH1579\Entity.cs" /> + <Compile Include="NHSpecificTest\NH1579\Fruit.cs" /> + <Compile Include="NHSpecificTest\NH1579\NH1579Fixture.cs" /> + <Compile Include="NHSpecificTest\NH1579\Orange.cs" /> <Compile Include="NHSpecificTest\NH1587\A.cs" /> <Compile Include="NHSpecificTest\NH1587\Fixture.cs" /> <Compile Include="NHSpecificTest\NH280\Fixture.cs" /> @@ -1546,6 +1552,7 @@ <EmbeddedResource Include="Cascade\JobBatch.hbm.xml" /> <EmbeddedResource Include="Deletetransient\Person.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> + <EmbeddedResource Include="NHSpecificTest\NH1579\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH298\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1587\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1556\Mappings.hbm.xml" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <dav...@us...> - 2008-11-30 00:54:27
|
Revision: 3939 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3939&view=rev Author: davybrion Date: 2008-11-30 00:54:18 +0000 (Sun, 30 Nov 2008) Log Message: ----------- Removed the EntityLoadContext class since it wasn't really used anywhere Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Engine/Loading/LoadContexts.cs trunk/nhibernate/src/NHibernate/NHibernate.csproj Removed Paths: ------------- trunk/nhibernate/src/NHibernate/Engine/Loading/EntityLoadContext.cs Deleted: trunk/nhibernate/src/NHibernate/Engine/Loading/EntityLoadContext.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Engine/Loading/EntityLoadContext.cs 2008-11-29 18:25:20 UTC (rev 3938) +++ trunk/nhibernate/src/NHibernate/Engine/Loading/EntityLoadContext.cs 2008-11-30 00:54:18 UTC (rev 3939) @@ -1,34 +0,0 @@ -using System.Collections; -using System.Data; -using log4net; - -namespace NHibernate.Engine.Loading -{ - public class EntityLoadContext - { - private static readonly ILog log = LogManager.GetLogger(typeof(EntityLoadContext)); - private LoadContexts loadContexts; - private readonly IDataReader resultSet; - private readonly IList hydratingEntities = new ArrayList(20); // todo : need map? the prob is a proper key, right? - - public EntityLoadContext(LoadContexts loadContexts, IDataReader resultSet) - { - this.loadContexts = loadContexts; - this.resultSet = resultSet; - } - - internal void Cleanup() - { - if (!(hydratingEntities.Count == 0)) - { - log.Warn("On CollectionLoadContext#clear, hydratingEntities contained [" + hydratingEntities.Count + "] entries"); - } - hydratingEntities.Clear(); - } - - public override string ToString() - { - return base.ToString() + "<rs=" + resultSet + ">"; - } - } -} Modified: trunk/nhibernate/src/NHibernate/Engine/Loading/LoadContexts.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Engine/Loading/LoadContexts.cs 2008-11-29 18:25:20 UTC (rev 3938) +++ trunk/nhibernate/src/NHibernate/Engine/Loading/LoadContexts.cs 2008-11-30 00:54:18 UTC (rev 3939) @@ -31,7 +31,6 @@ [NonSerialized] private readonly IPersistenceContext persistenceContext; private IDictionary collectionLoadContexts; - private IDictionary entityLoadContexts; private Dictionary<CollectionKey, LoadingCollectionEntry> xrefLoadingCollectionEntries; @@ -72,20 +71,10 @@ { if (collectionLoadContexts != null) { - object tempObject; - tempObject = collectionLoadContexts[resultSet]; - collectionLoadContexts.Remove(resultSet); - CollectionLoadContext collectionLoadContext = (CollectionLoadContext)tempObject; + CollectionLoadContext collectionLoadContext = (CollectionLoadContext)collectionLoadContexts[resultSet]; collectionLoadContext.Cleanup(); + collectionLoadContexts.Remove(resultSet); } - if (entityLoadContexts != null) - { - object tempObject2; - tempObject2 = entityLoadContexts[resultSet]; - entityLoadContexts.Remove(resultSet); - EntityLoadContext entityLoadContext = (EntityLoadContext)tempObject2; - entityLoadContext.Cleanup(); - } } /// <summary> Release internal state associated with *all* result sets. </summary> @@ -104,15 +93,6 @@ } collectionLoadContexts.Clear(); } - if (entityLoadContexts != null) - { - foreach (EntityLoadContext entityLoadContext in entityLoadContexts.Values) - { - log.Warn("fail-safe cleanup (entities) : " + entityLoadContext); - entityLoadContext.Cleanup(); - } - entityLoadContexts.Clear(); - } } /// <summary> @@ -262,24 +242,5 @@ foreach (CollectionKey entryKey in entryKeys) xrefLoadingCollectionEntries.Remove(entryKey); } - - public EntityLoadContext GetEntityLoadContext(IDataReader resultSet) - { - EntityLoadContext context = null; - if (entityLoadContexts == null) - { - entityLoadContexts = IdentityMap.Instantiate(8); - } - else - { - context = (EntityLoadContext)entityLoadContexts[resultSet]; - } - if (context == null) - { - context = new EntityLoadContext(this, resultSet); - entityLoadContexts[resultSet] = context; - } - return context; - } } } Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-29 18:25:20 UTC (rev 3938) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-30 00:54:18 UTC (rev 3939) @@ -616,7 +616,6 @@ <Compile Include="Engine\IdentifierValue.cs" /> <Compile Include="Engine\IPersistenceContext.cs" /> <Compile Include="Engine\Loading\CollectionLoadContext.cs" /> - <Compile Include="Engine\Loading\EntityLoadContext.cs" /> <Compile Include="Engine\Loading\LoadContexts.cs" /> <Compile Include="Engine\Loading\LoadingCollectionEntry.cs" /> <Compile Include="Engine\Nullability.cs" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-11-30 20:10:58
|
Revision: 3940 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3940&view=rev Author: fabiomaulo Date: 2008-11-30 20:10:54 +0000 (Sun, 30 Nov 2008) Log Message: ----------- Revert of r3937 because NH-1579 is not an issue (wrong mapping) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Persister/Entity/SingleTableEntityPersister.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Mappings.hbm.xml Modified: trunk/nhibernate/src/NHibernate/Persister/Entity/SingleTableEntityPersister.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Persister/Entity/SingleTableEntityPersister.cs 2008-11-30 00:54:18 UTC (rev 3939) +++ trunk/nhibernate/src/NHibernate/Persister/Entity/SingleTableEntityPersister.cs 2008-11-30 20:10:54 UTC (rev 3940) @@ -522,8 +522,7 @@ public override string OneToManyFilterFragment(string alias) { - //Previous code was checking forceDiscriminator value here, which caused issues with collection loading. - return DiscriminatorFilterFragment(alias); + return forceDiscriminator ? DiscriminatorFilterFragment(alias) : string.Empty; } private string DiscriminatorFilterFragment(string alias) Modified: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Mappings.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Mappings.hbm.xml 2008-11-30 00:54:18 UTC (rev 3939) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1579/Mappings.hbm.xml 2008-11-30 20:10:54 UTC (rev 3940) @@ -4,7 +4,7 @@ <id name="ID"> <generator class="guid.comb" /> </id> - <discriminator column="EntityType" length="64"/> + <discriminator column="EntityType" length="64" force="true"/> </class> <subclass name="Fruit" abstract="true" discriminator-value="Fruit" extends="NHibernate.Test.NHSpecificTest.NH1579.Entity, NHibernate.Test"> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <dav...@us...> - 2008-12-03 19:45:15
|
Revision: 3942 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3942&view=rev Author: davybrion Date: 2008-12-03 19:45:12 +0000 (Wed, 03 Dec 2008) Log Message: ----------- included patch from Robert Sosnowski for NH-1592 Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Dialect/InformixDialect.cs trunk/nhibernate/src/NHibernate/NHibernate.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate/Dialect/InformixDialect0940.cs trunk/nhibernate/src/NHibernate/Dialect/InformixDialect1000.cs trunk/nhibernate/src/NHibernate/Exceptions/ReflectionBasedSqlStateExtracter.cs trunk/nhibernate/src/NHibernate/Exceptions/SqlStateExtracter.cs trunk/nhibernate/src/NHibernate/Exceptions/TemplatedViolatedConstraintNameExtracter.cs trunk/nhibernate/src/NHibernate/SqlCommand/InformixJoinFragment.cs Modified: trunk/nhibernate/src/NHibernate/Dialect/InformixDialect.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/InformixDialect.cs 2008-11-30 20:32:19 UTC (rev 3941) +++ trunk/nhibernate/src/NHibernate/Dialect/InformixDialect.cs 2008-12-03 19:45:12 UTC (rev 3942) @@ -1,101 +1,490 @@ using System.Data; -using NHibernate.Cfg; +using NHibernate.Dialect.Function; +using NHibernate.SqlCommand; +using System.Data.Common; +using NHibernate.Exceptions; +//using NHibernate.Dialect.Schema; +using Environment = NHibernate.Cfg.Environment; + namespace NHibernate.Dialect { - /// <summary> - /// Summary description for InformixDialect. - /// </summary> - /// <remarks> - /// The InformixDialect defaults the following configuration properties: - /// <list type="table"> - /// <listheader> - /// <term>Property</term> - /// <description>Default Value</description> - /// </listheader> - /// <item> - /// <term>connection.driver_class</term> - /// <description><see cref="NHibernate.Driver.OdbcDriver" /></description> - /// </item> - /// </list> - /// </remarks> - public class InformixDialect : Dialect - { - /// <summary></summary> - public InformixDialect() : base() - { -// registerFunction( "concat", new VarArgsSQLFunction( Hibernate.STRING, "(", "||", ")" ) ); + /// <summary> + /// Summary description for InformixDialect. + /// This dialect is intended to work with IDS version 7.31 + /// However I can test only version 10.00 as I have only this version at work + /// </summary> + /// <remarks> + /// The InformixDialect defaults the following configuration properties: + /// <list type="table"> + /// <listheader> + /// <term>ConnectionDriver</term> + /// <description>NHibernate.Driver.OdbcDriver</description> + /// <term>PrepareSql</term> + /// <description>true</description> + /// </listheader> + /// <item> + /// <term>connection.driver_class</term> + /// <description><see cref="NHibernate.Driver.OdbcDriver" /></description> + /// </item> + /// </list> + /// </remarks> + public class InformixDialect : Dialect + { + /// <summary></summary> + public InformixDialect() + : base() + { + RegisterColumnType(DbType.AnsiStringFixedLength, "CHAR($l)"); + RegisterColumnType(DbType.AnsiString, 255, "VARCHAR($l)"); + RegisterColumnType(DbType.AnsiString, 32739, "LVARCHAR($l)"); + RegisterColumnType(DbType.AnsiString, 2147483647, "TEXT"); + RegisterColumnType(DbType.AnsiString, "VARCHAR(255)"); + RegisterColumnType(DbType.Binary, 2147483647, "BYTE"); + RegisterColumnType(DbType.Binary, "BYTE"); + RegisterColumnType(DbType.Boolean, "BOOLEAN"); + RegisterColumnType(DbType.Currency, "DECIMAL(16,4)"); + RegisterColumnType(DbType.Byte, "SMALLINT"); + RegisterColumnType(DbType.Date, "DATE"); + RegisterColumnType(DbType.DateTime, "datetime year to fraction(5)"); + RegisterColumnType(DbType.Decimal, "DECIMAL(19, 5)"); + RegisterColumnType(DbType.Decimal, 19, "DECIMAL($p, $s)"); + RegisterColumnType(DbType.Double, "DOUBLE"); + RegisterColumnType(DbType.Int16, "SMALLINT"); + RegisterColumnType(DbType.Int32, "INTEGER"); + RegisterColumnType(DbType.Int64, "BIGINT"); + RegisterColumnType(DbType.Single, "SmallFloat"); + RegisterColumnType(DbType.Time, "datetime hour to second"); + RegisterColumnType(DbType.StringFixedLength, "CHAR($l)"); + RegisterColumnType(DbType.String, 255, "VARCHAR($l)"); + RegisterColumnType(DbType.String, 32739, "LVARCHAR($l)"); + RegisterColumnType(DbType.String, 2147483647, "TEXT"); + RegisterColumnType(DbType.String, "VARCHAR(255)"); - RegisterColumnType(DbType.AnsiStringFixedLength, "CHAR($l)"); - RegisterColumnType(DbType.AnsiString, 255, "VARCHAR($l)"); - RegisterColumnType(DbType.AnsiString, 32739, "LVARCHAR($l)"); - RegisterColumnType(DbType.AnsiString, 2147483647, "CLOB"); - RegisterColumnType(DbType.AnsiString, "VARCHAR(255)"); - RegisterColumnType(DbType.Binary, 2147483647, "BLOB"); - RegisterColumnType(DbType.Binary, "BLOB"); - RegisterColumnType(DbType.Byte, "SMALLINT"); - RegisterColumnType(DbType.Date, "DATE"); - RegisterColumnType(DbType.DateTime, "datetime year to fraction(5)"); - RegisterColumnType(DbType.Decimal, "DECIMAL(19,5)"); - RegisterColumnType(DbType.Decimal, 19, "DECIMAL(19, $l)"); - RegisterColumnType(DbType.Double, "DOUBLE"); - RegisterColumnType(DbType.Int16, "SMALLINT"); - RegisterColumnType(DbType.Int32, "INTEGER"); - RegisterColumnType(DbType.Int64, "BIGINT"); - RegisterColumnType(DbType.Single, "SmallFloat"); - RegisterColumnType(DbType.Time, "datetime hour to second"); - RegisterColumnType(DbType.StringFixedLength, "CHAR($l)"); - RegisterColumnType(DbType.String, 255, "VARCHAR($l)"); - RegisterColumnType(DbType.String, 32739, "LVARCHAR($l)"); - RegisterColumnType(DbType.String, 2147483647, "CLOB"); - RegisterColumnType(DbType.String, "VARCHAR(255)"); + RegisterFunction("substring", new AnsiSubstringFunction()); // base class override + RegisterFunction("substr", new StandardSQLFunction("substr")); + // RegisterFunction("trim", new AnsiTrimFunction()); // defined in base class + // RegisterFunction("length", new StandardSQLFunction("length", NHibernateUtil.Int32)); // defined in base class + RegisterFunction("coalesce", new NvlFunction()); // base class override + // RegisterFunction("abs", new StandardSQLFunction("abs")); + // RegisterFunction("mod", new StandardSQLFunction("mod", NHibernateUtil.Int32)); + // RegisterFunction("sqrt", new StandardSQLFunction("sqrt", NHibernateUtil.Double)); + // RegisterFunction("upper", new StandardSQLFunction("upper")); + // RegisterFunction("lower", new StandardSQLFunction("lower")); + // RegisterFunction("cast", new CastFunction()); + // RegisterFunction("concat", new VarArgsSQLFunction(NHibernateUtil.String, "(", "||", ")")); + RegisterFunction("current_timestamp", new NoArgSQLFunction("current", NHibernateUtil.DateTime, false)); + RegisterFunction("sysdate", new NoArgSQLFunction("today", NHibernateUtil.DateTime, false)); + RegisterFunction("current", new NoArgSQLFunction("current", NHibernateUtil.DateTime, false)); + RegisterFunction("today", new NoArgSQLFunction("today", NHibernateUtil.DateTime, false)); + RegisterFunction("day", new StandardSQLFunction("day", NHibernateUtil.Int32)); + RegisterFunction("month", new StandardSQLFunction("month", NHibernateUtil.Int32)); + RegisterFunction("year", new StandardSQLFunction("year", NHibernateUtil.Int32)); + RegisterFunction("date", new StandardSQLFunction("date", NHibernateUtil.DateTime)); + RegisterFunction("mdy", new SQLFunctionTemplate(NHibernateUtil.DateTime, "mdy(?1, ?2, ?3)")); + RegisterFunction("to_char", new StandardSQLFunction("to_char", NHibernateUtil.String)); + RegisterFunction("to_date", new StandardSQLFunction("to_date", NHibernateUtil.Timestamp)); + RegisterFunction("instr", new StandardSQLFunction("instr", NHibernateUtil.String)); + // actually there is no Instr (or equivalent) in Informix; you have to write your own SPL or UDR - DefaultProperties[Environment.ConnectionDriver] = "NHibernate.Driver.OdbcDriver"; - } + DefaultProperties[Environment.ConnectionDriver] = "NHibernate.Driver.OdbcDriver"; + DefaultProperties[Environment.PrepareSql] = "true"; + } - /// <summary></summary> - public override string AddColumnString - { - get { return "add"; } - } + /// <summary> + /// The keyword used to insert a generated value into an identity column (or null). + /// Need if the dialect does not support inserts that specify no column values. + /// </summary> + public override string IdentityInsertString + { + get { return "0"; } + } - public override bool SupportsIdentityColumns - { - get { return true; } - } + /// <summary> Command used to create a temporary table. </summary> + public override string CreateTemporaryTableString + { + get { return "create temp table"; } + } - /// <summary> - /// The syntax that returns the identity value of the last insert, if native - /// key generation is supported - /// </summary> - public override string IdentitySelectString - { -// return type==Types.BIGINT ? -// "select dbinfo('serial8') from systables where tabid=1" : -// "select dbinfo('sqlca.sqlerrd1') from systables where tabid=1"; - get { return "select dbinfo('sqlca.sqlerrd1') from systables where tabid=1"; } - } + /// <summary> + /// Get any fragments needing to be postfixed to the command for + /// temporary table creation. + /// </summary> + public override string CreateTemporaryTablePostfix + { + get { return "with no log"; } + } + /// <summary> + /// Should the value returned by <see cref="CurrentTimestampSelectString"/> + /// be treated as callable. Typically this indicates that JDBC escape + /// sytnax is being used... + /// </summary> + public override bool IsCurrentTimestampSelectStringCallable + { + get { return true; } + } - /// <summary> - /// The keyword used to specify an identity column, if native key generation is supported - /// </summary> - public override string IdentityColumnString - { -// return type==Types.BIGINT ? -// "serial8 not null" : -// "serial not null"; - get { return "serial not null"; } - } + /// <summary> + /// Retrieve the command used to retrieve the current timestammp from the database. + /// </summary> + public override string CurrentTimestampSelectString + { + get { return "select current from systables where tabid=1"; } + } - /// <summary> - /// Whether this dialect have an Identity clause added to the data type or a - /// completely seperate identity data type - /// </summary> - public override bool HasDataTypeInIdentityColumn - { - get { return false; } - } - } + /// <summary> + /// The name of the database-specific SQL function for retrieving the + /// current timestamp. + /// </summary> + public override string CurrentTimestampSQLFunctionName + { + get { return "current"; } + } + + public override IViolatedConstraintNameExtracter ViolatedConstraintNameExtracter + { + get { return new IfxViolatedConstraintExtracter(); } + } + + /// <summary></summary> + public override string AddColumnString + { + get { return "add"; } + } + + //public override IDataBaseSchema GetDataBaseSchema(DbConnection connection) + //{ + // if (connection.ToString()=="IBM.Data.Informix.IfxConnection") { + // // this driver doesn't have working IfxConnection.GetSchema + // // and probably will never have + // throw new NotSupportedException(); + // } + // if (connection.ToString()=="System.Data.Odbc.OdbcConnection") { + // // waiting for somebody implementing OdbcBaseSchema + // // return new OdbcBaseSchema(connection); + // } + // if (connection.ToString()=="IBM.Data.DB2.IfxConnection") { + // // waiting for somebody implementing DB2BaseSchema + // return new DB2BaseSchema(connection); + // } + // throw new NotSupportedException(); + //} + + /// <summary> Is <tt>FOR UPDATE OF</tt> syntax supported? </summary> + /// <value> True if the database supports <tt>FOR UPDATE OF</tt> syntax; false otherwise. </value> + public override bool ForUpdateOfColumns + { + get { return true; } + } + + /// <summary> + /// Does this dialect support <tt>FOR UPDATE</tt> in conjunction with outer joined rows? + /// </summary> + /// <value> True if outer joined rows can be locked via <tt>FOR UPDATE</tt>. </value> + public override bool SupportsOuterJoinForUpdate + { + get { return false; } + } + + /// <summary> + /// Get the <tt>FOR UPDATE OF column_list</tt> fragment appropriate for this + /// dialect given the aliases of the columns to be write locked. + /// </summary> + /// <param name="aliases">The columns to be write locked. </param> + /// <returns> The appropriate <tt>FOR UPDATE OF column_list</tt> clause string. </returns> + public override string GetForUpdateString(string aliases) + { + return ForUpdateString + " of " + aliases; + } + + /// <summary> Does this dialect support temporary tables? </summary> + public override bool SupportsTemporaryTables + { + get { return true; } + } + + /// <summary> + /// Does the dialect require that temporary table DDL statements occur in + /// isolation from other statements? This would be the case if the creation + /// would cause any current transaction to get committed implicitly. + /// </summary> + /// <returns> see the result matrix above. </returns> + /// <remarks> + /// JDBC defines a standard way to query for this information via the + /// {@link java.sql.DatabaseMetaData#dataDefinitionCausesTransactionCommit()} + /// method. However, that does not distinguish between temporary table + /// DDL and other forms of DDL; MySQL, for example, reports DDL causing a + /// transaction commit via its driver, even though that is not the case for + /// temporary table DDL. + /// <p/> + /// Possible return values and their meanings:<ul> + /// <li>{@link Boolean#TRUE} - Unequivocally, perform the temporary table DDL in isolation.</li> + /// <li>{@link Boolean#FALSE} - Unequivocally, do <b>not</b> perform the temporary table DDL in isolation.</li> + /// <li><i>null</i> - defer to the JDBC driver response in regards to {@link java.sql.DatabaseMetaData#dataDefinitionCausesTransactionCommit()}</li> + /// </ul> + /// </remarks> + public override bool? PerformTemporaryTableDDLInIsolation() + { + return false; + } + + public override int RegisterResultSetOutParameter(DbCommand statement, int position) + { + return position; + } + + public override DbDataReader GetResultSet(DbCommand statement) + { + return statement.ExecuteReader(CommandBehavior.SingleResult); + } + + /// <summary> Does this dialect support a way to retrieve the database's current timestamp value? </summary> + public override bool SupportsCurrentTimestampSelection + { + get { return true; } + } + + public override long TimestampResolutionInTicks + { + get { return 100L; } // Maximum precision (one tick) + } + + public override bool SupportsIdentityColumns + { + get { return true; } + } + + /// <summary> + /// Whether this dialect have an Identity clause added to the data type or a + /// completely seperate identity data type + /// </summary> + public override bool HasDataTypeInIdentityColumn + { + get { return false; } + } + + /// <summary> + /// Get the select command to use to retrieve the last generated IDENTITY + /// value for a particular table + /// </summary> + /// <param name="tableName">The table into which the insert was done </param> + /// <param name="identityColumn">The PK column. </param> + /// <param name="type">The <see cref="DbType"/> type code. </param> + /// <returns> The appropriate select command </returns> + public override string GetIdentitySelectString(string identityColumn, string tableName, DbType type) + { + return type == DbType.Int64 ? + "select dbinfo('serial8') from systables where tabid=1" : + "select dbinfo('sqlca.sqlerrd1') from systables where tabid=1"; + } + + /// <summary> + /// The syntax that returns the identity value of the last insert, if native + /// key generation is supported + /// </summary> + public override string IdentitySelectString + { + // return type==Types.BIGINT ? + // "select dbinfo('serial8') from systables where tabid=1" : + // "select dbinfo('sqlca.sqlerrd1') from systables where tabid=1"; + get { return "select dbinfo('sqlca.sqlerrd1') from systables where tabid=1"; } + } + + /// <summary> + /// The syntax used during DDL to define a column as being an IDENTITY of + /// a particular type. + /// </summary> + /// <param name="type">The <see cref="DbType"/> type code. </param> + /// <returns> The appropriate DDL fragment. </returns> + public override string GetIdentityColumnString(DbType type) + { + return type == DbType.Int64 ? + "serial8 not null" : + "serial not null"; + } + + /// <summary> + /// The keyword used to specify an identity column, if native key generation is supported + /// </summary> + public override string IdentityColumnString + { + get { return "serial not null"; } + } + + /// <summary> + /// Does this dialect support sequences? + /// </summary> + public override bool SupportsSequences + { + get { return false; } + } + + /// <summary> + /// Create a <see cref="JoinFragment"/> strategy responsible + /// for handling this dialect's variations in how joins are handled. + /// </summary> + /// <returns> This dialect's <see cref="JoinFragment"/> strategy. </returns> + public override JoinFragment CreateOuterJoinFragment() + { + return new InformixJoinFragment(); + } + + /// <summary> The SQL literal value to which this database maps boolean values. </summary> + /// <param name="value">The boolean value </param> + /// <returns> The appropriate SQL literal. </returns> + public override string ToBooleanValueString(bool value) + { + return value ? "t" : "f"; + } + /// <summary> + /// Does this Dialect have some kind of <c>LIMIT</c> syntax? + /// </summary> + /// <value>False, unless overridden.</value> + public override bool SupportsLimit + { + // select first * is supported since 7.31 + // but it works with unions since 10.00 + // so it is safer to regard that it is not supported + get { return false; } + } + + /// <summary> + /// Does this Dialect support an offset? + /// </summary> + public override bool SupportsLimitOffset + { + get { return false; } + } + /// <summary> + /// Can parameters be used for a statement containing a LIMIT? + /// </summary> + public override bool SupportsVariableLimit + { + get { return false; } + } + /// <summary> + /// Does the <c>LIMIT</c> clause come at the start of the + /// <c>SELECT</c> statement rather than at the end? + /// </summary> + /// <value>false, unless overridden</value> + public override bool BindLimitParametersFirst + { + get { return true; } + } + + + /// <summary> Apply s limit clause to the query. </summary> + /// <param name="querySqlString">The query to which to apply the limit. </param> + /// <param name="hasOffset">Is the query requesting an offset? </param> + /// <returns> the modified SQL </returns> + /// <remarks> + /// Typically dialects utilize <see cref="SupportsVariableLimit"/> + /// limit caluses when they support limits. Thus, when building the + /// select command we do not actually need to know the limit or the offest + /// since we will just be using placeholders. + /// <p/> + /// Here we do still pass along whether or not an offset was specified + /// so that dialects not supporting offsets can generate proper exceptions. + /// In general, dialects will override one or the other of this method and + /// <see cref="GetLimitString(SqlString,int,int)"/>. + /// </remarks> + public override SqlString GetLimitString(SqlString querySqlString, int offset, int limit) + { + /* + * "SELECT [SKIP x] FIRST y rest-of-sql-statement" + */ + + int insertIndex = GetAfterSelectInsertPoint(querySqlString); + + if (offset > 0) + { + return querySqlString.Insert(insertIndex, " skip " + offset + " first " + limit); + } + + return querySqlString.Insert(insertIndex, " first " + limit); + } + /// <summary> + /// Does this dialect support UNION ALL, which is generally a faster variant of UNION? + /// True if UNION ALL is supported; false otherwise. + /// </summary> + public override bool SupportsUnionAll + { + get { return true; } + } + + public override bool SupportsEmptyInList + { + get { return false; } + } + + public override bool SupportsResultSetPositionQueryMethodsOnForwardOnlyCursor + { + get { return false; } + } + + public override bool DoesRepeatableReadCauseReadersToBlockWriters + { + get { return true; } + } + + public override ISQLExceptionConverter BuildSQLExceptionConverter() + { + // The default SQLExceptionConverter for all dialects is based on SQLState + // since SQLErrorCode is extremely vendor-specific. Specific Dialects + // may override to return whatever is most appropriate for that vendor. + return new SQLStateConverter(ViolatedConstraintNameExtracter); + } + + private static int GetAfterSelectInsertPoint(SqlString text) + { + if (text.StartsWithCaseInsensitive("select")) + { + return 6; + } + + return -1; + } + } + + public class IfxViolatedConstraintExtracter : TemplatedViolatedConstraintNameExtracter + { + /// <summary> + /// Extract the name of the violated constraint from the given DbException. + /// </summary> + /// <param name="sqle">The exception that was the result of the constraint violation.</param> + /// <returns>The extracted constraint name.</returns> + public override string ExtractConstraintName(DbException sqle) + { + string constraintName = null; + + ReflectionBasedSqlStateExtracter extracter = new ReflectionBasedSqlStateExtracter(); + + int errorCode = extracter.ExtractErrorCode(sqle); + if (errorCode == -268) + { + constraintName = ExtractUsingTemplate("Unique constraint (", ") violated.", sqle.Message); + } + else if (errorCode == -691) + { + constraintName = ExtractUsingTemplate("Missing key in referenced table for referential constraint (", ").", sqle.Message); + } + else if (errorCode == -692) + { + constraintName = ExtractUsingTemplate("Key value for constraint (", ") is still being referenced.", sqle.Message); + } + + if (constraintName != null) + { + // strip table-owner because Informix always returns constraint names as "<table-owner>.<constraint-name>" + int i = constraintName.IndexOf('.'); + if (i != -1) + { + constraintName = constraintName.Substring(i + 1); + } + } + return constraintName; + } + }; } \ No newline at end of file Added: trunk/nhibernate/src/NHibernate/Dialect/InformixDialect0940.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/InformixDialect0940.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Dialect/InformixDialect0940.cs 2008-12-03 19:45:12 UTC (rev 3942) @@ -0,0 +1,150 @@ +using System.Data; +using NHibernate.Cfg; +using NHibernate.Dialect.Function; +using NHibernate.SqlCommand; +using System.Data.Common; +using NHibernate.Exceptions; +using NHibernate.Util; +//using NHibernate.Dialect.Schema; +using Environment = NHibernate.Cfg.Environment; + + +namespace NHibernate.Dialect +{ + /// <summary> + /// Summary description for InformixDialect. + /// This dialect is intended to work with IDS version 9.40 + /// </summary> + /// <remarks> + /// The InformixDialect defaults the following configuration properties: + /// <list type="table"> + /// <listheader> + /// <term>ConnectionDriver</term> + /// <description>NHibernate.Driver.OdbcDriver</description> + /// <term>PrepareSql</term> + /// <description>true</description> + /// </listheader> + /// <item> + /// <term>connection.driver_class</term> + /// <description><see cref="NHibernate.Driver.OdbcDriver" /></description> + /// </item> + /// </list> + /// </remarks> + public class InformixDialect0940 : InformixDialect + { + /// <summary></summary> + public InformixDialect0940() + : base() + { + RegisterColumnType(DbType.AnsiString, 2147483647, "CLOB"); + RegisterColumnType(DbType.Binary, 2147483647, "BLOB"); + RegisterColumnType(DbType.Binary, "BLOB"); + RegisterColumnType(DbType.String, 2147483647, "CLOB"); + } + + + /// <summary> Get the select command used retrieve the names of all sequences.</summary> + /// <returns> The select command; or null if sequences are not supported. </returns> + public override string QuerySequencesString + { + get + { + return "select tabname from systables where tabtype='Q'"; + } + } + + /// <summary> + /// Does this dialect support sequences? + /// </summary> + public override bool SupportsSequences + { + get { return true; } + } + + /// <summary> + /// Does this dialect support "pooled" sequences. Not aware of a better + /// name for this. Essentially can we specify the initial and increment values? + /// </summary> + /// <returns> True if such "pooled" sequences are supported; false otherwise. </returns> + public override bool SupportsPooledSequences + { + get { return true; } + } + + /// <summary> + /// Generate the appropriate select statement to to retreive the next value + /// of a sequence. + /// </summary> + /// <param name="sequenceName">the name of the sequence </param> + /// <returns> String The "nextval" select string. </returns> + /// <remarks>This should be a "stand alone" select statement.</remarks> + public override string GetSequenceNextValString(string sequenceName) + { + return "select " + sequenceName + ".nextval from systables"; + } + + public override string GetDropSequenceString(string sequenceName) + { + return "drop sequence " + sequenceName; + } + /// <summary> + /// Generate the select expression fragment that will retrieve the next + /// value of a sequence as part of another (typically DML) statement. + /// </summary> + /// <param name="sequenceName">the name of the sequence </param> + /// <returns> The "nextval" fragment. </returns> + /// <remarks> + /// This differs from <see cref="GetSequenceNextValString"/> in that this + /// should return an expression usable within another statement. + /// </remarks> + public override string GetSelectSequenceNextValString(string sequenceName) + { + return sequenceName + ".nextval"; + } + public override string GetCreateSequenceString(string sequenceName) + { + return "create sequence " + sequenceName; + // + + //" INCREMENT BY 1 START WITH 1 MINVALUE 1 NOCYCLE CACHE 20 NOORDER"; + + } + + // in .NET overloaded version cannot be overriden (in Java allowed) + //protected override string GetCreateSequenceString(string sequenceName, int initialValue, int incrementSize) + //{ + // return "create sequence " + sequenceName + + // " INCREMENT BY " + incrementSize.ToString() + + // " START WITH " + initialValue.ToString() + + // " MINVALUE 1 NOCYCLE CACHE 20 NOORDER"; + //} + + /// <summary> + /// Create a <see cref="JoinFragment"/> strategy responsible + /// for handling this dialect's variations in how joins are handled. + /// </summary> + /// <returns> This dialect's <see cref="JoinFragment"/> strategy. </returns> + public override JoinFragment CreateOuterJoinFragment() + { + // ANSI join exist from 9.21 but CROSS, RIGHT and FULL were introduced in 9.40; + return new ANSIJoinFragment(); + } + + /// <summary> + /// Does this Dialect have some kind of <c>LIMIT</c> syntax? + /// </summary> + /// <value>False, unless overridden.</value> + public override bool SupportsLimit + { + get { return false; } + } + + /// <summary> + /// Does this Dialect support an offset? + /// </summary> + public override bool SupportsLimitOffset + { + get { return false; } + } + + }; +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate/Dialect/InformixDialect1000.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/InformixDialect1000.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Dialect/InformixDialect1000.cs 2008-12-03 19:45:12 UTC (rev 3942) @@ -0,0 +1,58 @@ +using System.Data; +using NHibernate.Cfg; +using NHibernate.Dialect.Function; +using NHibernate.SqlCommand; +using System.Data.Common; +using NHibernate.Exceptions; +using NHibernate.Util; +//using NHibernate.Dialect.Schema; +using Environment = NHibernate.Cfg.Environment; + + +namespace NHibernate.Dialect +{ + /// <summary> + /// Summary description for InformixDialect. + /// This dialect is intended to work with IDS version 10.00 + /// </summary> + /// <remarks> + /// The InformixDialect defaults the following configuration properties: + /// <list type="table"> + /// <listheader> + /// <term>ConnectionDriver</term> + /// <description>NHibernate.Driver.OdbcDriver</description> + /// <term>PrepareSql</term> + /// <description>true</description> + /// </listheader> + /// <item> + /// <term>connection.driver_class</term> + /// <description><see cref="NHibernate.Driver.OdbcDriver" /></description> + /// </item> + /// </list> + /// </remarks> + public class InformixDialect1000 : InformixDialect0940 + { + /// <summary></summary> + public InformixDialect1000() + : base() + { + } + + /// <summary> + /// Does this Dialect have some kind of <c>LIMIT</c> syntax? + /// </summary> + /// <value>False, unless overridden.</value> + public override bool SupportsLimit + { + get { return true; } + } + + /// <summary> + /// Does this Dialect support an offset? + /// </summary> + public override bool SupportsLimitOffset + { + get { return true; } + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate/Exceptions/ReflectionBasedSqlStateExtracter.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Exceptions/ReflectionBasedSqlStateExtracter.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Exceptions/ReflectionBasedSqlStateExtracter.cs 2008-12-03 19:45:12 UTC (rev 3942) @@ -0,0 +1,64 @@ +using System.Reflection; +using System.Collections; +using System.Data.Common; + +namespace NHibernate.Exceptions +{ + class ReflectionBasedSqlStateExtracter: SqlStateExtracter + { + + /* OdbcException, OleDbException, IfxException, Db2Exception, and possible others + * have Errors collection which contains fields: NativeError and SQLState + * These fields can be extracted using reflection + */ + public override int ExtractSingleErrorCode(DbException sqle) + { + System.Type type; + PropertyInfo pi; + int nativeError; + + type = sqle.GetType(); + pi = type.GetProperty("Errors"); + if (pi == null) // there is no Errors property + { + return 0; + } + nativeError = 0; + foreach (object o in (pi.GetValue(sqle, null) as IEnumerable)) + { + pi = o.GetType().GetProperty("NativeError"); + if (pi == null) + return 0; + nativeError = (int)pi.GetValue(o, null); + if (nativeError != 0) + break; + } + return nativeError; + } + + public override string ExtractSingleSqlState(DbException sqle) + { + System.Type type; + PropertyInfo pi; + string sqlState; + + type = sqle.GetType(); + pi = type.GetProperty("Errors"); + if (pi == null) // there is no Errors property + { + return null; + } + sqlState = ""; + foreach (object o in (pi.GetValue(sqle, null) as IEnumerable)) + { + pi = o.GetType().GetProperty("SQLState"); + if (pi == null) + return null; + sqlState = (string)pi.GetValue(o, null); + if (sqlState.Length != 0) + break; + } + return sqlState; + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate/Exceptions/SqlStateExtracter.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Exceptions/SqlStateExtracter.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Exceptions/SqlStateExtracter.cs 2008-12-03 19:45:12 UTC (rev 3942) @@ -0,0 +1,51 @@ +using System; +using System.Data.Common; + +namespace NHibernate.Exceptions +{ + public abstract class SqlStateExtracter + { + /* Many drivers provide both SqlState and NativeError in the Exception + * Some of them, like OdbcException, have fields SQLState, NativeError + * Some of them contain it in Data field, like PsqlException + * Some of them have only text message + */ + + public int ExtractErrorCode(DbException sqle) + { + int errorCode; + Exception nested; + errorCode = ExtractSingleErrorCode(sqle); + nested = sqle.InnerException; + while (errorCode == 0 && nested != null) + { + if (nested is DbException) + { + errorCode = ExtractSingleErrorCode(sqle); + } + nested = sqle.InnerException; + } + return errorCode; + } + + public string ExtractSqlState(DbException sqle) + { + string sqlState; + Exception nested; + sqlState = ExtractSingleSqlState(sqle); + nested = sqle.InnerException; + while (sqlState.Length == 0 && nested != null) + { + if (nested is DbException) + { + sqlState = ExtractSingleSqlState(sqle); + } + nested = sqle.InnerException; + } + return sqlState; + } + + public abstract int ExtractSingleErrorCode(DbException sqle); + public abstract string ExtractSingleSqlState(DbException sqle); + } +} Added: trunk/nhibernate/src/NHibernate/Exceptions/TemplatedViolatedConstraintNameExtracter.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Exceptions/TemplatedViolatedConstraintNameExtracter.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Exceptions/TemplatedViolatedConstraintNameExtracter.cs 2008-12-03 19:45:12 UTC (rev 3942) @@ -0,0 +1,44 @@ +using System.Data.Common; + +namespace NHibernate.Exceptions +{ + /// <summary> + /// Knows how to extract a violated constraint name from an error message based on the + /// fact that the constraint name is templated within the message. + /// </summary> + public abstract class TemplatedViolatedConstraintNameExtracter : IViolatedConstraintNameExtracter + { + + /// <summary> + /// Extracts the constraint name based on a template (i.e., <i>templateStart</i><b>constraintName</b><i>templateEnd</i>). + /// </summary> + /// <param name="templateStart">The pattern denoting the start of the constraint name within the message.</param> + /// <param name="templateEnd">The pattern denoting the end of the constraint name within the message.</param> + /// <param name="message">The templated error message containing the constraint name.</param> + /// <returns>The found constraint name, or null.</returns> + protected string ExtractUsingTemplate(string templateStart, string templateEnd, string message) + { + int templateStartPosition = message.IndexOf(templateStart); + if (templateStartPosition < 0) + { + return null; + } + + int start = templateStartPosition + templateStart.Length; + int end = message.IndexOf(templateEnd, start); + if (end < 0) + { + end = message.Length; + } + + return message.Substring(start, end); + } + + /// <summary> + /// Extract the name of the violated constraint from the given SQLException. + /// </summary> + /// <param name="sqle">The exception that was the result of the constraint violation. </param> + /// <returns> The extracted constraint name. </returns> + public abstract string ExtractConstraintName(DbException sqle); + } +} Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-11-30 20:32:19 UTC (rev 3941) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-12-03 19:45:12 UTC (rev 3942) @@ -443,11 +443,16 @@ <Compile Include="Bytecode\HibernateByteCodeException.cs" /> <Compile Include="Bytecode\ProxyFactoryFactoryNotConfiguredException.cs" /> <Compile Include="Bytecode\UnableToLoadProxyFactoryFactoryException.cs" /> + <Compile Include="Dialect\InformixDialect0940.cs" /> + <Compile Include="Dialect\InformixDialect1000.cs" /> <Compile Include="Dialect\Schema\SQLiteMetaData.cs" /> <Compile Include="Dialect\Schema\SybaseAnywhereMetaData.cs" /> <Compile Include="Dialect\SybaseASA10Dialect.cs" /> <Compile Include="Dialect\SybaseASA9Dialect.cs" /> <Compile Include="Driver\IfxDriver.cs" /> + <Compile Include="Exceptions\ReflectionBasedSqlStateExtracter.cs" /> + <Compile Include="Exceptions\SqlStateExtracter.cs" /> + <Compile Include="Exceptions\TemplatedViolatedConstraintNameExtracter.cs" /> <Compile Include="Id\SelectGenerator.cs" /> <Compile Include="Properties\BackFieldStrategy.cs" /> <Compile Include="Bytecode\CodeDom\BytecodeProviderImpl.cs" /> @@ -836,6 +841,7 @@ <Compile Include="Proxy\Poco\BasicLazyInitializer.cs" /> <Compile Include="QueryParameterException.cs" /> <Compile Include="SessionException.cs" /> + <Compile Include="SqlCommand\InformixJoinFragment.cs" /> <Compile Include="SqlCommand\SubselectClauseExtractor.cs" /> <Compile Include="Engine\SubselectFetch.cs" /> <Compile Include="Criterion\DetachedCriteria.cs" /> Added: trunk/nhibernate/src/NHibernate/SqlCommand/InformixJoinFragment.cs =================================================================== --- trunk/nhibernate/src/NHibernate/SqlCommand/InformixJoinFragment.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/SqlCommand/InformixJoinFragment.cs 2008-12-03 19:45:12 UTC (rev 3942) @@ -0,0 +1,113 @@ +using System; +using System.Text; +using Iesi.Collections; +using NHibernate.Util; + +namespace NHibernate.SqlCommand +{ + /// <summary> + /// An Informix-style (theta) Join + /// </summary> + public class InformixJoinFragment : JoinFragment + { + private SqlStringBuilder afterFrom = new SqlStringBuilder(); + private SqlStringBuilder afterWhere = new SqlStringBuilder(); + + public override void AddJoin(string tableName, string alias, string[] fkColumns, string[] pkColumns, JoinType joinType) + { + string joinString; + switch (joinType) + { + case JoinType.InnerJoin: + AddCrossJoin(tableName, alias); + break; + case JoinType.LeftOuterJoin: + afterFrom.Add(StringHelper.CommaSpace) + .Add("outer ") + .Add(tableName) + .Add(" ") + .Add(alias); + break; + case JoinType.RightOuterJoin: + int i = GetPrevTableInsertPoint(afterFrom.ToSqlString()); + afterFrom.Insert(i, "outer "); + break; + case JoinType.FullJoin: + throw new NotSupportedException("join type not supported by Informix"); + default: + throw new AssertionFailure("undefined join type"); + } + + for (int j = 0; j < fkColumns.Length; j++) + { + //HasThetaJoins = true; + afterWhere.Add(" and " + fkColumns[j]); + afterWhere.Add("=" + alias + StringHelper.Dot + pkColumns[j]); + } + } + + public override void AddJoin(string tableName, string alias, string[] fkColumns, string[] pkColumns, JoinType joinType, + string on) + { + //arbitrary on clause ignored!! + AddJoin(tableName, alias, fkColumns, pkColumns, joinType); + AddCondition(on); + } + + public override SqlString ToFromFragmentString + { + get { return afterFrom.ToSqlString(); } + } + + public override SqlString ToWhereFragmentString + { + get { return afterWhere.ToSqlString(); } + } + + public override void AddJoins(SqlString fromFragment, SqlString whereFragment) + { + afterFrom.Add(fromFragment); + afterWhere.Add(whereFragment); + } + + public override void AddCrossJoin(string tableName, string alias) + { + afterFrom.Add(StringHelper.CommaSpace) + .Add(tableName) + .Add(" ") + .Add(alias); + } + + public override bool AddCondition(string condition) + { + return AddCondition(afterWhere, condition); + } + + public override bool AddCondition(SqlString condition) + { + return AddCondition(afterWhere, condition); + } + + public override void AddFromFragmentString(SqlString fromFragmentString) + { + afterFrom.Add(fromFragmentString); + } + + private static int GetPrevTableInsertPoint(SqlString text) + { + int i, j; + + i = text.LastIndexOfCaseInsensitive("from"); + j = text.LastIndexOfCaseInsensitive(","); + if (i == -1 && j == -1) + { + return -1; + } + if (j > i) + { + return j + 1; + } + return i + 5; + } + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |