JinjaSQL is used to prepare SQL queries by evaluating a Jinja template against a context dictionary. It returns a parameterized SQL string and a list (or dictionary) of bind parameters, preventing SQL injection.
- Create a
JinjaSql instance (it is thread-safe). - Define your SQL template using Jinja syntax.
- Provide a context dictionary containing the variables.
- Call
prepare_query(template, context) to get the query and parameters.
from jinjasql import JinjaSql
# 1. Initialize
j = JinjaSql()
# 2. Define template
template = """
SELECT project, timesheet, hours
FROM timesheet
WHERE user_id = {{ user_id }}
{% if project_id %}
AND project_id = {{ project_id }}
{% endif %}
"""
# 3. Define context
data = {
"project_id": 123,
"user_id": "sripathi"
}
# 4. Prepare query
query, bind_params = j.prepare_query(template, data)
# Resulting query: "... WHERE user_id = %s AND project_id = %s"
# Resulting params: ['sripathi', 123]