← 中文资源

简体中文版本

带参数占位的类型安全查询构建器

基于行类型约束列名与取值,把 WHERE 条件按顺序转成编号占位符,并拼接 SELECT、ORDER BY 与 LIMIT 子句。

阅读英文原文

题目

实现 QueryBuilder,提供 from、select、where、order、limit 和 build。select 的列名必须是 Row 的键,where 的值类型必须与对应字段匹配,order 的列名同样受限,direction 只能是 asc 或 desc。build 返回 { sql, params },SQL 中使用 $1、$2 占位,params 按占位顺序排列。WHERE 条件的顺序必须稳定,并且 limit 为 0 时也要输出 LIMIT 0。

解题思路

构建器内部保存表名、已选列、条件键值对、排序设置和可选的 limit。where 接收 Partial,遍历 Object.keys 时保持对象键的插入顺序,把每个键和值成对压入条件数组,从而保证占位符编号稳定。build 依次拼接 SELECT 列、FROM 表名、WHERE 子句、ORDER BY 和 LIMIT;每处理一个条件就把值推入 params,并用 params.length 生成 $n。limit 用 !== null 判断,避免 0 被当成假值丢弃。

参考实现要点

列名类型使用 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()));