Real queries filter rows. A WHERE clause is a list of conditions joined by AND. Because a query can have many conditions, the builder collects them one call at a time.
Implement where(condition). Append the condition string to self.wheres and return self so the call keeps chaining.
The build method has already been extended: when self.wheres is non-empty it appends a space, the word WHERE, and the conditions joined by the four-character separator space-AND-space. With no conditions the clause is omitted entirely.
class QueryBuilder:
def __init__(self):
self.columns = []
self.table = None
self.wheres = []
self.order = None
self._limit = None
def select(self, *cols):
self.columns = list(cols)
return self
def from_(self, table):
self.table = table
return self
def where(self, condition):
"""Append condition to self.wheres and return self."""
# TODO: record this condition at the end of self.wheres so the clauses
# keep the order they were added in, then hand back the builder itself
# so the caller can keep chaining onto it.
pass
def build(self):
cols = ", ".join(self.columns) if self.columns else "*"
sql = "SELECT " + cols + " FROM " + self.table
if self.wheres:
sql += " WHERE " + " AND ".join(self.wheres)
return sql
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Real queries filter rows. A WHERE clause is a list of conditions joined by AND. Because a query can have many conditions, the builder collects them one call at a time.
Implement where(condition). Append the condition string to self.wheres and return self so the call keeps chaining.
The build method has already been extended: when self.wheres is non-empty it appends a space, the word WHERE, and the conditions joined by the four-character separator space-AND-space. With no conditions the clause is omitted entirely.
Press Run Tests or ββ© to check your solution.