Skip to content
This repository was archived by the owner on Oct 9, 2025. It is now read-only.

Commit 0593e1a

Browse files
committed
feat: make UPSERT its own function
1 parent ef77624 commit 0593e1a

File tree

1 file changed

+55
-2
lines changed

1 file changed

+55
-2
lines changed

src/lib/PostgrestQueryBuilder.ts

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,28 @@ export default class PostgrestQueryBuilder<T> extends PostgrestBuilder<T> {
5858
* Performs an INSERT into the table.
5959
*
6060
* @param values The values to insert.
61-
* @param upsert If `true`, performs an UPSERT.
62-
* @param onConflict By specifying the `on_conflict` query parameter, you can make UPSERT work on a column(s) that has a UNIQUE constraint.
6361
* @param returning By default the new record is returned. Set this to 'minimal' if you don't need this value.
62+
* @param count Count algorithm to use to count rows in a table.
63+
*/
64+
insert(
65+
values: Partial<T> | Partial<T>[],
66+
options?: {
67+
returning?: 'minimal' | 'representation'
68+
count?: null | 'exact' | 'planned' | 'estimated'
69+
}
70+
): PostgrestFilterBuilder<T>
71+
/**
72+
* @deprecated Use `upsert()` instead.
6473
*/
74+
insert(
75+
values: Partial<T> | Partial<T>[],
76+
options?: {
77+
upsert?: boolean
78+
onConflict?: string
79+
returning?: 'minimal' | 'representation'
80+
count?: null | 'exact' | 'planned' | 'estimated'
81+
}
82+
): PostgrestFilterBuilder<T>
6583
insert(
6684
values: Partial<T> | Partial<T>[],
6785
{
@@ -92,6 +110,41 @@ export default class PostgrestQueryBuilder<T> extends PostgrestBuilder<T> {
92110
return new PostgrestFilterBuilder(this)
93111
}
94112

113+
/**
114+
* Performs an UPSERT into the table.
115+
*
116+
* @param values The values to insert.
117+
* @param onConflict By specifying the `on_conflict` query parameter, you can make UPSERT work on a column(s) that has a UNIQUE constraint.
118+
* @param returning By default the new record is returned. Set this to 'minimal' if you don't need this value.
119+
* @param count Count algorithm to use to count rows in a table.
120+
*/
121+
upsert(
122+
values: Partial<T> | Partial<T>[],
123+
{
124+
onConflict,
125+
returning = 'representation',
126+
count = null,
127+
}: {
128+
onConflict?: string
129+
returning?: 'minimal' | 'representation'
130+
count?: null | 'exact' | 'planned' | 'estimated'
131+
} = {}
132+
): PostgrestFilterBuilder<T> {
133+
this.method = 'POST'
134+
135+
const prefersHeaders = ['resolution=merge-duplicates', `return=${returning}`]
136+
137+
if (onConflict !== undefined) this.url.searchParams.set('on_conflict', onConflict)
138+
this.body = values
139+
if (count) {
140+
prefersHeaders.push(`count=${count}`)
141+
}
142+
143+
this.headers['Prefer'] = prefersHeaders.join(',')
144+
145+
return new PostgrestFilterBuilder(this)
146+
}
147+
95148
/**
96149
* Performs an UPDATE on the table.
97150
*

0 commit comments

Comments
 (0)