diff --git a/index.js b/index.js index 0fb0894..efa6fce 100644 --- a/index.js +++ b/index.js @@ -82,7 +82,7 @@ class PagiHelp { returnString += this.tupleCreator(schemaObject, replacements, asItIs) + " AND "; } else { - let subString = "( "; + let subString = "("; for (let subObject of schemaObject) { subString += this.genSchema(subObject, replacements, asItIs) + " OR "; } @@ -184,7 +184,7 @@ class PagiHelp { "`" + joinQuery; - let totalCountQuery = + let totalCountQuery = "SELECT COUNT(*) AS countValue " + " FROM `" + tableName + @@ -192,27 +192,24 @@ class PagiHelp { joinQuery; let replacements = []; - let whereQuery = " WHERE "; + let whereQuery = ""; if (additionalWhereConditions.length > 0) { - whereQuery += this.genSchema(additionalWhereConditions, replacements, true) + " AND "; + whereQuery += (whereQuery === "" ? " WHERE " : " AND ") + this.genSchema(additionalWhereConditions, replacements, true); } if (filterConditions.length > 0) { - whereQuery += this.genSchema(filterConditions, replacements, false) + " AND "; + whereQuery += (whereQuery === "" ? " WHERE " : " AND ") + this.genSchema(filterConditions, replacements, false); } - if(searchColumnList && searchColumnList.length>0 && paginationObject.search !== "") { - whereQuery = whereQuery + "( "; + if(searchColumnList && searchColumnList.length > 0 && paginationObject.search !== "") { + whereQuery += (whereQuery === "" ? " WHERE " : " AND ") + "("; for (let column of searchColumnList) { - whereQuery = whereQuery + column + " LIKE ? OR "; - replacements.push(`%${paginationObject.search}%`); + whereQuery += column + " LIKE ? OR "; + replacements.push(`%${paginationObject.search}%`); } - whereQuery = rtrim(whereQuery, "OR "); - whereQuery = whereQuery + " )"; - } else { - whereQuery = rtrim(whereQuery, "AND "); + whereQuery = whereQuery.replace(/\s*(AND|OR)\s*$/i, ""); + whereQuery += ")"; } - query = query + whereQuery; countQuery = countQuery + whereQuery;