Fluent SQL SELECT Query Builder in Python
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Implement a fluent Python SQL SELECT builder consisting of two factory functions, table(name) and cond(column, operator, value), alongside the Query and Condition classes. Callers construct queries either directly or via a namespace object o exposing o.table and o.cond, chain builder methods in arbitrary order, and call render() to produce an exact SQL SELECT string.
Builder API
table(name: str) -> Query: Creates aQuerytargetingname.cond(column: str, operator: str, value: Value) -> Condition: Creates a single predicate comparingcolumnagainstvalueusingoperator.Query.select(*columns: str) -> Query: Appends one or more column names to this query's projection list and returnsself.Query.where(*conditions: Condition) -> Query: Appends one or moreConditioninstances to this query's filter list and returnsself.Query.alias(name: str) -> Query: Assigns (or updates) this table's SQL alias (FROM <table> AS <alias>) and returnsself.Query.join(other: Query, using: str) -> Query: Appends an inner join against another distinct single-tableQueryon a shared column (JOIN <other> USING (<using>)) and returnsself.Query.render() -> str: Formats and returns the complete SQL statement without mutating stored builder state.
Note that select, where, alias, and join mutate the Query in place and return self (so both chained calls q.select(...).where(...) and standalone statements left.join(right, using=...) take effect on left).
SQL Rendering & Validation Rules
- Clause order & formatting: Emit clauses in standard SQL order:
SELECT <cols> FROM <table> [JOIN <other> USING (<col>) ...] [WHERE <preds>]. Use uppercase SQL keywords (SELECT,FROM,AS,JOIN,USING,WHERE,AND,IS NULL,IS NOT NULL,TRUE,FALSE), single spaces between clauses and operators,", "between projected columns," AND "between predicates, and no trailing semicolon. - Column qualification:
- If a
Queryhas.alias(a), qualify all of its projected columns andWHEREpredicates witha.(even when not joined). - Inside a joined query, any participating
Querywithout an alias qualifies its projected columns andWHEREpredicates with<table_name>.. - On an unaliased single-table query without joins, leave columns unqualified.
- If a
- Projection & filter ordering: Concatenate projected columns in table order (left
Queryfirst, then each joinedQueryin.join()order), preserving.select()call order within each table; if zero columns are selected across all tables, emitSELECT *. Combine allWHEREconditions across participating tables in the same table order usingAND. - Literals & operators:
- Supported operators:
"=","!=","<>","<","<=",">",">=". Any other operator raisesValueError. bool:True->TRUE,False->FALSE.intand finitefloat: unquoted numeric text (25,-3,2.5);NaNor+/-infraisesValueError.str: wrapped in single quotes with internal single quotes doubled ("DHL's Express"->'DHL''s Express').None: permitted only with"="(<col> IS NULL) or"!="/"<>"(<col> IS NOT NULL); pairingNonewith<,<=,>, or>=raisesValueError.- Unsupported value types (or passing non-
Condition/ non-Queryobjects towhere/join) raiseTypeError.
- Supported operators:
Examples
Example 1
o.table("customers").select("customer_id", "tier").render()
Output:
"SELECT customer_id, tier FROM customers"
Walk-through: A single unaliased table without joins renders unqualified column names separated by ", " in .select() order.
Example 2
o.table("shipments").select("shipment_id", "carrier", "weight_kg").where(
o.cond("weight_kg", ">=", 25),
o.cond("carrier", "=", "DHL's Express"),
o.cond("delivered_at", "=", None),
).render()
Output:
"SELECT shipment_id, carrier, weight_kg FROM shipments WHERE weight_kg >= 25 AND carrier = 'DHL''s Express' AND delivered_at IS NULL"
Walk-through: Integers render bare (25), strings are single-quoted with embedded apostrophes doubled ('DHL''s Express'), = None renders as IS NULL, and multiple predicates join with AND.
Example 3
(
o.table("invoices")
.where(o.cond("total_cents", ">", 5000))
.alias("inv")
.select("invoice_id", "total_cents")
.render()
)
Output:
"SELECT inv.invoice_id, inv.total_cents FROM invoices AS inv WHERE inv.total_cents > 5000"
Walk-through: Even though .where() ran before .alias("inv") and .select(), rendering happens lazily at the end so AS inv is emitted and inv. prefixes both selected columns and filter columns.
Example 4
customers = o.table("customers").select("customer_id", "tier").alias("c")
orders = o.table("orders").select("order_id").alias("ord").where(o.cond("paid", "=", True))
customers.join(orders, using="customer_id")
customers.render()
Output:
"SELECT c.customer_id, c.tier, ord.order_id FROM customers AS c JOIN orders AS ord USING (customer_id) WHERE ord.paid = TRUE"
Walk-through: customers.join(orders, using="customer_id") mutates customers in place, concatenates c's selected columns ahead of ord's, emits JOIN orders AS ord USING (customer_id), and qualifies ord's boolean filter as ord.paid = TRUE.
Constraints
- Every table name, column name, alias, and
usingcolumn must be a valid plain ASCII identifier matching[A-Za-z_][A-Za-z0-9_]*; any other string or non-string raisesValueError. join(other, using)only accepts a distinct single-tableQuery(other is not selfandotherhas no joins of its own, both whenjoin()is called and whenrender()runs); violations raiseValueError.- Across a joined query, all active table qualifiers (each table's alias if set, otherwise its table name) must be unique case-insensitively (
customersvs.Customers, or aliasesCvs.c, must raiseValueError).
Step-by-step walkthrough
Pin down the exact SQL contract
Callers drive the query builder through a fluent API (a design pattern where configuration methods return
selfso calls read left-to-right in a chain). Becauserender()must produce exact SQL text, review the formatting and scoping rules first:- Keywords and spacing: uppercase SQL keywords (
SELECT,FROM,AS,JOIN,USING,WHERE,AND), single spaces between tokens,", "between columns, and no trailing semicolon. - Aliases and column prefixes:
.alias("inv")emitsFROM invoices AS invand prefixes that table's selected columns and filter conditions (inv.total_cents) even on a single-table query. - Joins:
.join(other, using="customer_id")emitsJOIN orders AS ord USING (customer_id). Inside a join, any table without an alias falls back to its own table name (customers.customer_id) so column references are never ambiguous. - Selected columns: left query's columns first, then each joined query's columns in
.join()order, preserving.select()order within each table. When zero columns are selected anywhere, emitSELECT *. - Conditions: multiple predicates in one
.where(...), repeated.where(...)calls, and predicates across joined tables all combine withAND, left query first. - In-place mutation: In Example 4,
customers.join(orders, using="customer_id")is called as a standalone statement beforecustomers.render(). Thus builder methods must mutate the receiver in place while also returningself.
Trace how the four examples map onto those rules:
1. o.table("customers").select("customer_id", "tier") -> SELECT customer_id, tier FROM customers 2. o.table("shipments").select("shipment_id", "carrier", "weight_kg").where( o.cond("weight_kg", ">=", 25), o.cond("carrier", "=", "DHL's Express"), o.cond("delivered_at", "=", None)) -> SELECT shipment_id, carrier, weight_kg FROM shipments WHERE weight_kg >= 25 AND carrier = 'DHL''s Express' AND delivered_at IS NULL 3. o.table("invoices").where(o.cond("total_cents", ">", 5000)).alias("inv").select("invoice_id", "total_cents") -> SELECT inv.invoice_id, inv.total_cents FROM invoices AS inv WHERE inv.total_cents > 5000 4. customers.join(orders, using="customer_id") -> SELECT c.customer_id, c.tier, ord.order_id FROM customers AS c JOIN orders AS ord USING (customer_id) WHERE ord.paid = TRUE- Keywords and spacing: uppercase SQL keywords (
Record first, render last
Concatenating SQL strings eagerly inside
.select()or.where()breaks immediately on Example 3, where.where(...)is called before.alias("inv")and.select(...):Eager string concatenation (broken): o.table("invoices") -> "FROM invoices" .where(o.cond("total_cents", ">", 5000)) -> "FROM invoices WHERE total_cents > 5000" (missing 'inv.'!) .alias("inv") -> too late: WHERE text was already frozen Record first, render last (clean): o.table("invoices") -> table_name="invoices" .where(o.cond("total_cents", ">", 5000)) -> conditions=[Condition("total_cents", ">", 5000)] .alias("inv") -> alias_name="inv" .select("invoice_id", "total_cents") -> columns=["invoice_id", "total_cents"] .render() -> prefixes everything with "inv." at render time!So
Querystores five structured fields (table_name,columns,conditions,alias_name,joins), validates inputs eagerly, and leaves string construction entirely torender():class Query: """A SELECT on one table, optionally joined with other single-table queries. Builder methods mutate this Query in place and return self so calls can be chained. """ def __init__(self, table_name: str): self.table_name: str = check_identifier(table_name) # columns: plain column names in call order, e.g. ["id", "email"] self.columns: List[str] = [] # conditions: Condition objects in call order, combined later with AND self.conditions: List[Condition] = [] # alias_name: optional SQL table alias, e.g. "u" for `FROM users AS u` self.alias_name: Optional[str] = None # joins: list of (other_query, shared_using_column) pairs, e.g. [(apps, "user_id")] self.joins: List[Tuple["Query", str]] = [] def select(self, *columns: str) -> "Query": for column in columns: self.columns.append(check_identifier(column)) return self def where(self, *conditions: Condition) -> "Query": for condition in conditions: if not isinstance(condition, Condition): raise TypeError("where() takes conditions made by cond()") self.conditions.append(condition) return self def alias(self, name: str) -> "Query": self.alias_name = check_identifier(name) return self def join(self, other: "Query", using: str) -> "Query": if not isinstance(other, Query): raise TypeError("join() takes another query") # Only flat joins of distinct single-table queries are representable without subqueries if other is self or other.joins: raise ValueError("join() takes a different, single-table query") shared_col = check_identifier(using) self.joins.append((other, shared_col)) return selfValidate identifiers and format SQL literals
Each Python scalar in
cond(column, operator, value)maps to a specific SQL literal syntax:NonebecomesNULL.boolbecomesTRUEorFALSE. Checkisinstance(value, bool)beforeisinstance(value, int)becauseboolsubclassesintin Python (isinstance(True, int)evaluates toTrue!).intand finitefloatrender unquoted (25,-12,4.75). RejectNaNand+/-infviamath.isfinite(value)because standard SQL has no numeric literal for them.strwraps in single quotes with any embedded single quote doubled ("DHL's Express"->'DHL''s Express').
Because table, column, and alias identifiers cannot be quoted as string values,
check_identifierenforces[A-Za-z_][A-Za-z0-9_]*, rejecting SQL-injection attempts like"customers; DROP TABLE customers"immediately:IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") OPERATORS = ("=", "!=", "<>", "<", "<=", ">", ">=") def check_identifier(name: str) -> str: """Return name if it is a plain SQL identifier, else raise ValueError.""" # Table, column, and alias names cannot be bound as value literals, so validate strictly if not isinstance(name, str) or not IDENTIFIER.fullmatch(name): raise ValueError(f"not a plain identifier: {name!r}") return name def sql_literal(value: Value) -> str: """Convert one Python scalar value into its exact SQL literal text.""" if value is None: return "NULL" # Check bool BEFORE int because bool is a subclass of int in Python (isinstance(True, int) is True) if isinstance(value, bool): return "TRUE" if value else "FALSE" if isinstance(value, int): return str(value) if isinstance(value, float): # NaN and +/-inf have no standard SQL numeric literal if not math.isfinite(value): raise ValueError(f"SQL has no literal for {value!r}") return repr(value) if isinstance(value, str): # Standard SQL escapes a single quote inside a string literal by doubling it ('O''Brien') escaped = value.replace("'", "''") return "'" + escaped + "'" raise TypeError(f"unsupported value type: {type(value).__name__}")Build table-independent Condition objects
When caller code creates
o.cond("total_cents", ">", 5000), thatConditionis not yet attached to anyQueryand cannot know whether its qualifier will beNone,"inv", or"invoices". SoConditionstores(column, operator, value)and receivesqualifierlater insideCondition.render(qualifier).Nonerequires special handling because SQL uses three-valued logic (TRUE,FALSE, andUNKNOWN). Writingdelivered_at = NULLevaluates toUNKNOWNon every row and matches nothing! Instead,= Nonemust emitIS NULL,!= Noneand<> Nonemust emitIS NOT NULL, and ordering operators like> Nonemust raiseValueError:def qualify(qualifier: Optional[str], column: str) -> str: """Prefix column with 'qualifier.' when a table or alias prefix is active.""" if qualifier is None: return column return qualifier + "." + column class Condition: """One comparison `column operator value`, made by cond().""" def __init__(self, column: str, operator: str, value: Value): # Store raw pieces now; the table/alias prefix is unknown until Query.render() runs self.column = check_identifier(column) if operator not in OPERATORS: raise ValueError(f"unsupported operator: {operator!r}") if value is None and operator not in ("=", "!=", "<>"): raise ValueError("None can only be compared with =, != or <>") # Validate value conversion eagerly so bad types/NaNs fail at cond(...) call time sql_literal(value) self.operator = operator self.value = value def render(self, qualifier: Optional[str]) -> str: qualified_col = qualify(qualifier, self.column) if self.value is None: # In SQL three-valued logic, `col = NULL` is UNKNOWN (never true), so use IS [NOT] NULL if self.operator == "=": return qualified_col + " IS NULL" return qualified_col + " IS NOT NULL" return qualified_col + " " + self.operator + " " + sql_literal(self.value)Choose qualifiers and assemble SQL clauses
Three rules determine a table's column prefix:
+-----------------------------------+--------------------+-------------------------+ | Query context | Active qualifier | Rendered column example | +-----------------------------------+--------------------+-------------------------+ | Query has .alias("inv") | alias ("inv") | inv.total_cents | | Unaliased, participating in JOIN | table name | customers.customer_id | | Unaliased, single-table query | None (unqualified) | customer_id | +-----------------------------------+--------------------+-------------------------+In any joined query, participating qualifiers must be distinct case-insensitively (
customersvs.Customers, or aliasesCvs.c) because unquoted SQL identifiers ignore case. Trackingprefix.lower()inseen_lowercatches collisions cleanly before emittingSELECT,FROM,JOIN ... USING (...), andWHERE:def qualifier(self, is_joined: bool) -> Optional[str]: """Prefix for this table's columns: alias if set, table name in a join, else None.""" if self.alias_name is not None: return self.alias_name if is_joined: return self.table_name return None def table_sql(self) -> str: """Render the FROM / JOIN target, e.g. 'users' or 'users AS u'.""" if self.alias_name is None: return self.table_name return self.table_name + " AS " + self.alias_name def render(self) -> str: # Phase 1: gather the left query followed by each joined query, checking for nested joins parts: List["Query"] = [self] for other, _ in self.joins: if other.joins: raise ValueError("a joined query cannot have joins of its own") parts.append(other) is_joined = len(parts) > 1 # Phase 2: compute each table's column qualifier and reject case-insensitive collisions qualifiers: List[Optional[str]] = [] seen_lower = set() for part in parts: prefix = part.qualifier(is_joined) if prefix is not None: # Unquoted SQL identifiers are case-insensitive ('U' and 'u' collide) lower_key = prefix.lower() if lower_key in seen_lower: raise ValueError(f"two tables are both called {prefix!r}; give one an alias") seen_lower.add(lower_key) qualifiers.append(prefix) # Phase 3: qualify SELECT columns and render WHERE conditions in table order select_items: List[str] = [] where_items: List[str] = [] for part, prefix in zip(parts, qualifiers): for column in part.columns: select_items.append(qualify(prefix, column)) for condition in part.conditions: where_items.append(condition.render(prefix)) # Phase 4: assemble SQL clauses in fixed grammar order (SELECT, FROM, JOIN, WHERE) if select_items: clauses = ["SELECT " + ", ".join(select_items)] else: clauses = ["SELECT *"] clauses.append("FROM " + self.table_sql()) for other, using_col in self.joins: clauses.append("JOIN " + other.table_sql() + " USING (" + using_col + ")") if where_items: clauses.append("WHERE " + " AND ".join(where_items)) return " ".join(clauses)Notice why
if other.joins:is checked both insidejoin()and again insiderender(): becauseQueryobjects are mutable, a caller could attachmiddletoleftfirst and subsequently callmiddle.join(refunds, ...)before callingleft.render().Trace Example 4 from start to finish
Walk through Example 4 step by step:
1. customers = o.table("customers").select("customer_id", "tier").alias("c") customers.table_name = "customers" customers.columns = ["customer_id", "tier"] customers.alias_name = "c" 2. orders = o.table("orders").select("order_id").alias("ord").where(o.cond("paid", "=", True)) orders.table_name = "orders" orders.columns = ["order_id"] orders.alias_name = "ord" orders.conditions = [Condition("paid", "=", True)] 3. customers.join(orders, using="customer_id") customers.joins = [(orders, "customer_id")] (mutated in place) 4. customers.render(): parts = [customers, orders], is_joined = True qualifiers = ["c", "ord"], seen_lower = {"c", "ord"} select_items = ["c.customer_id", "c.tier", "ord.order_id"] where_items = ["ord.paid = TRUE"] clauses = [ "SELECT c.customer_id, c.tier, ord.order_id", "FROM customers AS c", "JOIN orders AS ord USING (customer_id)", "WHERE ord.paid = TRUE" ] result -> "SELECT c.customer_id, c.tier, ord.order_id FROM customers AS c JOIN orders AS ord USING (customer_id) WHERE ord.paid = TRUE"Complete solution
from typing import List, Optional, Tuple, Union import math import re Value = Union[None, bool, int, float, str] # Plain SQL identifier: starts with a letter or underscore, followed by letters, digits, or underscores IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") OPERATORS = ("=", "!=", "<>", "<", "<=", ">", ">=") def check_identifier(name: str) -> str: """Return name if it is a plain SQL identifier, else raise ValueError.""" # Table, column, and alias names cannot be bound as value literals, so validate strictly if not isinstance(name, str) or not IDENTIFIER.fullmatch(name): raise ValueError(f"not a plain identifier: {name!r}") return name def sql_literal(value: Value) -> str: """Convert one Python scalar value into its exact SQL literal text.""" if value is None: return "NULL" # Check bool BEFORE int because bool is a subclass of int in Python (isinstance(True, int) is True) if isinstance(value, bool): return "TRUE" if value else "FALSE" if isinstance(value, int): return str(value) if isinstance(value, float): # NaN and +/-inf have no standard SQL numeric literal if not math.isfinite(value): raise ValueError(f"SQL has no literal for {value!r}") return repr(value) if isinstance(value, str): # Standard SQL escapes a single quote inside a string literal by doubling it ('O''Brien') escaped = value.replace("'", "''") return "'" + escaped + "'" raise TypeError(f"unsupported value type: {type(value).__name__}") def qualify(qualifier: Optional[str], column: str) -> str: """Prefix column with 'qualifier.' when a table or alias prefix is active.""" if qualifier is None: return column return qualifier + "." + column class Condition: """One comparison `column operator value`, made by cond().""" def __init__(self, column: str, operator: str, value: Value): # Store raw pieces now; the table/alias prefix is unknown until Query.render() runs self.column = check_identifier(column) if operator not in OPERATORS: raise ValueError(f"unsupported operator: {operator!r}") if value is None and operator not in ("=", "!=", "<>"): raise ValueError("None can only be compared with =, != or <>") # Validate value conversion eagerly so bad types/NaNs fail at cond(...) call time sql_literal(value) self.operator = operator self.value = value def render(self, qualifier: Optional[str]) -> str: qualified_col = qualify(qualifier, self.column) if self.value is None: # In SQL three-valued logic, `col = NULL` is UNKNOWN (never true), so use IS [NOT] NULL if self.operator == "=": return qualified_col + " IS NULL" return qualified_col + " IS NOT NULL" return qualified_col + " " + self.operator + " " + sql_literal(self.value) class Query: """A SELECT on one table, optionally joined with other single-table queries. Builder methods mutate this Query in place and return self so calls can be chained. """ def __init__(self, table_name: str): self.table_name: str = check_identifier(table_name) # columns: plain column names in call order, e.g. ["id", "email"] self.columns: List[str] = [] # conditions: Condition objects in call order, combined later with AND self.conditions: List[Condition] = [] # alias_name: optional SQL table alias, e.g. "u" for `FROM users AS u` self.alias_name: Optional[str] = None # joins: list of (other_query, shared_using_column) pairs, e.g. [(apps, "user_id")] self.joins: List[Tuple["Query", str]] = [] def select(self, *columns: str) -> "Query": for column in columns: self.columns.append(check_identifier(column)) return self def where(self, *conditions: Condition) -> "Query": for condition in conditions: if not isinstance(condition, Condition): raise TypeError("where() takes conditions made by cond()") self.conditions.append(condition) return self def alias(self, name: str) -> "Query": self.alias_name = check_identifier(name) return self def join(self, other: "Query", using: str) -> "Query": if not isinstance(other, Query): raise TypeError("join() takes another query") # Only flat joins of distinct single-table queries are representable without subqueries if other is self or other.joins: raise ValueError("join() takes a different, single-table query") shared_col = check_identifier(using) self.joins.append((other, shared_col)) return self def qualifier(self, is_joined: bool) -> Optional[str]: """Prefix for this table's columns: alias if set, table name in a join, else None.""" if self.alias_name is not None: return self.alias_name if is_joined: return self.table_name return None def table_sql(self) -> str: """Render the FROM / JOIN target, e.g. 'users' or 'users AS u'.""" if self.alias_name is None: return self.table_name return self.table_name + " AS " + self.alias_name def render(self) -> str: # Phase 1: gather the left query followed by each joined query, checking for nested joins parts: List["Query"] = [self] for other, _ in self.joins: if other.joins: raise ValueError("a joined query cannot have joins of its own") parts.append(other) is_joined = len(parts) > 1 # Phase 2: compute each table's column qualifier and reject case-insensitive collisions qualifiers: List[Optional[str]] = [] seen_lower = set() for part in parts: prefix = part.qualifier(is_joined) if prefix is not None: # Unquoted SQL identifiers are case-insensitive ('U' and 'u' collide) lower_key = prefix.lower() if lower_key in seen_lower: raise ValueError(f"two tables are both called {prefix!r}; give one an alias") seen_lower.add(lower_key) qualifiers.append(prefix) # Phase 3: qualify SELECT columns and render WHERE conditions in table order select_items: List[str] = [] where_items: List[str] = [] for part, prefix in zip(parts, qualifiers): for column in part.columns: select_items.append(qualify(prefix, column)) for condition in part.conditions: where_items.append(condition.render(prefix)) # Phase 4: assemble SQL clauses in fixed grammar order (SELECT, FROM, JOIN, WHERE) if select_items: clauses = ["SELECT " + ", ".join(select_items)] else: clauses = ["SELECT *"] clauses.append("FROM " + self.table_sql()) for other, using_col in self.joins: clauses.append("JOIN " + other.table_sql() + " USING (" + using_col + ")") if where_items: clauses.append("WHERE " + " AND ".join(where_items)) return " ".join(clauses) def table(name: str) -> Query: """o.table(name): start a query on one table.""" return Query(name) def cond(column: str, operator: str, value: Value) -> Condition: """o.cond(column, operator, value): one condition for where().""" return Condition(column, operator, value)✅ Submit now — all tests should pass.
Intuition & how it works
Think of a SQL query builder like jotting down customer requests on a cafe notepad before printing the kitchen ticket. A guest might give instructions in any sequence ("only orders over $50", "label this table inv", "show invoice_id and total_cents"), whereas SQL grammar insists on one rigid order (SELECT ... FROM ... JOIN ... WHERE ...). Applying the builder pattern (an object that records configuration pieces incrementally and assembles the finished product in one step at the end) cleanly decouples collecting caller intent from formatting SQL text.
Eagerly concatenating SQL substrings inside .where() or .select() fails immediately whenever methods run out of SQL clause order. For example, if .where(o.cond("total_cents", ">", 5000)) baked "WHERE total_cents > 5000" into a string right away, calling .alias("inv") on the next step would leave WHERE missing its inv. prefix, and a second .select() call would have nowhere clean to splice extra columns. Likewise, o.cond(...) is instantiated before being passed to any Query, so it cannot know its table qualifier at construction time.
Instead, every builder method appends validated items onto plain lists on Query, and render() formats everything in one final pass. Tracing Example 3:
1. o.table("invoices") initializes table_name = "invoices".
2. .where(o.cond("total_cents", ">", 5000)) appends Condition("total_cents", ">", 5000) to conditions.
3. .alias("inv") sets alias_name = "inv", and .select("invoice_id", "total_cents") appends both column names to columns.
4. .render() observes alias_name = "inv", prefixes every selected column and condition with "inv.", and emits "SELECT inv.invoice_id, inv.total_cents FROM invoices AS inv WHERE inv.total_cents > 5000".
Complexity
- Builder methods (
table,cond,select,where,alias,join):O(k)time for a call passingkarguments (treating identifier lengths as bounded by a small constant, or linear in total identifier character length), since each identifier is validated once viaIDENTIFIER.fullmatchand appended to a Python list inO(1)amortized time. render()time:O(S), whereSis the character length of the rendered SQL string. Each participating table is visited once (using anO(1)hash-set lookup onprefix.lower()to detect collisions), each column and condition is formatted once, and all pieces are joined in linear time via", ".join(...)," AND ".join(...), and" ".join(...).- Space:
O(C + W)onQueryto storeCprojected column names andWConditioninstances, plusO(S)temporary memory insiderender()for the formatted clause list and output string.
Edge cases
- No
select()called anywhere: EmitsSELECT *. In a multi-table join where one table selects columns and a bridge table selects none, only the selected columns appear. - Apostrophes inside string literals:
"DHL's Express"becomes'DHL''s Express'by doubling embedded single quotes;""becomes''. Nonecomparisons (NULL): Under SQL three-valued logic (expressions evaluate toTRUE,FALSE, orUNKNOWN),col = NULLis alwaysUNKNOWNand matches zero rows. Thus= NonerendersIS NULL,!= Noneand<> NonerenderIS NOT NULL, and ordering operators like> NoneraiseValueError.- Booleans vs. integers: Because
boolsubclassesintin Python (isinstance(True, int)isTrue),sql_literalchecksboolbeforeintsoTrue/Falserender asTRUE/FALSEinstead of1/0. - Non-finite floats:
float("nan")andfloat("inf")lack standard SQL numeric literals and raiseValueErroreagerly incond(...). - Arbitrary chaining order and repeated calls: Calling
.where()before.alias()or invoking.select()and.where()multiple times yields identical SQL because qualification and clause assembly happen lazily inrender(). - Self-joins and case-insensitive collisions: Unaliased
customers JOIN customers(orcustomers JOIN Customers, or aliasesCandc) is rejected viaprefix.lower(), whereasemployees AS mgr JOIN employees AS repsucceeds cleanly. - Post-join mutations: Because
join()stores a live reference toother, adding.where()ontoordersaftercustomers.join(orders, ...)still appears incustomers.render(); iforderslater adds its own.join(),customers.render()catchesother.joinsand raisesValueError. - Identifier injection attempts: Strings like
"customers; DROP TABLE customers","customer_id, tier", or"9col"failIDENTIFIER.fullmatchand raiseValueError.
Common mistakes
- Building SQL substrings eagerly inside
.where()or.select(). Breaks whenever.alias()or.join()is called afterward and requires retroactively prefixing columns. - Formatting literals with
str(value)orrepr(value)indiscriminately.str("west")omits quotes entirely, whilerepr("DHL's Express")wraps the string in double quotes ("DHL's Express"), which standard SQL interprets as a column identifier rather than a text literal. - Escaping quotes with backslashes (
\'). Standard SQLite and PostgreSQL (standard_conforming_strings = on) treat\literally, turning'Macy\'s'into a syntax error or a SQL injection vector (untrusted input altering query structure). - Emitting
col = NULLforNone. Executes without error while silently matching zero rows. - Returning new copies without mutating
self. Standalone calls such ascustomers.join(orders, using="customer_id")discard the return value and fail ifcustomerswas not mutated in place. - Qualifying
SELECTcolumns while forgettingWHEREcolumns.SELECT c.tier FROM customers AS c WHERE tier = 'gold'fails with an ambiguous-column error as soon as a joined table also has atiercolumn.
Alternative approaches
- Immutable copy-on-write builder: Each method (
select,where,alias,join) clonesQueryand its internal lists rather than mutatingself, letting callers safely branch multiple queries off one shared base template at the cost of requiring reassignment (customers = customers.join(...)). - Explicit AST + dialect compiler: Model queries and expressions as an abstract syntax tree (AST) (nodes like
SelectStmt,BinaryPredicate,ColumnRef,Literal) paired with per-dialect visitors for SQLite, PostgreSQL, and MySQL.
Follow-up questions
- How would you redesign
render()to output SQL placeholders alongside a bound-parameter list, and what security and database benefits does that provide? Haverender()(orrender_params()) emit a placeholder such as?(SQLite) or%s(PostgreSQLpsycopg) for each non-Nonecondition value while collecting raw Python values in aparamslist — returning, for instance,("SELECT shipment_id FROM shipments WHERE weight_kg >= ? AND carrier = ? AND delivered_at IS NULL", [25, "DHL's Express"]). A parameterized query transmits the SQL structure and data values separately so the database parses and compiles the query plan before reading any parameter bytes, eliminating value-based SQL injection, preserving exact driver types, and enabling database plan caching. Note thatNonestill emitsIS [NOT] NULLwith zero bound parameters, and identifiers still requirecheck_identifierbecause SQL placeholders cannot parameterize table or column names. - How would you extend
.join()to support customONpredicates as well asLEFT OUTER JOINsemantics? Store join entries as(join_keyword, other_query, using_col, on_expr)wherejoin_keywordis"JOIN"or"LEFT JOIN"(a left outer join, keeping every left-hand row and filling unmatched right-hand columns withNULL), accepting eitherusing=oron=(never both). Introduce a column-reference type (such aso.col("ord", "customer_id")) soon=compares two columns without quoting the right-hand side as a string literal. Crucially, for aLEFT JOIN, predicates belonging solely to the right-hand query (likeord.paid = TRUE) must move into that join'sONclause rather than the outerWHEREclause — otherwiseNULL-padded unmatched rows failWHEREand silently degrade the outer join into an inner join. - How can the API express
ORlogic and arbitrarily nested boolean condition groups while keeping caller code clean? Add a compositeConditionGroup(glue, children)created viao.any_of(*children)(OR) ando.all_of(*children)(AND), implementing the same.render(qualifier)interface asCondition. Because SQL bindsANDtighter thanOR(a OR b AND cparses asa OR (b AND c)),ConditionGroup.renderjoins rendered children with" OR "or" AND "and wrapsORgroups in parentheses — e.g.,WHERE (tier = 'gold' OR tier = 'platinum') AND active = TRUE. Explicitany_of/all_ofhelpers avoid the operator-precedence traps of overloading Python's bitwise|and&. - How would you store and render
.order_by()and.limit()clauses, especially when multiple queries are joined together? Addself.order_by_items: List[Tuple[str, str]](column identifier plus direction validated against("ASC", "DESC")) andself.limit_value: Optional[int](a non-negativeint, rejectingbool) onQuery, emittingORDER BY ...afterWHEREandLIMIT ...last. Across joins, qualify each participating query'sorder_by_itemswith its active prefix (c.tier ASC, ord.order_id DESC) in table order just likeSELECT. By contrast, SQLLIMITcaps the entire joined result set, so only the root query may carry a top-levelLIMIT; if a joined right-hand query specifies its own.limit(5), either raiseValueErroror compile that right-handQueryinto a parenthesized derived table subquery (JOIN (SELECT ... LIMIT 5) AS ord USING (customer_id)).
Follow-up questions
- How would you redesign `render()` to output SQL placeholders alongside a bound-parameter list, and what security and database benefits does that provide?
- How would you extend `.join()` to support custom `ON` predicates as well as `LEFT OUTER JOIN` semantics?
- How can the API express `OR` logic and arbitrarily nested boolean condition groups while keeping caller code clean?
- How would you store and render `.order_by()` and `.limit()` clauses, especially when multiple queries are joined together?
Similar questions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager
- Transactional Shopping Cart with Nested Scopes