Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 29 additions & 2 deletions MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -334,8 +334,8 @@ Passing `null` to a parameter of `BooksInsert` or `BooksUpdate` leaves the colum
request, so the database default applies or the value stays unchanged. To write SQL `NULL`, use the
generated `set…ToNull()` methods, which only exist for nullable columns.
A column left out of only some of the rows passed to `insertAll()` or `upsertAll()` also gets its
default, where an untyped `insert()` of a list writes `NULL`. Pass `defaultToNull: true` to write
`NULL` instead.
default, where an untyped `insert()` of a list writes `NULL`. Use `set…ToNull()` on the rows that
should write `NULL`.

An `update()` or `delete()` sends nothing until it says which rows it acts on, through `where()`
or, for every row in the table, `all()`; a bare `await` of it compiles but performs no request,
Expand Down Expand Up @@ -1060,6 +1060,33 @@ analyzer reports every such line as an `unused_result` warning, which is on by d
Anything chained directly after `update()` or `delete()` has to move after the `where()` or `all()`.
`update()` and `delete()` on `from()` are unchanged.

#### Typed inserts and upserts have no `defaultToNull`

The typed `insert()`, `insertAll()`, `upsert()` and `upsertAll()` no longer take `defaultToNull`.
A column left out of an inserted row always gets its database default, and SQL `NULL` is written
with the generated `set…ToNull()` methods. An upsert that merges into an existing row only updates
the columns the request sends, so a column left out of every row keeps its value. On `insert()` and
`upsert()` the parameter had no effect.

```dart skip
// Before
await supabase.table(Books.table).insertAll([
BooksInsert(authorId: 2, title: 'Dune', price: 10),
BooksInsert(authorId: 3, title: 'Emma'),
], defaultToNull: true);
```

```dart
// After
await supabase.table(Books.table).insertAll([
BooksInsert(authorId: 2, title: 'Dune', price: 10),
BooksInsert(authorId: 3, title: 'Emma').setPriceToNull(),
]);
```

`insert()` and `upsert()` on `from()` keep `defaultToNull`. `PostgrestTableRequest` has no
`defaultToNull` either: an executor sends a list payload with `Prefer: missing=default`.

#### Transforms that sent a different request now throw or narrow

These used to compile and send something other than what was asked for:
Expand Down
4 changes: 2 additions & 2 deletions packages/postgrest/lib/src/postgrest_table_executor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ final class PostgrestHttpTableExecutor implements PostgrestTableExecutor {
_rejectFilter(filter, request.operation);
return _query(request).insert(
request.payload!,
defaultToNull: request.defaultToNull,
defaultToNull: request.payload is! List,
);
case PostgrestTableOperation.upsert:
_rejectFilter(filter, request.operation);
Expand All @@ -127,7 +127,7 @@ final class PostgrestHttpTableExecutor implements PostgrestTableExecutor {
?.map((column) => column.name)
.join(','),
ignoreDuplicates: request.ignoreDuplicates,
defaultToNull: request.defaultToNull,
defaultToNull: request.payload is! List,
);
case PostgrestTableOperation.rpc:
return _applyFilter(_call(request), request);
Expand Down
10 changes: 3 additions & 7 deletions packages/postgrest/lib/src/postgrest_table_request.dart
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,6 @@ final class PostgrestTableRequest {
this.readOnly = false,
List<PostgrestStoredColumn<Object?, Object>>? onConflict,
this.ignoreDuplicates = false,
this.defaultToNull = true,
this.returning = false,
this.maxAffected,
this.stripNulls = false,
Expand Down Expand Up @@ -239,6 +238,9 @@ final class PostgrestTableRequest {
/// The rows a mutation sends: one JSON object, or a list of them. For
/// [PostgrestTableOperation.rpc] the arguments of the function call.
///
/// A column left out of some rows of a list gets its database default, and
/// a column set to `null` is written as `NULL`.
///
/// Kept as the caller passed it, not copied: the builders never modify it
/// and an executor must not either. An executor that stores a request for
/// later, an outbox for example, serializes the payload when it takes it.
Expand All @@ -259,10 +261,6 @@ final class PostgrestTableRequest {
/// Whether an upsert skips conflicting rows instead of merging them.
final bool ignoreDuplicates;

/// Whether columns missing from an insert payload become `null` rather
/// than their database default.
final bool defaultToNull;

/// Whether a mutation returns the rows it affected, which a trailing
/// `select` asks for. Without it the response body is empty whatever
/// [shape] says.
Expand Down Expand Up @@ -304,7 +302,6 @@ final class PostgrestTableRequest {
bool? readOnly,
List<PostgrestStoredColumn<Object?, Object>>? onConflict,
bool? ignoreDuplicates,
bool? defaultToNull,
bool? returning,
int? maxAffected,
bool? stripNulls,
Expand All @@ -327,7 +324,6 @@ final class PostgrestTableRequest {
readOnly: readOnly ?? this.readOnly,
onConflict: onConflict ?? this.onConflict,
ignoreDuplicates: ignoreDuplicates ?? this.ignoreDuplicates,
defaultToNull: defaultToNull ?? this.defaultToNull,
returning: returning ?? this.returning,
maxAffected: maxAffected ?? this.maxAffected,
stripNulls: stripNulls ?? this.stripNulls,
Expand Down
42 changes: 12 additions & 30 deletions packages/postgrest/lib/src/postgrest_typed_query_builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -175,16 +175,9 @@ class PostgrestTypedQueryBuilder<Row, Insert, Update> {
/// .single();
/// ```
///
/// See [insertAll] to insert several rows in one request and
/// [PostgrestQueryBuilder.insert] for [defaultToNull].
PostgrestTypedTransformBuilder<Row, void> insert(
Insert row, {
bool defaultToNull = true,
}) => _insertion(
_request(PostgrestTableOperation.insert).copyWith(
payload: row as Object,
defaultToNull: defaultToNull,
),
/// See [insertAll] to insert several rows in one request.
PostgrestTypedTransformBuilder<Row, void> insert(Insert row) => _insertion(
_request(PostgrestTableOperation.insert).copyWith(payload: row as Object),
);

/// Perform an INSERT of every row in [rows] into the table or view.
Expand All @@ -197,17 +190,12 @@ class PostgrestTypedQueryBuilder<Row, Insert, Update> {
/// ```
///
/// An empty [rows] writes nothing. A column left out of a row gets its
/// database default, even when other rows set it. Pass [defaultToNull] as
/// `true` to write `NULL` for it instead.
PostgrestTypedTransformBuilder<Row, void> insertAll(
List<Insert> rows, {
bool defaultToNull = false,
}) => _insertion(
_request(PostgrestTableOperation.insert).copyWith(
payload: rows,
defaultToNull: defaultToNull,
),
);
/// database default, even when other rows set it. Use the generated
/// `set…ToNull` methods of [Insert] to write `NULL` instead.
PostgrestTypedTransformBuilder<Row, void> insertAll(List<Insert> rows) =>
_insertion(
_request(PostgrestTableOperation.insert).copyWith(payload: rows),
);

/// Perform an UPSERT of a single [row] on the table or view.
///
Expand All @@ -225,18 +213,15 @@ class PostgrestTypedQueryBuilder<Row, Insert, Update> {
/// ```
///
/// See [upsertAll] to upsert several rows in one request and
/// [PostgrestQueryBuilder.upsert] for [ignoreDuplicates] and
/// [defaultToNull].
/// [PostgrestQueryBuilder.upsert] for [ignoreDuplicates].
PostgrestTypedTransformBuilder<Row, void> upsert(
Insert row, {
List<PostgrestStoredColumn<Row, Object>>? onConflict,
bool ignoreDuplicates = false,
bool defaultToNull = true,
}) => _upsert(
row as Object,
onConflict: onConflict,
ignoreDuplicates: ignoreDuplicates,
defaultToNull: defaultToNull,
);

/// Perform an UPSERT of every row in [rows] on the table or view.
Expand All @@ -253,27 +238,25 @@ class PostgrestTypedQueryBuilder<Row, Insert, Update> {
///
/// An empty [rows] writes nothing. A column left out of a row that another
/// row sets is written as its database default, also when the row merges
/// into an existing one. See [insertAll] for [defaultToNull].
/// into an existing one. Use the generated `set…ToNull` methods of [Insert]
/// to write `NULL` instead.
///
/// See [upsert] for [onConflict] and [PostgrestQueryBuilder.upsert] for
/// [ignoreDuplicates].
PostgrestTypedTransformBuilder<Row, void> upsertAll(
List<Insert> rows, {
List<PostgrestStoredColumn<Row, Object>>? onConflict,
bool ignoreDuplicates = false,
bool defaultToNull = false,
}) => _upsert(
rows,
onConflict: onConflict,
ignoreDuplicates: ignoreDuplicates,
defaultToNull: defaultToNull,
);

PostgrestTypedTransformBuilder<Row, void> _upsert(
Object values, {
required List<PostgrestStoredColumn<Row, Object>>? onConflict,
required bool ignoreDuplicates,
required bool defaultToNull,
}) {
if (onConflict != null && onConflict.isEmpty) {
throw ArgumentError.value(
Expand All @@ -287,7 +270,6 @@ class PostgrestTypedQueryBuilder<Row, Insert, Update> {
payload: values,
onConflict: onConflict,
ignoreDuplicates: ignoreDuplicates,
defaultToNull: defaultToNull,
),
);
}
Expand Down
12 changes: 8 additions & 4 deletions packages/postgrest/test/basic_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ extension type const UserInsert._(Map<String, dynamic> _json)
implements Object {
UserInsert({required String username, String? status})
: this._({'username': username, 'status': ?status});

UserInsert setStatusToNull() => UserInsert._({..._json, 'status': null});
}

class JsonUserInsert {
Expand Down Expand Up @@ -408,12 +410,14 @@ void main() {
expect(response.last['status'], 'ONLINE');
});

test('typed bulk insert with defaultToNull writes NULL', () async {
test('typed bulk insert writes an explicit NULL', () async {
final response = await postgrest.table(Users.table).insertAll([
UserInsert(username: 'null bot', status: 'OFFLINE'),
UserInsert(username: 'null crazy bot'),
], defaultToNull: true).select();
expect(response.last['status'], null);
UserInsert(username: 'null crazy bot').setStatusToNull(),
UserInsert(username: 'default crazy bot'),
]).select();
expect(response[1]['status'], null);
expect(response[2]['status'], 'ONLINE');
});

test('typed bulk upsert applies column defaults', () async {
Expand Down
2 changes: 0 additions & 2 deletions packages/postgrest/test/table_executor_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -282,14 +282,12 @@ void main() {
BookInsert(title: 'a'),
onConflict: [Books.title],
ignoreDuplicates: true,
defaultToNull: false,
);

final request = executor.onlyRequest;
expect(request.operation, PostgrestTableOperation.upsert);
expect(request.onConflict!.single.name, 'title');
expect(request.ignoreDuplicates, isTrue);
expect(request.defaultToNull, isFalse);
});

test('count reads the count of the result', () async {
Expand Down
47 changes: 39 additions & 8 deletions packages/postgrest/test/typed_query_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ extension type const BookInsert._(Map<String, dynamic> _json)
implements Object {
BookInsert({required String title, int? id})
: this._({'title': title, 'id': ?id});

BookInsert setIdToNull() => BookInsert._({..._json, 'id': null});
}

extension type const BookUpdate._(Map<String, dynamic> _json)
Expand Down Expand Up @@ -1363,6 +1365,8 @@ void main() {

expect(httpClient.requests.last.method, 'POST');
expect(httpClient.requests.last.body, '{"title":"foo"}');
expect(requestParameters()['columns'], isNull);
expect(httpClient.requests.last.headers['Prefer'], isNull);
});

test('insertAll posts every row and applies column defaults', () async {
Expand All @@ -1385,16 +1389,23 @@ void main() {
);
});

test('insertAll with defaultToNull writes NULL for missing keys', () async {
test('insertAll sends an explicit null next to a left out key', () async {
httpClient.stub(null);

await client.table(Books.table).insertAll([
BookInsert(title: 'foo'),
BookInsert(id: 2, title: 'bar'),
], defaultToNull: true);
BookInsert(title: 'bar').setIdToNull(),
]);

expect(
httpClient.requests.last.body,
'[{"title":"foo"},{"title":"bar","id":null}]',
);
expect(requestParameters()['columns'], '"title","id"');
expect(httpClient.requests.last.headers['Prefer'], isNull);
expect(
httpClient.requests.last.headers['Prefer'],
contains('missing=default'),
);
});

test('upsertAll applies column defaults to missing keys', () async {
Expand All @@ -1415,17 +1426,37 @@ void main() {
);
});

test('upsertAll with defaultToNull writes NULL for missing keys', () async {
test('upsertAll sends an explicit null next to a left out key', () async {
httpClient.stub(null);

await client.table(Books.table).upsertAll([
BookInsert(title: 'foo'),
BookInsert(id: 2, title: 'bar'),
], defaultToNull: true);
BookInsert(title: 'bar').setIdToNull(),
]);

expect(
httpClient.requests.last.body,
'[{"title":"foo"},{"title":"bar","id":null}]',
);
expect(requestParameters()['columns'], '"title","id"');
expect(
httpClient.requests.last.headers['Prefer'],
allOf(
contains('resolution=merge-duplicates'),
contains('missing=default'),
),
);
});

test('upsert of a single row sends no missing=default', () async {
httpClient.stub(null);

await client.table(Books.table).upsert(BookInsert(title: 'foo'));

expect(requestParameters()['columns'], isNull);
expect(
httpClient.requests.last.headers['Prefer'],
isNot(contains('missing=default')),
'resolution=merge-duplicates',
);
});

Expand Down
5 changes: 3 additions & 2 deletions packages/supabase/skills/supabase-migrate-v3/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,9 @@ Rules for the conversion:
- Passing `null` to an `Insert` or `Update` parameter leaves the column out.
Use the generated `set…ToNull()` method to write SQL `NULL`.
- `insertAll()` and `upsertAll()` give a column left out of only some rows its
database default, where the untyped list `insert()` wrote `NULL`. Pass
`defaultToNull: true` where the code relied on `NULL`.
database default, where the untyped list `insert()` wrote `NULL`, and take
no `defaultToNull`. Where the code relied on `NULL`, call `set…ToNull()` on
those rows.
- Replace `row['title'] as String` with `row.title` wherever the rows are
consumed. A model class that only mirrors a table is replaced by the
generated row type. A model that adds behavior is built from the row
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,8 +247,9 @@ Rules for the conversion:
- Passing `null` to an `Insert` or `Update` parameter leaves the column out.
Use the generated `set…ToNull()` method to write SQL `NULL`.
- `insertAll()` and `upsertAll()` give a column left out of only some rows its
database default, where the untyped list `insert()` wrote `NULL`. Pass
`defaultToNull: true` where the code relied on `NULL`.
database default, where the untyped list `insert()` wrote `NULL`, and take
no `defaultToNull`. Where the code relied on `NULL`, call `set…ToNull()` on
those rows.
- Replace `row['title'] as String` with `row.title` wherever the rows are
consumed. A model class that only mirrors a table is replaced by the
generated row type. A model that adds behavior is built from the row
Expand Down
4 changes: 3 additions & 1 deletion sdk-compliance.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -931,7 +931,6 @@ features:
- PostgrestTableRequest.readOnly
- PostgrestTableRequest.onConflict
- PostgrestTableRequest.ignoreDuplicates
- PostgrestTableRequest.defaultToNull
- PostgrestTableRequest.maxAffected
- PostgrestTableRequest.stripNulls
- PostgrestTableRequest.dryRun
Expand Down Expand Up @@ -1289,6 +1288,7 @@ features:
# database — mutate
database.mutate.insert:
status: implemented
note: "The typed insertAll and upsertAll always send Prefer: missing=default and take no defaultToNull, since their Insert types tell an absent field from an explicit null; the untyped insert and upsert keep defaultToNull with its default of true. The spec change is proposed in https://github.com/supabase/sdk/pull/306."
symbols:
- PostgrestQueryBuilder.insert
- PostgrestTypedQueryBuilder.insert
Expand All @@ -1304,6 +1304,7 @@ features:
- PostgrestTypedUnscopedBuilder.where
database.mutate.upsert:
status: implemented
note: "The typed insertAll and upsertAll always send Prefer: missing=default and take no defaultToNull, since their Insert types tell an absent field from an explicit null; the untyped insert and upsert keep defaultToNull with its default of true. The spec change is proposed in https://github.com/supabase/sdk/pull/306."
symbols:
- PostgrestQueryBuilder.upsert
- PostgrestTypedQueryBuilder.upsert
Expand Down Expand Up @@ -1335,6 +1336,7 @@ features:
- PostgrestTypedQueryBuilder.upsertAll
database.mutate.missing_defaults:
status: implemented
note: "The typed insertAll and upsertAll always send Prefer: missing=default and take no defaultToNull, since their Insert types tell an absent field from an explicit null; the untyped insert and upsert keep defaultToNull with its default of true. The spec change is proposed in https://github.com/supabase/sdk/pull/306."
symbols:
- PostgrestQueryBuilder.insert
- PostgrestQueryBuilder.upsert
Expand Down
Loading
Loading