Refactor select count strategy. Run the count query together with the normal query
This commit is contained in:
@@ -44,10 +44,9 @@ export default async function DbSelect<
|
||||
sqlObj = sqlGenerator({
|
||||
tableName: table,
|
||||
genObject: finalQuery,
|
||||
count,
|
||||
});
|
||||
|
||||
const sql = mysql.format(sqlObj.string, sqlObj.values);
|
||||
let sql = mysql.format(sqlObj.string, sqlObj.values);
|
||||
|
||||
const res = DbClient.query<Schema, Schema[]>(sql);
|
||||
const batchRes = res.all();
|
||||
@@ -63,11 +62,24 @@ export default async function DbSelect<
|
||||
};
|
||||
|
||||
if (count) {
|
||||
const count_val = count ? batchRes[0]?.["COUNT(*)"] : undefined;
|
||||
resp["count"] = Number(count_val);
|
||||
let count_sql_object = sqlGenerator({
|
||||
tableName: table,
|
||||
genObject: finalQuery,
|
||||
count,
|
||||
});
|
||||
|
||||
delete resp.payload;
|
||||
delete resp.singleRes;
|
||||
let count_sql = mysql.format(
|
||||
count_sql_object.string,
|
||||
count_sql_object.values,
|
||||
);
|
||||
|
||||
count_sql = `SELECT COUNT(*) FROM (${count_sql}) as c`;
|
||||
|
||||
const count_res = DbClient.query<Schema, Schema[]>(count_sql).all();
|
||||
|
||||
const count_val = count_res[0]?.["COUNT(*)"];
|
||||
resp["count"] = Number(count_val);
|
||||
resp["debug"]["count_sql"] = count_sql;
|
||||
}
|
||||
|
||||
return resp;
|
||||
|
||||
@@ -221,9 +221,7 @@ export default function sqlGenerator<
|
||||
let queryString = (() => {
|
||||
let str = "SELECT";
|
||||
|
||||
if (count) {
|
||||
str += ` COUNT(*)`;
|
||||
} else if (genObject?.selectFields?.[0]) {
|
||||
if (genObject?.selectFields?.[0]) {
|
||||
if (genObject.join) {
|
||||
str += ` ${genObject.selectFields
|
||||
?.map((fld) =>
|
||||
@@ -295,7 +293,7 @@ export default function sqlGenerator<
|
||||
str += `, ${countSqls.join(",")}`;
|
||||
}
|
||||
|
||||
if (genObject?.join && !count) {
|
||||
if (genObject?.join) {
|
||||
const existingJoinTableNames: string[] = [tableName];
|
||||
|
||||
str +=
|
||||
@@ -493,7 +491,7 @@ export default function sqlGenerator<
|
||||
return orderSrt;
|
||||
}
|
||||
|
||||
if (genObject?.order && !count) {
|
||||
if (genObject?.order) {
|
||||
let orderSrt = ` ORDER BY`;
|
||||
|
||||
if (Array.isArray(genObject.order)) {
|
||||
@@ -514,7 +512,7 @@ export default function sqlGenerator<
|
||||
|
||||
if (genObject?.limit && !count) queryString += ` LIMIT ${genObject.limit}`;
|
||||
|
||||
if (genObject?.offset && !count) {
|
||||
if (genObject?.offset) {
|
||||
queryString += ` OFFSET ${genObject.offset}`;
|
||||
} else if (genObject?.page && genObject.limit && !count) {
|
||||
queryString += ` OFFSET ${(genObject.page - 1) * genObject.limit}`;
|
||||
|
||||
Reference in New Issue
Block a user