Skip to content

Instantly share code, notes, and snippets.

@richiefrost
Last active June 21, 2022 13:13
Show Gist options
  • Save richiefrost/6318923a04b701f1c2e8e367c6fffbaa to your computer and use it in GitHub Desktop.
Save richiefrost/6318923a04b701f1c2e8e367c6fffbaa to your computer and use it in GitHub Desktop.
Simple use of the builder pattern to create a SQL query generator
class QueryBuilder:
def __init__(self):
self.select_value = ''
self.from_table_name = ''
self.where_value = ''
self.groupby_value = ''
def select(self, select_arg):
self.select_value = select_arg
return self
def from_table(self, from_arg):
self.from_table_name = from_arg
return self
def where(self, where_arg):
self.where_value = where_arg
return self
def groupby(self, groupby_args):
self.groupby_value = groupby_args
return self
def build(self):
if self.where_value:
where_clause = f'WHERE {self.where_value}'
if self.groupby_value:
groupby_clause = f'GROUP BY {self.groupby_value}'
return f"""
SELECT {self.select_value}
FROM {self.from_table_name}
{where_clause}
{groupby_clause}
"""
# Simple builder pattern example for building queries
query = QueryBuilder()
query.select('Customer, Region, SUM(SaleValue)') \
.from_table('Sales') \
# Optional - add where and groupby clauses.
# Object construction can easily be either simple or complex
query.where('DATEDIFF(day, TimeStamp, CURRENT_TIMESTAMP) < 180') \
.groupby('Customer, Region')
# Builder pattern collects the optional arguments and builds the actual SQL text
query_text = query.build()
"""
query_text value:
SELECT Customer, Region, SUM(SaleValue)
FROM Sales
WHERE DATEDIFF(day, TimeStamp, CURRENT_TIMESTAMP) < 180
GROUP BY Customer, Region
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment