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
14 changes: 9 additions & 5 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,11 +245,15 @@ await Supabase.initialize(
"Package skills" CI check fails. The script also pads every Markdown table.
The skills symlink `MIGRATION.md`, so links in it must be absolute URLs or
anchors
- Every ```dart block in a skill must compile: `melos run check-skill-snippets`
analyzes them against the workspace and the supabase_typegen schema golden.
A plain block is checked as a function body, ```dart file as a whole
library, ```dart test and ```dart test-file are also run as tests, and
```dart skip is not checked, for code such as v2 "before" examples
- Every ```dart block in a skill or a package README must compile:
`melos run check-skill-snippets` analyzes them against the workspace and the
supabase_typegen schema golden. A plain block is checked as a function body,
```dart file as a whole library, ```dart test and ```dart test-file are also
run as tests, and ```dart skip is not checked, for code such as v2 "before"
examples or code that needs a third-party package. A whole library gets no
imports injected, so it imports everything it uses, the schema as
`package:my_app/supabase_schema.g.dart`. MIGRATION.md, which the
migrate-v3 skills link, is not checked
- Line length limit is 80 characters
- Use `dart format` for consistent formatting

Expand Down
76 changes: 69 additions & 7 deletions MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,14 +179,21 @@ if (search != null) filter = filter & Books.title.ilike('%$search%');
final books = await supabase.table(Books.table).select().where(filter);
```

For an operator the API has no method for, `raw()` on a column keeps the column checked and takes
the operand as PostgREST spells it, `Books.title.raw('eq.Dune')`. `PostgrestFilter.raw` takes both
sides as strings, for an expression no column constant can name:
A JSON path is built on the column, with `jsonText()` for a key read as text and `jsonObject()`
to go deeper, and filters like any other column:

```dart
.where(PostgrestFilter.raw('metadata->>edition', 'eq.first'))
// Before
.eq('metadata->>edition', 'first')

// After
.where(Books.metadata.jsonText('edition').eq('first'))
```

For an operator the API has no method for, `raw()` on a column keeps the column checked and takes
the operand as PostgREST spells it, `Books.title.raw('eq.Dune')`. `PostgrestFilter.raw` takes both
sides as strings, for an expression no column constant or JSON path can name.

#### Ordering, pagination and single rows

The direction of an ordering is spelled on the column:
Expand Down Expand Up @@ -391,6 +398,10 @@ final List<String> titles = [

A to-one relation reads back as a nullable partial row and a to-many relation as a list of them.

The typed API cannot filter inside an embed yet, and has no `!inner` embed that drops the parent
rows without a match. Keep a query that needs either on `from()`, for example
`.select('title, authors!inner(name)').eq('authors.name', 'Frank Herbert')`.

When two foreign keys point at the same table, the generator adds the constraint hint and an alias,
so each embed comes back under its own key without spelling `authors!books_author_id_fkey` by hand.

Expand Down Expand Up @@ -494,6 +505,12 @@ explicitly:
- [Realtime throws exceptions instead of strings](#realtime-throws-exceptions-instead-of-strings),
so a catch of `String` or a `toString()` comparison around `subscribe()` or `httpSend()` no
longer matches
- [Broadcasts no longer fall back to the REST API](#broadcasts-no-longer-fall-back-to-the-rest-api),
so `sendBroadcastMessage()` on a channel that was never subscribed throws
- [Storage uploads return an `UploadResponse`](#storage-uploads-return-an-uploadresponse), so a
result stored in `var` or interpolated into a string is no longer the key
- [`exists()` only returns `false` for a missing object](#exists-only-returns-false-for-a-missing-object),
so a missing bucket or an invalid token throws instead of returning `false`
- [An `Authorization` header passed to `SupabaseClient` reaches the auth client](#an-authorization-header-passed-to-supabaseclient-reaches-the-auth-client)
- [Broadcast data arrives under `payload`](#broadcast-data-arrives-under-payload), so code that
reads the sent keys from the top of the received message gets `null`
Expand Down Expand Up @@ -579,6 +596,7 @@ runWithClient(() {
final supabase = SupabaseClient(
supabaseUrl,
supabaseKey,
authOptions: AuthClientOptions(asyncStorage: MemoryAuthAsyncStorage()),
httpClient: MockClient(handler),
);
```
Expand Down Expand Up @@ -1577,6 +1595,40 @@ Without `hierarchicalLoggingEnabled = true`, listen on `Logger.root` and filter

### Storage

#### Storage uploads return an `UploadResponse`

`upload`, `uploadBinary`, `update`, `updateBinary`, `uploadToSignedUrl` and
`uploadBinaryToSignedUrl` return an `UploadResponse` instead of a `String`. The uploads used to
return the key, the path prefixed with the bucket id, which is now `fullPath`. The signed URL
uploads used to return the path within the bucket, which is now `path`. Code that keeps the result
in a `var` or interpolates it into a string still compiles, but gets the whole response:

```dart
// Before
final key = await supabase.storage.from('avatars').upload('avatar.png', file);

// After
final response = await supabase.storage.from('avatars').upload('avatar.png', file);
final key = response.fullPath;
```

`UploadResponse` also carries the `id` of the stored object, and `versionId` for a resumable upload.

#### `exists()` only returns `false` for a missing object

`exists()` used to send a `HEAD` request and return `false` for any 400 or 404 response. It now
reads the object's metadata and returns `false` only when storage reports the object missing. A
missing bucket or an invalid token throws a `StorageApiException` instead:

```dart
try {
final found = await supabase.storage.from('avatars').exists('avatar.png');
print(found ? 'found' : 'missing');
} on StorageApiException catch (error) {
print('could not check: ${error.errorCode}');
}
```

#### `createSignedUrls` reports per-path failures

`createSignedUrls` returns a list of `SignedUrlSuccess` and `SignedUrlFailure` instead of
Expand Down Expand Up @@ -1910,8 +1962,7 @@ exception for token failures. An exception that is already a `SupabaseException`
| --------------------------------------------------------------- | ------------------------------------------------------------------------ |
| `subscribe()` called twice throws a `String` | `StateError` |
| `onPostgresChanges()` after `subscribe()` throws a `String` | `StateError` |
| `send()` or `track()` before `subscribe()` throws a `String` | `StateError` |
| `ChannelEvent.fromValue` with an unknown name throws a `String` | `ArgumentError` |
| `track()` or `untrack()` before `subscribe()` throws a `String` | `StateError` |
| `httpSend()` times out with a `TimeoutException` | `RealtimeTransportException` with the `TimeoutException` as `cause` |
| `httpSend()` gets a non-202 status, as `Exception(message)` | `RealtimeApiException` with `statusCode`, `requestId`, `headers`, `body` |
| `onStatusChange` reports `channelError` with an `Exception` | `RealtimeException` with the server's reason as `message` |
Expand Down Expand Up @@ -2058,7 +2109,18 @@ takes `jsonCodec:` too.
final client = SupabaseClient(url, key, isolate: YAJsonIsolate()..initialize());

// After
final client = SupabaseClient(url, key, jsonCodec: YAJsonIsolate());
final jsonCodec = YAJsonIsolate();
final client = SupabaseClient(
url,
key,
authOptions: AuthClientOptions(asyncStorage: MemoryAuthAsyncStorage()),
Comment thread
spydon marked this conversation as resolved.
Resolved
jsonCodec: jsonCodec,
);

// A codec passed in belongs to the caller. Dispose it after every client that
// uses it.
await client.dispose();
await jsonCodec.dispose();
```

`YAJsonIsolate.initialize()` is removed, because there is nothing to initialize, so delete the
Expand Down
1 change: 1 addition & 0 deletions packages/postgrest/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ to `table()`. Filters are methods on the column constants, so the compiler
checks every column name and value:

```dart file
import 'package:my_app/supabase_schema.g.dart';
import 'package:postgrest/postgrest.dart';

Future<void> main() async {
Expand Down
6 changes: 6 additions & 0 deletions packages/supabase/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,14 @@ import 'package:supabase/supabase.dart';
final supabase = SupabaseClient(
'https://your-project.supabase.co',
'your-publishable-key',
authOptions: AuthClientOptions(asyncStorage: MemoryAuthAsyncStorage()),
);
```

A client without an `asyncStorage` throws when it is created, since the
default PKCE flow keeps its code verifiers there. `MemoryAuthAsyncStorage`
keeps them, and the session, in memory for as long as the process runs.

### 3. Generate the typed schema

Queries are typed by a Dart file generated from your database schema. It
Expand Down Expand Up @@ -164,6 +169,7 @@ token of that request as the `Authorization` header of the call. The client only
`Authorization` header when the request has none:

```dart file
import 'package:my_app/supabase_schema.g.dart';
import 'package:supabase/supabase.dart';

Future<List<BooksRow>> booksOfUser(
Expand Down
33 changes: 20 additions & 13 deletions packages/supabase/skills/supabase-idioms/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ it against this file. To upgrade an existing v2 project, use the
## Client setup

```dart file
import 'package:supabase/supabase.dart';

final supabase = SupabaseClient(
'https://your-project.supabase.co',
'your-publishable-key',
Expand Down Expand Up @@ -147,21 +149,26 @@ final user = session.user;
complete without a session.

`AuthState` is sealed, with one subtype per event. Every new listener first
receives `AuthInitialSession` with the current session or `null`:
receives `AuthInitialSession` with the current session or `null`. A failed
token refresh, for example while offline, is an error of the stream, so every
listener passes `onError`:

```dart
final subscription = supabase.auth.onAuthStateChange.listen((state) {
switch (state) {
case AuthInitialSession(:final session):
// The session when this listener attached, or null.
print(session?.user.id);
case AuthSignedIn(:final session):
print('Signed in as ${session.user.email}');
case AuthSignedOut():
print('Signed out');
case _:
}
});
final subscription = supabase.auth.onAuthStateChange.listen(
(state) {
switch (state) {
case AuthInitialSession(:final session):
// The session when this listener attached, or null.
print(session?.user.id);
case AuthSignedIn(:final session):
print('Signed in as ${session.user.email}');
case AuthSignedOut():
print('Signed out');
case _:
}
},
onError: (Object error) => print('Auth error: $error'),
);
```

`user.userMetadata` is never null, and `user.appMetadata` is an
Expand Down
4 changes: 3 additions & 1 deletion packages/supabase/skills/supabase-migrate-v3/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,13 +243,15 @@ Rules for the conversion:
generated row type. A model that adds behavior is built from the row
getters, not from `toJson()`.
- An operator with no typed method uses `Books.title.raw('eq.Dune')`. A filter
on a JSON path uses `PostgrestFilter.raw('metadata->>edition', 'eq.first')`.
on a JSON path uses `Books.metadata.jsonText('edition').eq('first')`.

`from()` and the untyped `rpc('fn', params: …)` remain only for:

- a table, view or function missing from the generated file because its
schema was not generated or is not exposed through the Data API,
- a table name computed at runtime,
- a filter inside an embed, such as `.eq('authors.name', 'Frank Herbert')`,
or an `!inner` embed, which the typed API does not support yet,
- a function the generator gives no method, which it explains in a comment in
the generated file.

Expand Down
19 changes: 13 additions & 6 deletions packages/supabase/skills/supabase-realtime/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,15 +131,22 @@ current client's state.

## Status, errors and cleanup

`onStatusChange` reports the subscription status, and errors such as a join
the server declined arrive as `RealtimeException` errors on it:
`onStatusChange` reports the subscription status. A failure, such as a join
the server declined, is a `channelError` status that carries the
`RealtimeException` as `change.error`, not an error of the stream:

```dart
final channel = supabase.channel('room-1');
channel.onStatusChange.listen(
(change) => print('Channel is ${change.status.name}'),
onError: (Object error) => print('Channel failed: $error'),
);
channel.onStatusChange.listen((change) {
switch (change.status) {
case RealtimeSubscribeStatus.channelError:
print('Channel failed: ${change.error}');
case RealtimeSubscribeStatus.timedOut:
print('Channel timed out');
case _:
print('Channel is ${change.status.name}');
}
});
channel.subscribe();

await supabase.removeChannel(channel);
Expand Down
25 changes: 25 additions & 0 deletions packages/supabase_auth/test/refresh_retry_test.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'dart:async';

import 'package:http/http.dart';
import 'package:supabase_auth/supabase_auth.dart';
import 'package:test/test.dart';

Expand Down Expand Up @@ -99,4 +100,28 @@ void main() {
);
});
});

test('an offline refresh is an error of onAuthStateChange', () async {
final httpClient = MockSupabaseHttpClient()
..stubError(ClientException('Offline'));
final client = AuthClient(
url: authUrl,
asyncStorage: TestAsyncStorage(),
httpClient: httpClient,
autoRefreshToken: false,
retryOptions: const SupabaseRetryOptions(enabled: false),
);
final errors = <Object>[];
final subscription = client.onAuthStateChange.listen(
(_) {},
onError: errors.add,
);
addTearDown(subscription.cancel);

await client.setInitialSession(createExpiredSessionForUser1());
await expectLater(client.getSession(), throwsA(isA<AuthException>()));
await pumpEventQueue();

expect(errors, [isA<AuthRetryableFetchException>()]);
});
}
14 changes: 7 additions & 7 deletions packages/supabase_common/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@

Shared internal utilities used across the Supabase Dart and Flutter client
packages (`supabase_auth`, `postgrest`, `supabase_realtime`, `supabase_storage`,
`supabase_functions`, `supabase`, `supabase_flutter`).
`iceberg`, `supabase_functions`, `supabase`, `supabase_flutter`).

This package holds code that would otherwise be duplicated across those
packages: the `SupabaseException` base class the auth, postgrest, storage and
functions exceptions extend, the shared `HttpMethod` enum and HTTP request
helpers, the `X-Client-Info` header builder, platform detection, a small replay
stream subject, base64url/PKCE helpers and a few other primitives. It also
holds the Postgres value types, such as `PostgresDate` and `PostgresRange`,
which `postgrest` re-exports as public API.
packages: the `SupabaseException` base class the auth, postgrest, realtime,
storage, iceberg and functions exceptions extend, the shared `HttpMethod` enum
and HTTP request helpers, the `X-Client-Info` header builder, platform
detection, a small replay stream subject, base64url/PKCE helpers and a few other
primitives. It also holds the Postgres value types, such as `PostgresDate` and
`PostgresRange`, which `postgrest` re-exports as public API.
Loading
Loading