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
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,9 @@ the request to a `PostgrestTableExecutor` and converts the `PostgrestTableResult
`Row` type. The default `PostgrestHttpTableExecutor` renders the request through the untyped
builders at execution time, so both APIs send the same wire request; another executor (a
`SupabaseClientInterceptor` can wrap it) may cache, queue or answer from a local store instead.
The typed function calls on `client.rpc` (`rows`, `value` and the generated methods built on them)
collect a `PostgrestTableRequest` with `PostgrestTableOperation.rpc` and run through the same
executor.

### Realtime Architecture

Expand Down
7 changes: 4 additions & 3 deletions MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,10 @@ and writes only accept the generated insert and update types. We recommend gener
definitions for your project and using `table()` for every table they cover. `from()` keeps working,
and both can be used on one client, so a codebase can move over one table at a time.

Requests made through `table()` run through the executor that `SupabaseClientInterceptor`s wrap, so
features built as interceptors, such as offline support, only apply to them. Requests made through
`from()` bypass every interceptor.
Requests made through `table()` and the typed function calls generated on `rpc` run through the
executor that `SupabaseClientInterceptor`s wrap, so features built as interceptors, such as offline
support, only apply to them. Requests made through `from()` and the untyped `rpc('fn')` bypass every
interceptor.

The typed API is marked `@experimental` while it settles. Referencing an experimental type such as
`PostgrestFilter` directly reports `experimental_member_use`, which an
Expand Down
25 changes: 21 additions & 4 deletions packages/postgrest/lib/src/postgrest_rpc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,35 @@ part of 'postgrest_typed_builder.dart';
final class PostgrestRpc {
/// Calls functions through [client], in [schema] or the schema of the
/// client when `null`. When [schemaIsExplicit] is set, [schema] also wins
/// over the schema a generated method passes along.
/// over the schema a generated method passes along. [rows] and [value] run
/// through [executor], or a [PostgrestHttpTableExecutor] on [client] when
/// `null`.
@internal
const PostgrestRpc(
this._client, {
String? schema,
bool schemaIsExplicit = false,
PostgrestTableExecutor? executor,
}) : _schema = schema,
_schemaIsExplicit = schemaIsExplicit;
_schemaIsExplicit = schemaIsExplicit,
_executor = executor;

final PostgrestClient _client;
final String? _schema;
final bool _schemaIsExplicit;
final PostgrestTableExecutor? _executor;

PostgrestTableExecutor get _tableExecutor =>
_executor ?? PostgrestHttpTableExecutor(_client);

/// A copy of this that runs [rows] and [value] through [executor].
@internal
PostgrestRpc withExecutor(PostgrestTableExecutor executor) => PostgrestRpc(
_client,
schema: _schema,
schemaIsExplicit: _schemaIsExplicit,
executor: executor,
);

/// {@template postgrest_rpc}
/// Performs a stored procedure call.
Expand Down Expand Up @@ -99,7 +116,7 @@ final class PostgrestRpc {
bool get = false,
}) => PostgrestTypedFilterBuilder._(
_request(function, arguments, rowFromJson, schema, get),
PostgrestHttpTableExecutor(_client),
_tableExecutor,
(result) => [
for (final row in result.data! as List<dynamic>)
rowFromJson(row as Map<String, dynamic>),
Expand Down Expand Up @@ -133,7 +150,7 @@ final class PostgrestRpc {
schema,
get,
).copyWith(shape: PostgrestResultShape.value),
PostgrestHttpTableExecutor(_client),
_tableExecutor,
(result) => fromJson(result.data),
);

Expand Down
3 changes: 2 additions & 1 deletion packages/postgrest/lib/src/postgrest_table_executor.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
part of 'postgrest_typed_builder.dart';

/// Runs the requests of the typed table API.
/// Runs the requests of the typed table API and of the typed function calls,
/// [PostgrestRpc.rows] and [PostgrestRpc.value].
///
/// [PostgrestClient.table] uses a [PostgrestHttpTableExecutor] unless another
/// one is given. An executor that decorates another, to cache, queue or log
Expand Down
8 changes: 6 additions & 2 deletions packages/supabase/lib/src/supabase_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ import 'trace_http_client.dart';
///
/// [interceptors] extend the client from the outside, see
/// [SupabaseClientInterceptor]. They wrap the executor the typed table API
/// runs through, in the order given, and are disposed together with the
/// client.
/// and the typed function calls run through, in the order given, and are
/// disposed together with the client.
///
/// The pkce flow is used by default and keeps its code verifiers in the
/// `AuthAsyncStorage` passed to the `asyncStorage` field of [authOptions].
Expand Down Expand Up @@ -338,6 +338,10 @@ class SupabaseClient {
/// ```dart
/// await supabase.rpc('get_status', params: {'name_param': 'supabot'});
/// ```
///
/// The typed calls, [PostgrestRpc.rows], [PostgrestRpc.value] and the
/// methods generated on them, run through the [interceptors]; the untyped
/// call above does not.
PostgrestRpc get rpc => _defaultSchema.rpc;

/// Creates a Realtime channel with Broadcast, Presence, and Postgres Changes.
Expand Down
19 changes: 14 additions & 5 deletions packages/supabase/lib/src/supabase_client_interceptor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import 'supabase_client.dart';
/// application calls it.
///
/// An interceptor can wrap the [PostgrestTableExecutor] that runs the
/// requests of the typed table API, [SupabaseClient.table], and receives the
/// client once it is fully constructed. The untyped [SupabaseClient.from],
/// `rpc`, storage, functions and realtime traffic never passes through an
/// interceptor.
/// requests of the typed table API, [SupabaseClient.table], and of the typed
/// function calls, [PostgrestRpc.rows] and [PostgrestRpc.value], and receives
/// the client once it is fully constructed. The untyped [SupabaseClient.from]
/// and [PostgrestRpc.call], storage, functions and realtime traffic never
/// passes through an interceptor.
///
/// Interceptors are given to the [SupabaseClient] constructor, or to
/// `Supabase.initialize` in Flutter:
Expand All @@ -22,13 +23,21 @@ import 'supabase_client.dart';
abstract class SupabaseClientInterceptor {
const SupabaseClientInterceptor();

/// Returns the executor [SupabaseClient.table] runs its requests through.
/// Returns the executor [SupabaseClient.table] and the typed function
/// calls of [SupabaseClient.rpc] run their requests through. A function
/// call arrives as a request with [PostgrestTableOperation.rpc], which
/// counts as a mutation unless [PostgrestTableRequest.readOnly] is set. Its
/// [PostgrestTableRequest.table] has no primary key, and a call read with
/// [PostgrestResultShape.value] has no rows to convert.
///
/// [inner] sends a request to PostgREST with the current access token, so
/// an executor that holds a request back and runs it through [inner] later
/// still authenticates as the current user. Interceptors wrap in the order
/// they were given, so the last interceptor sees a request first. Return
/// [inner] to leave execution untouched.
///
/// Typed requests the interceptor makes on the client itself run through
/// this executor again. Run them through [inner] to bypass the chain.
PostgrestTableExecutor wrapTableExecutor(PostgrestTableExecutor inner) =>
inner;

Expand Down
6 changes: 4 additions & 2 deletions packages/supabase/lib/src/supabase_query_schema.dart
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,10 @@ class SupabaseQuerySchema {
/// Calls Postgres functions in this schema, see [PostgrestClient.rpc].
///
/// The schema of this object wins over the schema a generated function
/// method addresses.
PostgrestRpc get rpc => _rest.rpc;
/// method addresses. The typed calls run through the interceptors of the
/// client.
// ignore: invalid_use_of_internal_member
PostgrestRpc get rpc => _rest.rpc.withExecutor(_tableExecutor);

/// Returns a copy of this scoped to [schema] instead.
SupabaseQuerySchema schema(String schema) {
Expand Down
95 changes: 94 additions & 1 deletion packages/supabase/test/client_interceptor_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,29 @@ class LoggingInterceptor extends SupabaseClientInterceptor {
}
}

class RecordingInterceptor extends SupabaseClientInterceptor {
const RecordingInterceptor(this.requests);

final List<PostgrestTableRequest> requests;

@override
PostgrestTableExecutor wrapTableExecutor(PostgrestTableExecutor inner) =>
RecordingExecutor(inner, requests);
}

class RecordingExecutor implements PostgrestTableExecutor {
const RecordingExecutor(this.inner, this.requests);

final PostgrestTableExecutor inner;
final List<PostgrestTableRequest> requests;

@override
Future<PostgrestTableResult> execute(PostgrestTableRequest request) {
requests.add(request);
return inner.execute(request);
}
}

class FailingAttachInterceptor extends SupabaseClientInterceptor {
const FailingAttachInterceptor();

Expand Down Expand Up @@ -111,7 +134,77 @@ void main() {
expect(httpClient.requestsTo('/rest/v1/todos'), hasLength(2));
});

test('rpc, storage and functions bypass the interceptor', () async {
test('typed function calls run through the interceptor', () async {
httpClient
..stubRpc('search_todos', body: todoRows)
..stubRpc('count_todos', body: 1);

final List<Todo> rows = await supabase.rpc
.rows('search_todos', rowFromJson: Todo.new)
.where(Todos.id.gt(0));
final count = await supabase.rpc.value(
'count_todos',
fromJson: (json) => json! as int,
);

expect(rows.single.task, 'Ship it');
expect(count, 1);
expect(log, ['a attached', 'a rpc search_todos', 'a rpc count_todos']);
final sent = httpClient.requestsTo('/rest/v1/rpc/search_todos').single;
expect(sent.url.queryParameters['id'], 'gt.0');
expect(sent.headers['apikey'], isNotNull);
});

test('a schema scoped function call carries its schema', () async {
httpClient.stubRpc('count_todos', body: 1, schema: 'library');

await supabase
.schema('library')
.rpc
.value('count_todos', fromJson: (json) => json! as int);

final sent = httpClient.requestsTo('/rest/v1/rpc/count_todos').single;
expect(sent.headers['Content-Profile'], 'library');
expect(log, ['a attached', 'a rpc count_todos']);
});

test('a read-only function call reaches the interceptor as a GET', () async {
final requests = <PostgrestTableRequest>[];
await supabase.dispose();
supabase = testSupabaseClient(
httpClient: httpClient,
interceptors: [RecordingInterceptor(requests)],
);
httpClient.stubRpc('count_todos', body: 1);

await supabase.rpc.value(
'count_todos',
arguments: {'done': true},
fromJson: (json) => json! as int,
get: true,
);

expect(requests.single.readOnly, isTrue);
final sent = httpClient.requestsTo('/rest/v1/rpc/count_todos').single;
expect(sent.method, HttpMethod.get.value);
expect(sent.url.queryParameters['done'], 'true');
});

test('a header change reaches typed function calls', () async {
httpClient.stubRpc('count_todos', body: 1);
supabase.headers = {'x-tenant': 'acme'};

await supabase.rpc.value(
'count_todos',
fromJson: (json) => json! as int,
);

expect(log, ['a attached', 'a rpc count_todos']);
final sent = httpClient.requestsTo('/rest/v1/rpc/count_todos').single;
expect(sent.headers['x-tenant'], 'acme');
});

test('untyped rpc, storage and functions bypass the interceptor', () async {
httpClient
..stubRpc('ping', body: 'pong')
..stubStorageList('avatars', objects: [])
Expand Down
Loading