Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
Amin-ir opened this issue Feb 27, 2024 · 5 comments
Closed

Comments

@Amin-ir
Copy link

Amin-ir commented Feb 27, 2024

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
Copy link

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
Copy link
Author

Amin-ir commented Mar 3, 2024

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!

@Amin-ir Amin-ir closed this as completed Mar 3, 2024
@ahmad-moussawi
Copy link
Contributor

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
Copy link

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

@ahmad-moussawi
Copy link
Contributor

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants