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
17 changes: 11 additions & 6 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,12 +160,17 @@ Example: `supabase.from('users').select('id, name').eq('id', 1).limit(10)`
`PostgrestBuilder<T>` is the executable base: `T` is what awaiting the request resolves to. Steps
that change the result (`select()`, `single()`, `count()`, `withConverter()`) each supply a decoder
for the response, and the decoders compose in call order, so the converter always receives whatever
the chain resolved to right before it. The typed builders (`PostgrestTypedQueryBuilder` →
`PostgrestTypedFilterBuilder` → `PostgrestTypedTransformBuilder` → `PostgrestTypedBuilder<T>`) each
wrap the untyped builder of the same phase. `PostgrestTypedBuilder<T>` and its subclasses hold that
builder as a `PostgrestBuilder<T>`, while `PostgrestTypedQueryBuilder` holds a plain
`PostgrestQueryBuilder`. Rows are converted into the table's `Row` type with `withConverter` in that
same decoder chain.
the chain resolved to right before it.

The typed builders returned by `client.table(...)` (`PostgrestTypedQueryBuilder` →
`PostgrestTypedFilterBuilder` → `PostgrestTypedTransformBuilder` → `PostgrestTypedBuilder<T>`) do
not wrap untyped builders. Each method returns a copy holding an immutable `PostgrestTableRequest`
that describes the query as structured values (operation, columns, filter, orderings, payload, and
`PostgrestRequestOptions` for headers, retry, timeout and abort signal). Awaiting the builder hands
the request to a `PostgrestTableExecutor` and converts the `PostgrestTableResult` into the table's
`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
`SupabaseClientPlugin` can wrap it) may cache, queue or answer from a local store instead.

### Realtime Architecture

Expand Down
42 changes: 36 additions & 6 deletions packages/postgrest/lib/src/postgrest_table_executor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,19 @@ final class PostgrestHttpTableExecutor implements PostgrestTableExecutor {
final query = client.fromInSchema(request.table.name, request.schema);

if (request.operation == PostgrestTableOperation.count) {
final counted = _applyFilter(
query.count(request.countOption ?? CountOption.exact),
request,
final counted = _applyOptions(
_applyFilter(
query.count(request.countOption ?? CountOption.exact),
request,
),
request.options,
);
return PostgrestTableResult(count: await counted);
}

final terminal = _terminal(
_transforms(_operation(query, request), request),
request,
final terminal = _applyOptions(
_terminal(_transforms(_operation(query, request), request), request),
request.options,
);

final countOption = request.countOption;
Expand All @@ -62,6 +65,33 @@ final class PostgrestHttpTableExecutor implements PostgrestTableExecutor {
return PostgrestTableResult(data: await terminal);
}

/// [builder] with the headers, retry policy, timeout and abort signal of
/// [options] applied.
PostgrestBuilder<T> _applyOptions<T>(
PostgrestBuilder<T> builder,
PostgrestRequestOptions options,
) {
var configured = builder;
for (final MapEntry(:key, :value) in options.headers.entries) {
configured = configured.setHeader(key, value);
}
final retryEnabled = options.retryEnabled;
final retryCount = options.retryCount;
if (retryEnabled != null || retryCount != null) {
configured = configured.retry(
enabled: retryEnabled ?? client.retryOptions.enabled,
count: retryCount,
);
}
final requestTimeout = options.requestTimeout;
if (requestTimeout != null) {
configured = configured.requestTimeout(requestTimeout);
}
final abortSignal = options.abortSignal;
if (abortSignal != null) configured = configured.abortSignal(abortSignal);
return configured;
}

/// The operation of [request] with its filter applied.
///
/// An insert or upsert takes no filter, the same way the untyped builders
Expand Down
63 changes: 62 additions & 1 deletion packages/postgrest/lib/src/postgrest_table_request.dart
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,59 @@ final class PostgrestExplainOptions {
final ExplainFormat format;
}

/// How a [PostgrestTableRequest] is sent, as opposed to what it asks for.
///
/// [PostgrestHttpTableExecutor] applies every option. An executor that does
/// not send the request over HTTP, one answering from a local store for
/// example, may ignore them.
@experimental
final class PostgrestRequestOptions {
PostgrestRequestOptions({
Map<String, String> headers = const {},
this.retryEnabled,
this.retryCount,
this.requestTimeout,
this.abortSignal,
}) : headers = Map.unmodifiable(headers);

/// The headers sent on top of the ones the request produces, see
/// [PostgrestBuilder.setHeader].
final Map<String, String> headers;

/// Whether a failed attempt is retried, or `null` for the client's
/// [PostgrestClient.retryOptions], see [PostgrestBuilder.retry].
final bool? retryEnabled;

/// The number of retry attempts, or `null` for the client's
/// [PostgrestClient.retryOptions].
final int? retryCount;

/// How long a single attempt may take, or `null` for the client's
/// [PostgrestClient.requestTimeout], see [PostgrestBuilder.requestTimeout].
final Duration? requestTimeout;

/// Cancels the request when it completes, see [PostgrestBuilder.abortSignal].
///
/// A signal is not part of what the request asks for, so a cache that keys
/// on the request leaves it out of the key.
final Future<void>? abortSignal;

/// A copy with the given fields replaced.
PostgrestRequestOptions copyWith({
Map<String, String>? headers,
bool? retryEnabled,
int? retryCount,
Duration? requestTimeout,
Future<void>? abortSignal,
}) => PostgrestRequestOptions(
headers: headers ?? this.headers,
retryEnabled: retryEnabled ?? this.retryEnabled,
retryCount: retryCount ?? this.retryCount,
requestTimeout: requestTimeout ?? this.requestTimeout,
abortSignal: abortSignal ?? this.abortSignal,
);
}

/// Everything a typed table builder has collected, ready to be run by a
/// [PostgrestTableExecutor].
///
Expand Down Expand Up @@ -138,7 +191,9 @@ final class PostgrestTableRequest {
this.stripNulls = false,
this.dryRun = false,
this.explainOptions,
}) : columns = List.unmodifiable(columns),
PostgrestRequestOptions? options,
}) : options = options ?? PostgrestRequestOptions(),
columns = List.unmodifiable(columns),
orderings = List.unmodifiable(orderings),
embeddedPages = List.unmodifiable(embeddedPages),
onConflict = onConflict == null ? null : List.unmodifiable(onConflict);
Expand Down Expand Up @@ -218,6 +273,10 @@ final class PostgrestTableRequest {
/// The options of an explain request.
final PostgrestExplainOptions? explainOptions;

/// How the request is sent: its headers, retry policy, timeout and abort
/// signal.
final PostgrestRequestOptions options;

/// A copy with the given fields replaced.
///
/// A field that is not given keeps its value, so a nullable field cannot
Expand All @@ -243,6 +302,7 @@ final class PostgrestTableRequest {
bool? stripNulls,
bool? dryRun,
PostgrestExplainOptions? explainOptions,
PostgrestRequestOptions? options,
}) => PostgrestTableRequest(
table: table ?? this.table,
operation: operation ?? this.operation,
Expand All @@ -264,6 +324,7 @@ final class PostgrestTableRequest {
stripNulls: stripNulls ?? this.stripNulls,
dryRun: dryRun ?? this.dryRun,
explainOptions: explainOptions ?? this.explainOptions,
options: options ?? this.options,
);
}

Expand Down
66 changes: 66 additions & 0 deletions packages/postgrest/lib/src/postgrest_typed_builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,36 @@ List<PostgrestSelectable<Row>> _checkedSelections<Row>(
return selections;
}

/// The per-request options the typed builders set, see
/// [PostgrestRequestOptions].
extension on PostgrestRequestOptions {
PostgrestRequestOptions _retry(bool enabled, int? count) =>
copyWith(retryEnabled: enabled, retryCount: count);

PostgrestRequestOptions _requestTimeout(Duration timeout) =>
copyWith(requestTimeout: timeout);

PostgrestRequestOptions _abortSignal(Future<void> abortSignal) =>
copyWith(abortSignal: abortSignal);

PostgrestRequestOptions _header(String key, String value) =>
copyWith(headers: {...headers, key: value});
}

extension on PostgrestTableRequest {
PostgrestTableRequest _retry(bool enabled, int? count) =>
copyWith(options: options._retry(enabled, count));

PostgrestTableRequest _requestTimeout(Duration timeout) =>
copyWith(options: options._requestTimeout(timeout));

PostgrestTableRequest _abortSignal(Future<void> abortSignal) =>
copyWith(options: options._abortSignal(abortSignal));

PostgrestTableRequest _header(String key, String value) =>
copyWith(options: options._header(key, value));
}

/// Converts the result of a [PostgrestTableRequest] into [T].
typedef _ResultConverter<T> = T Function(PostgrestTableResult result);

Expand Down Expand Up @@ -201,6 +231,42 @@ class PostgrestTypedBuilder<T> implements Future<T> {
Future<T> _execute() =>
Future.sync(() => _executor.execute(request)).then(_convert);

PostgrestTypedBuilder<T> _with(PostgrestTableRequest changed) =>
PostgrestTypedBuilder._(changed, _executor, _convert);

/// Overrides the retry behavior for this request.
///
/// See [PostgrestBuilder.retry] for [enabled] and [count].
PostgrestTypedBuilder<T> retry({bool enabled = true, int? count}) =>
_with(request._retry(enabled, count));

/// Bounds how long a single attempt of this request may take, overriding
/// the timeout configured on [PostgrestClient].
///
/// Unlike [timeout], which only stops waiting for the result, this cancels
/// the attempt. See [PostgrestBuilder.requestTimeout].
PostgrestTypedBuilder<T> requestTimeout(Duration timeout) =>
_with(request._requestTimeout(timeout));

/// Cancels the request when [abortSignal] completes, throwing a
/// [RequestAbortedException] and stopping any retries.
///
/// ```dart
/// final abort = Completer<void>();
/// final books = client
/// .table(Books.table)
/// .select()
/// .abortSignal(abort.future);
/// ```
///
/// See [PostgrestBuilder.abortSignal].
PostgrestTypedBuilder<T> abortSignal(Future<void> abortSignal) =>
_with(request._abortSignal(abortSignal));

/// Sets [key] to [value] in the headers of this request.
PostgrestTypedBuilder<T> setHeader(String key, String value) =>
_with(request._header(key, value));

/// A broadcast stream of the one result. The request runs when the first
/// listener subscribes, so a listener added later still receives it.
@override
Expand Down
32 changes: 28 additions & 4 deletions packages/postgrest/lib/src/postgrest_typed_filter_builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,33 @@ class PostgrestTypedFilterBuilder<Row, T>
super.rowFromJson,
) : super._();

PostgrestTypedFilterBuilder<Row, T> _filtered(
PostgrestTableRequest request,
) => PostgrestTypedFilterBuilder._(
request,
_executor,
_convert,
_rowFromJson,
);

@override
PostgrestTypedFilterBuilder<Row, T> retry({
bool enabled = true,
int? count,
}) => _filtered(request._retry(enabled, count));

@override
PostgrestTypedFilterBuilder<Row, T> requestTimeout(Duration timeout) =>
_filtered(request._requestTimeout(timeout));

@override
PostgrestTypedFilterBuilder<Row, T> abortSignal(Future<void> abortSignal) =>
_filtered(request._abortSignal(abortSignal));

@override
PostgrestTypedFilterBuilder<Row, T> setHeader(String key, String value) =>
_filtered(request._header(key, value));

/// Only rows satisfying [filter].
///
/// Operators are methods on a column, composed with `&`, `|` and
Expand All @@ -39,11 +66,8 @@ class PostgrestTypedFilterBuilder<Row, T>
/// Repeated [where] calls combine with logical AND.
PostgrestTypedFilterBuilder<Row, T> where(PostgrestFilter<Row> filter) {
final current = request.filter;
return PostgrestTypedFilterBuilder._(
return _filtered(
request.copyWith(filter: current == null ? filter : current & filter),
_executor,
_convert,
_rowFromJson,
);
}
}
49 changes: 48 additions & 1 deletion packages/postgrest/lib/src/postgrest_typed_query_builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,19 @@ class PostgrestTypedQueryBuilder<Row, Insert, Update> {
required PostgrestTableExecutor executor,
String? schema,
}) : _executor = executor,
_schema = schema;
_schema = schema,
_options = null;

const PostgrestTypedQueryBuilder._(
this.table,
this._executor,
this._schema,
this._options,
);

final PostgrestTableExecutor _executor;
final String? _schema;
final PostgrestRequestOptions? _options;

/// The table this builder queries.
final PostgrestTable<Row, Insert, Update> table;
Expand All @@ -29,8 +38,46 @@ class PostgrestTypedQueryBuilder<Row, Insert, Update> {
table: table,
operation: operation,
schema: _schema,
options: _options,
);

PostgrestTypedQueryBuilder<Row, Insert, Update> _with(
PostgrestRequestOptions options,
) => PostgrestTypedQueryBuilder._(table, _executor, _schema, options);

PostgrestRequestOptions get _currentOptions =>
_options ?? PostgrestRequestOptions();

/// Overrides the retry behavior of the requests built by this builder.
///
/// See [PostgrestBuilder.retry] for [enabled] and [count].
PostgrestTypedQueryBuilder<Row, Insert, Update> retry({
bool enabled = true,
int? count,
}) => _with(_currentOptions._retry(enabled, count));

/// Bounds how long a single attempt of the requests built by this builder
/// may take.
///
/// See [PostgrestBuilder.requestTimeout].
PostgrestTypedQueryBuilder<Row, Insert, Update> requestTimeout(
Duration timeout,
) => _with(_currentOptions._requestTimeout(timeout));

/// Cancels the requests built by this builder when [abortSignal]
/// completes.
///
/// See [PostgrestTypedBuilder.abortSignal].
PostgrestTypedQueryBuilder<Row, Insert, Update> abortSignal(
Future<void> abortSignal,
) => _with(_currentOptions._abortSignal(abortSignal));

/// Sets a header on the requests built by this builder.
PostgrestTypedQueryBuilder<Row, Insert, Update> setHeader(
String key,
String value,
) => _with(_currentOptions._header(key, value));

PostgrestTypedFilterBuilder<Row, void> _mutation(
PostgrestTableRequest request,
) => PostgrestTypedFilterBuilder._(
Expand Down
Loading
Loading