Skip to content

Commit e781bc1

Browse files
rosswaycastersoedirgo
authored andcommitted
feat: add ignoreDuplicates option to upsert
1 parent db3a70b commit e781bc1

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

packages/core/postgrest-js/src/lib/PostgrestQueryBuilder.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,22 +125,28 @@ export default class PostgrestQueryBuilder<T> extends PostgrestBuilder<T> {
125125
* @param onConflict By specifying the `on_conflict` query parameter, you can make UPSERT work on a column(s) that has a UNIQUE constraint.
126126
* @param returning By default the new record is returned. Set this to 'minimal' if you don't need this value.
127127
* @param count Count algorithm to use to count rows in a table.
128+
* @param ignoreDuplicates Specifies if duplicate rows should be ignored and not inserted.
128129
*/
129130
upsert(
130131
values: Partial<T> | Partial<T>[],
131132
{
132133
onConflict,
133134
returning = 'representation',
134135
count = null,
136+
ignoreDuplicates = false,
135137
}: {
136138
onConflict?: string
137139
returning?: 'minimal' | 'representation'
138140
count?: null | 'exact' | 'planned' | 'estimated'
141+
ignoreDuplicates?: boolean
139142
} = {}
140143
): PostgrestFilterBuilder<T> {
141144
this.method = 'POST'
142145

143-
const prefersHeaders = ['resolution=merge-duplicates', `return=${returning}`]
146+
const prefersHeaders = [
147+
`resolution=${ignoreDuplicates ? 'ignore' : 'merge'}-duplicates`,
148+
`return=${returning}`,
149+
]
144150

145151
if (onConflict !== undefined) this.url.searchParams.set('on_conflict', onConflict)
146152
this.body = values

packages/core/postgrest-js/test/__snapshots__/index.test.ts.snap

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1122,6 +1122,17 @@ Object {
11221122
}
11231123
`;
11241124

1125+
exports[`ignoreDuplicates upsert 1`] = `
1126+
Object {
1127+
"body": Array [],
1128+
"count": null,
1129+
"data": Array [],
1130+
"error": null,
1131+
"status": 201,
1132+
"statusText": "Created",
1133+
}
1134+
`;
1135+
11251136
exports[`insert, update, delete with count: 'exact' basic delete count: 'exact' 1`] = `
11261137
Object {
11271138
"body": Array [

packages/core/postgrest-js/test/basic.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,13 @@ test('on_conflict insert', async () => {
4141
expect(res).toMatchSnapshot()
4242
})
4343

44+
test('ignoreDuplicates upsert', async () => {
45+
const res = await postgrest
46+
.from('users')
47+
.upsert({ username: 'dragarcia' }, { onConflict: 'username', ignoreDuplicates: true })
48+
expect(res).toMatchSnapshot()
49+
})
50+
4451
describe('basic insert, update, delete', () => {
4552
test('basic insert', async () => {
4653
let res = await postgrest

0 commit comments

Comments
 (0)