//查询构建器
class QueryBuilder {
    constructor() {
        this.query = '';
        this.params = [];
    }

    clear(){
        this.query = '';
        this.params = []; 
    }

    select(fields = '*') {
        this.query = `SELECT ${Array.isArray(fields) ? fields.join(', ') : fields}`;
        return this;
    }

    from(table) {
        this.query += ` FROM ${table}`;
        return this;
    }

    where(conditions) {
        if (Object.keys(conditions).length) {
            const whereConditions = [];
            for (const [key, value] of Object.entries(conditions)) {
                whereConditions.push(`${key} = ?`);
                this.params.push(value);
            }
            this.query += ` WHERE ${whereConditions.join(' AND ')}`;
        }
        return this;
    }

    limit(limit) {
        this.query += ` LIMIT ?`;
        this.params.push(limit);
        return this;
    }

    orderBy(field, direction = 'ASC') {
        this.query += ` ORDER BY ${field} ${direction}`;
        return this;
    }

    insert(table, data) {
        const fields = Object.keys(data);
        const values = Object.values(data);
        const placeholders = new Array(fields.length).fill('?').join(', ');
        
        this.query = `INSERT INTO ${table} (${fields.join(', ')}) VALUES (${placeholders})`;
        this.params = values;
        return this;
    }

    update(table, data) {
        const fields = Object.keys(data).map(key => `${key} = ?`);
        this.query = `UPDATE ${table} SET ${fields.join(', ')}`;
        this.params = Object.values(data);
        return this;
    }

    delete(table) {
        this.query = `DELETE FROM ${table}`;
        return this;
    }

    getQuery() {
        return {
            sql: this.query,
            params: this.params
        };
    }
}

module.exports = QueryBuilder;