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.09k stars 499 forks source link

Getting Raw SQL from the package, without passing it to the database engine #708

Closed Amin-ir closed 7 months ago

Amin-ir commented 7 months ago

I was lookin' for a sql query builder. but looks like, SQL Kata doesn't directly deliver a SQL text output. Our team is currently using another ORM, so I cannot switch to a new one right now. I was wondering if getting a raw SQL query out of SqlKata is possible? e.g. new Query("Products").Select("").ToString() //return 'SELECT FROM Products'

Revazashvili commented 7 months ago

Yes, you can. package contains compilers for every database it supports, under SqlKata.Compilers namespace.

you can use Compile method to get SqlResult which contains Sql and RawSql properties. if you want to get Sql parsed with actually passed parameters call ToString() method on SqlResult.

Example with postgres;

var query = new Query();
var compiler = new PostgresCompiler();
var sqlResult = compiler.Compile(query);
var sql = sqlResult.ToString();
Amin-ir commented 7 months ago

Fantastic! you see, I feel the queries so much more readable once written using SqlKata chaining methods, and then only converted to raw SQL to be fed into an ORM. TY!

ahmad-moussawi commented 7 months ago

It is worth noting that the ToString() method is meant only for debugging purposes and not for executing queries. Check https://sqlkata.com/docs#compile-only-example

Revazashvili commented 7 months ago

You're right. Is there any other way to compile query?

ahmad-moussawi commented 7 months ago

You're right. Is there any other way to compile query?

If you are not the SqlKata.Execution package, you should use the SqlResult class to get the SQL string with the parameters bindings.

See https://github.com/sqlkata/querybuilder/blob/master/SqlKata.Execution/QueryFactory.cs#L77 as an example