JSFiddle - React, Tailwind, and code Playground

by parksd

JavaScript

function SqlBuilder() {
    this.queryParts = {
        type: null,
        select: [],
        from: null,
        group: [],
        where: [],
        order: [],
        values: [],
        update: null,
        set: [],
        insert: null,
    };
}

SqlBuilder.prototype.select = function () {
    this.queryParts.select.push("*");
    return this;
};

SqlBuilder.prototype.from = function (source, alias) {
    if (source instanceof SqlBuilder) {
        this.queryParts.from = "(" + source.toString() + ")" + (alias ? " AS `" + alias + "`" : "");
    } else {
        this.queryParts.from = source;
    }
    return this;
};

SqlBuilder.prototype.field = function (field, alias) {
    if (field instanceof SqlBuilder) {
        this.queryParts.select.push("(" + field.toString() + ")" + (alias ? ' AS "' + alias + '"' : ""));
    } else {
        this.queryParts.select.push(field);
    }
    return this;
};

SqlBuilder.prototype.group = function (groupField) {
    this.queryParts.group.push(groupField);
    return this;
};

SqlBuilder.prototype.where = function (condition, ...params) {
    this.queryParts.where.push(condition);
    for (let param of params) {
        if (param instanceof SqlBuilder) {
            // Replace the placeholder with the subquery's SQL string and append its values
            let lastIndex = this.queryParts.where.length - 1;
            this.queryParts.where[lastIndex] = this.queryParts.where[lastIndex].replace(
                /\?/,
                "(" + param.toString() + ")"
            );
            this.queryParts.values.push(...param.queryParts.values);
        } else {
            this.queryParts.values.push(param);
        }
    }
    return this;
};

SqlBuilder.prototype.order = function (field, orderDirection, ...params) {
    var orderClause = field + (orderDirection === "DESC" ? " DESC" : " ASC");
    this.queryParts.order.push(orderClause);
    this.queryParts.values.push(...params);
    return...