Builders often ship with presets - small helpers that assemble a common query so callers do not repeat the chain. This is the spirit of a Director in the Builder pattern.
Implement the classmethod count_all(table). Using a fresh builder, select the single column COUNT(), set the table with from_, and return the built string. The result must be exactly SELECT COUNT() FROM <table>.
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):
self.wheres.append(condition)
return self
def order_by(self, col):
self.order = col
return self
def limit(self, n):
self._limit = n
return self
def reset(self):
self.columns = []
self.table = None
self.wheres = []
self.order = None
self._limit = None
return self
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)
if self.order is not None:
sql += " ORDER BY " + self.order
if self._limit is not None:
sql += " LIMIT " + str(self._limit)
return sql
@classmethod
def count_all(cls, table):
"""Return a COUNT(*) query for the given table using the builder."""
# TODO: return cls().select("COUNT(*)").from_(table).build()
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Builders often ship with presets - small helpers that assemble a common query so callers do not repeat the chain. This is the spirit of a Director in the Builder pattern.
Implement the classmethod count_all(table). Using a fresh builder, select the single column COUNT(), set the table with from_, and return the built string. The result must be exactly SELECT COUNT() FROM <table>.
Press Run Tests or ββ© to check your solution.