Developer Interface¶
This covers all interfaces of the Py-QueryBuilder library.
Class¶
All functionality is available with the QueryBuilder
class.
-
class
py_querybuilder.api.
QueryBuilder
(package_name: str, filters: list, operators: dict = None)[source]¶ Relies on Jinja2 templates & JinjaSql to generate SQL statements.
Usage:
# Assuming the target module has a template with {{ where }}: with open("app/articles/templates/query.sql", "r") as f: print(f.read()) # SELECT * # FROM my_table # WHERE {{ where }} from py_querybuilder import QueryBuilder qb = QueryBuilder("app.articles", [ { "label": "Article", "options": [ { "label": "Title", "value": "title", "type": "text", }, { "label": "URL", "value": "url", "type": "text", }, ], }, ]) sql_query, sql_params = qb.render("query.sql", { "combinator": "and", "rules": [ { "field": "title", "operator": "contains", "value": "France", }, ], }) print(sql_query) # SELECT * # FROM my_table # WHERE title ~* ? AS "Title" print(sql_params) # ["France"]
Methods¶
-
py_querybuilder.api.QueryBuilder.
__init__
(self, package_name: str, filters: list, operators: dict = None) → None¶ Initializes the QueryBuilder instance with package name and filters.
- Parameters
package_name – Target module containing a templates folder.
filters – The filters object is a list of grouped dictionaries with label str and options list properties. Each option is a dictionary with label str, value str, and type str. The label can be anything, but the value must be an unique key, used by each field in a ruleset. In case an option’s type is “select” or “multiselect”, it will require a nested options list property with label & value items.
operators – The operators object is a dictionary for translating known operators to their SQL equivalents.
-
py_querybuilder.api.QueryBuilder.
render
(self, template_name: str, query: dict) → Tuple[str, List]¶ Renders a SQL statement provided a query object.
- Parameters
template_name – The template file under the templates folder.
query – The query object is a recursive data structure composed of combinator ‘str’ and rules list properties. Each rule is an object with field ‘str’, operator ‘str’, and value (anything, depending on the field’s type). In case the rule contains a combinator property, it’s considered a nested group.
- Returns
The rendered query and its parameters.