|
From: <fab...@us...> - 2010-03-15 16:06:18
|
Revision: 4956
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4956&view=rev
Author: fabiomaulo
Date: 2010-03-15 16:06:07 +0000 (Mon, 15 Mar 2010)
Log Message:
-----------
Fix NH-2137
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/ValuePropertyBinder.cs
trunk/nhibernate/src/NHibernate.Test/App.config
trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
Added Paths:
-----------
trunk/nhibernate/src/NHibernate.Test/ListIndex/SimpleOneToMany.cs
trunk/nhibernate/src/NHibernate.Test/ListIndex/SimpleOneToMany.hbm.xml
trunk/nhibernate/src/NHibernate.Test/ListIndex/SimpleOneToManyTest.cs
Modified: trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/ValuePropertyBinder.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/ValuePropertyBinder.cs 2010-03-07 10:16:09 UTC (rev 4955)
+++ trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/ValuePropertyBinder.cs 2010-03-15 16:06:07 UTC (rev 4956)
@@ -133,7 +133,7 @@
public void BindSimpleValue(HbmListIndex listIndexMapping, string propertyPath, bool isNullable)
{
new TypeBinder(value, Mappings).Bind(NHibernateUtil.Int32.Name);
- new ColumnsBinder(value, Mappings).Bind(listIndexMapping.Columns, false,
+ new ColumnsBinder(value, Mappings).Bind(listIndexMapping.Columns, isNullable,
() =>
new HbmColumn
{
Modified: trunk/nhibernate/src/NHibernate.Test/App.config
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/App.config 2010-03-07 10:16:09 UTC (rev 4955)
+++ trunk/nhibernate/src/NHibernate.Test/App.config 2010-03-15 16:06:07 UTC (rev 4956)
@@ -126,7 +126,7 @@
</logger>
<logger name="NHibernate.SQL">
- <level value="OFF" />
+ <level value="DEBUG" />
</logger>
<logger name="NHibernate.AdoNet.AbstractBatcher">
Added: trunk/nhibernate/src/NHibernate.Test/ListIndex/SimpleOneToMany.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/ListIndex/SimpleOneToMany.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/ListIndex/SimpleOneToMany.cs 2010-03-15 16:06:07 UTC (rev 4956)
@@ -0,0 +1,21 @@
+using System.Collections.Generic;
+
+namespace NHibernate.Test.ListIndex
+{
+ public class Image
+ {
+ public virtual int Id { get; set; }
+ public virtual string Path { get; set; }
+ }
+
+ public class Galery
+ {
+ public Galery()
+ {
+ Images = new List<Image>();
+ }
+ public virtual int Id { get; set; }
+
+ public virtual IList<Image> Images { get; set; }
+ }
+}
\ No newline at end of file
Added: trunk/nhibernate/src/NHibernate.Test/ListIndex/SimpleOneToMany.hbm.xml
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/ListIndex/SimpleOneToMany.hbm.xml (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/ListIndex/SimpleOneToMany.hbm.xml 2010-03-15 16:06:07 UTC (rev 4956)
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
+ assembly="NHibernate.Test"
+ namespace="NHibernate.Test.ListIndex">
+ <class name="Image">
+ <id name="Id">
+ <generator class="hilo"/>
+ </id>
+ <property name="Path"/>
+ </class>
+
+ <class name="Galery">
+ <id name="Id">
+ <generator class="hilo"/>
+ </id>
+ <list name="Images" cascade="all">
+ <key column="img_key"/>
+ <list-index column="imgIdx"/>
+ <one-to-many class="Image"/>
+ </list>
+ </class>
+</hibernate-mapping>
\ No newline at end of file
Added: trunk/nhibernate/src/NHibernate.Test/ListIndex/SimpleOneToManyTest.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/ListIndex/SimpleOneToManyTest.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/ListIndex/SimpleOneToManyTest.cs 2010-03-15 16:06:07 UTC (rev 4956)
@@ -0,0 +1,39 @@
+using System.Collections;
+using NUnit.Framework;
+
+namespace NHibernate.Test.ListIndex
+{
+ [TestFixture]
+ public class SimpleOneToManyTest : TestCase
+ {
+ protected override IList Mappings
+ {
+ get { return new string[] { "ListIndex.SimpleOneToMany.hbm.xml" }; }
+ }
+
+ protected override string MappingsAssembly
+ {
+ get { return "NHibernate.Test"; }
+ }
+
+ [Test]
+ public void ShouldIncludeTheListIdxInserting()
+ {
+ using (var s = OpenSession())
+ using (var tx = s.BeginTransaction())
+ {
+ var galery = new Galery();
+ galery.Images.Add(new Image {Path = "image01.jpg"});
+ s.Persist(galery);
+ Assert.DoesNotThrow(tx.Commit);
+ }
+ using (var s = OpenSession())
+ using (var tx = s.BeginTransaction())
+ {
+ s.CreateQuery("delete from Image").ExecuteUpdate();
+ s.CreateQuery("delete from Galery").ExecuteUpdate();
+ tx.Commit();
+ }
+ }
+ }
+}
\ No newline at end of file
Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-03-07 10:16:09 UTC (rev 4955)
+++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-03-15 16:06:07 UTC (rev 4956)
@@ -429,6 +429,8 @@
<Compile Include="Linq\SelectionTests.cs" />
<Compile Include="Linq\WhereSubqueryTests.cs" />
<Compile Include="Linq\WhereTests.cs" />
+ <Compile Include="ListIndex\SimpleOneToMany.cs" />
+ <Compile Include="ListIndex\SimpleOneToManyTest.cs" />
<Compile Include="MappingTest\NonReflectiveBinderFixture.cs" />
<Compile Include="MappingTest\Wicked.cs" />
<Compile Include="NHSpecificTest\CriteriaQueryOnComponentCollection\Employee.cs" />
@@ -2126,6 +2128,7 @@
<EmbeddedResource Include="CfgTest\Loquacious\EntityToCache.hbm.xml" />
<EmbeddedResource Include="DriverTest\SqlServerCeEntity.hbm.xml" />
<Content Include="DynamicEntity\package.html" />
+ <EmbeddedResource Include="ListIndex\SimpleOneToMany.hbm.xml" />
<EmbeddedResource Include="NHSpecificTest\NH2113\Mappings.hbm.xml" />
<EmbeddedResource Include="NHSpecificTest\NH1981\Mappings.hbm.xml" />
<EmbeddedResource Include="NHSpecificTest\NH2074\Mappings.hbm.xml" />
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ste...@us...> - 2010-03-17 12:41:52
|
Revision: 4957
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4957&view=rev
Author: steverstrong
Date: 2010-03-17 12:41:45 +0000 (Wed, 17 Mar 2010)
Log Message:
-----------
Tweaked EagerFetching extension methods so that a client no longer needs to reference re-linq
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Linq/EagerFetchingExtensionMethods.cs
trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.build
trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
Modified: trunk/nhibernate/src/NHibernate/Linq/EagerFetchingExtensionMethods.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Linq/EagerFetchingExtensionMethods.cs 2010-03-15 16:06:07 UTC (rev 4956)
+++ trunk/nhibernate/src/NHibernate/Linq/EagerFetchingExtensionMethods.cs 2010-03-17 12:41:45 UTC (rev 4957)
@@ -3,14 +3,14 @@
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
-using Remotion.Data.Linq.EagerFetching;
+using Remotion.Data.Linq;
using Remotion.Data.Linq.Utilities;
namespace NHibernate.Linq
{
public static class EagerFetchingExtensionMethods
{
- public static FluentFetchRequest<TOriginating, TRelated> Fetch<TOriginating, TRelated>(
+ public static INhFetchRequest<TOriginating, TRelated> Fetch<TOriginating, TRelated>(
this IQueryable<TOriginating> query, Expression<Func<TOriginating, TRelated>> relatedObjectSelector)
{
ArgumentUtility.CheckNotNull("query", query);
@@ -20,7 +20,7 @@
return CreateFluentFetchRequest<TOriginating, TRelated>(methodInfo, query, relatedObjectSelector);
}
- public static FluentFetchRequest<TOriginating, TRelated> FetchMany<TOriginating, TRelated>(
+ public static INhFetchRequest<TOriginating, TRelated> FetchMany<TOriginating, TRelated>(
this IQueryable<TOriginating> query, Expression<Func<TOriginating, IEnumerable<TRelated>>> relatedObjectSelector)
{
ArgumentUtility.CheckNotNull("query", query);
@@ -30,8 +30,8 @@
return CreateFluentFetchRequest<TOriginating, TRelated>(methodInfo, query, relatedObjectSelector);
}
- public static FluentFetchRequest<TQueried, TRelated> ThenFetch<TQueried, TFetch, TRelated>(
- this FluentFetchRequest<TQueried, TFetch> query, Expression<Func<TFetch, TRelated>> relatedObjectSelector)
+ public static INhFetchRequest<TQueried, TRelated> ThenFetch<TQueried, TFetch, TRelated>(
+ this INhFetchRequest<TQueried, TFetch> query, Expression<Func<TFetch, TRelated>> relatedObjectSelector)
{
ArgumentUtility.CheckNotNull("query", query);
ArgumentUtility.CheckNotNull("relatedObjectSelector", relatedObjectSelector);
@@ -40,8 +40,8 @@
return CreateFluentFetchRequest<TQueried, TRelated>(methodInfo, query, relatedObjectSelector);
}
- public static FluentFetchRequest<TQueried, TRelated> ThenFetchMany<TQueried, TFetch, TRelated>(
- this FluentFetchRequest<TQueried, TFetch> query, Expression<Func<TFetch, IEnumerable<TRelated>>> relatedObjectSelector)
+ public static INhFetchRequest<TQueried, TRelated> ThenFetchMany<TQueried, TFetch, TRelated>(
+ this INhFetchRequest<TQueried, TFetch> query, Expression<Func<TFetch, IEnumerable<TRelated>>> relatedObjectSelector)
{
ArgumentUtility.CheckNotNull("query", query);
ArgumentUtility.CheckNotNull("relatedObjectSelector", relatedObjectSelector);
@@ -50,14 +50,26 @@
return CreateFluentFetchRequest<TQueried, TRelated>(methodInfo, query, relatedObjectSelector);
}
- private static FluentFetchRequest<TOriginating, TRelated> CreateFluentFetchRequest<TOriginating, TRelated>(
+ private static INhFetchRequest<TOriginating, TRelated> CreateFluentFetchRequest<TOriginating, TRelated>(
MethodInfo currentFetchMethod,
IQueryable<TOriginating> query,
LambdaExpression relatedObjectSelector)
{
var queryProvider = query.Provider; // ArgumentUtility.CheckNotNullAndType<QueryProviderBase>("query.Provider", query.Provider);
var callExpression = Expression.Call(currentFetchMethod, query.Expression, relatedObjectSelector);
- return new FluentFetchRequest<TOriginating, TRelated>(queryProvider, callExpression);
+ return new NhFetchRequest<TOriginating, TRelated>(queryProvider, callExpression);
}
}
+
+ public interface INhFetchRequest<TQueried, TFetch> : IOrderedQueryable<TQueried>
+ {
+ }
+
+ public class NhFetchRequest<TQueried, TFetch> : QueryableBase<TQueried>, INhFetchRequest<TQueried, TFetch>
+ {
+ public NhFetchRequest(IQueryProvider provider, Expression expression)
+ : base(provider, expression)
+ {
+ }
+ }
}
\ No newline at end of file
Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.build
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.build 2010-03-15 16:06:07 UTC (rev 4956)
+++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.build 2010-03-17 12:41:45 UTC (rev 4957)
@@ -24,8 +24,7 @@
<include name="LinFu.DynamicProxy.dll" />
<include name="nunit.framework.dll" />
<include name="Antlr3.Runtime.dll" />
- <include name="Remotion.Data.Linq.dll" />
- <include name="System.Linq.Dynamic.dll" />
+ <include name="System.Linq.Dynamic.dll" />
</assemblyfileset>
<resourcefileset id="project.resources" prefix="NHibernate.Test" dynamicprefix="true">
<include name="**/*.xml" />
Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-03-15 16:06:07 UTC (rev 4956)
+++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-03-17 12:41:45 UTC (rev 4957)
@@ -62,10 +62,6 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\net\3.5\nunit.framework.dll</HintPath>
</Reference>
- <Reference Include="Remotion.Data.Linq, Version=1.13.9.2, Culture=neutral, PublicKeyToken=cab60358ab4081ea, processorArchitecture=MSIL">
- <SpecificVersion>False</SpecificVersion>
- <HintPath>..\..\lib\net\3.5\Remotion.Data.Linq.dll</HintPath>
- </Reference>
<Reference Include="System" />
<Reference Include="System.configuration" />
<Reference Include="System.Core">
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ste...@us...> - 2010-03-17 14:18:10
|
Revision: 4958
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4958&view=rev
Author: steverstrong
Date: 2010-03-17 14:18:03 +0000 (Wed, 17 Mar 2010)
Log Message:
-----------
Added support for DateTime.Date in Linq query, and tweaked ByteCode test to try to resolve buggered TeamCity server
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Dialect/MsSql2000Dialect.cs
trunk/nhibernate/src/NHibernate/Linq/Functions/DateTimeGenerator.cs
trunk/nhibernate/src/NHibernate.ByteCode.Castle.Tests/TestCase.cs
trunk/nhibernate/src/NHibernate.Test/App.config
trunk/nhibernate/src/NHibernate.Test/Linq/LinqTestCase.cs
trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
Added Paths:
-----------
trunk/nhibernate/src/NHibernate.Test/Linq/DateTimeTests.cs
Modified: trunk/nhibernate/src/NHibernate/Dialect/MsSql2000Dialect.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Dialect/MsSql2000Dialect.cs 2010-03-17 12:41:45 UTC (rev 4957)
+++ trunk/nhibernate/src/NHibernate/Dialect/MsSql2000Dialect.cs 2010-03-17 14:18:03 UTC (rev 4958)
@@ -116,7 +116,8 @@
RegisterFunction("day", new SQLFunctionTemplate(NHibernateUtil.Int32, "datepart(day, ?1)"));
RegisterFunction("month", new SQLFunctionTemplate(NHibernateUtil.Int32, "datepart(month, ?1)"));
RegisterFunction("year", new SQLFunctionTemplate(NHibernateUtil.Int32, "datepart(year, ?1)"));
- RegisterFunction("concat", new VarArgsSQLFunction(NHibernateUtil.String, "(", "+", ")"));
+ RegisterFunction("date", new SQLFunctionTemplate(NHibernateUtil.Date, "dateadd(dd, 0, datediff(dd, 0, ?1))"));
+ RegisterFunction("concat", new VarArgsSQLFunction(NHibernateUtil.String, "(", "+", ")"));
RegisterFunction("digits", new StandardSQLFunction("digits", NHibernateUtil.String));
RegisterFunction("chr", new StandardSQLFunction("chr", NHibernateUtil.Character));
RegisterFunction("upper", new StandardSQLFunction("upper"));
Modified: trunk/nhibernate/src/NHibernate/Linq/Functions/DateTimeGenerator.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Linq/Functions/DateTimeGenerator.cs 2010-03-17 12:41:45 UTC (rev 4957)
+++ trunk/nhibernate/src/NHibernate/Linq/Functions/DateTimeGenerator.cs 2010-03-17 14:18:03 UTC (rev 4958)
@@ -25,6 +25,7 @@
ReflectionHelper.GetProperty((DateTime x) => x.Hour),
ReflectionHelper.GetProperty((DateTime x) => x.Minute),
ReflectionHelper.GetProperty((DateTime x) => x.Second),
+ ReflectionHelper.GetProperty((DateTime x) => x.Date),
};
}
Modified: trunk/nhibernate/src/NHibernate.ByteCode.Castle.Tests/TestCase.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.ByteCode.Castle.Tests/TestCase.cs 2010-03-17 12:41:45 UTC (rev 4957)
+++ trunk/nhibernate/src/NHibernate.ByteCode.Castle.Tests/TestCase.cs 2010-03-17 14:18:03 UTC (rev 4958)
@@ -197,7 +197,8 @@
private void CreateSchema()
{
- new SchemaExport(cfg).Create(OutputDdl, true);
+ new SchemaExport(cfg).Drop(OutputDdl, true);
+ new SchemaExport(cfg).Create(OutputDdl, true);
}
private void DropSchema()
Modified: trunk/nhibernate/src/NHibernate.Test/App.config
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/App.config 2010-03-17 12:41:45 UTC (rev 4957)
+++ trunk/nhibernate/src/NHibernate.Test/App.config 2010-03-17 14:18:03 UTC (rev 4958)
@@ -126,7 +126,7 @@
</logger>
<logger name="NHibernate.SQL">
- <level value="DEBUG" />
+ <level value="OFF" />
</logger>
<logger name="NHibernate.AdoNet.AbstractBatcher">
Added: trunk/nhibernate/src/NHibernate.Test/Linq/DateTimeTests.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Linq/DateTimeTests.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/Linq/DateTimeTests.cs 2010-03-17 14:18:03 UTC (rev 4958)
@@ -0,0 +1,50 @@
+using System;
+using System.Linq;
+using NUnit.Framework;
+
+namespace NHibernate.Test.Linq
+{
+ [TestFixture]
+ public class DateTimeTests : LinqTestCase
+ {
+ [Test]
+ public void CanQueryByYear()
+ {
+ var x = (from o in db.Orders
+ where o.OrderDate.Value.Year == 1998
+ select o).ToList();
+
+ Assert.AreEqual(270, x.Count());
+ }
+
+ [Test]
+ public void CanQueryByDate()
+ {
+ var x = (from o in db.Orders
+ where o.OrderDate.Value.Date == new DateTime(1998, 02, 26)
+ select o).ToList();
+
+ Assert.AreEqual(6, x.Count());
+ }
+
+ [Test]
+ public void CanQueryByDateTime()
+ {
+ var x = (from o in db.Orders
+ where o.OrderDate.Value == new DateTime(1998, 02, 26)
+ select o).ToList();
+
+ Assert.AreEqual(5, x.Count());
+ }
+
+ [Test]
+ public void CanQueryByDateTime2()
+ {
+ var x = (from o in db.Orders
+ where o.OrderDate.Value == new DateTime(1998, 02, 26, 0, 1, 0)
+ select o).ToList();
+
+ Assert.AreEqual(1, x.Count());
+ }
+ }
+}
Modified: trunk/nhibernate/src/NHibernate.Test/Linq/LinqTestCase.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Linq/LinqTestCase.cs 2010-03-17 12:41:45 UTC (rev 4957)
+++ trunk/nhibernate/src/NHibernate.Test/Linq/LinqTestCase.cs 2010-03-17 14:18:03 UTC (rev 4958)
@@ -1208,7 +1208,7 @@
order = new Order { OrderId = 10905, Customer = customers.Where(c => c.CompanyName == "Wellington Importadora").First(), Employee = employees.Where(e => e.LastName == "Dodsworth").First(), OrderDate = DateTime.Parse("Feb 24 1998 12:00AM"), RequiredDate = DateTime.Parse("Mar 24 1998 12:00AM"), ShippingDate = DateTime.Parse("Mar 6 1998 12:00AM"), Shipper = shippers.Where(s => s.CompanyName == "United Package").First(), Freight = 13.72M, ShippedTo = "Wellington Importadora",ShippingAddress = new Address("Rua do Mercado, 12", "Resende", "SP", "08737-363", "Brazil", null, null) }; session.Insert(order); orders.Add(order);
order = new Order { OrderId = 10906, Customer = customers.Where(c => c.CompanyName == "Wolski Zajazd").First(), Employee = employees.Where(e => e.LastName == "Peacock").First(), OrderDate = DateTime.Parse("Feb 25 1998 12:00AM"), RequiredDate = DateTime.Parse("Mar 11 1998 12:00AM"), ShippingDate = DateTime.Parse("Mar 3 1998 12:00AM"), Shipper = shippers.Where(s => s.CompanyName == "Federal Shipping").First(), Freight = 26.29M, ShippedTo = "Wolski Zajazd",ShippingAddress = new Address("ul. Filtrowa 68", "Warszawa", "null", "01-012", "Poland", null, null) }; session.Insert(order); orders.Add(order);
order = new Order { OrderId = 10907, Customer = customers.Where(c => c.CompanyName == "Spécialités du monde").First(), Employee = employees.Where(e => e.LastName == "Suyama").First(), OrderDate = DateTime.Parse("Feb 25 1998 12:00AM"), RequiredDate = DateTime.Parse("Mar 25 1998 12:00AM"), ShippingDate = DateTime.Parse("Feb 27 1998 12:00AM"), Shipper = shippers.Where(s => s.CompanyName == "Federal Shipping").First(), Freight = 9.19M, ShippedTo = "Spécialités du monde",ShippingAddress = new Address("25, rue Lauriston", "Paris", "null", "75016", "France", null, null) }; session.Insert(order); orders.Add(order);
- order = new Order { OrderId = 10908, Customer = customers.Where(c => c.CompanyName == "Reggiani Caseifici").First(), Employee = employees.Where(e => e.LastName == "Peacock").First(), OrderDate = DateTime.Parse("Feb 26 1998 12:00AM"), RequiredDate = DateTime.Parse("Mar 26 1998 12:00AM"), ShippingDate = DateTime.Parse("Mar 6 1998 12:00AM"), Shipper = shippers.Where(s => s.CompanyName == "United Package").First(), Freight = 32.96M, ShippedTo = "Reggiani Caseifici",ShippingAddress = new Address("Strada Provinciale 124", "Reggio Emilia", "null", "42100", "Italy", null, null) }; session.Insert(order); orders.Add(order);
+ order = new Order { OrderId = 10908, Customer = customers.Where(c => c.CompanyName == "Reggiani Caseifici").First(), Employee = employees.Where(e => e.LastName == "Peacock").First(), OrderDate = DateTime.Parse("Feb 26 1998 12:01AM"), RequiredDate = DateTime.Parse("Mar 26 1998 12:00AM"), ShippingDate = DateTime.Parse("Mar 6 1998 12:00AM"), Shipper = shippers.Where(s => s.CompanyName == "United Package").First(), Freight = 32.96M, ShippedTo = "Reggiani Caseifici",ShippingAddress = new Address("Strada Provinciale 124", "Reggio Emilia", "null", "42100", "Italy", null, null) }; session.Insert(order); orders.Add(order);
order = new Order { OrderId = 10909, Customer = customers.Where(c => c.CompanyName == "Santé Gourmet").First(), Employee = employees.Where(e => e.LastName == "Davolio").First(), OrderDate = DateTime.Parse("Feb 26 1998 12:00AM"), RequiredDate = DateTime.Parse("Mar 26 1998 12:00AM"), ShippingDate = DateTime.Parse("Mar 10 1998 12:00AM"), Shipper = shippers.Where(s => s.CompanyName == "United Package").First(), Freight = 53.05M, ShippedTo = "Santé Gourmet",ShippingAddress = new Address("Erling Skakkes gate 78", "Stavern", "null", "4110", "Norway", null, null) }; session.Insert(order); orders.Add(order);
order = new Order { OrderId = 10910, Customer = customers.Where(c => c.CompanyName == "Wilman Kala").First(), Employee = employees.Where(e => e.LastName == "Davolio").First(), OrderDate = DateTime.Parse("Feb 26 1998 12:00AM"), RequiredDate = DateTime.Parse("Mar 26 1998 12:00AM"), ShippingDate = DateTime.Parse("Mar 4 1998 12:00AM"), Shipper = shippers.Where(s => s.CompanyName == "Federal Shipping").First(), Freight = 38.11M, ShippedTo = "Wilman Kala",ShippingAddress = new Address("Keskuskatu 45", "Helsinki", "null", "21240", "Finland", null, null) }; session.Insert(order); orders.Add(order);
order = new Order { OrderId = 10911, Customer = customers.Where(c => c.CompanyName == "Godos Cocina Típica").First(), Employee = employees.Where(e => e.LastName == "Leverling").First(), OrderDate = DateTime.Parse("Feb 26 1998 12:00AM"), RequiredDate = DateTime.Parse("Mar 26 1998 12:00AM"), ShippingDate = DateTime.Parse("Mar 5 1998 12:00AM"), Shipper = shippers.Where(s => s.CompanyName == "Speedy Express").First(), Freight = 38.19M, ShippedTo = "Godos Cocina Típica",ShippingAddress = new Address("C/ Romero, 33", "Sevilla", "null", "41101", "Spain", null, null) }; session.Insert(order); orders.Add(order);
Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-03-17 12:41:45 UTC (rev 4957)
+++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-03-17 14:18:03 UTC (rev 4958)
@@ -382,6 +382,7 @@
<Compile Include="Linq\BinaryBooleanExpressionTests.cs" />
<Compile Include="Linq\BinaryExpressionOrdererTests.cs" />
<Compile Include="Linq\CollectionAssert.cs" />
+ <Compile Include="Linq\DateTimeTests.cs" />
<Compile Include="Linq\DynamicQueryTests.cs" />
<Compile Include="Linq\EagerLoadTests.cs" />
<Compile Include="Linq\Entities\Address.cs" />
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ste...@us...> - 2010-03-22 15:18:05
|
Revision: 4964
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4964&view=rev
Author: steverstrong
Date: 2010-03-22 15:17:58 +0000 (Mon, 22 Mar 2010)
Log Message:
-----------
Added support for Query Caching in the Linq provider
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Linq/LinqExtensionMethods.cs
trunk/nhibernate/src/NHibernate/Linq/NhRelinqQueryParser.cs
trunk/nhibernate/src/NHibernate/Linq/Visitors/QueryModelVisitor.cs
trunk/nhibernate/src/NHibernate/NHibernate.csproj
trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
Added Paths:
-----------
trunk/nhibernate/src/NHibernate/Linq/TypeHelperExtensionMethods.cs
trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessCacheable.cs
trunk/nhibernate/src/NHibernate.Test/Linq/QueryCacheableTests.cs
Modified: trunk/nhibernate/src/NHibernate/Linq/LinqExtensionMethods.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Linq/LinqExtensionMethods.cs 2010-03-17 17:16:04 UTC (rev 4963)
+++ trunk/nhibernate/src/NHibernate/Linq/LinqExtensionMethods.cs 2010-03-22 15:17:58 UTC (rev 4964)
@@ -1,6 +1,5 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
+using System.Linq;
+using System.Linq.Expressions;
namespace NHibernate.Linq
{
@@ -11,47 +10,31 @@
return new NhQueryable<T>(session);
}
- public static void ForEach<T>(this IEnumerable<T> query, Action<T> method)
+ public static IQueryable<T> Cacheable<T>(this IQueryable<T> query)
{
- foreach (T item in query)
- {
- method(item);
- }
- }
+ var method = ReflectionHelper.GetMethod(() => Cacheable<object>(null)).MakeGenericMethod(typeof(T));
- public static bool IsEnumerableOfT(this System.Type type)
- {
- return type.IsGenericType && type.GetGenericTypeDefinition() == typeof (IEnumerable<>);
- }
+ var callExpression = Expression.Call(method, query.Expression);
- public static bool IsNullable(this System.Type type)
- {
- return (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>));
+ return new NhQueryable<T>(query.Provider, callExpression);
}
- public static bool IsNullableOrReference(this System.Type type)
+ public static IQueryable<T> CacheMode<T>(this IQueryable<T> query, CacheMode cacheMode)
{
- return !type.IsValueType || type.IsNullable();
- }
+ var method = ReflectionHelper.GetMethod(() => CacheMode<object>(null, NHibernate.CacheMode.Normal)).MakeGenericMethod(typeof(T));
- public static System.Type NullableOf(this System.Type type)
- {
- return type.GetGenericArguments()[0];
- }
+ var callExpression = Expression.Call(method, query.Expression, Expression.Constant(cacheMode));
- public static bool IsPrimitive(this System.Type type)
- {
- return (type.IsValueType || type.IsNullable() || type == typeof (string));
+ return new NhQueryable<T>(query.Provider, callExpression);
}
- public static bool IsNonPrimitive(this System.Type type)
+ public static IQueryable<T> CacheRegion<T>(this IQueryable<T> query, string region)
{
- return !type.IsPrimitive();
- }
+ var method = ReflectionHelper.GetMethod(() => CacheRegion<object>(null, null)).MakeGenericMethod(typeof(T));
- public static T As<T>(this object source)
- {
- return (T) source;
+ var callExpression = Expression.Call(method, query.Expression, Expression.Constant(region));
+
+ return new NhQueryable<T>(query.Provider, callExpression);
}
- }
+ }
}
\ No newline at end of file
Modified: trunk/nhibernate/src/NHibernate/Linq/NhRelinqQueryParser.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Linq/NhRelinqQueryParser.cs 2010-03-17 17:16:04 UTC (rev 4963)
+++ trunk/nhibernate/src/NHibernate/Linq/NhRelinqQueryParser.cs 2010-03-22 15:17:58 UTC (rev 4964)
@@ -1,7 +1,10 @@
-using System.Collections.Generic;
+using System;
+using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Remotion.Data.Linq;
+using Remotion.Data.Linq.Clauses;
+using Remotion.Data.Linq.Clauses.StreamedData;
using Remotion.Data.Linq.EagerFetching.Parsing;
using Remotion.Data.Linq.Parsing.Structure;
using Remotion.Data.Linq.Parsing.Structure.IntermediateModel;
@@ -40,6 +43,14 @@
MethodCallRegistry.Register(new[] { typeof(EagerFetchingExtensionMethods).GetMethod("ThenFetch") }, typeof(ThenFetchOneExpressionNode));
MethodCallRegistry.Register(new[] { typeof(EagerFetchingExtensionMethods).GetMethod("ThenFetchMany") }, typeof(ThenFetchManyExpressionNode));
+ MethodCallRegistry.Register(
+ new[]
+ {
+ typeof(LinqExtensionMethods).GetMethod("Cacheable"),
+ typeof(LinqExtensionMethods).GetMethod("CacheMode"),
+ typeof(LinqExtensionMethods).GetMethod("CacheRegion"),
+ }, typeof(CacheableExpressionNode));
+
}
public static QueryModel Parse(Expression expression)
@@ -47,4 +58,57 @@
return new QueryParser(new ExpressionTreeParser(MethodCallRegistry)).GetParsedQuery(expression);
}
}
+
+ public class CacheableExpressionNode : ResultOperatorExpressionNodeBase
+ {
+ private readonly MethodCallExpressionParseInfo _parseInfo;
+ private readonly ConstantExpression _data;
+
+ public CacheableExpressionNode(MethodCallExpressionParseInfo parseInfo, ConstantExpression data) : base(parseInfo, null, null)
+ {
+ _parseInfo = parseInfo;
+ _data = data;
+ }
+
+ public override Expression Resolve(ParameterExpression inputParameter, Expression expressionToBeResolved, ClauseGenerationContext clauseGenerationContext)
+ {
+ throw new NotImplementedException();
+ }
+
+ protected override ResultOperatorBase CreateResultOperator(ClauseGenerationContext clauseGenerationContext)
+ {
+ return new CacheableResultOperator(_parseInfo, _data);
+ }
+ }
+
+ public class CacheableResultOperator : ResultOperatorBase
+ {
+ public MethodCallExpressionParseInfo ParseInfo { get; private set; }
+ public ConstantExpression Data { get; private set; }
+
+ public CacheableResultOperator(MethodCallExpressionParseInfo parseInfo, ConstantExpression data)
+ {
+ ParseInfo = parseInfo;
+ Data = data;
+ }
+
+ public override IStreamedData ExecuteInMemory(IStreamedData input)
+ {
+ throw new NotImplementedException();
+ }
+
+ public override IStreamedDataInfo GetOutputDataInfo(IStreamedDataInfo inputInfo)
+ {
+ return inputInfo;
+ }
+
+ public override ResultOperatorBase Clone(CloneContext cloneContext)
+ {
+ throw new NotImplementedException();
+ }
+
+ public override void TransformExpressions(Func<Expression, Expression> transformation)
+ {
+ }
+ }
}
\ No newline at end of file
Added: trunk/nhibernate/src/NHibernate/Linq/TypeHelperExtensionMethods.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Linq/TypeHelperExtensionMethods.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate/Linq/TypeHelperExtensionMethods.cs 2010-03-22 15:17:58 UTC (rev 4964)
@@ -0,0 +1,51 @@
+using System;
+using System.Collections.Generic;
+
+namespace NHibernate.Linq
+{
+ public static class TypeHelperExtensionMethods
+ {
+ public static void ForEach<T>(this IEnumerable<T> query, Action<T> method)
+ {
+ foreach (T item in query)
+ {
+ method(item);
+ }
+ }
+
+ public static bool IsEnumerableOfT(this System.Type type)
+ {
+ return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>);
+ }
+
+ public static bool IsNullable(this System.Type type)
+ {
+ return (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>));
+ }
+
+ public static bool IsNullableOrReference(this System.Type type)
+ {
+ return !type.IsValueType || type.IsNullable();
+ }
+
+ public static System.Type NullableOf(this System.Type type)
+ {
+ return type.GetGenericArguments()[0];
+ }
+
+ public static bool IsPrimitive(this System.Type type)
+ {
+ return (type.IsValueType || type.IsNullable() || type == typeof(string));
+ }
+
+ public static bool IsNonPrimitive(this System.Type type)
+ {
+ return !type.IsPrimitive();
+ }
+
+ public static T As<T>(this object source)
+ {
+ return (T)source;
+ }
+ }
+}
Modified: trunk/nhibernate/src/NHibernate/Linq/Visitors/QueryModelVisitor.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Linq/Visitors/QueryModelVisitor.cs 2010-03-17 17:16:04 UTC (rev 4963)
+++ trunk/nhibernate/src/NHibernate/Linq/Visitors/QueryModelVisitor.cs 2010-03-22 15:17:58 UTC (rev 4964)
@@ -62,6 +62,7 @@
static QueryModelVisitor()
{
+ // TODO - reflection to build map
ResultOperatorMap = new ResultOperatorMap();
ResultOperatorMap.Add<AggregateResultOperator, ProcessAggregate>();
@@ -77,6 +78,7 @@
ResultOperatorMap.Add<AllResultOperator, ProcessAll>();
ResultOperatorMap.Add<FetchOneRequest, ProcessFetchOne>();
ResultOperatorMap.Add<FetchManyRequest, ProcessFetchMany>();
+ ResultOperatorMap.Add<CacheableResultOperator, ProcessCacheable>();
}
private QueryModelVisitor(VisitorParameters visitorParameters, bool root, QueryModel queryModel)
Added: trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessCacheable.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessCacheable.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessCacheable.cs 2010-03-22 15:17:58 UTC (rev 4964)
@@ -0,0 +1,41 @@
+namespace NHibernate.Linq.Visitors.ResultOperatorProcessors
+{
+ public class ProcessCacheable : IResultOperatorProcessor<CacheableResultOperator>
+ {
+ public void Process(CacheableResultOperator resultOperator, QueryModelVisitor queryModelVisitor, IntermediateHqlTree tree)
+ {
+ NamedParameter parameterName;
+
+ switch (resultOperator.ParseInfo.ParsedExpression.Method.Name)
+ {
+ case "Cacheable":
+ tree.AddAdditionalCriteria((q, p) => q.SetCacheable(true));
+ break;
+ case "CacheMode":
+ queryModelVisitor.VisitorParameters.ConstantToParameterMap.TryGetValue(resultOperator.Data,
+ out parameterName);
+ if (parameterName != null)
+ {
+ tree.AddAdditionalCriteria((q, p) => q.SetCacheMode((CacheMode) p[parameterName.Name].First));
+ }
+ else
+ {
+ tree.AddAdditionalCriteria((q, p) => q.SetCacheMode((CacheMode) resultOperator.Data.Value));
+ }
+ break;
+ case "CacheRegion":
+ queryModelVisitor.VisitorParameters.ConstantToParameterMap.TryGetValue(resultOperator.Data,
+ out parameterName);
+ if (parameterName != null)
+ {
+ tree.AddAdditionalCriteria((q, p) => q.SetCacheRegion((string) p[parameterName.Name].First));
+ }
+ else
+ {
+ tree.AddAdditionalCriteria((q, p) => q.SetCacheRegion((string) resultOperator.Data.Value));
+ }
+ break;
+ }
+ }
+ }
+}
\ No newline at end of file
Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj
===================================================================
--- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-03-17 17:16:04 UTC (rev 4963)
+++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-03-22 15:17:58 UTC (rev 4964)
@@ -649,6 +649,7 @@
<Compile Include="Impl\SessionIdLoggingContext.cs" />
<Compile Include="Linq\Expressions\AggregateExpressionNode.cs" />
<Compile Include="Linq\EagerFetchingExtensionMethods.cs" />
+ <Compile Include="Linq\TypeHelperExtensionMethods.cs" />
<Compile Include="Linq\Visitors\NameUnNamedParameters.cs" />
<Compile Include="Linq\NhRelinqQueryParser.cs" />
<Compile Include="Linq\ResultOperators\AggregateResultOperator.cs" />
@@ -681,6 +682,7 @@
<Compile Include="Linq\ReWriters\RemoveUnnecessaryBodyOperators.cs" />
<Compile Include="Linq\Clauses\LeftJoinClause.cs" />
<Compile Include="Linq\IntermediateHqlTree.cs" />
+ <Compile Include="Linq\Visitors\ResultOperatorProcessors\ProcessCacheable.cs" />
<Compile Include="Linq\Visitors\QuerySourceLocator.cs" />
<Compile Include="Linq\Visitors\ResultOperatorProcessors\ProcessFetch.cs" />
<Compile Include="Linq\Visitors\ResultOperatorProcessors\ProcessFetchMany.cs" />
Added: trunk/nhibernate/src/NHibernate.Test/Linq/QueryCacheableTests.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Linq/QueryCacheableTests.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/Linq/QueryCacheableTests.cs 2010-03-22 15:17:58 UTC (rev 4964)
@@ -0,0 +1,72 @@
+using System.Linq;
+using NHibernate.Cfg;
+using NHibernate.Linq;
+using NUnit.Framework;
+
+namespace NHibernate.Test.Linq
+{
+ [TestFixture]
+ public class QueryCacheableTests : LinqTestCase
+ {
+ protected override void Configure(Configuration cfg)
+ {
+ cfg.SetProperty(Environment.UseQueryCache, "true");
+ cfg.SetProperty(Environment.GenerateStatistics, "true");
+ base.Configure(cfg);
+ }
+
+ [Test]
+ public void QueryIsCacheable()
+ {
+ Sfi.Statistics.Clear();
+ Sfi.QueryCache.Clear();
+
+ var x = (from c in db.Customers
+ select c).Cacheable().ToList();
+
+ var x2 = (from c in db.Customers
+ select c).Cacheable().ToList();
+
+ Assert.That(Sfi.Statistics.QueryExecutionCount, Is.EqualTo(1));
+ Assert.That(Sfi.Statistics.QueryCachePutCount, Is.EqualTo(1));
+ Assert.That(Sfi.Statistics.QueryCacheHitCount, Is.EqualTo(1));
+ }
+
+ [Test]
+ public void QueryIsCacheable2()
+ {
+ Sfi.Statistics.Clear();
+ Sfi.QueryCache.Clear();
+
+ var x = (from c in db.Customers
+ select c).Cacheable().ToList();
+
+ var x2 = (from c in db.Customers
+ select c).ToList();
+
+ Assert.That(Sfi.Statistics.QueryExecutionCount, Is.EqualTo(2));
+ Assert.That(Sfi.Statistics.QueryCachePutCount, Is.EqualTo(1));
+ Assert.That(Sfi.Statistics.QueryCacheHitCount, Is.EqualTo(0));
+ }
+
+ [Test]
+ public void QueryIsCacheableWithRegion()
+ {
+ Sfi.Statistics.Clear();
+ Sfi.QueryCache.Clear();
+
+ var x = (from c in db.Customers
+ select c).Cacheable().CacheRegion("test").ToList();
+
+ var x2 = (from c in db.Customers
+ select c).Cacheable().CacheRegion("test").ToList();
+
+ var x3 = (from c in db.Customers
+ select c).Cacheable().CacheRegion("other").ToList();
+
+ Assert.That(Sfi.Statistics.QueryExecutionCount, Is.EqualTo(2));
+ Assert.That(Sfi.Statistics.QueryCachePutCount, Is.EqualTo(2));
+ Assert.That(Sfi.Statistics.QueryCacheHitCount, Is.EqualTo(1));
+ }
+ }
+}
Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-03-17 17:16:04 UTC (rev 4963)
+++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-03-22 15:17:58 UTC (rev 4964)
@@ -420,6 +420,7 @@
<Compile Include="Linq\PatientTests.cs" />
<Compile Include="Linq\ProjectionsTests.cs" />
<Compile Include="Linq\PropertyMethodMappingTests.cs" />
+ <Compile Include="Linq\QueryCacheableTests.cs" />
<Compile Include="Linq\QueryReuseTests.cs" />
<Compile Include="Linq\ReadonlyTestCase.cs" />
<Compile Include="Linq\RegresstionTests.cs" />
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ric...@us...> - 2010-04-05 07:15:49
|
Revision: 4969
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4969&view=rev
Author: ricbrown
Date: 2010-04-05 07:15:43 +0000 (Mon, 05 Apr 2010)
Log Message:
-----------
Implement NH-2152 (QueryOver equality to null)
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Impl/ExpressionProcessor.cs
trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/ExpressionProcessorFixture.cs
trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/RestrictionsFixture.cs
Modified: trunk/nhibernate/src/NHibernate/Impl/ExpressionProcessor.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Impl/ExpressionProcessor.cs 2010-04-05 07:14:54 UTC (rev 4968)
+++ trunk/nhibernate/src/NHibernate/Impl/ExpressionProcessor.cs 2010-04-05 07:15:43 UTC (rev 4969)
@@ -292,6 +292,9 @@
object value = valueExpression.DynamicInvoke();
value = ConvertType(value, propertyType);
+ if (value == null)
+ return ProcessSimpleNullExpression(property, be.NodeType);
+
if (!_simpleExpressionCreators.ContainsKey(be.NodeType))
throw new Exception("Unhandled simple expression type: " + be.NodeType);
@@ -300,6 +303,18 @@
return criterion;
}
+ private static ICriterion ProcessSimpleNullExpression(string property, ExpressionType expressionType)
+ {
+ if (expressionType == ExpressionType.Equal)
+ return Restrictions.IsNull(property);
+
+ if (expressionType == ExpressionType.NotEqual)
+ return Restrictions.Not(
+ Restrictions.IsNull(property));
+
+ throw new Exception("Cannot supply null value to operator " + expressionType);
+ }
+
private static ICriterion ProcessMemberExpression(BinaryExpression be)
{
string leftProperty = FindMemberExpression(be.Left);
Modified: trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/ExpressionProcessorFixture.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/ExpressionProcessorFixture.cs 2010-04-05 07:14:54 UTC (rev 4968)
+++ trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/ExpressionProcessorFixture.cs 2010-04-05 07:15:43 UTC (rev 4969)
@@ -61,8 +61,7 @@
{
Person person = new Person() { Name = null };
ICriterion criterion = ExpressionProcessor.ProcessExpression<Person>(p => p.Name == person.Name);
- SimpleExpression simpleExpression = (SimpleExpression)criterion;
- Assert.AreEqual(null, simpleExpression.Value);
+ Assert.That(criterion, Is.InstanceOfType<NullExpression>());
}
[Test]
Modified: trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/RestrictionsFixture.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/RestrictionsFixture.cs 2010-04-05 07:14:54 UTC (rev 4968)
+++ trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/RestrictionsFixture.cs 2010-04-05 07:15:43 UTC (rev 4969)
@@ -171,6 +171,56 @@
AssertCriteriaAreEqual(expected, actual);
}
+ [Test]
+ public void NullRestriction()
+ {
+ ICriteria expected =
+ CreateTestCriteria(typeof(Person), "personAlias")
+ .Add(Restrictions.IsNull("Name"))
+ .Add(Restrictions.IsNull("Name"))
+ .Add(Restrictions.IsNull("Name"))
+ .Add(Restrictions.IsNull("Father"))
+ .Add(Restrictions.IsNull("Father"))
+ .Add(Restrictions.IsNull("NullableGender"))
+ .Add(Restrictions.IsNull("NullableAge"))
+ .Add(Restrictions.IsNull("NullableIsParent"))
+ .Add(Restrictions.Not(Restrictions.IsNull("Name")))
+ .Add(Restrictions.Not(Restrictions.IsNull("Name")))
+ .Add(Restrictions.Not(Restrictions.IsNull("Name")))
+ .Add(Restrictions.Not(Restrictions.IsNull("Father")))
+ .Add(Restrictions.Not(Restrictions.IsNull("Father")))
+ .Add(Restrictions.Not(Restrictions.IsNull("NullableGender")))
+ .Add(Restrictions.Not(Restrictions.IsNull("NullableAge")))
+ .Add(Restrictions.Not(Restrictions.IsNull("NullableIsParent")))
+ .Add(Restrictions.IsNull("personAlias.Name"));
+
+ Person personAlias = null;
+ CustomPerson nullPerson = null;
+ Person.StaticName = null;
+ Person emptyPerson = new Person() { Name = null };
+ var actual =
+ CreateTestQueryOver<Person>(() => personAlias)
+ .Where(p => p.Name == null)
+ .Where(p => p.Name == Person.StaticName)
+ .Where(p => p.Name == emptyPerson.Name)
+ .Where(p => p.Father == null)
+ .Where(p => p.Father == nullPerson)
+ .Where(p => p.NullableGender == null)
+ .Where(p => p.NullableAge == null)
+ .Where(p => p.NullableIsParent == null)
+ .Where(p => p.Name != null)
+ .Where(p => p.Name != Person.StaticName)
+ .Where(p => p.Name != emptyPerson.Name)
+ .Where(p => p.Father != null)
+ .Where(p => p.Father != nullPerson)
+ .Where(p => p.NullableGender != null)
+ .Where(p => p.NullableAge != null)
+ .Where(p => p.NullableIsParent != null)
+ .Where(() => personAlias.Name == null);
+
+ AssertCriteriaAreEqual(expected, actual);
+ }
+
}
}
\ 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: <ste...@us...> - 2010-04-07 10:48:48
|
Revision: 4970
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4970&view=rev
Author: steverstrong
Date: 2010-04-07 10:48:41 +0000 (Wed, 07 Apr 2010)
Log Message:
-----------
Added support for OfType() and "is" in Linq queries
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeBuilder.cs
trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeNode.cs
trunk/nhibernate/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs
trunk/nhibernate/src/NHibernate/Linq/Visitors/QueryModelVisitor.cs
trunk/nhibernate/src/NHibernate/NHibernate.csproj
trunk/nhibernate/src/NHibernate.Test/Linq/PagingTests.cs
trunk/nhibernate/src/NHibernate.Test/Linq/WhereTests.cs
Added Paths:
-----------
trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessOfType.cs
Modified: trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeBuilder.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeBuilder.cs 2010-04-05 07:15:43 UTC (rev 4969)
+++ trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeBuilder.cs 2010-04-07 10:48:41 UTC (rev 4970)
@@ -405,5 +405,10 @@
{
return new HqlLeftFetchJoin(_factory, expression, @alias);
}
+
+ public HqlClass Class()
+ {
+ return new HqlClass(_factory);
+ }
}
}
\ No newline at end of file
Modified: trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeNode.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeNode.cs 2010-04-05 07:15:43 UTC (rev 4969)
+++ trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeNode.cs 2010-04-07 10:48:41 UTC (rev 4970)
@@ -697,6 +697,14 @@
}
}
+ public class HqlClass : HqlExpression
+ {
+ public HqlClass(IASTFactory factory)
+ : base(HqlSqlWalker.CLASS, "class", factory)
+ {
+ }
+ }
+
public class HqlLeft : HqlTreeNode
{
public HqlLeft(IASTFactory factory)
Modified: trunk/nhibernate/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs 2010-04-05 07:15:43 UTC (rev 4969)
+++ trunk/nhibernate/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs 2010-04-07 10:48:41 UTC (rev 4970)
@@ -102,8 +102,8 @@
// return VisitListInitExpression((ListInitExpression)expression);
case ExpressionType.Parameter:
return VisitParameterExpression((ParameterExpression)expression);
- //case ExpressionType.TypeIs:
- // return VisitTypeBinaryExpression((TypeBinaryExpression)expression);
+ case ExpressionType.TypeIs:
+ return VisitTypeBinaryExpression((TypeBinaryExpression)expression);
default:
if (expression is SubQueryExpression)
@@ -136,6 +136,15 @@
}
}
+ private HqlTreeNode VisitTypeBinaryExpression(TypeBinaryExpression expression)
+ {
+ return _hqlTreeBuilder.Equality(
+ _hqlTreeBuilder.Dot(
+ Visit(expression.Expression).AsExpression(),
+ _hqlTreeBuilder.Class()),
+ _hqlTreeBuilder.Ident(expression.TypeOperand.FullName));
+ }
+
protected HqlTreeNode VisitNhStar(NhStarExpression expression)
{
return _hqlTreeBuilder.Star();
Modified: trunk/nhibernate/src/NHibernate/Linq/Visitors/QueryModelVisitor.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Linq/Visitors/QueryModelVisitor.cs 2010-04-05 07:15:43 UTC (rev 4969)
+++ trunk/nhibernate/src/NHibernate/Linq/Visitors/QueryModelVisitor.cs 2010-04-07 10:48:41 UTC (rev 4970)
@@ -79,6 +79,7 @@
ResultOperatorMap.Add<FetchOneRequest, ProcessFetchOne>();
ResultOperatorMap.Add<FetchManyRequest, ProcessFetchMany>();
ResultOperatorMap.Add<CacheableResultOperator, ProcessCacheable>();
+ ResultOperatorMap.Add<OfTypeResultOperator, ProcessOfType>();
}
private QueryModelVisitor(VisitorParameters visitorParameters, bool root, QueryModel queryModel)
Added: trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessOfType.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessOfType.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessOfType.cs 2010-04-07 10:48:41 UTC (rev 4970)
@@ -0,0 +1,36 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using NHibernate.Hql.Ast;
+using Remotion.Data.Linq.Clauses.ResultOperators;
+using Remotion.Data.Linq.Clauses.StreamedData;
+
+namespace NHibernate.Linq.Visitors.ResultOperatorProcessors
+{
+ public class ProcessOfType : IResultOperatorProcessor<OfTypeResultOperator>
+ {
+ public void Process(OfTypeResultOperator resultOperator, QueryModelVisitor queryModelVisitor, IntermediateHqlTree tree)
+ {
+ var source =
+ queryModelVisitor.CurrentEvaluationType.As<StreamedSequenceInfo>().ItemExpression;
+
+ var type = BuildDot(resultOperator.SearchedItemType.FullName.Split('.'), tree.TreeBuilder);
+
+ tree.AddWhereClause(tree.TreeBuilder.Equality(
+ tree.TreeBuilder.Dot(
+ HqlGeneratorExpressionTreeVisitor.Visit(source, queryModelVisitor.VisitorParameters).AsExpression(),
+ tree.TreeBuilder.Class()),
+ tree.TreeBuilder.Ident(resultOperator.SearchedItemType.FullName)));
+ }
+
+ private static HqlExpression BuildDot(IEnumerable<string> split, HqlTreeBuilder builder)
+ {
+ if (split.Count() == 1)
+ {
+ return builder.Ident(split.First());
+ }
+
+ return builder.Dot(builder.Ident(split.First()), BuildDot(split.Skip(1), builder));
+ }
+ }
+}
\ No newline at end of file
Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj
===================================================================
--- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-04-05 07:15:43 UTC (rev 4969)
+++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-04-07 10:48:41 UTC (rev 4970)
@@ -682,6 +682,7 @@
<Compile Include="Linq\ReWriters\RemoveUnnecessaryBodyOperators.cs" />
<Compile Include="Linq\Clauses\LeftJoinClause.cs" />
<Compile Include="Linq\IntermediateHqlTree.cs" />
+ <Compile Include="Linq\Visitors\ResultOperatorProcessors\ProcessOfType.cs" />
<Compile Include="Linq\Visitors\ResultOperatorProcessors\ProcessCacheable.cs" />
<Compile Include="Linq\Visitors\QuerySourceLocator.cs" />
<Compile Include="Linq\Visitors\ResultOperatorProcessors\ProcessFetch.cs" />
Modified: trunk/nhibernate/src/NHibernate.Test/Linq/PagingTests.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Linq/PagingTests.cs 2010-04-05 07:15:43 UTC (rev 4969)
+++ trunk/nhibernate/src/NHibernate.Test/Linq/PagingTests.cs 2010-04-07 10:48:41 UTC (rev 4970)
@@ -26,7 +26,7 @@
}
[Test]
- [Ignore("NHibernate does not currently support subqueries in from clause")]
+ [Ignore("Multiple Takes (or Skips) not handled correctly")]
public void CustomersChainedTake()
{
var q = (from c in db.Customers
@@ -41,7 +41,7 @@
}
[Test]
- [Ignore("NHibernate does not currently support subqueries in from clause")]
+ [Ignore("Multiple Takes (or Skips) not handled correctly")]
public void CustomersChainedSkip()
{
var q = (from c in db.Customers select c.CustomerId).Skip(10).Skip(5);
@@ -53,7 +53,7 @@
[Test]
- [Ignore("NHibernate does not currently support subqueries in from clause")]
+ [Ignore("Count with Skip or Take is incorrect (Skip / Take done on the query not the HQL, so get applied at the wrong point")]
public void CountAfterTakeShouldReportTheCorrectNumber()
{
var users = db.Customers.Skip(3).Take(10);
Modified: trunk/nhibernate/src/NHibernate.Test/Linq/WhereTests.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Linq/WhereTests.cs 2010-04-05 07:15:43 UTC (rev 4969)
+++ trunk/nhibernate/src/NHibernate.Test/Linq/WhereTests.cs 2010-04-07 10:48:41 UTC (rev 4970)
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
+using NHibernate.Linq;
using NHibernate.Test.Linq.Entities;
using NUnit.Framework;
@@ -384,5 +385,24 @@
Assert.AreEqual(2, query.Count);
}
- }
+
+ [Test]
+ public void SearchOnObjectTypeWithExtensionMethod()
+ {
+ var query = (from o in session.Query<Animal>()
+ select o).OfType<Dog>().ToList();
+
+ Assert.AreEqual(2, query.Count);
+ }
+
+ [Test]
+ public void SearchOnObjectTypeWithIsKeyword()
+ {
+ var query = (from o in session.Query<Animal>()
+ where o is Dog
+ select o).ToList();
+
+ Assert.AreEqual(2, query.Count);
+ }
+ }
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ric...@us...> - 2010-04-13 18:10:39
|
Revision: 4971
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4971&view=rev
Author: ricbrown
Date: 2010-04-13 18:10:31 +0000 (Tue, 13 Apr 2010)
Log Message:
-----------
Fix NH-2173 (SetMaxResults fails when Dialect has BindLimitParametersFirst == true)
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Engine/QueryParameters.cs
trunk/nhibernate/src/NHibernate/Loader/Loader.cs
trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
Added Paths:
-----------
trunk/nhibernate/src/NHibernate.Test/Pagination/CustomDialectFixture.cs
trunk/nhibernate/src/NHibernate.Test/Pagination/CustomMsSqlDialect.cs
trunk/nhibernate/src/NHibernate.Test/Pagination/CustomMsSqlDriver.cs
Modified: trunk/nhibernate/src/NHibernate/Engine/QueryParameters.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Engine/QueryParameters.cs 2010-04-07 10:48:41 UTC (rev 4970)
+++ trunk/nhibernate/src/NHibernate/Engine/QueryParameters.cs 2010-04-13 18:10:31 UTC (rev 4971)
@@ -526,7 +526,7 @@
public int BindParameters(IDbCommand command, int start, ISessionImplementor session)
{
- int location = 0;
+ int location = start;
var values = new List<object>();
var types = new List<IType>();
var sources = new List<string>();
@@ -565,13 +565,14 @@
}
int span = 0;
- for (int i = 0; i < values.Count; i++)
+ for (int i = start; i < values.Count; i++)
{
IType type = types[i];
object value = values[i];
+ string source = sources[i];
if (log.IsDebugEnabled)
{
- log.Debug(string.Format("BindParameters({0}:{1}) {2} -> [{3}]", "Named", type, value, i));
+ log.Debug(string.Format("BindParameters({0}:{1}) {2} -> [{3}]", source, type, value, i));
}
type.NullSafeSet(command, value, start + span, session);
span += type.GetColumnSpan(session.Factory);
Modified: trunk/nhibernate/src/NHibernate/Loader/Loader.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Loader/Loader.cs 2010-04-07 10:48:41 UTC (rev 4970)
+++ trunk/nhibernate/src/NHibernate/Loader/Loader.cs 2010-04-13 18:10:31 UTC (rev 4971)
@@ -1104,9 +1104,10 @@
bool useLimit = UseLimit(selection, dialect);
bool hasFirstRow = GetFirstRow(selection) > 0;
bool useOffset = hasFirstRow && useLimit && dialect.SupportsLimitOffset;
+ int startIndex = GetFirstLimitParameterCount(dialect, useLimit, hasFirstRow, useOffset);
// TODO NH bool callable = queryParameters.Callable;
- SqlType[] parameterTypes = queryParameters.PrepareParameterTypes(sqlString, Factory, GetNamedParameterLocs, 0, useLimit, useOffset);
+ SqlType[] parameterTypes = queryParameters.PrepareParameterTypes(sqlString, Factory, GetNamedParameterLocs, startIndex, useLimit, useOffset);
if (useLimit)
{
@@ -1204,6 +1205,13 @@
}
}
+ private int GetFirstLimitParameterCount(Dialect.Dialect dialect, bool useLimit, bool hasFirstRow, bool useOffset)
+ {
+ if (!useLimit) return 0;
+ if (!dialect.BindLimitParametersFirst) return 0;
+ return (hasFirstRow && useOffset) ? 2 : 1;
+ }
+
/// <summary>
/// Bind parameters needed by the dialect-specific LIMIT clause
/// </summary>
@@ -1264,7 +1272,7 @@
// NH Different behavior:
// The responsibility of parameter binding was entirely moved to QueryParameters
// to deal with positionslParameter+NamedParameter+ParameterOfFilters
- return queryParameters.BindParameters(statement, 0, session);
+ return queryParameters.BindParameters(statement, startIndex, session);
}
public virtual int[] GetNamedParameterLocs(string name)
@@ -1693,8 +1701,9 @@
bool useLimit = UseLimit(selection, dialect);
bool hasFirstRow = GetFirstRow(selection) > 0;
bool useOffset = hasFirstRow && useLimit && dialect.SupportsLimitOffset;
+ int limitParameterCount = GetFirstLimitParameterCount(dialect, useLimit, hasFirstRow, useOffset);
- SqlType[] sqlTypes = parameters.PrepareParameterTypes(sqlString, Factory, GetNamedParameterLocs, startParameterIndex, useLimit, useOffset);
+ SqlType[] sqlTypes = parameters.PrepareParameterTypes(sqlString, Factory, GetNamedParameterLocs, startParameterIndex + limitParameterCount, useLimit, useOffset);
if (useLimit)
{
Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-04-07 10:48:41 UTC (rev 4970)
+++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-04-13 18:10:31 UTC (rev 4971)
@@ -1320,6 +1320,9 @@
<Compile Include="Operations\PersonalDetails.cs" />
<Compile Include="Operations\TimestampedEntity.cs" />
<Compile Include="Operations\VersionedEntity.cs" />
+ <Compile Include="Pagination\CustomDialectFixture.cs" />
+ <Compile Include="Pagination\CustomMsSqlDialect.cs" />
+ <Compile Include="Pagination\CustomMsSqlDriver.cs" />
<Compile Include="Pagination\DataPoint.cs" />
<Compile Include="Pagination\PaginationFixture.cs" />
<Compile Include="ProjectionFixtures\Key.cs" />
Added: trunk/nhibernate/src/NHibernate.Test/Pagination/CustomDialectFixture.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Pagination/CustomDialectFixture.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/Pagination/CustomDialectFixture.cs 2010-04-13 18:10:31 UTC (rev 4971)
@@ -0,0 +1,119 @@
+using System.Collections;
+using System.Collections.Generic;
+using NHibernate.Cfg;
+using NHibernate.Criterion;
+using NUnit.Framework;
+using Environment = NHibernate.Cfg.Environment;
+
+namespace NHibernate.Test.Pagination
+{
+ [TestFixture]
+ public class CustomDialectFixture : TestCase
+ {
+ protected override string MappingsAssembly
+ {
+ get { return "NHibernate.Test"; }
+ }
+
+ protected override IList Mappings
+ {
+ get { return new[] {"Pagination.DataPoint.hbm.xml"}; }
+ }
+
+ protected override void Configure(Configuration configuration)
+ {
+ if (!(Dialect is Dialect.MsSql2005Dialect))
+ Assert.Ignore("Test is for SQL dialect only");
+
+ cfg.SetProperty(Environment.Dialect, typeof(CustomMsSqlDialect).AssemblyQualifiedName);
+ cfg.SetProperty(Environment.ConnectionDriver, typeof(CustomMsSqlDriver).AssemblyQualifiedName);
+ }
+
+ private CustomMsSqlDialect CustomDialect
+ {
+ get { return (CustomMsSqlDialect)Sfi.Dialect; }
+ }
+
+ private CustomMsSqlDriver CustomDriver
+ {
+ get { return (CustomMsSqlDriver)Sfi.ConnectionProvider.Driver; }
+ }
+
+ protected override void OnSetUp()
+ {
+ base.OnSetUp();
+
+ CustomDriver.CustomMsSqlDialect = CustomDialect;
+
+ using (ISession s = OpenSession())
+ using (ITransaction t = s.BeginTransaction())
+ {
+ s.Save(new DataPoint() { X = 5 });
+ s.Save(new DataPoint() { X = 6 });
+ s.Save(new DataPoint() { X = 7 });
+ s.Save(new DataPoint() { X = 8 });
+ s.Save(new DataPoint() { X = 9 });
+ t.Commit();
+ }
+ }
+
+ protected override void OnTearDown()
+ {
+
+ using (ISession s = OpenSession())
+ using (ITransaction t = s.BeginTransaction())
+ {
+ s.Delete("from DataPoint");
+ t.Commit();
+ }
+ base.OnTearDown();
+ }
+
+ [Test]
+ public void LimitFirst()
+ {
+ using (ISession s = OpenSession())
+ {
+ CustomDialect.ForcedSupportsVariableLimit = true;
+ CustomDialect.ForcedBindLimitParameterFirst = true;
+
+ var points =
+ s.CreateCriteria<DataPoint>()
+ .Add(Restrictions.Gt("X", 5.1d))
+ .AddOrder(Order.Asc("X"))
+ .SetFirstResult(1)
+ .SetMaxResults(2)
+ .List<DataPoint>();
+
+ Assert.That(points.Count, Is.EqualTo(2));
+ Assert.That(points[0].X, Is.EqualTo(7d));
+ Assert.That(points[1].X, Is.EqualTo(8d));
+ }
+ }
+
+ [Test]
+ public void LimitFirstMultiCriteria()
+ {
+ using (ISession s = OpenSession())
+ {
+ CustomDialect.ForcedSupportsVariableLimit = true;
+ CustomDialect.ForcedBindLimitParameterFirst = true;
+
+ var criteria =
+ s.CreateMultiCriteria()
+ .Add<DataPoint>(
+ s.CreateCriteria<DataPoint>()
+ .Add(Restrictions.Gt("X", 5.1d))
+ .AddOrder(Order.Asc("X"))
+ .SetFirstResult(1)
+ .SetMaxResults(2));
+
+ var points = (IList<DataPoint>)criteria.List()[0];
+
+ Assert.That(points.Count, Is.EqualTo(2));
+ Assert.That(points[0].X, Is.EqualTo(7d));
+ Assert.That(points[1].X, Is.EqualTo(8d));
+ }
+ }
+ }
+}
\ No newline at end of file
Added: trunk/nhibernate/src/NHibernate.Test/Pagination/CustomMsSqlDialect.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Pagination/CustomMsSqlDialect.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/Pagination/CustomMsSqlDialect.cs 2010-04-13 18:10:31 UTC (rev 4971)
@@ -0,0 +1,17 @@
+using NHibernate.Dialect;
+
+namespace NHibernate.Test.Pagination
+{
+ /// <summary>
+ /// Class to simulate dialects with different binding of limit parameters
+ /// using an MSSql database
+ /// </summary>
+ public class CustomMsSqlDialect : MsSql2005Dialect
+ {
+ public bool ForcedBindLimitParameterFirst;
+ public bool ForcedSupportsVariableLimit;
+
+ public override bool BindLimitParametersFirst { get { return ForcedBindLimitParameterFirst; } }
+ public override bool SupportsVariableLimit { get { return ForcedSupportsVariableLimit; } }
+ }
+}
\ No newline at end of file
Added: trunk/nhibernate/src/NHibernate.Test/Pagination/CustomMsSqlDriver.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Pagination/CustomMsSqlDriver.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/Pagination/CustomMsSqlDriver.cs 2010-04-13 18:10:31 UTC (rev 4971)
@@ -0,0 +1,35 @@
+using System.Data;
+using System.Text.RegularExpressions;
+using NHibernate.Driver;
+using NUnit.Framework;
+
+namespace NHibernate.Test.Pagination
+{
+ /// <summary>
+ /// Class to work with CustomMsSqlDialect to allow
+ /// verification of simulated limit parameters
+ /// </summary>
+ public class CustomMsSqlDriver : SqlClientDriver
+ {
+ public CustomMsSqlDialect CustomMsSqlDialect;
+
+ protected override void OnBeforePrepare(IDbCommand command)
+ {
+ bool hasLimit = new Regex(@"select\s+top").IsMatch(command.CommandText.ToLower());
+
+ if (hasLimit && CustomMsSqlDialect.ForcedSupportsVariableLimit && CustomMsSqlDialect.ForcedBindLimitParameterFirst)
+ {
+ int offset = (int)((IDataParameter)command.Parameters[0]).Value;
+ int limit = (int)((IDataParameter)command.Parameters[1]).Value;
+
+ Assert.That(command.CommandText.ToLower().Contains("top " + limit),
+ "Expected string containing 'top " + limit + "', but got " + command.CommandText);
+
+ Assert.That(command.CommandText.ToLower().Contains("hibernate_sort_row > " + offset),
+ "Expected string containing 'hibernate_sort_row > " + offset + "', but got " + command.CommandText);
+ }
+
+ base.OnBeforePrepare(command);
+ }
+ }
+}
\ 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: <aye...@us...> - 2010-04-22 22:25:27
|
Revision: 4972
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4972&view=rev
Author: ayenderahien
Date: 2010-04-22 22:25:21 +0000 (Thu, 22 Apr 2010)
Log Message:
-----------
Applying patch for NH-2131
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Impl/AbstractSessionImpl.cs
trunk/nhibernate/src/NHibernate/Transaction/AdoNetTransactionFactory.cs
trunk/nhibernate/src/NHibernate/Transaction/AdoNetWithDistrubtedTransactionFactory.cs
trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
Added Paths:
-----------
trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/SessionIdLoggingContextTest/
trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/SessionIdLoggingContextTest/Mappings.hbm.xml
trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/SessionIdLoggingContextTest/Model.cs
trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/SessionIdLoggingContextTest/PerfTest.cs
trunk/nhibernate/src/NHibernate.TestDatabaseSetup/Properties/
Modified: trunk/nhibernate/src/NHibernate/Impl/AbstractSessionImpl.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Impl/AbstractSessionImpl.cs 2010-04-13 18:10:31 UTC (rev 4971)
+++ trunk/nhibernate/src/NHibernate/Impl/AbstractSessionImpl.cs 2010-04-22 22:25:21 UTC (rev 4972)
@@ -186,12 +186,9 @@
protected internal virtual void CheckAndUpdateSessionStatus()
{
- using (new SessionIdLoggingContext(SessionId))
- {
- ErrorIfClosed();
- EnlistInAmbientTransactionIfNeeded();
- }
- }
+ ErrorIfClosed();
+ EnlistInAmbientTransactionIfNeeded();
+ }
protected internal virtual void ErrorIfClosed()
{
@@ -335,10 +332,7 @@
protected void EnlistInAmbientTransactionIfNeeded()
{
- using (new SessionIdLoggingContext(SessionId))
- {
- factory.TransactionFactory.EnlistInDistributedTransactionIfNeeded(this);
- }
+ factory.TransactionFactory.EnlistInDistributedTransactionIfNeeded(this);
}
}
}
Modified: trunk/nhibernate/src/NHibernate/Transaction/AdoNetTransactionFactory.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Transaction/AdoNetTransactionFactory.cs 2010-04-13 18:10:31 UTC (rev 4971)
+++ trunk/nhibernate/src/NHibernate/Transaction/AdoNetTransactionFactory.cs 2010-04-22 22:25:21 UTC (rev 4972)
@@ -7,6 +7,7 @@
using NHibernate.Engine;
using NHibernate.Engine.Transaction;
using NHibernate.Exceptions;
+using NHibernate.Impl;
namespace NHibernate.Transaction
{
@@ -64,30 +65,34 @@
}
catch (Exception t)
{
- try
- {
- if (trans != null && connection.State != ConnectionState.Closed)
- {
- trans.Rollback();
- }
- }
- catch (Exception ignore)
- {
- isolaterLog.Debug("unable to release connection on exception [" + ignore + "]");
- }
+ using (new SessionIdLoggingContext(session.SessionId))
+ {
+ try
+ {
+ if (trans != null && connection.State != ConnectionState.Closed)
+ {
+ trans.Rollback();
+ }
+ }
+ catch (Exception ignore)
+ {
+ isolaterLog.Debug("unable to release connection on exception [" + ignore + "]");
+ }
- if (t is HibernateException)
- {
- throw;
- }
- else if (t is DbException)
- {
- throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, t, "error performing isolated work");
- }
- else
- {
- throw new HibernateException("error performing isolated work", t);
- }
+ if (t is HibernateException)
+ {
+ throw;
+ }
+ else if (t is DbException)
+ {
+ throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, t,
+ "error performing isolated work");
+ }
+ else
+ {
+ throw new HibernateException("error performing isolated work", t);
+ }
+ }
}
finally
{
Modified: trunk/nhibernate/src/NHibernate/Transaction/AdoNetWithDistrubtedTransactionFactory.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Transaction/AdoNetWithDistrubtedTransactionFactory.cs 2010-04-13 18:10:31 UTC (rev 4971)
+++ trunk/nhibernate/src/NHibernate/Transaction/AdoNetWithDistrubtedTransactionFactory.cs 2010-04-22 22:25:21 UTC (rev 4972)
@@ -26,34 +26,42 @@
public void EnlistInDistributedTransactionIfNeeded(ISessionImplementor session)
{
- if (session.TransactionContext != null)
- return;
- if (System.Transactions.Transaction.Current == null)
- return;
- var transactionContext = new DistributedTransactionContext(session, System.Transactions.Transaction.Current);
- session.TransactionContext = transactionContext;
- logger.DebugFormat("enlisted into DTC transaction: {0}", transactionContext.AmbientTransation.IsolationLevel);
- session.AfterTransactionBegin(null);
- transactionContext.AmbientTransation.TransactionCompleted += delegate(object sender, TransactionEventArgs e)
- {
- bool wasSuccessful = false;
- try
- {
- wasSuccessful = e.Transaction.TransactionInformation.Status
- == TransactionStatus.Committed;
- }
- catch (ObjectDisposedException ode)
- {
- logger.Warn("Completed transaction was disposed, assuming transaction rollback", ode);
- }
- session.AfterTransactionCompletion(wasSuccessful, null);
- if (transactionContext.ShouldCloseSessionOnDistributedTransactionCompleted)
- {
- session.CloseSessionFromDistributedTransaction();
- }
- session.TransactionContext = null;
- };
- transactionContext.AmbientTransation.EnlistVolatile(transactionContext, EnlistmentOptions.EnlistDuringPrepareRequired);
+ if (session.TransactionContext != null)
+ return;
+ if (System.Transactions.Transaction.Current == null)
+ return;
+ var transactionContext = new DistributedTransactionContext(session,
+ System.Transactions.Transaction.Current);
+ session.TransactionContext = transactionContext;
+ logger.DebugFormat("enlisted into DTC transaction: {0}",
+ transactionContext.AmbientTransation.IsolationLevel);
+ session.AfterTransactionBegin(null);
+ transactionContext.AmbientTransation.TransactionCompleted +=
+ delegate(object sender, TransactionEventArgs e)
+ {
+ using (new SessionIdLoggingContext(session.SessionId))
+ {
+ bool wasSuccessful = false;
+ try
+ {
+ wasSuccessful = e.Transaction.TransactionInformation.Status
+ == TransactionStatus.Committed;
+ }
+ catch (ObjectDisposedException ode)
+ {
+ logger.Warn("Completed transaction was disposed, assuming transaction rollback", ode);
+ }
+ session.AfterTransactionCompletion(wasSuccessful, null);
+ if (transactionContext.ShouldCloseSessionOnDistributedTransactionCompleted)
+ {
+ session.CloseSessionFromDistributedTransaction();
+ }
+ session.TransactionContext = null;
+ }
+ };
+ transactionContext.AmbientTransation.EnlistVolatile(transactionContext,
+ EnlistmentOptions.EnlistDuringPrepareRequired);
+
}
public bool IsInDistributedActiveTransaction(ISessionImplementor session)
Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/SessionIdLoggingContextTest/Mappings.hbm.xml
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/SessionIdLoggingContextTest/Mappings.hbm.xml (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/SessionIdLoggingContextTest/Mappings.hbm.xml 2010-04-22 22:25:21 UTC (rev 4972)
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
+ namespace="NHibernate.Test.NHSpecificTest.SessionIdLoggingContextTest"
+ assembly="NHibernate.Test">
+
+ <class name="ClassA">
+ <id name="Id">
+ <generator class="guid.comb"/>
+ </id>
+ <property name="Name"/>
+ <bag name="Children" cascade="all-delete-orphan">
+ <key column="Parent" />
+ <one-to-many class="ClassA"/>
+ </bag>
+
+ </class>
+
+</hibernate-mapping>
Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/SessionIdLoggingContextTest/Model.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/SessionIdLoggingContextTest/Model.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/SessionIdLoggingContextTest/Model.cs 2010-04-22 22:25:21 UTC (rev 4972)
@@ -0,0 +1,12 @@
+using System;
+using System.Collections.Generic;
+
+namespace NHibernate.Test.NHSpecificTest.SessionIdLoggingContextTest
+{
+ public class ClassA
+ {
+ public virtual Guid Id { get; set; }
+ public virtual IList<ClassA> Children { get; set; }
+ public virtual string Name { get; set; }
+ }
+}
Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/SessionIdLoggingContextTest/PerfTest.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/SessionIdLoggingContextTest/PerfTest.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/SessionIdLoggingContextTest/PerfTest.cs 2010-04-22 22:25:21 UTC (rev 4972)
@@ -0,0 +1,82 @@
+using System;
+using System.Collections.Generic;
+using NHibernate.Criterion;
+using NHibernate.Transform;
+using NUnit.Framework;
+using NHibernate.Transaction;
+
+namespace NHibernate.Test.NHSpecificTest.SessionIdLoggingContextTest
+{
+ [TestFixture]
+ public class PerfTest : BugTestCase
+ {
+ const int noOfParents = 1000;
+ const int noOfChildrenForEachParent = 20;
+
+ [Test]
+ public void Benchmark()
+ {
+ using(var s= OpenSession())
+ {
+ var ticksAtStart = DateTime.Now.Ticks;
+ var res = s.CreateCriteria<ClassA>()
+ .SetFetchMode("Children", FetchMode.Join)
+ .SetResultTransformer(Transformers.DistinctRootEntity)
+ .Add(Restrictions.Eq("Name", "Parent"))
+ .List<ClassA>();
+ Console.WriteLine(TimeSpan.FromTicks(DateTime.Now.Ticks-ticksAtStart));
+ Assert.AreEqual(noOfParents, res.Count);
+ Assert.AreEqual(noOfChildrenForEachParent, res[0].Children.Count);
+ }
+ }
+
+ protected override void Configure(Cfg.Configuration configuration)
+ {
+ //get rid of the overhead supporting distr trans
+ configuration.SetProperty(Cfg.Environment.TransactionStrategy, typeof(AdoNetTransactionFactory).FullName);
+ }
+
+ protected override void OnSetUp()
+ {
+ using (var s = OpenSession())
+ {
+ using (var tx = s.BeginTransaction())
+ {
+ for (var i = 0; i < noOfParents; i++)
+ {
+ var parent = createEntity("Parent");
+ for (var j = 0; j < noOfChildrenForEachParent; j++)
+ {
+ var child = createEntity("Child");
+ parent.Children.Add(child);
+ }
+ s.Save(parent);
+ }
+ tx.Commit();
+ }
+ }
+ }
+
+ protected override void OnTearDown()
+ {
+ using(var s = OpenSession())
+ {
+ using(var tx = s.BeginTransaction())
+ {
+ s.CreateQuery("delete from ClassA").ExecuteUpdate();
+ tx.Commit();
+ }
+ }
+ }
+
+ private static ClassA createEntity(string name)
+ {
+ var obj = new ClassA
+ {
+ Children = new List<ClassA>(),
+ Name = name
+ };
+ return obj;
+ }
+ }
+}
Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-04-13 18:10:31 UTC (rev 4971)
+++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-04-22 22:25:21 UTC (rev 4972)
@@ -1291,6 +1291,8 @@
<Compile Include="NHSpecificTest\ProxyValidator\Fixture.cs" />
<Compile Include="NHSpecificTest\NH1362\Fixture.cs" />
<Compile Include="NHSpecificTest\NH1362\Model.cs" />
+ <Compile Include="NHSpecificTest\SessionIdLoggingContextTest\Model.cs" />
+ <Compile Include="NHSpecificTest\SessionIdLoggingContextTest\PerfTest.cs" />
<Compile Include="NHSpecificTest\SetFixture.cs" />
<Compile Include="NHSpecificTest\SimpleComponentFixture.cs" />
<Compile Include="NHSpecificTest\UnsavedValueFixture.cs" />
@@ -2129,8 +2131,9 @@
<EmbeddedResource Include="CfgTest\Loquacious\EntityToCache.hbm.xml" />
<EmbeddedResource Include="DriverTest\SqlServerCeEntity.hbm.xml" />
<Content Include="DynamicEntity\package.html" />
- <EmbeddedResource Include="ListIndex\SimpleOneToMany.hbm.xml" />
- <EmbeddedResource Include="NHSpecificTest\NH2113\Mappings.hbm.xml" />
+ <EmbeddedResource Include="ListIndex\SimpleOneToMany.hbm.xml" />
+ <EmbeddedResource Include="NHSpecificTest\SessionIdLoggingContextTest\Mappings.hbm.xml" />
+ <EmbeddedResource Include="NHSpecificTest\NH2113\Mappings.hbm.xml" />
<EmbeddedResource Include="NHSpecificTest\NH1981\Mappings.hbm.xml" />
<EmbeddedResource Include="NHSpecificTest\NH2074\Mappings.hbm.xml" />
<EmbeddedResource Include="NHSpecificTest\NH2077\Mappings.hbm.xml" />
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ric...@us...> - 2010-04-27 16:28:16
|
Revision: 4973
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4973&view=rev
Author: ricbrown
Date: 2010-04-27 16:28:10 +0000 (Tue, 27 Apr 2010)
Log Message:
-----------
Implement NH-2186 (Allow MultiCriteria to directly add IQueryOver; improvement suggested by Jason Dentler)
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs
trunk/nhibernate/src/NHibernate/IMultiCriteria.cs
trunk/nhibernate/src/NHibernate/IQueryOver.cs
trunk/nhibernate/src/NHibernate/Impl/MultiCriteriaImpl.cs
trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs
Modified: trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs 2010-04-22 22:25:21 UTC (rev 4972)
+++ trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs 2010-04-27 16:28:10 UTC (rev 4973)
@@ -35,6 +35,11 @@
get { return criteria; }
}
+ public ICriteria RootCriteria
+ {
+ get { return impl; }
+ }
+
public DetachedCriteria DetachedCriteria
{
get { return new DetachedCriteria(impl, impl); }
@@ -138,9 +143,6 @@
}
- ICriteria IQueryOver<TRoot>.UnderlyingCriteria
- { get { return UnderlyingCriteria; } }
-
IList<TRoot> IQueryOver<TRoot>.List()
{ return List(); }
Modified: trunk/nhibernate/src/NHibernate/IMultiCriteria.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/IMultiCriteria.cs 2010-04-22 22:25:21 UTC (rev 4972)
+++ trunk/nhibernate/src/NHibernate/IMultiCriteria.cs 2010-04-27 16:28:10 UTC (rev 4973)
@@ -83,6 +83,44 @@
IMultiCriteria Add(string key, DetachedCriteria detachedCriteria);
/// <summary>
+ /// Adds the specified IQueryOver to the query. The result will be contained in a <see cref="System.Collections.Generic.List{resultGenericListType}"/>
+ /// </summary>
+ /// <param name="resultGenericListType">Return results in a <see cref="System.Collections.Generic.List{resultGenericListType}"/></param>
+ /// <param name="queryOver">The IQueryOver.</param>
+ /// <returns></returns>
+ IMultiCriteria Add(System.Type resultGenericListType, IQueryOver queryOver);
+
+ /// <summary>
+ /// Adds the specified IQueryOver to the query. The result will be contained in a <see cref="System.Collections.Generic.List{T}"/>
+ /// </summary>
+ /// <param name="queryOver">The IQueryOver.</param>
+ /// <returns></returns>
+ IMultiCriteria Add<T>(IQueryOver<T> queryOver);
+
+ /// <summary>
+ /// Adds the specified IQueryOver to the query. The result will be contained in a <see cref="System.Collections.Generic.List{U}"/>
+ /// </summary>
+ /// <param name="queryOver">The IQueryOver.</param>
+ /// <returns></returns>
+ IMultiCriteria Add<U>(IQueryOver queryOver);
+
+ /// <summary>
+ /// Adds the specified IQueryOver to the query, and associates it with the given key. The result will be contained in a <see cref="System.Collections.Generic.List{T}"/>
+ /// </summary>
+ /// <param name="key">The key</param>
+ /// <param name="queryOver">The IQueryOver</param>
+ /// <returns></returns>
+ IMultiCriteria Add<T>(string key, IQueryOver<T> queryOver);
+
+ /// <summary>
+ /// Adds the specified IQueryOver to the query, and associates it with the given key. The result will be contained in a <see cref="System.Collections.Generic.List{U}"/>
+ /// </summary>
+ /// <param name="key">The key</param>
+ /// <param name="queryOver">The IQueryOver</param>
+ /// <returns></returns>
+ IMultiCriteria Add<U>(string key, IQueryOver queryOver);
+
+ /// <summary>
/// Sets whatevert this criteria is cacheable.
/// </summary>
/// <param name="cachable">if set to <c>true</c> [cachable].</param>
Modified: trunk/nhibernate/src/NHibernate/IQueryOver.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/IQueryOver.cs 2010-04-22 22:25:21 UTC (rev 4972)
+++ trunk/nhibernate/src/NHibernate/IQueryOver.cs 2010-04-27 16:28:10 UTC (rev 4973)
@@ -10,6 +10,19 @@
namespace NHibernate
{
+ public interface IQueryOver
+ {
+ /// <summary>
+ /// Access the underlying ICriteria
+ /// </summary>
+ ICriteria UnderlyingCriteria { get; }
+
+ /// <summary>
+ /// Access the root underlying ICriteria
+ /// </summary>
+ ICriteria RootCriteria { get; }
+ }
+
/// <summary>
/// QueryOver<TRoot> is an API for retrieving entities by composing
/// <see cref="Criterion.Expression" /> objects expressed using Lambda expression syntax.
@@ -22,14 +35,9 @@
/// .List();
/// </code>
/// </remarks>
- public interface IQueryOver<TRoot>
+ public interface IQueryOver<TRoot> : IQueryOver
{
/// <summary>
- /// Access the underlying ICriteria
- /// </summary>
- ICriteria UnderlyingCriteria { get; }
-
- /// <summary>
/// Get the results of the root type and fill the <see cref="IList<T>"/>
/// </summary>
/// <returns>The list filled with the results.</returns>
Modified: trunk/nhibernate/src/NHibernate/Impl/MultiCriteriaImpl.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Impl/MultiCriteriaImpl.cs 2010-04-22 22:25:21 UTC (rev 4972)
+++ trunk/nhibernate/src/NHibernate/Impl/MultiCriteriaImpl.cs 2010-04-27 16:28:10 UTC (rev 4973)
@@ -424,6 +424,31 @@
return this;
}
+ public IMultiCriteria Add(System.Type resultGenericListType, IQueryOver queryOver)
+ {
+ return Add(resultGenericListType, queryOver.RootCriteria);
+ }
+
+ public IMultiCriteria Add<T>(IQueryOver<T> queryOver)
+ {
+ return Add<T>(queryOver.RootCriteria);
+ }
+
+ public IMultiCriteria Add<U>(IQueryOver queryOver)
+ {
+ return Add<U>(queryOver.RootCriteria);
+ }
+
+ public IMultiCriteria Add<T>(string key, IQueryOver<T> queryOver)
+ {
+ return Add<T>(key, queryOver.RootCriteria);
+ }
+
+ public IMultiCriteria Add<U>(string key, IQueryOver queryOver)
+ {
+ return Add<U>(key, queryOver.RootCriteria);
+ }
+
public IMultiCriteria SetCacheable(bool cachable)
{
isCacheable = cachable;
Modified: trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs 2010-04-22 22:25:21 UTC (rev 4972)
+++ trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs 2010-04-27 16:28:10 UTC (rev 4973)
@@ -265,24 +265,8 @@
[Test]
public void RowCount()
{
- using (ISession s = OpenSession())
- using (ITransaction t = s.BeginTransaction())
- {
- s.Save(new Person() { Name = "Name 1", Age = 1 }
- .AddChild(new Child() { Nickname = "Name 1.1", Age = 1}));
+ SetupPagingData();
- s.Save(new Person() { Name = "Name 2", Age = 2 }
- .AddChild(new Child() { Nickname = "Name 2.1", Age = 3}));
-
- s.Save(new Person() { Name = "Name 3", Age = 3 }
- .AddChild(new Child() { Nickname = "Name 3.1", Age = 2}));
-
- s.Save(new Person() { Name = "Name 4", Age = 4 }
- .AddChild(new Child() { Nickname = "Name 4.1", Age = 4}));
-
- t.Commit();
- }
-
using (ISession s = OpenSession())
{
IQueryOver<Person> query =
@@ -301,6 +285,79 @@
}
}
+ [Test]
+ public void MultiCriteria()
+ {
+ SetupPagingData();
+
+ using (ISession s = OpenSession())
+ {
+ IQueryOver<Person> query =
+ s.QueryOver<Person>()
+ .JoinQueryOver(p => p.Children)
+ .OrderBy(c => c.Age).Desc
+ .Skip(2)
+ .Take(1);
+
+ var multiCriteria =
+ s.CreateMultiCriteria()
+ .Add("page", query)
+ .Add<int>("count", query.ToRowCountQuery());
+
+ var pageResults = (IList<Person>) multiCriteria.GetResult("page");
+ var countResults = (IList<int>) multiCriteria.GetResult("count");
+
+ Assert.That(pageResults.Count, Is.EqualTo(1));
+ Assert.That(pageResults[0].Name, Is.EqualTo("Name 3"));
+ Assert.That(countResults.Count, Is.EqualTo(1));
+ Assert.That(countResults[0], Is.EqualTo(4));
+ }
+
+ using (ISession s = OpenSession())
+ {
+ QueryOver<Person> query =
+ QueryOver.Of<Person>()
+ .JoinQueryOver(p => p.Children)
+ .OrderBy(c => c.Age).Desc
+ .Skip(2)
+ .Take(1);
+
+ var multiCriteria =
+ s.CreateMultiCriteria()
+ .Add("page", query)
+ .Add<int>("count", query.ToRowCountQuery());
+
+ var pageResults = (IList<Person>) multiCriteria.GetResult("page");
+ var countResults = (IList<int>) multiCriteria.GetResult("count");
+
+ Assert.That(pageResults.Count, Is.EqualTo(1));
+ Assert.That(pageResults[0].Name, Is.EqualTo("Name 3"));
+ Assert.That(countResults.Count, Is.EqualTo(1));
+ Assert.That(countResults[0], Is.EqualTo(4));
+ }
+ }
+
+ private void SetupPagingData()
+ {
+ using (ISession s = OpenSession())
+ using (ITransaction t = s.BeginTransaction())
+ {
+ s.Save(new Person() { Name = "Name 1", Age = 1 }
+ .AddChild(new Child() { Nickname = "Name 1.1", Age = 1}));
+
+ s.Save(new Person() { Name = "Name 2", Age = 2 }
+ .AddChild(new Child() { Nickname = "Name 2.1", Age = 3}));
+
+ s.Save(new Person() { Name = "Name 3", Age = 3 }
+ .AddChild(new Child() { Nickname = "Name 3.1", Age = 2}));
+
+ s.Save(new Person() { Name = "Name 4", Age = 4 }
+ .AddChild(new Child() { Nickname = "Name 4.1", Age = 4}));
+
+ t.Commit();
+ }
+ }
+
}
}
\ 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-04-27 16:54:50
|
Revision: 4974
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4974&view=rev
Author: ricbrown
Date: 2010-04-27 16:54:44 +0000 (Tue, 27 Apr 2010)
Log Message:
-----------
Added RowCountInt64 to IQueryOver.
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs
trunk/nhibernate/src/NHibernate/IQueryOver.cs
trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs
trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/QueryOverFixture.cs
Modified: trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs 2010-04-27 16:28:10 UTC (rev 4973)
+++ trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs 2010-04-27 16:54:44 UTC (rev 4974)
@@ -124,6 +124,20 @@
}
/// <summary>
+ /// Clones the QueryOver, clears the orders and paging, and projects the RowCount (Int64)
+ /// </summary>
+ /// <returns></returns>
+ public QueryOver<TRoot,TRoot> ToRowCountInt64Query()
+ {
+ return
+ Clone()
+ .ClearOrders()
+ .Skip(0)
+ .Take(RowSelection.NoValue)
+ .Select(Projections.RowCountInt64());
+ }
+
+ /// <summary>
/// Creates an exact clone of the QueryOver
/// </summary>
public QueryOver<TRoot,TRoot> Clone()
@@ -152,9 +166,15 @@
IQueryOver<TRoot,TRoot> IQueryOver<TRoot>.ToRowCountQuery()
{ return ToRowCountQuery(); }
+ IQueryOver<TRoot,TRoot> IQueryOver<TRoot>.ToRowCountInt64Query()
+ { return ToRowCountInt64Query(); }
+
int IQueryOver<TRoot>.RowCount()
{ return ToRowCountQuery().SingleOrDefault<int>(); }
+ long IQueryOver<TRoot>.RowCountInt64()
+ { return ToRowCountInt64Query().SingleOrDefault<long>(); }
+
TRoot IQueryOver<TRoot>.SingleOrDefault()
{ return SingleOrDefault(); }
Modified: trunk/nhibernate/src/NHibernate/IQueryOver.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/IQueryOver.cs 2010-04-27 16:28:10 UTC (rev 4973)
+++ trunk/nhibernate/src/NHibernate/IQueryOver.cs 2010-04-27 16:54:44 UTC (rev 4974)
@@ -56,11 +56,22 @@
IQueryOver<TRoot,TRoot> ToRowCountQuery();
/// <summary>
- /// Short for ToRowCountQuery().SingleOrDefault()
+ /// Clones the QueryOver, removes orders and paging, and projects the row-count (Int64)
+ /// for the query
/// </summary>
+ IQueryOver<TRoot,TRoot> ToRowCountInt64Query();
+
+ /// <summary>
+ /// Short for ToRowCountQuery().SingleOrDefault<int>()
+ /// </summary>
int RowCount();
/// <summary>
+ /// Short for ToRowCountInt64Query().SingleOrDefault<long>()
+ /// </summary>
+ long RowCountInt64();
+
+ /// <summary>
/// Convenience method to return a single instance that matches
/// the query, or null if the query returns no results.
/// </summary>
Modified: trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs 2010-04-27 16:28:10 UTC (rev 4973)
+++ trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs 2010-04-27 16:54:44 UTC (rev 4974)
@@ -278,10 +278,13 @@
IList<Person> results = query.List();
int rowCount = query.RowCount();
+ object bigRowCount = query.RowCountInt64();
Assert.That(results.Count, Is.EqualTo(1));
Assert.That(results[0].Name, Is.EqualTo("Name 3"));
Assert.That(rowCount, Is.EqualTo(4));
+ Assert.That(bigRowCount, Is.TypeOf<long>());
+ Assert.That(bigRowCount, Is.EqualTo(4));
}
}
Modified: trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/QueryOverFixture.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/QueryOverFixture.cs 2010-04-27 16:28:10 UTC (rev 4973)
+++ trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/QueryOverFixture.cs 2010-04-27 16:54:44 UTC (rev 4974)
@@ -552,6 +552,31 @@
AssertCriteriaAreEqual(expected.UnderlyingCriteria, actual);
}
+ [Test]
+ public void TransformQueryOverToRowCount64()
+ {
+ IQueryOver<Person> expected =
+ CreateTestQueryOver<Person>()
+ .Where(p => p.Name == "test")
+ .JoinQueryOver(p => p.Children)
+ .Where((Child c) => c.Age == 5)
+ .Select(Projections.RowCountInt64());
+
+ IQueryOver<Person> actual =
+ CreateTestQueryOver<Person>()
+ .Where(p => p.Name == "test")
+ .JoinQueryOver(p => p.Children)
+ .Where((Child c) => c.Age == 5)
+ .OrderBy(c => c.Age).Asc
+ .Skip(20)
+ .Take(10);
+
+ expected = expected.Clone();
+ actual = actual.ToRowCountInt64Query();
+
+ AssertCriteriaAreEqual(expected.UnderlyingCriteria, actual);
+ }
+
}
}
\ 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: <ste...@us...> - 2010-05-01 18:38:27
|
Revision: 4977
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4977&view=rev
Author: steverstrong
Date: 2010-05-01 18:38:21 +0000 (Sat, 01 May 2010)
Log Message:
-----------
Fix for JIRA NH-2169
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Linq/Functions/StringGenerator.cs
trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
Added Paths:
-----------
trunk/nhibernate/src/NHibernate.Test/Linq/CasingTest.cs
Modified: trunk/nhibernate/src/NHibernate/Linq/Functions/StringGenerator.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Linq/Functions/StringGenerator.cs 2010-04-29 21:49:12 UTC (rev 4976)
+++ trunk/nhibernate/src/NHibernate/Linq/Functions/StringGenerator.cs 2010-05-01 18:38:21 UTC (rev 4977)
@@ -122,11 +122,11 @@
if (((method.Name == "ToUpper") || (method.Name == "ToUpperInvariant")))
{
- methodName = "lower";
+ methodName = "upper";
}
else
{
- methodName = "upper";
+ methodName = "lower";
}
return treeBuilder.MethodCall(methodName, visitor.Visit(targetObject).AsExpression());
Added: trunk/nhibernate/src/NHibernate.Test/Linq/CasingTest.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Linq/CasingTest.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/Linq/CasingTest.cs 2010-05-01 18:38:21 UTC (rev 4977)
@@ -0,0 +1,49 @@
+using System.Linq;
+using NUnit.Framework;
+
+namespace NHibernate.Test.Linq
+{
+ [TestFixture]
+ public class CasingTest : LinqTestCase
+ {
+ [Test]
+ public void ToUpper()
+ {
+ var name = (from e in db.Employees
+ where e.EmployeeId == 1
+ select e.FirstName.ToUpper())
+ .Single();
+ Assert.AreEqual("NANCY", name);
+ }
+
+ [Test]
+ public void ToUpperInvariant()
+ {
+ var name = (from e in db.Employees
+ where e.EmployeeId == 1
+ select e.FirstName.ToUpper())
+ .Single();
+ Assert.AreEqual("NANCY", name);
+ }
+
+ [Test]
+ public void ToLower()
+ {
+ var name = (from e in db.Employees
+ where e.EmployeeId == 1
+ select e.FirstName.ToLower())
+ .Single();
+ Assert.AreEqual("nancy", name);
+ }
+
+ [Test]
+ public void ToLowerInvariant()
+ {
+ var name = (from e in db.Employees
+ where e.EmployeeId == 1
+ select e.FirstName.ToLowerInvariant())
+ .Single();
+ Assert.AreEqual("nancy", name);
+ }
+ }
+}
\ No newline at end of file
Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-04-29 21:49:12 UTC (rev 4976)
+++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-05-01 18:38:21 UTC (rev 4977)
@@ -381,6 +381,7 @@
<Compile Include="Linq\AggregateTests.cs" />
<Compile Include="Linq\BinaryBooleanExpressionTests.cs" />
<Compile Include="Linq\BinaryExpressionOrdererTests.cs" />
+ <Compile Include="Linq\CasingTest.cs" />
<Compile Include="Linq\CollectionAssert.cs" />
<Compile Include="Linq\DateTimeTests.cs" />
<Compile Include="Linq\DynamicQueryTests.cs" />
@@ -2131,9 +2132,9 @@
<EmbeddedResource Include="CfgTest\Loquacious\EntityToCache.hbm.xml" />
<EmbeddedResource Include="DriverTest\SqlServerCeEntity.hbm.xml" />
<Content Include="DynamicEntity\package.html" />
- <EmbeddedResource Include="ListIndex\SimpleOneToMany.hbm.xml" />
- <EmbeddedResource Include="NHSpecificTest\SessionIdLoggingContextTest\Mappings.hbm.xml" />
- <EmbeddedResource Include="NHSpecificTest\NH2113\Mappings.hbm.xml" />
+ <EmbeddedResource Include="ListIndex\SimpleOneToMany.hbm.xml" />
+ <EmbeddedResource Include="NHSpecificTest\SessionIdLoggingContextTest\Mappings.hbm.xml" />
+ <EmbeddedResource Include="NHSpecificTest\NH2113\Mappings.hbm.xml" />
<EmbeddedResource Include="NHSpecificTest\NH1981\Mappings.hbm.xml" />
<EmbeddedResource Include="NHSpecificTest\NH2074\Mappings.hbm.xml" />
<EmbeddedResource Include="NHSpecificTest\NH2077\Mappings.hbm.xml" />
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ric...@us...> - 2010-05-07 22:44:20
|
Revision: 4979
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4979&view=rev
Author: ricbrown
Date: 2010-05-07 22:44:13 +0000 (Fri, 07 May 2010)
Log Message:
-----------
Fix NH-2192 (Thread safety issue with QueryParameters.PrepareParameterTypes)
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Engine/QueryParameters.cs
trunk/nhibernate/src/NHibernate/SqlCommand/SqlString.cs
trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
Added Paths:
-----------
trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2192/
trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2192/Fixture.cs
trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2192/Mappings.hbm.xml
trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2192/Model.cs
Modified: trunk/nhibernate/src/NHibernate/Engine/QueryParameters.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Engine/QueryParameters.cs 2010-05-01 22:22:06 UTC (rev 4978)
+++ trunk/nhibernate/src/NHibernate/Engine/QueryParameters.cs 2010-05-07 22:44:13 UTC (rev 4979)
@@ -304,7 +304,7 @@
if (session.EnabledFilters.Count == 0 || sql.ToString().IndexOf(ParserHelper.HqlVariablePrefix) < 0)
{
- processedSQL = sql;
+ processedSQL = sql.Copy();
return;
}
@@ -393,7 +393,7 @@
processedSQL = result.ToSqlString();
}
- private IList<Parameter> ResetParameterLocations(SqlString sqlString)
+ private IList<Parameter> FindParametersIn(SqlString sqlString)
{
IList<Parameter> sqlParameters = new List<Parameter>();
@@ -401,9 +401,7 @@
{
if (sqlParameter is Parameter)
{
- Parameter parameter = (Parameter)sqlParameter;
- parameter.ParameterPosition = null;
- sqlParameters.Add(parameter);
+ sqlParameters.Add((Parameter)sqlParameter);
}
}
@@ -441,7 +439,7 @@
int parameterIndex = 0;
int totalSpan = 0;
- IList<Parameter> sqlParameters = ResetParameterLocations(sqlString);
+ IList<Parameter> sqlParameters = FindParametersIn(sqlString);
for (int index = 0; index < PositionalParameterTypes.Length; index++)
{
Modified: trunk/nhibernate/src/NHibernate/SqlCommand/SqlString.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/SqlCommand/SqlString.cs 2010-05-01 22:22:06 UTC (rev 4978)
+++ trunk/nhibernate/src/NHibernate/SqlCommand/SqlString.cs 2010-05-07 22:44:13 UTC (rev 4979)
@@ -572,6 +572,22 @@
}
/// <summary>
+ /// Make a copy of the SqlString, with new parameter references (Placeholders)
+ /// </summary>
+ public SqlString Copy()
+ {
+ SqlString clone = Clone();
+
+ for (int i=0; i<clone.sqlParts.Length; i++)
+ {
+ if (clone.sqlParts[i] is Parameter)
+ clone.sqlParts[i] = SqlCommand.Parameter.Placeholder;
+ }
+
+ return clone;
+ }
+
+ /// <summary>
/// Returns substring of this SqlString starting with the specified
/// <paramref name="text" />. If the text is not found, returns an
/// empty, not-null SqlString.
Property changes on: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2192
___________________________________________________________________
Added: bugtraq:url
+ http://jira.nhibernate.org/browse/%BUGID%
Added: bugtraq:logregex
+ NH-\d+
Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2192/Fixture.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2192/Fixture.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2192/Fixture.cs 2010-05-07 22:44:13 UTC (rev 4979)
@@ -0,0 +1,121 @@
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using NUnit.Framework;
+
+namespace NHibernate.Test.NHSpecificTest.NH2192
+{
+ [TestFixture]
+ public class Fixture : BugTestCase
+ {
+ protected override void OnSetUp()
+ {
+ base.OnSetUp();
+
+ using (var s = OpenSession())
+ using (var tx = s.BeginTransaction())
+ {
+ s.Save(new ContentItem() { Name = "Test" });
+ s.Save(new ContentItem() { Name = "Test" });
+ s.Save(new ContentItem() { Name = "Test2" });
+ tx.Commit();
+ }
+ }
+
+ protected override void OnTearDown()
+ {
+ using (var s = OpenSession())
+ using (var tx = s.BeginTransaction())
+ {
+ s.Delete("from ContentItem");
+ tx.Commit();
+ }
+
+ base.OnTearDown();
+ }
+
+ private const int _threadCount = 150;
+
+ [Test]
+ public void HqlIsThreadsafe_UsingThreads()
+ {
+ object sync = new object();
+ List<int> results = new List<int>();
+ List<Exception> exceptions = new List<Exception>();
+
+ var threads = new List<Thread>();
+
+ for (int i=0; i<_threadCount; i++)
+ {
+ var thread = new Thread(new ThreadStart(() =>
+ {
+ try
+ {
+ int result = FetchRowResults();
+ lock (sync)
+ {
+ results.Add(result);
+ }
+ }
+ catch (Exception e)
+ {
+ lock (sync)
+ {
+ exceptions.Add(e);
+ }
+ }
+ }));
+
+ threads.Add(thread);
+ }
+
+ threads.ForEach(t => t.Start());
+ threads.ForEach(t => t.Join());
+
+ if (exceptions.Count > 0)
+ throw exceptions[0];
+
+ results.ForEach(r => Assert.That(r, Is.EqualTo(2)));
+ }
+
+ [Test]
+ public void HqlIsThreadsafe_UsingPool()
+ {
+ List<Exception> exceptions = new List<Exception>();
+ Func<int> result = FetchRowResults;
+ List<IAsyncResult> results = new List<IAsyncResult>();
+
+ for (int i=0; i<_threadCount; i++)
+ results.Add(result.BeginInvoke(null, null));
+
+ results.ForEach(r =>
+ {
+ try
+ {
+ Assert.That(result.EndInvoke(r), Is.EqualTo(2));
+ }
+ catch (Exception e)
+ {
+ exceptions.Add(e);
+ }
+ });
+
+ if (exceptions.Count > 0)
+ throw exceptions[0];
+ }
+
+ private int FetchRowResults()
+ {
+ using (var s = Sfi.OpenSession())
+ {
+ var count =
+ s.CreateQuery("select ci from ContentItem ci where ci.Name = :v1")
+ .SetParameter("v1", "Test")
+ .List<ContentItem>()
+ .Count;
+
+ return count;
+ }
+ }
+ }
+}
Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2192/Mappings.hbm.xml
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2192/Mappings.hbm.xml (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2192/Mappings.hbm.xml 2010-05-07 22:44:13 UTC (rev 4979)
@@ -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.NH2192">
+
+ <class name="ContentItem">
+ <id name="Id">
+ <generator class="hilo" />
+ </id>
+ <property name="Name" type="String" />
+ </class>
+
+</hibernate-mapping>
Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2192/Model.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2192/Model.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2192/Model.cs 2010-05-07 22:44:13 UTC (rev 4979)
@@ -0,0 +1,8 @@
+namespace NHibernate.Test.NHSpecificTest.NH2192
+{
+ public class ContentItem
+ {
+ public virtual int Id { get; set; }
+ public virtual string Name { get; set; }
+ }
+}
Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-05-01 22:22:06 UTC (rev 4978)
+++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-05-07 22:44:13 UTC (rev 4979)
@@ -710,6 +710,8 @@
<Compile Include="NHSpecificTest\NH2077\Model.cs" />
<Compile Include="NHSpecificTest\NH2113\Fixture.cs" />
<Compile Include="NHSpecificTest\NH2113\Model.cs" />
+ <Compile Include="NHSpecificTest\NH2192\Fixture.cs" />
+ <Compile Include="NHSpecificTest\NH2192\Model.cs" />
<Compile Include="NHSpecificTest\NH473\Child.cs" />
<Compile Include="NHSpecificTest\NH473\Fixture.cs" />
<Compile Include="NHSpecificTest\NH473\Parent.cs" />
@@ -2132,6 +2134,7 @@
<EmbeddedResource Include="CfgTest\Loquacious\EntityToCache.hbm.xml" />
<EmbeddedResource Include="DriverTest\SqlServerCeEntity.hbm.xml" />
<Content Include="DynamicEntity\package.html" />
+ <EmbeddedResource Include="NHSpecificTest\NH2192\Mappings.hbm.xml" />
<EmbeddedResource Include="ListIndex\SimpleOneToMany.hbm.xml" />
<EmbeddedResource Include="NHSpecificTest\SessionIdLoggingContextTest\Mappings.hbm.xml" />
<EmbeddedResource Include="NHSpecificTest\NH2113\Mappings.hbm.xml" />
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ric...@us...> - 2010-05-10 11:24:38
|
Revision: 4980
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4980&view=rev
Author: ricbrown
Date: 2010-05-10 11:24:31 +0000 (Mon, 10 May 2010)
Log Message:
-----------
Added IResultTransformer method to IQueryOver.
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Criterion/Lambda/QueryOverOrderBuilder.cs
trunk/nhibernate/src/NHibernate/Criterion/Lambda/QueryOverProjectionBuilder.cs
trunk/nhibernate/src/NHibernate/Criterion/ProjectionsExtensions.cs
trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs
trunk/nhibernate/src/NHibernate/IQueryOver.cs
trunk/nhibernate/src/NHibernate/Impl/ExpressionProcessor.cs
trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs
trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/LambdaFixtureBase.cs
trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/Model.cs
trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/ProjectionsFixture.cs
trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/QueryOverFixture.cs
Modified: trunk/nhibernate/src/NHibernate/Criterion/Lambda/QueryOverOrderBuilder.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Criterion/Lambda/QueryOverOrderBuilder.cs 2010-05-07 22:44:13 UTC (rev 4979)
+++ trunk/nhibernate/src/NHibernate/Criterion/Lambda/QueryOverOrderBuilder.cs 2010-05-10 11:24:31 UTC (rev 4980)
@@ -15,7 +15,7 @@
public QueryOverOrderBuilder(QueryOver<TRoot,TSubType> root, Expression<Func<TSubType, object>> path) : base(root, path)
{}
- public QueryOverOrderBuilder(QueryOver<TRoot,TSubType> root, Expression<Func<object>> path) : base(root, path)
+ public QueryOverOrderBuilder(QueryOver<TRoot,TSubType> root, Expression<Func<object>> path, bool isAlias) : base(root, path, isAlias)
{}
}
@@ -26,7 +26,7 @@
public IQueryOverOrderBuilder(IQueryOver<TRoot,TSubType> root, Expression<Func<TSubType, object>> path) : base(root, path)
{}
- public IQueryOverOrderBuilder(IQueryOver<TRoot,TSubType> root, Expression<Func<object>> path) : base(root, path)
+ public IQueryOverOrderBuilder(IQueryOver<TRoot,TSubType> root, Expression<Func<object>> path, bool isAlias) : base(root, path, isAlias)
{}
}
@@ -36,24 +36,27 @@
protected TReturn root;
protected LambdaExpression path;
+ protected bool isAlias;
protected QueryOverOrderBuilderBase(TReturn root, Expression<Func<TSubType, object>> path)
{
this.root = root;
this.path = path;
+ this.isAlias = false;
}
- protected QueryOverOrderBuilderBase(TReturn root, Expression<Func<object>> path)
+ protected QueryOverOrderBuilderBase(TReturn root, Expression<Func<object>> path, bool isAlias)
{
this.root = root;
this.path = path;
+ this.isAlias = isAlias;
}
public TReturn Asc
{
get
{
- this.root.UnderlyingCriteria.AddOrder(ExpressionProcessor.ProcessOrder(path, Order.Asc));
+ this.root.UnderlyingCriteria.AddOrder(ExpressionProcessor.ProcessOrder(path, Order.Asc, isAlias));
return this.root;
}
}
@@ -62,7 +65,7 @@
{
get
{
- this.root.UnderlyingCriteria.AddOrder(ExpressionProcessor.ProcessOrder(path, Order.Desc));
+ this.root.UnderlyingCriteria.AddOrder(ExpressionProcessor.ProcessOrder(path, Order.Desc, isAlias));
return this.root;
}
}
Modified: trunk/nhibernate/src/NHibernate/Criterion/Lambda/QueryOverProjectionBuilder.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Criterion/Lambda/QueryOverProjectionBuilder.cs 2010-05-07 22:44:13 UTC (rev 4979)
+++ trunk/nhibernate/src/NHibernate/Criterion/Lambda/QueryOverProjectionBuilder.cs 2010-05-10 11:24:31 UTC (rev 4980)
@@ -46,7 +46,7 @@
/// </summary>
public QueryOverProjectionBuilder<T> WithAlias(Expression<Func<object>> alias)
{
- string aliasContainer = ExpressionProcessor.FindMemberExpression(alias.Body);
+ string aliasContainer = ExpressionProcessor.FindPropertyExpression(alias.Body);
lastProjection = Projections.Alias(lastProjection, aliasContainer);
return this;
}
Modified: trunk/nhibernate/src/NHibernate/Criterion/ProjectionsExtensions.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Criterion/ProjectionsExtensions.cs 2010-05-07 22:44:13 UTC (rev 4979)
+++ trunk/nhibernate/src/NHibernate/Criterion/ProjectionsExtensions.cs 2010-05-10 11:24:31 UTC (rev 4980)
@@ -16,7 +16,7 @@
public static IProjection WithAlias(this IProjection projection,
Expression<Func<object>> alias)
{
- string aliasContainer = ExpressionProcessor.FindMemberExpression(alias.Body);
+ string aliasContainer = ExpressionProcessor.FindPropertyExpression(alias.Body);
return Projections.Alias(projection, aliasContainer);
}
}
Modified: trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs 2010-05-07 22:44:13 UTC (rev 4979)
+++ trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs 2010-05-10 11:24:31 UTC (rev 4980)
@@ -7,6 +7,7 @@
using NHibernate.Engine;
using NHibernate.Impl;
using NHibernate.SqlCommand;
+using NHibernate.Transform;
namespace NHibernate.Criterion
{
@@ -330,9 +331,14 @@
public QueryOverOrderBuilder<TRoot,TSubType> OrderBy(Expression<Func<object>> path)
{
- return new QueryOverOrderBuilder<TRoot,TSubType>(this, path);
+ return new QueryOverOrderBuilder<TRoot,TSubType>(this, path, false);
}
+ public QueryOverOrderBuilder<TRoot,TSubType> OrderByAlias(Expression<Func<object>> path)
+ {
+ return new QueryOverOrderBuilder<TRoot,TSubType>(this, path, true);
+ }
+
public QueryOverOrderBuilder<TRoot,TSubType> ThenBy(Expression<Func<TSubType, object>> path)
{
return new QueryOverOrderBuilder<TRoot,TSubType>(this, path);
@@ -340,15 +346,26 @@
public QueryOverOrderBuilder<TRoot,TSubType> ThenBy(Expression<Func<object>> path)
{
- return new QueryOverOrderBuilder<TRoot,TSubType>(this, path);
+ return new QueryOverOrderBuilder<TRoot,TSubType>(this, path, false);
}
+ public QueryOverOrderBuilder<TRoot,TSubType> ThenByAlias(Expression<Func<object>> path)
+ {
+ return new QueryOverOrderBuilder<TRoot,TSubType>(this, path, true);
+ }
+
public QueryOver<TRoot,TSubType> ClearOrders()
{
criteria.ClearOrders();
return this;
}
+ public QueryOver<TRoot,TSubType> TransformUsing(IResultTransformer resultTransformer)
+ {
+ criteria.SetResultTransformer(resultTransformer);
+ return this;
+ }
+
public QueryOver<TRoot,TSubType> Skip(int firstResult)
{
criteria.SetFirstResult(firstResult);
@@ -671,17 +688,26 @@
{ return new IQueryOverOrderBuilder<TRoot,TSubType>(this, path); }
IQueryOverOrderBuilder<TRoot,TSubType> IQueryOver<TRoot,TSubType>.OrderBy(Expression<Func<object>> path)
- { return new IQueryOverOrderBuilder<TRoot,TSubType>(this, path); }
+ { return new IQueryOverOrderBuilder<TRoot,TSubType>(this, path, false); }
+ IQueryOverOrderBuilder<TRoot,TSubType> IQueryOver<TRoot,TSubType>.OrderByAlias(Expression<Func<object>> path)
+ { return new IQueryOverOrderBuilder<TRoot,TSubType>(this, path, true); }
+
IQueryOverOrderBuilder<TRoot,TSubType> IQueryOver<TRoot,TSubType>.ThenBy(Expression<Func<TSubType, object>> path)
{ return new IQueryOverOrderBuilder<TRoot,TSubType>(this, path); }
IQueryOverOrderBuilder<TRoot,TSubType> IQueryOver<TRoot,TSubType>.ThenBy(Expression<Func<object>> path)
- { return new IQueryOverOrderBuilder<TRoot,TSubType>(this, path); }
+ { return new IQueryOverOrderBuilder<TRoot,TSubType>(this, path, false); }
+ IQueryOverOrderBuilder<TRoot,TSubType> IQueryOver<TRoot,TSubType>.ThenByAlias(Expression<Func<object>> path)
+ { return new IQueryOverOrderBuilder<TRoot,TSubType>(this, path, true); }
+
IQueryOver<TRoot,TSubType> IQueryOver<TRoot, TSubType>.ClearOrders()
{ return ClearOrders(); }
+ IQueryOver<TRoot,TSubType> IQueryOver<TRoot,TSubType>.TransformUsing(IResultTransformer resultTransformer)
+ { return TransformUsing(resultTransformer); }
+
IQueryOver<TRoot,TSubType> IQueryOver<TRoot,TSubType>.Skip(int firstResult)
{ return Skip(firstResult); }
Modified: trunk/nhibernate/src/NHibernate/IQueryOver.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/IQueryOver.cs 2010-05-07 22:44:13 UTC (rev 4979)
+++ trunk/nhibernate/src/NHibernate/IQueryOver.cs 2010-05-10 11:24:31 UTC (rev 4980)
@@ -6,6 +6,7 @@
using NHibernate.Criterion;
using NHibernate.Criterion.Lambda;
using NHibernate.SqlCommand;
+using NHibernate.Transform;
namespace NHibernate
{
@@ -262,6 +263,13 @@
IQueryOverOrderBuilder<TRoot,TSubType> OrderBy(Expression<Func<object>> path);
/// <summary>
+ /// Add order for an aliased projection expressed as a lambda expression
+ /// </summary>
+ /// <param name="path">Lambda expression</param>
+ /// <returns>criteria instance</returns>
+ IQueryOverOrderBuilder<TRoot,TSubType> OrderByAlias(Expression<Func<object>> path);
+
+ /// <summary>
/// Add order expressed as a lambda expression
/// </summary>
/// <param name="path">Lambda expression</param>
@@ -276,11 +284,23 @@
IQueryOverOrderBuilder<TRoot,TSubType> ThenBy(Expression<Func<object>> path);
/// <summary>
+ /// Add order for an aliased projection expressed as a lambda expression
+ /// </summary>
+ /// <param name="path">Lambda expression</param>
+ /// <returns>criteria instance</returns>
+ IQueryOverOrderBuilder<TRoot,TSubType> ThenByAlias(Expression<Func<object>> path);
+
+ /// <summary>
/// Clear all orders from the query.
/// </summary>
IQueryOver<TRoot, TSubType> ClearOrders();
/// <summary>
+ /// Transform the results using the supplied IResultTransformer
+ /// </summary>
+ IQueryOver<TRoot,TSubType> TransformUsing(IResultTransformer resultTransformer);
+
+ /// <summary>
/// Set the first result to be retrieved
/// </summary>
/// <param name="firstResult"></param>
Modified: trunk/nhibernate/src/NHibernate/Impl/ExpressionProcessor.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Impl/ExpressionProcessor.cs 2010-05-07 22:44:13 UTC (rev 4979)
+++ trunk/nhibernate/src/NHibernate/Impl/ExpressionProcessor.cs 2010-05-10 11:24:31 UTC (rev 4980)
@@ -174,6 +174,17 @@
}
/// <summary>
+ /// Retrieves the name of the property from a member expression (without leading member access)
+ /// </summary>
+ public static string FindPropertyExpression(Expression expression)
+ {
+ string memberExpression = FindMemberExpression(expression);
+ int periodPosition = memberExpression.LastIndexOf('.') + 1;
+ string property = (periodPosition <= 0) ? memberExpression : memberExpression.Substring(periodPosition);
+ return property;
+ }
+
+ /// <summary>
/// Retrieves a detached criteria from an appropriate lambda expression
/// </summary>
/// <param name="expression">Expresson for detached criteria using .As<>() extension"/></param>
@@ -458,11 +469,13 @@
/// </summary>
/// <param name="expression">The lambda expression to convert</param>
/// <param name="orderDelegate">The appropriate order delegate (order direction)</param>
+ /// <param name="isAlias">Indicates if the path is an aliased projection</param>
/// <returns>NHibernate Order</returns>
public static Order ProcessOrder( LambdaExpression expression,
- Func<string, Order> orderDelegate)
+ Func<string, Order> orderDelegate,
+ bool isAlias)
{
- string property = FindMemberExpression(expression.Body);
+ string property = isAlias ? FindPropertyExpression(expression.Body) : FindMemberExpression(expression.Body);
Order order = orderDelegate(property);
return order;
}
Modified: trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs 2010-05-07 22:44:13 UTC (rev 4979)
+++ trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs 2010-05-10 11:24:31 UTC (rev 4980)
@@ -146,6 +146,38 @@
}
[Test]
+ public void Project_TransformToDto()
+ {
+ using (ISession s = OpenSession())
+ using (ITransaction t = s.BeginTransaction())
+ {
+ s.Save(new Person() { Name = "test person 1", Age = 20 });
+ s.Save(new Person() { Name = "test person 1", Age = 30 });
+ s.Save(new Person() { Name = "test person 2", Age = 40 });
+ t.Commit();
+ }
+
+ using (ISession s = OpenSession())
+ {
+ PersonSummary summary = null;
+ var actual =
+ s.QueryOver<Person>()
+ .Select(list => list
+ .SelectGroup(p => p.Name).WithAlias(() => summary.Name)
+ .Select(Projections.RowCount()).WithAlias(() => summary.Count))
+ .OrderByAlias(() => summary.Name).Asc
+ .TransformUsing(Transformers.AliasToBean<PersonSummary>())
+ .List<PersonSummary>();
+
+ Assert.That(actual.Count, Is.EqualTo(2));
+ Assert.That(actual[0].Name, Is.EqualTo("test person 1"));
+ Assert.That(actual[0].Count, Is.EqualTo(2));
+ Assert.That(actual[1].Name, Is.EqualTo("test person 2"));
+ Assert.That(actual[1].Count, Is.EqualTo(1));
+ }
+ }
+
+ [Test]
public void UniqueResult()
{
using (ISession s = OpenSession())
@@ -244,7 +276,7 @@
.Select(list => list
.Select(p => p.Name)
.SelectSubQuery(childCountQuery).WithAlias(() => childCountAlias))
- .OrderBy(() => childCountAlias).Desc
+ .OrderByAlias(() => childCountAlias).Desc
.List<object[]>()
.Select(props => new {
Name = (string)props[0],
Modified: trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/LambdaFixtureBase.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/LambdaFixtureBase.cs 2010-05-07 22:44:13 UTC (rev 4979)
+++ trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/LambdaFixtureBase.cs 2010-05-10 11:24:31 UTC (rev 4980)
@@ -157,6 +157,13 @@
return;
}
+ if (expected is ConstructorInfo)
+ {
+ Assert.AreEqual(expected.ToString(), actual.ToString());
+ _fieldPath.Pop();
+ return;
+ }
+
while (expectedType != null)
{
foreach (FieldInfo fieldInfo in expectedType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
Modified: trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/Model.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/Model.cs 2010-05-07 22:44:13 UTC (rev 4979)
+++ trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/Model.cs 2010-05-10 11:24:31 UTC (rev 4980)
@@ -75,5 +75,11 @@
}
+ public class PersonSummary
+ {
+ public string Name { get; set; }
+ public int Count { get; set; }
+ }
+
}
Modified: trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/ProjectionsFixture.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/ProjectionsFixture.cs 2010-05-07 22:44:13 UTC (rev 4979)
+++ trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/ProjectionsFixture.cs 2010-05-10 11:24:31 UTC (rev 4980)
@@ -41,7 +41,7 @@
.SetProjection(Projections.ProjectionList()
.Add(Projections.Alias(Projections.Avg("Age"), "personAgeProjectionAlias"))
.Add(Projections.Avg("Age"), "personAgeProjectionAlias")
- .Add(Projections.Avg("personAlias.Age"))
+ .Add(Projections.Avg("personAlias.Age"), "Age")
.Add(Projections.Count("Age"))
.Add(Projections.Count("personAlias.Age"))
.Add(Projections.CountDistinct("Age"))
@@ -65,7 +65,7 @@
.Select(Projections.ProjectionList()
.Add(Projections.Avg<Person>(p => p.Age).WithAlias(() => personAgeProjectionAlias))
.Add(Projections.Avg<Person>(p => p.Age), () => personAgeProjectionAlias)
- .Add(Projections.Avg(() => personAlias.Age))
+ .Add(Projections.Avg(() => personAlias.Age).WithAlias(() => personAlias.Age))
.Add(Projections.Count<Person>(p => p.Age))
.Add(Projections.Count(() => personAlias.Age))
.Add(Projections.CountDistinct<Person>(p => p.Age))
@@ -93,7 +93,7 @@
.SetProjection(Projections.ProjectionList()
.Add(Projections.Alias(Projections.Avg("Age"), "personAgeProjectionAlias"))
.Add(Projections.Avg("Age"))
- .Add(Projections.Avg("personAlias.Age"))
+ .Add(Projections.Avg("personAlias.Age"), "Age")
.Add(Projections.Count("Age"))
.Add(Projections.Count("personAlias.Age"))
.Add(Projections.CountDistinct("Age"))
@@ -117,7 +117,7 @@
.Select(list => list
.SelectAvg(p => p.Age).WithAlias(() => personAgeProjectionAlias)
.Select(Projections.Avg("Age")) // allows private properties
- .SelectAvg(() => personAlias.Age)
+ .SelectAvg(() => personAlias.Age).WithAlias(() => personAlias.Age)
.SelectCount(p => p.Age)
.SelectCount(() => personAlias.Age)
.SelectCountDistinct(p => p.Age)
Modified: trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/QueryOverFixture.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/QueryOverFixture.cs 2010-05-07 22:44:13 UTC (rev 4979)
+++ trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/QueryOverFixture.cs 2010-05-10 11:24:31 UTC (rev 4980)
@@ -354,15 +354,20 @@
.AddOrder(Order.Asc("Name"))
.AddOrder(Order.Desc("Age"))
.AddOrder(Order.Desc("personAlias.Name"))
- .AddOrder(Order.Asc("personAlias.Age"));
+ .AddOrder(Order.Asc("personAlias.Age"))
+ .AddOrder(Order.Asc("summary"))
+ .AddOrder(Order.Desc("Count"));
Person personAlias = null;
+ PersonSummary summary = null;
IQueryOver<Person> actual =
CreateTestQueryOver<Person>(() => personAlias)
.OrderBy(p => p.Name).Asc
.ThenBy(p => p.Age).Desc
.ThenBy(() => personAlias.Name).Desc
- .ThenBy(() => personAlias.Age).Asc;
+ .ThenBy(() => personAlias.Age).Asc
+ .OrderByAlias(() => summary).Asc
+ .ThenByAlias(() => summary.Count).Desc;
AssertCriteriaAreEqual(expected, actual);
}
@@ -454,6 +459,20 @@
}
[Test]
+ public void ResultTransformer()
+ {
+ ICriteria expected =
+ CreateTestCriteria(typeof(Person))
+ .SetResultTransformer(Transformers.AliasToBean<Person>());
+
+ IQueryOver<Person> actual =
+ CreateTestQueryOver<Person>()
+ .TransformUsing(Transformers.AliasToBean<Person>());
+
+ AssertCriteriaAreEqual(expected, actual);
+ }
+
+ [Test]
public void LockAlias()
{
ICriteria expected =
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ric...@us...> - 2010-05-24 20:02:33
|
Revision: 4981
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4981&view=rev
Author: ricbrown
Date: 2010-05-24 20:02:27 +0000 (Mon, 24 May 2010)
Log Message:
-----------
Fix NH-2201 (NDataReader doesn't reset the currentrow index when a move to NextResult is executed)
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Driver/NDataReader.cs
trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
Added Paths:
-----------
trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2201/
trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2201/Fixture.cs
trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2201/Mappings.hbm.xml
trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2201/Model.cs
Modified: trunk/nhibernate/src/NHibernate/Driver/NDataReader.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Driver/NDataReader.cs 2010-05-10 11:24:31 UTC (rev 4980)
+++ trunk/nhibernate/src/NHibernate/Driver/NDataReader.cs 2010-05-24 20:02:27 UTC (rev 4981)
@@ -117,6 +117,7 @@
public bool NextResult()
{
currentResultIndex++;
+ currentRowIndex = -1;
if (currentResultIndex >= results.Length)
{
Property changes on: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2201
___________________________________________________________________
Added: bugtraq:url
+ http://jira.nhibernate.org/browse/%BUGID%
Added: bugtraq:logregex
+ NH-\d+
Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2201/Fixture.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2201/Fixture.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2201/Fixture.cs 2010-05-24 20:02:27 UTC (rev 4981)
@@ -0,0 +1,52 @@
+using System;
+using System.Collections.Generic;
+using NUnit.Framework;
+
+namespace NHibernate.Test.NHSpecificTest.NH2201
+{
+ [TestFixture]
+ public class Fixture : BugTestCase
+ {
+ protected override void OnTearDown()
+ {
+ using (var s = OpenSession())
+ using (var tx = s.BeginTransaction())
+ {
+ s.Delete("from Parent");
+ tx.Commit();
+ }
+
+ base.OnTearDown();
+ }
+
+ [Test]
+ public void CanUseMutliCriteriaAndFetchSelect()
+ {
+ using (var s = OpenSession())
+ using (var tx = s.BeginTransaction())
+ {
+ s.Save(new Parent());
+ s.Save(new SubClass() { Name = "test" });
+
+ tx.Commit();
+ }
+
+ using (ISession s = OpenSession())
+ {
+ Console.WriteLine("*** start");
+ var results =
+ s.CreateMultiCriteria()
+ .Add<Parent>(s.CreateCriteria<Parent>())
+ .Add<Parent>(s.CreateCriteria<Parent>())
+ .List();
+
+ var result1 = (IList<Parent>)results[0];
+ var result2 = (IList<Parent>)results[1];
+
+ Assert.That(result1.Count, Is.EqualTo(2));
+ Assert.That(result2.Count, Is.EqualTo(2));
+ Console.WriteLine("*** end");
+ }
+ }
+ }
+}
Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2201/Mappings.hbm.xml
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2201/Mappings.hbm.xml (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2201/Mappings.hbm.xml 2010-05-24 20:02:27 UTC (rev 4981)
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
+ assembly="NHibernate.Test"
+ namespace="NHibernate.Test.NHSpecificTest.NH2201">
+
+ <class name="Parent" lazy="false">
+ <id name="Id">
+ <generator class="guid.comb" />
+ </id>
+ <discriminator />
+ <subclass name="SubClass">
+ <join table="ParentDetail" fetch="select">
+ <key column="ParentId" />
+ <property name="Name" />
+ </join>
+ </subclass>
+ </class>
+
+</hibernate-mapping>
Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2201/Model.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2201/Model.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2201/Model.cs 2010-05-24 20:02:27 UTC (rev 4981)
@@ -0,0 +1,14 @@
+using System;
+
+namespace NHibernate.Test.NHSpecificTest.NH2201
+{
+ public class Parent
+ {
+ public virtual Guid Id { get; set; }
+ }
+
+ public class SubClass : Parent
+ {
+ public virtual string Name { get; set; }
+ }
+}
Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-05-10 11:24:31 UTC (rev 4980)
+++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-05-24 20:02:27 UTC (rev 4981)
@@ -712,6 +712,8 @@
<Compile Include="NHSpecificTest\NH2113\Model.cs" />
<Compile Include="NHSpecificTest\NH2192\Fixture.cs" />
<Compile Include="NHSpecificTest\NH2192\Model.cs" />
+ <Compile Include="NHSpecificTest\NH2201\Fixture.cs" />
+ <Compile Include="NHSpecificTest\NH2201\Model.cs" />
<Compile Include="NHSpecificTest\NH473\Child.cs" />
<Compile Include="NHSpecificTest\NH473\Fixture.cs" />
<Compile Include="NHSpecificTest\NH473\Parent.cs" />
@@ -2134,6 +2136,7 @@
<EmbeddedResource Include="CfgTest\Loquacious\EntityToCache.hbm.xml" />
<EmbeddedResource Include="DriverTest\SqlServerCeEntity.hbm.xml" />
<Content Include="DynamicEntity\package.html" />
+ <EmbeddedResource Include="NHSpecificTest\NH2201\Mappings.hbm.xml" />
<EmbeddedResource Include="NHSpecificTest\NH2192\Mappings.hbm.xml" />
<EmbeddedResource Include="ListIndex\SimpleOneToMany.hbm.xml" />
<EmbeddedResource Include="NHSpecificTest\SessionIdLoggingContextTest\Mappings.hbm.xml" />
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ste...@us...> - 2010-05-27 14:18:14
|
Revision: 4984
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4984&view=rev
Author: steverstrong
Date: 2010-05-27 14:18:07 +0000 (Thu, 27 May 2010)
Log Message:
-----------
Added support for queries such as "from c in db.Customers.Cacheable() select c"
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Linq/ReWriters/QueryReferenceExpressionFlattener.cs
trunk/nhibernate/src/NHibernate.Test/Linq/QueryCacheableTests.cs
Modified: trunk/nhibernate/src/NHibernate/Linq/ReWriters/QueryReferenceExpressionFlattener.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Linq/ReWriters/QueryReferenceExpressionFlattener.cs 2010-05-27 10:11:44 UTC (rev 4983)
+++ trunk/nhibernate/src/NHibernate/Linq/ReWriters/QueryReferenceExpressionFlattener.cs 2010-05-27 14:18:07 UTC (rev 4984)
@@ -8,17 +8,43 @@
{
public class QueryReferenceExpressionFlattener : NhExpressionTreeVisitor
{
- private QueryReferenceExpressionFlattener()
+ private readonly QueryModel _model;
+
+ private QueryReferenceExpressionFlattener(QueryModel model)
{
+ _model = model;
}
- public static void ReWrite(QueryModel model)
+ public static void ReWrite(QueryModel model)
{
- var visitor = new QueryReferenceExpressionFlattener();
+ var visitor = new QueryReferenceExpressionFlattener(model);
model.TransformExpressions(visitor.VisitExpression);
}
- protected override Expression VisitQuerySourceReferenceExpression(QuerySourceReferenceExpression expression)
+ protected override Expression VisitSubQueryExpression(SubQueryExpression subQuery)
+ {
+ if ((subQuery.QueryModel.BodyClauses.Count == 0) &&
+ ((subQuery.QueryModel.ResultOperators.Count == 0) || (subQuery.QueryModel.ResultOperators.Count == 1 && subQuery.QueryModel.ResultOperators[0] is CacheableResultOperator))
+ )
+ {
+ var selectQuerySource =
+ subQuery.QueryModel.SelectClause.Selector as QuerySourceReferenceExpression;
+
+ if (selectQuerySource != null && selectQuerySource.ReferencedQuerySource == subQuery.QueryModel.MainFromClause)
+ {
+ if (subQuery.QueryModel.ResultOperators.Count == 1)
+ {
+ _model.ResultOperators.Add(subQuery.QueryModel.ResultOperators[0]);
+ }
+
+ return subQuery.QueryModel.MainFromClause.FromExpression;
+ }
+ }
+
+ return base.VisitSubQueryExpression(subQuery);
+ }
+
+ protected override Expression VisitQuerySourceReferenceExpression(QuerySourceReferenceExpression expression)
{
var fromClauseBase = expression.ReferencedQuerySource as FromClauseBase;
@@ -28,10 +54,8 @@
{
return fromClauseBase.FromExpression;
}
- else
- {
- return base.VisitQuerySourceReferenceExpression(expression);
- }
+
+ return base.VisitQuerySourceReferenceExpression(expression);
}
}
}
\ No newline at end of file
Modified: trunk/nhibernate/src/NHibernate.Test/Linq/QueryCacheableTests.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Linq/QueryCacheableTests.cs 2010-05-27 10:11:44 UTC (rev 4983)
+++ trunk/nhibernate/src/NHibernate.Test/Linq/QueryCacheableTests.cs 2010-05-27 14:18:07 UTC (rev 4984)
@@ -50,6 +50,23 @@
}
[Test]
+ public void QueryIsCacheable3()
+ {
+ Sfi.Statistics.Clear();
+ Sfi.QueryCache.Clear();
+
+ var x = (from c in db.Customers.Cacheable()
+ select c).ToList();
+
+ var x2 = (from c in db.Customers
+ select c).ToList();
+
+ Assert.That(Sfi.Statistics.QueryExecutionCount, Is.EqualTo(2));
+ Assert.That(Sfi.Statistics.QueryCachePutCount, Is.EqualTo(1));
+ Assert.That(Sfi.Statistics.QueryCacheHitCount, Is.EqualTo(0));
+ }
+
+ [Test]
public void QueryIsCacheableWithRegion()
{
Sfi.Statistics.Clear();
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ric...@us...> - 2010-05-29 19:25:38
|
Revision: 4985
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4985&view=rev
Author: ricbrown
Date: 2010-05-29 19:25:32 +0000 (Sat, 29 May 2010)
Log Message:
-----------
Fix NH-2189 (Fetch Join Not Consistently Working With Future)
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Impl/MultiCriteriaImpl.cs
trunk/nhibernate/src/NHibernate/Impl/MultiQueryImpl.cs
trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
Added Paths:
-----------
trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2189/
trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2189/Fixture.cs
trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2189/Mappings.hbm.xml
trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2189/Model.cs
Modified: trunk/nhibernate/src/NHibernate/Impl/MultiCriteriaImpl.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Impl/MultiCriteriaImpl.cs 2010-05-27 14:18:07 UTC (rev 4984)
+++ trunk/nhibernate/src/NHibernate/Impl/MultiCriteriaImpl.cs 2010-05-29 19:25:32 UTC (rev 4985)
@@ -241,7 +241,7 @@
object o =
loader.GetRowFromResultSet(reader, session, queryParameters, loader.GetLockModes(queryParameters.LockModes),
- null, hydratedObjects[i], keys, false);
+ null, hydratedObjects[i], keys, true);
if (createSubselects[i])
{
subselectResultKeys[i].Add(keys);
Modified: trunk/nhibernate/src/NHibernate/Impl/MultiQueryImpl.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Impl/MultiQueryImpl.cs 2010-05-27 14:18:07 UTC (rev 4984)
+++ trunk/nhibernate/src/NHibernate/Impl/MultiQueryImpl.cs 2010-05-29 19:25:32 UTC (rev 4985)
@@ -530,7 +530,7 @@
optionalObjectKey,
hydratedObjects[i],
keys,
- false);
+ true);
tempResults.Add(result);
Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2189/Fixture.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2189/Fixture.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2189/Fixture.cs 2010-05-29 19:25:32 UTC (rev 4985)
@@ -0,0 +1,155 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+using NHibernate.Criterion;
+using NUnit.Framework;
+
+namespace NHibernate.Test.NHSpecificTest.NH2189
+{
+ [TestFixture]
+ public class Fixture : BugTestCase
+ {
+ private Guid _policy2Id;
+
+ protected override void OnSetUp()
+ {
+ base.OnSetUp();
+
+ using (ISession s = sessions.OpenSession())
+ using (ITransaction tx = s.BeginTransaction())
+ {
+ TeamMember tm1 = new TeamMember() { Name = "Joe" };
+ TeamMember tm2 = new TeamMember() { Name = "Bill" };
+
+ s.Save(tm1);
+ s.Save(tm2);
+
+ var policy1 = new Policy() { PolicyNumber = 5 };
+ policy1.Tasks.Add(new Task() { Policy = policy1, TaskName = "Task1", TeamMember = tm1 });
+
+ var policy2 = new Policy() { PolicyNumber = 5 };
+ policy2.Tasks.Add(new Task() { Policy = policy2, TaskName = "Task2", TeamMember = tm2 });
+ policy2.Tasks.Add(new Task() { Policy = policy2, TaskName = "Task3", TeamMember = tm2 });
+
+ s.Save(policy1);
+ s.Save(policy2);
+ _policy2Id = policy2.Id;
+
+ tx.Commit();
+ }
+ }
+
+ protected override void OnTearDown()
+ {
+ using (ISession s = sessions.OpenSession())
+ using (ITransaction tx = s.BeginTransaction())
+ {
+ s.Delete("FROM Task");
+ s.Delete("FROM Policy");
+ s.Delete("FROM TeamMember");
+ tx.Commit();
+ }
+
+ base.OnTearDown();
+ }
+
+ [Test]
+ public void FutureQueryReturnsExistingProxy()
+ {
+ using (ISession s = sessions.OpenSession())
+ using (ITransaction t = s.BeginTransaction())
+ {
+ Policy policyProxy = s.Load<Policy>(_policy2Id);
+ Assert.That(NHibernateUtil.IsInitialized(policyProxy), Is.False);
+
+ IEnumerable<Policy> futurePolicy =
+ s.CreateQuery("FROM Policy p where p.Id = :id")
+ .SetParameter("id", _policy2Id)
+ .Future<Policy>();
+
+ Policy queriedPolicy = futurePolicy.ElementAt(0);
+ Assert.That(NHibernateUtil.IsInitialized(queriedPolicy));
+ Assert.That(queriedPolicy, Is.SameAs(policyProxy));
+ }
+ }
+
+ [Test]
+ public void FutureCriteriaReturnsExistingProxy()
+ {
+ using (ISession s = sessions.OpenSession())
+ using (ITransaction t = s.BeginTransaction())
+ {
+ Policy policyProxy = s.Load<Policy>(_policy2Id);
+ Assert.That(NHibernateUtil.IsInitialized(policyProxy), Is.False);
+
+ IEnumerable<Policy> futurePolicy =
+ s.CreateCriteria<Policy>()
+ .Add(Restrictions.Eq("Id", _policy2Id))
+ .Future<Policy>();
+
+ Policy queriedPolicy = futurePolicy.ElementAt(0);
+ Assert.That(NHibernateUtil.IsInitialized(queriedPolicy));
+ Assert.That(queriedPolicy, Is.SameAs(policyProxy));
+ }
+ }
+
+ [Test]
+ public void FutureQueryEagerLoadUsesAlreadyLoadedEntity()
+ {
+ using (ISession s = sessions.OpenSession())
+ using (ITransaction t = s.BeginTransaction())
+ {
+ Policy policy2 = s.CreateQuery("SELECT p FROM Policy p " +
+ "LEFT JOIN FETCH p.Tasks t " +
+ "WHERE p.Id = :id")
+ .SetParameter("id", _policy2Id)
+ .UniqueResult<Policy>();
+
+ Assert.That(NHibernateUtil.IsInitialized(policy2.Tasks));
+ Assert.That(NHibernateUtil.IsInitialized(policy2.Tasks.ElementAt(0)));
+ Assert.That(NHibernateUtil.IsInitialized(policy2.Tasks.ElementAt(1)));
+
+ IEnumerable<Task> tasks = s.CreateQuery("SELECT t FROM Task t " +
+ "INNER JOIN FETCH t.TeamMember ORDER BY t.TaskName")
+ .Future<Task>();
+
+ Assert.That(tasks.Count(), Is.EqualTo(3));
+
+ Assert.That(NHibernateUtil.IsInitialized(tasks.ElementAt(0).TeamMember), Is.True, "Task1 TeamMember not initialized");
+ Assert.That(NHibernateUtil.IsInitialized(tasks.ElementAt(1).TeamMember), Is.True, "Task2 TeamMember not initialized");
+ Assert.That(NHibernateUtil.IsInitialized(tasks.ElementAt(2).TeamMember), Is.True, "Task3 TeamMember not initialized");
+ }
+ }
+
+ [Test]
+ public void FutureCriteriaEagerLoadUsesAlreadyLoadedEntity()
+ {
+ using (ISession s = sessions.OpenSession())
+ using (ITransaction t = s.BeginTransaction())
+ {
+ Policy policy2 =
+ s.CreateCriteria<Policy>()
+ .Add(Restrictions.Eq("Id", _policy2Id))
+ .SetFetchMode("Tasks", FetchMode.Eager)
+ .UniqueResult<Policy>();
+
+ Assert.That(NHibernateUtil.IsInitialized(policy2.Tasks));
+ Assert.That(NHibernateUtil.IsInitialized(policy2.Tasks.ElementAt(0)));
+ Assert.That(NHibernateUtil.IsInitialized(policy2.Tasks.ElementAt(1)));
+
+ IEnumerable<Task> tasks =
+ s.CreateCriteria<Task>()
+ .SetFetchMode("TeamMember", FetchMode.Eager)
+ .AddOrder(Order.Asc("TaskName"))
+ .Future<Task>();
+
+ Assert.That(tasks.Count(), Is.EqualTo(3));
+
+ Assert.That(NHibernateUtil.IsInitialized(tasks.ElementAt(0).TeamMember), Is.True, "Task1 TeamMember not initialized");
+ Assert.That(NHibernateUtil.IsInitialized(tasks.ElementAt(1).TeamMember), Is.True, "Task2 TeamMember not initialized");
+ Assert.That(NHibernateUtil.IsInitialized(tasks.ElementAt(2).TeamMember), Is.True, "Task3 TeamMember not initialized");
+ }
+ }
+ }
+}
Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2189/Mappings.hbm.xml
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2189/Mappings.hbm.xml (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2189/Mappings.hbm.xml 2010-05-29 19:25:32 UTC (rev 4985)
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
+ assembly="NHibernate.Test"
+ namespace="NHibernate.Test.NHSpecificTest.NH2189">
+
+ <class name="Policy">
+ <id name="Id">
+ <generator class="guid.comb" />
+ </id>
+ <property name="PolicyNumber" />
+ <set name="Tasks" inverse="true" cascade="save-update">
+ <key column="PolicyId" />
+ <one-to-many class="Task" />
+ </set>
+ </class>
+
+ <class name="Task">
+ <id name="Id">
+ <generator class="guid.comb" />
+ </id>
+ <property name="TaskName" />
+ <many-to-one name="Policy" column="PolicyId" />
+ <many-to-one name="TeamMember" column="TeamMemberId" />
+ </class>
+
+ <class name="TeamMember">
+ <id name="Id">
+ <generator class="guid.comb" />
+ </id>
+ <property name="Name" />
+ </class>
+
+</hibernate-mapping>
Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2189/Model.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2189/Model.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH2189/Model.cs 2010-05-29 19:25:32 UTC (rev 4985)
@@ -0,0 +1,31 @@
+using Iesi.Collections.Generic;
+using System;
+
+namespace NHibernate.Test.NHSpecificTest.NH2189
+{
+ public class Policy
+ {
+ public Policy()
+ {
+ Tasks = new HashedSet<Task>();
+ }
+
+ public virtual Guid Id { get; protected set; }
+ public virtual int PolicyNumber { get; set; }
+ public virtual ISet<Task> Tasks { get; protected set; }
+ }
+
+ public class Task
+ {
+ public virtual Guid Id { get; protected set; }
+ public virtual string TaskName { get; set; }
+ public virtual Policy Policy { get; set; }
+ public virtual TeamMember TeamMember { get; set; }
+ }
+
+ public class TeamMember
+ {
+ public virtual Guid Id { get; protected set; }
+ public virtual string Name { get; set; }
+ }
+}
Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-05-27 14:18:07 UTC (rev 4984)
+++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2010-05-29 19:25:32 UTC (rev 4985)
@@ -437,6 +437,8 @@
<Compile Include="NHSpecificTest\CriteriaQueryOnComponentCollection\Employee.cs" />
<Compile Include="NHSpecificTest\CriteriaQueryOnComponentCollection\Fixture.cs" />
<Compile Include="NHSpecificTest\CriteriaQueryOnComponentCollection\Money.cs" />
+ <Compile Include="NHSpecificTest\NH2189\Fixture.cs" />
+ <Compile Include="NHSpecificTest\NH2189\Model.cs" />
<Compile Include="NHSpecificTest\ElementsEnums\AbstractIntEnumsBagFixture.cs" />
<Compile Include="NHSpecificTest\ElementsEnums\IntEnumsBagNoNameFixture.cs" />
<Compile Include="NHSpecificTest\ElementsEnums\IntEnumsBagPartialNameFixture.cs" />
@@ -2139,6 +2141,7 @@
<EmbeddedResource Include="DriverTest\SqlServerCeEntity.hbm.xml" />
<EmbeddedResource Include="CollectionTest\NullableValueTypeElementMapFixture.hbm.xml" />
<Content Include="DynamicEntity\package.html" />
+ <EmbeddedResource Include="NHSpecificTest\NH2189\Mappings.hbm.xml" />
<EmbeddedResource Include="NHSpecificTest\NH2201\Mappings.hbm.xml" />
<EmbeddedResource Include="NHSpecificTest\NH2192\Mappings.hbm.xml" />
<EmbeddedResource Include="ListIndex\SimpleOneToMany.hbm.xml" />
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ste...@us...> - 2010-06-21 14:57:39
|
Revision: 4993
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4993&view=rev
Author: steverstrong
Date: 2010-06-21 14:57:32 +0000 (Mon, 21 Jun 2010)
Log Message:
-----------
Improved support for projections, can now do things like
from u in users
select SomeCSharpFunction(u.username)
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.Test/Linq/ProjectionsTests.cs
Modified: trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs 2010-06-19 15:00:19 UTC (rev 4992)
+++ trunk/nhibernate/src/NHibernate/Linq/Functions/FunctionRegistry.cs 2010-06-21 14:57:32 UTC (rev 4993)
@@ -28,56 +28,85 @@
{
public class FunctionRegistry
{
- public static FunctionRegistry Initialise()
- {
- var registry = new FunctionRegistry();
+ public static readonly FunctionRegistry Instance = new FunctionRegistry();
- // TODO - could use reflection here
- registry.Register(new QueryableGenerator());
- registry.Register(new StringGenerator());
- registry.Register(new DateTimeGenerator());
- registry.Register(new ICollectionGenerator());
-
- return registry;
- }
-
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()
+ {
+ // TODO - could use reflection here
+ Register(new QueryableGenerator());
+ Register(new StringGenerator());
+ Register(new DateTimeGenerator());
+ Register(new ICollectionGenerator());
+ }
+
public IHqlGeneratorForMethod GetMethodGenerator(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 (_registeredMethods.TryGetValue(method, out methodGenerator))
+ 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;
+
+ foreach (var typeGenerator in _typeGenerators.Where(typeGenerator => typeGenerator.SupportsMethod(method)))
{
- return methodGenerator;
+ methodGenerator = typeGenerator.GetMethodGenerator(method);
+ return true;
}
+ return false;
+ }
- // No method generator registered. Look to see if it's a standard LinqExtensionMethod
- var attr = method.GetCustomAttributes(typeof (LinqExtensionMethodAttribute), false);
+ private bool GetStandardLinqExtensionMethodGenerator(MethodInfo method, out IHqlGeneratorForMethod methodGenerator)
+ {
+ methodGenerator = null;
+
+ var attr = method.GetCustomAttributes(typeof(LinqExtensionMethodAttribute), false);
+
if (attr.Length == 1)
{
// It is
- // TODO - cache this? Is it worth it?
- return new HqlGeneratorForExtensionMethod((LinqExtensionMethodAttribute) attr[0], method);
+ methodGenerator = new HqlGeneratorForExtensionMethod((LinqExtensionMethodAttribute)attr[0], method);
+ return true;
}
+ return false;
+ }
- // Not that either. Let's query each type generator to see if it can handle it
- foreach (var typeGenerator in _typeGenerators)
+ private bool GetRegisteredMethodGenerator(MethodInfo method, out IHqlGeneratorForMethod methodGenerator)
+ {
+ if (_registeredMethods.TryGetValue(method, out methodGenerator))
{
- if (typeGenerator.SupportsMethod(method))
- {
- return typeGenerator.GetMethodGenerator(method);
- }
+ return true;
}
-
- throw new NotSupportedException(method.ToString());
+ return false;
}
public IHqlGeneratorForProperty GetPropertyGenerator(MemberInfo member)
Modified: trunk/nhibernate/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs 2010-06-19 15:00:19 UTC (rev 4992)
+++ trunk/nhibernate/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs 2010-06-21 14:57:32 UTC (rev 4993)
@@ -12,7 +12,7 @@
{
private readonly HqlTreeBuilder _hqlTreeBuilder;
private readonly VisitorParameters _parameters;
- static private readonly FunctionRegistry FunctionRegistry = FunctionRegistry.Initialise();
+ static private readonly FunctionRegistry FunctionRegistry = FunctionRegistry.Instance;
public static HqlTreeNode Visit(Expression expression, VisitorParameters parameters)
{
Modified: trunk/nhibernate/src/NHibernate/Linq/Visitors/SelectClauseVisitor.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Linq/Visitors/SelectClauseVisitor.cs 2010-06-19 15:00:19 UTC (rev 4992)
+++ trunk/nhibernate/src/NHibernate/Linq/Visitors/SelectClauseVisitor.cs 2010-06-21 14:57:32 UTC (rev 4993)
@@ -3,12 +3,15 @@
using System.Linq.Expressions;
using NHibernate.Hql.Ast;
using NHibernate.Linq.Expressions;
+using NHibernate.Linq.Functions;
using Remotion.Data.Linq.Parsing;
namespace NHibernate.Linq.Visitors
{
public class SelectClauseVisitor : ExpressionTreeVisitor
{
+ static private readonly FunctionRegistry FunctionRegistry = FunctionRegistry.Instance;
+
private HashSet<Expression> _hqlNodes;
private readonly ParameterExpression _inputParameter;
private readonly VisitorParameters _parameters;
@@ -69,7 +72,24 @@
private static bool CanBeEvaluatedInHqlSelectStatement(Expression expression)
{
- return (expression.NodeType != ExpressionType.MemberInit) && (expression.NodeType != ExpressionType.New);
+ if ((expression.NodeType == ExpressionType.MemberInit) || (expression.NodeType == ExpressionType.New) || (expression.NodeType == ExpressionType.Constant))
+ {
+ // Hql can't do New or Member Init
+ return false;
+ }
+
+ if (expression.NodeType == ExpressionType.Call)
+ {
+ // Depends if it's in the function registry
+ IHqlGeneratorForMethod methodGenerator;
+ if (!FunctionRegistry.TryGetMethodGenerator(((MethodCallExpression) expression).Method, out methodGenerator))
+ {
+ return false;
+ }
+ }
+
+ // Assume all is good
+ return true;
}
private static bool CanBeEvaluatedInHqlStatementShortcut(Expression expression)
Modified: trunk/nhibernate/src/NHibernate.Test/Linq/ProjectionsTests.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Linq/ProjectionsTests.cs 2010-06-19 15:00:19 UTC (rev 4992)
+++ trunk/nhibernate/src/NHibernate.Test/Linq/ProjectionsTests.cs 2010-06-21 14:57:32 UTC (rev 4993)
@@ -147,5 +147,55 @@
Assert.AreEqual(3, query.Intersect(new[] { "ayende", "rahien", "nhibernate" })
.ToList().Count);
}
+
+ [Test]
+ public void CanCallLocalMethodsInSelect()
+ {
+ var query = (
+ from user in db.Users
+ orderby user.Id
+ select FormatName(user.Name, user.LastLoginDate)
+ ).ToList();
+
+ Assert.AreEqual(3, query.Count);
+ Assert.IsTrue(query[0].StartsWith("User ayende logged in at"));
+ Assert.IsTrue(query[1].StartsWith("User rahien logged in at"));
+ Assert.IsTrue(query[2].StartsWith("User nhibernate logged in at"));
+ }
+
+ [Test]
+ public void CanCallLocalMethodsInAnonymousTypeInSelect()
+ {
+ var query = (
+ from user in db.Users
+ orderby user.Id
+ select new {Title = FormatName(user.Name, user.LastLoginDate)}
+ ).ToList();
+
+ Assert.AreEqual(3, query.Count);
+ Assert.IsTrue(query[0].Title.StartsWith("User ayende logged in at"));
+ Assert.IsTrue(query[1].Title.StartsWith("User rahien logged in at"));
+ Assert.IsTrue(query[2].Title.StartsWith("User nhibernate logged in at"));
+ }
+
+ [Test]
+ public void CanPerformStringOperationsInSelect()
+ {
+ var query = (
+ from user in db.Users
+ orderby user.Id
+ select new { Title = "User " + user.Name + " logged in at " + user.LastLoginDate }
+ ).ToList();
+
+ Assert.AreEqual(3, query.Count);
+ Assert.IsTrue(query[0].Title.StartsWith("User ayende logged in at"));
+ Assert.IsTrue(query[1].Title.StartsWith("User rahien logged in at"));
+ Assert.IsTrue(query[2].Title.StartsWith("User nhibernate logged in at"));
+ }
+
+ private string FormatName(string name, DateTime? lastLoginDate)
+ {
+ return string.Format("User {0} logged in at {1}", name, lastLoginDate);
+ }
}
}
\ 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-06-27 13:30:23
|
Revision: 4994
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4994&view=rev
Author: fabiomaulo
Date: 2010-06-27 13:30:16 +0000 (Sun, 27 Jun 2010)
Log Message:
-----------
Starting fix NH-2230
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/ClassBinder.cs
trunk/nhibernate/src/NHibernate/Mapping/Component.cs
trunk/nhibernate/src/NHibernate/Tuple/Component/PocoComponentTuplizer.cs
Modified: trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/ClassBinder.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/ClassBinder.cs 2010-06-21 14:57:32 UTC (rev 4993)
+++ trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/ClassBinder.cs 2010-06-27 13:30:16 UTC (rev 4994)
@@ -305,7 +305,11 @@
// Parent
if (componentMapping.Parent != null && !string.IsNullOrEmpty(componentMapping.Parent.name))
{
- model.ParentProperty = componentMapping.Parent.name;
+ model.ParentProperty = new Property
+ {
+ Name = componentMapping.Parent.name,
+ PropertyAccessorName = mappings.DefaultAccess
+ };
}
new PropertiesBinder(Mappings, model, className, path, isNullable, Mappings.Dialect).Bind(
Modified: trunk/nhibernate/src/NHibernate/Mapping/Component.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Mapping/Component.cs 2010-06-21 14:57:32 UTC (rev 4993)
+++ trunk/nhibernate/src/NHibernate/Mapping/Component.cs 2010-06-27 13:30:16 UTC (rev 4994)
@@ -16,7 +16,7 @@
private readonly List<Property> properties = new List<Property>();
private System.Type componentClass;
private bool embedded;
- private string parentProperty;
+ private Property parentProperty;
private PersistentClass owner;
private bool dynamic;
private bool isKey;
@@ -165,7 +165,7 @@
}
/// <summary></summary>
- public string ParentProperty
+ public Property ParentProperty
{
get { return parentProperty; }
set { parentProperty = value; }
Modified: trunk/nhibernate/src/NHibernate/Tuple/Component/PocoComponentTuplizer.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Tuple/Component/PocoComponentTuplizer.cs 2010-06-21 14:57:32 UTC (rev 4993)
+++ trunk/nhibernate/src/NHibernate/Tuple/Component/PocoComponentTuplizer.cs 2010-06-27 13:30:16 UTC (rev 4994)
@@ -28,17 +28,16 @@
{
componentClass = component.ComponentClass;
- string parentPropertyName = component.ParentProperty;
- if (parentPropertyName == null)
+ var parentProperty = component.ParentProperty;
+ if (parentProperty == null)
{
parentSetter = null;
parentGetter = null;
}
else
{
- IPropertyAccessor pa = PropertyAccessorFactory.GetPropertyAccessor(null);
- parentSetter = pa.GetSetter(componentClass, parentPropertyName);
- parentGetter = pa.GetGetter(componentClass, parentPropertyName);
+ parentSetter = parentProperty.GetSetter(componentClass);
+ parentGetter = parentProperty.GetGetter(componentClass);
}
if (hasCustomAccessors || !Cfg.Environment.UseReflectionOptimizer)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ric...@us...> - 2010-06-28 10:32:24
|
Revision: 4995
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4995&view=rev
Author: ricbrown
Date: 2010-06-28 10:32:18 +0000 (Mon, 28 Jun 2010)
Log Message:
-----------
Updated to IQueryOver.SelectList (syntax was clashing with .Select in intellisense).
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs
trunk/nhibernate/src/NHibernate/IQueryOver.cs
trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs
trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/ProjectionsFixture.cs
Modified: trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs 2010-06-27 13:30:16 UTC (rev 4994)
+++ trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs 2010-06-28 10:32:18 UTC (rev 4995)
@@ -318,7 +318,7 @@
return this;
}
- public QueryOver<TRoot, TSubType> Select(Func<QueryOverProjectionBuilder<TSubType>, QueryOverProjectionBuilder<TSubType>> list)
+ public QueryOver<TRoot, TSubType> SelectList(Func<QueryOverProjectionBuilder<TSubType>, QueryOverProjectionBuilder<TSubType>> list)
{
criteria.SetProjection(list(new QueryOverProjectionBuilder<TSubType>()).ProjectionList);
return this;
@@ -681,8 +681,8 @@
IQueryOver<TRoot,TSubType> IQueryOver<TRoot,TSubType>.Select(params IProjection[] projections)
{ return Select(projections); }
- IQueryOver<TRoot, TSubType> IQueryOver<TRoot, TSubType>.Select(Func<QueryOverProjectionBuilder<TSubType>, QueryOverProjectionBuilder<TSubType>> list)
- { return Select(list); }
+ IQueryOver<TRoot, TSubType> IQueryOver<TRoot, TSubType>.SelectList(Func<QueryOverProjectionBuilder<TSubType>, QueryOverProjectionBuilder<TSubType>> list)
+ { return SelectList(list); }
IQueryOverOrderBuilder<TRoot,TSubType> IQueryOver<TRoot,TSubType>.OrderBy(Expression<Func<TSubType, object>> path)
{ return new IQueryOverOrderBuilder<TRoot,TSubType>(this, path); }
Modified: trunk/nhibernate/src/NHibernate/IQueryOver.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/IQueryOver.cs 2010-06-27 13:30:16 UTC (rev 4994)
+++ trunk/nhibernate/src/NHibernate/IQueryOver.cs 2010-06-28 10:32:18 UTC (rev 4995)
@@ -246,7 +246,7 @@
/// <summary>
/// Create a list of projections using a projection builder
/// </summary>
- IQueryOver<TRoot, TSubType> Select(Func<QueryOverProjectionBuilder<TSubType>, QueryOverProjectionBuilder<TSubType>> list);
+ IQueryOver<TRoot, TSubType> SelectList(Func<QueryOverProjectionBuilder<TSubType>, QueryOverProjectionBuilder<TSubType>> list);
/// <summary>
/// Add order expressed as a lambda expression
Modified: trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs 2010-06-27 13:30:16 UTC (rev 4994)
+++ trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs 2010-06-28 10:32:18 UTC (rev 4995)
@@ -162,7 +162,7 @@
PersonSummary summary = null;
var actual =
s.QueryOver<Person>()
- .Select(list => list
+ .SelectList(list => list
.SelectGroup(p => p.Name).WithAlias(() => summary.Name)
.Select(Projections.RowCount()).WithAlias(() => summary.Count))
.OrderByAlias(() => summary.Name).Asc
@@ -263,7 +263,7 @@
QueryOver<Child> averageChildAge =
QueryOver.Of<Child>()
- .Select(p => p.SelectAvg(c => c.Age));
+ .SelectList(list => list.SelectAvg(c => c.Age));
QueryOver<Child> childCountQuery =
QueryOver.Of<Child>()
@@ -273,7 +273,7 @@
var nameAndChildCount =
s.QueryOver<Person>(() => personAlias)
.WithSubquery.Where(p => p.Age <= averageChildAge.As<int>())
- .Select(list => list
+ .SelectList(list => list
.Select(p => p.Name)
.SelectSubQuery(childCountQuery).WithAlias(() => childCountAlias))
.OrderByAlias(() => childCountAlias).Desc
Modified: trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/ProjectionsFixture.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/ProjectionsFixture.cs 2010-06-27 13:30:16 UTC (rev 4994)
+++ trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/ProjectionsFixture.cs 2010-06-28 10:32:18 UTC (rev 4995)
@@ -114,7 +114,7 @@
Person personAgeProjectionAlias = null;
var actual =
CreateTestQueryOver<Person>(() => personAlias)
- .Select(list => list
+ .SelectList(list => list
.SelectAvg(p => p.Age).WithAlias(() => personAgeProjectionAlias)
.Select(Projections.Avg("Age")) // allows private properties
.SelectAvg(() => personAlias.Age).WithAlias(() => personAlias.Age)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <jul...@us...> - 2010-07-03 14:46:30
|
Revision: 4997
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4997&view=rev
Author: julian-maughan
Date: 2010-07-03 14:46:23 +0000 (Sat, 03 Jul 2010)
Log Message:
-----------
Fixed badly named class: AdoNetWithDistrubtedTransactionFactory. Retained original naming for backwards compatibility, but marked as Obsolete.
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Cfg/SettingsFactory.cs
trunk/nhibernate/src/NHibernate/NHibernate.csproj
trunk/nhibernate/src/NHibernate/Transaction/AdoNetWithDistrubtedTransactionFactory.cs
trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1054/NH1054Fixture.cs
Added Paths:
-----------
trunk/nhibernate/src/NHibernate/Transaction/AdoNetWithDistributedTransactionFactory.cs
Modified: trunk/nhibernate/src/NHibernate/Cfg/SettingsFactory.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Cfg/SettingsFactory.cs 2010-06-28 12:11:26 UTC (rev 4996)
+++ trunk/nhibernate/src/NHibernate/Cfg/SettingsFactory.cs 2010-07-03 14:46:23 UTC (rev 4997)
@@ -352,7 +352,7 @@
private static ITransactionFactory CreateTransactionFactory(IDictionary<string, string> properties)
{
string className = PropertiesHelper.GetString(
- Environment.TransactionStrategy, properties, typeof(AdoNetWithDistrubtedTransactionFactory).FullName);
+ Environment.TransactionStrategy, properties, typeof(AdoNetWithDistributedTransactionFactory).FullName);
log.Info("Transaction factory: " + className);
try
Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj
===================================================================
--- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-06-28 12:11:26 UTC (rev 4996)
+++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-07-03 14:46:23 UTC (rev 4997)
@@ -349,6 +349,7 @@
<Compile Include="StaleObjectStateException.cs" />
<Compile Include="Tool\hbm2ddl\SchemaExport.cs" />
<Compile Include="TransactionException.cs" />
+ <Compile Include="Transaction\AdoNetWithDistributedTransactionFactory.cs" />
<Compile Include="Transaction\AdoTransaction.cs" />
<Compile Include="Transaction\ITransactionFactory.cs" />
<Compile Include="Transform\AliasToEntityMapResultTransformer.cs" />
Added: trunk/nhibernate/src/NHibernate/Transaction/AdoNetWithDistributedTransactionFactory.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Transaction/AdoNetWithDistributedTransactionFactory.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate/Transaction/AdoNetWithDistributedTransactionFactory.cs 2010-07-03 14:46:23 UTC (rev 4997)
@@ -0,0 +1,175 @@
+using System;
+using System.Collections;
+using System.Transactions;
+using log4net;
+using NHibernate.Engine;
+using NHibernate.Engine.Transaction;
+using NHibernate.Impl;
+
+namespace NHibernate.Transaction
+{
+ public class AdoNetWithDistributedTransactionFactory : ITransactionFactory
+ {
+ private static readonly ILog logger = LogManager.GetLogger(typeof (AbstractSessionImpl));
+
+ private readonly AdoNetTransactionFactory adoNetTransactionFactory = new AdoNetTransactionFactory();
+
+ public void Configure(IDictionary props)
+ {
+ }
+
+ public ITransaction CreateTransaction(ISessionImplementor session)
+ {
+ return new AdoTransaction(session);
+ }
+
+ public void EnlistInDistributedTransactionIfNeeded(ISessionImplementor session)
+ {
+ if (session.TransactionContext != null)
+ return;
+
+ if (System.Transactions.Transaction.Current == null)
+ return;
+
+ var transactionContext = new DistributedTransactionContext(session,
+ System.Transactions.Transaction.Current);
+ session.TransactionContext = transactionContext;
+ logger.DebugFormat("enlisted into DTC transaction: {0}",
+ transactionContext.AmbientTransation.IsolationLevel);
+ session.AfterTransactionBegin(null);
+ transactionContext.AmbientTransation.TransactionCompleted +=
+ delegate(object sender, TransactionEventArgs e)
+ {
+ using (new SessionIdLoggingContext(session.SessionId))
+ {
+ bool wasSuccessful = false;
+ try
+ {
+ wasSuccessful = e.Transaction.TransactionInformation.Status
+ == TransactionStatus.Committed;
+ }
+ catch (ObjectDisposedException ode)
+ {
+ logger.Warn("Completed transaction was disposed, assuming transaction rollback", ode);
+ }
+ session.AfterTransactionCompletion(wasSuccessful, null);
+ if (transactionContext.ShouldCloseSessionOnDistributedTransactionCompleted)
+ {
+ session.CloseSessionFromDistributedTransaction();
+ }
+ session.TransactionContext = null;
+ }
+ };
+ transactionContext.AmbientTransation.EnlistVolatile(transactionContext,
+ EnlistmentOptions.EnlistDuringPrepareRequired);
+ }
+
+ public bool IsInDistributedActiveTransaction(ISessionImplementor session)
+ {
+ var distributedTransactionContext = ((DistributedTransactionContext) session.TransactionContext);
+ return distributedTransactionContext != null &&
+ distributedTransactionContext.IsInActiveTransaction;
+ }
+
+ public void ExecuteWorkInIsolation(ISessionImplementor session, IIsolatedWork work, bool transacted)
+ {
+ using(var tx = new TransactionScope(TransactionScopeOption.Suppress))
+ {
+ // instead of duplicating the logic, we suppress the DTC transaction and create
+ // our own transaction instead
+ adoNetTransactionFactory.ExecuteWorkInIsolation(session, work, transacted);
+ tx.Complete();
+ }
+ }
+
+ public class DistributedTransactionContext : ITransactionContext, IEnlistmentNotification
+ {
+ public System.Transactions.Transaction AmbientTransation { get; set; }
+ public bool ShouldCloseSessionOnDistributedTransactionCompleted { get; set; }
+ private readonly ISessionImplementor sessionImplementor;
+ public bool IsInActiveTransaction;
+
+ public DistributedTransactionContext(ISessionImplementor sessionImplementor, System.Transactions.Transaction transaction)
+ {
+ this.sessionImplementor = sessionImplementor;
+ AmbientTransation = transaction.Clone();
+ IsInActiveTransaction = true;
+ }
+
+ #region IEnlistmentNotification Members
+
+ void IEnlistmentNotification.Prepare(PreparingEnlistment preparingEnlistment)
+ {
+ using (new SessionIdLoggingContext(sessionImplementor.SessionId))
+ {
+ try
+ {
+ using (var tx = new TransactionScope(AmbientTransation))
+ {
+ sessionImplementor.BeforeTransactionCompletion(null);
+ if (sessionImplementor.FlushMode != FlushMode.Never && sessionImplementor.ConnectionManager.IsConnected)
+ {
+ using (sessionImplementor.ConnectionManager.FlushingFromDtcTransaction)
+ {
+ logger.Debug(string.Format("[session-id={0}] Flushing from Dtc Transaction", sessionImplementor.SessionId));
+ sessionImplementor.Flush();
+ }
+ }
+ logger.Debug("prepared for DTC transaction");
+
+ tx.Complete();
+ }
+ preparingEnlistment.Prepared();
+ }
+ catch (Exception exception)
+ {
+ logger.Error("DTC transaction prepre phase failed", exception);
+ preparingEnlistment.ForceRollback(exception);
+ }
+ }
+ }
+
+ void IEnlistmentNotification.Commit(Enlistment enlistment)
+ {
+ using (new SessionIdLoggingContext(sessionImplementor.SessionId))
+ {
+ logger.Debug("committing DTC transaction");
+ // we have nothing to do here, since it is the actual
+ // DB connection that will commit the transaction
+ enlistment.Done();
+ IsInActiveTransaction = false;
+ }
+ }
+
+ void IEnlistmentNotification.Rollback(Enlistment enlistment)
+ {
+ using (new SessionIdLoggingContext(sessionImplementor.SessionId))
+ {
+ sessionImplementor.AfterTransactionCompletion(false, null);
+ logger.Debug("rolled back DTC transaction");
+ enlistment.Done();
+ IsInActiveTransaction = false;
+ }
+ }
+
+ void IEnlistmentNotification.InDoubt(Enlistment enlistment)
+ {
+ using (new SessionIdLoggingContext(sessionImplementor.SessionId))
+ {
+ sessionImplementor.AfterTransactionCompletion(false, null);
+ logger.Debug("DTC transaction is in doubt");
+ enlistment.Done();
+ IsInActiveTransaction = false;
+ }
+ }
+
+ #endregion
+
+ public void Dispose()
+ {
+ if (AmbientTransation != null)
+ AmbientTransation.Dispose();
+ }
+ }
+ }
+}
\ No newline at end of file
Modified: trunk/nhibernate/src/NHibernate/Transaction/AdoNetWithDistrubtedTransactionFactory.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Transaction/AdoNetWithDistrubtedTransactionFactory.cs 2010-06-28 12:11:26 UTC (rev 4996)
+++ trunk/nhibernate/src/NHibernate/Transaction/AdoNetWithDistrubtedTransactionFactory.cs 2010-07-03 14:46:23 UTC (rev 4997)
@@ -1,175 +1,9 @@
using System;
-using System.Collections;
-using System.Transactions;
-using log4net;
-using NHibernate.Engine;
-using NHibernate.Engine.Transaction;
-using NHibernate.Impl;
namespace NHibernate.Transaction
{
- public class AdoNetWithDistrubtedTransactionFactory : ITransactionFactory
+ [Obsolete("Use renamed class: AdoNetWithDistributedTransactionFactory")]
+ public class AdoNetWithDistrubtedTransactionFactory : AdoNetWithDistributedTransactionFactory
{
- private static readonly ILog logger = LogManager.GetLogger(typeof (AbstractSessionImpl));
- private readonly AdoNetTransactionFactory adoNetTransactionFactory = new AdoNetTransactionFactory();
-
-
- public void Configure(IDictionary props)
- {
-
- }
-
- public ITransaction CreateTransaction(ISessionImplementor session)
- {
- return new AdoTransaction(session);
- }
-
- public void EnlistInDistributedTransactionIfNeeded(ISessionImplementor session)
- {
- if (session.TransactionContext != null)
- return;
- if (System.Transactions.Transaction.Current == null)
- return;
- var transactionContext = new DistributedTransactionContext(session,
- System.Transactions.Transaction.Current);
- session.TransactionContext = transactionContext;
- logger.DebugFormat("enlisted into DTC transaction: {0}",
- transactionContext.AmbientTransation.IsolationLevel);
- session.AfterTransactionBegin(null);
- transactionContext.AmbientTransation.TransactionCompleted +=
- delegate(object sender, TransactionEventArgs e)
- {
- using (new SessionIdLoggingContext(session.SessionId))
- {
- bool wasSuccessful = false;
- try
- {
- wasSuccessful = e.Transaction.TransactionInformation.Status
- == TransactionStatus.Committed;
- }
- catch (ObjectDisposedException ode)
- {
- logger.Warn("Completed transaction was disposed, assuming transaction rollback", ode);
- }
- session.AfterTransactionCompletion(wasSuccessful, null);
- if (transactionContext.ShouldCloseSessionOnDistributedTransactionCompleted)
- {
- session.CloseSessionFromDistributedTransaction();
- }
- session.TransactionContext = null;
- }
- };
- transactionContext.AmbientTransation.EnlistVolatile(transactionContext,
- EnlistmentOptions.EnlistDuringPrepareRequired);
-
- }
-
- public bool IsInDistributedActiveTransaction(ISessionImplementor session)
- {
- var distributedTransactionContext = ((DistributedTransactionContext) session.TransactionContext);
- return distributedTransactionContext != null &&
- distributedTransactionContext.IsInActiveTransaction;
- }
-
- public void ExecuteWorkInIsolation(ISessionImplementor session, IIsolatedWork work, bool transacted)
- {
- using(var tx = new TransactionScope(TransactionScopeOption.Suppress))
- {
- // instead of duplicating the logic, we suppress the DTC transaction and create
- // our own transaction instead
- adoNetTransactionFactory.ExecuteWorkInIsolation(session, work, transacted);
- tx.Complete();
- }
- }
-
- public class DistributedTransactionContext : ITransactionContext, IEnlistmentNotification
- {
- public System.Transactions.Transaction AmbientTransation { get; set; }
- public bool ShouldCloseSessionOnDistributedTransactionCompleted { get; set; }
- private readonly ISessionImplementor sessionImplementor;
- public bool IsInActiveTransaction;
-
- public DistributedTransactionContext(ISessionImplementor sessionImplementor, System.Transactions.Transaction transaction)
- {
- this.sessionImplementor = sessionImplementor;
- AmbientTransation = transaction.Clone();
- IsInActiveTransaction = true;
- }
-
- #region IEnlistmentNotification Members
-
- void IEnlistmentNotification.Prepare(PreparingEnlistment preparingEnlistment)
- {
- using (new SessionIdLoggingContext(sessionImplementor.SessionId))
- {
- try
- {
- using (var tx = new TransactionScope(AmbientTransation))
- {
- sessionImplementor.BeforeTransactionCompletion(null);
- if (sessionImplementor.FlushMode != FlushMode.Never && sessionImplementor.ConnectionManager.IsConnected)
- {
- using (sessionImplementor.ConnectionManager.FlushingFromDtcTransaction)
- {
- logger.Debug(string.Format("[session-id={0}] Flushing from Dtc Transaction", sessionImplementor.SessionId));
- sessionImplementor.Flush();
- }
- }
- logger.Debug("prepared for DTC transaction");
-
- tx.Complete();
- }
- preparingEnlistment.Prepared();
- }
- catch (Exception exception)
- {
- logger.Error("DTC transaction prepre phase failed", exception);
- preparingEnlistment.ForceRollback(exception);
- }
- }
- }
-
- void IEnlistmentNotification.Commit(Enlistment enlistment)
- {
- using (new SessionIdLoggingContext(sessionImplementor.SessionId))
- {
- logger.Debug("committing DTC transaction");
- // we have nothing to do here, since it is the actual
- // DB connection that will commit the transaction
- enlistment.Done();
- IsInActiveTransaction = false;
- }
- }
-
- void IEnlistmentNotification.Rollback(Enlistment enlistment)
- {
- using (new SessionIdLoggingContext(sessionImplementor.SessionId))
- {
- sessionImplementor.AfterTransactionCompletion(false, null);
- logger.Debug("rolled back DTC transaction");
- enlistment.Done();
- IsInActiveTransaction = false;
- }
- }
-
- void IEnlistmentNotification.InDoubt(Enlistment enlistment)
- {
- using (new SessionIdLoggingContext(sessionImplementor.SessionId))
- {
- sessionImplementor.AfterTransactionCompletion(false, null);
- logger.Debug("DTC transaction is in doubt");
- enlistment.Done();
- IsInActiveTransaction = false;
- }
- }
-
- #endregion
-
- public void Dispose()
- {
- if (AmbientTransation != null)
- AmbientTransation.Dispose();
- }
- }
}
}
\ No newline at end of file
Modified: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1054/NH1054Fixture.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1054/NH1054Fixture.cs 2010-06-28 12:11:26 UTC (rev 4996)
+++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1054/NH1054Fixture.cs 2010-07-03 14:46:23 UTC (rev 4997)
@@ -27,7 +27,7 @@
Configuration configuration = new Configuration();
ISessionFactoryImplementor sessionFactory = (ISessionFactoryImplementor)configuration.BuildSessionFactory();
- Assert.IsInstanceOfType(typeof(NHibernate.Transaction.AdoNetWithDistrubtedTransactionFactory),
+ Assert.IsInstanceOfType(typeof(NHibernate.Transaction.AdoNetWithDistributedTransactionFactory),
sessionFactory.Settings.TransactionFactory);
}
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ste...@us...> - 2010-07-06 09:15:06
|
Revision: 4998
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4998&view=rev
Author: steverstrong
Date: 2010-07-06 09:14:59 +0000 (Tue, 06 Jul 2010)
Log Message:
-----------
Fixed semantics of .Single
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessFirst.cs
trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessFirstOrSingleBase.cs
trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessSingle.cs
trunk/nhibernate/src/NHibernate/NHibernate.csproj
trunk/nhibernate/src/NHibernate.Test/Linq/WhereTests.cs
Modified: trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessFirst.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessFirst.cs 2010-07-03 14:46:23 UTC (rev 4997)
+++ trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessFirst.cs 2010-07-06 09:14:59 UTC (rev 4998)
@@ -11,7 +11,9 @@
? ReflectionHelper.GetMethod(() => Queryable.FirstOrDefault<object>(null))
: ReflectionHelper.GetMethod(() => Queryable.First<object>(null));
- ProcessFirstOrSingle(firstMethod, queryModelVisitor, tree);
+ AddClientSideEval(firstMethod, queryModelVisitor, tree);
+
+ tree.AddAdditionalCriteria((q, p) => q.SetMaxResults(1));
}
}
}
\ No newline at end of file
Modified: trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessFirstOrSingleBase.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessFirstOrSingleBase.cs 2010-07-03 14:46:23 UTC (rev 4997)
+++ trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessFirstOrSingleBase.cs 2010-07-06 09:14:59 UTC (rev 4998)
@@ -5,7 +5,7 @@
{
public class ProcessFirstOrSingleBase
{
- protected static void ProcessFirstOrSingle(MethodInfo target, QueryModelVisitor queryModelVisitor, IntermediateHqlTree tree)
+ protected static void AddClientSideEval(MethodInfo target, QueryModelVisitor queryModelVisitor, IntermediateHqlTree tree)
{
target = target.MakeGenericMethod(queryModelVisitor.CurrentEvaluationType.DataType);
@@ -17,7 +17,6 @@
parameter),
parameter);
- tree.AddAdditionalCriteria((q, p) => q.SetMaxResults(1));
tree.AddPostExecuteTransformer(lambda);
}
}
Modified: trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessSingle.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessSingle.cs 2010-07-03 14:46:23 UTC (rev 4997)
+++ trunk/nhibernate/src/NHibernate/Linq/Visitors/ResultOperatorProcessors/ProcessSingle.cs 2010-07-06 09:14:59 UTC (rev 4998)
@@ -11,7 +11,7 @@
? ReflectionHelper.GetMethod(() => Queryable.SingleOrDefault<object>(null))
: ReflectionHelper.GetMethod(() => Queryable.Single<object>(null));
- ProcessFirstOrSingle(firstMethod, queryModelVisitor, tree);
+ AddClientSideEval(firstMethod, queryModelVisitor, tree);
}
}
}
\ No newline at end of file
Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj
===================================================================
--- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-07-03 14:46:23 UTC (rev 4997)
+++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-07-06 09:14:59 UTC (rev 4998)
@@ -1,4 +1,5 @@
-<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
@@ -43,35 +44,35 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
- <Reference Include="Antlr3.Runtime, Version=3.1.0.39271, Culture=neutral, PublicKeyToken=3a9cab8f8d22bfb7, processorArchitecture=MSIL">
+ <Reference Include="System" />
+ <Reference Include="System.Core">
+ <RequiredTargetFramework>3.5</RequiredTargetFramework>
+ </Reference>
+ <Reference Include="System.Data" />
+ <Reference Include="System.Data.OracleClient" />
+ <Reference Include="System.ServiceModel">
+ <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>
<HintPath>..\..\lib\net\3.5\Antlr3.Runtime.dll</HintPath>
</Reference>
- <Reference Include="Iesi.Collections, Version=1.0.1.0, Culture=neutral, PublicKeyToken=aa95f207798dfdb4, processorArchitecture=MSIL">
+ <Reference Include="Iesi.Collections, Version=1.0.1.0, Culture=neutral, PublicKeyToken=aa95f207798dfdb4">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\net\3.5\Iesi.Collections.dll</HintPath>
</Reference>
- <Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL">
+ <Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\net\3.5\log4net.dll</HintPath>
</Reference>
- <Reference Include="Remotion.Data.Linq, Version=1.13.9.2, Culture=neutral, PublicKeyToken=cab60358ab4081ea, processorArchitecture=MSIL">
+ <Reference Include="Remotion.Data.Linq, Version=1.13.41.2, Culture=neutral, PublicKeyToken=cab60358ab4081ea">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\net\3.5\Remotion.Data.Linq.dll</HintPath>
</Reference>
- <Reference Include="System" />
- <Reference Include="System.configuration" />
- <Reference Include="System.Core">
- <RequiredTargetFramework>3.5</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.Data" />
- <Reference Include="System.Data.OracleClient" />
- <Reference Include="System.ServiceModel">
- <RequiredTargetFramework>3.0</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.Transactions" />
- <Reference Include="System.Web" />
- <Reference Include="System.Xml" />
+ <Reference Include="System.Configuration" />
</ItemGroup>
<ItemGroup>
<Compile Include="ADOException.cs" />
Modified: trunk/nhibernate/src/NHibernate.Test/Linq/WhereTests.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Linq/WhereTests.cs 2010-07-03 14:46:23 UTC (rev 4997)
+++ trunk/nhibernate/src/NHibernate.Test/Linq/WhereTests.cs 2010-07-06 09:14:59 UTC (rev 4998)
@@ -82,6 +82,14 @@
select user).Single();
}
+ [Test]
+ [ExpectedException(typeof(InvalidOperationException))]
+ public void SingleElementWithQueryThatReturnsMultipleResults()
+ {
+ var query = (from user in db.Users
+ select user).Single();
+ }
+
[Test]
public void SingleOrDefaultElementWithQueryThatReturnsNoResults()
{
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ste...@us...> - 2010-07-06 19:37:12
|
Revision: 4999
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4999&view=rev
Author: steverstrong
Date: 2010-07-06 19:37:06 +0000 (Tue, 06 Jul 2010)
Log Message:
-----------
Fix for JIRA NH-2225
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeBuilder.cs
trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeNode.cs
trunk/nhibernate/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs
trunk/nhibernate/src/NHibernate.Test/DbScripts/MsSql2008DialectLinqReadonlyCreateScript.sql
trunk/nhibernate/src/NHibernate.Test/Linq/Entities/User.cs
trunk/nhibernate/src/NHibernate.Test/Linq/Mappings/User.hbm.xml
trunk/nhibernate/src/NHibernate.Test/Linq/WhereTests.cs
Modified: trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeBuilder.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeBuilder.cs 2010-07-06 09:14:59 UTC (rev 4998)
+++ trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeBuilder.cs 2010-07-06 19:37:06 UTC (rev 4999)
@@ -410,5 +410,15 @@
{
return new HqlClass(_factory);
}
+
+ public HqlBitwiseAnd BitwiseAnd(HqlExpression lhs, HqlExpression rhs)
+ {
+ return new HqlBitwiseAnd(_factory, lhs, rhs);
+ }
+
+ public HqlBitwiseOr BitwiseOr(HqlExpression lhs, HqlExpression rhs)
+ {
+ return new HqlBitwiseOr(_factory, lhs, rhs);
+ }
}
}
\ No newline at end of file
Modified: trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeNode.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeNode.cs 2010-07-06 09:14:59 UTC (rev 4998)
+++ trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeNode.cs 2010-07-06 19:37:06 UTC (rev 4999)
@@ -705,6 +705,22 @@
}
}
+ public class HqlBitwiseOr : HqlExpression
+ {
+ public HqlBitwiseOr(IASTFactory factory, HqlExpression lhs, HqlExpression rhs)
+ : base(HqlSqlWalker.BAND, "band", factory, lhs, rhs)
+ {
+ }
+ }
+
+ public class HqlBitwiseAnd : HqlExpression
+ {
+ public HqlBitwiseAnd(IASTFactory factory, HqlExpression lhs, HqlExpression rhs)
+ : base(HqlSqlWalker.BOR, "bor", factory, lhs, rhs)
+ {
+ }
+ }
+
public class HqlLeft : HqlTreeNode
{
public HqlLeft(IASTFactory factory)
Modified: trunk/nhibernate/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs 2010-07-06 09:14:59 UTC (rev 4998)
+++ trunk/nhibernate/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionTreeVisitor.cs 2010-07-06 19:37:06 UTC (rev 4999)
@@ -290,10 +290,14 @@
return _hqlTreeBuilder.Inequality(lhs, rhs);
case ExpressionType.And:
+ return _hqlTreeBuilder.BitwiseAnd(lhs, rhs);
+
case ExpressionType.AndAlso:
return _hqlTreeBuilder.BooleanAnd(lhs.AsBooleanExpression(), rhs.AsBooleanExpression());
case ExpressionType.Or:
+ return _hqlTreeBuilder.BitwiseOr(lhs, rhs);
+
case ExpressionType.OrElse:
return _hqlTreeBuilder.BooleanOr(lhs.AsBooleanExpression(), rhs.AsBooleanExpression());
Modified: trunk/nhibernate/src/NHibernate.Test/DbScripts/MsSql2008DialectLinqReadonlyCreateScript.sql
===================================================================
(Binary files differ)
Modified: trunk/nhibernate/src/NHibernate.Test/Linq/Entities/User.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Linq/Entities/User.cs 2010-07-06 09:14:59 UTC (rev 4998)
+++ trunk/nhibernate/src/NHibernate.Test/Linq/Entities/User.cs 2010-07-06 19:37:06 UTC (rev 4999)
@@ -4,6 +4,15 @@
namespace NHibernate.Test.Linq.Entities
{
+ [Flags]
+ public enum FeatureSet
+ {
+ HasThis = 1,
+ HasThat = 2,
+ HasMore = 4,
+ HasAll = 8
+ }
+
public interface IUser
{
int Id { get; set; }
@@ -12,6 +21,7 @@
DateTime RegisteredAt { get; set; }
DateTime? LastLoginDate { get; set; }
UserComponent Component { get; set; }
+ FeatureSet Features { get; set; }
Role Role { get; set; }
EnumStoredAsString Enum1 { get; set; }
EnumStoredAsInt32 Enum2 { get; set; }
@@ -33,6 +43,8 @@
public virtual Role Role { get; set; }
+ public virtual FeatureSet Features { get; set; }
+
public virtual EnumStoredAsString Enum1 { get; set; }
public virtual EnumStoredAsInt32 Enum2 { get; set; }
Modified: trunk/nhibernate/src/NHibernate.Test/Linq/Mappings/User.hbm.xml
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Linq/Mappings/User.hbm.xml 2010-07-06 09:14:59 UTC (rev 4998)
+++ trunk/nhibernate/src/NHibernate.Test/Linq/Mappings/User.hbm.xml 2010-07-06 19:37:06 UTC (rev 4999)
@@ -18,6 +18,8 @@
<property name="Enum2" not-null="true" />
+ <property name="Features" not-null="true" />
+
<many-to-one name="Role" class="Role">
<column name="RoleId" />
</many-to-one>
Modified: trunk/nhibernate/src/NHibernate.Test/Linq/WhereTests.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Linq/WhereTests.cs 2010-07-06 09:14:59 UTC (rev 4998)
+++ trunk/nhibernate/src/NHibernate.Test/Linq/WhereTests.cs 2010-07-06 19:37:06 UTC (rev 4999)
@@ -412,5 +412,16 @@
Assert.AreEqual(2, query.Count);
}
+
+ [Test]
+ public void BitwiseQuery()
+ {
+ var featureSet = FeatureSet.HasMore;
+ var query = (from o in session.Query<User>()
+ where (o.Features & featureSet) == featureSet
+ select o).ToList();
+
+ Assert.IsNotNull(query);
+ }
}
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ste...@us...> - 2010-07-07 08:39:31
|
Revision: 5001
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5001&view=rev
Author: steverstrong
Date: 2010-07-07 08:39:24 +0000 (Wed, 07 Jul 2010)
Log Message:
-----------
Added more bitwise tests and fixed silly bug in tree builder
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeNode.cs
trunk/nhibernate/src/NHibernate.Test/DbScripts/MsSql2008DialectLinqReadonlyCreateScript.sql
trunk/nhibernate/src/NHibernate.Test/Linq/WhereTests.cs
Modified: trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeNode.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeNode.cs 2010-07-06 20:05:52 UTC (rev 5000)
+++ trunk/nhibernate/src/NHibernate/Hql/Ast/HqlTreeNode.cs 2010-07-07 08:39:24 UTC (rev 5001)
@@ -708,7 +708,7 @@
public class HqlBitwiseOr : HqlExpression
{
public HqlBitwiseOr(IASTFactory factory, HqlExpression lhs, HqlExpression rhs)
- : base(HqlSqlWalker.BAND, "band", factory, lhs, rhs)
+ : base(HqlSqlWalker.BOR, "bor", factory, lhs, rhs)
{
}
}
@@ -716,7 +716,7 @@
public class HqlBitwiseAnd : HqlExpression
{
public HqlBitwiseAnd(IASTFactory factory, HqlExpression lhs, HqlExpression rhs)
- : base(HqlSqlWalker.BOR, "bor", factory, lhs, rhs)
+ : base(HqlSqlWalker.BAND, "band", factory, lhs, rhs)
{
}
}
Modified: trunk/nhibernate/src/NHibernate.Test/DbScripts/MsSql2008DialectLinqReadonlyCreateScript.sql
===================================================================
(Binary files differ)
Modified: trunk/nhibernate/src/NHibernate.Test/Linq/WhereTests.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Linq/WhereTests.cs 2010-07-06 20:05:52 UTC (rev 5000)
+++ trunk/nhibernate/src/NHibernate.Test/Linq/WhereTests.cs 2010-07-07 08:39:24 UTC (rev 5001)
@@ -423,5 +423,28 @@
Assert.IsNotNull(query);
}
+
+ [Test]
+ public void BitwiseQuery2()
+ {
+ var featureSet = FeatureSet.HasAll;
+ var query = (from o in session.Query<User>()
+ where (o.Features & featureSet) == featureSet
+ select o).ToList();
+
+ Assert.AreEqual(1, query.Count);
+ }
+
+ [Test]
+ public void BitwiseQuery3()
+ {
+ var featureSet = FeatureSet.HasThat;
+ var query = (from o in session.Query<User>()
+ where ((o.Features | featureSet) & featureSet) == featureSet
+ select o).ToList();
+
+ Assert.AreEqual(3, query.Count);
+ }
+
}
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ric...@us...> - 2010-07-08 20:48:45
|
Revision: 5002
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5002&view=rev
Author: ricbrown
Date: 2010-07-08 20:48:39 +0000 (Thu, 08 Jul 2010)
Log Message:
-----------
Fix NH-2235 (Corrected type syntax for .SelectList on QueryOver)
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs
trunk/nhibernate/src/NHibernate/IQueryOver.cs
trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs
Modified: trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs 2010-07-07 08:39:24 UTC (rev 5001)
+++ trunk/nhibernate/src/NHibernate/Criterion/QueryOver.cs 2010-07-08 20:48:39 UTC (rev 5002)
@@ -318,9 +318,9 @@
return this;
}
- public QueryOver<TRoot, TSubType> SelectList(Func<QueryOverProjectionBuilder<TSubType>, QueryOverProjectionBuilder<TSubType>> list)
+ public QueryOver<TRoot, TSubType> SelectList(Func<QueryOverProjectionBuilder<TRoot>, QueryOverProjectionBuilder<TRoot>> list)
{
- criteria.SetProjection(list(new QueryOverProjectionBuilder<TSubType>()).ProjectionList);
+ criteria.SetProjection(list(new QueryOverProjectionBuilder<TRoot>()).ProjectionList);
return this;
}
@@ -681,7 +681,7 @@
IQueryOver<TRoot,TSubType> IQueryOver<TRoot,TSubType>.Select(params IProjection[] projections)
{ return Select(projections); }
- IQueryOver<TRoot, TSubType> IQueryOver<TRoot, TSubType>.SelectList(Func<QueryOverProjectionBuilder<TSubType>, QueryOverProjectionBuilder<TSubType>> list)
+ IQueryOver<TRoot, TSubType> IQueryOver<TRoot, TSubType>.SelectList(Func<QueryOverProjectionBuilder<TRoot>, QueryOverProjectionBuilder<TRoot>> list)
{ return SelectList(list); }
IQueryOverOrderBuilder<TRoot,TSubType> IQueryOver<TRoot,TSubType>.OrderBy(Expression<Func<TSubType, object>> path)
Modified: trunk/nhibernate/src/NHibernate/IQueryOver.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/IQueryOver.cs 2010-07-07 08:39:24 UTC (rev 5001)
+++ trunk/nhibernate/src/NHibernate/IQueryOver.cs 2010-07-08 20:48:39 UTC (rev 5002)
@@ -246,7 +246,7 @@
/// <summary>
/// Create a list of projections using a projection builder
/// </summary>
- IQueryOver<TRoot, TSubType> SelectList(Func<QueryOverProjectionBuilder<TSubType>, QueryOverProjectionBuilder<TSubType>> list);
+ IQueryOver<TRoot, TSubType> SelectList(Func<QueryOverProjectionBuilder<TRoot>, QueryOverProjectionBuilder<TRoot>> list);
/// <summary>
/// Add order expressed as a lambda expression
Modified: trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs 2010-07-07 08:39:24 UTC (rev 5001)
+++ trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/IntegrationFixture.cs 2010-07-08 20:48:39 UTC (rev 5002)
@@ -238,6 +238,56 @@
}
[Test]
+ public void SubCriteriaProjections()
+ {
+ using (ISession s = OpenSession())
+ using (ITransaction t = s.BeginTransaction())
+ {
+ s.Save(new Person() { Name = "Name 1", Age = 33 }
+ .AddChild(new Child() { Nickname = "Name 1.1", Age = 3}));
+
+ t.Commit();
+ }
+
+ using (ISession s = OpenSession())
+ {
+ var simpleProjection =
+ s.QueryOver<Child>()
+ .JoinQueryOver(c => c.Parent)
+ .Where(p => p.Name == "Name 1" && p.Age == 33)
+ .Select(c => c.Nickname, c => c.Age)
+ .List<object[]>()
+ .Select(props => new
+ {
+ Name = (string)props[0],
+ Age = (int)props[1],
+ });
+
+ Assert.That(simpleProjection.Count(), Is.EqualTo(1));
+ Assert.That(simpleProjection.First().Name, Is.EqualTo("Name 1.1"));
+ Assert.That(simpleProjection.First().Age, Is.EqualTo(3));
+
+ var listProjection =
+ s.QueryOver<Child>()
+ .JoinQueryOver(c => c.Parent)
+ .Where(p => p.Name == "Name 1" && p.Age == 33)
+ .SelectList(list => list
+ .Select(c => c.Nickname)
+ .Select(c => c.Age))
+ .List<object[]>()
+ .Select(props => new
+ {
+ Name = (string)props[0],
+ Age = (int)props[1],
+ });
+
+ Assert.That(listProjection.Count(), Is.EqualTo(1));
+ Assert.That(listProjection.First().Name, Is.EqualTo("Name 1.1"));
+ Assert.That(listProjection.First().Age, Is.EqualTo(3));
+ }
+ }
+
+ [Test]
public void SubQuery()
{
using (ISession s = OpenSession())
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ric...@us...> - 2010-07-08 22:14:00
|
Revision: 5003
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=5003&view=rev
Author: ricbrown
Date: 2010-07-08 22:13:54 +0000 (Thu, 08 Jul 2010)
Log Message:
-----------
Added extension methods for QueryOver builders to allow single-line statements on builders e.g., query.OrderBy(p => p.Name).Asc();
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/Criterion/Lambda/QueryOverFetchBuilder.cs
trunk/nhibernate/src/NHibernate/NHibernate.csproj
trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/QueryOverFixture.cs
Added Paths:
-----------
trunk/nhibernate/src/NHibernate/Criterion/QueryOverBuilderExtensions.cs
Modified: trunk/nhibernate/src/NHibernate/Criterion/Lambda/QueryOverFetchBuilder.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Criterion/Lambda/QueryOverFetchBuilder.cs 2010-07-08 20:48:39 UTC (rev 5002)
+++ trunk/nhibernate/src/NHibernate/Criterion/Lambda/QueryOverFetchBuilder.cs 2010-07-08 22:13:54 UTC (rev 5003)
@@ -6,7 +6,7 @@
using NHibernate.Impl;
using NHibernate.SqlCommand;
-namespace NHibernate.Criterion
+namespace NHibernate.Criterion.Lambda
{
public class QueryOverFetchBuilder<TRoot,TSubType> : QueryOverFetchBuilderBase<QueryOver<TRoot,TSubType>, TRoot, TSubType>
Added: trunk/nhibernate/src/NHibernate/Criterion/QueryOverBuilderExtensions.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Criterion/QueryOverBuilderExtensions.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate/Criterion/QueryOverBuilderExtensions.cs 2010-07-08 22:13:54 UTC (rev 5003)
@@ -0,0 +1,168 @@
+using System;
+using System.Linq.Expressions;
+
+using NHibernate.Impl;
+
+namespace NHibernate.Criterion
+{
+ public static class QueryOverBuilderExtensions
+ {
+ // Fetch builder
+ public static QueryOver<TRoot, TSubType> Default<TRoot, TSubType>(this Lambda.QueryOverFetchBuilder<TRoot, TSubType> builder)
+ {
+ return builder.Default;
+ }
+
+ public static QueryOver<TRoot, TSubType> Eager<TRoot, TSubType>(this Lambda.QueryOverFetchBuilder<TRoot, TSubType> builder)
+ {
+ return builder.Eager;
+ }
+
+ public static QueryOver<TRoot, TSubType> Lazy<TRoot, TSubType>(this Lambda.QueryOverFetchBuilder<TRoot, TSubType> builder)
+ {
+ return builder.Lazy;
+ }
+
+ public static IQueryOver<TRoot, TSubType> Default<TRoot, TSubType>(this Lambda.IQueryOverFetchBuilder<TRoot, TSubType> builder)
+ {
+ return builder.Default;
+ }
+
+ public static IQueryOver<TRoot, TSubType> Eager<TRoot, TSubType>(this Lambda.IQueryOverFetchBuilder<TRoot, TSubType> builder)
+ {
+ return builder.Eager;
+ }
+
+ public static IQueryOver<TRoot, TSubType> Lazy<TRoot, TSubType>(this Lambda.IQueryOverFetchBuilder<TRoot, TSubType> builder)
+ {
+ return builder.Lazy;
+ }
+
+
+ // Lock builder
+ public static QueryOver<TRoot, TSubType> Force<TRoot, TSubType>(this Lambda.QueryOverLockBuilder<TRoot, TSubType> builder)
+ {
+ return builder.Force;
+ }
+
+ public static QueryOver<TRoot, TSubType> None<TRoot, TSubType>(this Lambda.QueryOverLockBuilder<TRoot, TSubType> builder)
+ {
+ return builder.None;
+ }
+
+ public static QueryOver<TRoot, TSubType> Read<TRoot, TSubType>(this Lambda.QueryOverLockBuilder<TRoot, TSubType> builder)
+ {
+ return builder.Read;
+ }
+
+ public static QueryOver<TRoot, TSubType> Upgrade<TRoot, TSubType>(this Lambda.QueryOverLockBuilder<TRoot, TSubType> builder)
+ {
+ return builder.Upgrade;
+ }
+
+ public static QueryOver<TRoot, TSubType> UpgradeNoWait<TRoot, TSubType>(this Lambda.QueryOverLockBuilder<TRoot, TSubType> builder)
+ {
+ return builder.UpgradeNoWait;
+ }
+
+ public static QueryOver<TRoot, TSubType> Write<TRoot, TSubType>(this Lambda.QueryOverLockBuilder<TRoot, TSubType> builder)
+ {
+ return builder.Write;
+ }
+
+ public static IQueryOver<TRoot, TSubType> Force<TRoot, TSubType>(this Lambda.IQueryOverLockBuilder<TRoot, TSubType> builder)
+ {
+ return builder.Force;
+ }
+
+ public static IQueryOver<TRoot, TSubType> None<TRoot, TSubType>(this Lambda.IQueryOverLockBuilder<TRoot, TSubType> builder)
+ {
+ return builder.None;
+ }
+
+ public static IQueryOver<TRoot, TSubType> Read<TRoot, TSubType>(this Lambda.IQueryOverLockBuilder<TRoot, TSubType> builder)
+ {
+ return builder.Read;
+ }
+
+ public static IQueryOver<TRoot, TSubType> Upgrade<TRoot, TSubType>(this Lambda.IQueryOverLockBuilder<TRoot, TSubType> builder)
+ {
+ return builder.Upgrade;
+ }
+
+ public static IQueryOver<TRoot, TSubType> UpgradeNoWait<TRoot, TSubType>(this Lambda.IQueryOverLockBuilder<TRoot, TSubType> builder)
+ {
+ return builder.UpgradeNoWait;
+ }
+
+ public static IQueryOver<TRoot, TSubType> Write<TRoot, TSubType>(this Lambda.IQueryOverLockBuilder<TRoot, TSubType> builder)
+ {
+ return builder.Write;
+ }
+
+
+ // Order builder
+ public static QueryOver<TRoot, TSubType> Asc<TRoot, TSubType>(this Lambda.QueryOverOrderBuilder<TRoot, TSubType> builder)
+ {
+ return builder.Asc;
+ }
+
+ public static QueryOver<TRoot, TSubType> Desc<TRoot, TSubType>(this Lambda.QueryOverOrderBuilder<TRoot, TSubType> builder)
+ {
+ return builder.Desc;
+ }
+
+ public static IQueryOver<TRoot, TSubType> Asc<TRoot, TSubType>(this Lambda.IQueryOverOrderBuilder<TRoot, TSubType> builder)
+ {
+ return builder.Asc;
+ }
+
+ public static IQueryOver<TRoot, TSubType> Desc<TRoot, TSubType>(this Lambda.IQueryOverOrderBuilder<TRoot, TSubType> builder)
+ {
+ return builder.Desc;
+ }
+
+
+ // Restriction builder
+ public static QueryOver<TRoot, TSubType> IsEmpty<TRoot, TSubType>(this Lambda.QueryOverRestrictionBuilder<TRoot, TSubType> builder)
+ {
+ return builder.IsEmpty;
+ }
+
+ public static QueryOver<TRoot, TSubType> IsNotEmpty<TRoot, TSubType>(this Lambda.QueryOverRestrictionBuilder<TRoot, TSubType> builder)
+ {
+ return builder.IsNotEmpty;
+ }
+
+ public static QueryOver<TRoot, TSubType> IsNotNull<TRoot, TSubType>(this Lambda.QueryOverRestrictionBuilder<TRoot, TSubType> builder)
+ {
+ return builder.IsNotNull;
+ }
+
+ public static QueryOver<TRoot, TSubType> IsNull<TRoot, TSubType>(this Lambda.QueryOverRestrictionBuilder<TRoot, TSubType> builder)
+ {
+ return builder.IsNull;
+ }
+
+ public static IQueryOver<TRoot, TSubType> IsEmpty<TRoot, TSubType>(this Lambda.IQueryOverRestrictionBuilder<TRoot, TSubType> builder)
+ {
+ return builder.IsEmpty;
+ }
+
+ public static IQueryOver<TRoot, TSubType> IsNotEmpty<TRoot, TSubType>(this Lambda.IQueryOverRestrictionBuilder<TRoot, TSubType> builder)
+ {
+ return builder.IsNotEmpty;
+ }
+
+ public static IQueryOver<TRoot, TSubType> IsNotNull<TRoot, TSubType>(this Lambda.IQueryOverRestrictionBuilder<TRoot, TSubType> builder)
+ {
+ return builder.IsNotNull;
+ }
+
+ public static IQueryOver<TRoot, TSubType> IsNull<TRoot, TSubType>(this Lambda.IQueryOverRestrictionBuilder<TRoot, TSubType> builder)
+ {
+ return builder.IsNull;
+ }
+
+ }
+}
Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj
===================================================================
--- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-07-08 20:48:39 UTC (rev 5002)
+++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2010-07-08 22:13:54 UTC (rev 5003)
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="utf-8"?>
+<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@@ -578,6 +578,7 @@
<Compile Include="Criterion\Lambda\QueryOverSubqueryBuilder.cs" />
<Compile Include="Criterion\Lambda\QueryOverSubqueryPropertyBuilder.cs" />
<Compile Include="Criterion\NullSubqueryExpression.cs" />
+ <Compile Include="Criterion\QueryOverBuilderExtensions.cs" />
<Compile Include="Criterion\ProjectionsExtensions.cs" />
<Compile Include="Dialect\MsSql2008Dialect.cs" />
<Compile Include="Dialect\InformixDialect0940.cs" />
Modified: trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/QueryOverFixture.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/QueryOverFixture.cs 2010-07-08 20:48:39 UTC (rev 5002)
+++ trunk/nhibernate/src/NHibernate.Test/Criteria/Lambda/QueryOverFixture.cs 2010-07-08 22:13:54 UTC (rev 5003)
@@ -373,6 +373,24 @@
}
[Test]
+ public void AllowSingleCallSyntax()
+ {
+ ICriteria expected = CreateTestCriteria(typeof(Person));
+ expected.Add(Restrictions.IsNotEmpty("Children"));
+ expected.AddOrder(Order.Asc("Name"));
+ expected.SetFetchMode("PersonList", FetchMode.Eager);
+ expected.SetLockMode(LockMode.UpgradeNoWait);
+
+ IQueryOver<Person,Person> actual = CreateTestQueryOver<Person>();
+ actual.WhereRestrictionOn(p => p.Children).IsNotEmpty();
+ actual.OrderBy(p => p.Name).Asc();
+ actual.Fetch(p => p.PersonList).Eager();
+ actual.Lock().UpgradeNoWait();
+
+ AssertCriteriaAreEqual(expected, actual);
+ }
+
+ [Test]
public void Project()
{
ICriteria expected =
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|