UNPKG

sqlmongoose

Version:

Mongoose-like schemas and models for SQLite3

52 lines (51 loc) 1.54 kB
export class QueryBuilder { constructor(tableName) { this.tableName = tableName; this.conditions = []; this.values = []; this.orderByValues = {}; this.includeFields = []; } where(condition) { // ...existing query building logic... return this; } select(...fields) { this.includeFields = fields; return this; } limit(limit) { this.limitValue = limit; return this; } offset(offset) { this.offsetValue = offset; return this; } orderBy(field, direction) { this.orderByValues[field] = direction; return this; } build() { const fields = this.includeFields.length > 0 ? this.includeFields.join(', ') : '*'; let sql = `SELECT ${fields} FROM ${this.tableName}`; if (this.conditions.length > 0) { sql += ` WHERE ${this.conditions.join(' AND ')}`; } if (Object.keys(this.orderByValues).length > 0) { const orderClauses = Object.entries(this.orderByValues) .map(([field, direction]) => `${field} ${direction}`) .join(', '); sql += ` ORDER BY ${orderClauses}`; } if (this.limitValue !== undefined) { sql += ` LIMIT ${this.limitValue}`; if (this.offsetValue !== undefined) { sql += ` OFFSET ${this.offsetValue}`; } } return { sql, values: this.values }; } }