题目
实现 QueryBuilder
解题思路
构建器内部保存表名、已选列、条件键值对、排序设置和可选的 limit。where 接收 Partial
参考实现要点
列名类型使用 keyof Row & string,既排除 symbol 键,又让点号与排序方向在编译期受限。占位符编号由 params 长度决定,而不是单独维护计数器,可以减少不同步的风险。条件用数组保存,避免对象无序导致 SQL 与参数错位。排序方向调用 toUpperCase 后输出,SQL 关键字统一大写,输出逐字可比较。
常见错误
把条件值直接拼进 SQL 字符串,既可能注入,也无法复用预编译语句。WHERE 条件用对象键遍历但没有保持顺序,占位符和参数可能对不上。用 if (this.rowLimit) 判断,导致 LIMIT 0 被静默丢弃。列名类型写成 string,拼错字段名时编译器无法发现,直到运行时 SQL 才报错。
验证方式
用 tsc –strict 编译,确认选择不存在的列或给 age 传字符串都会报错。运行三个样例并比对 JSON,重点检查占位符编号与 params 顺序。补充测试:where({}) 不应生成 WHERE 子句;limit 为 0 时应输出 LIMIT 0;order 只把方向转成大写,列名保持原样。
代码示例
declare const input: string;
interface UserRow {
id: number;
name: string;
status: string;
age: number;
}
class QueryBuilder<Row extends object> {
private tableName = '';
private columns: Array<keyof Row & string> = [];
private conditions: Array<[keyof Row & string, unknown]> = [];
private orderBy: { column: keyof Row & string; direction: 'asc' | 'desc' } | null = null;
private rowLimit: number | null = null;
from(table: string): this {
this.tableName = table;
return this;
}
select(...columns: Array<keyof Row & string>): this {
this.columns = columns;
return this;
}
where(conditions: Partial<Row>): this {
for (const key of Object.keys(conditions) as Array<keyof Row & string>) {
this.conditions.push([key, conditions[key]]);
}
return this;
}
order(column: keyof Row & string, direction: 'asc' | 'desc'): this {
this.orderBy = { column, direction };
return this;
}
limit(count: number): this {
this.rowLimit = count;
return this;
}
build(): { sql: string; params: unknown[] } {
const params: unknown[] = [];
const parts = [`SELECT ${this.columns.join(', ')} FROM ${this.tableName}`];
if (this.conditions.length > 0) {
const clauses = this.conditions.map(([column, value]) => {
params.push(value);
return `${column} = $${params.length}`;
});
parts.push(`WHERE ${clauses.join(' AND ')}`);
}
if (this.orderBy) {
parts.push(`ORDER BY ${this.orderBy.column} ${this.orderBy.direction.toUpperCase()}`);
}
if (this.rowLimit !== null) parts.push(`LIMIT ${this.rowLimit}`);
return { sql: parts.join(' '), params };
}
}
interface Spec {
table: string;
select: Array<keyof UserRow & string>;
where?: Partial<UserRow>;
orderBy?: { column: keyof UserRow & string; direction: 'asc' | 'desc' };
limit?: number;
}
const spec = JSON.parse(input) as Spec;
const builder = new QueryBuilder<UserRow>().from(spec.table).select(...spec.select);
if (spec.where) builder.where(spec.where);
if (spec.orderBy) builder.order(spec.orderBy.column, spec.orderBy.direction);
if (typeof spec.limit === 'number') builder.limit(spec.limit);
console.log(JSON.stringify(builder.build()));