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
1 change: 1 addition & 0 deletions packages/postgrest/lib/src/postgrest_builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import 'package:postgrest/src/postgrest_typed_builder.dart'
show
checkPostgrestHeadArguments,
checkPostgrestRange,
postgrestArgumentsFitQuery,
renderPostgrestQueryValue;
import 'package:meta/meta.dart';
import 'package:postgrest/postgrest.dart';
Expand Down
13 changes: 9 additions & 4 deletions packages/postgrest/lib/src/postgrest_rpc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,13 @@ final class PostgrestRpc {
/// arguments, or the value of a function's sole unnamed `json` or `jsonb`
/// parameter, such as a list or a number.
///
/// When [get] is set to `true`, the function will be called with read-only
/// access mode, and [params] has to be a [Map] of named arguments or
/// `null`.
/// When [get] is set to `true`, the function is called with a `GET`
/// request in read-only access mode, and [params] has to be a [Map] of
/// named arguments or `null`, which are sent as query parameters. 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, which is neither read-only
/// nor retried.
/// {@endtemplate}
///
/// ```dart
Expand Down Expand Up @@ -106,7 +110,8 @@ final class PostgrestRpc {
/// [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.
/// such as `eq.foo`, is sent as a `POST` instead, which is neither
/// read-only nor retried.
@experimental
PostgrestTypedFilterBuilder<Row, List<Row>> rows<Row>(
String function, {
Expand Down
26 changes: 22 additions & 4 deletions packages/postgrest/lib/src/postgrest_rpc_builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -30,22 +30,40 @@ class PostgrestRpcBuilder {
/// [params] is an optional object to pass as arguments to the function call.
///
/// When [get] is set to `true`, [params] must be a [Map] or `null`, and the
/// function is called with read-only access mode.
/// function is called with a `GET` request in read-only access mode, with
/// [params] as query parameters. 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, which is neither read-only nor retried.
PostgrestFilterBuilder<T> rpc<T>([
Object? params,
bool get = false,
]) {
final query = get && postgrestArgumentsFitQuery(params);
return _filterBuilder(
_config.copyWith(
method: get ? HttpMethod.get : HttpMethod.post,
url: get ? _appendArguments(_config.url, params) : null,
body: params,
method: query ? HttpMethod.get : HttpMethod.post,
Comment thread
spydon marked this conversation as resolved.
Resolved
url: query ? _appendArguments(_config.url, params) : null,
body: get && !query ? _jsonArguments(params! as Map) : params,
functionCall: true,
),
);
}
}

/// [arguments] with each value that JSON cannot carry, such as a [DateTime],
/// rendered the way [_appendArguments] renders it, for a read-only call sent
/// as a `POST`.
Map<Object?, Object?> _jsonArguments(Map<Object?, Object?> arguments) =>
arguments.map((name, value) => MapEntry(name, _jsonArgument(value)));

Object? _jsonArgument(Object? value) => switch (value) {
null || String() || num() || bool() || Map() => value,
Uint8List() => renderPostgrestQueryValue(value),
List() => value.map(_jsonArgument).toList(),
_ => renderPostgrestQueryValue(value),
};

/// [url] with each of the function arguments in [params] appended as a query
/// parameter, for a call sent without a body.
Uri _appendArguments(Uri url, Object? params) {
Expand Down
11 changes: 5 additions & 6 deletions packages/postgrest/lib/src/postgrest_table_executor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -146,17 +146,16 @@ final class PostgrestHttpTableExecutor implements PostgrestTableExecutor {
///
/// 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, and such a
/// call read with [PostgrestResultShape.head] is rejected.
/// arguments as query parameters. A read-only call whose arguments would
/// not reach the function as query parameters is sent as a POST instead,
/// see [PostgrestRpc.call], and such a call read with
/// [PostgrestResultShape.head] is rejected.
PostgrestFilterBuilder<Object?> _call(PostgrestTableRequest request) {
final name = request.table.name;
if (request.shape == PostgrestResultShape.head) {
checkPostgrestHeadArguments(request.payload);
}
final get =
request.shape == PostgrestResultShape.head ||
(request.readOnly && postgrestArgumentsFitQuery(request.payload));
final get = request.shape == PostgrestResultShape.head || request.readOnly;
final arguments = get
? (request.payload ?? const <String, Object?>{})
: request.payload;
Expand Down
10 changes: 10 additions & 0 deletions packages/postgrest/test/basic_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,16 @@ void main() {
expect(result, 'ONLINE');
});

test('read-only stored procedure with an argument that looks like a '
'filter', () async {
final response = await postgrest.rpc<PostgrestList>(
'get_username_and_status',
params: {'name_param': 'eq.supabot'},
get: true,
);
expect(response, isEmpty);
});

test('select on stored procedure', () async {
final response = await postgrest
.rpc(
Expand Down
77 changes: 77 additions & 0 deletions packages/postgrest/test/transform_request_test.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:typed_data';

import 'package:postgrest/postgrest.dart';
import 'package:supabase_test/supabase_test.dart';
import 'package:test/test.dart';
Expand Down Expand Up @@ -368,6 +370,81 @@ void main() {
throwsArgumentError,
);
});

test('sends arguments that fit a query as query parameters', () async {
await client.rpc(
'search',
params: {'query': 'dart', 'page': 2},
get: true,
);

final request = httpClient.requests.single;
expect(request.method, 'GET');
expect(request.queryParameters, {'query': 'dart', 'page': '2'});
expect(request.body, isEmpty);
});

for (final (description, params) in [
('a reserved name', {'limit': 5}),
('a dotted name', {'author.name': 'Ada'}),
('a null value', {'name_param': null}),
('a value that reads as a filter', {'name_param': 'eq.supabot'}),
('a value that reads as a negated filter', {'ids': 'not.in.(1)'}),
]) {
test('sends $description as a POST body', () async {
await client.rpc('search', params: params, get: true);

final request = httpClient.requests.single;
expect(request.method, 'POST');
expect(request.url.path, '/rest/v1/rpc/search');
expect(request.queryParameters, isEmpty);
expect(request.jsonBody, params);
});
}

test('renders values JSON cannot carry the way a GET does', () async {
await client.rpc(
'search',
params: {
'limit': 5,
'after': DateTime.utc(2024, 2, 29, 12),
'days': [DateTime.utc(2024, 3)],
'cover': Uint8List.fromList([1, 2]),
'filter': {'tag': 'dart'},
},
get: true,
);

final request = httpClient.requests.single;
expect(request.method, 'POST');
expect(request.jsonBody, {
'limit': 5,
'after': '2024-02-29T12:00:00.000Z',
'days': ['2024-03-01T00:00:00.000Z'],
'cover': r'\x0102',
'filter': {'tag': 'dart'},
});
});

test('keeps chained filters on a call sent as a POST', () async {
await client
.rpc('search', params: {'limit': 5}, get: true)
.eq('id', 1)
.select('id');

final request = httpClient.requests.single;
expect(request.method, 'POST');
expect(request.queryParameters, {'select': 'id', 'id': 'eq.1'});
expect(request.jsonBody, {'limit': 5});
});

test('head() still rejects arguments that do not fit a query', () {
expect(
() => client.rpc('search', params: {'limit': 5}, get: true).head(),
throwsArgumentError,
);
expect(httpClient.requests, isEmpty);
});
});

group('range()', () {
Expand Down
4 changes: 2 additions & 2 deletions packages/postgrest/test/typed_rpc_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -91,13 +91,13 @@ void main() {

final PostgrestList rows = await client.rpc<PostgrestList>(
'list_books',
params: {'limit': 2},
params: {'max_count': 2},
get: true,
);

expect(rows, bookRows);
expect(lastRequest().method, HttpMethod.get.value);
expect(lastRequest().url.queryParameters, {'limit': '2'});
expect(lastRequest().url.queryParameters, {'max_count': '2'});
});

test('calls in the schema the client was scoped to', () async {
Expand Down
Loading