-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselect.ts
More file actions
159 lines (134 loc) · 3.93 KB
/
select.ts
File metadata and controls
159 lines (134 loc) · 3.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import { SQLKITException } from "../exceptions";
import {
Join,
OrderBy,
PaginatedResult,
PaginationMeta,
PaginationOptions,
QueryRowsPayload,
WhereCondition
} from "../types";
import {
buildJoinClause,
buildOrderByClause,
buildWhereClause
} from "../utils";
import { BaseQueryBuilder } from "./base";
export class SelectQueryBuilder<T> extends BaseQueryBuilder<T> {
private payload: QueryRowsPayload<T> = {};
select(columns?: Array<keyof T>): this {
this.payload.columns = columns;
return this;
}
where(condition: WhereCondition<T>): this {
this.payload.where = condition;
return this;
}
join<F>(join: Join<T, F>): this {
if (!this.payload.joins) {
this.payload.joins = [];
}
this.payload.joins.push(join);
return this;
}
orderBy(orderBy: OrderBy<T> | Array<OrderBy<T>>): this {
if (!this.payload.orderBy) {
this.payload.orderBy = [];
}
if (Array.isArray(orderBy)) {
this.payload.orderBy.push(...orderBy);
} else {
this.payload.orderBy.push(orderBy);
}
return this;
}
limit(limit: number): this {
this.payload.limit = limit;
return this;
}
offset(offset: number): this {
this.payload.offset = offset;
return this;
}
build(): { sql: string; values: any[] } {
// Default columns to '*' if none are provided
const columns =
this.payload.columns
?.map((col) => `"${this.tableName}"."${col.toString()}"`)
.join(",") ?? `"${this.tableName}".*`;
const { whereClause, values } = buildWhereClause(
this.payload.where,
this.tableName
);
const orderByClause = buildOrderByClause(
this.payload.orderBy,
this.tableName
);
const { joinConditionClause, joinSelectClause } = buildJoinClause(
this.payload.joins,
this.tableName
);
// Build the SQL query with LIMIT, OFFSET, and ORDER BY
const limit = this?.payload?.limit ?? undefined;
const offset = this.payload.offset ?? 0;
const sql = `
SELECT ${columns}
${joinSelectClause.length > 0 ? `,${joinSelectClause.join(",")}` : ""}
FROM "${this.tableName}"
${joinConditionClause ? joinConditionClause : ""}
${whereClause ? `WHERE ${whereClause}` : ""}
${orderByClause ? orderByClause : ""}
${(limit !== undefined && limit !== -1) ? `LIMIT ${limit}` : ""} ${offset ? `OFFSET ${offset}` : ""};
`;
return { sql, values };
}
async paginate(options: PaginationOptions<T>): Promise<PaginatedResult<T>> {
if (!this?.executor) {
throw new SQLKITException("Executor is not set for the query builder.");
}
const limit = options.limit || 10;
const page = options.page || 1;
const offset = (page - 1) * limit;
// Set pagination options
this.limit(limit);
this.offset(offset);
// Execute the main query for data
const result = await this.commit();
const nodes = result.rows as T[];
// Execute count query for pagination metadata
const countBuilder = new SelectQueryBuilder<T>(
this.tableName,
this.executor
);
if (options.where) {
countBuilder.where(options.where);
}
if (options.joins) {
options.joins.forEach((join) => countBuilder.join(join));
}
const countSql = `
SELECT COUNT(*) as count
FROM ${this.tableName}
${
buildWhereClause(options.where, this.tableName).whereClause
? `WHERE ${buildWhereClause(options.where, this.tableName).whereClause}`
: ""
}
`;
const countResult: any = await this.executor.executeSQL(
countSql,
buildWhereClause(options.where, this.tableName).values
);
const totalCount = parseInt(countResult.rows[0].count, 10);
const meta: PaginationMeta = {
totalCount,
currentPage: page,
hasNextPage: page * limit < totalCount,
totalPages: limit === -1 ? 1 : Math.ceil(totalCount / limit)
};
return {
nodes,
meta
};
}
}