JinjaSQL is our new open source library to generate SQL using a Jinja template.
Why should you use JinjaSQL?
At HashedIn, Django is used extensively. The Django ORM is great for most of the use cases, however, there are times when you just need to write a raw SQL query and bypass the ORM altogether. The most common use cases are reports and listing pages that need complex joins.
When you hit a 5% use case that requires the expressiveness and power of raw SQL query, it is unlikely that your query is a simple one-liner.
For those use cases, JinjaSQL helps you maintain the queries in an external template file. You can put in placeholder variables, add if/else conditions, use macros and all the power that is available to a regular Jinja template. You don’t have to manually track your bind parameters. It tracks them and binds them appropriately.
Prevention of the SQL Injection
As a matter of fact templates are not a new idea, however, they haven’t been popular because they are vulnerable to SQL Injection. JinjaSQL never inserts values directly into the query. Instead, it gives you the generated SQL query, and a list of bind parameters. It is then up to you to use them to execute the query.
Take a look at an example:
If this template is executed using plain-old Jinja2, you’d get :
With JinjaSQL, you get back two things,
and a list of bind parameters:
The list of bind parameters can be integers, strings, or for that matter even python datetime objects.