Skip to content

Interceptors for SQL generation #19748

Open

Description

@BalassaMarton

Note: #28505 to allow interception of the LINQ expression tree has been split off from this and implemented in EF7.

Use cases

The current query generation pipeline is hard to extend without relying on implementation details.

Proposal

Enable intercepting the translation steps in QueryCompilationContext.CreateQueryExecutor.
API details are to be discussed here, I don't have a concrete proposal yet.

Activity

  1. roji commented on Jan 30, 2020

    @roji
    Member

    @BalassaMarton the query pipeline is already extensible in many different ways, thanks to the DI infrastructure of EF Core:

    • Providers (and plugins) can easily add method and member translators
    • Providers (and even users) can provide their own implementation of IRelationalSqlTranslatingExpressionVisitorFactory to translate other types of expressions
    • Providers (and even users) can add query pipeline preprocessors (which run at the very beginning) and postprocessors (which run after translations). We do have plans to improve the API for inserting new preprocessing/postprocessing visitors for 5.0.

    Admittedly we currently lack documentation on how to do the above - we definitely plan on making all this more discoverable for 5.0 (see dotnet/EntityFramework.Docs#681 for example, as well as other issues).

    Are there any specific scenarios you have in mind, where you're unsure how to proceed? Is your interest more as a provider writer, or as an end user?

  2. BalassaMarton commented on Jan 31, 2020

    @BalassaMarton
    Author

    I'm only interested as a user, but I'll look deeper into the visitors and try to understand how it can be extended, thank you.

  3. ajcvickers commented on Feb 3, 2020

    @ajcvickers
    Contributor

    Note from team discussion: we need to document this (see dotnet/EntityFramework.Docs#951 and dotnet/EntityFramework.Docs#500) but following that we should look at adding sugar for common patterns to avoid the need to understand expression visitors for common custom translations.

  4. added this to the Backlog milestone on Feb 3, 2020
  5. smitpatel commented on May 7, 2020

    @smitpatel
    Contributor

    @BalassaMarton & @powermetal63 - Can you provide details of exactly what you want to change in expression tree for which you need extensibility? We can determine based on that what could be right hook for it and if it is missing, add it. Query pipeline is a complex system which has multiple parts end to end. As @roji mentioned above, there are hooks a long the way depending what kind of task need to be done.

  6. powermetal63 commented on May 7, 2020

    @powermetal63

    @smitpatel I would start with the ability to preprocess/transform the IQueryable.Expression before EF Core infrastructure. This will be very useful for lambda injection extensions like NeinLinq, LinqKit and similar which currently have to implement custom IQueryProvider and IQueryable just to do that. The end user is required to call a custom method like ToInjectable(), AsExpandanle(), which can easily be forgotten, and also custom query providers doesn't play well with EF Core queryable/async extensions.

    Also it will be useful if we want to add "fixes" to some things you are not willing to (or have no time, or will do it in future version we cannot afford waiting for etc.), like the one here #19930 (comment).

    I guess all this falls into bullet #3 - Easy way to add query pipeline preprocessors. By easy I mean to be able to do that without implementing custom options in order to add services etc. Something as easy to use as the current ReplaceService.

  7. smitpatel commented on May 7, 2020

    @smitpatel
    Contributor

    Something as easy to use as the current ReplaceService.

    That already works for everything you want to inject during compilation phase.

    Anything before pre-funcletization can be done outside of EF before passing expression into EF.

  8. powermetal63 commented on May 8, 2020

    @powermetal63

    @smitpatel But we don't want it do be done externally. I already gave you several examples. We don't want to ask the user to call custom methods like ToInjectable, AsExpandable, ConvertGroupJoins etc. in order get the functionality. Because we are extending/fixing EF/C# query limitations, and want these pure query expression transformations to be executed automatically for each EF query "compilation".

    So what we want is an easy way to plug something similar to your current QueryTranslationPreprocessor.Process - like GroupJoinConverter from #19930 (comment), or LinqKit Expand functionality. Or in other words, something similar to AddInterceptors, but for query preprocessors which then run before EF.

  9. smitpatel commented on May 8, 2020

    @smitpatel
    Contributor

    @powermetal63 - You can already replace QueryTranslationPreprocessor by using ReplaceService API on IQueryTranslationPreprocessorFactory service. Did you look at that functionality?

  10. powermetal63 commented on May 8, 2020

    @powermetal63

    @powermetal63 - You can already replace QueryTranslationPreprocessor by using ReplaceService API on IQueryTranslationPreprocessorFactory service. Did you look at that functionality?

    @smitpatel Sure I know it, but that's the problem - all I can do is to replace it. Let say I replace it and return custom QueryTranslationPreprocessor. Which one QueryTranslationPreprocessor should I inherit - QueryTranslationPreprocessor, RelationalQueryTranslationPreprocessor or something else - at that moment I have no idea which is the default (current) IQueryTranslationPreprocessorFactory, what dependencies it has and what type of QueryTranslationPreprocessor. it creates. And since EF relies on that query preprocessing, we can easily break it unintentionally.

    Shortly, IMHO this factory service approach is quite limited - I'm not sure why you created it and what it will be used for internally by EF, but it definitely is not something I (or 3rd party extensions creators) want to dial with. We don't need to replace something existing, we need something additive like recently added interceptors.


    P.S. Please don't get me wrong. I'm doing EF Core hacks/workarounds from the very beginning. Here we are discussing a good public way of extending EF Core. Cheers.

  11. smitpatel commented on May 8, 2020

    @smitpatel
    Contributor

    Here we are discussing a good public way of extending EF Core. Cheers.

    Infrastructure to extend EF already exists as asked by OP. It is personal preference to use it or not. That has no affect on this issue whatsoever.

  12. 28 remaining items

  13. removed this from the milestone on Jul 25, 2022
  14. ajcvickers commented on Jul 25, 2022

    @ajcvickers
    Contributor

    Note: #28505 to allow interception of the LINQ expression tree has been split off from this and implemented in EF7.

  15. changed the title [-]Interceptors for expression trees[/-] [+]Interceptors for SQL generation[/+] on Jul 25, 2022
  16. added this to the Backlog milestone on Jul 27, 2022
  17. sensslen commented on Sep 6, 2022

    @sensslen

    I am currently trying to use the ReplaceService solution in order to register additional functions when evaluating expressions. This seems to work fine when using a real microsoft wql connection. However in our unit tests we use an in memory database. Whenever I try to resolve e.g. QueryTranslationPreprocessorDependencies this fails. Is there some sample code on how this would work?

  18. MrZander commented on Mar 13, 2024

    @MrZander

    There is a lot of back-and-forth about the fact that this can be done, but not a whole lot of info on how to actually do it. Especially considering it is still undocumented.
    Can anyone shed some light on how I'm supposed to implement this?:

    If you are using SqlServer or Sqlite provider, then derive from RelationalQueryTranslationPreprocessor add your custom processor. Create a new implementation of IQueryTranslationPreprocessorFactory which during create method creates the new derived class you generated and use Replace service method to register your custom factory in EF Core provider and it works.

    I understand replacing the service with my own factory, but how do I actually derive from RelationalQueryTranslationPreprocessor?

    	public class CustomQueryTranslationFactory : IQueryTranslationPreprocessorFactory
    	{
    		public QueryTranslationPreprocessor Create(QueryCompilationContext queryCompilationContext)
    		{
    			return new MyCustomPreprocessor(queryCompilationContext);
    		}
    	}
    
    	public class MyCustomPreprocessor : RelationalQueryTranslationPreprocessor
    	{
    		public MyCustomPreprocessor(QueryCompilationContext queryCompilationContext)
    			//What the heck are the first two arguments to this constructor supposed to be?
    			: base(null, null, queryCompilationContext)
    		{
    		}
    
    		public override Expression Process(Expression query)
    		{
    			return base.Process(query);
    		}
    	}
    

    I could also be misunderstanding what this is for. We used IDbCommandTreeInterceptor extensively in EF6 and it was quite simple to transform the DbCommandTree before it was translated into SQL. Is this issue proposing this level of control or am I barking up the wrong tree?

  19. roji commented on Mar 13, 2024

    @roji
    Member

    @MrZander if your goal is to perform some transformation on the incoming LINQ expression tree - that's the tree that represents your LINQ query before it's translated to SQL, then we've added an interceptor for that in EF Core 7.0 (docs). I'm mentioning that since that's what preprocessing means in this context. So it should no longer be necessary to extend RelationalQueryTranslationPreprocessor.

    This issue is about intercepting at a much later point in query processing, after it has already been translated to SQL; so the interceptor here would accept an expression tree representing a (mostly) finalized representation of the SQL query, just before it gets serialized to a string.

  20. MrZander commented on Mar 14, 2024

    @MrZander

    My goal is the latter.
    Ideally, we would be able to intercept the SqlExpression as close to the end of the pipeline as possible.

    I see a few services I could potentially use, like IMemberTranslator or ISqlExpressionFactory, but it isn't clear to me which will get me the "final" representation of the SqlExpression.

    For some context, we are trying to swap out tables and add filtering at runtime in order to show entities at a certain point-in-time. The replacement tables are not part of the entity model, so I can't reference them in the LINQ query.

  21. roji commented on Mar 14, 2024

    @roji
    Member

    Yeah, at this point you best bet is to use a command interceptor to do this at the SQL string level. It's definitely not great - but that's the recommended thing at the moment.

    Otherwise, you would replace RelationalQueryTranslationPostprocessor (postprocessor, not preprocessor), and add an additional visitation step at the end that would go through the SQL tree and do its thing. This is not a trivial thing to do, but should be possible.

  22. removed their assignment
    on Aug 31, 2024
  23. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions