Query builder — fluent API for building SQL queries.
1class QueryBuilder {2 constructor(table) {3 this.table = table;4 this._where = [];5 this._orderBy = null;6 this._limit = null;7 this._select = ["*"];8 this.params = [];9 }1011 select(...columns) {12 this._select = columns;13 return this;14 }1516 where(column, value) {17 this._where.push(`${column} = $${this.params.length + 1}`);18 this.params.push(value);19 return this;20 }2122 orderBy(column, dir = "ASC") {23 this._orderBy = `${column} ${dir}`;24 return this;25 }2627 limit(n) {28 this._limit = n;29 return this;30 }3132 toSQL() {33 let sql = `SELECT ${this._select.join(", ")} FROM ${this.table}`;34 if (this._where.length) sql += ` WHERE ${this._where.join(" AND ")}`;35 if (this._orderBy) sql += ` ORDER BY ${this._orderBy}`;36 if (this._limit) sql += ` LIMIT ${this._limit}`;37 return { sql, params: this.params };38 }3940 async execute(db) {41 const { sql, params } = this.toSQL();42 return db.query(sql, params);43 }44}4546// Usage47const users = await new QueryBuilder("users")48 .select("id", "name", "email")49 .where("active", true)50 .orderBy("name")51 .limit(10)52 .execute(db);