sqlkata / querybuilder

SQL query builder, written in c#, helps you build complex queries easily, supports SqlServer, MySql, PostgreSql, Oracle, Sqlite and Firebird
https://sqlkata.com
MIT License
3.13k stars 502 forks source link

Add support for OPTION hints on queries #206

Open andreminelli opened 5 years ago

andreminelli commented 5 years ago

I would like to add hints like OPTION (RECOMPILE). which comes on the end of queries.

https://blogs.msdn.microsoft.com/robinlester/2016/08/10/improving-query-performance-with-option-recompile-constant-folding-and-avoiding-parameter-sniffing-issues/

I couldn't find a way to do this. Are there any plans to support it? If not, any suggestion on how this could be modeled in the DSL (for a possible PR) ?

naergaga commented 5 years ago

I do it this way.

var sql = result.Sql;
sql += " OPTION (OPTIMIZE FOR UNKNOWN)";
var pars = result.NamedBindings;
return conn.Query<T>(sql, pars);
andreminelli commented 5 years ago

I do it this way.

var sql = result.Sql;
sql += " OPTION (OPTIMIZE FOR UNKNOWN)";
var pars = result.NamedBindings;
return conn.Query<T>(sql, pars);

Nice workaround, thanks!

But it would be good having a supported way of doing this...

jjamid commented 10 months ago

Did anything happen with this feature? I'm using this ugly workaround which doesn't seem very safe, use the last order by to add the option as such:

query.OrderByRaw($"{columnName.HSqlEncode()} OPTION(RECOMPILE)");

ahmad-moussawi commented 10 months ago

Thinking of something like this (as initial thought)

db.Query().AppendRaw("OPTION ....");

or by providing a transform method like this one

db.Query().Transform(sql => sql + " OPTION")

WDYT?

jjamid commented 10 months ago

Thinking of something like this (as initial thought)

db.Query().AppendRaw("OPTION ....");

or by providing a transform method like this one

db.Query().Transform(sql => sql + " OPTION")

WDYT?

I think that the first option is more flexible and more intuitive as it is closer to how we add to the query regularly. But maybe the Transform idea can be useful for other scenarios.