upsert method

PostgrestFilterBuilder<T> upsert(
  1. Object values, {
  2. String? onConflict,
  3. bool ignoreDuplicates = false,
  4. bool defaultToNull = true,
})

Perform an UPSERT on the table or view.

By specifying the onConflict parameter, you can make UPSERT work on a column(s) that has a UNIQUE constraint. ignoreDuplicates Specifies if duplicate rows should be ignored and not inserted.

By default no data is returned. Use a trailing select to return data.

When inserting multiple rows in bulk, defaultToNull is used to set the values of fields missing in a proper subset of rows to be either NULL or the default value of these columns. Fields missing in all rows always use the default value of these columns.

For single row insertions, missing fields will be set to default values when applicable.

Default (not returning data):

await supabase.from('messages').upsert({
  'id': 3,
  'message': 'foo',
  'username': 'supabot',
  'channel_id': 2
});

Returning data:

final data = await supabase.from('messages').upsert({
  'message': 'foo',
  'username': 'supabot',
  'channel_id': 1
}).select();

Implementation

PostgrestFilterBuilder<T> upsert(
  Object values, {
  String? onConflict,
  bool ignoreDuplicates = false,
  bool defaultToNull = true,
}) {
  final newHeaders = {..._headers};
  newHeaders['Prefer'] =
      'resolution=${ignoreDuplicates ? 'ignore' : 'merge'}-duplicates';

  if (!defaultToNull) {
    newHeaders['Prefer'] = '${newHeaders['Prefer']!},missing=default';
  }
  Uri url = _url;
  if (onConflict != null) {
    url = _url.replace(
      queryParameters: {
        'on_conflict': onConflict,
        ..._url.queryParameters,
      },
    );
  }

  if (values is List) {
    url = _setColumnsSearchParam(values);
  }

  return PostgrestFilterBuilder<T>(_copyWith(
    method: METHOD_POST,
    headers: newHeaders,
    body: values,
    url: url,
  ));
}