sripathikrishnan / jinjasql

Template Language for SQL with Automatic Bind Parameter Extraction
MIT License
815 stars 89 forks source link

List all variables in a template #37

Closed the21st closed 3 years ago

the21st commented 3 years ago

Hi, I have a template string, e.g.

SELECT *
FROM users
WHERE name in {{ names | inclause }}
AND age > {{ min_age }}

Is there a way to get the list of all variables present in the template? i.e. something that would return ["names", "min_age"].

Thanks!

the21st commented 3 years ago

I think I figured it out, here's a way:

from jinja2 import meta
from jinjasql import JinjaSql
j = JinjaSql()
template_query = "SELECT *..."
parsed_content = j.env.parse(template_query)
variables = meta.find_undeclared_variables(parsed_content)

Thanks to: https://stackoverflow.com/a/8284419/2761695