From: <fab...@us...> - 2010-07-28 16:51:37
|
Revision: 5065 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5065&view=rev Author: fabiomaulo Date: 2010-07-28 16:51:31 +0000 (Wed, 28 Jul 2010) Log Message: ----------- Minor (moved class in its own file) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs trunk/nhibernate/src/NHibernate/NHibernate.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate/Linq/LinqExtensionMethodAttribute.cs Modified: trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs 2010-07-27 20:19:40 UTC (rev 5064) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs 2010-07-28 16:51:31 UTC (rev 5065) @@ -7,23 +7,6 @@ using NHibernate.Hql.Ast; using NHibernate.Linq.Visitors; -namespace NHibernate.Linq -{ - public class LinqExtensionMethodAttribute : Attribute - { - public string Name { get; private set; } - - public LinqExtensionMethodAttribute() - { - } - - public LinqExtensionMethodAttribute(string name) - { - Name = name; - } - } -} - namespace NHibernate.Linq.Functions { public class FunctionRegistry Added: trunk/nhibernate/src/NHibernate/Linq/LinqExtensionMethodAttribute.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/LinqExtensionMethodAttribute.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Linq/LinqExtensionMethodAttribute.cs 2010-07-28 16:51:31 UTC (rev 5065) @@ -0,0 +1,18 @@ +using System; + +namespace NHibernate.Linq +{ + public class LinqExtensionMethodAttribute: Attribute + { + public LinqExtensionMethodAttribute() + { + } + + public LinqExtensionMethodAttribute(string name) + { + Name = name; + } + + public string Name { get; private set; } + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-07-27 20:19:40 UTC (rev 5064) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-07-28 16:51:31 UTC (rev 5065) @@ -654,6 +654,7 @@ <Compile Include="Impl\SessionIdLoggingContext.cs" /> <Compile Include="Linq\Expressions\AggregateExpressionNode.cs" /> <Compile Include="Linq\EagerFetchingExtensionMethods.cs" /> + <Compile Include="Linq\LinqExtensionMethodAttribute.cs" /> <Compile Include="Linq\TypeHelperExtensionMethods.cs" /> <Compile Include="Linq\Visitors\NameUnNamedParameters.cs" /> <Compile Include="Linq\NhRelinqQueryParser.cs" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2010-07-28 19:24:01
|
Revision: 5067 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5067&view=rev Author: fabiomaulo Date: 2010-07-28 19:23:54 +0000 (Wed, 28 Jul 2010) Log Message: ----------- Refactoring (extract interface) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs trunk/nhibernate/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs trunk/nhibernate/src/NHibernate/Linq/Visitors/SelectClauseVisitor.cs trunk/nhibernate/src/NHibernate/NHibernate.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate/Linq/Functions/ILinqToHqlGeneratorsRegistry.cs Modified: trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs 2010-07-28 17:48:04 UTC (rev 5066) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs 2010-07-28 19:23:54 UTC (rev 5067) @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Linq.Expressions; @@ -9,8 +8,8 @@ namespace NHibernate.Linq.Functions { - public class FunctionRegistry - { + public class FunctionRegistry : ILinqToHqlGeneratorsRegistry + { public static readonly FunctionRegistry Instance = new FunctionRegistry(); private readonly Dictionary<MethodInfo, IHqlGeneratorForMethod> registeredMethods = new Dictionary<MethodInfo, IHqlGeneratorForMethod>(); @@ -26,36 +25,6 @@ Register(new ICollectionGenerator()); } - public IHqlGeneratorForMethod GetGenerator(MethodInfo method) - { - IHqlGeneratorForMethod methodGenerator; - - if (!TryGetMethodGenerator(method, out methodGenerator)) - { - throw new NotSupportedException(method.ToString()); - } - - return methodGenerator; - } - - public bool TryGetMethodGenerator(MethodInfo method, out IHqlGeneratorForMethod methodGenerator) - { - if (method.IsGenericMethod) - { - method = method.GetGenericMethodDefinition(); - } - - if (GetRegisteredMethodGenerator(method, out methodGenerator)) return true; - - // No method generator registered. Look to see if it's a standard LinqExtensionMethod - if (GetStandardLinqExtensionMethodGenerator(method, out methodGenerator)) return true; - - // Not that either. Let's query each type generator to see if it can handle it - if (GetMethodGeneratorForType(method, out methodGenerator)) return true; - - return false; - } - private bool GetMethodGeneratorForType(MethodInfo method, out IHqlGeneratorForMethod methodGenerator) { methodGenerator = null; @@ -105,7 +74,30 @@ return null; } - public void RegisterGenerator(MethodInfo method, IHqlGeneratorForMethod generator) + public bool TryGetGenerator(MethodInfo method, out IHqlGeneratorForMethod generator) + { + if (method.IsGenericMethod) + { + method = method.GetGenericMethodDefinition(); + } + + if (GetRegisteredMethodGenerator(method, out generator)) return true; + + // No method generator registered. Look to see if it's a standard LinqExtensionMethod + if (GetStandardLinqExtensionMethodGenerator(method, out generator)) return true; + + // Not that either. Let's query each type generator to see if it can handle it + if (GetMethodGeneratorForType(method, out generator)) return true; + + return false; + } + + public bool TryGetGenerator(MemberInfo property, out IHqlGeneratorForProperty generator) + { + return registeredProperties.TryGetValue(property, out generator); + } + + public void RegisterGenerator(MethodInfo method, IHqlGeneratorForMethod generator) { registeredMethods.Add(method, generator); } Added: trunk/nhibernate/src/NHibernate/Linq/Functions/ILinqToHqlGeneratorsRegistry.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/ILinqToHqlGeneratorsRegistry.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/ILinqToHqlGeneratorsRegistry.cs 2010-07-28 19:23:54 UTC (rev 5067) @@ -0,0 +1,12 @@ +using System.Reflection; + +namespace NHibernate.Linq.Functions +{ + public interface ILinqToHqlGeneratorsRegistry + { + bool TryGetGenerator(MethodInfo method, out IHqlGeneratorForMethod generator); + bool TryGetGenerator(MemberInfo property, out IHqlGeneratorForProperty generator); + void RegisterGenerator(MethodInfo method, IHqlGeneratorForMethod generator); + void RegisterGenerator(MemberInfo property, IHqlGeneratorForProperty generator); + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs 2010-07-28 17:48:04 UTC (rev 5066) +++ trunk/nhibernate/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs 2010-07-28 19:23:54 UTC (rev 5067) @@ -351,9 +351,10 @@ } // Look for "special" properties (DateTime.Month etc) - var generator = FunctionRegistry.GetGenerator(expression.Member); + IHqlGeneratorForProperty generator; + generator = FunctionRegistry.GetGenerator(expression.Member); - if (generator != null) + if (generator != null) { return generator.BuildHql(expression.Member, expression.Expression, _hqlTreeBuilder, this); } @@ -394,9 +395,15 @@ protected HqlTreeNode VisitMethodCallExpression(MethodCallExpression expression) { - var generator = FunctionRegistry.GetGenerator(expression.Method); + IHqlGeneratorForMethod generator; - return generator.BuildHql(expression.Method, expression.Object, expression.Arguments, _hqlTreeBuilder, this); + var method = expression.Method; + if (!FunctionRegistry.TryGetGenerator(method, out generator)) + { + throw new NotSupportedException(method.ToString()); + } + + return generator.BuildHql(method, expression.Object, expression.Arguments, _hqlTreeBuilder, this); } protected HqlTreeNode VisitLambdaExpression(LambdaExpression expression) Modified: trunk/nhibernate/src/NHibernate/Linq/Visitors/SelectClauseVisitor.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Visitors/SelectClauseVisitor.cs 2010-07-28 17:48:04 UTC (rev 5066) +++ trunk/nhibernate/src/NHibernate/Linq/Visitors/SelectClauseVisitor.cs 2010-07-28 19:23:54 UTC (rev 5067) @@ -82,7 +82,7 @@ { // Depends if it's in the function registry IHqlGeneratorForMethod methodGenerator; - if (!FunctionRegistry.TryGetMethodGenerator(((MethodCallExpression) expression).Method, out methodGenerator)) + if (!FunctionRegistry.TryGetGenerator(((MethodCallExpression) expression).Method, out methodGenerator)) { return false; } Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-07-28 17:48:04 UTC (rev 5066) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-07-28 19:23:54 UTC (rev 5067) @@ -654,6 +654,7 @@ <Compile Include="Impl\SessionIdLoggingContext.cs" /> <Compile Include="Linq\Expressions\AggregateExpressionNode.cs" /> <Compile Include="Linq\EagerFetchingExtensionMethods.cs" /> + <Compile Include="Linq\Functions\ILinqToHqlGeneratorsRegistry.cs" /> <Compile Include="Linq\LinqExtensionMethodAttribute.cs" /> <Compile Include="Linq\TypeHelperExtensionMethods.cs" /> <Compile Include="Linq\Visitors\NameUnNamedParameters.cs" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2010-07-28 20:11:37
|
Revision: 5070 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5070&view=rev Author: fabiomaulo Date: 2010-07-28 20:11:31 +0000 (Wed, 28 Jul 2010) Log Message: ----------- Refactoring (removed some 'static' and pushed out the responsibility of creation of ILinqToHqlGeneratorsRegistry) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Cfg/Settings.cs trunk/nhibernate/src/NHibernate/Cfg/SettingsFactory.cs trunk/nhibernate/src/NHibernate/IQueryExpression.cs trunk/nhibernate/src/NHibernate/Impl/ExpressionQueryImpl.cs trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs trunk/nhibernate/src/NHibernate/Linq/NhLinqExpression.cs trunk/nhibernate/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs trunk/nhibernate/src/NHibernate/Linq/Visitors/SelectClauseVisitor.cs trunk/nhibernate/src/NHibernate/Linq/Visitors/VisitorParameters.cs Modified: trunk/nhibernate/src/NHibernate/Cfg/Settings.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/Settings.cs 2010-07-28 19:45:24 UTC (rev 5069) +++ trunk/nhibernate/src/NHibernate/Cfg/Settings.cs 2010-07-28 20:11:31 UTC (rev 5070) @@ -6,6 +6,7 @@ using NHibernate.Connection; using NHibernate.Exceptions; using NHibernate.Hql; +using NHibernate.Linq.Functions; using NHibernate.Transaction; namespace NHibernate.Cfg @@ -119,6 +120,11 @@ public bool IsOuterJoinFetchEnabled { get; internal set; } + /// <summary> + /// Get the registry to provide Hql-Generators for known properties/methods. + /// </summary> + public ILinqToHqlGeneratorsRegistry LinqToHqlGeneratorsRegistry { get; internal set; } + #endregion } } \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Cfg/SettingsFactory.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/SettingsFactory.cs 2010-07-28 19:45:24 UTC (rev 5069) +++ trunk/nhibernate/src/NHibernate/Cfg/SettingsFactory.cs 2010-07-28 20:11:31 UTC (rev 5070) @@ -10,6 +10,7 @@ using NHibernate.Dialect; using NHibernate.Exceptions; using NHibernate.Hql; +using NHibernate.Linq.Functions; using NHibernate.Transaction; using NHibernate.Util; @@ -51,6 +52,8 @@ } settings.Dialect = dialect; + settings.LinqToHqlGeneratorsRegistry = new FunctionRegistry(); + #region SQL Exception converter ISQLExceptionConverter sqlExceptionConverter; Modified: trunk/nhibernate/src/NHibernate/IQueryExpression.cs =================================================================== --- trunk/nhibernate/src/NHibernate/IQueryExpression.cs 2010-07-28 19:45:24 UTC (rev 5069) +++ trunk/nhibernate/src/NHibernate/IQueryExpression.cs 2010-07-28 20:11:31 UTC (rev 5070) @@ -1,13 +1,13 @@ using System.Collections.Generic; +using NHibernate.Engine; using NHibernate.Engine.Query; using NHibernate.Hql.Ast.ANTLR.Tree; -using NHibernate.Impl; namespace NHibernate { public interface IQueryExpression { - IASTNode Translate(ISessionFactory sessionFactory); + IASTNode Translate(ISessionFactoryImplementor sessionFactory); string Key { get; } System.Type Type { get; } IList<NamedParameterDescriptor> ParameterDescriptors { get; } Modified: trunk/nhibernate/src/NHibernate/Impl/ExpressionQueryImpl.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Impl/ExpressionQueryImpl.cs 2010-07-28 19:45:24 UTC (rev 5069) +++ trunk/nhibernate/src/NHibernate/Impl/ExpressionQueryImpl.cs 2010-07-28 20:11:31 UTC (rev 5070) @@ -150,7 +150,7 @@ ParameterDescriptors = queryExpression.ParameterDescriptors; } - public IASTNode Translate(ISessionFactory sessionFactory) + public IASTNode Translate(ISessionFactoryImplementor sessionFactory) { return _tree; } Modified: trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs 2010-07-28 19:45:24 UTC (rev 5069) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs 2010-07-28 20:11:31 UTC (rev 5070) @@ -10,13 +10,11 @@ { public class FunctionRegistry : ILinqToHqlGeneratorsRegistry { - public static readonly ILinqToHqlGeneratorsRegistry Instance = new FunctionRegistry(); - private readonly Dictionary<MethodInfo, IHqlGeneratorForMethod> registeredMethods = new Dictionary<MethodInfo, IHqlGeneratorForMethod>(); private readonly Dictionary<MemberInfo, IHqlGeneratorForProperty> registeredProperties = new Dictionary<MemberInfo, IHqlGeneratorForProperty>(); private readonly List<IHqlGeneratorForType> typeGenerators = new List<IHqlGeneratorForType>(); - private FunctionRegistry() + public FunctionRegistry() { // TODO - could use reflection here Register(new QueryableGenerator()); Modified: trunk/nhibernate/src/NHibernate/Linq/NhLinqExpression.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/NhLinqExpression.cs 2010-07-28 19:45:24 UTC (rev 5069) +++ trunk/nhibernate/src/NHibernate/Linq/NhLinqExpression.cs 2010-07-28 20:11:31 UTC (rev 5070) @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; +using NHibernate.Engine; using NHibernate.Engine.Query; using NHibernate.Hql.Ast.ANTLR.Tree; using NHibernate.Linq.Visitors; @@ -54,7 +55,7 @@ } } - public IASTNode Translate(ISessionFactory sessionFactory) + public IASTNode Translate(ISessionFactoryImplementor sessionFactory) { //if (_astNode == null) { Modified: trunk/nhibernate/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs 2010-07-28 19:45:24 UTC (rev 5069) +++ trunk/nhibernate/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs 2010-07-28 20:11:31 UTC (rev 5070) @@ -23,7 +23,7 @@ public HqlGeneratorExpressionTreeVisitor(VisitorParameters parameters) { - functionRegistry = FunctionRegistry.Instance; + functionRegistry = parameters.SessionFactory.Settings.LinqToHqlGeneratorsRegistry; _parameters = parameters; _hqlTreeBuilder = new HqlTreeBuilder(); } Modified: trunk/nhibernate/src/NHibernate/Linq/Visitors/SelectClauseVisitor.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Visitors/SelectClauseVisitor.cs 2010-07-28 19:45:24 UTC (rev 5069) +++ trunk/nhibernate/src/NHibernate/Linq/Visitors/SelectClauseVisitor.cs 2010-07-28 20:11:31 UTC (rev 5070) @@ -20,7 +20,7 @@ public SelectClauseVisitor(System.Type inputType, VisitorParameters parameters) { - functionRegistry = FunctionRegistry.Instance; + functionRegistry = parameters.SessionFactory.Settings.LinqToHqlGeneratorsRegistry; _inputParameter = Expression.Parameter(inputType, "input"); _parameters = parameters; } Modified: trunk/nhibernate/src/NHibernate/Linq/Visitors/VisitorParameters.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Visitors/VisitorParameters.cs 2010-07-28 19:45:24 UTC (rev 5069) +++ trunk/nhibernate/src/NHibernate/Linq/Visitors/VisitorParameters.cs 2010-07-28 20:11:31 UTC (rev 5070) @@ -1,16 +1,17 @@ using System.Collections.Generic; using System.Linq.Expressions; +using NHibernate.Engine; using NHibernate.Engine.Query; namespace NHibernate.Linq.Visitors { public class VisitorParameters { - public ISessionFactory SessionFactory { get; private set; } + public ISessionFactoryImplementor SessionFactory { get; private set; } public IDictionary<ConstantExpression, NamedParameter> ConstantToParameterMap { get; private set; } public List<NamedParameterDescriptor> RequiredHqlParameters { get; private set; } - public VisitorParameters(ISessionFactory sessionFactory, IDictionary<ConstantExpression, NamedParameter> constantToParameterMap, List<NamedParameterDescriptor> requiredHqlParameters) + public VisitorParameters(ISessionFactoryImplementor sessionFactory, IDictionary<ConstantExpression, NamedParameter> constantToParameterMap, List<NamedParameterDescriptor> requiredHqlParameters) { SessionFactory = sessionFactory; ConstantToParameterMap = constantToParameterMap; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2010-07-28 20:40:46
|
Revision: 5071 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5071&view=rev Author: fabiomaulo Date: 2010-07-28 20:40:40 +0000 (Wed, 28 Jul 2010) Log Message: ----------- Added LinqToHqlGeneratorsRegistryFactory to create Generators Registry from configuration properties and through ObjectsFactory Modified Paths: -------------- 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/Linq/Functions/LinqToHqlGeneratorsRegistryFactory.cs trunk/nhibernate/src/NHibernate.Test/Linq/LinqToHqlGeneratorsRegistryFactoryTest.cs Modified: trunk/nhibernate/src/NHibernate/Cfg/Environment.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/Environment.cs 2010-07-28 20:11:31 UTC (rev 5070) +++ trunk/nhibernate/src/NHibernate/Cfg/Environment.cs 2010-07-28 20:40:40 UTC (rev 5071) @@ -159,6 +159,8 @@ public const string DefaultBatchFetchSize = "default_batch_fetch_size"; public const string CollectionTypeFactoryClass = "collectiontype.factory_class"; + + public const string LinqToHqlGeneratorsRegistry = "linqtohql.generatorsregistry"; private static readonly Dictionary<string, string> GlobalProperties; Added: trunk/nhibernate/src/NHibernate/Linq/Functions/LinqToHqlGeneratorsRegistryFactory.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/LinqToHqlGeneratorsRegistryFactory.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/LinqToHqlGeneratorsRegistryFactory.cs 2010-07-28 20:40:40 UTC (rev 5071) @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using log4net; +using NHibernate.Util; +using Environment = NHibernate.Cfg.Environment; + +namespace NHibernate.Linq.Functions +{ + public sealed class LinqToHqlGeneratorsRegistryFactory + { + private static readonly ILog log = LogManager.GetLogger(typeof (LinqToHqlGeneratorsRegistryFactory)); + + public static ILinqToHqlGeneratorsRegistry CreateGeneratorsRegistry(IDictionary<string, string> properties) + { + string registry; + if (properties.TryGetValue(Environment.LinqToHqlGeneratorsRegistry, out registry)) + { + try + { + log.Info("Initializing LinqToHqlGeneratorsRegistry: " + registry); + return (ILinqToHqlGeneratorsRegistry) Environment.BytecodeProvider.ObjectsFactory.CreateInstance(ReflectHelper.ClassForName(registry)); + } + catch (Exception e) + { + log.Fatal("Could not instantiate LinqToHqlGeneratorsRegistry", e); + throw new HibernateException("Could not instantiate LinqToHqlGeneratorsRegistry: " + registry, e); + } + } + return new FunctionRegistry(); + } + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-07-28 20:11:31 UTC (rev 5070) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-07-28 20:40:40 UTC (rev 5071) @@ -655,6 +655,7 @@ <Compile Include="Linq\Expressions\AggregateExpressionNode.cs" /> <Compile Include="Linq\EagerFetchingExtensionMethods.cs" /> <Compile Include="Linq\Functions\ILinqToHqlGeneratorsRegistry.cs" /> + <Compile Include="Linq\Functions\LinqToHqlGeneratorsRegistryFactory.cs" /> <Compile Include="Linq\LinqExtensionMethodAttribute.cs" /> <Compile Include="Linq\TypeHelperExtensionMethods.cs" /> <Compile Include="Linq\Visitors\NameUnNamedParameters.cs" /> Added: trunk/nhibernate/src/NHibernate.Test/Linq/LinqToHqlGeneratorsRegistryFactoryTest.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Linq/LinqToHqlGeneratorsRegistryFactoryTest.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/Linq/LinqToHqlGeneratorsRegistryFactoryTest.cs 2010-07-28 20:40:40 UTC (rev 5071) @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using NHibernate.Linq.Functions; +using NUnit.Framework; +using SharpTestsEx; +using Environment = NHibernate.Cfg.Environment; + +namespace NHibernate.Test.Linq +{ + public class LinqToHqlGeneratorsRegistryFactoryTest + { + [Test] + public void WhenNotDefinedThenReturnDefaultRegistry() + { + var registry = LinqToHqlGeneratorsRegistryFactory.CreateGeneratorsRegistry(new Dictionary<string, string>()); + registry.Should().Not.Be.Null(); + registry.Should().Be.OfType<FunctionRegistry>(); + } + + [Test] + public void WhenDefinedThenReturnCustomtRegistry() + { + var properties = new Dictionary<string, string> { { Environment.LinqToHqlGeneratorsRegistry, typeof(MyLinqToHqlGeneratorsRegistry).AssemblyQualifiedName } }; + var registry = LinqToHqlGeneratorsRegistryFactory.CreateGeneratorsRegistry(properties); + registry.Should().Not.Be.Null(); + registry.Should().Be.OfType<MyLinqToHqlGeneratorsRegistry>(); + } + + private class MyLinqToHqlGeneratorsRegistry : ILinqToHqlGeneratorsRegistry + { + public bool TryGetGenerator(MethodInfo method, out IHqlGeneratorForMethod generator) + { + throw new NotImplementedException(); + } + + public bool TryGetGenerator(MemberInfo property, out IHqlGeneratorForProperty generator) + { + throw new NotImplementedException(); + } + + public void RegisterGenerator(MethodInfo method, IHqlGeneratorForMethod generator) + { + throw new NotImplementedException(); + } + + public void RegisterGenerator(MemberInfo property, IHqlGeneratorForProperty generator) + { + throw new NotImplementedException(); + } + } + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-07-28 20:11:31 UTC (rev 5070) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-07-28 20:40:40 UTC (rev 5071) @@ -425,6 +425,7 @@ <Compile Include="Linq\LinqQuerySamples.cs" /> <Compile Include="Linq\LinqReadonlyTestsContext.cs" /> <Compile Include="Linq\LinqTestCase.cs" /> + <Compile Include="Linq\LinqToHqlGeneratorsRegistryFactoryTest.cs" /> <Compile Include="Linq\MethodCallTests.cs" /> <Compile Include="Linq\MiscellaneousTextFixture.cs" /> <Compile Include="Linq\NorthwindDbCreator.cs" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <ric...@us...> - 2010-07-28 20:57:52
|
Revision: 5073 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5073&view=rev Author: ricbrown Date: 2010-07-28 20:57:45 +0000 (Wed, 28 Jul 2010) Log Message: ----------- Fix NH-2257 (Parameter ordering not working when driver does not support Named Parameters) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/AdoNet/AbstractBatcher.cs trunk/nhibernate/src/NHibernate/Driver/DriverBase.cs trunk/nhibernate/src/NHibernate/Driver/IDriver.cs trunk/nhibernate/src/NHibernate/Engine/IBatcher.cs trunk/nhibernate/src/NHibernate/Loader/Loader.cs trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2257/ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2257/Domain.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2257/Fixture.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2257/Mappings.hbm.xml Modified: trunk/nhibernate/src/NHibernate/AdoNet/AbstractBatcher.cs =================================================================== --- trunk/nhibernate/src/NHibernate/AdoNet/AbstractBatcher.cs 2010-07-28 20:44:14 UTC (rev 5072) +++ trunk/nhibernate/src/NHibernate/AdoNet/AbstractBatcher.cs 2010-07-28 20:57:45 UTC (rev 5073) @@ -222,6 +222,11 @@ } } + public void ExpandQueryParameters(IDbCommand cmd, SqlString sqlString) + { + Driver.ExpandQueryParameters(cmd, sqlString); + } + public IDataReader ExecuteReader(IDbCommand cmd) { CheckReaders(); Modified: trunk/nhibernate/src/NHibernate/Driver/DriverBase.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Driver/DriverBase.cs 2010-07-28 20:44:14 UTC (rev 5072) +++ trunk/nhibernate/src/NHibernate/Driver/DriverBase.cs 2010-07-28 20:57:45 UTC (rev 5073) @@ -208,6 +208,36 @@ return dbParam; } + public virtual void ExpandQueryParameters(IDbCommand cmd, SqlString sqlString) + { + if (UseNamedPrefixInSql) + return; // named parameters are ok + + var expandedParameters = new List<IDbDataParameter>(); + foreach (object part in sqlString.Parts) + { + if (part is Parameter) + { + var parameter = (Parameter)part; + var originalParameter = (IDbDataParameter)cmd.Parameters[parameter.ParameterPosition.Value]; + expandedParameters.Add(CloneParameter(cmd, originalParameter)); + } + } + + cmd.Parameters.Clear(); + foreach (var parameter in expandedParameters) + cmd.Parameters.Add(parameter); + } + + protected virtual IDbDataParameter CloneParameter(IDbCommand cmd, IDbDataParameter originalParameter) + { + var clone = cmd.CreateParameter(); + clone.DbType = originalParameter.DbType; + clone.ParameterName = originalParameter.ParameterName; + clone.Value = originalParameter.Value; + return clone; + } + public void PrepareCommand(IDbCommand command) { OnBeforePrepare(command); Modified: trunk/nhibernate/src/NHibernate/Driver/IDriver.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Driver/IDriver.cs 2010-07-28 20:44:14 UTC (rev 5072) +++ trunk/nhibernate/src/NHibernate/Driver/IDriver.cs 2010-07-28 20:57:45 UTC (rev 5073) @@ -95,5 +95,16 @@ /// <param name="sqlType">The SqlType to set for IDbDataParameter.</param> /// <returns>An IDbDataParameter ready to be added to an IDbCommand.</returns> IDbDataParameter GenerateParameter(IDbCommand command, string name, SqlType sqlType); + + /// <summary> + /// Expand the parameters of the cmd to have a single parameter for each parameter in the + /// sql string + /// </summary> + /// <remarks> + /// This is for databases that do not support named parameters. So, instead of a single parameter + /// for 'select ... from MyTable t where t.Col1 = @p0 and t.Col2 = @p0' we can issue + /// 'select ... from MyTable t where t.Col1 = ? and t.Col2 = ?' + /// </remarks> + void ExpandQueryParameters(IDbCommand cmd, SqlString sqlString); } } \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Engine/IBatcher.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Engine/IBatcher.cs 2010-07-28 20:44:14 UTC (rev 5072) +++ trunk/nhibernate/src/NHibernate/Engine/IBatcher.cs 2010-07-28 20:57:45 UTC (rev 5073) @@ -132,6 +132,17 @@ int ExecuteNonQuery(IDbCommand cmd); /// <summary> + /// Expand the parameters of the cmd to have a single parameter for each parameter in the + /// sql string + /// </summary> + /// <remarks> + /// This is for databases that do not support named parameters. So, instead of a single parameter + /// for 'select ... from MyTable t where t.Col1 = @p0 and t.Col2 = @p0' we can issue + /// 'select ... from MyTable t where t.Col1 = ? and t.Col2 = ?' + /// </remarks> + void ExpandQueryParameters(IDbCommand cmd, SqlString sqlString); + + /// <summary> /// Must be called when an exception occurs. /// </summary> /// <param name="e"></param> Modified: trunk/nhibernate/src/NHibernate/Loader/Loader.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Loader/Loader.cs 2010-07-28 20:44:14 UTC (rev 5072) +++ trunk/nhibernate/src/NHibernate/Loader/Loader.cs 2010-07-28 20:57:45 UTC (rev 5073) @@ -1148,6 +1148,8 @@ BindLimitParameters(command, colIndex, selection, session); } + session.Batcher.ExpandQueryParameters(command, sqlString); + if (!useLimit) { SetMaxRows(command, selection); Property changes on: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2257 ___________________________________________________________________ Added: bugtraq:url + http://jira.nhibernate.org/browse/%BUGID% Added: bugtraq:logregex + NH-\d+ Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2257/Domain.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2257/Domain.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2257/Domain.cs 2010-07-28 20:57:45 UTC (rev 5073) @@ -0,0 +1,11 @@ +using System; + +namespace NHibernate.Test.NHSpecificTest.NH2257 +{ + public class Foo + { + public virtual int Id { get; set; } + public virtual string Name { get; set; } + public virtual int Ord { get; set; } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2257/Fixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2257/Fixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2257/Fixture.cs 2010-07-28 20:57:45 UTC (rev 5073) @@ -0,0 +1,30 @@ +using System.Linq; +using NUnit.Framework; + +namespace NHibernate.Test.NHSpecificTest.NH2257 +{ + public class Fixture : BugTestCase + { + protected override bool AppliesTo(NHibernate.Dialect.Dialect dialect) + { + return (dialect is NHibernate.Dialect.InformixDialect1000); + } + + [Test] + public void InformixUsingDuplicateParameters() + { + using (var session = OpenSession()) + using (var transaction = session.BeginTransaction()) + { + session.Save(new Foo() { Name = "aa" }); + + var list = + session.CreateQuery("from Foo f where f.Name = :p1 and not f.Name <> :p1") + .SetParameter("p1", "aa") + .List<Foo>(); + + Assert.That(list.Count, Is.EqualTo(1)); + } + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2257/Mappings.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2257/Mappings.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2257/Mappings.hbm.xml 2010-07-28 20:57:45 UTC (rev 5073) @@ -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.NH2257"> + + <class name="Foo"> + <id name="Id"> + <generator class="hilo" /> + </id> + <property name="Name"/> + <property name="Ord"/> + </class> +</hibernate-mapping> Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-07-28 20:44:14 UTC (rev 5072) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-07-28 20:57:45 UTC (rev 5073) @@ -774,6 +774,8 @@ <Compile Include="NHSpecificTest\NH2243\Person.cs" /> <Compile Include="NHSpecificTest\NH2251\Domain.cs" /> <Compile Include="NHSpecificTest\NH2251\Fixture.cs" /> + <Compile Include="NHSpecificTest\NH2257\Domain.cs" /> + <Compile Include="NHSpecificTest\NH2257\Fixture.cs" /> <Compile Include="NHSpecificTest\NH473\Child.cs" /> <Compile Include="NHSpecificTest\NH473\Fixture.cs" /> <Compile Include="NHSpecificTest\NH473\Parent.cs" /> @@ -2215,6 +2217,7 @@ <EmbeddedResource Include="DriverTest\SqlServerCeEntity.hbm.xml" /> <EmbeddedResource Include="CollectionTest\NullableValueTypeElementMapFixture.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> + <EmbeddedResource Include="NHSpecificTest\NH2257\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH2208\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH2251\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH2041\Mappings.hbm.xml" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2010-07-28 21:15:21
|
Revision: 5074 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5074&view=rev Author: fabiomaulo Date: 2010-07-28 21:15:15 +0000 (Wed, 28 Jul 2010) Log Message: ----------- Added the new LinqToHqlGeneratorsRegistry property configuration through Loquacious Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Cfg/Loquacious/ConfigurationExtensions.cs trunk/nhibernate/src/NHibernate.Test/CfgTest/Loquacious/LambdaConfigurationFixture.cs Modified: trunk/nhibernate/src/NHibernate/Cfg/Loquacious/ConfigurationExtensions.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/Loquacious/ConfigurationExtensions.cs 2010-07-28 20:57:45 UTC (rev 5073) +++ trunk/nhibernate/src/NHibernate/Cfg/Loquacious/ConfigurationExtensions.cs 2010-07-28 21:15:15 UTC (rev 5074) @@ -1,5 +1,6 @@ using System; using NHibernate.Hql; +using NHibernate.Linq.Functions; using NHibernate.Util; namespace NHibernate.Cfg.Loquacious @@ -42,6 +43,12 @@ return configuration; } + public static Configuration LinqToHqlGeneratorsRegistry<TLinqToHqlGeneratorsRegistry>(this Configuration configuration) where TLinqToHqlGeneratorsRegistry : ILinqToHqlGeneratorsRegistry + { + configuration.SetProperty(Environment.LinqToHqlGeneratorsRegistry, typeof(TLinqToHqlGeneratorsRegistry).AssemblyQualifiedName); + return configuration; + } + public static Configuration Mappings(this Configuration configuration, Action<IMappingsConfigurationProperties> mappingsProperties) { mappingsProperties(new MappingsConfigurationProperties(configuration)); Modified: trunk/nhibernate/src/NHibernate.Test/CfgTest/Loquacious/LambdaConfigurationFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/CfgTest/Loquacious/LambdaConfigurationFixture.cs 2010-07-28 20:57:45 UTC (rev 5073) +++ trunk/nhibernate/src/NHibernate.Test/CfgTest/Loquacious/LambdaConfigurationFixture.cs 2010-07-28 21:15:15 UTC (rev 5074) @@ -4,11 +4,13 @@ using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Hql.Classic; +using NHibernate.Linq.Functions; using NHibernate.Type; using NUnit.Framework; using NHibernate.Cfg.Loquacious; using System.Data; using NHibernate.Exceptions; +using SharpTestsEx; namespace NHibernate.Test.CfgTest.Loquacious { @@ -30,6 +32,7 @@ }); configure.CollectionTypeFactory<DefaultCollectionTypeFactory>(); configure.HqlQueryTranslator<ClassicQueryTranslatorFactory>(); + configure.LinqToHqlGeneratorsRegistry<FunctionRegistry>(); configure.Proxy(p => { p.Validation = false; @@ -99,6 +102,7 @@ Assert.That(configure.Properties[Environment.MaxFetchDepth], Is.EqualTo("11")); Assert.That(configure.Properties[Environment.QuerySubstitutions], Is.EqualTo("true 1, false 0, yes 'Y', no 'N'")); Assert.That(configure.Properties[Environment.Hbm2ddlAuto], Is.EqualTo("validate")); + configure.Properties[Environment.LinqToHqlGeneratorsRegistry].Should().Be(typeof(FunctionRegistry).AssemblyQualifiedName); } } } \ 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...> - 2010-07-28 21:19:54
|
Revision: 5075 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5075&view=rev Author: fabiomaulo Date: 2010-07-28 21:19:47 +0000 (Wed, 28 Jul 2010) Log Message: ----------- Refactoring (class renaming) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Linq/Functions/BaseHqlGeneratorForType.cs trunk/nhibernate/src/NHibernate/Linq/Functions/IHqlGeneratorForType.cs trunk/nhibernate/src/NHibernate/Linq/Functions/LinqToHqlGeneratorsRegistryFactory.cs trunk/nhibernate/src/NHibernate/NHibernate.csproj trunk/nhibernate/src/NHibernate.Test/CfgTest/Loquacious/LambdaConfigurationFixture.cs trunk/nhibernate/src/NHibernate.Test/Linq/LinqToHqlGeneratorsRegistryFactoryTest.cs Added Paths: ----------- trunk/nhibernate/src/NHibernate/Linq/Functions/DefaultLinqToHqlGeneratorsRegistry.cs Removed Paths: ------------- trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs Modified: trunk/nhibernate/src/NHibernate/Linq/Functions/BaseHqlGeneratorForType.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/BaseHqlGeneratorForType.cs 2010-07-28 21:15:15 UTC (rev 5074) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/BaseHqlGeneratorForType.cs 2010-07-28 21:19:47 UTC (rev 5075) @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Reflection; using NHibernate.Linq.Visitors; @@ -10,7 +10,7 @@ protected readonly List<IHqlGeneratorForMethod> MethodRegistry = new List<IHqlGeneratorForMethod>(); protected readonly List<IHqlGeneratorForProperty> PropertyRegistry = new List<IHqlGeneratorForProperty>(); - public void Register(FunctionRegistry functionRegistry) + public void Register(DefaultLinqToHqlGeneratorsRegistry functionRegistry) { foreach (var generator in MethodRegistry) { Copied: trunk/nhibernate/src/NHibernate/Linq/Functions/DefaultLinqToHqlGeneratorsRegistry.cs (from rev 5070, trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs) =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/DefaultLinqToHqlGeneratorsRegistry.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/DefaultLinqToHqlGeneratorsRegistry.cs 2010-07-28 21:19:47 UTC (rev 5075) @@ -0,0 +1,133 @@ +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using NHibernate.Hql.Ast; +using NHibernate.Linq.Visitors; + +namespace NHibernate.Linq.Functions +{ + public class DefaultLinqToHqlGeneratorsRegistry : ILinqToHqlGeneratorsRegistry + { + private readonly Dictionary<MethodInfo, IHqlGeneratorForMethod> registeredMethods = new Dictionary<MethodInfo, IHqlGeneratorForMethod>(); + private readonly Dictionary<MemberInfo, IHqlGeneratorForProperty> registeredProperties = new Dictionary<MemberInfo, IHqlGeneratorForProperty>(); + private readonly List<IHqlGeneratorForType> typeGenerators = new List<IHqlGeneratorForType>(); + + public DefaultLinqToHqlGeneratorsRegistry() + { + // TODO - could use reflection here + Register(new QueryableGenerator()); + Register(new StringGenerator()); + Register(new DateTimeGenerator()); + Register(new ICollectionGenerator()); + } + + private bool GetMethodGeneratorForType(MethodInfo method, out IHqlGeneratorForMethod methodGenerator) + { + methodGenerator = null; + + foreach (var typeGenerator in typeGenerators.Where(typeGenerator => typeGenerator.SupportsMethod(method))) + { + methodGenerator = typeGenerator.GetMethodGenerator(method); + return true; + } + return false; + } + + private bool GetStandardLinqExtensionMethodGenerator(MethodInfo method, out IHqlGeneratorForMethod methodGenerator) + { + methodGenerator = null; + + var attr = method.GetCustomAttributes(typeof(LinqExtensionMethodAttribute), false); + + if (attr.Length == 1) + { + // It is + methodGenerator = new HqlGeneratorForExtensionMethod((LinqExtensionMethodAttribute)attr[0], method); + return true; + } + return false; + } + + private bool GetRegisteredMethodGenerator(MethodInfo method, out IHqlGeneratorForMethod methodGenerator) + { + if (registeredMethods.TryGetValue(method, out methodGenerator)) + { + return true; + } + return false; + } + + public bool TryGetGenerator(MethodInfo method, out IHqlGeneratorForMethod generator) + { + if (method.IsGenericMethod) + { + method = method.GetGenericMethodDefinition(); + } + + if (GetRegisteredMethodGenerator(method, out generator)) return true; + + // No method generator registered. Look to see if it's a standard LinqExtensionMethod + if (GetStandardLinqExtensionMethodGenerator(method, out generator)) return true; + + // Not that either. Let's query each type generator to see if it can handle it + if (GetMethodGeneratorForType(method, out generator)) return true; + + return false; + } + + public bool TryGetGenerator(MemberInfo property, out IHqlGeneratorForProperty generator) + { + return registeredProperties.TryGetValue(property, out generator); + } + + public void RegisterGenerator(MethodInfo method, IHqlGeneratorForMethod generator) + { + registeredMethods.Add(method, generator); + } + + public void RegisterGenerator(MemberInfo property, IHqlGeneratorForProperty generator) + { + registeredProperties.Add(property, generator); + } + + private void Register(IHqlGeneratorForType typeMethodGenerator) + { + typeGenerators.Add(typeMethodGenerator); + typeMethodGenerator.Register(this); + } + } + + public class HqlGeneratorForExtensionMethod : BaseHqlGeneratorForMethod + { + private readonly string _name; + + public HqlGeneratorForExtensionMethod(LinqExtensionMethodAttribute attribute, MethodInfo method) + { + _name = string.IsNullOrEmpty(attribute.Name) ? method.Name : attribute.Name; + } + + public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) + { + var args = visitor.Visit(targetObject) + .Union(arguments.Select(a => visitor.Visit(a))) + .Cast<HqlExpression>(); + + return treeBuilder.MethodCall(_name, args); + } + } + + static class UnionExtension + { + public static IEnumerable<HqlTreeNode> Union(this HqlTreeNode first, IEnumerable<HqlTreeNode> rest) + { + yield return first; + + foreach (var x in rest) + { + yield return x; + } + } + } +} \ No newline at end of file Deleted: trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs 2010-07-28 21:15:15 UTC (rev 5074) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs 2010-07-28 21:19:47 UTC (rev 5075) @@ -1,133 +0,0 @@ -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using NHibernate.Hql.Ast; -using NHibernate.Linq.Visitors; - -namespace NHibernate.Linq.Functions -{ - public class FunctionRegistry : ILinqToHqlGeneratorsRegistry - { - private readonly Dictionary<MethodInfo, IHqlGeneratorForMethod> registeredMethods = new Dictionary<MethodInfo, IHqlGeneratorForMethod>(); - private readonly Dictionary<MemberInfo, IHqlGeneratorForProperty> registeredProperties = new Dictionary<MemberInfo, IHqlGeneratorForProperty>(); - private readonly List<IHqlGeneratorForType> typeGenerators = new List<IHqlGeneratorForType>(); - - public FunctionRegistry() - { - // TODO - could use reflection here - Register(new QueryableGenerator()); - Register(new StringGenerator()); - Register(new DateTimeGenerator()); - Register(new ICollectionGenerator()); - } - - private bool GetMethodGeneratorForType(MethodInfo method, out IHqlGeneratorForMethod methodGenerator) - { - methodGenerator = null; - - foreach (var typeGenerator in typeGenerators.Where(typeGenerator => typeGenerator.SupportsMethod(method))) - { - methodGenerator = typeGenerator.GetMethodGenerator(method); - return true; - } - return false; - } - - private bool GetStandardLinqExtensionMethodGenerator(MethodInfo method, out IHqlGeneratorForMethod methodGenerator) - { - methodGenerator = null; - - var attr = method.GetCustomAttributes(typeof(LinqExtensionMethodAttribute), false); - - if (attr.Length == 1) - { - // It is - methodGenerator = new HqlGeneratorForExtensionMethod((LinqExtensionMethodAttribute)attr[0], method); - return true; - } - return false; - } - - private bool GetRegisteredMethodGenerator(MethodInfo method, out IHqlGeneratorForMethod methodGenerator) - { - if (registeredMethods.TryGetValue(method, out methodGenerator)) - { - return true; - } - return false; - } - - public bool TryGetGenerator(MethodInfo method, out IHqlGeneratorForMethod generator) - { - if (method.IsGenericMethod) - { - method = method.GetGenericMethodDefinition(); - } - - if (GetRegisteredMethodGenerator(method, out generator)) return true; - - // No method generator registered. Look to see if it's a standard LinqExtensionMethod - if (GetStandardLinqExtensionMethodGenerator(method, out generator)) return true; - - // Not that either. Let's query each type generator to see if it can handle it - if (GetMethodGeneratorForType(method, out generator)) return true; - - return false; - } - - public bool TryGetGenerator(MemberInfo property, out IHqlGeneratorForProperty generator) - { - return registeredProperties.TryGetValue(property, out generator); - } - - public void RegisterGenerator(MethodInfo method, IHqlGeneratorForMethod generator) - { - registeredMethods.Add(method, generator); - } - - public void RegisterGenerator(MemberInfo property, IHqlGeneratorForProperty generator) - { - registeredProperties.Add(property, generator); - } - - private void Register(IHqlGeneratorForType typeMethodGenerator) - { - typeGenerators.Add(typeMethodGenerator); - typeMethodGenerator.Register(this); - } - } - - public class HqlGeneratorForExtensionMethod : BaseHqlGeneratorForMethod - { - private readonly string _name; - - public HqlGeneratorForExtensionMethod(LinqExtensionMethodAttribute attribute, MethodInfo method) - { - _name = string.IsNullOrEmpty(attribute.Name) ? method.Name : attribute.Name; - } - - public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) - { - var args = visitor.Visit(targetObject) - .Union(arguments.Select(a => visitor.Visit(a))) - .Cast<HqlExpression>(); - - return treeBuilder.MethodCall(_name, args); - } - } - - static class UnionExtension - { - public static IEnumerable<HqlTreeNode> Union(this HqlTreeNode first, IEnumerable<HqlTreeNode> rest) - { - yield return first; - - foreach (var x in rest) - { - yield return x; - } - } - } -} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Linq/Functions/IHqlGeneratorForType.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/IHqlGeneratorForType.cs 2010-07-28 21:15:15 UTC (rev 5074) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/IHqlGeneratorForType.cs 2010-07-28 21:19:47 UTC (rev 5075) @@ -1,10 +1,10 @@ -using System.Reflection; +using System.Reflection; namespace NHibernate.Linq.Functions { public interface IHqlGeneratorForType { - void Register(FunctionRegistry functionRegistry); + void Register(DefaultLinqToHqlGeneratorsRegistry functionRegistry); bool SupportsMethod(MethodInfo method); IHqlGeneratorForMethod GetMethodGenerator(MethodInfo method); } Modified: trunk/nhibernate/src/NHibernate/Linq/Functions/LinqToHqlGeneratorsRegistryFactory.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/LinqToHqlGeneratorsRegistryFactory.cs 2010-07-28 21:15:15 UTC (rev 5074) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/LinqToHqlGeneratorsRegistryFactory.cs 2010-07-28 21:19:47 UTC (rev 5075) @@ -26,7 +26,7 @@ throw new HibernateException("Could not instantiate LinqToHqlGeneratorsRegistry: " + registry, e); } } - return new FunctionRegistry(); + return new DefaultLinqToHqlGeneratorsRegistry(); } } } \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-07-28 21:15:15 UTC (rev 5074) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-07-28 21:19:47 UTC (rev 5075) @@ -678,7 +678,7 @@ <Compile Include="Linq\GroupJoin\LocateGroupJoinQuerySource.cs" /> <Compile Include="Linq\GroupJoin\NonAggregatingGroupJoinRewriter.cs" /> <Compile Include="Linq\Functions\BaseHqlGeneratorForProperty.cs" /> - <Compile Include="Linq\Functions\FunctionRegistry.cs" /> + <Compile Include="Linq\Functions\DefaultLinqToHqlGeneratorsRegistry.cs" /> <Compile Include="Linq\Functions\IHqlGeneratorForMethod.cs" /> <Compile Include="Linq\Functions\IHqlGeneratorForProperty.cs" /> <Compile Include="Linq\Functions\BaseHqlGeneratorForMethod.cs" /> Modified: trunk/nhibernate/src/NHibernate.Test/CfgTest/Loquacious/LambdaConfigurationFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/CfgTest/Loquacious/LambdaConfigurationFixture.cs 2010-07-28 21:15:15 UTC (rev 5074) +++ trunk/nhibernate/src/NHibernate.Test/CfgTest/Loquacious/LambdaConfigurationFixture.cs 2010-07-28 21:19:47 UTC (rev 5075) @@ -32,7 +32,7 @@ }); configure.CollectionTypeFactory<DefaultCollectionTypeFactory>(); configure.HqlQueryTranslator<ClassicQueryTranslatorFactory>(); - configure.LinqToHqlGeneratorsRegistry<FunctionRegistry>(); + configure.LinqToHqlGeneratorsRegistry<DefaultLinqToHqlGeneratorsRegistry>(); configure.Proxy(p => { p.Validation = false; @@ -102,7 +102,7 @@ Assert.That(configure.Properties[Environment.MaxFetchDepth], Is.EqualTo("11")); Assert.That(configure.Properties[Environment.QuerySubstitutions], Is.EqualTo("true 1, false 0, yes 'Y', no 'N'")); Assert.That(configure.Properties[Environment.Hbm2ddlAuto], Is.EqualTo("validate")); - configure.Properties[Environment.LinqToHqlGeneratorsRegistry].Should().Be(typeof(FunctionRegistry).AssemblyQualifiedName); + configure.Properties[Environment.LinqToHqlGeneratorsRegistry].Should().Be(typeof(DefaultLinqToHqlGeneratorsRegistry).AssemblyQualifiedName); } } } \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate.Test/Linq/LinqToHqlGeneratorsRegistryFactoryTest.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Linq/LinqToHqlGeneratorsRegistryFactoryTest.cs 2010-07-28 21:15:15 UTC (rev 5074) +++ trunk/nhibernate/src/NHibernate.Test/Linq/LinqToHqlGeneratorsRegistryFactoryTest.cs 2010-07-28 21:19:47 UTC (rev 5075) @@ -15,7 +15,7 @@ { var registry = LinqToHqlGeneratorsRegistryFactory.CreateGeneratorsRegistry(new Dictionary<string, string>()); registry.Should().Not.Be.Null(); - registry.Should().Be.OfType<FunctionRegistry>(); + registry.Should().Be.OfType<DefaultLinqToHqlGeneratorsRegistry>(); } [Test] This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2010-07-28 22:19:27
|
Revision: 5078 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5078&view=rev Author: fabiomaulo Date: 2010-07-28 22:19:19 +0000 (Wed, 28 Jul 2010) Log Message: ----------- Refactoring (extracted StandardLinqExtensionMethodGenerator as an IHqlGeneratorForType) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Linq/Functions/DefaultLinqToHqlGeneratorsRegistry.cs trunk/nhibernate/src/NHibernate/NHibernate.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate/Linq/Functions/StandardLinqExtensionMethodGenerator.cs Modified: trunk/nhibernate/src/NHibernate/Linq/Functions/DefaultLinqToHqlGeneratorsRegistry.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/DefaultLinqToHqlGeneratorsRegistry.cs 2010-07-28 21:42:28 UTC (rev 5077) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/DefaultLinqToHqlGeneratorsRegistry.cs 2010-07-28 22:19:19 UTC (rev 5078) @@ -17,6 +17,7 @@ public DefaultLinqToHqlGeneratorsRegistry() { // TODO - could use reflection here + Register(new StandardLinqExtensionMethodGenerator()); Register(new QueryableGenerator()); Register(new StringGenerator()); Register(new DateTimeGenerator()); @@ -35,21 +36,6 @@ return false; } - protected bool GetStandardLinqExtensionMethodGenerator(MethodInfo method, out IHqlGeneratorForMethod methodGenerator) - { - methodGenerator = null; - - var attr = method.GetCustomAttributes(typeof(LinqExtensionMethodAttribute), false); - - if (attr.Length == 1) - { - // It is - methodGenerator = new HqlGeneratorForExtensionMethod((LinqExtensionMethodAttribute)attr[0], method); - return true; - } - return false; - } - protected bool GetRegisteredMethodGenerator(MethodInfo method, out IHqlGeneratorForMethod methodGenerator) { if (registeredMethods.TryGetValue(method, out methodGenerator)) @@ -68,9 +54,6 @@ if (GetRegisteredMethodGenerator(method, out generator)) return true; - // No method generator registered. Look to see if it's a standard LinqExtensionMethod - if (GetStandardLinqExtensionMethodGenerator(method, out generator)) return true; - // Not that either. Let's query each type generator to see if it can handle it if (GetMethodGeneratorForType(method, out generator)) return true; @@ -98,36 +81,4 @@ typeMethodGenerator.Register(this); } } - - public class HqlGeneratorForExtensionMethod : BaseHqlGeneratorForMethod - { - private readonly string _name; - - public HqlGeneratorForExtensionMethod(LinqExtensionMethodAttribute attribute, MethodInfo method) - { - _name = string.IsNullOrEmpty(attribute.Name) ? method.Name : attribute.Name; - } - - public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) - { - var args = visitor.Visit(targetObject) - .Union(arguments.Select(a => visitor.Visit(a))) - .Cast<HqlExpression>(); - - return treeBuilder.MethodCall(_name, args); - } - } - - static class UnionExtension - { - public static IEnumerable<HqlTreeNode> Union(this HqlTreeNode first, IEnumerable<HqlTreeNode> rest) - { - yield return first; - - foreach (var x in rest) - { - yield return x; - } - } - } } \ No newline at end of file Added: trunk/nhibernate/src/NHibernate/Linq/Functions/StandardLinqExtensionMethodGenerator.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/StandardLinqExtensionMethodGenerator.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/StandardLinqExtensionMethodGenerator.cs 2010-07-28 22:19:19 UTC (rev 5078) @@ -0,0 +1,64 @@ +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using NHibernate.Hql.Ast; +using NHibernate.Linq.Visitors; + +namespace NHibernate.Linq.Functions +{ + public class StandardLinqExtensionMethodGenerator : IHqlGeneratorForType + { + #region IHqlGeneratorForType Members + + public void Register(ILinqToHqlGeneratorsRegistry functionRegistry) + { + // nothing to do + } + + public bool SupportsMethod(MethodInfo method) + { + return method.GetCustomAttributes(typeof (LinqExtensionMethodAttribute), false).Any(); + } + + public IHqlGeneratorForMethod GetMethodGenerator(MethodInfo method) + { + return new HqlGeneratorForExtensionMethod((LinqExtensionMethodAttribute) method.GetCustomAttributes(typeof (LinqExtensionMethodAttribute), false).First(), method); + } + + #endregion + } + + public class HqlGeneratorForExtensionMethod : BaseHqlGeneratorForMethod + { + private readonly string _name; + + public HqlGeneratorForExtensionMethod(LinqExtensionMethodAttribute attribute, MethodInfo method) + { + _name = string.IsNullOrEmpty(attribute.Name) ? method.Name : attribute.Name; + } + + public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) + { + var args = visitor.Visit(targetObject) + .Union(arguments.Select(a => visitor.Visit(a))) + .Cast<HqlExpression>(); + + return treeBuilder.MethodCall(_name, args); + } + } + + static class UnionExtension + { + public static IEnumerable<HqlTreeNode> Union(this HqlTreeNode first, IEnumerable<HqlTreeNode> rest) + { + yield return first; + + foreach (var x in rest) + { + yield return x; + } + } + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-07-28 21:42:28 UTC (rev 5077) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-07-28 22:19:19 UTC (rev 5078) @@ -656,6 +656,7 @@ <Compile Include="Linq\EagerFetchingExtensionMethods.cs" /> <Compile Include="Linq\Functions\ILinqToHqlGeneratorsRegistry.cs" /> <Compile Include="Linq\Functions\LinqToHqlGeneratorsRegistryFactory.cs" /> + <Compile Include="Linq\Functions\StandardLinqExtensionMethodGenerator.cs" /> <Compile Include="Linq\LinqExtensionMethodAttribute.cs" /> <Compile Include="Linq\TypeHelperExtensionMethods.cs" /> <Compile Include="Linq\Visitors\NameUnNamedParameters.cs" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2010-07-30 17:03:06
|
Revision: 5082 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5082&view=rev Author: fabiomaulo Date: 2010-07-30 17:03:00 +0000 (Fri, 30 Jul 2010) Log Message: ----------- - ReflectionHelper tests - Renamed methods (more representative because return generic definition) - Added documentation for ReflectionHelper Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Linq/EnumerableHelper.cs trunk/nhibernate/src/NHibernate/Linq/Functions/QueryableGenerator.cs trunk/nhibernate/src/NHibernate/Linq/Functions/StringGenerator.cs trunk/nhibernate/src/NHibernate/Linq/LinqExtensionMethods.cs trunk/nhibernate/src/NHibernate/Linq/NhQueryProvider.cs trunk/nhibernate/src/NHibernate/Linq/NhRelinqQueryParser.cs trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessAggregate.cs trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessFirst.cs trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessSingle.cs trunk/nhibernate/src/NHibernate.Test/Linq/CustomExtensionsExample.cs trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectionHelperTest.cs Modified: trunk/nhibernate/src/NHibernate/Linq/EnumerableHelper.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/EnumerableHelper.cs 2010-07-29 13:10:59 UTC (rev 5081) +++ trunk/nhibernate/src/NHibernate/Linq/EnumerableHelper.cs 2010-07-30 17:03:00 UTC (rev 5082) @@ -5,28 +5,58 @@ namespace NHibernate.Linq { - public static class ReflectionHelper - { - public delegate void Action(); + public static class ReflectionHelper + { + /// <summary> + /// Extract the <see cref="MethodInfo"/> from a given expression. + /// </summary> + /// <typeparam name="TSource">The declaring-type of the method.</typeparam> + /// <param name="method">The method.</param> + /// <returns>The <see cref="MethodInfo"/> of the no-generic method or the generic-definition for a generic-method.</returns> + /// <seealso cref="MethodInfo.GetGenericMethodDefinition"/> + public static MethodInfo GetMethodDefinition<TSource>(Expression<Action<TSource>> method) + { + if (method == null) + { + throw new ArgumentNullException("method"); + } + MethodInfo methodInfo = ((MethodCallExpression) method.Body).Method; + return methodInfo.IsGenericMethod ? methodInfo.GetGenericMethodDefinition() : methodInfo; + } - public static MethodInfo GetMethod<TSource>(Expression<Action<TSource>> method) - { - var methodInfo = ((MethodCallExpression) method.Body).Method; - return methodInfo.IsGenericMethod ? methodInfo.GetGenericMethodDefinition() : methodInfo; - } + /// <summary> + /// Extract the <see cref="MethodInfo"/> from a given expression. + /// </summary> + /// <param name="method">The method.</param> + /// <returns>The <see cref="MethodInfo"/> of the no-generic method or the generic-definition for a generic-method.</returns> + /// <seealso cref="MethodInfo.GetGenericMethodDefinition"/> + public static MethodInfo GetMethodDefinition(Expression<System.Action> method) + { + if (method == null) + { + throw new ArgumentNullException("method"); + } + var methodInfo = ((MethodCallExpression)method.Body).Method; + return methodInfo.IsGenericMethod ? methodInfo.GetGenericMethodDefinition() : methodInfo; + } - public static MethodInfo GetMethod(Expression<Action> method) - { - var methodInfo = ((MethodCallExpression)method.Body).Method; - return methodInfo.IsGenericMethod ? methodInfo.GetGenericMethodDefinition() : methodInfo; - } + /// <summary> + /// Gets the field or property to be accessed. + /// </summary> + /// <typeparam name="TSource">The declaring-type of the property.</typeparam> + /// <typeparam name="TResult">The type of the property.</typeparam> + /// <param name="property">The expression representing the property getter.</param> + /// <returns>The <see cref="MemberInfo"/> of the property.</returns> + public static MemberInfo GetProperty<TSource, TResult>(Expression<Func<TSource, TResult>> property) + { + if (property == null) + { + throw new ArgumentNullException("property"); + } + return ((MemberExpression)property.Body).Member; + } + } - public static MemberInfo GetProperty<TSource, TResult>(Expression<Func<TSource, TResult>> property) - { - return ((MemberExpression) property.Body).Member; - } - } - // TODO rename / remove - reflection helper above is better public static class EnumerableHelper { Modified: trunk/nhibernate/src/NHibernate/Linq/Functions/QueryableGenerator.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/QueryableGenerator.cs 2010-07-29 13:10:59 UTC (rev 5081) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/QueryableGenerator.cs 2010-07-30 17:03:00 UTC (rev 5082) @@ -26,10 +26,10 @@ { SupportedMethods = new[] { - ReflectionHelper.GetMethod(() => Queryable.Any<object>(null)), - ReflectionHelper.GetMethod(() => Queryable.Any<object>(null, null)), - ReflectionHelper.GetMethod(() => Enumerable.Any<object>(null)), - ReflectionHelper.GetMethod(() => Enumerable.Any<object>(null, null)) + ReflectionHelper.GetMethodDefinition(() => Queryable.Any<object>(null)), + ReflectionHelper.GetMethodDefinition(() => Queryable.Any<object>(null, null)), + ReflectionHelper.GetMethodDefinition(() => Enumerable.Any<object>(null)), + ReflectionHelper.GetMethodDefinition(() => Enumerable.Any<object>(null, null)) }; } @@ -65,8 +65,8 @@ { SupportedMethods = new[] { - ReflectionHelper.GetMethod(() => Queryable.All<object>(null, null)), - ReflectionHelper.GetMethod(() => Enumerable.All<object>(null, null)) + ReflectionHelper.GetMethodDefinition(() => Queryable.All<object>(null, null)), + ReflectionHelper.GetMethodDefinition(() => Enumerable.All<object>(null, null)) }; } @@ -100,8 +100,8 @@ { SupportedMethods = new[] { - ReflectionHelper.GetMethod(() => Queryable.Min<object>(null)), - ReflectionHelper.GetMethod(() => Enumerable.Min<object>(null)) + ReflectionHelper.GetMethodDefinition(() => Queryable.Min<object>(null)), + ReflectionHelper.GetMethodDefinition(() => Enumerable.Min<object>(null)) }; } @@ -117,8 +117,8 @@ { SupportedMethods = new[] { - ReflectionHelper.GetMethod(() => Queryable.Max<object>(null)), - ReflectionHelper.GetMethod(() => Enumerable.Max<object>(null)) + ReflectionHelper.GetMethodDefinition(() => Queryable.Max<object>(null)), + ReflectionHelper.GetMethodDefinition(() => Enumerable.Max<object>(null)) }; } Modified: trunk/nhibernate/src/NHibernate/Linq/Functions/StringGenerator.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/StringGenerator.cs 2010-07-29 13:10:59 UTC (rev 5081) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/StringGenerator.cs 2010-07-30 17:03:00 UTC (rev 5082) @@ -1,4 +1,4 @@ -using System.Collections.ObjectModel; +using System.Collections.ObjectModel; using System.Linq.Expressions; using System.Reflection; using NHibernate.Hql.Ast; @@ -40,7 +40,7 @@ { public StartsWithGenerator() { - SupportedMethods = new[] { ReflectionHelper.GetMethod<string>(x => x.StartsWith(null)) }; + SupportedMethods = new[] { ReflectionHelper.GetMethodDefinition<string>(x => x.StartsWith(null)) }; } public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) @@ -57,7 +57,7 @@ { public EndsWithGenerator() { - SupportedMethods = new[] { ReflectionHelper.GetMethod<string>(x => x.EndsWith(null)) }; + SupportedMethods = new[] { ReflectionHelper.GetMethodDefinition<string>(x => x.EndsWith(null)) }; } public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) @@ -74,7 +74,7 @@ { public ContainsGenerator() { - SupportedMethods = new[] { ReflectionHelper.GetMethod<string>(x => x.Contains(null)) }; + SupportedMethods = new[] { ReflectionHelper.GetMethodDefinition<string>(x => x.Contains(null)) }; } public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) @@ -92,7 +92,7 @@ { public EqualsGenerator() { - SupportedMethods = new[] { ReflectionHelper.GetMethod<string>(x => x.Equals((string)null)) }; + SupportedMethods = new[] { ReflectionHelper.GetMethodDefinition<string>(x => x.Equals((string)null)) }; } public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) @@ -109,10 +109,10 @@ { SupportedMethods = new[] { - ReflectionHelper.GetMethod<string>(x => x.ToUpper()), - ReflectionHelper.GetMethod<string>(x => x.ToUpperInvariant()), - ReflectionHelper.GetMethod<string>(x => x.ToLower()), - ReflectionHelper.GetMethod<string>(x => x.ToLowerInvariant()) + ReflectionHelper.GetMethodDefinition<string>(x => x.ToUpper()), + ReflectionHelper.GetMethodDefinition<string>(x => x.ToUpperInvariant()), + ReflectionHelper.GetMethodDefinition<string>(x => x.ToLower()), + ReflectionHelper.GetMethodDefinition<string>(x => x.ToLowerInvariant()) }; } @@ -139,8 +139,8 @@ { SupportedMethods = new[] { - ReflectionHelper.GetMethod<string>(s => s.Substring(0)), - ReflectionHelper.GetMethod<string>(s => s.Substring(0, 0)) + ReflectionHelper.GetMethodDefinition<string>(s => s.Substring(0)), + ReflectionHelper.GetMethodDefinition<string>(s => s.Substring(0, 0)) }; } public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) @@ -164,10 +164,10 @@ { SupportedMethods = new[] { - ReflectionHelper.GetMethod<string>(s => s.IndexOf(' ')), - ReflectionHelper.GetMethod<string>(s => s.IndexOf(" ")), - ReflectionHelper.GetMethod<string>(s => s.IndexOf(' ', 0)), - ReflectionHelper.GetMethod<string>(s => s.IndexOf(" ", 0)) + ReflectionHelper.GetMethodDefinition<string>(s => s.IndexOf(' ')), + ReflectionHelper.GetMethodDefinition<string>(s => s.IndexOf(" ")), + ReflectionHelper.GetMethodDefinition<string>(s => s.IndexOf(' ', 0)), + ReflectionHelper.GetMethodDefinition<string>(s => s.IndexOf(" ", 0)) }; } public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) @@ -192,8 +192,8 @@ { SupportedMethods = new[] { - ReflectionHelper.GetMethod<string>(s => s.Replace(' ', ' ')), - ReflectionHelper.GetMethod<string>(s => s.Replace("", "")) + ReflectionHelper.GetMethodDefinition<string>(s => s.Replace(' ', ' ')), + ReflectionHelper.GetMethodDefinition<string>(s => s.Replace("", "")) }; } Modified: trunk/nhibernate/src/NHibernate/Linq/LinqExtensionMethods.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/LinqExtensionMethods.cs 2010-07-29 13:10:59 UTC (rev 5081) +++ trunk/nhibernate/src/NHibernate/Linq/LinqExtensionMethods.cs 2010-07-30 17:03:00 UTC (rev 5082) @@ -1,4 +1,4 @@ -using System.Linq; +using System.Linq; using System.Linq.Expressions; namespace NHibernate.Linq @@ -12,7 +12,7 @@ public static IQueryable<T> Cacheable<T>(this IQueryable<T> query) { - var method = ReflectionHelper.GetMethod(() => Cacheable<object>(null)).MakeGenericMethod(typeof(T)); + var method = ReflectionHelper.GetMethodDefinition(() => Cacheable<object>(null)).MakeGenericMethod(typeof(T)); var callExpression = Expression.Call(method, query.Expression); @@ -21,7 +21,7 @@ public static IQueryable<T> CacheMode<T>(this IQueryable<T> query, CacheMode cacheMode) { - var method = ReflectionHelper.GetMethod(() => CacheMode<object>(null, NHibernate.CacheMode.Normal)).MakeGenericMethod(typeof(T)); + var method = ReflectionHelper.GetMethodDefinition(() => CacheMode<object>(null, NHibernate.CacheMode.Normal)).MakeGenericMethod(typeof(T)); var callExpression = Expression.Call(method, query.Expression, Expression.Constant(cacheMode)); @@ -30,7 +30,7 @@ public static IQueryable<T> CacheRegion<T>(this IQueryable<T> query, string region) { - var method = ReflectionHelper.GetMethod(() => CacheRegion<object>(null, null)).MakeGenericMethod(typeof(T)); + var method = ReflectionHelper.GetMethodDefinition(() => CacheRegion<object>(null, null)).MakeGenericMethod(typeof(T)); var callExpression = Expression.Call(method, query.Expression, Expression.Constant(region)); Modified: trunk/nhibernate/src/NHibernate/Linq/NhQueryProvider.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/NhQueryProvider.cs 2010-07-29 13:10:59 UTC (rev 5081) +++ trunk/nhibernate/src/NHibernate/Linq/NhQueryProvider.cs 2010-07-30 17:03:00 UTC (rev 5082) @@ -1,4 +1,4 @@ -using System.Collections; +using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; @@ -57,7 +57,7 @@ public IQueryable CreateQuery(Expression expression) { - var m = ReflectionHelper.GetMethod((NhQueryProvider p) => p.CreateQuery<object>(null)).MakeGenericMethod(expression.Type.GetGenericArguments()[0]); + var m = ReflectionHelper.GetMethodDefinition((NhQueryProvider p) => p.CreateQuery<object>(null)).MakeGenericMethod(expression.Type.GetGenericArguments()[0]); return (IQueryable) m.Invoke(this, new[] {expression}); } Modified: trunk/nhibernate/src/NHibernate/Linq/NhRelinqQueryParser.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/NhRelinqQueryParser.cs 2010-07-29 13:10:59 UTC (rev 5081) +++ trunk/nhibernate/src/NHibernate/Linq/NhRelinqQueryParser.cs 2010-07-30 17:03:00 UTC (rev 5082) @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; @@ -23,9 +23,9 @@ new[] { MethodCallExpressionNodeTypeRegistry.GetRegisterableMethodDefinition( - ReflectionHelper.GetMethod(() => Queryable.Aggregate<object>(null, null))), + ReflectionHelper.GetMethodDefinition(() => Queryable.Aggregate<object>(null, null))), MethodCallExpressionNodeTypeRegistry.GetRegisterableMethodDefinition( - ReflectionHelper.GetMethod(() => Queryable.Aggregate<object, object>(null, null, null))) + ReflectionHelper.GetMethodDefinition(() => Queryable.Aggregate<object, object>(null, null, null))) }, typeof (AggregateExpressionNode)); @@ -33,7 +33,7 @@ new[] { MethodCallExpressionNodeTypeRegistry.GetRegisterableMethodDefinition( - ReflectionHelper.GetMethod((List<object> l) => l.Contains(null))), + ReflectionHelper.GetMethodDefinition((List<object> l) => l.Contains(null))), }, typeof (ContainsExpressionNode)); Modified: trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessAggregate.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessAggregate.cs 2010-07-29 13:10:59 UTC (rev 5081) +++ trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessAggregate.cs 2010-07-30 17:03:00 UTC (rev 5082) @@ -1,4 +1,4 @@ -using System.Collections; +using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; @@ -21,7 +21,7 @@ if (resultOperator.ParseInfo.ParsedExpression.Arguments.Count == 2) { - var aggregate = ReflectionHelper.GetMethod(() => Enumerable.Aggregate<object>(null, null)); + var aggregate = ReflectionHelper.GetMethodDefinition(() => Enumerable.Aggregate<object>(null, null)); aggregate = aggregate.GetGenericMethodDefinition().MakeGenericMethod(inputType); call = Expression.Call( @@ -33,7 +33,7 @@ } else if (resultOperator.ParseInfo.ParsedExpression.Arguments.Count == 3) { - var aggregate = ReflectionHelper.GetMethod(() => Enumerable.Aggregate<object, object>(null, null, null)); + var aggregate = ReflectionHelper.GetMethodDefinition(() => Enumerable.Aggregate<object, object>(null, null, null)); aggregate = aggregate.GetGenericMethodDefinition().MakeGenericMethod(inputType, accumulatorType); call = Expression.Call( @@ -46,7 +46,7 @@ else { var selectorType = resultOperator.OptionalSelector.Type.GetGenericArguments()[2]; - var aggregate = ReflectionHelper.GetMethod(() => Enumerable.Aggregate<object, object, object>(null, null, null, null)); + var aggregate = ReflectionHelper.GetMethodDefinition(() => Enumerable.Aggregate<object, object, object>(null, null, null, null)); aggregate = aggregate.GetGenericMethodDefinition().MakeGenericMethod(inputType, accumulatorType, selectorType); call = Expression.Call( Modified: trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessFirst.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessFirst.cs 2010-07-29 13:10:59 UTC (rev 5081) +++ trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessFirst.cs 2010-07-30 17:03:00 UTC (rev 5082) @@ -1,4 +1,4 @@ -using System.Linq; +using System.Linq; using Remotion.Data.Linq.Clauses.ResultOperators; namespace NHibernate.Linq.Visitors.ResultOperatorProcessors @@ -8,8 +8,8 @@ public void Process(FirstResultOperator resultOperator, QueryModelVisitor queryModelVisitor, IntermediateHqlTree tree) { var firstMethod = resultOperator.ReturnDefaultWhenEmpty - ? ReflectionHelper.GetMethod(() => Queryable.FirstOrDefault<object>(null)) - : ReflectionHelper.GetMethod(() => Queryable.First<object>(null)); + ? ReflectionHelper.GetMethodDefinition(() => Queryable.FirstOrDefault<object>(null)) + : ReflectionHelper.GetMethodDefinition(() => Queryable.First<object>(null)); AddClientSideEval(firstMethod, queryModelVisitor, tree); Modified: trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessSingle.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessSingle.cs 2010-07-29 13:10:59 UTC (rev 5081) +++ trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessSingle.cs 2010-07-30 17:03:00 UTC (rev 5082) @@ -1,4 +1,4 @@ -using System.Linq; +using System.Linq; using Remotion.Data.Linq.Clauses.ResultOperators; namespace NHibernate.Linq.Visitors.ResultOperatorProcessors @@ -8,8 +8,8 @@ public void Process(SingleResultOperator resultOperator, QueryModelVisitor queryModelVisitor, IntermediateHqlTree tree) { var firstMethod = resultOperator.ReturnDefaultWhenEmpty - ? ReflectionHelper.GetMethod(() => Queryable.SingleOrDefault<object>(null)) - : ReflectionHelper.GetMethod(() => Queryable.Single<object>(null)); + ? ReflectionHelper.GetMethodDefinition(() => Queryable.SingleOrDefault<object>(null)) + : ReflectionHelper.GetMethodDefinition(() => Queryable.Single<object>(null)); AddClientSideEval(firstMethod, queryModelVisitor, tree); } Modified: trunk/nhibernate/src/NHibernate.Test/Linq/CustomExtensionsExample.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Linq/CustomExtensionsExample.cs 2010-07-29 13:10:59 UTC (rev 5081) +++ trunk/nhibernate/src/NHibernate.Test/Linq/CustomExtensionsExample.cs 2010-07-30 17:03:00 UTC (rev 5082) @@ -29,7 +29,7 @@ { public MyLinqToHqlGeneratorsRegistry():base() { - RegisterGenerator(ReflectionHelper.GetMethod(() => MyLinqExtensions.IsLike(null, null)), + RegisterGenerator(ReflectionHelper.GetMethodDefinition(() => MyLinqExtensions.IsLike(null, null)), new IsLikeGenerator()); } } @@ -38,7 +38,7 @@ { public IsLikeGenerator() { - SupportedMethods = new[] {ReflectionHelper.GetMethod(() => MyLinqExtensions.IsLike(null, null))}; + SupportedMethods = new[] {ReflectionHelper.GetMethodDefinition(() => MyLinqExtensions.IsLike(null, null))}; } public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-07-29 13:10:59 UTC (rev 5081) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-07-30 17:03:00 UTC (rev 5082) @@ -440,6 +440,7 @@ <Compile Include="Linq\QueryCacheableTests.cs" /> <Compile Include="Linq\QueryReuseTests.cs" /> <Compile Include="Linq\ReadonlyTestCase.cs" /> + <Compile Include="UtilityTest\ReflectionHelperTest.cs" /> <Compile Include="Linq\RegresstionTests.cs" /> <Compile Include="Linq\SelectionTests.cs" /> <Compile Include="Linq\WhereSubqueryTests.cs" /> Added: trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectionHelperTest.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectionHelperTest.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectionHelperTest.cs 2010-07-30 17:03:00 UTC (rev 5082) @@ -0,0 +1,74 @@ +using System; +using System.Linq; +using System.Linq.Expressions; +using NHibernate.Linq; +using NUnit.Framework; +using SharpTestsEx; + +namespace NHibernate.Test.UtilityTest +{ + public class ReflectionHelperTest + { + private class MyClass + { + public void NoGenericMethod() {} + public void GenericMethod<T>() { } + public string BaseProperty { get; set; } + public bool BaseBool { get; set; } + } + + [Test] + public void WhenGetMethodForNullThenThrows() + { + Executing.This(() => ReflectionHelper.GetMethodDefinition((Expression<System.Action>) null)).Should().Throw<ArgumentNullException>(); + } + + [Test] + public void WhenGenericGetMethodForNullThenThrows() + { + Executing.This(() => ReflectionHelper.GetMethodDefinition<object>((Expression<System.Action<object>>)null)).Should().Throw<ArgumentNullException>(); + } + + [Test] + public void WhenGetPropertyForNullThenThrows() + { + Executing.This(() => ReflectionHelper.GetProperty<object, object>(null)).Should().Throw<ArgumentNullException>(); + } + + [Test] + public void WhenGenericMethodOfClassThenReturnGenericDefinition() + { + ReflectionHelper.GetMethodDefinition<MyClass>(mc => mc.GenericMethod<int>()).Should().Be(typeof (MyClass).GetMethod("GenericMethod").GetGenericMethodDefinition()); + } + + [Test] + public void WhenNoGenericMethodOfClassThenReturnDefinition() + { + ReflectionHelper.GetMethodDefinition<MyClass>(mc => mc.NoGenericMethod()).Should().Be(typeof(MyClass).GetMethod("NoGenericMethod")); + } + + [Test] + public void WhenStaticGenericMethodThenReturnGenericDefinition() + { + ReflectionHelper.GetMethodDefinition(() => Enumerable.All<int>(null, null)).Should().Be(typeof(Enumerable).GetMethod("All").GetGenericMethodDefinition()); + } + + [Test] + public void WhenStaticNoGenericMethodThenReturnDefinition() + { + ReflectionHelper.GetMethodDefinition(() => string.Join(null, null)).Should().Be(typeof(string).GetMethod("Join", new []{typeof(string), typeof(string[])})); + } + + [Test] + public void WhenGetPropertyThenReturnPropertyInfo() + { + ReflectionHelper.GetProperty<MyClass, string>(mc => mc.BaseProperty).Should().Be(typeof(MyClass).GetProperty("BaseProperty")); + } + + [Test] + public void WhenGetPropertyForBoolThenReturnPropertyInfo() + { + ReflectionHelper.GetProperty<MyClass, bool>(mc => mc.BaseBool).Should().Be(typeof(MyClass).GetProperty("BaseBool")); + } + } +} \ 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: <ric...@us...> - 2010-07-31 08:30:24
|
Revision: 5083 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5083&view=rev Author: ricbrown Date: 2010-07-31 08:30:17 +0000 (Sat, 31 Jul 2010) Log Message: ----------- Returned AbstractCriterion from LambdaRestrictionBuilder to allow operator overloading syntax. Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Criterion/AbstractEmptinessExpression.cs trunk/nhibernate/src/NHibernate/Criterion/Lambda/LambdaRestrictionBuilder.cs trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/RestrictionsFixture.cs Modified: trunk/nhibernate/src/NHibernate/Criterion/AbstractEmptinessExpression.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Criterion/AbstractEmptinessExpression.cs 2010-07-30 17:03:00 UTC (rev 5082) +++ trunk/nhibernate/src/NHibernate/Criterion/AbstractEmptinessExpression.cs 2010-07-31 08:30:17 UTC (rev 5083) @@ -10,7 +10,7 @@ namespace NHibernate.Criterion { [Serializable] - public abstract class AbstractEmptinessExpression : ICriterion + public abstract class AbstractEmptinessExpression : AbstractCriterion { private readonly TypedValue[] NO_VALUES = new TypedValue[0]; private readonly string propertyName; @@ -23,19 +23,17 @@ this.propertyName = propertyName; } - public TypedValue[] GetTypedValues(ICriteria criteria, ICriteriaQuery criteriaQuery) + public override TypedValue[] GetTypedValues(ICriteria criteria, ICriteriaQuery criteriaQuery) { return NO_VALUES; } - public abstract IProjection[] GetProjections(); - public override sealed string ToString() { return propertyName + (ExcludeEmpty ? " is not empty" : " is empty"); } - public SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery, IDictionary<string, IFilter> enabledFilters) + public override SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery, IDictionary<string, IFilter> enabledFilters) { string entityName = criteriaQuery.GetEntityName(criteria, propertyName); string actualPropertyName = criteriaQuery.GetPropertyName(propertyName); @@ -92,54 +90,5 @@ throw new QueryException("collection role not found: " + role, e); } } - - #region Operator Overloading - - public static AbstractCriterion operator &(AbstractEmptinessExpression lhs, AbstractEmptinessExpression rhs) - { - return new AndExpression(lhs, rhs); - } - - public static AbstractCriterion operator |(AbstractEmptinessExpression lhs, AbstractEmptinessExpression rhs) - { - return new OrExpression(lhs, rhs); - } - - - public static AbstractCriterion operator &(AbstractEmptinessExpression lhs, AbstractCriterion rhs) - { - return new AndExpression(lhs, rhs); - } - - public static AbstractCriterion operator |(AbstractEmptinessExpression lhs, AbstractCriterion rhs) - { - return new OrExpression(lhs, rhs); - } - - - public static AbstractCriterion operator !(AbstractEmptinessExpression crit) - { - return new NotExpression(crit); - } - - /// <summary> - /// See here for details: - /// http://steve.emxsoftware.com/NET/Overloading+the++and++operators - /// </summary> - public static bool operator false(AbstractEmptinessExpression criteria) - { - return false; - } - - /// <summary> - /// See here for details: - /// http://steve.emxsoftware.com/NET/Overloading+the++and++operators - /// </summary> - public static bool operator true(AbstractEmptinessExpression criteria) - { - return false; - } - - #endregion } } Modified: trunk/nhibernate/src/NHibernate/Criterion/Lambda/LambdaRestrictionBuilder.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Criterion/Lambda/LambdaRestrictionBuilder.cs 2010-07-30 17:03:00 UTC (rev 5082) +++ trunk/nhibernate/src/NHibernate/Criterion/Lambda/LambdaRestrictionBuilder.cs 2010-07-31 08:30:17 UTC (rev 5083) @@ -37,7 +37,7 @@ private string propertyName; private bool isNot; - private ICriterion Process(ICriterion criterion) + private AbstractCriterion Process(AbstractCriterion criterion) { if (isNot) return Restrictions.Not(criterion); @@ -73,7 +73,7 @@ /// <summary> /// Apply an "in" constraint to the named property /// </summary> - public ICriterion IsIn(ICollection values) + public AbstractCriterion IsIn(ICollection values) { return Process(Restrictions.In(propertyName, values)); } @@ -81,7 +81,7 @@ /// <summary> /// Apply an "in" constraint to the named property /// </summary> - public ICriterion IsIn(object[] values) + public AbstractCriterion IsIn(object[] values) { return Process(Restrictions.In(propertyName, values)); } @@ -89,7 +89,7 @@ /// <summary> /// Apply an "in" constraint to the named property /// </summary> - public ICriterion IsInG<T>(ICollection<T> values) + public AbstractCriterion IsInG<T>(ICollection<T> values) { return Process(Restrictions.InG(propertyName, values)); } @@ -97,7 +97,7 @@ /// <summary> /// A case-insensitive "like", similar to Postgres "ilike" operator /// </summary> - public ICriterion IsInsensitiveLike(object value) + public AbstractCriterion IsInsensitiveLike(object value) { return Process(Restrictions.InsensitiveLike(propertyName, value)); } @@ -105,7 +105,7 @@ /// <summary> /// A case-insensitive "like", similar to Postgres "ilike" operator /// </summary> - public ICriterion IsInsensitiveLike(string value, MatchMode matchMode) + public AbstractCriterion IsInsensitiveLike(string value, MatchMode matchMode) { return Process(Restrictions.InsensitiveLike(propertyName, value, matchMode)); } @@ -113,7 +113,7 @@ /// <summary> /// Apply an "is empty" constraint to the named property /// </summary> - public ICriterion IsEmpty + public AbstractCriterion IsEmpty { get { return Process(Restrictions.IsEmpty(propertyName)); } } @@ -121,7 +121,7 @@ /// <summary> /// Apply a "not is empty" constraint to the named property /// </summary> - public ICriterion IsNotEmpty + public AbstractCriterion IsNotEmpty { get { return Process(Restrictions.IsNotEmpty(propertyName)); } } @@ -129,7 +129,7 @@ /// <summary> /// Apply an "is null" constraint to the named property /// </summary> - public ICriterion IsNull + public AbstractCriterion IsNull { get { return Process(Restrictions.IsNull(propertyName)); } } @@ -137,7 +137,7 @@ /// <summary> /// Apply an "not is null" constraint to the named property /// </summary> - public ICriterion IsNotNull + public AbstractCriterion IsNotNull { get { return Process(Restrictions.IsNotNull(propertyName)); } } @@ -145,7 +145,7 @@ /// <summary> /// Apply a "like" constraint to the named property /// </summary> - public ICriterion IsLike(object value) + public AbstractCriterion IsLike(object value) { return Process(Restrictions.Like(propertyName, value)); } @@ -153,7 +153,7 @@ /// <summary> /// Apply a "like" constraint to the named property /// </summary> - public ICriterion IsLike(string value, MatchMode matchMode) + public AbstractCriterion IsLike(string value, MatchMode matchMode) { return Process(Restrictions.Like(propertyName, value, matchMode)); } @@ -161,7 +161,7 @@ /// <summary> /// Apply a "like" constraint to the named property /// </summary> - public ICriterion IsLike(string value, MatchMode matchMode, char? escapeChar) + public AbstractCriterion IsLike(string value, MatchMode matchMode, char? escapeChar) { return Process(Restrictions.Like(propertyName, value, matchMode, escapeChar)); } Modified: trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/RestrictionsFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/RestrictionsFixture.cs 2010-07-30 17:03:00 UTC (rev 5082) +++ trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/RestrictionsFixture.cs 2010-07-31 08:30:17 UTC (rev 5083) @@ -41,6 +41,7 @@ .Add(Restrictions.Between("Age", 18, 65)) .Add(Restrictions.Between("personAlias.Age", 18, 65)) .Add(Restrictions.Not(Restrictions.Between("personAlias.Age", 10, 20))) + .Add(!Restrictions.In("Name", new string[] { "name4" })) .Add(Restrictions.In("Name", new string[] { "name1", "name2", "name3" })) .Add(Restrictions.In("Name", new ArrayList() { "name1", "name2", "name3" })) .Add(Restrictions.InG<int>("Age", new int[] { 1, 2, 3 })) @@ -64,6 +65,7 @@ .Where(Restrictions.On<Person>(p => p.Age).IsBetween(18).And(65)) .And(Restrictions.On(() => personAlias.Age).IsBetween(18).And(65)) .And(Restrictions.On(() => personAlias.Age).Not.IsBetween(10).And(20)) + .And(!Restrictions.On<Person>(p => p.Name).IsIn(new string[] { "name4" })) .And(Restrictions.On<Person>(p => p.Name).IsIn(new string[] { "name1", "name2", "name3" })) .And(Restrictions.On<Person>(p => p.Name).IsIn(new ArrayList() { "name1", "name2", "name3" })) .And(Restrictions.On<Person>(p => p.Age).IsInG<int>(new int[] { 1, 2, 3 })) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2010-07-31 11:38:11
|
Revision: 5084 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5084&view=rev Author: fabiomaulo Date: 2010-07-31 11:38:05 +0000 (Sat, 31 Jul 2010) Log Message: ----------- Added extension to check if a method is declared by an interface. Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Linq/EnumerableHelper.cs trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectionHelperIsMethodOfTests.cs Modified: trunk/nhibernate/src/NHibernate/Linq/EnumerableHelper.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/EnumerableHelper.cs 2010-07-31 08:30:17 UTC (rev 5083) +++ trunk/nhibernate/src/NHibernate/Linq/EnumerableHelper.cs 2010-07-31 11:38:05 UTC (rev 5084) @@ -55,6 +55,58 @@ } return ((MemberExpression)property.Body).Member; } + + /// <summary> + /// Check if a method is declared in a given <see cref="System.Type"/>. + /// </summary> + /// <param name="source">The method to check.</param> + /// <param name="realDeclaringType">The where the method is really declared.</param> + /// <returns>True if the method is an implementation of the method declared in <paramref name="realDeclaringType"/>; false otherwise. </returns> + public static bool IsMethodOf(this MethodInfo source, System.Type realDeclaringType) + { + if (source == null) + { + throw new ArgumentNullException("source"); + } + if (realDeclaringType == null) + { + throw new ArgumentNullException("realDeclaringType"); + } + var methodDeclaringType = source.DeclaringType; + if(realDeclaringType.Equals(methodDeclaringType)) + { + return true; + } + if (methodDeclaringType.IsGenericType && !methodDeclaringType.IsGenericTypeDefinition && + realDeclaringType.Equals(methodDeclaringType.GetGenericTypeDefinition())) + { + return true; + } + if (realDeclaringType.IsInterface) + { + var declaringTypeInterfaces = methodDeclaringType.GetInterfaces(); + if(declaringTypeInterfaces.Contains(realDeclaringType)) + { + var methodsMap = methodDeclaringType.GetInterfaceMap(realDeclaringType); + if(methodsMap.TargetMethods.Contains(source)) + { + return true; + } + } + if (realDeclaringType.IsGenericTypeDefinition) + { + bool implements = declaringTypeInterfaces + .Where(t => t.IsGenericType && t.GetGenericTypeDefinition().Equals(realDeclaringType)) + .Select(implementedGenericInterface => methodDeclaringType.GetInterfaceMap(implementedGenericInterface)) + .Any(methodsMap => methodsMap.TargetMethods.Contains(source)); + if (implements) + { + return true; + } + } + } + return false; + } } // TODO rename / remove - reflection helper above is better Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-07-31 08:30:17 UTC (rev 5083) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-07-31 11:38:05 UTC (rev 5084) @@ -440,6 +440,7 @@ <Compile Include="Linq\QueryCacheableTests.cs" /> <Compile Include="Linq\QueryReuseTests.cs" /> <Compile Include="Linq\ReadonlyTestCase.cs" /> + <Compile Include="UtilityTest\ReflectionHelperIsMethodOfTests.cs" /> <Compile Include="UtilityTest\ReflectionHelperTest.cs" /> <Compile Include="Linq\RegresstionTests.cs" /> <Compile Include="Linq\SelectionTests.cs" /> Added: trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectionHelperIsMethodOfTests.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectionHelperIsMethodOfTests.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/UtilityTest/ReflectionHelperIsMethodOfTests.cs 2010-07-31 11:38:05 UTC (rev 5084) @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using NHibernate.Linq; +using NUnit.Framework; +using SharpTestsEx; + +namespace NHibernate.Test.UtilityTest +{ + public class ReflectionHelperIsMethodOfTests + { + [Test] + public void WhenNullMethodInfoThenThrows() + { + ((MethodInfo) null).Executing(mi => mi.IsMethodOf(typeof (Object))).Throws<ArgumentNullException>(); + } + + [Test] + public void WhenNullTypeThenThrows() + { + ReflectionHelper.GetMethodDefinition<List<int>>(t => t.Contains(5)).Executing(mi => mi.IsMethodOf(null)).Throws<ArgumentNullException>(); + } + + [Test] + public void WhenDeclaringTypeMatchThenTrue() + { + ReflectionHelper.GetMethodDefinition<List<int>>(t => t.Contains(5)).IsMethodOf(typeof(List<int>)).Should().Be.True(); + } + + private class MyCollection: List<int> + { + + } + + [Test] + public void WhenCustomTypeMatchThenTrue() + { + ReflectionHelper.GetMethodDefinition<MyCollection>(t => t.Contains(5)).IsMethodOf(typeof(List<int>)).Should().Be.True(); + } + + [Test] + public void WhenTypeIsGenericDefinitionAndMatchThenTrue() + { + ReflectionHelper.GetMethodDefinition<List<int>>(t => t.Contains(5)).IsMethodOf(typeof(List<>)).Should().Be.True(); + } + + [Test] + public void WhenTypeIsGenericImplementedInterfaceAndMatchThenTrue() + { + var containsMethodDefinition = ReflectionHelper.GetMethodDefinition<List<int>>(t => t.Contains(5)); + containsMethodDefinition.IsMethodOf(typeof(ICollection<int>)).Should().Be.True(); + } + + [Test] + public void WhenTypeIsGenericImplementedInterfaceAndMatchGenericInterfaceDefinitionThenTrue() + { + var containsMethodDefinition = ReflectionHelper.GetMethodDefinition<List<int>>(t => t.Contains(5)); + containsMethodDefinition.IsMethodOf(typeof(ICollection<>)).Should().Be.True(); + } + + [Test] + public void WhenNoMatchThenFalse() + { + ReflectionHelper.GetMethodDefinition<List<int>>(t => t.Contains(5)).IsMethodOf(typeof(IEnumerable<>)).Should().Be.False(); + } + + private abstract class MyAbstractClass<T> + { + public abstract T MyMethod(); + } + + private class MyClass : MyAbstractClass<int> + { + public override int MyMethod() {return 0;} + } + + [Test] + public void WhenTypeIsGenericImplementedAbstractAndMatchThenTrue() + { + var containsMethodDefinition = ReflectionHelper.GetMethodDefinition<MyClass>(t => t.MyMethod()); + containsMethodDefinition.IsMethodOf(typeof(MyAbstractClass<int>)).Should().Be.True(); + } + + [Test] + public void WhenTypeIsGenericImplementedAbstractAndMatchGenericInterfaceDefinitionThenTrue() + { + var containsMethodDefinition = ReflectionHelper.GetMethodDefinition<MyClass>(t => t.MyMethod()); + containsMethodDefinition.IsMethodOf(typeof(MyAbstractClass<>)).Should().Be.True(); + } + } +} \ 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...> - 2010-07-31 14:00:06
|
Revision: 5085 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5085&view=rev Author: fabiomaulo Date: 2010-07-31 13:59:59 +0000 (Sat, 31 Jul 2010) Log Message: ----------- Refactoring in order to allow/show a more grained of ILinqToHqlGeneratorsRegistry; In this way the user can choose what reuse, what replace and what override. Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Linq/Functions/DefaultLinqToHqlGeneratorsRegistry.cs trunk/nhibernate/src/NHibernate/Linq/Functions/ILinqToHqlGeneratorsRegistry.cs trunk/nhibernate/src/NHibernate/Linq/Functions/QueryableGenerator.cs trunk/nhibernate/src/NHibernate/Linq/Functions/StandardLinqExtensionMethodGenerator.cs trunk/nhibernate/src/NHibernate/Linq/Functions/StringGenerator.cs trunk/nhibernate/src/NHibernate/NHibernate.csproj trunk/nhibernate/src/NHibernate.Test/Linq/LinqToHqlGeneratorsRegistryFactoryTest.cs Added Paths: ----------- trunk/nhibernate/src/NHibernate/Linq/Functions/DateTimePropertiesHqlGenerator.cs trunk/nhibernate/src/NHibernate/Linq/Functions/IRuntimeMethodHqlGenerator.cs trunk/nhibernate/src/NHibernate/Linq/Functions/LinqToHqlGeneratorsRegistryExtensions.cs Removed Paths: ------------- trunk/nhibernate/src/NHibernate/Linq/Functions/BaseHqlGeneratorForType.cs trunk/nhibernate/src/NHibernate/Linq/Functions/DateTimeGenerator.cs trunk/nhibernate/src/NHibernate/Linq/Functions/IHqlGeneratorForType.cs Deleted: trunk/nhibernate/src/NHibernate/Linq/Functions/BaseHqlGeneratorForType.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/BaseHqlGeneratorForType.cs 2010-07-31 11:38:05 UTC (rev 5084) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/BaseHqlGeneratorForType.cs 2010-07-31 13:59:59 UTC (rev 5085) @@ -1,45 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace NHibernate.Linq.Functions -{ - public abstract class BaseHqlGeneratorForType : IHqlGeneratorForType - { - protected readonly List<IHqlGeneratorForMethod> MethodRegistry = new List<IHqlGeneratorForMethod>(); - protected readonly List<IHqlGeneratorForProperty> PropertyRegistry = new List<IHqlGeneratorForProperty>(); - - #region IHqlGeneratorForType Members - - public void Register(ILinqToHqlGeneratorsRegistry functionRegistry) - { - foreach (IHqlGeneratorForMethod generator in MethodRegistry) - { - foreach (MethodInfo method in generator.SupportedMethods) - { - functionRegistry.RegisterGenerator(method, generator); - } - } - - foreach (IHqlGeneratorForProperty generator in PropertyRegistry) - { - foreach (MemberInfo property in generator.SupportedProperties) - { - functionRegistry.RegisterGenerator(property, generator); - } - } - } - - public virtual bool SupportsMethod(MethodInfo method) - { - return false; - } - - public virtual IHqlGeneratorForMethod GetMethodGenerator(MethodInfo method) - { - throw new NotSupportedException(); - } - - #endregion - } -} \ No newline at end of file Deleted: trunk/nhibernate/src/NHibernate/Linq/Functions/DateTimeGenerator.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/DateTimeGenerator.cs 2010-07-31 11:38:05 UTC (rev 5084) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/DateTimeGenerator.cs 2010-07-31 13:59:59 UTC (rev 5085) @@ -1,39 +0,0 @@ -using System; -using System.Linq.Expressions; -using System.Reflection; -using NHibernate.Hql.Ast; -using NHibernate.Linq.Visitors; - -namespace NHibernate.Linq.Functions -{ - public class DateTimeGenerator : BaseHqlGeneratorForType - { - public DateTimeGenerator() - { - PropertyRegistry.Add(new DatePartGenerator()); - } - - public class DatePartGenerator : BaseHqlGeneratorForProperty - { - public DatePartGenerator() - { - SupportedProperties = new[] - { - ReflectionHelper.GetProperty((DateTime x) => x.Year), - ReflectionHelper.GetProperty((DateTime x) => x.Month), - ReflectionHelper.GetProperty((DateTime x) => x.Day), - ReflectionHelper.GetProperty((DateTime x) => x.Hour), - ReflectionHelper.GetProperty((DateTime x) => x.Minute), - ReflectionHelper.GetProperty((DateTime x) => x.Second), - ReflectionHelper.GetProperty((DateTime x) => x.Date), - }; - } - - public override HqlTreeNode BuildHql(MemberInfo member, Expression expression, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) - { - return treeBuilder.MethodCall(member.Name.ToLowerInvariant(), - visitor.Visit(expression).AsExpression()); - } - } - } -} \ No newline at end of file Copied: trunk/nhibernate/src/NHibernate/Linq/Functions/DateTimePropertiesHqlGenerator.cs (from rev 5083, trunk/nhibernate/src/NHibernate/Linq/Functions/DateTimeGenerator.cs) =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/DateTimePropertiesHqlGenerator.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/DateTimePropertiesHqlGenerator.cs 2010-07-31 13:59:59 UTC (rev 5085) @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq.Expressions; +using System.Reflection; +using NHibernate.Hql.Ast; +using NHibernate.Linq.Visitors; + +namespace NHibernate.Linq.Functions +{ + public class DateTimePropertiesHqlGenerator : IHqlGeneratorForProperty + { + private readonly MemberInfo[] supportedProperties; + + public DateTimePropertiesHqlGenerator() + { + supportedProperties = new[] + { + ReflectionHelper.GetProperty((DateTime x) => x.Year), + ReflectionHelper.GetProperty((DateTime x) => x.Month), + ReflectionHelper.GetProperty((DateTime x) => x.Day), + ReflectionHelper.GetProperty((DateTime x) => x.Hour), + ReflectionHelper.GetProperty((DateTime x) => x.Minute), + ReflectionHelper.GetProperty((DateTime x) => x.Second), + ReflectionHelper.GetProperty((DateTime x) => x.Date), + }; + } + + public IEnumerable<MemberInfo> SupportedProperties + { + get + { + return supportedProperties; + } + } + + public HqlTreeNode BuildHql(MemberInfo member, Expression expression, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) + { + return treeBuilder.MethodCall(member.Name.ToLowerInvariant(), + visitor.Visit(expression).AsExpression()); + } + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Linq/Functions/DefaultLinqToHqlGeneratorsRegistry.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/DefaultLinqToHqlGeneratorsRegistry.cs 2010-07-31 11:38:05 UTC (rev 5084) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/DefaultLinqToHqlGeneratorsRegistry.cs 2010-07-31 13:59:59 UTC (rev 5085) @@ -8,22 +8,37 @@ { private readonly Dictionary<MethodInfo, IHqlGeneratorForMethod> registeredMethods = new Dictionary<MethodInfo, IHqlGeneratorForMethod>(); private readonly Dictionary<MemberInfo, IHqlGeneratorForProperty> registeredProperties = new Dictionary<MemberInfo, IHqlGeneratorForProperty>(); - private readonly List<IHqlGeneratorForType> typeGenerators = new List<IHqlGeneratorForType>(); + private readonly List<IRuntimeMethodHqlGenerator> runtimeMethodHqlGenerators = new List<IRuntimeMethodHqlGenerator>(); public DefaultLinqToHqlGeneratorsRegistry() { - Register(new StandardLinqExtensionMethodGenerator()); - Register(new QueryableGenerator()); - Register(new StringGenerator()); - Register(new DateTimeGenerator()); - Register(new ICollectionGenerator()); + RegisterGenerator(new StandardLinqExtensionMethodGenerator()); + RegisterGenerator(new CollectionContainsRuntimeHqlGenerator()); + + this.Merge(new StartsWithGenerator()); + this.Merge(new EndsWithGenerator()); + this.Merge(new ContainsGenerator()); + this.Merge(new EqualsGenerator()); + this.Merge(new ToUpperLowerGenerator()); + this.Merge(new SubStringGenerator()); + this.Merge(new IndexOfGenerator()); + this.Merge(new ReplaceGenerator()); + this.Merge(new LengthGenerator()); + + this.Merge(new AnyHqlGenerator()); + this.Merge(new AllHqlGenerator()); + this.Merge(new MinHqlGenerator()); + this.Merge(new MaxHqlGenerator()); + this.Merge(new CollectionContainsGenerator()); + + this.Merge(new DateTimePropertiesHqlGenerator()); } - protected bool GetMethodGeneratorForType(MethodInfo method, out IHqlGeneratorForMethod methodGenerator) + protected bool GetRuntimeMethodGenerator(MethodInfo method, out IHqlGeneratorForMethod methodGenerator) { methodGenerator = null; - foreach (var typeGenerator in typeGenerators.Where(typeGenerator => typeGenerator.SupportsMethod(method))) + foreach (var typeGenerator in runtimeMethodHqlGenerators.Where(typeGenerator => typeGenerator.SupportsMethod(method))) { methodGenerator = typeGenerator.GetMethodGenerator(method); return true; @@ -41,7 +56,7 @@ if (registeredMethods.TryGetValue(method, out generator)) return true; // Not that either. Let's query each type generator to see if it can handle it - if (GetMethodGeneratorForType(method, out generator)) return true; + if (GetRuntimeMethodGenerator(method, out generator)) return true; return false; } @@ -61,10 +76,9 @@ registeredProperties.Add(property, generator); } - protected void Register(IHqlGeneratorForType typeMethodGenerator) + public void RegisterGenerator(IRuntimeMethodHqlGenerator generator) { - typeGenerators.Add(typeMethodGenerator); - typeMethodGenerator.Register(this); + runtimeMethodHqlGenerators.Add(generator); } } } \ No newline at end of file Deleted: trunk/nhibernate/src/NHibernate/Linq/Functions/IHqlGeneratorForType.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/IHqlGeneratorForType.cs 2010-07-31 11:38:05 UTC (rev 5084) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/IHqlGeneratorForType.cs 2010-07-31 13:59:59 UTC (rev 5085) @@ -1,11 +0,0 @@ -using System.Reflection; - -namespace NHibernate.Linq.Functions -{ - public interface IHqlGeneratorForType - { - void Register(ILinqToHqlGeneratorsRegistry functionRegistry); - bool SupportsMethod(MethodInfo method); - IHqlGeneratorForMethod GetMethodGenerator(MethodInfo method); - } -} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Linq/Functions/ILinqToHqlGeneratorsRegistry.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/ILinqToHqlGeneratorsRegistry.cs 2010-07-31 11:38:05 UTC (rev 5084) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/ILinqToHqlGeneratorsRegistry.cs 2010-07-31 13:59:59 UTC (rev 5085) @@ -8,5 +8,6 @@ bool TryGetGenerator(MemberInfo property, out IHqlGeneratorForProperty generator); void RegisterGenerator(MethodInfo method, IHqlGeneratorForMethod generator); void RegisterGenerator(MemberInfo property, IHqlGeneratorForProperty generator); + void RegisterGenerator(IRuntimeMethodHqlGenerator generator); } } \ No newline at end of file Added: trunk/nhibernate/src/NHibernate/Linq/Functions/IRuntimeMethodHqlGenerator.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/IRuntimeMethodHqlGenerator.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/IRuntimeMethodHqlGenerator.cs 2010-07-31 13:59:59 UTC (rev 5085) @@ -0,0 +1,10 @@ +using System.Reflection; + +namespace NHibernate.Linq.Functions +{ + public interface IRuntimeMethodHqlGenerator + { + bool SupportsMethod(MethodInfo method); + IHqlGeneratorForMethod GetMethodGenerator(MethodInfo method); + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate/Linq/Functions/LinqToHqlGeneratorsRegistryExtensions.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/LinqToHqlGeneratorsRegistryExtensions.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/LinqToHqlGeneratorsRegistryExtensions.cs 2010-07-31 13:59:59 UTC (rev 5085) @@ -0,0 +1,34 @@ +using System; +using System.Linq; + +namespace NHibernate.Linq.Functions +{ + public static class LinqToHqlGeneratorsRegistryExtensions + { + public static void Merge(this ILinqToHqlGeneratorsRegistry registry, IHqlGeneratorForMethod generator) + { + if (registry == null) + { + throw new ArgumentNullException("registry"); + } + if (generator == null) + { + throw new ArgumentNullException("generator"); + } + Array.ForEach(generator.SupportedMethods.ToArray(), method=> registry.RegisterGenerator(method, generator)); + } + + public static void Merge(this ILinqToHqlGeneratorsRegistry registry, IHqlGeneratorForProperty generator) + { + if (registry == null) + { + throw new ArgumentNullException("registry"); + } + if (generator == null) + { + throw new ArgumentNullException("generator"); + } + Array.ForEach(generator.SupportedProperties.ToArray(), property => registry.RegisterGenerator(property, generator)); + } + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Linq/Functions/QueryableGenerator.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/QueryableGenerator.cs 2010-07-31 11:38:05 UTC (rev 5084) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/QueryableGenerator.cs 2010-07-31 13:59:59 UTC (rev 5085) @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Linq.Expressions; @@ -9,193 +8,165 @@ namespace NHibernate.Linq.Functions { - public class QueryableGenerator : BaseHqlGeneratorForType - { - public QueryableGenerator() - { - // TODO - could use reflection - MethodRegistry.Add(new AnyGenerator()); - MethodRegistry.Add(new AllGenerator()); - MethodRegistry.Add(new MinGenerator()); - MethodRegistry.Add(new MaxGenerator()); - } + public class AnyHqlGenerator : BaseHqlGeneratorForMethod + { + public AnyHqlGenerator() + { + SupportedMethods = new[] + { + ReflectionHelper.GetMethodDefinition(() => Queryable.Any<object>(null)), + ReflectionHelper.GetMethodDefinition(() => Queryable.Any<object>(null, null)), + ReflectionHelper.GetMethodDefinition(() => Enumerable.Any<object>(null)), + ReflectionHelper.GetMethodDefinition(() => Enumerable.Any<object>(null, null)) + }; + } - class AnyGenerator : BaseHqlGeneratorForMethod - { - public AnyGenerator() - { - SupportedMethods = new[] - { - ReflectionHelper.GetMethodDefinition(() => Queryable.Any<object>(null)), - ReflectionHelper.GetMethodDefinition(() => Queryable.Any<object>(null, null)), - ReflectionHelper.GetMethodDefinition(() => Enumerable.Any<object>(null)), - ReflectionHelper.GetMethodDefinition(() => Enumerable.Any<object>(null, null)) - }; - } + public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) + { + HqlAlias alias = null; + HqlWhere where = null; - public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) - { - HqlAlias alias = null; - HqlWhere where = null; + if (arguments.Count > 1) + { + var expr = (LambdaExpression) arguments[1]; - if (arguments.Count > 1) - { - var expr = (LambdaExpression)arguments[1]; + alias = treeBuilder.Alias(expr.Parameters[0].Name); + where = treeBuilder.Where(visitor.Visit(arguments[1]).AsExpression()); + } - alias = treeBuilder.Alias(expr.Parameters[0].Name); - where = treeBuilder.Where(visitor.Visit(arguments[1]).AsExpression()); - } + return treeBuilder.Exists( + treeBuilder.Query( + treeBuilder.SelectFrom( + treeBuilder.From( + treeBuilder.Range( + visitor.Visit(arguments[0]), + alias) + ) + ), + where)); + } + } - return treeBuilder.Exists( - treeBuilder.Query( - treeBuilder.SelectFrom( - treeBuilder.From( - treeBuilder.Range( - visitor.Visit(arguments[0]), - alias) - ) - ), - where)); - } - } + public class AllHqlGenerator : BaseHqlGeneratorForMethod + { + public AllHqlGenerator() + { + SupportedMethods = new[] + { + ReflectionHelper.GetMethodDefinition(() => Queryable.All<object>(null, null)), + ReflectionHelper.GetMethodDefinition(() => Enumerable.All<object>(null, null)) + }; + } - class AllGenerator : BaseHqlGeneratorForMethod - { - public AllGenerator() - { - SupportedMethods = new[] - { - ReflectionHelper.GetMethodDefinition(() => Queryable.All<object>(null, null)), - ReflectionHelper.GetMethodDefinition(() => Enumerable.All<object>(null, null)) - }; - } + public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) + { + // All has two arguments. Arg 1 is the source and arg 2 is the predicate + var predicate = (LambdaExpression) arguments[1]; - public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) - { - // All has two arguments. Arg 1 is the source and arg 2 is the predicate - var predicate = (LambdaExpression)arguments[1]; + return treeBuilder.BooleanNot( + treeBuilder.Exists( + treeBuilder.Query( + treeBuilder.SelectFrom( + treeBuilder.From( + treeBuilder.Range( + visitor.Visit(arguments[0]), + treeBuilder.Alias(predicate.Parameters[0].Name)) + ) + ), + treeBuilder.Where( + treeBuilder.BooleanNot(visitor.Visit(arguments[1]).AsBooleanExpression()) + ) + ) + ) + ); + } + } - return treeBuilder.BooleanNot( - treeBuilder.Exists( - treeBuilder.Query( - treeBuilder.SelectFrom( - treeBuilder.From( - treeBuilder.Range( - visitor.Visit(arguments[0]), - treeBuilder.Alias(predicate.Parameters[0].Name)) - ) - ), - treeBuilder.Where( - treeBuilder.BooleanNot(visitor.Visit(arguments[1]).AsBooleanExpression()) - ) - ) - ) - ); - } - } + public class MinHqlGenerator : BaseHqlGeneratorForMethod + { + public MinHqlGenerator() + { + SupportedMethods = new[] + { + ReflectionHelper.GetMethodDefinition(() => Queryable.Min<object>(null)), + ReflectionHelper.GetMethodDefinition(() => Enumerable.Min<object>(null)) + }; + } - class MinGenerator : BaseHqlGeneratorForMethod - { - public MinGenerator() - { - SupportedMethods = new[] - { - ReflectionHelper.GetMethodDefinition(() => Queryable.Min<object>(null)), - ReflectionHelper.GetMethodDefinition(() => Enumerable.Min<object>(null)) - }; - } + public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) + { + return treeBuilder.Min(visitor.Visit(arguments[1]).AsExpression()); + } + } - public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) - { - return treeBuilder.Min(visitor.Visit(arguments[1]).AsExpression()); - } - } + public class MaxHqlGenerator : BaseHqlGeneratorForMethod + { + public MaxHqlGenerator() + { + SupportedMethods = new[] + { + ReflectionHelper.GetMethodDefinition(() => Queryable.Max<object>(null)), + ReflectionHelper.GetMethodDefinition(() => Enumerable.Max<object>(null)) + }; + } - class MaxGenerator : BaseHqlGeneratorForMethod - { - public MaxGenerator() - { - SupportedMethods = new[] - { - ReflectionHelper.GetMethodDefinition(() => Queryable.Max<object>(null)), - ReflectionHelper.GetMethodDefinition(() => Enumerable.Max<object>(null)) - }; - } + public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) + { + return treeBuilder.Max(visitor.Visit(arguments[1]).AsExpression()); + } + } - public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) - { - return treeBuilder.Max(visitor.Visit(arguments[1]).AsExpression()); - } - } - } + public class CollectionContainsRuntimeHqlGenerator : IRuntimeMethodHqlGenerator + { + private readonly IHqlGeneratorForMethod containsGenerator = new CollectionContainsGenerator(); - public class ICollectionGenerator : BaseHqlGeneratorForType - { - public ICollectionGenerator() - { - // TODO - could use reflection - MethodRegistry.Add(new ContainsGenerator()); - } + #region IRuntimeMethodHqlGenerator Members - public override bool SupportsMethod(MethodInfo method) - { - var declaringType = method.DeclaringType; + public bool SupportsMethod(MethodInfo method) + { + // the check about the name is to make things a little be fasters + return method != null && method.Name == "Contains" && method.IsMethodOf(typeof(ICollection<>)); + } - if (declaringType.IsGenericType) - { - if (declaringType.GetGenericTypeDefinition() == typeof(ICollection<>) || - declaringType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) - { - if (method.Name == "Contains") - { - return true; - } - } - } + public IHqlGeneratorForMethod GetMethodGenerator(MethodInfo method) + { + return containsGenerator; + } - return false; - } + #endregion + } - public override IHqlGeneratorForMethod GetMethodGenerator(MethodInfo method) - { - // TODO - ick - if (method.Name == "Contains") - { - return new ContainsGenerator(); - } + public class CollectionContainsGenerator : BaseHqlGeneratorForMethod + { + public CollectionContainsGenerator() + { + SupportedMethods = new[] + { + ReflectionHelper.GetMethodDefinition(() => Queryable.Contains<object>(null, null)), + ReflectionHelper.GetMethodDefinition(() => Enumerable.Contains<object>(null, null)) + }; + } - throw new NotSupportedException(method.Name); - } + public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) + { + // TODO - alias generator + HqlAlias alias = treeBuilder.Alias("x"); - class ContainsGenerator : BaseHqlGeneratorForMethod - { - public ContainsGenerator() - { - SupportedMethods = new MethodInfo[0]; - } + ParameterExpression param = Expression.Parameter(targetObject.Type, "x"); + HqlWhere where = treeBuilder.Where(visitor.Visit(Expression.Lambda( + Expression.Equal(param, arguments[0]), param)) + .AsExpression()); - public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) - { - // TODO - alias generator - var alias = treeBuilder.Alias("x"); - - var param = Expression.Parameter(targetObject.Type, "x"); - var where = treeBuilder.Where(visitor.Visit(Expression.Lambda( - Expression.Equal(param, arguments[0]), param)) - .AsExpression()); - - return treeBuilder.Exists( - treeBuilder.Query( - treeBuilder.SelectFrom( - treeBuilder.From( - treeBuilder.Range( - visitor.Visit(targetObject), - alias) - ) - ), - where)); - } - } - - } + return treeBuilder.Exists( + treeBuilder.Query( + treeBuilder.SelectFrom( + treeBuilder.From( + treeBuilder.Range( + visitor.Visit(targetObject), + alias) + ) + ), + where)); + } + } } \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Linq/Functions/StandardLinqExtensionMethodGenerator.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/StandardLinqExtensionMethodGenerator.cs 2010-07-31 11:38:05 UTC (rev 5084) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/StandardLinqExtensionMethodGenerator.cs 2010-07-31 13:59:59 UTC (rev 5085) @@ -8,15 +8,10 @@ namespace NHibernate.Linq.Functions { - public class StandardLinqExtensionMethodGenerator : IHqlGeneratorForType + public class StandardLinqExtensionMethodGenerator : IRuntimeMethodHqlGenerator { - #region IHqlGeneratorForType Members + #region IRuntimeMethodHqlGenerator Members - public void Register(ILinqToHqlGeneratorsRegistry functionRegistry) - { - // nothing to do - } - public bool SupportsMethod(MethodInfo method) { return method.GetCustomAttributes(typeof (LinqExtensionMethodAttribute), false).Any(); @@ -41,21 +36,21 @@ public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) { - var args = visitor.Visit(targetObject) - .Union(arguments.Select(a => visitor.Visit(a))) - .Cast<HqlExpression>(); + IEnumerable<HqlExpression> args = visitor.Visit(targetObject) + .Union(arguments.Select(a => visitor.Visit(a))) + .Cast<HqlExpression>(); return treeBuilder.MethodCall(_name, args); } } - static class UnionExtension + internal static class UnionExtension { public static IEnumerable<HqlTreeNode> Union(this HqlTreeNode first, IEnumerable<HqlTreeNode> rest) { yield return first; - foreach (var x in rest) + foreach (HqlTreeNode x in rest) { yield return x; } Modified: trunk/nhibernate/src/NHibernate/Linq/Functions/StringGenerator.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Linq/Functions/StringGenerator.cs 2010-07-31 11:38:05 UTC (rev 5084) +++ trunk/nhibernate/src/NHibernate/Linq/Functions/StringGenerator.cs 2010-07-31 13:59:59 UTC (rev 5085) @@ -6,204 +6,187 @@ namespace NHibernate.Linq.Functions { - public class StringGenerator : BaseHqlGeneratorForType - { - public StringGenerator() - { - // TODO - could use reflection - MethodRegistry.Add(new StartsWithGenerator()); - MethodRegistry.Add(new EndsWithGenerator()); - MethodRegistry.Add(new ContainsGenerator()); - MethodRegistry.Add(new EqualsGenerator()); - MethodRegistry.Add(new ToUpperLowerGenerator()); - MethodRegistry.Add(new SubStringGenerator()); - MethodRegistry.Add(new IndexOfGenerator()); - MethodRegistry.Add(new ReplaceGenerator()); + public class LengthGenerator : BaseHqlGeneratorForProperty + { + public LengthGenerator() + { + SupportedProperties = new[] { ReflectionHelper.GetProperty((string x) => x.Length) }; + } - PropertyRegistry.Add(new LengthGenerator()); - } + public override HqlTreeNode BuildHql(MemberInfo member, Expression expression, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) + { + return treeBuilder.MethodCall("length", visitor.Visit(expression).AsExpression()); + } + } - public class LengthGenerator : BaseHqlGeneratorForProperty - { - public LengthGenerator() - { - SupportedProperties = new[] {ReflectionHelper.GetProperty((string x) => x.Length)}; - } + public class StartsWithGenerator : BaseHqlGeneratorForMethod + { + public StartsWithGenerator() + { + SupportedMethods = new[] { ReflectionHelper.GetMethodDefinition<string>(x => x.StartsWith(null)) }; + } - public override HqlTreeNode BuildHql(MemberInfo member, Expression expression, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) - { - return treeBuilder.MethodCall("length", visitor.Visit(expression).AsExpression()); - } - } + public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) + { + return treeBuilder.Like( + visitor.Visit(targetObject).AsExpression(), + treeBuilder.Concat( + visitor.Visit(arguments[0]).AsExpression(), + treeBuilder.Constant("%"))); + } + } - class StartsWithGenerator : BaseHqlGeneratorForMethod - { - public StartsWithGenerator() - { - SupportedMethods = new[] { ReflectionHelper.GetMethodDefinition<string>(x => x.StartsWith(null)) }; - } + public class EndsWithGenerator : BaseHqlGeneratorForMethod + { + public EndsWithGenerator() + { + SupportedMethods = new[] { ReflectionHelper.GetMethodDefinition<string>(x => x.EndsWith(null)) }; + } - public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) - { - return treeBuilder.Like( - visitor.Visit(targetObject).AsExpression(), - treeBuilder.Concat( - visitor.Visit(arguments[0]).AsExpression(), - treeBuilder.Constant("%"))); - } - } + public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) + { + return treeBuilder.Like( + visitor.Visit(targetObject).AsExpression(), + treeBuilder.Concat( + treeBuilder.Constant("%"), + visitor.Visit(arguments[0]).AsExpression())); + } + } - class EndsWithGenerator : BaseHqlGeneratorForMethod - { - public EndsWithGenerator() - { - SupportedMethods = new[] { ReflectionHelper.GetMethodDefinition<string>(x => x.EndsWith(null)) }; - } + public class ContainsGenerator : BaseHqlGeneratorForMethod + { + public ContainsGenerator() + { + SupportedMethods = new[] { ReflectionHelper.GetMethodDefinition<string>(x => x.Contains(null)) }; + } - public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) - { - return treeBuilder.Like( - visitor.Visit(targetObject).AsExpression(), - treeBuilder.Concat( - treeBuilder.Constant("%"), - visitor.Visit(arguments[0]).AsExpression())); - } - } + public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) + { + return treeBuilder.Like( + visitor.Visit(targetObject).AsExpression(), + treeBuilder.Concat( + treeBuilder.Constant("%"), + visitor.Visit(arguments[0]).AsExpression(), + treeBuilder.Constant("%"))); + } + } - class ContainsGenerator : BaseHqlGeneratorForMethod - { - public ContainsGenerator() - { - SupportedMethods = new[] { ReflectionHelper.GetMethodDefinition<string>(x => x.Contains(null)) }; - } + public class EqualsGenerator : BaseHqlGeneratorForMethod + { + public EqualsGenerator() + { + SupportedMethods = new[] { ReflectionHelper.GetMethodDefinition<string>(x => x.Equals((string)null)) }; + } - public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) - { - return treeBuilder.Like( - visitor.Visit(targetObject).AsExpression(), - treeBuilder.Concat( - treeBuilder.Constant("%"), - visitor.Visit(arguments[0]).AsExpression(), - treeBuilder.Constant("%"))); - } - } + public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) + { + return treeBuilder.Equality( + visitor.Visit(targetObject).AsExpression(), + visitor.Visit(arguments[0]).AsExpression()); + } + } - class EqualsGenerator : BaseHqlGeneratorForMethod - { - public EqualsGenerator() - { - SupportedMethods = new[] { ReflectionHelper.GetMethodDefinition<string>(x => x.Equals((string)null)) }; - } - - public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) - { - return treeBuilder.Equality( - visitor.Visit(targetObject).AsExpression(), - visitor.Visit(arguments[0]).AsExpression()); - } - } - - class ToUpperLowerGenerator : BaseHqlGeneratorForMethod - { - public ToUpperLowerGenerator() - { - SupportedMethods = new[] + public class ToUpperLowerGenerator : BaseHqlGeneratorForMethod + { + public ToUpperLowerGenerator() + { + SupportedMethods = new[] { ReflectionHelper.GetMethodDefinition<string>(x => x.ToUpper()), ReflectionHelper.GetMethodDefinition<string>(x => x.ToUpperInvariant()), ReflectionHelper.GetMethodDefinition<string>(x => x.ToLower()), ReflectionHelper.GetMethodDefinition<string>(x => x.ToLowerInvariant()) }; - } + } - public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) - { - string methodName; + public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) + { + string methodName; - if (((method.Name == "ToUpper") || (method.Name == "ToUpperInvariant"))) - { - methodName = "upper"; - } - else - { - methodName = "lower"; - } + if (((method.Name == "ToUpper") || (method.Name == "ToUpperInvariant"))) + { + methodName = "upper"; + } + else + { + methodName = "lower"; + } - return treeBuilder.MethodCall(methodName, visitor.Visit(targetObject).AsExpression()); - } - } + return treeBuilder.MethodCall(methodName, visitor.Visit(targetObject).AsExpression()); + } + } - class SubStringGenerator : BaseHqlGeneratorForMethod - { - public SubStringGenerator() - { - SupportedMethods = new[] + public class SubStringGenerator : BaseHqlGeneratorForMethod + { + public SubStringGenerator() + { + SupportedMethods = new[] { ReflectionHelper.GetMethodDefinition<string>(s => s.Substring(0)), ReflectionHelper.GetMethodDefinition<string>(s => s.Substring(0, 0)) }; - } - public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) - { - if (arguments.Count == 1) - { - return treeBuilder.MethodCall("substring", visitor.Visit(targetObject).AsExpression(), - treeBuilder.Constant(0), - visitor.Visit(arguments[0]).AsExpression()); - } - - return treeBuilder.MethodCall("substring", visitor.Visit(targetObject).AsExpression(), - visitor.Visit(arguments[0]).AsExpression(), - visitor.Visit(arguments[1]).AsExpression()); - } - } + } + public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) + { + if (arguments.Count == 1) + { + return treeBuilder.MethodCall("substring", visitor.Visit(targetObject).AsExpression(), + treeBuilder.Constant(0), + visitor.Visit(arguments[0]).AsExpression()); + } - class IndexOfGenerator : BaseHqlGeneratorForMethod - { - public IndexOfGenerator() - { - SupportedMethods = new[] + return treeBuilder.MethodCall("substring", visitor.Visit(targetObject).AsExpression(), + visitor.Visit(arguments[0]).AsExpression(), + visitor.Visit(arguments[1]).AsExpression()); + } + } + + public class IndexOfGenerator : BaseHqlGeneratorForMethod + { + public IndexOfGenerator() + { + SupportedMethods = new[] { ReflectionHelper.GetMethodDefinition<string>(s => s.IndexOf(' ')), ReflectionHelper.GetMethodDefinition<string>(s => s.IndexOf(" ")), ReflectionHelper.GetMethodDefinition<string>(s => s.IndexOf(' ', 0)), ReflectionHelper.GetMethodDefinition<string>(s => s.IndexOf(" ", 0)) }; - } - public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) - { - if (arguments.Count == 1) - { - return treeBuilder.MethodCall("locate", - visitor.Visit(arguments[0]).AsExpression(), - visitor.Visit(targetObject).AsExpression(), - treeBuilder.Constant(0)); - } - return treeBuilder.MethodCall("locate", - visitor.Visit(arguments[0]).AsExpression(), - visitor.Visit(targetObject).AsExpression(), - visitor.Visit(arguments[1]).AsExpression()); - } - } + } + public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) + { + if (arguments.Count == 1) + { + return treeBuilder.MethodCall("locate", + visitor.Visit(arguments[0]).AsExpression(), + visitor.Visit(targetObject).AsExpression(), + treeBuilder.Constant(0)); + } + return treeBuilder.MethodCall("locate", + visitor.Visit(arguments[0]).AsExpression(), + visitor.Visit(targetObject).AsExpression(), + visitor.Visit(arguments[1]).AsExpression()); + } + } - class ReplaceGenerator : BaseHqlGeneratorForMethod - { - public ReplaceGenerator() - { - SupportedMethods = new[] + public class ReplaceGenerator : BaseHqlGeneratorForMethod + { + public ReplaceGenerator() + { + SupportedMethods = new[] { ReflectionHelper.GetMethodDefinition<string>(s => s.Replace(' ', ' ')), ReflectionHelper.GetMethodDefinition<string>(s => s.Replace("", "")) }; - } + } - public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) - { - return treeBuilder.MethodCall("replace", - visitor.Visit(targetObject).AsExpression(), - visitor.Visit(arguments[0]).AsExpression(), - visitor.Visit(arguments[1]).AsExpression()); - } - } - } + public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) + { + return treeBuilder.MethodCall("replace", + visitor.Visit(targetObject).AsExpression(), + visitor.Visit(arguments[0]).AsExpression(), + visitor.Visit(arguments[1]).AsExpression()); + } + } + } \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-07-31 11:38:05 UTC (rev 5084) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-07-31 13:59:59 UTC (rev 5085) @@ -655,6 +655,10 @@ <Compile Include="Linq\Expressions\AggregateExpressionNode.cs" /> <Compile Include="Linq\EagerFetchingExtensionMethods.cs" /> <Compile Include="Linq\Functions\ILinqToHqlGeneratorsRegistry.cs" /> + <Compile Include="Linq\Functions\IRuntimeMethodHqlGenerator.cs"> + <SubType>Code</SubType> + </Compile> + <Compile Include="Linq\Functions\LinqToHqlGeneratorsRegistryExtensions.cs" /> <Compile Include="Linq\Functions\LinqToHqlGeneratorsRegistryFactory.cs" /> <Compile Include="Linq\Functions\StandardLinqExtensionMethodGenerator.cs" /> <Compile Include="Linq\LinqExtensionMethodAttribute.cs" /> @@ -683,9 +687,7 @@ <Compile Include="Linq\Functions\IHqlGeneratorForMethod.cs" /> <Compile Include="Linq\Functions\IHqlGeneratorForProperty.cs" /> <Compile Include="Linq\Functions\BaseHqlGeneratorForMethod.cs" /> - <Compile Include="Linq\Functions\BaseHqlGeneratorForType.cs" /> - <Compile Include="Linq\Functions\IHqlGeneratorForType.cs" /> - <Compile Include="Linq\Functions\DateTimeGenerator.cs" /> + <Compile Include="Linq\Functions\DateTimePropertiesHqlGenerator.cs" /> <Compile Include="Linq\Functions\StringGenerator.cs" /> <Compile Include="Linq\Functions\QueryableGenerator.cs" /> <Compile Include="Linq\ReWriters\RemoveUnnecessaryBodyOperators.cs" /> Modified: trunk/nhibernate/src/NHibernate.Test/Linq/LinqToHqlGeneratorsRegistryFactoryTest.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Linq/LinqToHqlGeneratorsRegistryFactoryTest.cs 2010-07-31 11:38:05 UTC (rev 5084) +++ trunk/nhibernate/src/NHibernate.Test/Linq/LinqToHqlGeneratorsRegistryFactoryTest.cs 2010-07-31 13:59:59 UTC (rev 5085) @@ -48,6 +48,11 @@ { throw new NotImplementedException(); } + + public void RegisterGenerator(IRuntimeMethodHqlGenerator generator) + { + throw new NotImplementedException(); + } } } } \ 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...> - 2010-08-01 12:50:07
|
Revision: 5087 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5087&view=rev Author: fabiomaulo Date: 2010-08-01 12:50:01 +0000 (Sun, 01 Aug 2010) Log Message: ----------- Fix NH-2245 (thanks to Harold Howe) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2245/ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2245/Fixture.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2245/Mappings.hbm.xml trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2245/Model.cs Modified: trunk/nhibernate/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs 2010-07-31 14:15:53 UTC (rev 5086) +++ trunk/nhibernate/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs 2010-08-01 12:50:01 UTC (rev 5087) @@ -2367,7 +2367,8 @@ .SetTableName(GetTableName(j)) .SetIdentityColumn(GetKeyColumns(j), IdentifierType); - if (j == 0 && IsVersioned) + // NH: Only add version to where clause if optimistic lock mode is Version + if (j == 0 && IsVersioned && entityMetamodel.OptimisticLockMode == Versioning.OptimisticLock.Version) { deleteBuilder.SetVersionColumn(new[] { VersionColumnName }, VersionType); } @@ -2811,7 +2812,9 @@ return; } - bool useVersion = j == 0 && IsVersioned; + // NH : Only use version if lock mode is Version + bool useVersion = j == 0 && IsVersioned && Versioning.OptimisticLock.Version == entityMetamodel.OptimisticLockMode; + //bool callable = IsDeleteCallable(j); IExpectation expectation = Expectations.AppropriateExpectation(deleteResultCheckStyles[j]); bool useBatch = j == 0 && expectation.CanBeBatched && IsBatchable; Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2245/Fixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2245/Fixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2245/Fixture.cs 2010-08-01 12:50:01 UTC (rev 5087) @@ -0,0 +1,62 @@ +using System; +using NUnit.Framework; +using SharpTestsEx; + +namespace NHibernate.Test.NHSpecificTest.NH2245 +{ + [TestFixture] + public class Fixture : BugTestCase + { + [Test] + public void TestDelete_OptimisticLockNone() + { + Guid id; + + // persist a foo instance + using (ISession session = OpenSession()) + { + using (ITransaction tx = session.BeginTransaction()) + { + var f = new Foo(); + f.Name = "Henry"; + f.Description = "description"; + session.Save(f); + tx.Commit(); + id = f.Id; + } + } + + using (ISession session1 = OpenSession()) + using (ISession session2 = OpenSession()) + { + // Load the foo from two different sessions. Modify the foo in one session to bump the version in the database, and save. + // Then try to delete the foo from the other session. With optimistic lock set to none, this should succeed when the 2245 + // patch is applied to AbstractEntityPersister.cs. Without the patch, NH adds the version to the where clause of the delete + // statement, and the delete fails. + var f1 = session1.Get<Foo>(id); + var f2 = session2.Get<Foo>(id); + + // Bump version + using (ITransaction trans1 = session1.BeginTransaction()) + { + f1.Description = "modified description"; + session1.Update(f1); + trans1.Commit(); + } + + // Now delete from second session + using (ITransaction trans2 = session2.BeginTransaction()) + { + session2.Executing(s=> s.Delete(f2)).NotThrows(); + trans2.Commit(); + } + } + + // Assert that row is really gone + using (ISession assertSession = OpenSession()) + { + Assert.IsNull(assertSession.Get<Foo>(id)); + } + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2245/Mappings.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2245/Mappings.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2245/Mappings.hbm.xml 2010-08-01 12:50:01 UTC (rev 5087) @@ -0,0 +1,15 @@ +<?xml version="1.0"?> + +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" + assembly="NHibernate.Test" + namespace="NHibernate.Test.NHSpecificTest.NH2245"> + + <class name="Foo" table="Foos" optimistic-lock="none"> + <id name="Id"> + <generator class="guid.comb"/> + </id> + <version name="Version" column="Version" /> + <property name="Name" type="String" /> + <property name="Description" type="String"/> + </class> +</hibernate-mapping> Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2245/Model.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2245/Model.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2245/Model.cs 2010-08-01 12:50:01 UTC (rev 5087) @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; + +namespace NHibernate.Test.NHSpecificTest.NH2245 +{ +public class Foo +{ + public Foo() {} + public virtual Guid Id {get; private set;} + public virtual string Name {get; set;} + public virtual string Description {get; set;} + public virtual int Version{get; set;} +} + +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-07-31 14:15:53 UTC (rev 5086) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-08-01 12:50:01 UTC (rev 5087) @@ -440,6 +440,8 @@ <Compile Include="Linq\QueryCacheableTests.cs" /> <Compile Include="Linq\QueryReuseTests.cs" /> <Compile Include="Linq\ReadonlyTestCase.cs" /> + <Compile Include="NHSpecificTest\NH2245\Fixture.cs" /> + <Compile Include="NHSpecificTest\NH2245\Model.cs" /> <Compile Include="UtilityTest\ReflectionHelperIsMethodOfTests.cs" /> <Compile Include="UtilityTest\ReflectionHelperTest.cs" /> <Compile Include="Linq\RegresstionTests.cs" /> @@ -2220,6 +2222,7 @@ <EmbeddedResource Include="DriverTest\SqlServerCeEntity.hbm.xml" /> <EmbeddedResource Include="CollectionTest\NullableValueTypeElementMapFixture.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> + <EmbeddedResource Include="NHSpecificTest\NH2245\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH2257\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH2208\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH2251\Mappings.hbm.xml" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2010-08-01 19:49:18
|
Revision: 5090 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5090&view=rev Author: fabiomaulo Date: 2010-08-01 19:49:12 +0000 (Sun, 01 Aug 2010) Log Message: ----------- Removed obsolete classes (thanks to Patrick Earl) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/NHibernate.csproj Removed Paths: ------------- trunk/nhibernate/src/NHibernate/Impl/DbCommandSet.cs trunk/nhibernate/src/NHibernate/Impl/IDbCommandSet.cs trunk/nhibernate/src/NHibernate/Impl/OracleClientCommandSet.cs trunk/nhibernate/src/NHibernate/Impl/SqlClientCommandSet.cs Deleted: trunk/nhibernate/src/NHibernate/Impl/DbCommandSet.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Impl/DbCommandSet.cs 2010-08-01 17:41:53 UTC (rev 5089) +++ trunk/nhibernate/src/NHibernate/Impl/DbCommandSet.cs 2010-08-01 19:49:12 UTC (rev 5090) @@ -1,133 +0,0 @@ - -using System; -using System.Data; - -namespace NHibernate.Impl -{ - /// <summary> - /// Expose the batch functionality in ADO.Net 2.0 - /// Microsoft in its wisdom decided to make my life hard and mark it internal. - /// Through the use of Reflection and some delegates magic, I opened up the functionality. - /// - /// Observable performance benefits are 50%+ when used, so it is really worth it. - /// </summary> - public abstract class DbCommandSet<TConnection, TCommand> : IDbCommandSet - where TConnection : class, IDbConnection - where TCommand : class, IDbCommand - { - private readonly PropGetter<TCommand> commandGetter; - private readonly AppendCommand doAppend; - private readonly ExecuteNonQueryCommand doExecuteNonQuery; - private readonly DisposeCommand doDispose; - private int countOfCommands; - - protected DbCommandSet() - { - object internalCommandSet = CreateInternalCommandSet(); - commandGetter = - (PropGetter<TCommand>) - Delegate.CreateDelegate(typeof(PropGetter<TCommand>), internalCommandSet, - "get_BatchCommand"); - doAppend = (AppendCommand)Delegate.CreateDelegate(typeof(AppendCommand), internalCommandSet, "Append"); - doExecuteNonQuery = (ExecuteNonQueryCommand) - Delegate.CreateDelegate(typeof(ExecuteNonQueryCommand), - internalCommandSet, "ExecuteNonQuery"); - doDispose = (DisposeCommand)Delegate.CreateDelegate(typeof(DisposeCommand), internalCommandSet, "Dispose"); - } - - protected abstract object CreateInternalCommandSet(); - - /// <summary> - /// Append a command to the batch - /// </summary> - /// <param name="command"></param> - public void Append(IDbCommand command) - { - AssertHasParameters(command); - TCommand sqlCommand = (TCommand)command; - doAppend(sqlCommand); - countOfCommands++; - } - - /// <summary> - /// This is required because SqlClient.SqlCommandSet will throw if - /// the command has no parameters. - /// </summary> - /// <param name="command"></param> - private static void AssertHasParameters(IDbCommand command) - { - if (command.Parameters.Count == 0) - { - throw new ArgumentException("A command in SqlCommandSet must have parameters. You can't pass hardcoded sql strings."); - } - } - - - /// <summary> - /// Return the batch command to be executed - /// </summary> - public IDbCommand BatchCommand - { - get { return commandGetter(); } - } - - /// <summary> - /// The number of commands batched in this instance - /// </summary> - public int CountOfCommands - { - get { return countOfCommands; } - } - - /// <summary> - /// Executes the batch - /// </summary> - /// <returns> - /// This seems to be returning the total number of affected rows in all queries - /// </returns> - public int ExecuteNonQuery() - { - if (Connection == null) - throw new ArgumentNullException("Connection", - "Connection was not set! You must set the connection property before calling ExecuteNonQuery()"); - try - { - if (CountOfCommands == 0) - return 0; - return doExecuteNonQuery(); - } - catch (Exception e) - { - throw new HibernateException("An exception occurred when executing batch queries", e); - } - } - - public TConnection Connection - { - get { return (TConnection) commandGetter().Connection; } - set { commandGetter().Connection = value; } - } - - ///<summary> - ///Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - ///</summary> - ///<filterpriority>2</filterpriority> - public void Dispose() - { - doDispose(); - } - - #region Delegate Definitions - - private delegate T PropGetter<T>(); - - private delegate void AppendCommand(TCommand command); - - private delegate int ExecuteNonQueryCommand(); - - private delegate void DisposeCommand(); - - #endregion - } -} - Deleted: trunk/nhibernate/src/NHibernate/Impl/IDbCommandSet.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Impl/IDbCommandSet.cs 2010-08-01 17:41:53 UTC (rev 5089) +++ trunk/nhibernate/src/NHibernate/Impl/IDbCommandSet.cs 2010-08-01 19:49:12 UTC (rev 5090) @@ -1,32 +0,0 @@ -using System; -using System.Data; - -namespace NHibernate.Impl -{ - internal interface IDbCommandSet : IDisposable - { - /// <summary> - /// Append a command to the batch - /// </summary> - /// <param name="command"></param> - void Append(IDbCommand command); - - /// <summary> - /// Return the batch command to be executed - /// </summary> - IDbCommand BatchCommand { get; } - - /// <summary> - /// The number of commands batched in this instance - /// </summary> - int CountOfCommands { get; } - - /// <summary> - /// Executes the batch - /// </summary> - /// <returns> - /// This seems to be returning the total number of affected rows in all queries - /// </returns> - int ExecuteNonQuery(); - } -} Deleted: trunk/nhibernate/src/NHibernate/Impl/OracleClientCommandSet.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Impl/OracleClientCommandSet.cs 2010-08-01 17:41:53 UTC (rev 5089) +++ trunk/nhibernate/src/NHibernate/Impl/OracleClientCommandSet.cs 2010-08-01 19:49:12 UTC (rev 5090) @@ -1,25 +0,0 @@ -using System; -using System.Data.OracleClient; -using System.Diagnostics; -using System.Reflection; - -namespace NHibernate.Impl -{ - internal class OracleClientCommandSet : DbCommandSet<OracleConnection, OracleCommand> - { - private static readonly System.Type oracleCmdSetType; - - static OracleClientCommandSet() - { - Assembly sysDataOracleClient = - Assembly.Load("System.Data.OracleClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); - oracleCmdSetType = sysDataOracleClient.GetType("System.Data.OracleClient.OracleCommandSet"); - Debug.Assert(oracleCmdSetType != null, "Could not find OracleCommandSet!"); - } - - protected override object CreateInternalCommandSet() - { - return Activator.CreateInstance(oracleCmdSetType, true); - } - } -} \ No newline at end of file Deleted: trunk/nhibernate/src/NHibernate/Impl/SqlClientCommandSet.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Impl/SqlClientCommandSet.cs 2010-08-01 17:41:53 UTC (rev 5089) +++ trunk/nhibernate/src/NHibernate/Impl/SqlClientCommandSet.cs 2010-08-01 19:49:12 UTC (rev 5090) @@ -1,33 +0,0 @@ -using System; -using System.Data; -using System.Data.SqlClient; -using System.Reflection; - -namespace NHibernate.Impl -{ - internal class SqlClientCommandSet : DbCommandSet<SqlConnection, System.Data.SqlClient.SqlCommand> - { - private static readonly System.Type sqlCmdSetType; - - static SqlClientCommandSet() - { - Assembly sysData = typeof (IDbConnection).Assembly; - sqlCmdSetType = sysData.GetType("System.Data.SqlClient.SqlCommandSet"); - } - - protected override object CreateInternalCommandSet() - { - if (sqlCmdSetType == null) - { - throw new HibernateException("Could not find SqlCommandSet" + Environment.NewLine - + "If you are running on Mono, batching support isn't implemented on Mono" - + Environment.NewLine - + "If you are running on Microsoft .NET, this probably means that internal details" - + Environment.NewLine - + - "of the BCL that we rely on to allow this have changed, this is a bug. Please inform the developers"); - } - return Activator.CreateInstance(sqlCmdSetType, true); - } - } -} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-08-01 17:41:53 UTC (rev 5089) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-08-01 19:49:12 UTC (rev 5090) @@ -1210,17 +1210,13 @@ <Compile Include="Impl\AbstractDetachedQuery.cs" /> <Compile Include="Hql\Classic\FunctionStack.cs" /> <Compile Include="Impl\AbstractSessionImpl.cs" /> - <Compile Include="Impl\DbCommandSet.cs" /> <Compile Include="Impl\DetachedNamedQuery.cs" /> <Compile Include="Impl\DetachedQuery.cs" /> <Compile Include="IDetachedQuery.cs" /> <Compile Include="IdentityEqualityComparer.cs" /> - <Compile Include="Impl\IDbCommandSet.cs" /> <Compile Include="Impl\IDetachedQueryImplementor.cs" /> <Compile Include="Impl\MultiCriteriaImpl.cs" /> <Compile Include="Impl\MultipleQueriesCacheAssembler.cs" /> - <Compile Include="Impl\OracleClientCommandSet.cs" /> - <Compile Include="Impl\SqlClientCommandSet.cs" /> <Compile Include="Impl\StatelessSessionImpl.cs" /> <Compile Include="IMultiCriteria.cs" /> <Compile Include="Intercept\AbstractFieldInterceptor.cs" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2010-08-02 11:35:15
|
Revision: 5091 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5091&view=rev Author: fabiomaulo Date: 2010-08-02 11:35:07 +0000 (Mon, 02 Aug 2010) Log Message: ----------- Apply NH-2190 (thanks to Mihai Codrean) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Criterion/DetachedCriteria.cs trunk/nhibernate/src/NHibernate/Dialect/Sybase11Dialect.cs trunk/nhibernate/src/NHibernate/Engine/JoinSequence.cs trunk/nhibernate/src/NHibernate/ICriteria.cs trunk/nhibernate/src/NHibernate/Impl/CriteriaImpl.cs trunk/nhibernate/src/NHibernate/Loader/AbstractEntityJoinWalker.cs trunk/nhibernate/src/NHibernate/Loader/Collection/BasicCollectionJoinWalker.cs trunk/nhibernate/src/NHibernate/Loader/Collection/OneToManyJoinWalker.cs trunk/nhibernate/src/NHibernate/Loader/Criteria/CriteriaJoinWalker.cs trunk/nhibernate/src/NHibernate/Loader/Criteria/CriteriaQueryTranslator.cs trunk/nhibernate/src/NHibernate/Loader/JoinWalker.cs trunk/nhibernate/src/NHibernate/Loader/OuterJoinableAssociation.cs trunk/nhibernate/src/NHibernate/SqlCommand/ANSIJoinFragment.cs trunk/nhibernate/src/NHibernate/SqlCommand/InformixJoinFragment.cs trunk/nhibernate/src/NHibernate/SqlCommand/JoinFragment.cs trunk/nhibernate/src/NHibernate/SqlCommand/OracleJoinFragment.cs trunk/nhibernate/src/NHibernate/SqlCommand/QueryJoinFragment.cs trunk/nhibernate/src/NHibernate/Util/StringHelper.cs trunk/nhibernate/src/NHibernate.Test/Criteria/CriteriaQueryTest.cs Modified: trunk/nhibernate/src/NHibernate/Criterion/DetachedCriteria.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Criterion/DetachedCriteria.cs 2010-08-01 19:49:12 UTC (rev 5090) +++ trunk/nhibernate/src/NHibernate/Criterion/DetachedCriteria.cs 2010-08-02 11:35:07 UTC (rev 5091) @@ -129,6 +129,12 @@ return this; } + public DetachedCriteria CreateAlias(string associationPath, string alias, JoinType joinType, ICriterion withClause) + { + criteria.CreateAlias(associationPath, alias, joinType, withClause); + return this; + } + public DetachedCriteria CreateCriteria(string associationPath, string alias) { return new DetachedCriteria(impl, criteria.CreateCriteria(associationPath, alias)); Modified: trunk/nhibernate/src/NHibernate/Dialect/Sybase11Dialect.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/Sybase11Dialect.cs 2010-08-01 19:49:12 UTC (rev 5090) +++ trunk/nhibernate/src/NHibernate/Dialect/Sybase11Dialect.cs 2010-08-02 11:35:07 UTC (rev 5091) @@ -69,7 +69,7 @@ } public override void AddJoin(string tableName, string alias, string[] fkColumns, string[] pkColumns, JoinType joinType, - string on) + SqlString on) { AddJoin(tableName, alias, fkColumns, pkColumns, joinType); AddCondition(on); Modified: trunk/nhibernate/src/NHibernate/Engine/JoinSequence.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Engine/JoinSequence.cs 2010-08-01 19:49:12 UTC (rev 5090) +++ trunk/nhibernate/src/NHibernate/Engine/JoinSequence.cs 2010-08-02 11:35:07 UTC (rev 5091) @@ -203,7 +203,7 @@ join.LHSColumns, JoinHelper.GetRHSColumnNames(join.AssociationType, factory), join.JoinType, - condition + new SqlString(condition) ); if (includeExtraJoins) { Modified: trunk/nhibernate/src/NHibernate/ICriteria.cs =================================================================== --- trunk/nhibernate/src/NHibernate/ICriteria.cs 2010-08-01 19:49:12 UTC (rev 5090) +++ trunk/nhibernate/src/NHibernate/ICriteria.cs 2010-08-02 11:35:07 UTC (rev 5091) @@ -130,6 +130,17 @@ ICriteria CreateAlias(string associationPath, string alias, JoinType joinType); /// <summary> + /// Join an association using the specified join-type, assigning an alias to the joined + /// association + /// </summary> + /// <param name="associationPath"></param> + /// <param name="alias"></param> + /// <param name="joinType">The type of join to use.</param> + /// <param name="withClause"The criteria to be added to the join condition (ON clause)</param> + /// <returns>this (for method chaining)</returns> + ICriteria CreateAlias(string associationPath, string alias, JoinType joinType, ICriterion withClause); + + /// <summary> /// Create a new <see cref="ICriteria" />, "rooted" at the associated entity /// </summary> /// <param name="associationPath"></param> @@ -165,6 +176,17 @@ ICriteria CreateCriteria(string associationPath, string alias, JoinType joinType); /// <summary> + /// Create a new <see cref="ICriteria" />, "rooted" at the associated entity, + /// assigning the given alias and using the specified join type. + /// </summary> + /// <param name="associationPath">A dot-separated property path</param> + /// <param name="alias">The alias to assign to the joined association (for later reference).</param> + /// <param name="joinType">The type of join to use.</param> + /// <param name="withClause"The criteria to be added to the join condition (ON clause)</param> + /// <returns>The created "sub criteria"</returns> + ICriteria CreateCriteria(string associationPath, string alias, JoinType joinType, ICriterion withClause); + + /// <summary> /// Set a strategy for handling the query results. This determines the /// "shape" of the query result set. /// <seealso cref="CriteriaSpecification.RootEntity"/> Modified: trunk/nhibernate/src/NHibernate/Impl/CriteriaImpl.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Impl/CriteriaImpl.cs 2010-08-01 19:49:12 UTC (rev 5090) +++ trunk/nhibernate/src/NHibernate/Impl/CriteriaImpl.cs 2010-08-02 11:35:07 UTC (rev 5091) @@ -345,6 +345,12 @@ return this; } + public ICriteria CreateAlias(string associationPath, string alias, JoinType joinType, ICriterion withClause) + { + new Subcriteria(this, this, associationPath, alias, joinType, withClause); + return this; + } + public ICriteria Add(ICriteria criteriaInst, ICriterion expression) { criteria.Add(new CriterionEntry(expression, criteriaInst)); @@ -371,6 +377,11 @@ return new Subcriteria(this, this, associationPath, alias, joinType); } + public ICriteria CreateCriteria(string associationPath, string alias, JoinType joinType, ICriterion withClause) + { + return new Subcriteria(this, this, associationPath, alias, joinType, withClause); + } + public IFutureValue<T> FutureValue<T>() { if (!session.Factory.ConnectionProvider.Driver.SupportsMultipleQueries) @@ -607,14 +618,16 @@ private readonly string path; private LockMode lockMode; private readonly JoinType joinType; + private ICriterion withClause; - internal Subcriteria(CriteriaImpl root, ICriteria parent, string path, string alias, JoinType joinType) + internal Subcriteria(CriteriaImpl root, ICriteria parent, string path, string alias, JoinType joinType, ICriterion withClause) { this.root = root; this.parent = parent; this.alias = alias; this.path = path; this.joinType = joinType; + this.withClause = withClause; root.subcriteriaList.Add(this); @@ -625,9 +638,17 @@ } } + internal Subcriteria(CriteriaImpl root, ICriteria parent, string path, string alias, JoinType joinType) + : this(root, parent, path, alias, joinType, null) {} + internal Subcriteria(CriteriaImpl root, ICriteria parent, string path, JoinType joinType) - : this(root, parent, path, null, joinType) {} + : this(root, parent, path, null, joinType) { } + public ICriterion WithClause + { + get { return withClause; } + } + public string Path { get { return path; } @@ -688,6 +709,12 @@ return this; } + public ICriteria CreateAlias(string associationPath, string alias, JoinType joinType, ICriterion withClause) + { + new Subcriteria(root, this, associationPath, alias, joinType, withClause); + return this; + } + public ICriteria CreateCriteria(string associationPath) { return CreateCriteria(associationPath, JoinType.InnerJoin); @@ -708,6 +735,11 @@ return new Subcriteria(root, this, associationPath, alias, joinType); } + public ICriteria CreateCriteria(string associationPath, string alias, JoinType joinType, ICriterion withClause) + { + return new Subcriteria(root, this, associationPath, alias, joinType, withClause); + } + public ICriteria SetCacheable(bool cacheable) { root.SetCacheable(cacheable); Modified: trunk/nhibernate/src/NHibernate/Loader/AbstractEntityJoinWalker.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Loader/AbstractEntityJoinWalker.cs 2010-08-01 19:49:12 UTC (rev 5090) +++ trunk/nhibernate/src/NHibernate/Loader/AbstractEntityJoinWalker.cs 2010-08-02 11:35:07 UTC (rev 5091) @@ -4,6 +4,7 @@ using NHibernate.SqlCommand; using NHibernate.Type; using NHibernate.Util; +using NHibernate.Loader.Criteria; namespace NHibernate.Loader { @@ -33,19 +34,27 @@ WalkEntityTree(persister, Alias); IList<OuterJoinableAssociation> allAssociations = new List<OuterJoinableAssociation>(associations); allAssociations.Add( - new OuterJoinableAssociation(persister.EntityType, null, null, alias, JoinType.LeftOuterJoin, Factory, + new OuterJoinableAssociation(persister.EntityType, null, null, alias, JoinType.LeftOuterJoin, null, Factory, new CollectionHelper.EmptyMapClass<string, IFilter>())); InitPersisters(allAssociations, lockMode); InitStatementString(whereString, orderByString, lockMode); } - protected void InitProjection(SqlString projectionString, SqlString whereString, - SqlString orderByString, string groupByString, SqlString havingString, LockMode lockMode) + protected void InitProjection(CriteriaQueryTranslator translator, + IDictionary<string, IFilter> enabledFilters, LockMode lockMode) { + // the order of the calls here is important, as the join clauses can contain parameter bindings + SqlString projectionString = translator.GetSelect(enabledFilters); WalkEntityTree(persister, Alias); + SqlString whereString = translator.GetWhereCondition(enabledFilters); + SqlString orderByString = translator.GetOrderBy(); + SqlString groupByString = translator.GetGroupBy(); + SqlString havingString = translator.GetHavingCondition(enabledFilters); + Persisters = new ILoadable[0]; - InitStatementString(projectionString, whereString, orderByString, groupByString, havingString, lockMode); + InitStatementString(projectionString, whereString, orderByString, groupByString.ToString(), + havingString, lockMode); } private void InitStatementString(SqlString condition, SqlString orderBy, LockMode lockMode) Modified: trunk/nhibernate/src/NHibernate/Loader/Collection/BasicCollectionJoinWalker.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Loader/Collection/BasicCollectionJoinWalker.cs 2010-08-01 19:49:12 UTC (rev 5090) +++ trunk/nhibernate/src/NHibernate/Loader/Collection/BasicCollectionJoinWalker.cs 2010-08-02 11:35:07 UTC (rev 5091) @@ -29,7 +29,7 @@ // NH Different behavior : passing enabledFilters instead empty-filter allAssociations.Add( - new OuterJoinableAssociation(collectionPersister.CollectionType, null, null, alias, JoinType.LeftOuterJoin, Factory, + new OuterJoinableAssociation(collectionPersister.CollectionType, null, null, alias, JoinType.LeftOuterJoin, null, Factory, enabledFilters)); InitPersisters(allAssociations, LockMode.None); Modified: trunk/nhibernate/src/NHibernate/Loader/Collection/OneToManyJoinWalker.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Loader/Collection/OneToManyJoinWalker.cs 2010-08-01 19:49:12 UTC (rev 5090) +++ trunk/nhibernate/src/NHibernate/Loader/Collection/OneToManyJoinWalker.cs 2010-08-02 11:35:07 UTC (rev 5091) @@ -35,7 +35,7 @@ IList<OuterJoinableAssociation> allAssociations = new List<OuterJoinableAssociation>(associations); allAssociations.Add( - new OuterJoinableAssociation(oneToManyPersister.CollectionType, null, null, alias, JoinType.LeftOuterJoin, Factory, + new OuterJoinableAssociation(oneToManyPersister.CollectionType, null, null, alias, JoinType.LeftOuterJoin, null, Factory, new CollectionHelper.EmptyMapClass<string, IFilter>())); InitPersisters(allAssociations, LockMode.None); Modified: trunk/nhibernate/src/NHibernate/Loader/Criteria/CriteriaJoinWalker.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Loader/Criteria/CriteriaJoinWalker.cs 2010-08-01 19:49:12 UTC (rev 5090) +++ trunk/nhibernate/src/NHibernate/Loader/Criteria/CriteriaJoinWalker.cs 2010-08-02 11:35:07 UTC (rev 5091) @@ -42,9 +42,7 @@ { resultTypes = translator.ProjectedTypes; - InitProjection(translator.GetSelect(enabledFilters), translator.GetWhereCondition(enabledFilters), - translator.GetOrderBy(), translator.GetGroupBy().ToString(), - translator.GetHavingCondition(enabledFilters), LockMode.None); + InitProjection(translator, enabledFilters, LockMode.None); } else { @@ -175,5 +173,10 @@ return CriteriaQueryTranslator.RootSqlAlias; // NH: really not used (we are using a different ctor to support SubQueryCriteria) } + + protected override SqlString GetWithClause(string path) + { + return translator.GetWithClause(path, EnabledFilters); + } } } \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Loader/Criteria/CriteriaQueryTranslator.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Loader/Criteria/CriteriaQueryTranslator.cs 2010-08-01 19:49:12 UTC (rev 5090) +++ trunk/nhibernate/src/NHibernate/Loader/Criteria/CriteriaQueryTranslator.cs 2010-08-02 11:35:07 UTC (rev 5091) @@ -39,6 +39,7 @@ private readonly IDictionary<string, ICriteria> aliasCriteriaMap = new Dictionary<string, ICriteria>(); private readonly IDictionary<string, ICriteria> associationPathCriteriaMap = new LinkedHashMap<string, ICriteria>(); private readonly IDictionary<string, JoinType> associationPathJoinTypesMap = new LinkedHashMap<string, JoinType>(); + private readonly IDictionary<string, ICriterion> withClauseMap = new Dictionary<string, ICriterion>(); private readonly ISessionFactoryImplementor sessionFactory; private int indexForAlias = 0; @@ -300,6 +301,18 @@ { throw new QueryException("duplicate association path: " + wholeAssociationPath, ae); } + + try + { + if (crit.WithClause != null) + { + withClauseMap.Add(wholeAssociationPath, crit.WithClause); + } + } + catch (ArgumentException ae) + { + throw new QueryException("duplicate association path: " + wholeAssociationPath, ae); + } } } @@ -685,6 +698,16 @@ return propertyName; } + public SqlString GetWithClause(string path, IDictionary<string, IFilter> enabledFilters) + { + if (withClauseMap.ContainsKey(path)) + { + ICriterion crit = (ICriterion)withClauseMap[path]; + return crit == null ? null : crit.ToSqlString(GetCriteria(path), this, enabledFilters); + } + return null; + } + #region NH specific public int GetIndexForAlias() Modified: trunk/nhibernate/src/NHibernate/Loader/JoinWalker.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Loader/JoinWalker.cs 2010-08-01 19:49:12 UTC (rev 5090) +++ trunk/nhibernate/src/NHibernate/Loader/JoinWalker.cs 2010-08-02 11:35:07 UTC (rev 5091) @@ -130,6 +130,11 @@ } } + protected virtual SqlString GetWithClause(string path) + { + return SqlString.Empty; + } + /// <summary> /// Add on association (one-to-one, many-to-one, or a collection) to a list /// of associations to be fetched by outerjoin @@ -142,7 +147,7 @@ string subalias = GenerateTableAlias(associations.Count + 1, path, joinable); OuterJoinableAssociation assoc = - new OuterJoinableAssociation(type, alias, aliasedLhsColumns, subalias, joinType, Factory, enabledFilters); + new OuterJoinableAssociation(type, alias, aliasedLhsColumns, subalias, joinType, GetWithClause(path), Factory, enabledFilters); assoc.ValidateJoin(path); associations.Add(assoc); Modified: trunk/nhibernate/src/NHibernate/Loader/OuterJoinableAssociation.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Loader/OuterJoinableAssociation.cs 2010-08-01 19:49:12 UTC (rev 5090) +++ trunk/nhibernate/src/NHibernate/Loader/OuterJoinableAssociation.cs 2010-08-02 11:35:07 UTC (rev 5091) @@ -5,6 +5,7 @@ using NHibernate.Persister.Entity; using NHibernate.SqlCommand; using NHibernate.Type; +using NHibernate.Util; namespace NHibernate.Loader { @@ -17,11 +18,11 @@ private readonly string rhsAlias; private readonly string[] rhsColumns; private readonly JoinType joinType; - private readonly string on; + private readonly SqlString on; private readonly IDictionary<string, IFilter> enabledFilters; public OuterJoinableAssociation(IAssociationType joinableType, String lhsAlias, String[] lhsColumns, String rhsAlias, - JoinType joinType, ISessionFactoryImplementor factory, + JoinType joinType, SqlString withClause, ISessionFactoryImplementor factory, IDictionary<string, IFilter> enabledFilters) { this.joinableType = joinableType; @@ -31,7 +32,9 @@ this.joinType = joinType; joinable = joinableType.GetAssociatedJoinable(factory); rhsColumns = JoinHelper.GetRHSColumnNames(joinableType, factory); - on = joinableType.GetOnCondition(rhsAlias, factory, enabledFilters); + on = new SqlString(joinableType.GetOnCondition(rhsAlias, factory, enabledFilters)); + if (StringHelper.IsNotEmpty(withClause)) + on = on.Append(" and ( ").Append(withClause).Append(" )"); this.enabledFilters = enabledFilters; // needed later for many-to-many/filter application } @@ -146,9 +149,10 @@ public void AddManyToManyJoin(JoinFragment outerjoin, IQueryableCollection collection) { string manyToManyFilter = collection.GetManyToManyFilterFragment(rhsAlias, enabledFilters); - string condition = string.Empty.Equals(manyToManyFilter) + SqlString condition = string.Empty.Equals(manyToManyFilter) ? on - : string.Empty.Equals(on) ? manyToManyFilter : on + " and " + manyToManyFilter; + : StringHelper.IsEmpty(on) ? new SqlString(manyToManyFilter) : + on.Append(" and ").Append(manyToManyFilter); outerjoin.AddJoin(joinable.TableName, rhsAlias, lhsColumns, rhsColumns, joinType, condition); outerjoin.AddJoins(joinable.FromJoinFragment(rhsAlias, false, true), Modified: trunk/nhibernate/src/NHibernate/SqlCommand/ANSIJoinFragment.cs =================================================================== --- trunk/nhibernate/src/NHibernate/SqlCommand/ANSIJoinFragment.cs 2010-08-01 19:49:12 UTC (rev 5090) +++ trunk/nhibernate/src/NHibernate/SqlCommand/ANSIJoinFragment.cs 2010-08-02 11:35:07 UTC (rev 5091) @@ -17,7 +17,7 @@ } public override void AddJoin(string tableName, string alias, string[] fkColumns, string[] pkColumns, JoinType joinType, - string on) + SqlString on) { string joinString; switch (joinType) Modified: trunk/nhibernate/src/NHibernate/SqlCommand/InformixJoinFragment.cs =================================================================== --- trunk/nhibernate/src/NHibernate/SqlCommand/InformixJoinFragment.cs 2010-08-01 19:49:12 UTC (rev 5090) +++ trunk/nhibernate/src/NHibernate/SqlCommand/InformixJoinFragment.cs 2010-08-02 11:35:07 UTC (rev 5091) @@ -40,7 +40,7 @@ } public override void AddJoin(string tableName, string alias, string[] fkColumns, string[] pkColumns, JoinType joinType, - string on) + SqlString on) { //arbitrary on clause ignored!! AddJoin(tableName, alias, fkColumns, pkColumns, joinType); Modified: trunk/nhibernate/src/NHibernate/SqlCommand/JoinFragment.cs =================================================================== --- trunk/nhibernate/src/NHibernate/SqlCommand/JoinFragment.cs 2010-08-01 19:49:12 UTC (rev 5090) +++ trunk/nhibernate/src/NHibernate/SqlCommand/JoinFragment.cs 2010-08-02 11:35:07 UTC (rev 5091) @@ -20,7 +20,7 @@ public abstract void AddJoin(string tableName, string alias, string[] fkColumns, string[] pkColumns, JoinType joinType); public abstract void AddJoin(string tableName, string alias, string[] fkColumns, string[] pkColumns, JoinType joinType, - string on); + SqlString on); public abstract void AddCrossJoin(string tableName, string alias); Modified: trunk/nhibernate/src/NHibernate/SqlCommand/OracleJoinFragment.cs =================================================================== --- trunk/nhibernate/src/NHibernate/SqlCommand/OracleJoinFragment.cs 2010-08-01 19:49:12 UTC (rev 5090) +++ trunk/nhibernate/src/NHibernate/SqlCommand/OracleJoinFragment.cs 2010-08-02 11:35:07 UTC (rev 5091) @@ -36,7 +36,7 @@ } public override void AddJoin(string tableName, string alias, string[] fkColumns, string[] pkColumns, JoinType joinType, - string on) + SqlString on) { //arbitrary on clause ignored!! AddJoin(tableName, alias, fkColumns, pkColumns, joinType); @@ -62,9 +62,9 @@ /// was a normal join condition, but is natural /// for a filter. /// </summary> - private void AddLeftOuterJoinCondition(string on) + private void AddLeftOuterJoinCondition(SqlString on) { - StringBuilder buf = new StringBuilder(on); + StringBuilder buf = new StringBuilder(on.ToString()); for (int i = 0; i < buf.Length; i++) { char character = buf[i]; @@ -76,7 +76,7 @@ i += 3; } } - AddCondition(buf.ToString()); + AddCondition(SqlString.Parse(buf.ToString())); } private static readonly ISet Operators = new HashedSet(); Modified: trunk/nhibernate/src/NHibernate/SqlCommand/QueryJoinFragment.cs =================================================================== --- trunk/nhibernate/src/NHibernate/SqlCommand/QueryJoinFragment.cs 2010-08-01 19:49:12 UTC (rev 5090) +++ trunk/nhibernate/src/NHibernate/SqlCommand/QueryJoinFragment.cs 2010-08-02 11:35:07 UTC (rev 5091) @@ -25,7 +25,7 @@ } private void AddJoin(string tableName, string alias, string concreteAlias, string[] fkColumns, string[] pkColumns, - JoinType joinType, string on) + JoinType joinType, SqlString on) { if (!useThetaStyleInnerJoins || joinType != JoinType.InnerJoin) { @@ -42,7 +42,7 @@ } public override void AddJoin(string tableName, string alias, string[] fkColumns, string[] pkColumns, JoinType joinType, - string on) + SqlString on) { AddJoin(tableName, alias, alias, fkColumns, pkColumns, joinType, on); } Modified: trunk/nhibernate/src/NHibernate/Util/StringHelper.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Util/StringHelper.cs 2010-08-01 19:49:12 UTC (rev 5090) +++ trunk/nhibernate/src/NHibernate/Util/StringHelper.cs 2010-08-02 11:35:07 UTC (rev 5091) @@ -496,9 +496,14 @@ public static bool IsNotEmpty(SqlString str) { - return str != null && str.Count > 0; + return !IsEmpty(str); } + public static bool IsEmpty(SqlString str) + { + return str == null || str.Count == 0; + } + /// <summary> /// /// </summary> Modified: trunk/nhibernate/src/NHibernate.Test/Criteria/CriteriaQueryTest.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/Criteria/CriteriaQueryTest.cs 2010-08-01 19:49:12 UTC (rev 5090) +++ trunk/nhibernate/src/NHibernate.Test/Criteria/CriteriaQueryTest.cs 2010-08-02 11:35:07 UTC (rev 5091) @@ -1849,5 +1849,111 @@ criteria.List(); } } + + + [Test] + public void AliasJoinCriterion() + { + using (ISession session = this.OpenSession()) + { + using (ITransaction t = session.BeginTransaction()) + { + Course courseA = new Course(); + courseA.CourseCode = "HIB-A"; + courseA.Description = "Hibernate Training A"; + session.Persist(courseA); + + Course courseB = new Course(); + courseB.CourseCode = "HIB-B"; + courseB.Description = "Hibernate Training B"; + session.Persist(courseB); + + Student gavin = new Student(); + gavin.Name = "Gavin King"; + gavin.StudentNumber = 232; + gavin.PreferredCourse = courseA; + session.Persist(gavin); + + Student leonardo = new Student(); + leonardo.Name = "Leonardo Quijano"; + leonardo.StudentNumber = 233; + leonardo.PreferredCourse = courseB; + session.Persist(leonardo); + + Student johnDoe = new Student(); + johnDoe.Name = "John Doe"; + johnDoe.StudentNumber = 235; + johnDoe.PreferredCourse = null; + session.Persist(johnDoe); + + // test == on one value exists + IList<string> result = session.CreateCriteria<Student>() + .CreateAlias("PreferredCourse", "pc", JoinType.LeftOuterJoin, + Restrictions.Eq("pc.CourseCode", "HIB-A")) + .SetProjection(Property.ForName("pc.CourseCode")) + .AddOrder(Order.Asc("pc.CourseCode")) + .List<string>(); + + // can't be sure of NULL comparison ordering aside from they should + // either come first or last + if (result[0] == null) + { + Assert.IsNull(result[1]); + Assert.AreEqual("HIB-A", result[2]); + } + else + { + Assert.IsNull(result[2]); + Assert.IsNull(result[1]); + Assert.AreEqual("HIB-A", result[0]); + } + + // test == on non existent value + result = session.CreateCriteria<Student>() + .CreateAlias("PreferredCourse", "pc", JoinType.LeftOuterJoin, + Restrictions.Eq("pc.CourseCode", "HIB-R")) + .SetProjection(Property.ForName("pc.CourseCode")) + .AddOrder(Order.Asc("pc.CourseCode")) + .List<string>(); + + Assert.AreEqual(3, result.Count); + Assert.IsNull(result[2]); + Assert.IsNull(result[1]); + Assert.IsNull(result[0]); + + // test != on one existing value + result = session.CreateCriteria<Student>() + .CreateAlias("PreferredCourse", "pc", JoinType.LeftOuterJoin, + Restrictions.Not(Restrictions.Eq("pc.CourseCode", "HIB-A"))) + .SetProjection(Property.ForName("pc.CourseCode")) + .AddOrder(Order.Asc("pc.CourseCode")) + .List<string>(); + + Assert.AreEqual(3, result.Count); + + // can't be sure of NULL comparison ordering aside from they should + // either come first or last + if (result[0] == null) + { + Assert.IsNull(result[1]); + Assert.AreEqual("HIB-B", result[2]); + } + else + { + Assert.AreEqual("HIB-B", result[0]); + Assert.IsNull(result[1]); + Assert.IsNull(result[2]); + } + + session.Delete(gavin); + session.Delete(leonardo); + session.Delete(johnDoe); + session.Delete(courseA); + session.Delete(courseB); + + t.Commit(); + } + } + } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2010-08-02 11:44:33
|
Revision: 5092 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5092&view=rev Author: fabiomaulo Date: 2010-08-02 11:44:24 +0000 (Mon, 02 Aug 2010) Log Message: ----------- Apply NH-2252 (thanks to Diego Mijelshon) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/NHibernate.csproj trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate/Dialect/MsSqlCe40Dialect.cs trunk/nhibernate/src/NHibernate.Test/DialectTest/MsSqlCe40DialectFixture.cs Added: trunk/nhibernate/src/NHibernate/Dialect/MsSqlCe40Dialect.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/MsSqlCe40Dialect.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Dialect/MsSqlCe40Dialect.cs 2010-08-02 11:44:24 UTC (rev 5092) @@ -0,0 +1,30 @@ +using NHibernate.SqlCommand; + +namespace NHibernate.Dialect +{ + public class MsSqlCe40Dialect : MsSqlCeDialect + { + public override SqlString GetLimitString(SqlString querySqlString, int offset, int limit) + { + if (querySqlString.IndexOfCaseInsensitive(" ORDER BY ") < 0) + querySqlString = querySqlString.Append(" ORDER BY GETDATE()"); + return querySqlString.Append(string.Format(" OFFSET {0} ROWS FETCH NEXT {1} ROWS ONLY", offset, limit)); + } + + public override bool SupportsLimit + { + get + { + return true; + } + } + + public override bool SupportsLimitOffset + { + get + { + return true; + } + } + } +} Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-08-02 11:35:07 UTC (rev 5091) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-08-02 11:44:24 UTC (rev 5092) @@ -585,6 +585,7 @@ <Compile Include="Dialect\MsSql2008Dialect.cs" /> <Compile Include="Dialect\InformixDialect0940.cs" /> <Compile Include="Dialect\InformixDialect1000.cs" /> + <Compile Include="Dialect\MsSqlCe40Dialect.cs" /> <Compile Include="Dialect\Oracle10gDialect.cs" /> <Compile Include="Dialect\Oracle8iDialect.cs" /> <Compile Include="Dialect\Oracle9iDialect.cs" /> Added: trunk/nhibernate/src/NHibernate.Test/DialectTest/MsSqlCe40DialectFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/DialectTest/MsSqlCe40DialectFixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/DialectTest/MsSqlCe40DialectFixture.cs 2010-08-02 11:44:24 UTC (rev 5092) @@ -0,0 +1,25 @@ +using NHibernate.Dialect; +using NHibernate.SqlCommand; +using NUnit.Framework; + +namespace NHibernate.Test.DialectTest +{ + public class MsSqlCe40DialectFixture + { + [Test] + public void GetLimitString() + { + var dialect = new MsSqlCe40Dialect(); + var str = dialect.GetLimitString(new SqlString("SELECT id FROM user ORDER BY name"), 13, 17); + Assert.AreEqual("SELECT id FROM user ORDER BY name OFFSET 13 ROWS FETCH NEXT 17 ROWS ONLY", str.ToString()); + } + + [Test] + public void GetLimitStringWithDummyOrder() + { + var dialect = new MsSqlCe40Dialect(); + var str = dialect.GetLimitString(new SqlString("SELECT id FROM user"), 13, 17); + Assert.AreEqual("SELECT id FROM user ORDER BY GETDATE() OFFSET 13 ROWS FETCH NEXT 17 ROWS ONLY", str.ToString()); + } + } +} Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-08-02 11:35:07 UTC (rev 5091) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-08-02 11:44:24 UTC (rev 5092) @@ -177,6 +177,7 @@ <Compile Include="Criteria\MaterialResource.cs" /> <Compile Include="Criteria\ProjectionsTest.cs" /> <Compile Include="Criteria\Reptile.cs" /> + <Compile Include="DialectTest\MsSqlCe40DialectFixture.cs" /> <Compile Include="DriverTest\SqlClientDriverFixture.cs" /> <Compile Include="DriverTest\SqlServerCeDriverFixture.cs" /> <Compile Include="EngineTest\CallableParserFixture.cs" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2010-08-02 17:30:42
|
Revision: 5094 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5094&view=rev Author: fabiomaulo Date: 2010-08-02 17:30:36 +0000 (Mon, 02 Aug 2010) Log Message: ----------- Fix NH-2226 Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Cfg/ConfigurationSchema/CfgXmlHelper.cs trunk/nhibernate/src/NHibernate/Cfg/ConfigurationSchema/HibernateConfiguration.cs trunk/nhibernate/src/NHibernate/Cfg/Environment.cs trunk/nhibernate/src/NHibernate/Cfg/IHibernateConfiguration.cs trunk/nhibernate/src/NHibernate.Test/CfgTest/ConfigurationSchemaFixture.cs trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/CfgTest/CustomBytecodeProviderTest.cs Modified: trunk/nhibernate/src/NHibernate/Cfg/ConfigurationSchema/CfgXmlHelper.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/ConfigurationSchema/CfgXmlHelper.cs 2010-08-02 12:00:24 UTC (rev 5093) +++ trunk/nhibernate/src/NHibernate/Cfg/ConfigurationSchema/CfgXmlHelper.cs 2010-08-02 17:30:36 UTC (rev 5094) @@ -64,34 +64,10 @@ /// <summary>XPath expression for session-factory.listener nodes</summary> public static readonly XPathExpression SessionFactoryListenersExpression; - /// <summary> - /// Convert a string to <see cref="BytecodeProviderType"/>. - /// </summary> - /// <param name="byteCodeProvider">The string that represent <see cref="BytecodeProviderType"/>.</param> - /// <returns> - /// The <paramref name="byteCodeProvider"/> converted to <see cref="BytecodeProviderType"/>. - /// <see cref="BytecodeProviderType.Null"/> for invalid values. - /// </returns> - /// <remarks> - /// See <see cref="BytecodeProviderType"/> for allowed values. - /// </remarks> - public static BytecodeProviderType ByteCodeProviderConvertFrom(string byteCodeProvider) + internal static string ToConfigurationString(this BytecodeProviderType source) { - switch (byteCodeProvider) + switch (source) { - case "codedom": - return BytecodeProviderType.Codedom; - case "lcg": - return BytecodeProviderType.Lcg; - default: - return BytecodeProviderType.Null; - } - } - - internal static string ByteCodeProviderToString(BytecodeProviderType byteCodeProvider) - { - switch (byteCodeProvider) - { case BytecodeProviderType.Codedom: return "codedom"; case BytecodeProviderType.Lcg: Modified: trunk/nhibernate/src/NHibernate/Cfg/ConfigurationSchema/HibernateConfiguration.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/ConfigurationSchema/HibernateConfiguration.cs 2010-08-02 12:00:24 UTC (rev 5093) +++ trunk/nhibernate/src/NHibernate/Cfg/ConfigurationSchema/HibernateConfiguration.cs 2010-08-02 17:30:36 UTC (rev 5094) @@ -96,7 +96,7 @@ if (fromAppConfig) { xpn.MoveToFirstAttribute(); - byteCodeProviderType = CfgXmlHelper.ByteCodeProviderConvertFrom(xpn.Value); + byteCodeProviderType = xpn.Value; } else { @@ -128,12 +128,12 @@ } } - private BytecodeProviderType byteCodeProviderType = BytecodeProviderType.Lcg; + private string byteCodeProviderType = BytecodeProviderType.Lcg.ToConfigurationString(); /// <summary> /// Value for bytecode-provider system property. /// </summary> /// <remarks>Default value <see cref="BytecodeProviderType.Lcg"/>.</remarks> - public BytecodeProviderType ByteCodeProviderType + public string ByteCodeProviderType { get { return byteCodeProviderType; } } Modified: trunk/nhibernate/src/NHibernate/Cfg/Environment.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/Environment.cs 2010-08-02 12:00:24 UTC (rev 5093) +++ trunk/nhibernate/src/NHibernate/Cfg/Environment.cs 2010-08-02 17:30:36 UTC (rev 5094) @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Configuration; using System.Reflection; @@ -3,5 +4,4 @@ using log4net; using NHibernate.Bytecode; -using NHibernate.Bytecode.CodeDom; using NHibernate.Cfg.ConfigurationSchema; using NHibernate.Util; @@ -218,7 +218,7 @@ return; } - GlobalProperties[PropertyBytecodeProvider] = CfgXmlHelper.ByteCodeProviderToString(nhConfig.ByteCodeProviderType); + GlobalProperties[PropertyBytecodeProvider] = nhConfig.ByteCodeProviderType; GlobalProperties[PropertyUseReflectionOptimizer] = nhConfig.UseReflectionOptimizer.ToString(); if (nhConfig.SessionFactory != null) { @@ -317,15 +317,43 @@ switch (providerName) { case "codedom": - return new BytecodeProviderImpl(); + return new Bytecode.CodeDom.BytecodeProviderImpl(); case "lcg": return new Bytecode.Lightweight.BytecodeProviderImpl(); case "null": return new NullBytecodeProvider(); default: - log.Warn("unrecognized bytecode provider [" + providerName + "], using null by default"); - return new NullBytecodeProvider(); + log.Info("custom bytecode provider [" + providerName + "]"); + return CreateCustomBytecodeProvider(providerName); } } + + private static IBytecodeProvider CreateCustomBytecodeProvider(string assemblyQualifiedName) + { + try + { + var type = ReflectHelper.ClassForName(assemblyQualifiedName); + try + { + return (IBytecodeProvider)Activator.CreateInstance(type); + } + catch (MissingMethodException ex) + { + throw new HibernateByteCodeException("Public constructor was not found for " + type, ex); + } + catch (InvalidCastException ex) + { + throw new HibernateByteCodeException(type + "Type does not implement " + typeof(IBytecodeProvider), ex); + } + catch (Exception ex) + { + throw new HibernateByteCodeException("Unable to instantiate: " + type, ex); + } + } + catch (Exception e) + { + throw new HibernateByteCodeException("Unable to create the instance of Bytecode provider; check inner exception for detail", e); + } + } } } \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Cfg/IHibernateConfiguration.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/IHibernateConfiguration.cs 2010-08-02 12:00:24 UTC (rev 5093) +++ trunk/nhibernate/src/NHibernate/Cfg/IHibernateConfiguration.cs 2010-08-02 17:30:36 UTC (rev 5094) @@ -1,10 +1,8 @@ -using NHibernate.Cfg.ConfigurationSchema; - -namespace NHibernate.Cfg +namespace NHibernate.Cfg { public interface IHibernateConfiguration { - BytecodeProviderType ByteCodeProviderType { get; } + string ByteCodeProviderType { get; } bool UseReflectionOptimizer { get; } ISessionFactoryConfiguration SessionFactory { get; } } Modified: trunk/nhibernate/src/NHibernate.Test/CfgTest/ConfigurationSchemaFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/CfgTest/ConfigurationSchemaFixture.cs 2010-08-02 12:00:24 UTC (rev 5093) +++ trunk/nhibernate/src/NHibernate.Test/CfgTest/ConfigurationSchemaFixture.cs 2010-08-02 17:30:36 UTC (rev 5094) @@ -5,6 +5,7 @@ using NHibernate.Cfg; using NHibernate.Cfg.ConfigurationSchema; using System.Xml; +using SharpTestsEx; namespace NHibernate.Test.CfgTest { @@ -28,7 +29,7 @@ public void FromAppConfigTest() { IHibernateConfiguration hc = ConfigurationManager.GetSection("hibernate-configuration") as IHibernateConfiguration; - Assert.AreEqual(BytecodeProviderType.Lcg, hc.ByteCodeProviderType); + hc.ByteCodeProviderType.Should().Be("lcg"); Assert.IsTrue(hc.UseReflectionOptimizer); Assert.AreEqual("NHibernate.Test", hc.SessionFactory.Name); } Added: trunk/nhibernate/src/NHibernate.Test/CfgTest/CustomBytecodeProviderTest.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/CfgTest/CustomBytecodeProviderTest.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/CfgTest/CustomBytecodeProviderTest.cs 2010-08-02 17:30:36 UTC (rev 5094) @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using NHibernate.Bytecode; +using NHibernate.Properties; +using NUnit.Framework; +using SharpTestsEx; +using Environment = NHibernate.Cfg.Environment; + +namespace NHibernate.Test.CfgTest +{ + public class CustomBytecodeProviderTest + { + private class MyByteCodeProvider : AbstractBytecodeProvider + { + public override IReflectionOptimizer GetReflectionOptimizer(System.Type clazz, IGetter[] getters, ISetter[] setters) + { + throw new NotImplementedException(); + } + } + private class InvalidByteCodeProvider + { + } + private class InvalidNoCtorByteCodeProvider : AbstractBytecodeProvider + { + public InvalidNoCtorByteCodeProvider(string pizza) {} + + public override IReflectionOptimizer GetReflectionOptimizer(System.Type clazz, IGetter[] getters, ISetter[] setters) + { + throw new NotImplementedException(); + } + } + + [Test] + public void WhenNoShortCutUsedThenCanBuildBytecodeProvider() + { + var properties = new Dictionary<string, string> { { Environment.PropertyBytecodeProvider, typeof(MyByteCodeProvider).AssemblyQualifiedName } }; + Executing.This(() => Environment.BuildBytecodeProvider(properties)).Should().NotThrow(); + } + + [Test] + public void WhenNoShortCutUsedThenCanBuildInstanceOfConfiguredBytecodeProvider() + { + var properties = new Dictionary<string, string> { { Environment.PropertyBytecodeProvider, typeof(MyByteCodeProvider).AssemblyQualifiedName } }; + Environment.BuildBytecodeProvider(properties).Should().Be.InstanceOf<MyByteCodeProvider>(); + } + + [Test] + public void WhenInvalidThenThrow() + { + var properties = new Dictionary<string, string> { { Environment.PropertyBytecodeProvider, typeof(InvalidByteCodeProvider).AssemblyQualifiedName } }; + Executing.This(() => Environment.BuildBytecodeProvider(properties)).Should().Throw<HibernateByteCodeException>(); + } + + [Test] + public void WhenNoDefaultCtorThenThrow() + { + var properties = new Dictionary<string, string> { { Environment.PropertyBytecodeProvider, typeof(InvalidNoCtorByteCodeProvider).AssemblyQualifiedName } }; + Executing.This(() => Environment.BuildBytecodeProvider(properties)).Should().Throw<HibernateByteCodeException>() + .And.Exception.InnerException.Message.Should().Contain("constructor was not found"); + } + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-08-02 12:00:24 UTC (rev 5093) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-08-02 17:30:36 UTC (rev 5094) @@ -112,6 +112,7 @@ <Compile Include="CfgTest\ConfigurationFixture.cs" /> <Compile Include="CfgTest\ConfigurationSchemaFixture.cs" /> <Compile Include="CfgTest\ConfigurationSerializationTests.cs" /> + <Compile Include="CfgTest\CustomBytecodeProviderTest.cs" /> <Compile Include="CfgTest\DefaultNsAssmFixture.cs" /> <Compile Include="CfgTest\EntityCacheUsageParserFixture.cs" /> <Compile Include="CfgTest\HbmOrderingFixture.cs" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2010-08-02 17:56:27
|
Revision: 5095 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5095&view=rev Author: fabiomaulo Date: 2010-08-02 17:56:21 +0000 (Mon, 02 Aug 2010) Log Message: ----------- Partial fix of NH-2263 (thanks to Patrick Earl for the issue) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Driver/OracleClientDriver.cs trunk/nhibernate/src/NHibernate/NHibernate.csproj Modified: trunk/nhibernate/src/NHibernate/Driver/OracleClientDriver.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Driver/OracleClientDriver.cs 2010-08-02 17:30:36 UTC (rev 5094) +++ trunk/nhibernate/src/NHibernate/Driver/OracleClientDriver.cs 2010-08-02 17:56:21 UTC (rev 5095) @@ -1,5 +1,4 @@ using System.Data; -using System.Data.OracleClient; using NHibernate.Engine.Query; using NHibernate.SqlTypes; @@ -8,20 +7,13 @@ /// <summary> /// A NHibernate Driver for using the Oracle DataProvider. /// </summary> - public class OracleClientDriver : DriverBase + public class OracleClientDriver : ReflectionBasedDriver { private static readonly SqlType GuidSqlType = new SqlType(DbType.Binary, 16); - public override IDbConnection CreateConnection() - { - return new OracleConnection(); - } + public OracleClientDriver() : + base("System.Data.OracleClient", "System.Data.OracleClient.OracleConnection", "System.Data.OracleClient.OracleCommand") { } - public override IDbCommand CreateCommand() - { - return new OracleCommand(); - } - public override bool UseNamedPrefixInSql { get { return true; } Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-08-02 17:30:36 UTC (rev 5094) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-08-02 17:56:21 UTC (rev 5095) @@ -49,7 +49,6 @@ <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Data" /> - <Reference Include="System.Data.OracleClient" /> <Reference Include="System.ServiceModel"> <RequiredTargetFramework>3.0</RequiredTargetFramework> </Reference> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2010-08-02 22:34:25
|
Revision: 5101 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5101&view=rev Author: fabiomaulo Date: 2010-08-02 22:34:19 +0000 (Mon, 02 Aug 2010) Log Message: ----------- Fix NH-2160 (for datetimeoffset too) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Driver/SqlClientDriver.cs trunk/nhibernate/src/NHibernate.Test/DriverTest/MultiTypeEntity.hbm.xml trunk/nhibernate/src/NHibernate.Test/DriverTest/SqlClientDriverFixture.cs trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/DriverTest/EntityForMs2008.hbm.xml trunk/nhibernate/src/NHibernate.Test/DriverTest/Sql2008DateTime2Test.cs Modified: trunk/nhibernate/src/NHibernate/Driver/SqlClientDriver.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Driver/SqlClientDriver.cs 2010-08-02 21:44:15 UTC (rev 5100) +++ trunk/nhibernate/src/NHibernate/Driver/SqlClientDriver.cs 2010-08-02 22:34:19 UTC (rev 5101) @@ -95,6 +95,8 @@ private const int MaxStringClobSize = MaxBinaryBlobSize / 2; private const byte MaxPrecision = 28; private const byte MaxScale = 5; + private const byte MaxDateTime2 = 8; + private const byte MaxDateTimeOffset = 10; private static void SetDefaultParameterSize(IDbDataParameter dbParam, SqlType sqlType) { @@ -130,6 +132,12 @@ dbParam.Size = MaxStringSize; } break; + case DbType.DateTime2: + dbParam.Size = MaxDateTime2; + break; + case DbType.DateTimeOffset: + dbParam.Size = MaxDateTimeOffset; + break; } } Added: trunk/nhibernate/src/NHibernate.Test/DriverTest/EntityForMs2008.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/DriverTest/EntityForMs2008.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/DriverTest/EntityForMs2008.hbm.xml 2010-08-02 22:34:19 UTC (rev 5101) @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="utf-8" ?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" + namespace="NHibernate.Test.DriverTest" + assembly="NHibernate.Test"> + + <class name="EntityForMs2008"> + <id name="Id"> + <generator class="native" /> + </id> + <property name="DateTimeProp" type="DateTime2"/> + <property name="TimeSpanProp" type="TimeSpan"/> + </class> +</hibernate-mapping> \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate.Test/DriverTest/MultiTypeEntity.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/DriverTest/MultiTypeEntity.hbm.xml 2010-08-02 21:44:15 UTC (rev 5100) +++ trunk/nhibernate/src/NHibernate.Test/DriverTest/MultiTypeEntity.hbm.xml 2010-08-02 22:34:19 UTC (rev 5101) @@ -16,5 +16,6 @@ <property name="BinaryBlob" type="BinaryBlob"/> <property name="Binary" type="Byte[]"/> <property name="StringClob" type="StringClob"/> - </class> + <property name="DateTimeProp" type="DateTime"/> + </class> </hibernate-mapping> \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/DriverTest/Sql2008DateTime2Test.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/DriverTest/Sql2008DateTime2Test.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/DriverTest/Sql2008DateTime2Test.cs 2010-08-02 22:34:19 UTC (rev 5101) @@ -0,0 +1,74 @@ +using System; +using System.Collections; +using NHibernate.Cfg; +using NHibernate.Dialect; +using NUnit.Framework; +using SharpTestsEx; +using Environment = NHibernate.Cfg.Environment; + +namespace NHibernate.Test.DriverTest +{ + public class EntityForMs2008 + { + public virtual int Id { get; set; } + public virtual DateTime DateTimeProp { get; set; } + public virtual TimeSpan TimeSpanProp { get; set; } + } + + public class Sql2008DateTime2Test : TestCase + { + protected override void Configure(Configuration configuration) + { + configuration.SetProperty(Environment.PrepareSql, "true"); + } + protected override string MappingsAssembly + { + get { return "NHibernate.Test"; } + } + + protected override IList Mappings + { + get { return new[] { "DriverTest.EntityForMs2008.hbm.xml" }; } + } + + protected override bool AppliesTo(Dialect.Dialect dialect) + { + return dialect is MsSql2008Dialect; + } + + [Test] + public void Crud() + { + var expectedMoment = new DateTime(1848, 6, 1, 12, 00, 00, 123); + var expectedLapse = new TimeSpan((DateTime.Now - expectedMoment).Ticks); + object savedId; + using (ISession s = OpenSession()) + using (ITransaction t = s.BeginTransaction()) + { + savedId = s.Save(new EntityForMs2008 + { + DateTimeProp = expectedMoment, + TimeSpanProp = expectedLapse, + }); + t.Commit(); + } + + using (ISession s = OpenSession()) + using (ITransaction t = s.BeginTransaction()) + { + var m = s.Get<EntityForMs2008>(savedId); + m.DateTimeProp.Should().Be(expectedMoment); + m.TimeSpanProp.Should().Be(expectedLapse); + t.Commit(); + } + + using (ISession s = OpenSession()) + using (ITransaction t = s.BeginTransaction()) + { + s.CreateQuery("delete from EntityForMs2008").ExecuteUpdate(); + t.Commit(); + } + } + + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate.Test/DriverTest/SqlClientDriverFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/DriverTest/SqlClientDriverFixture.cs 2010-08-02 21:44:15 UTC (rev 5100) +++ trunk/nhibernate/src/NHibernate.Test/DriverTest/SqlClientDriverFixture.cs 2010-08-02 22:34:19 UTC (rev 5101) @@ -1,3 +1,4 @@ +using System; using System.Collections; using NHibernate.Cfg; using NHibernate.Dialect; @@ -8,6 +9,10 @@ { public class MultiTypeEntity { + public MultiTypeEntity() + { + DateTimeProp = DateTime.Now; + } public virtual int Id { get; set; } public virtual string StringProp { get; set; } public virtual string AnsiStringProp { get; set; } @@ -18,6 +23,7 @@ public virtual byte[] BinaryBlob { get; set; } public virtual byte[] Binary { get; set; } public virtual string StringClob { get; set; } + public virtual DateTime DateTimeProp { get; set; } } [TestFixture] Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-08-02 21:44:15 UTC (rev 5100) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-08-02 22:34:19 UTC (rev 5101) @@ -179,6 +179,7 @@ <Compile Include="Criteria\ProjectionsTest.cs" /> <Compile Include="Criteria\Reptile.cs" /> <Compile Include="DialectTest\MsSqlCe40DialectFixture.cs" /> + <Compile Include="DriverTest\Sql2008DateTime2Test.cs" /> <Compile Include="DriverTest\SqlClientDriverFixture.cs" /> <Compile Include="DriverTest\SqlServerCeDriverFixture.cs" /> <Compile Include="EngineTest\CallableParserFixture.cs" /> @@ -2223,6 +2224,7 @@ <EmbeddedResource Include="CfgTest\Loquacious\EntityToCache.hbm.xml" /> <EmbeddedResource Include="DriverTest\SqlServerCeEntity.hbm.xml" /> <EmbeddedResource Include="CollectionTest\NullableValueTypeElementMapFixture.hbm.xml" /> + <EmbeddedResource Include="DriverTest\EntityForMs2008.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> <EmbeddedResource Include="NHSpecificTest\NH2245\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH2257\Mappings.hbm.xml" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2010-08-03 13:04:44
|
Revision: 5104 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5104&view=rev Author: fabiomaulo Date: 2010-08-03 13:04:37 +0000 (Tue, 03 Aug 2010) Log Message: ----------- Fix NH-2103 Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs trunk/nhibernate/src/NHibernate/NHibernate.csproj trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate/Cfg/BindMappingEventArgs.cs trunk/nhibernate/src/NHibernate.Test/CfgTest/ConfigurationAddMappingEvents.cs Added: trunk/nhibernate/src/NHibernate/Cfg/BindMappingEventArgs.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/BindMappingEventArgs.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Cfg/BindMappingEventArgs.cs 2010-08-03 13:04:37 UTC (rev 5104) @@ -0,0 +1,19 @@ +using System; +using NHibernate.Cfg.MappingSchema; + +namespace NHibernate.Cfg +{ + public class BindMappingEventArgs: EventArgs + { + public BindMappingEventArgs(Dialect.Dialect dialect, HbmMapping mapping, string fileName) + { + Dialect = dialect; + Mapping = mapping; + FileName = fileName; + } + + public Dialect.Dialect Dialect { get; private set; } + public HbmMapping Mapping { get; private set; } + public string FileName { get; private set; } + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs 2010-08-03 11:41:25 UTC (rev 5103) +++ trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs 2010-08-03 13:04:37 UTC (rev 5104) @@ -496,6 +496,9 @@ AddDeserializedMapping(doc.Document, doc.Name); } + public event EventHandler<BindMappingEventArgs> BeforeBindMapping; + public event EventHandler<BindMappingEventArgs> AfterBindMapping; + /// <summary> /// Add mapping data using deserialized class. /// </summary> @@ -510,9 +513,11 @@ try { Dialect.Dialect dialect = Dialect.Dialect.GetDialect(properties); + OnBeforeBindMapping(new BindMappingEventArgs(dialect, mappingDocument, documentFileName)); Mappings mappings = CreateMappings(dialect); new MappingRootBinder(mappings, dialect).Bind(mappingDocument); + OnAfterBindMapping(new BindMappingEventArgs(dialect, mappingDocument, documentFileName)); } catch (Exception e) { @@ -523,6 +528,24 @@ } } + private void OnAfterBindMapping(BindMappingEventArgs bindMappingEventArgs) + { + var handler = AfterBindMapping; + if (handler != null) + { + handler(this, bindMappingEventArgs); + } + } + + private void OnBeforeBindMapping(BindMappingEventArgs bindMappingEventArgs) + { + var handler = BeforeBindMapping; + if(handler != null) + { + handler(this, bindMappingEventArgs); + } + } + /// <summary> /// Create a new <see cref="Mappings" /> to add classes and collection /// mappings to. Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-08-03 11:41:25 UTC (rev 5103) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-08-03 13:04:37 UTC (rev 5104) @@ -467,6 +467,7 @@ <Compile Include="Bytecode\ProxyFactoryFactoryNotConfiguredException.cs" /> <Compile Include="Bytecode\UnableToLoadProxyFactoryFactoryException.cs" /> <Compile Include="Cache\FakeCache.cs" /> + <Compile Include="Cfg\BindMappingEventArgs.cs" /> <Compile Include="Cfg\EntityCacheUsage.cs" /> <Compile Include="Cfg\FilterSecondPassArgs.cs" /> <Compile Include="Cfg\Hbm2ddlKeyWords.cs" /> Added: trunk/nhibernate/src/NHibernate.Test/CfgTest/ConfigurationAddMappingEvents.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/CfgTest/ConfigurationAddMappingEvents.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/CfgTest/ConfigurationAddMappingEvents.cs 2010-08-03 13:04:37 UTC (rev 5104) @@ -0,0 +1,76 @@ +using System.Collections.Generic; +using System.Linq; +using NHibernate.Cfg; +using NHibernate.Cfg.Loquacious; +using NHibernate.Dialect; +using NUnit.Framework; +using SharpTestsEx; + +namespace NHibernate.Test.CfgTest +{ + public class ConfigurationAddMappingEvents + { + private const string ProductLineMapping = + @"<?xml version='1.0' encoding='utf-8' ?> +<hibernate-mapping xmlns='urn:nhibernate-mapping-2.2'> + <class entity-name='ProductLine'> + <id name='Id' type='int'> + <generator class='hilo'/> + </id> + <property name='Description' not-null='true' length='200' type='string'/> + <bag name='Models' cascade='all' inverse='true'> + <key column='productId'/> + <one-to-many class='Model'/> + </bag> + </class> +</hibernate-mapping> +"; + private const string ModelMapping = + @"<?xml version='1.0' encoding='utf-8' ?> +<hibernate-mapping xmlns='urn:nhibernate-mapping-2.2'> + <class entity-name='Model'> + <id name='Id' type='int'> + <generator class='hilo'/> + </id> + + <property name='Name' not-null='true' length='25' type='string'/> + <property name='Description' not-null='true' length='200' type='string'/> + <many-to-one name='ProductLine' column='productId' not-null='true' class='ProductLine'/> + </class> +</hibernate-mapping> +"; + [Test] + public void WhenSubscribedToBeforeBindThenRaiseEventForEachMapping() + { + var listOfCalls = new List<BindMappingEventArgs>(); + var configuration = new Configuration(); + configuration.DataBaseIntegration(x => x.Dialect<MsSql2008Dialect>()); + configuration.BeforeBindMapping += (sender, args) => { sender.Should().Be.SameInstanceAs(configuration); listOfCalls.Add(args); }; + + configuration.AddXmlString(ProductLineMapping); + configuration.AddXmlString(ModelMapping); + + listOfCalls.Count.Should().Be(2); + listOfCalls.Select(x => x.FileName).All(x => x.Satisfy(filename => filename != null)); + listOfCalls.Select(x => x.Mapping).All(x => x.Satisfy(mappingDoc => mappingDoc != null)); + listOfCalls.Select(x => x.Dialect).All(x => x.Satisfy(dialect => dialect.GetType() == typeof(MsSql2008Dialect))); + } + + [Test] + public void WhenSubscribedToAfterBindThenRaiseEventForEachMapping() + { + var listOfCalls = new List<BindMappingEventArgs>(); + var configuration = new Configuration(); + configuration.DataBaseIntegration(x => x.Dialect<MsSql2008Dialect>()); + configuration.AfterBindMapping += (sender, args) => { sender.Should().Be.SameInstanceAs(configuration); listOfCalls.Add(args); }; + + configuration.AddXmlString(ProductLineMapping); + configuration.AddXmlString(ModelMapping); + + listOfCalls.Count.Should().Be(2); + listOfCalls.Select(x => x.FileName).All(x => x.Satisfy(filename => filename != null)); + listOfCalls.Select(x => x.Mapping).All(x => x.Satisfy(mappingDoc => mappingDoc != null)); + listOfCalls.Select(x => x.Dialect).All(x => x.Satisfy(dialect => dialect.GetType() == typeof(MsSql2008Dialect))); + } + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-08-03 11:41:25 UTC (rev 5103) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-08-03 13:04:37 UTC (rev 5104) @@ -109,6 +109,7 @@ <Compile Include="Cascade\JobBatch.cs" /> <Compile Include="Cascade\RefreshFixture.cs" /> <Compile Include="CfgTest\AccessorsSerializableTest.cs" /> + <Compile Include="CfgTest\ConfigurationAddMappingEvents.cs" /> <Compile Include="CfgTest\ConfigurationFixture.cs" /> <Compile Include="CfgTest\ConfigurationSchemaFixture.cs" /> <Compile Include="CfgTest\ConfigurationSerializationTests.cs" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2010-08-04 19:54:39
|
Revision: 5110 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5110&view=rev Author: fabiomaulo Date: 2010-08-04 19:54:32 +0000 (Wed, 04 Aug 2010) Log Message: ----------- Apply NH-2120 (by Nikolaos Tountas) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/NHibernate.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate/Driver/CsharpSqliteDriver.cs Added: trunk/nhibernate/src/NHibernate/Driver/CsharpSqliteDriver.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Driver/CsharpSqliteDriver.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Driver/CsharpSqliteDriver.cs 2010-08-04 19:54:32 UTC (rev 5110) @@ -0,0 +1,53 @@ +namespace NHibernate.Driver +{ + /// <summary> + /// NHibernate driver for the Community CsharpSqlite data provider. + /// <p> + /// Author: <a href="mailto:nic...@ho..."> Nikolaos Tountas </a> + /// </p> + /// </summary> + /// <remarks> + /// <p> + /// In order to use this Driver you must have the Community.CsharpSqlite.dll and Community.CsharpSqlite.SQLiteClient assemblies referenced. + /// </p> + /// <p> + /// Please check <a href="http://code.google.com/p/csharp-sqlite/"> http://code.google.com/p/csharp-sqlite/ </a> for more information regarding csharp-sqlite. + /// </p> + /// </remarks> + public class CsharpSqliteDriver : ReflectionBasedDriver + { + /// <summary> + /// Initializes a new instance of <see cref="CsharpSqliteDriver"/>. + /// </summary> + /// <exception cref="HibernateException"> + /// Thrown when the <c>Community.CsharpSqlite.dll</c> assembly can not be loaded. + /// </exception> + public CsharpSqliteDriver() + : base( + "Community.CsharpSqlite.SQLiteClient", + "Community.CsharpSqlite.SQLiteClient.SqliteConnection", + "Community.CsharpSqlite.SQLiteClient.SqliteCommand") + { + } + + public override bool UseNamedPrefixInSql + { + get { return true; } + } + + public override bool UseNamedPrefixInParameter + { + get { return true; } + } + + public override string NamedPrefix + { + get { return "@"; } + } + + public override bool SupportsMultipleOpenReaders + { + get { return false; } + } + } +} Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-08-04 17:40:14 UTC (rev 5109) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-08-04 19:54:32 UTC (rev 5110) @@ -596,6 +596,7 @@ <Compile Include="Dialect\Schema\SybaseAnywhereMetaData.cs" /> <Compile Include="Dialect\SybaseASA10Dialect.cs" /> <Compile Include="Dialect\SybaseASA9Dialect.cs" /> + <Compile Include="Driver\CsharpSqliteDriver.cs" /> <Compile Include="Driver\IfxDriver.cs" /> <Compile Include="Driver\OracleLiteDataClientDriver.cs" /> <Compile Include="Engine\Query\CallableParser.cs" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2010-08-05 03:06:28
|
Revision: 5111 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5111&view=rev Author: fabiomaulo Date: 2010-08-05 03:06:22 +0000 (Thu, 05 Aug 2010) Log Message: ----------- Fix NH-2158 (thanks to Richard Birkby) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Criterion/SqlFunctionProjection.cs trunk/nhibernate/src/NHibernate.Test/ExpressionTest/Projection/ProjectionFixture.cs Modified: trunk/nhibernate/src/NHibernate/Criterion/SqlFunctionProjection.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Criterion/SqlFunctionProjection.cs 2010-08-04 19:54:32 UTC (rev 5110) +++ trunk/nhibernate/src/NHibernate/Criterion/SqlFunctionProjection.cs 2010-08-05 03:06:22 UTC (rev 5111) @@ -1,4 +1,5 @@ using System; +using System.Collections; using System.Collections.Generic; using NHibernate.Dialect.Function; using NHibernate.Engine; @@ -72,7 +73,7 @@ IDictionary<string, IFilter> enabledFilters) { ISQLFunction sqlFunction = GetFunction(criteriaQuery); - List<string> tokens = new List<string>(); + var tokens = new ArrayList(); string replacemenToken = Guid.NewGuid().ToString("n"); for (int i = 0; i < args.Length; i++) { Modified: trunk/nhibernate/src/NHibernate.Test/ExpressionTest/Projection/ProjectionFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/ExpressionTest/Projection/ProjectionFixture.cs 2010-08-04 19:54:32 UTC (rev 5110) +++ trunk/nhibernate/src/NHibernate.Test/ExpressionTest/Projection/ProjectionFixture.cs 2010-08-05 03:06:22 UTC (rev 5111) @@ -8,6 +8,7 @@ namespace NHibernate.Test.ExpressionTest.Projection { using Util; + using NHibernate.Dialect.Function; [TestFixture] public class ProjectionFixture : BaseExpressionFixture @@ -88,6 +89,19 @@ } [Test] + public void NvlTest() + { + ISession session = factory.OpenSession(); + IProjection expression = Projections.SqlFunction(new NvlFunction(), + NHibernateUtil.String, Projections.Property("Name"), Projections.Property("Address")); + CreateObjects(typeof (Simple), session); + SqlString sqlString = expression.ToSqlString(criteria, 0, criteriaQuery, new CollectionHelper.EmptyMapClass<string, IFilter>()); + string expectedSql = "nvl(sql_alias.Name, sql_alias.address) as y0_"; + CompareSqlStrings(sqlString, expectedSql, 0); + session.Close(); + } + + [Test] public void DistinctTest() { ISession session = factory.OpenSession(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2010-08-05 12:20:16
|
Revision: 5113 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5113&view=rev Author: fabiomaulo Date: 2010-08-05 12:20:09 +0000 (Thu, 05 Aug 2010) Log Message: ----------- Partial fix of NH-2263 2 step (thanks to Patrick Earl) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Context/ManagedWebSessionContext.cs trunk/nhibernate/src/NHibernate/Context/WebSessionContext.cs trunk/nhibernate/src/NHibernate/NHibernate.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate/Context/ReflectiveHttpContext.cs Modified: trunk/nhibernate/src/NHibernate/Context/ManagedWebSessionContext.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Context/ManagedWebSessionContext.cs 2010-08-05 11:06:46 UTC (rev 5112) +++ trunk/nhibernate/src/NHibernate/Context/ManagedWebSessionContext.cs 2010-08-05 12:20:09 UTC (rev 5113) @@ -1,13 +1,12 @@ using System; using System.Collections; -using System.Web; using NHibernate.Engine; namespace NHibernate.Context { /// <summary> /// Provides a <see cref="ISessionFactory.GetCurrentSession()">current session</see> - /// for each <see cref="System.Web.HttpContext"/>. + /// for each System.Web.HttpContext. /// Works only with Web Applications. /// </summary> [Serializable] @@ -23,7 +22,7 @@ public ISession CurrentSession() { - ISession currentSession = GetExistingSession(HttpContext.Current, factory); + ISession currentSession = GetExistingSession(ReflectiveHttpContext.HttpContextCurrentGetter(), factory); if (currentSession == null) { throw new HibernateException("No session bound to the current HttpContext"); @@ -33,20 +32,20 @@ #region Static API - public static void Bind(HttpContext context, ISession session) + public static void Bind(object httpContext, ISession session) { - GetSessionMap(context, true)[((ISessionImplementor) session).Factory] = session; + GetSessionMap(httpContext, true)[((ISessionImplementor) session).Factory] = session; } - public static bool HasBind(HttpContext context, ISessionFactory factory) + public static bool HasBind(object httpContext, ISessionFactory factory) { - return GetExistingSession(context, factory) != null; + return GetExistingSession(httpContext, factory) != null; } - public static ISession Unbind(HttpContext context, ISessionFactory factory) + public static ISession Unbind(object httpContext, ISessionFactory factory) { ISession result = null; - IDictionary sessionMap = GetSessionMap(context, false); + IDictionary sessionMap = GetSessionMap(httpContext, false); if (sessionMap != null) { result = sessionMap[factory] as ISession; @@ -57,9 +56,9 @@ #endregion - private static ISession GetExistingSession(HttpContext context, ISessionFactory factory) + private static ISession GetExistingSession(object httpContext, ISessionFactory factory) { - IDictionary sessionMap = GetSessionMap(context, false); + IDictionary sessionMap = GetSessionMap(httpContext, false); if (sessionMap == null) { return null; @@ -68,15 +67,16 @@ return sessionMap[factory] as ISession; } - private static IDictionary GetSessionMap(HttpContext context, bool create) + private static IDictionary GetSessionMap(object httpContext, bool create) { - IDictionary map = context.Items[SessionFactoryMapKey] as IDictionary; + IDictionary httpContextItems = ReflectiveHttpContext.HttpContextItemsGetter(httpContext); + var map = httpContextItems[SessionFactoryMapKey] as IDictionary; if (map == null && create) { map = new Hashtable(); - context.Items[SessionFactoryMapKey] = map; + httpContextItems[SessionFactoryMapKey] = map; } return map; } } -} +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate/Context/ReflectiveHttpContext.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Context/ReflectiveHttpContext.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Context/ReflectiveHttpContext.cs 2010-08-05 12:20:09 UTC (rev 5113) @@ -0,0 +1,50 @@ +using System; +using System.Collections; +using System.Linq.Expressions; +using System.Reflection; + +namespace NHibernate.Context +{ + /// <summary> + /// This class allows access to the HttpContext without referring to HttpContext at compile time. + /// The accessors are cached as delegates for performance. + /// </summary> + public static class ReflectiveHttpContext + { + static ReflectiveHttpContext() + { + CreateCurrentHttpContextGetter(); + CreateHttpContextItemsGetter(); + } + + public static Func<object> HttpContextCurrentGetter { get; private set; } + + public static Func<object, IDictionary> HttpContextItemsGetter { get; private set; } + + public static IDictionary HttpContextCurrentItems + { + get { return HttpContextItemsGetter(HttpContextCurrentGetter()); } + } + + private static System.Type HttpContextType + { + get { return System.Type.GetType("System.Web.HttpContext, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); } + } + + private static void CreateCurrentHttpContextGetter() + { + PropertyInfo currentProperty = HttpContextType.GetProperty("Current", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy); + Expression propertyExpression = Expression.Property(null, currentProperty); + Expression convertedExpression = Expression.Convert(propertyExpression, typeof (object)); + HttpContextCurrentGetter = (Func<object>) Expression.Lambda(convertedExpression).Compile(); + } + + private static void CreateHttpContextItemsGetter() + { + ParameterExpression contextParam = Expression.Parameter(typeof (object), "context"); + Expression convertedParam = Expression.Convert(contextParam, HttpContextType); + Expression itemsProperty = Expression.Property(convertedParam, "Items"); + HttpContextItemsGetter = (Func<object, IDictionary>) Expression.Lambda(itemsProperty, contextParam).Compile(); + } + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Context/WebSessionContext.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Context/WebSessionContext.cs 2010-08-05 11:06:46 UTC (rev 5112) +++ trunk/nhibernate/src/NHibernate/Context/WebSessionContext.cs 2010-08-05 12:20:09 UTC (rev 5113) @@ -1,32 +1,28 @@ using System; using System.Collections; -using System.Web; - using NHibernate.Engine; namespace NHibernate.Context { /// <summary> /// Provides a <see cref="ISessionFactory.GetCurrentSession()">current session</see> - /// for each <see cref="System.Web.HttpContext"/>. Works only with web applications. + /// for each System.Web.HttpContext. Works only with web applications. /// </summary> [Serializable] public class WebSessionContext : MapBasedSessionContext { private const string SessionFactoryMapKey = "NHibernate.Context.WebSessionContext.SessionFactoryMapKey"; - public WebSessionContext(ISessionFactoryImplementor factory) : base(factory) - { - } + public WebSessionContext(ISessionFactoryImplementor factory) : base(factory) {} protected override IDictionary GetMap() { - return HttpContext.Current.Items[SessionFactoryMapKey] as IDictionary; + return ReflectiveHttpContext.HttpContextCurrentItems[SessionFactoryMapKey] as IDictionary; } protected override void SetMap(IDictionary value) { - HttpContext.Current.Items[SessionFactoryMapKey] = value; + ReflectiveHttpContext.HttpContextCurrentItems[SessionFactoryMapKey] = value; } } } \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-08-05 11:06:46 UTC (rev 5112) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-08-05 12:20:09 UTC (rev 5113) @@ -53,7 +53,6 @@ <RequiredTargetFramework>3.0</RequiredTargetFramework> </Reference> <Reference Include="System.Transactions" /> - <Reference Include="System.Web" /> <Reference Include="System.Xml" /> <Reference Include="Antlr3.Runtime, Version=3.1.0.39271, Culture=neutral, PublicKeyToken=3a9cab8f8d22bfb7"> <SpecificVersion>False</SpecificVersion> @@ -564,6 +563,7 @@ </Compile> <Compile Include="Cfg\XmlHbmBinding\TypeBinder.cs" /> <Compile Include="Cfg\XmlHbmBinding\ValuePropertyBinder.cs" /> + <Compile Include="Context\ReflectiveHttpContext.cs" /> <Compile Include="Context\WcfOperationSessionContext.cs" /> <Compile Include="Criterion\GroupedProjection.cs" /> <Compile Include="Criterion\IPropertyProjection.cs" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2010-08-05 16:11:21
|
Revision: 5116 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5116&view=rev Author: fabiomaulo Date: 2010-08-05 16:11:15 +0000 (Thu, 05 Aug 2010) Log Message: ----------- Fix NH-1421 Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Impl/AbstractQueryImpl.cs trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1421/ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1421/AnEntity.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1421/Fixture.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1421/Mappings.hbm.xml Modified: trunk/nhibernate/src/NHibernate/Impl/AbstractQueryImpl.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Impl/AbstractQueryImpl.cs 2010-08-05 12:39:25 UTC (rev 5115) +++ trunk/nhibernate/src/NHibernate/Impl/AbstractQueryImpl.cs 2010-08-05 16:11:15 UTC (rev 5116) @@ -657,6 +657,14 @@ throw new ArgumentException("Parameter " + name + " does not exist as a named parameter in [" + QueryString + "]"); } + if (type == null) + { + throw new ArgumentNullException("type","Can't determine the type of parameter-list elements."); + } + if(vals.Count == 0) + { + throw new QueryException(string.Format("An empty parameter-list generate wrong SQL; parameter name '{0}'", name)); + } namedParameterLists[name] = new TypedValue(type, vals, session.EntityMode); return this; } @@ -665,7 +673,7 @@ { if (vals == null) { - throw new QueryException("Collection must be not null!"); + throw new ArgumentNullException("vals"); } if (!parameterMetadata.NamedParameterNames.Contains(name)) @@ -676,7 +684,7 @@ if (vals.Count == 0) { - SetParameterList(name, vals, null); + SetParameterList(name, vals, GuessType(vals.GetCollectionElementType())); } else { @@ -690,12 +698,12 @@ public IQuery SetParameterList(string name, object[] vals, IType type) { - return SetParameterList(name, new ArrayList(vals), type); + return SetParameterList(name, vals as ICollection, type); } public IQuery SetParameterList(string name, object[] vals) { - return SetParameterList(name, new ArrayList(vals)); + return SetParameterList(name, vals as ICollection); } #endregion Modified: trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs 2010-08-05 12:39:25 UTC (rev 5115) +++ trunk/nhibernate/src/NHibernate/Util/ReflectHelper.cs 2010-08-05 16:11:15 UTC (rev 5116) @@ -1,5 +1,7 @@ using System; +using System.Collections; using System.Collections.Generic; +using System.Linq; using System.Reflection; using System.Text; using log4net; @@ -621,5 +623,41 @@ { return method.Name.Substring(4); } + + public static System.Type GetCollectionElementType(this IEnumerable collectionInstance) + { + if (collectionInstance == null) + { + throw new ArgumentNullException("collectionInstance"); + } + var collectionType = collectionInstance.GetType(); + return GetCollectionElementType(collectionType); + } + + public static System.Type GetCollectionElementType(System.Type collectionType) + { + if (collectionType == null) + { + throw new ArgumentNullException("collectionType"); + } + if (collectionType.IsArray) + { + return collectionType.GetElementType(); + } + if (collectionType.IsGenericType) + { + List<System.Type> interfaces = collectionType.GetInterfaces().Where(t => t.IsGenericType).ToList(); + if (collectionType.IsInterface) + { + interfaces.Add(collectionType); + } + var enumerableInterface = interfaces.FirstOrDefault(t => t.GetGenericTypeDefinition() == typeof (IEnumerable<>)); + if (enumerableInterface != null) + { + return enumerableInterface.GetGenericArguments()[0]; + } + } + return null; + } } } Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1421/AnEntity.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1421/AnEntity.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1421/AnEntity.cs 2010-08-05 16:11:15 UTC (rev 5116) @@ -0,0 +1,7 @@ +namespace NHibernate.Test.NHSpecificTest.NH1421 +{ + public class AnEntity + { + public virtual long Id { get; set; } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1421/Fixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1421/Fixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1421/Fixture.cs 2010-08-05 16:11:15 UTC (rev 5116) @@ -0,0 +1,62 @@ +using System; +using System.Collections; +using NUnit.Framework; +using SharpTestsEx; +using System.Collections.ObjectModel; + +namespace NHibernate.Test.NHSpecificTest.NH1421 +{ + public class Fixture: BugTestCase + { + [Test] + public void WhenParameterListIsEmptyArrayUsingQueryThenDoesNotTrowsNullReferenceException() + { + using (var s = OpenSession()) + { + var query = s.CreateQuery("from AnEntity a where a.id in (:myList)"); + query.Executing(x => x.SetParameterList("myList", new long[0])).Throws().And.Exception.Should().Not.Be.InstanceOf<NullReferenceException>(); + } + } + + [Test] + public void WhenParameterListIsEmptyGenericCollectionUsingQueryThenDoesNotTrowsNullReferenceException() + { + using (var s = OpenSession()) + { + var query = s.CreateQuery("from AnEntity a where a.id in (:myList)"); + query.Executing(x => x.SetParameterList("myList", new Collection<long>())).Throws().And.Exception.Should().Not.Be.InstanceOf<NullReferenceException>(); + } + } + + [Test] + public void WhenParameterListIsEmptyCollectionUsingQueryThenTrowsArgumentException() + { + using (var s = OpenSession()) + { + var query = s.CreateQuery("from AnEntity a where a.id in (:myList)"); + query.Executing(x => x.SetParameterList("myList", new ArrayList())).Throws().And.Exception.Should().Be.InstanceOf<ArgumentException>(); + } + } + + [Test] + public void WhenParameterListIsNullUsingQueryThenTrowsArgumentException() + { + using (var s = OpenSession()) + { + var query = s.CreateQuery("from AnEntity a where a.id in (:myList)"); + query.Executing(x => x.SetParameterList("myList", null)).Throws().And.Exception.Should().Be.InstanceOf<ArgumentNullException>(); + } + } + + [Test] + public void WhenParameterListIsEmptyUsingQueryThenDoesNotTrowsNullReferenceException() + { + using (var s = OpenSession()) + { + var query = s.CreateQuery("from AnEntity a where a.id in (:myList)"); + query.Executing(x => x.SetParameterList("myList", new long[0]).List()).Throws().And.Exception.Should().Not.Be.InstanceOf<NullReferenceException>(); + } + } + + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1421/Mappings.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1421/Mappings.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1421/Mappings.hbm.xml 2010-08-05 16:11:15 UTC (rev 5116) @@ -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.NH1421"> + + <class name="AnEntity"> + <id name="Id"> + <generator class="assigned" /> + </id> + </class> + +</hibernate-mapping> Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-08-05 12:39:25 UTC (rev 5115) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-08-05 16:11:15 UTC (rev 5116) @@ -445,6 +445,8 @@ <Compile Include="Linq\QueryCacheableTests.cs" /> <Compile Include="Linq\QueryReuseTests.cs" /> <Compile Include="Linq\ReadonlyTestCase.cs" /> + <Compile Include="NHSpecificTest\NH1421\AnEntity.cs" /> + <Compile Include="NHSpecificTest\NH1421\Fixture.cs" /> <Compile Include="NHSpecificTest\NH2148\BugFixture.cs" /> <Compile Include="NHSpecificTest\NH2148\Domain.cs" /> <Compile Include="NHSpecificTest\NH2245\Fixture.cs" /> @@ -2230,6 +2232,7 @@ <EmbeddedResource Include="CollectionTest\NullableValueTypeElementMapFixture.hbm.xml" /> <EmbeddedResource Include="DriverTest\EntityForMs2008.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> + <EmbeddedResource Include="NHSpecificTest\NH1421\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH2148\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH2245\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH2257\Mappings.hbm.xml" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2010-08-06 22:29:28
|
Revision: 5119 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5119&view=rev Author: fabiomaulo Date: 2010-08-06 22:29:22 +0000 (Fri, 06 Aug 2010) Log Message: ----------- Fix NH-1836 Modified Paths: -------------- trunk/nhibernate/src/NHibernate/IMultiQuery.cs trunk/nhibernate/src/NHibernate/Impl/MultiQueryImpl.cs trunk/nhibernate/src/NHibernate/Transform/AliasToBeanResultTransformer.cs trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1836/ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1836/Entity.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1836/EntityDTO.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1836/Fixture.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1836/Mappings.hbm.xml Modified: trunk/nhibernate/src/NHibernate/IMultiQuery.cs =================================================================== --- trunk/nhibernate/src/NHibernate/IMultiQuery.cs 2010-08-06 19:57:08 UTC (rev 5118) +++ trunk/nhibernate/src/NHibernate/IMultiQuery.cs 2010-08-06 22:29:22 UTC (rev 5119) @@ -314,6 +314,9 @@ /// Set a strategy for handling the query results. This can be used to change /// "shape" of the query result. /// </summary> + /// <remarks> + /// The <param name="transformer"/> will be applied after the transformer of each single query. + /// </remarks> IMultiQuery SetResultTransformer(IResultTransformer transformer); /// <summary> Modified: trunk/nhibernate/src/NHibernate/Impl/MultiQueryImpl.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Impl/MultiQueryImpl.cs 2010-08-06 19:57:08 UTC (rev 5118) +++ trunk/nhibernate/src/NHibernate/Impl/MultiQueryImpl.cs 2010-08-06 22:29:22 UTC (rev 5119) @@ -410,45 +410,52 @@ protected virtual IList GetResultList(IList results) { - for (int i = 0, len = results.Count; i < len; ++i) + var multiqueryHolderInstatiator = GetMultiQueryHolderInstatiator(); + int len = results.Count; + for (int i = 0; i < len; ++i) { - IList subList = (IList)results[i]; - QueryParameters parameter = Parameters[i]; - HolderInstantiator holderInstantiator = GetHolderInstantiator(parameter); - if (holderInstantiator.IsRequired) - { - for (int j = 0; j < subList.Count; j++) - { - object[] row = subList[j] as object[] ?? new[] { subList[j] }; - subList[j] = holderInstantiator.Instantiate(row); - } - - IResultTransformer transformer = - holderInstantiator.ResultTransformer; - if (transformer != null) - { - results[i] = transformer.TransformList(subList); - } - } + // First use the transformer of each query transformig each row and then the list + results[i] = GetTransformedResults((IList)results[i], GetQueryHolderInstantiator(i)); + // then use the MultiQueryTransformer (if it has some sense...) using, as source, the transformed result. + results[i] = GetTransformedResults((IList)results[i], multiqueryHolderInstatiator); } return results; } - private HolderInstantiator GetHolderInstantiator(QueryParameters parameter) + private IList GetTransformedResults(IList source, HolderInstantiator holderInstantiator) { - //if multi query has result transformer, then this will override IQuery transformations - if (resultTransformer != null) + if (!holderInstantiator.IsRequired) { - return new HolderInstantiator(resultTransformer, null); + return source; } - if (parameter.ResultTransformer != null) + for (int j = 0; j < source.Count; j++) { - return new HolderInstantiator(parameter.ResultTransformer, null); + object[] row = source[j] as object[] ?? new[] { source[j] }; + source[j] = holderInstantiator.Instantiate(row); } - return HolderInstantiator.NoopInstantiator; + + return holderInstantiator.ResultTransformer.TransformList(source); } + private HolderInstantiator GetQueryHolderInstantiator(int queryPosition) + { + // TODO : we need a test to check the behavior when the query has a 'new' istead a trasformer + // we should take the HolderInstantiator directly from QueryTranslator... taking care with Parameters. + return Parameters[queryPosition].ResultTransformer != null ? + new HolderInstantiator(Parameters[queryPosition].ResultTransformer, translators[queryPosition].ReturnAliases) + : HolderInstantiator.NoopInstantiator; + } + private HolderInstantiator GetMultiQueryHolderInstatiator() + { + return HasMultiQueryResultTrasformer() ? new HolderInstantiator(resultTransformer, null) : HolderInstantiator.NoopInstantiator; + } + + private bool HasMultiQueryResultTrasformer() + { + return resultTransformer != null; + } + protected ArrayList DoList() { bool statsEnabled = session.Factory.Statistics.IsStatisticsEnabled; Modified: trunk/nhibernate/src/NHibernate/Transform/AliasToBeanResultTransformer.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Transform/AliasToBeanResultTransformer.cs 2010-08-06 19:57:08 UTC (rev 5118) +++ trunk/nhibernate/src/NHibernate/Transform/AliasToBeanResultTransformer.cs 2010-08-06 22:29:22 UTC (rev 5119) @@ -61,6 +61,10 @@ public object TransformTuple(object[] tuple, String[] aliases) { + if (aliases == null) + { + throw new ArgumentNullException("aliases"); + } object result; try Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1836/Entity.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1836/Entity.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1836/Entity.cs 2010-08-06 22:29:22 UTC (rev 5119) @@ -0,0 +1,7 @@ +namespace NHibernate.Test.NHSpecificTest.NH1836 +{ + public class Entity + { + public virtual int Id { get; set; } + } +} Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1836/EntityDTO.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1836/EntityDTO.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1836/EntityDTO.cs 2010-08-06 22:29:22 UTC (rev 5119) @@ -0,0 +1,7 @@ +namespace NHibernate.Test.NHSpecificTest.NH1836 +{ + public class EntityDTO + { + public int EntityId { get; set; } + } +} Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1836/Fixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1836/Fixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1836/Fixture.cs 2010-08-06 22:29:22 UTC (rev 5119) @@ -0,0 +1,58 @@ +using System.Collections; +using NHibernate.Transform; +using NUnit.Framework; +using SharpTestsEx; + +namespace NHibernate.Test.NHSpecificTest.NH1836 +{ + [TestFixture] + public class Fixture : BugTestCase + { + protected override bool AppliesTo(Engine.ISessionFactoryImplementor factory) + { + return factory.ConnectionProvider.Driver.SupportsMultipleQueries; + } + + protected override void OnSetUp() + { + base.OnSetUp(); + + using (var s = OpenSession()) + using (var t = s.BeginTransaction()) + { + s.Save(new Entity {Id = 1}); + t.Commit(); + } + } + + [Test] + public void AliasToBeanTransformerShouldApplyCorrectlyToMultiQuery() + { + using (var s = OpenSession()) + using (var t = s.BeginTransaction()) + { + IMultiQuery multiQuery = s.CreateMultiQuery() + .Add(s.CreateQuery("select entity.Id as EntityId from Entity entity") + .SetResultTransformer(Transformers.AliasToBean(typeof(EntityDTO))) + ); + + IList results = null; + Executing.This(() => results = multiQuery.List()).Should().NotThrow(); + var elementOfFirstResult = ((IList)results[0])[0]; + elementOfFirstResult.Should().Be.OfType<EntityDTO>().And.ValueOf.EntityId.Should().Be(1); + } + } + + protected override void OnTearDown() + { + base.OnTearDown(); + + using (var s = OpenSession()) + using (var t = s.BeginTransaction()) + { + s.CreateQuery("delete from System.Object").ExecuteUpdate(); + t.Commit(); + } + } + } +} Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1836/Mappings.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1836/Mappings.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1836/Mappings.hbm.xml 2010-08-06 22:29:22 UTC (rev 5119) @@ -0,0 +1,10 @@ +<?xml version="1.0" encoding="utf-8" ?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" + namespace="NHibernate.Test.NHSpecificTest.NH1836" + assembly="NHibernate.Test"> + <class name="Entity"> + <id name="Id"> + <generator class="assigned" /> + </id> + </class> +</hibernate-mapping> Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-08-06 19:57:08 UTC (rev 5118) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-08-06 22:29:22 UTC (rev 5119) @@ -447,6 +447,9 @@ <Compile Include="Linq\ReadonlyTestCase.cs" /> <Compile Include="NHSpecificTest\NH1421\AnEntity.cs" /> <Compile Include="NHSpecificTest\NH1421\Fixture.cs" /> + <Compile Include="NHSpecificTest\NH1836\Entity.cs" /> + <Compile Include="NHSpecificTest\NH1836\EntityDTO.cs" /> + <Compile Include="NHSpecificTest\NH1836\Fixture.cs" /> <Compile Include="NHSpecificTest\NH2148\BugFixture.cs" /> <Compile Include="NHSpecificTest\NH2148\Domain.cs" /> <Compile Include="NHSpecificTest\NH2245\Fixture.cs" /> @@ -2235,6 +2238,7 @@ <EmbeddedResource Include="CollectionTest\NullableValueTypeElementMapFixture.hbm.xml" /> <EmbeddedResource Include="DriverTest\EntityForMs2008.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> + <EmbeddedResource Include="NHSpecificTest\NH1836\Mappings.hbm.xml" /> <EmbeddedResource Include="TypesTest\DateTimeClass.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1421\Mappings.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH2148\Mappings.hbm.xml" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |