Ayende @ Rahien

Refunds available at head office

The REALLY long way to query with NHibernate

I am doing some work on NHibernate, mostly rediscovering how things works. It is quite amazing how those things work, to tell you the truth. A few days ago I had a conversation about the NH source and I made three rapid discoveries that reduce the complexity of a feature by three orders of magnitude.

The code that I am showing is how NHibernate manages its queries internally (well, one way of doing that). This is internal information, so not only you would never do that, but you canot even do that.

   1: using (var s = sessions.OpenSession())
   2: using (var tx = s.BeginTransaction())
   3: {
   4:     var sessionImplementor = ((ISessionImplementor)s);
   5:     var q = new QueryTranslator("query",
   6:                                 "query",
   7:                                 sessionImplementor.EnabledFilters,
   8:                                 sessionImplementor.Factory);
   9:  
  10:     var p = q.GetPersisterUsingImports("Animal");
  11:     var entityName = q.CreateNameFor(p.EntityName);
  12:     q.AddFromClass(entityName, p);
  13:  
  14:     q.SetAliasName("a", entityName);
  15:  
  16:     var currentName = q.Unalias("a.Id");
  17:     var pathParser = new PathExpressionParser();
  18:     pathParser.Start(q);
  19:     foreach (var token in new StringTokenizer(currentName, ".", true))
  20:     {
  21:         pathParser.Token(token, q);
  22:     }
  23:     pathParser.End(q);
  24:  
  25:     q.AddFromJoinOnly(pathParser.Name, pathParser.WhereJoin);
  26:  
  27:     q.AddNamedParameter("id");
  28:  
  29:     q.AppendWhereToken(new SqlString(pathParser.WhereColumns[0]));
  30:     q.AppendWhereToken(new SqlString("="));
  31:     q.AppendWhereToken(new SqlString(Parameter.Placeholder));
  32:  
  33:     q.RenderSqlAndPostInstansiate();
  34:     var fromDb = q.List(sessionImplementor, 
  35:         CreateQueryParameters(sessionImplementor, 
  36:             "id", 
  37:             new TypedValue(NHibernateUtil.Int32, 1, sessionImplementor.EntityMode)));
  38:  
  39:     var contains = s.Contains(fromDb[0]);
  40:     Assert.IsTrue(contains);
  41:  
  42:     tx.Commit();
  43: }

I just thought that this is an interesting piece of code.

Comments

Brian Chavez
01/17/2009 10:13 PM by
Brian Chavez

NHibernate for LIFE now and FOREVER! Long live NHIBERNATE!!!

Comments have been closed on this topic.