Group by using linq with NHibernate 3.0 - nhibernate

As far as I know group by has only been added in NHibernate 3.0, but even when using version 3, I can't get group by to work.
I have tried to do the following query:
Session.Query().GroupBy(gbftr
=> gbftr.Tag).OrderByDescending(obftr => obftr.Count()).Take(count).ToList();
But I receive the following error:
Antlr.Runtime.NoViableAltException'. [. OrderByDescending (. GroupBy (NHibernate.Linq.NhQueryable `1 [Forum.Core.ForumTagRelation] Quote ((gbftr,) => (gbftr.Tag)),), Quote ((obftr,) => (. Count (obftr,))),)]
Does anyone have an idea if I might be mistaken, and group by isn't implemented in NHibernate 3.0, or who knows what I might be doing wrong?

GroupBy does work, but it's the combination with other operators that is causing trouble.
For example, this works:
session.Query<Foo>().GroupBy(x => x.Tag).Select(x => x.Count()).ToList();
But if you try to use Skip/Take to page, it fails.
In short: some constructs are not supported yet; you can use HQL for those. I suggest you open an issue at http://jira.nhforge.org

Related

How to order by an associated model in Rails 4, and specify a direction?

In Rails 3.2.17, i could have the following:
scope :sorted, -> { joins(:other).order({:other => :code}, :code) }
Which produces the following SQL:
SELECT [things].* FROM [things] INNER JOIN [others] ON [others].[id] = [things].[other_id] ORDER BY [others].[code] ASC, [things].[code] ASC
The same code in Rails 4.0.4 gives the following error, however:
Direction should be :asc or :desc
But, I cannot figure out a way to keep the ordering and specify the direct. The scope below, for example, gives the same error:
scope :sorted, -> { joins(:other).order({:other => {:code => :asc}}, :code => :asc) }
EDIT: To be clear, I want to use the Hash style syntax and do not want to write raw SQL strings
This looks like a bug in Rails 4.0+ (something about order accepting nested hashes)
I found a Github issue for you explaining the issue
They recommend using source:, but that's only for an association declaration. If you find the answer, I will gladly remove this, but hopefully it will help you!

NHibernate QueryOver order by first non-null value (coalescing)

What I'm trying to come up is something that's expressed like this:
var result = Session.QueryOver<Foo>().OrderBy(f => f.UpdatedAt ?? f.CreatedAt);
Sure enough, this doesn't work. Rough equivalent of this in T-SQL is
... order by coalesce(f.UpdatedAt, f.CreatedAt)
What's the kosher way to do "coalescing" in NHibernate QueryOver?
.OrderBy(Projections.SqlFunction("coalesce",
NHibernateUtil.DateTime,
Projections.Property<Foo>(x => x.UpdatedAt),
Projections.Property<Foo>(x => x.CreatedAt)))
Diego's answer is the way I came up with, but it seemed to be too verbose to me, so I asked a question, and got an excellent answer. Basically, you can register your own extensions and then just do
.OrderBy(f => f.UpdatedAt.IfNull(f.CreatedAt));
where IfNull is your new extension. I've even submitted an improvement proposal to NH Jira, but got no response yet.

NHibernate fetchmany Object does not match the destination type

I am trying to solve the n+1 issue, where I retrieve all my forumthreads and posts. I tried to do it like the following:
return Session.Query<ForumThread>().Where(x => x.IsActive)
.OrderByDescending(x => x.LastForumPost)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.FetchMany(x=>x.ForumPosts)
.Cacheable();
But this gives an error:
Object does not match the destination type.
If I remove .Cacheable() it works. Is there any known error with fetching and using query caching?
I believe this was fixed in 3.1 (see https://nhibernate.jira.com/browse/NH-2502), although other bug numbers suggest otherwise.
If you're not using 3.1, try upgrading.

nHibernate 3.0 queries

Working through the summer of nHibernate tutorials have gotten to the section on queries. Seems there have been changes since that series was made. So I went to the online docs for nHB 3.0 but code such as:
IList cats = session.CreateCriteria(typeof(Cat))
.Add(Expression.Like("Name", "Fritz%"))
.Add(Expression.Between("Weight", minWeight, maxWeight))
.List();
Generates the error "The name 'Expression' does not exist in the current context"
Code like:
return session.CreateCriteria(typeof(DataTransfer.Customer))
.Add(new NHibernate.Criterion.LikeExpression("Firstname", firstname))
.Add(new NHibernate.Criterion.LikeExpression("Lastname", lastname))
.List<Customer>();
Works but it seems that it is missing a number of query methods like GtExpression.
Are the online docs up to date, and if so, why can't I use Expression...
If the online docs aren't up to date then where do I get a description of the Criterion interface?
Thanks
You forgot to add using NHibernate.Criterion;.
Anyway, the Expression class is deprecated. Use Restrictions instead.
Weird thing. I still use Expression.* static methods and these are still work. Are you sure you use the latest version of NH3.0? I use Alpha 2 version.
If you need to make it work urgently, let's try the QueryOver<> feature:
return session.QueryOver<DataTransfer.Customer>()
.WhereRestrictionOn(u => u.Name).IsLike("Fritz%")
.AndRestrictionOn(u => u.Weight).IsBetween(minWeight).And(maxWeight)
.List();
It works well for simple queries

Rails 3 ActiveRecord query using both SQL IN and SQL OR operators

I'm writing a Rails 3 ActiveRecord query using the "where" syntax, that uses both the SQL IN and the SQL OR operator and can't figure out how to use both of them together.
This code works (in my User model):
Question.where(:user_id => self.friends.ids)
#note: self.friends.ids returns an array of integers
but this code
Question.where(:user_id => self.friends.ids OR :target => self.friends.usernames)
returns this error
syntax error, unexpected tCONSTANT, expecting ')'
...user_id => self.friends.ids OR :target => self.friends.usern...
Any idea how to write this in Rails, or just what the raw SQL query should be?
You don't need to use raw SQL, just provide the pattern as a string, and add named parameters:
Question.where('user_id in (:ids) or target in (:usernames)',
:ids => self.friends.ids, :usernames => self.friends.usernames)
Or positional parameters:
Question.where('user_id in (?) or target in (?)',
self.friends.ids, self.friends.usernames)
You can also use the excellent Squeel gem, as #erroric pointed out on his answer (the my { } block is only needed if you need access to self or instance variables):
Question.where { user_id.in(my { self.friends.ids }) |
target.in(my { self.friends.usernames }) }
Though Rails 3 AR doesn't give you an or operator you can still achieve the same result without going all the way down to SQL and use Arel directly. By that I mean that you can do it like this:
t = Question.arel_table
Question.where(t[:user_id].in(self.friends.ids).or(t[:username].in(self.friends.usernames)))
Some might say it ain't so pretty, some might say it's pretty simply because it includes no SQL. Anyhow it most certainly could be prettier and there's a gem for it too: MetaWhere
For more info see this railscast: http://railscasts.com/episodes/215-advanced-queries-in-rails-3
and MetaWhere site: http://metautonomo.us/projects/metawhere/
UPDATE: Later Ryan Bates has made another railscast about metawhere and metasearch: http://railscasts.com/episodes/251-metawhere-metasearch
Later though Metawhere (and search) have become more or less legacy gems. I.e. they don't even work with Rails 3.1. The author felt they (Metawhere and search) needed drastic rewrite. So much that he actually went for a new gem all together. The successor of Metawhere is Squeel. Read more about the authors announcement here:
http://erniemiller.org/2011/08/31/rails-3-1-and-the-future-of-metawhere-and-metasearch/
and check out the project home page:
http://erniemiller.org/projects/squeel/
"Metasearch 2.0" is called Ransack and you can read something about it from here:
http://erniemiller.org/2011/04/01/ransack-the-library-formerly-known-as-metasearch-2-0/
Alternatively, you could use Squeel. To my eyes, it is simpler. You can accomplish both the IN (>>) and OR (|) operations using the following syntax:
Question.where{(:user_id >> my{friends.id}) | (:target >> my{friends.usernames})}
I generally wrap my conditions in (...) to ensure the appropriate order of operation - both the INs happen before the OR.
The my{...} block executes methods from the self context as defined before the Squeel call - in this case Question. Inside of the Squeel block, self refers to a Squeel object and not the Question object (see the Squeel Readme for more). You get around this by using the my{...} wrapper to restore the original context.
raw SQL
SELECT *
FROM table
WHERE user_id in (LIST OF friend.ids) OR target in (LIST OF friends.usernames)
with each list comma separate. I don't know the Rails ActiveRecord stuff that well. For AND you would just put a comma between those two conditions, but idk about OR