-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdate.ts
More file actions
51 lines (42 loc) · 1.31 KB
/
update.ts
File metadata and controls
51 lines (42 loc) · 1.31 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
import { UpdatePayload, WhereCondition } from "../types";
import { buildSetClause, buildWhereClause } from "../utils";
import { BaseQueryBuilder } from "./base";
export class UpdateQueryBuilder<T> extends BaseQueryBuilder<T> {
private payload: UpdatePayload<T> = { where: {}, data: {} };
set(data: Partial<T>): this {
this.payload.data = data;
return this;
}
where(condition: WhereCondition<T>): this {
this.payload.where = condition;
return this;
}
returning(columns?: Array<keyof T>): this {
this.payload.returning = columns;
return this;
}
build(): { sql: string; values: any[] } {
// Build WHERE clause
const { whereClause, values: whereValues } = buildWhereClause(
this.payload.where,
this.tableName
);
// Build SET clause using the where values as starting point
const { setClause, values: allValues } = buildSetClause(
this.payload.data,
whereValues
);
// Handle columns for RETURNING
const returningColumns = this.payload.returning
? this.payload.returning.join(", ")
: "*";
// Build final SQL query
const sql = `
UPDATE "${this.tableName}"
SET ${setClause}
${whereClause ? `WHERE ${whereClause}` : ""}
RETURNING ${returningColumns};
`;
return { sql, values: allValues };
}
}