Jinja Templates to SQL
Project description
Jinja2SQL (Jinja To SQL)
Jinja2SQL
is a simple and efficient library for generating SQL queries from Jinja2 templates. It is type-friendly and offers async
support, drawing significant inspiration from the excellent library at jinjasql.
Documentation
http://jinja2sql.readthedocs.io/
Requirements
Python 3.8+
and Jinja2 3.1.2+
.
Installation
Install using pip
:
pip install jinja2sql
or using poetry
:
poetry add jinja2sql
Quick Example
from jinja2sql import Jinja2SQL
j2sql = Jinja2SQL(param_style="named") # default param style is "named"
query, params = j2sql.from_string(
"SELECT * FROM {{ table | identifier }} WHERE email = {{ email }}",
context={"table": "users", "email": "user@mail.com"},
)
# using with your favorite database driver connection
conn.execute(query, params)
Param Styles
Jinja2SQL
supports different param styles depending on the database driver you are using.
You can choose between the following supported param styles:
from jinja2sql import Jinja2SQL
j2sql = Jinja2SQL(param_style="named") # default
query, params = j2sql.from_string(
"SELECT * FROM table WHERE param = {{ param }}",
context={"param": ...},
param_style="named", # or "qmark", "numeric", "format", "pyformat", "asyncpg"
)
param_style | Example |
---|---|
named |
:param |
qmark |
? |
numeric |
:1 |
format |
%s |
pyformat |
%(param)s |
asyncpg |
$1 |
or you can provide a custom function to format your database specific param style:
from jinja2sql import Jinja2SQL
j2sql = Jinja2SQL()
query, params = j2sql.from_string(
"SELECT * FROM table WHERE column = {{ param }}",
context={"param": ...},
param_style=lambda key, _: f"{{{key}}}",
)
assert query == "SELECT * FROM table WHERE column = {email}"
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
jinja2sql-0.4.0.tar.gz
(7.1 kB
view hashes)
Built Distribution
Close
Hashes for jinja2sql-0.4.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 77b3f97407f50d39b7884cc6cf17ae9b4b9d845fb6b36e8c39f750bfb07d65d5 |
|
MD5 | 91cc395f3ef6f95cd03d0b4bb9d445d1 |
|
BLAKE2b-256 | 3862efab3ba1710b71ac185224f8812cd82105fc3af901650c1025ff4e55b40b |