JinjaSQL

0.1.8 · maintenance · verified Mon Apr 13

JinjaSQL is a Python library (version 0.1.8) that enables the generation of SQL queries and their corresponding bind parameters using Jinja2 templates. It leverages Jinja2's powerful templating features (conditionals, loops, macros) while automatically binding parameters to mitigate common SQL injection vulnerabilities for templated values. It prepares the query and parameters, leaving actual execution to the database driver. While its latest release was in May 2020, this release included a critical bug fix, suggesting it is in a maintenance state rather than active development.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize JinjaSQL, define a Jinja2 template for an SQL query, and prepare the query along with its bind parameters using a context dictionary. It shows how conditional logic in the template affects the final query and parameters. The prepared query and parameters can then be passed to any database driver for execution.

from jinjasql import JinjaSql

j = JinjaSql()

template = """
SELECT username, sum(spend)
FROM transactions
WHERE start_date > {{ request.start_date }}
  AND end_date < {{ request.end_date }}
{% if request.organization %}
  AND organization = {{ request.organization }}
{% endif %}
"""

data = {
    "request": {
        "start_date": "2026-01-01",
        "end_date": "2026-03-31",
        "organization": "ExampleOrg"
    }
}

query, bind_params = j.prepare_query(template, data)

print("Generated Query:", query)
print("Bind Parameters:", bind_params)

# Example with missing organization
data_no_org = {
    "request": {
        "start_date": "2026-01-01",
        "end_date": "2026-03-31"
    }
}
query_no_org, bind_params_no_org = j.prepare_query(template, data_no_org)

print("\nGenerated Query (no organization):", query_no_org)
print("Bind Parameters (no organization):", bind_params_no_org)

view raw JSON →