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
46 changes: 34 additions & 12 deletions packages/postgrest/lib/src/postgrest_rpc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,23 @@ final class PostgrestRpc {
/// arguments, or the value of a function's sole unnamed `json` or `jsonb`
/// parameter. The call addresses [schema] unless this object was scoped
/// with [PostgrestClient.schema].
///
/// When [get] is set, the function is called with a `GET` request in
/// read-only access mode, so that it is retried like a select.
/// [arguments] are then sent as query parameters, so they have to be a
/// [Map] of values a query parameter can hold, and not rows or `json`. A
/// call with an argument PostgREST would read as an option of the request,
/// such as `limit`, a `null` value, or a value it would read as a filter,
/// such as `eq.foo`, is sent as a `POST` instead and not retried.
@experimental
PostgrestTypedFilterBuilder<Row, List<Row>> rows<Row>(
String function, {
Object? arguments,
required RowConverter<Row> rowFromJson,
String? schema,
bool get = false,
}) => PostgrestTypedFilterBuilder._(
_request(function, arguments, rowFromJson, schema),
_request(function, arguments, rowFromJson, schema, get),
PostgrestHttpTableExecutor(_client),
(result) => [
for (final row in result.data! as List<dynamic>)
Expand All @@ -105,19 +114,21 @@ final class PostgrestRpc {
/// );
/// ```
///
/// See [rows] for [arguments] and [schema].
/// See [rows] for [arguments], [schema] and [get].
@experimental
PostgrestTypedBuilder<T> value<T>(
String function, {
Object? arguments,
required T Function(Object? json) fromJson,
String? schema,
bool get = false,
}) => PostgrestTypedBuilder._(
_request(
function,
arguments,
_noRows,
schema,
get,
).copyWith(shape: PostgrestResultShape.value),
PostgrestHttpTableExecutor(_client),
(result) => fromJson(result.data),
Expand All @@ -128,16 +139,27 @@ final class PostgrestRpc {
Object? arguments,
RowConverter<Row> rowFromJson,
String? schema,
) => PostgrestTableRequest(
table: PostgrestTable<Row, Never, Never>(
function,
rowFromJson,
primaryKey: const [],
),
operation: PostgrestTableOperation.rpc,
schema: _schemaIsExplicit ? _schema : (schema ?? _schema),
payload: arguments,
);
bool get,
) {
if (get && arguments is! Map?) {
throw ArgumentError.value(
arguments,
'arguments',
'A call with get set takes a map of named arguments',
);
}
return PostgrestTableRequest(
table: PostgrestTable<Row, Never, Never>(
function,
rowFromJson,
primaryKey: const [],
),
operation: PostgrestTableOperation.rpc,
schema: _schemaIsExplicit ? _schema : (schema ?? _schema),
payload: arguments,
readOnly: get,
);
}
}

Never _noRows(Map<String, dynamic> json) =>
Expand Down
47 changes: 42 additions & 5 deletions packages/postgrest/lib/src/postgrest_table_executor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -137,12 +137,16 @@ final class PostgrestHttpTableExecutor implements PostgrestTableExecutor {
/// The function call of [request], decoding a response read as rows into
/// a [PostgrestList] the way a select does.
///
/// A HEAD request has no body, so a call read with
/// [PostgrestResultShape.head] sends its arguments as query parameters.
/// A GET or HEAD request has no body, so a [PostgrestTableRequest.readOnly]
/// call, and a call read with [PostgrestResultShape.head], sends its
/// arguments as query parameters. A read-only call whose arguments
/// PostgREST would read as filters is sent as a POST instead.
PostgrestFilterBuilder<Object?> _call(PostgrestTableRequest request) {
final name = request.table.name;
final head = request.shape == PostgrestResultShape.head;
final arguments = head
final get =
request.shape == PostgrestResultShape.head ||
(request.readOnly && _fitsQueryParameters(request.payload));
final arguments = get
? (request.payload ?? const <String, Object?>{})
: request.payload;
if (request.shape == PostgrestResultShape.value) {
Expand All @@ -151,17 +155,50 @@ final class PostgrestHttpTableExecutor implements PostgrestTableExecutor {
name,
request.schema,
params: arguments,
get: get,
);
}
// ignore: invalid_use_of_internal_member
return client.rpcInSchema<PostgrestList>(
name,
request.schema,
params: arguments,
get: head,
get: get,
);
}

/// Whether PostgREST passes every one of [arguments] to the function when
/// they are sent as query parameters. It does not when a name is an option
/// of the request, `limit`, or an embed path, when a value is `null`, which
/// a query parameter can only carry as the text `null`, or when a value
/// starts like a filter, `eq.foo` or `not.in.(1)`, which it applies to the
/// result instead.
static bool _fitsQueryParameters(Object? arguments) =>
arguments is! Map ||
arguments.entries.every(
(argument) =>
!_reservedQueryParameters.contains(argument.key) &&
!'${argument.key}'.contains('.') &&
argument.value != null &&
!_filterSyntax.hasMatch(renderPostgrestQueryValue(argument.value)),
Comment thread
spydon marked this conversation as resolved.
Resolved
);

static const _reservedQueryParameters = {
'select',
'columns',
'on_conflict',
'order',
'limit',
'offset',
'and',
'or',
};

static final _filterSyntax = RegExp(
r'^(not\.)?(eq|gte?|lte?|neq|i?like|i?match|cs|cd|ov|sl|sr|nx[lr]|adj|'
r'in|is|isdistinct|(pl|ph|w)?fts)(\([^)]*\))?\.',
);

static void _rejectFilter(
PostgrestFilter<Object?>? filter,
PostgrestTableOperation operation,
Expand Down
11 changes: 11 additions & 0 deletions packages/postgrest/lib/src/postgrest_table_request.dart
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ final class PostgrestTableRequest {
this.shape = PostgrestResultShape.rows,
this.countOption,
this.payload,
this.readOnly = false,
List<PostgrestStoredColumn<Object?, Object>>? onConflict,
this.ignoreDuplicates = false,
this.defaultToNull = true,
Expand Down Expand Up @@ -243,6 +244,14 @@ final class PostgrestTableRequest {
/// later, an outbox for example, serializes the payload when it takes it.
final Object? payload;

/// Whether a [PostgrestTableOperation.rpc] call only reads, so that it can
/// run in a read-only transaction and be retried like a select.
///
/// [PostgrestHttpTableExecutor] sends such a call as a `GET`, with
/// [payload] as query parameters, unless PostgREST would read one of them
/// as an option of the request or as a filter.
final bool readOnly;

/// The columns of the unique constraint an upsert merges on, or `null` for
/// the primary key.
final List<PostgrestStoredColumn<Object?, Object>>? onConflict;
Expand Down Expand Up @@ -292,6 +301,7 @@ final class PostgrestTableRequest {
PostgrestResultShape? shape,
CountOption? countOption,
Object? payload,
bool? readOnly,
List<PostgrestStoredColumn<Object?, Object>>? onConflict,
bool? ignoreDuplicates,
bool? defaultToNull,
Expand All @@ -314,6 +324,7 @@ final class PostgrestTableRequest {
shape: shape ?? this.shape,
countOption: countOption ?? this.countOption,
payload: payload ?? this.payload,
readOnly: readOnly ?? this.readOnly,
onConflict: onConflict ?? this.onConflict,
ignoreDuplicates: ignoreDuplicates ?? this.ignoreDuplicates,
defaultToNull: defaultToNull ?? this.defaultToNull,
Expand Down
35 changes: 35 additions & 0 deletions packages/postgrest/test/typed_rpc_integration_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,41 @@ void main() {
await postgrest.rpc.value('void_func', fromJson: (json) {});
});

test('calls a function read-only with its arguments in the query', () async {
final rows = await postgrest.rpc
.rows(
'get_username_and_status',
arguments: {'name_param': 'supabot'},
rowFromJson: UserStatus.new,
get: true,
)
.where(UserStatuses.status.eq('ONLINE'));
expect(rows.single.username, 'supabot');

final element = await postgrest.rpc.value(
'get_array_element',
arguments: {
'arr': [37, 420, 64],
'index': 2,
},
fromJson: (json) => json as int?,
get: true,
);
expect(element, 420);
});

test('calls a function read-only with an argument that looks like a '
'filter', () async {
final status = await postgrest.rpc.value(
'get_status',
arguments: {'name_param': 'eq.supabot'},
fromJson: (json) => json as String?,
get: true,
);

expect(status, isNull);
});

test('calls a function of the schema it is given', () async {
final status = await postgrest.rpc.value(
'get_status',
Expand Down
140 changes: 140 additions & 0 deletions packages/postgrest/test/typed_rpc_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,119 @@ void main() {
});
});

test('sends a read-only call as a get request', () async {
httpClient.stub(bookRows);

await client.rpc
.rows(
'search_books',
arguments: {
'query': 'dart',
'tags': ['a', 'b,c'],
},
rowFromJson: Book.new,
get: true,
)
.where(Books.id.gt(1));

expect(lastRequest().method, HttpMethod.get.value);
expect(lastRequest().url.queryParameters, {
'query': 'dart',
'tags': '{a,"b,c"}',
'id': 'gt.1',
});
});

test('sends a read-only call with an argument a query parameter cannot '
'carry as a post request', () async {
httpClient.stub(bookRows);

for (final query in ['eq.dart', 'not.in.(a)', 'fts(english).dart']) {
await client.rpc.rows(
'search_books',
arguments: {'query': query},
rowFromJson: Book.new,
get: true,
);

expect(lastRequest().method, HttpMethod.post.value);
expect(lastRequest().jsonBody, {'query': query});
}

await client.rpc.rows(
'search_books',
arguments: {'limit': 2},
rowFromJson: Book.new,
get: true,
);
expect(lastRequest().method, HttpMethod.post.value);
expect(lastRequest().jsonBody, {'limit': 2});

await client.rpc.rows(
'search_books',
arguments: {'query': null},
rowFromJson: Book.new,
get: true,
);
expect(lastRequest().method, HttpMethod.post.value);
expect(lastRequest().jsonBody, {'query': null});

await client.rpc.rows(
'search_books',
arguments: {'query': 'equal.parts'},
rowFromJson: Book.new,
get: true,
);
expect(lastRequest().method, HttpMethod.get.value);
});

test('retries a read-only call', () async {
httpClient.stubStatuses([503, 200], body: bookRows);
final retrying = PostgrestClient(
'http://localhost/rest/v1',
httpClient: httpClient,
retryOptions: const SupabaseRetryOptions(initialDelay: Duration.zero),
);
addTearDown(retrying.dispose);

final books = await retrying.rpc
.rows('search_books', rowFromJson: Book.new, get: true)
.retry(count: 1);

expect(books, hasLength(2));
expect(httpClient.requests, hasLength(2));
});

test('does not retry a call that is not read-only', () async {
httpClient.stubStatuses([503, 200], body: bookRows);
final retrying = PostgrestClient(
'http://localhost/rest/v1',
httpClient: httpClient,
retryOptions: const SupabaseRetryOptions(initialDelay: Duration.zero),
);
addTearDown(retrying.dispose);

await expectLater(
() => retrying.rpc
.rows('search_books', rowFromJson: Book.new)
.retry(count: 1),
throwsA(isA<PostgrestException>()),
);
expect(httpClient.requests, hasLength(1));
});

test('rejects a read-only call with arguments that are not a map', () {
expect(
() => client.rpc.rows(
'search_books',
arguments: ['dart'],
rowFromJson: Book.new,
get: true,
),
throwsArgumentError,
);
});

test('calls in the schema it is given', () async {
httpClient.stub(bookRows);

Expand Down Expand Up @@ -211,6 +324,33 @@ void main() {
expect(lastRequest().jsonBody, {'kind': 'click'});
});

test('sends a read-only call as a get request', () async {
httpClient.stub(3);

await client.rpc.value(
'count_books',
arguments: {'author_id': 1},
fromJson: (json) => json as int?,
get: true,
);

expect(lastRequest().method, HttpMethod.get.value);
expect(lastRequest().url.queryParameters, {'author_id': '1'});
});

test('sends a read-only call without arguments as a get request', () async {
httpClient.stub(3);

await client
.schema('inventory')
.rpc
.value('count_books', fromJson: (json) => json as int?, get: true);

expect(lastRequest().method, HttpMethod.get.value);
expect(lastRequest().url.queryParameters, isEmpty);
expect(lastRequest().headers['accept-profile'], 'inventory');
});

test('converts a list of scalars', () async {
httpClient.stub([1, 2, null]);

Expand Down
Loading
Loading