NHibernate - Is it possible to apply filters on UPDATE/DELETE? - nhibernate

I know that we can easily apply filters to query with additional where conditions with NHibernate, but is it possible to apply a filter when doing an update or delete?
If it is, how can I achieve that?

Yes it is possible, using HQL (Hibernate Query Language)
Here's an example of a batch update
IQuery updateQuery = this.Session.CreateQuery("update TransferItem set Status = :newStatus where Status = :oldStatus")
.SetParameter("oldStatus", DownloadStatus.Active)
.SetParameter("newStatus", DownloadStatus.Queued);
updateQuery.ExecuteUpdate();
NHibernate applies the configured mappings to create and run the following SQL:
update cms_TransferItem set Status=#p0 where Status=#p1
Here's an example of a batch delete
IQuery deleteQuery = this.Session.CreateQuery("delete TransferItem ti WHERE ti.Status = :statusToGo")
.SetParameter("statusToGo", DownloadStatus.Completed);
deleteQuery.ExecuteUpdate();
Which executes SQL like this:
delete from cms_TransferItem where Status=#p0
You might ask, if you have to work with a query language, why not just write raw SQL? When you use HQL you are working with the conceptual business objects that the rest of the .NET code is working with. The benefits of an ORM tool is that, for much of the code, the database tables and object-to-table mappings are abstracted away. With HQL you are continuing to interact with the object layer, rather than directly with the database tables.

Related

EF core 3.1 can not run complex raw sql query

The following query was working fine with EF core 2 but EF core 3 would throw error!
I even could add some include after this query in EF core 2 which I let go now.
query:
// just to have an Id
var id = Guid.NewGuid();
var resutl = Context.Parties.FromSqlInterpolated($#"WITH mainOffice AS
(SELECT * FROM Parties as o1 WHERE (Discriminator = N'Office')
AND (Id = '{id}')
UNION ALL SELECT o.* FROM Parties AS o INNER JOIN mainOffice AS m
ON m.Id = o.ParentOfficeId)
SELECT * FROM mainOffice as f").ToList();
The error it produces is as follows:
FromSqlRaw or FromSqlInterpolated was called with non-composable SQL
and with a query composing over it. Consider calling AsEnumerable
after the FromSqlRaw or FromSqlInterpolated method to perform the
composition on the client side.
Knowing the following information might help:
Table "Parties" is a table per hierarchy
I tried to run the query both from the root type DbSet and the type I am interested for
No success with nether FromSqlRaw nor FromSqlInterpolated
Adding 'AsEnumerable' did not help too
Did I forget any thing? What am I doing wrong?
What does 'non-composable SQL' mean? Does it mean EF core is trying to interpret query?
I don't have the answer, but I know the reason now.
The reason this error is being generated is similar to this issue:
FromSql method when used with stored procedure cannot be composed
In my case weather or not I use any method, because the table I am trying to query is containing some different type (Table per hierarchy), my query will always be warped inside a select query to limit discriminators. Even though I write the query from the root, the wrapper select query is generated with all possible discriminators.
So it means I can only run queries that can be placed as sub query. My query can not, store procedures can not ...
I found a workaround for this issue,
You can create a view in database and a query type in your model and then run your query against this view (note that the way you do that has been changed from ef 2 to 3 as it is explained here)
So in this way inheritance and discriminators are not problems any more and query can be run.
Maybe related?
https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/breaking-changes#linq-queries-are-no-longer-evaluated-on-the-client
Efcore 2 implicity performed linq to objects on parts of a query that it could not transform to sql. This functionality was removed in efcore 3.

For update simulation in oracle using NHiberante

Can any one tell me how to implement for update in oracle using NHibernate? Are there any pre defined clauses for this? If not please tell me how can I implement it.
Read this chapter.
Basically, you need to get your poco using ISession.Get(Of Poco)(id, LockMode.Upgrade).
As a result, that should issue a SELECT ... FROM Poco Where Id = ? FOR UPDATE.
You can also invoke using LockMode.UpgradeNoWait to get a equivalent FOR UPDATE NOWAIT SQL Statement

What is the easiest way to find the LINQ statement for a SQL statement

I am a SQL Server DBA for a company that sells an ASP.NET MVC3 application that uses LINQ and Entity Framework 4 for all database access. When I find an inefficient query in my SQL Server's plan cache that was generated by LINQ, I would like to be able to find that LINQ statement in the source code so that I can optimize it. What is the best way to find the LINQ that generated a given SQL statement?
For example, is there any way to put an entry in a config file or decorate the code somehow so that the class and method name or the LINQ statement itself are included as comments in the generated SQL?
The commercial tools ORM Profiler, Entity Framework Profiler or Hugati Query Profiler will both give you a stack trace for the methods which generated the SQL. That makes it fairly easy to find the LINQ in code, though it isn't displayed directly.
These tools also have the advantage that they make it easy to find inefficient queries amongst the many other SQL statements executed by the app.
Although it is not a free tool, this may provide the information you need:
http://efprof.com/
There is also a less expensive tool described here, which I have not used, but it looks very promising:
http://huagati.blogspot.com/2010/06/entity-framework-support-in-huagati.html
http://www.huagati.com/L2SProfiler/
I bet Entity Framework Profiler (http://efprof.com/) would help you out. The workflow is very different from what you asked for (which would be pretty cool BTW). It is a good tool, and is worth a look even if it's not your final solution.
Good luck!
If you have access to the ASP.NET code where the LINQ code is you can more or less know which query you are looking for, copy it into a freeware tool called LINQPad and run it directly there to get the generated SQL statements. http://www.linqpad.net/
You need first get the LINQ queries on your .net code, create a connection to your datasource, paste the Linq code in new queries and run them. You will get the SQL Query generated from the LINQ code.
For example:
from e in ETUSERs
where e.LoginName.Contains("a")
orderby e.LoginName
select e
SQL Results Tab:
-- Region Parameters
DECLARE #p0 VarChar(1000) = '%a%'
-- EndRegion
SELECT [t0].[UserID], [t0].[UsrFirstName], [t0].[UsrLastName], [t0].[LoginName], [t0].[Location], [t0].[Password], [t0].[UsrEmail], ...
FROM [ETUSER] AS [t0]
WHERE [t0].[LoginName] LIKE #p0
ORDER BY [t0].[LoginName]
This is probably not exactly what you are looking for, but it is worth knowing about this tool since it is very helpful to quickly test LINQ queries. There you can quickly edit and run to improve the code without recompiling the whole stuff.
I don't think you can modify the generated SQL easily but what you can do is to get the generated SQL before sending the query to the database.
So you can log every query in a separate textfile with timestamp and source code context information. But that means to modify each place in your source where LINQ queries are sent to the database. Maybe there is an extension point somewhere in the DataContext class for simplifying this.
Anyway here is the code to get the corresponding sql query for a LINQ query:
YourDataContext dc = new YourDataContext();
IQueryable<YourEntityClass> query =
from e in dc.YourEntities
where ...
select e;
string command = dc.GetCommand(query).CommandText;

NHibernate Lambda expressions - are they turned into SQL

I'm a bit of a NHibernate newbie and Im taking on some code written by another developer. I want to find out how NHibernate converts lambda based criteria into SQL.
I know in Linq to SQL using Lambda expressions on queries means that the whole thing is turned into an expression tree and then into SQL (where possible) by the Linq to SQL provider. This can be seen by doing DataContext.Log = Console.Out.
But what about an NHibernate criteria expression where Linq to NHibernate isnt being used?
The following namespaces are imported...
using NHibernate;
using NHibernate.Criterion;
using NHibernate.LambdaExtensions;
.. and the criteria code looks like this...
return Session.CreateCriteria<MyObjectType>()
.Add<MyObjectType>(x => x.Id == id)
.UniqueResult<MyObjectType>();
Will this be turned into an SQL statement e.g.
Select distinct * from table where id = [param]
... or will the whole dataset be pulled into memory giving a List and then have the lambda expressions applied against the objects. e.g.
return List<MyObject>.Where(x => x.id = id) [or something similar].
I', not sure if my importing NHibernate.LambdaExtensions provides a sort of translation into SQL.
It is turned to an HQL statement first (enable logging and look at the console for the statements) and then to an SQL and sent to the database.
It does not select the whole table to memory and filters there.

Hibernate and dry-running HQL queries statically

I'd like to "dry-run" Hibernate HQL queries. That is I'd like to know what actual SQL queries Hibernate will execute from given HQL query without actually executing the HQL query against real database.
I have access to hibernate mapping for tables, the HQL query string, the dialect for my database. I have also access to database if that is needed.
Now, how can I find out all the SQL queries Hibernate can generate from my HQL without actually executing the query against any database? Are there any tools for this?
Note, that many SQL queries can be generated from one HQL query and the set of generated SQL queries may differ based on the contents of database.
I am not asking how to log SQL queries while HQL query is executing.
Edit: I don't mind connecting to database to fetch some metadata, I just don't want to execute queries.
Edit: I also know what limits and offsets are applied to query. I also have the actual parameters that will be bind to query.
The short answer is "you can't". The long answer is below.
There are two approaches you can take:
A) Look into HQLQueryPlan class, particularly its getSqlStrings() method. It will not get you the exact SQL because further preprocessing is involved before query is actually executed (parameters are bound, limit / offset are applied, etc...) but it may be close enough to what you want.
The thing to keep in mind here is that you'll need an actual SessionFactory instance in order to construct HQLQueryPlan, which means you won't be able to do so without "connecting to any database". You can, however, use in-memory database (SqlLite and the likes) and have Hibernate auto-create necessary schema for it.
B) Start with ASTQueryTranslatorFactory and descend into AST / ANTLR madness. In theory you may be able to hack together a parser that would work without relying on metadata but I have a hardest time imagining what is it you're trying to do for this to be worth it. Perhaps you can clarify? There has to be a better approach.
Update: for an offline, dry-run of some HQL, using HQLQueryPlan directly is a good approach. If you want to intercept every query in the app, while it's running, and record the SQL, you'll have to use proxies and reflection as described below.
Take a look at this answer for Criteria Queries.
For HQL, it's the same concept - you have to cast to Hibernate implementation classes and/or access private members, so it's not a supported method, but it will work with a the 3.2-3.3 versions of Hibernate. Here is the code to access the query from HQL (query is the object returned by session.createQuery(hql_string):
Field f = AbstractQueryImpl.class.getDeclaredField("session");
f.setAccessible(true);
SessionImpl sessionImpl = (SessionImpl) f.get(query);
Method m = AbstractSessionImpl.class.getDeclaredMethod("getHQLQueryPlan", new Class[] { String.class, boolean.class });
m.setAccessible(true);
HQLQueryPlan plan = (HQLQueryPlan) m.invoke(sessionImpl, new Object[] { query.getQueryString(), Boolean.FALSE });
for (int i = 0; i < plan.getSqlStrings().length; ++i) {
sql += plan.getSqlStrings()[i];
}
I would wrap all of that in a try/catch so you can go on with the query if the logging doesn't work.
It's possible to proxy your session and then proxy your queries so that you can log the sql and the parameters of every query (hql, sql, criteria) before it runs, without the code that builds the query having to do anything (as long as the initial session is retrieved from code you control).