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

Commit 3a902b3

Browse files
authored
feat: implement on_conflict (#113)
1 parent f887ed4 commit 3a902b3

File tree

3 files changed

+39
-1
lines changed

3 files changed

+39
-1
lines changed

src/builder.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,12 +125,17 @@ export class PostgrestQueryBuilder<T> extends PostgrestBuilder<T> {
125125
*
126126
* @param values The values to insert.
127127
* @param upsert If `true`, performs an UPSERT.
128+
* @param onConflict By specifying the `on_conflict` query parameter, you can make UPSERT work on a column(s) that has a UNIQUE constraint.
128129
*/
129-
insert(values: Partial<T> | Partial<T>[], { upsert = false } = {}): PostgrestBuilder<T> {
130+
insert(
131+
values: Partial<T> | Partial<T>[],
132+
{ upsert = false, onConflict }: { upsert?: boolean; onConflict?: string } = {}
133+
): PostgrestBuilder<T> {
130134
this.method = 'POST'
131135
this.headers['Prefer'] = upsert
132136
? 'return=representation,resolution=merge-duplicates'
133137
: 'return=representation'
138+
if (upsert && onConflict !== undefined) this.url.searchParams.set('on_conflict', onConflict)
134139
this.body = values
135140
return this
136141
}

test/__snapshots__/basic.test.ts.snap

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -595,6 +595,32 @@ Object {
595595
}
596596
`;
597597

598+
exports[`on_conflict insert 1`] = `
599+
Object {
600+
"body": Array [
601+
Object {
602+
"age_range": "[20,30)",
603+
"catchphrase": "'fat' 'rat'",
604+
"data": null,
605+
"status": "ONLINE",
606+
"username": "dragarcia",
607+
},
608+
],
609+
"data": Array [
610+
Object {
611+
"age_range": "[20,30)",
612+
"catchphrase": "'fat' 'rat'",
613+
"data": null,
614+
"status": "ONLINE",
615+
"username": "dragarcia",
616+
},
617+
],
618+
"error": null,
619+
"status": 201,
620+
"statusText": "Created",
621+
}
622+
`;
623+
598624
exports[`stored procedure 1`] = `
599625
Object {
600626
"body": "ONLINE",

test/basic.test.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,13 @@ test('switch schema', async () => {
2929
expect(res).toMatchSnapshot()
3030
})
3131

32+
test('on_conflict insert', async () => {
33+
const res = await postgrest
34+
.from('users')
35+
.insert({ username: 'dragarcia' }, { upsert: true, onConflict: 'username' })
36+
expect(res).toMatchSnapshot()
37+
})
38+
3239
describe('basic insert, update, delete', () => {
3340
test('basic insert', async () => {
3441
let res = await postgrest

0 commit comments

Comments
 (0)