From 32d80ba6e4dea03c08d8503aa3e760214bd2d22c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Wed, 2 Dec 2026 08:56:10 +0100 Subject: [PATCH 1/9] fix: 4.1.1 - OpenAPI, generated clients and MCP describe what endpoints answer with (#36) The generators decided the response from the routine alone and ignored the endpoint's annotations, so their descriptions differed from the responses. - core: RoutineEndpoint.GetResponseKind, one decision for all generators; the cache invalidation endpoint gets the cached endpoint's custom parameters - OpenAPI: single, void (204), text/plain values, bytea, raw, table_format, json as any value, composite arrays, nested, record, SQL files with several statements, cache invalidation, proxy, login - TsClient, DartClient: raw returns text, table_format and bytea return the response, cache invalidation returns { invalidated }, Dart void annotation - MCP: outputSchema and structuredContent agree for a set with one named column, single and the void annotation --- NpgsqlRest/NpgsqlRestBuilder.cs | 6 +- NpgsqlRest/RoutineEndpoint.cs | 62 ++++ .../DartClientTests/ResponseShapeTests.cs | 219 +++++++++++ .../McpTests/McpResponseShapeTests.cs | 100 +++++ .../OpenApiTests/ResponseShapeTests.cs | 341 ++++++++++++++++++ .../OpenApiTests/SpecVersion32Tests.cs | 6 +- .../OpenApiSqlFileResponseTests.cs | 87 +++++ .../Setup/SqlFileSourceTestFixture.cs | 8 + .../TsClientTests/ResponseShapeTests.cs | 199 ++++++++++ changelog/v4.1.1.md | 92 +++++ plugins/NpgsqlRest.DartClient/DartClient.cs | 25 +- plugins/NpgsqlRest.Mcp/McpServer.cs | 115 ++++-- plugins/NpgsqlRest.OpenApi/OpenApi.cs | 95 +---- plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs | 281 +++++++++++++++ plugins/NpgsqlRest.TsClient/TsClient.cs | 20 +- 15 files changed, 1521 insertions(+), 135 deletions(-) create mode 100644 NpgsqlRestTests/DartClientTests/ResponseShapeTests.cs create mode 100644 NpgsqlRestTests/McpTests/McpResponseShapeTests.cs create mode 100644 NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs create mode 100644 NpgsqlRestTests/SqlFileSourceTests/OpenApiTests/OpenApiSqlFileResponseTests.cs create mode 100644 NpgsqlRestTests/TsClientTests/ResponseShapeTests.cs create mode 100644 changelog/v4.1.1.md create mode 100644 plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs diff --git a/NpgsqlRest/NpgsqlRestBuilder.cs b/NpgsqlRest/NpgsqlRestBuilder.cs index 13ed3efc..ce720e4e 100644 --- a/NpgsqlRest/NpgsqlRestBuilder.cs +++ b/NpgsqlRest/NpgsqlRestBuilder.cs @@ -505,7 +505,11 @@ private static Metadata Build(IApplicationBuilder? builder, RetryStrategy? defau authorizeRoles: endpoint.AuthorizeRoles, cached: true, cachedParams: endpoint.CachedParams?.ToArray(), - connectionName: endpoint.ConnectionName + connectionName: endpoint.ConnectionName, + // the endpoint's custom parameters, so that the settings of the code generators (the + // module of a generated client function, whether one is generated at all) apply to + // this endpoint as they do to the endpoint it belongs to + customParameters: endpoint.CustomParameters ) { InvalidateCache = true, diff --git a/NpgsqlRest/RoutineEndpoint.cs b/NpgsqlRest/RoutineEndpoint.cs index 9340daef..f12a1040 100644 --- a/NpgsqlRest/RoutineEndpoint.cs +++ b/NpgsqlRest/RoutineEndpoint.cs @@ -507,6 +507,49 @@ public bool OmitParameterFromGeneratedRequest(NpgsqlRestParameter parameter) => IsAutomaticParameter(parameter) && (parameter.TypeDescriptor.HasDefault || parameter.TypeDescriptor.CustomType is not null); + /// + /// What kind of response this endpoint gives. The code and documentation generators (TypeScript and Dart + /// clients, OpenAPI, MCP) decide with this method what they say about the response, so that all of them say what + /// the request handling does: the conditions are the ones of NpgsqlRestEndpoint, in the same order. Login and + /// logout endpoints are not covered here: their response is decided by the authentication scheme. + /// + /// The options the endpoint was built with (for the registered table formats). + public EndpointResponseKind GetResponseKind(NpgsqlRestOptions? options = null) + { + if (InvalidateCache) + { + return EndpointResponseKind.CacheInvalidation; + } + // proxy_out always, and proxy when the routine returns nothing: the upstream response is passed on. + if (IsProxyOut || (IsProxy && Routine.IsVoid)) + { + return EndpointResponseKind.Upstream; + } + if (Routine.IsMultiCommand && Routine.MultiCommandInfo is not null) + { + return Void ? EndpointResponseKind.NoContent : EndpointResponseKind.Routine; + } + if (Routine.IsVoid || Void) + { + return EndpointResponseKind.NoContent; + } + var binary = Routine.ColumnsTypeDescriptor is { Length: 1 } && Routine.ColumnsTypeDescriptor[0].IsBinary; + var oneValue = Routine.ReturnsSet is false && Routine.ColumnCount == 1 && Routine.ReturnsRecordType is false; + if (oneValue is false + && options?.TableFormatHandlers is not null + && CustomParameters is not null + && CustomParameters.TryGetValue("table_format", out var format) + && (options.TableFormatHandlers.ContainsKey(format) || format.Contains('{'))) + { + return EndpointResponseKind.TableFormat; + } + if (binary) + { + return EndpointResponseKind.Binary; + } + return Raw ? EndpointResponseKind.RawText : EndpointResponseKind.Routine; + } + /// /// True when this parameter is the one designated by @body_parameter_name — it carries the /// raw request body rather than a query/JSON field. The configured name is matched @@ -526,3 +569,22 @@ public bool IsBodyParameter(NpgsqlRestParameter parameter) || (parameter.ExpandedName is not null && string.Equals(BodyParameterName, parameter.ExpandedName, StringComparison.OrdinalIgnoreCase)); } } + +/// What kind of response an endpoint gives (see ). +public enum EndpointResponseKind +{ + /// What the routine returns, as JSON (or as text, for a single value that is not json or an array). + Routine, + /// 204 No Content: the routine returns nothing, or the endpoint has the void annotation. + NoContent, + /// What the routine returns, as text that is not JSON: the raw annotation. + RawText, + /// The bytes of a single bytea value. + Binary, + /// The rows in a table format (an HTML table, an Excel file...): the table_format annotation. + TableFormat, + /// The response of the upstream service, as it is: proxy_out, or proxy with a routine that returns nothing. + Upstream, + /// {"invalidated": true|false}: the cache invalidation endpoint of a cached endpoint. The routine is not run. + CacheInvalidation +} diff --git a/NpgsqlRestTests/DartClientTests/ResponseShapeTests.cs b/NpgsqlRestTests/DartClientTests/ResponseShapeTests.cs new file mode 100644 index 00000000..5ee19698 --- /dev/null +++ b/NpgsqlRestTests/DartClientTests/ResponseShapeTests.cs @@ -0,0 +1,219 @@ +namespace NpgsqlRestTests +{ + public static partial class Database + { + public static void DartClientResponseShapeTests() + { + script.Append(""" +create schema if not exists dartclient_test; + +create function dartclient_test.shape_raw() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function dartclient_test.shape_raw() is ' +dartclient_module=dart_shape +raw +separator ,'; + +create function dartclient_test.shape_void() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function dartclient_test.shape_void() is ' +dartclient_module=dart_shape +@void'; + +create function dartclient_test.shape_html() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function dartclient_test.shape_html() is ' +dartclient_module=dart_shape +@table_format = html'; + +create function dartclient_test.shape_bytes() returns bytea language sql as $$ select 'abc'::bytea $$; +comment on function dartclient_test.shape_bytes() is ' +dartclient_module=dart_shape'; + +create function dartclient_test.shape_cached() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function dartclient_test.shape_cached() is ' +dartclient_module=dart_shape +cached'; +"""); + } + } +} + +namespace NpgsqlRestTests.DartClientTests +{ + // What the generated functions return, for endpoints that do not answer with the routine's rows as JSON. + // https://github.com/NpgsqlRest/NpgsqlRest/issues/36 + [Collection("TestFixture")] + public class ResponseShapeTests + { + private const string Expected = """ +import 'dart:convert'; +import 'package:http/http.dart' as http; + +String baseUrl = ''; + +/// Override to inject a custom [http.Client] (e.g. MockClient in tests). +http.Client? httpClient; + +http.Client get _client => httpClient ??= http.Client(); + +Future _send( + String method, + Uri uri, { + Map? headers, + String? body, +}) async { + final request = http.Request(method, uri); + if (headers != null) { + request.headers.addAll(headers); + } + if (body != null) { + request.body = body; + } + return http.Response.fromStream(await _client.send(request)); +} + +class DartclientTestShapeCachedResponse { + final int? a; + final String? b; + + const DartclientTestShapeCachedResponse({ + this.a, + this.b, + }); + + factory DartclientTestShapeCachedResponse.fromJson(Map json) { + return DartclientTestShapeCachedResponse( + a: (json['a'] as num?)?.toInt(), + b: json['b'] as String?, + ); + } + + Map toJson() { + return { + 'a': a, + 'b': b, + }; + } +} + +/// function dartclient_test.shape_bytes() +/// returns bytea +/// +/// comment on function dartclient_test.shape_bytes is 'dartclient_module=dart_shape'; +/// +/// Returns `http.Response`. +/// +/// See FUNCTION dartclient_test.shape_bytes +Future dartclientTestShapeBytes() async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-bytes'); + final response = await _send('POST', uri); + return response; +} + +/// function dartclient_test.shape_cached() +/// returns table( +/// a integer, +/// b text +/// ) +/// +/// comment on function dartclient_test.shape_cached is 'dartclient_module=dart_shape +/// cached'; +/// +/// Returns `List`. +/// +/// See FUNCTION dartclient_test.shape_cached +Future> dartclientTestShapeCached() async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-cached'); + final response = await _send( + 'POST', + uri, + headers: { + 'Content-Type': 'application/json', + }, + ); + return (jsonDecode(utf8.decode(response.bodyBytes)) as List) + .map((e) => DartclientTestShapeCachedResponse.fromJson(e as Map)) + .toList(); +} + +/// function dartclient_test.shape_cached() +/// returns table( +/// a integer, +/// b text +/// ) +/// +/// comment on function dartclient_test.shape_cached is 'dartclient_module=dart_shape +/// cached'; +/// +/// Returns `Map`. +/// +/// See FUNCTION dartclient_test.shape_cached +Future> dartclientTestShapeCachedInvalidate() async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-cached/invalidate'); + final response = await _send('POST', uri); + return jsonDecode(utf8.decode(response.bodyBytes)) as Map; +} + +/// function dartclient_test.shape_html() +/// returns table( +/// a integer, +/// b text +/// ) +/// +/// comment on function dartclient_test.shape_html is 'dartclient_module=dart_shape +/// @table_format = html'; +/// +/// Returns `http.Response`. +/// +/// See FUNCTION dartclient_test.shape_html +Future dartclientTestShapeHtml() async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-html'); + final response = await _send('POST', uri); + return response; +} + +/// function dartclient_test.shape_raw() +/// returns table( +/// a integer, +/// b text +/// ) +/// +/// comment on function dartclient_test.shape_raw is 'dartclient_module=dart_shape +/// raw +/// separator ,'; +/// +/// Returns `String`. +/// +/// See FUNCTION dartclient_test.shape_raw +Future dartclientTestShapeRaw() async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-raw'); + final response = await _send('POST', uri); + return utf8.decode(response.bodyBytes); +} + +/// function dartclient_test.shape_void() +/// returns table( +/// a integer, +/// b text +/// ) +/// +/// comment on function dartclient_test.shape_void is 'dartclient_module=dart_shape +/// @void'; +/// +/// See FUNCTION dartclient_test.shape_void +Future dartclientTestShapeVoid() async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-void'); + await _send('POST', uri); +} + +"""; + + [Fact] + public void Test_ResponseShape_GeneratedFile() + { + var filePath = Path.Combine(Setup.Program.DartClientOutputPath, "dart_shape.dart"); + File.Exists(filePath).Should().BeTrue($"Expected file at {filePath}"); + + var content = File.ReadAllText(filePath); + content.Should().Be(Expected); + } + } +} diff --git a/NpgsqlRestTests/McpTests/McpResponseShapeTests.cs b/NpgsqlRestTests/McpTests/McpResponseShapeTests.cs new file mode 100644 index 00000000..d76185ee --- /dev/null +++ b/NpgsqlRestTests/McpTests/McpResponseShapeTests.cs @@ -0,0 +1,100 @@ +using NpgsqlRestTests.Setup; + +namespace NpgsqlRestTests; + +public static partial class Database +{ + // Return shapes on which a tool's outputSchema and its structuredContent used to disagree with what the + // endpoint answers. https://github.com/NpgsqlRest/NpgsqlRest/issues/36 + public static void McpResponseShapeTools() + { + script.Append(@" +create schema if not exists mcp; + +-- a set with ONE NAMED column: rows are objects, not values +create function mcp.shape_one_column() returns table(val text) language sql as 'select ''a'''; +comment on function mcp.shape_one_column() is ' +HTTP GET +@mcp A set of rows with one column.'; + +-- the same with `single`: one row, an object +create function mcp.shape_one_column_single() returns table(val text) language sql as 'select ''a'''; +comment on function mcp.shape_one_column_single() is ' +HTTP GET +@mcp One row with one column. +single'; + +-- a set of values with `single`: one value +create function mcp.shape_value_single() returns setof text language sql as 'select ''a'''; +comment on function mcp.shape_value_single() is ' +HTTP GET +@mcp One value of a set. +single'; + +-- the `void` annotation on a routine that returns rows: no body +create function mcp.shape_void() returns table(val text) language sql as 'select ''a'''; +comment on function mcp.shape_void() is ' +HTTP GET +@mcp Runs and returns nothing. +void'; +"); + } +} + +[Collection("McpPluginFixture")] +public class McpResponseShapeTests(McpPluginTestFixture test) +{ + private async Task CallAsync(string tool) + { + var json = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"" + + tool + "\",\"arguments\":{}}}"; + using var content = new StringContent(json, Encoding.UTF8, "application/json"); + using var response = await test.Client.PostAsync("/mcp", content); + response.StatusCode.Should().Be(HttpStatusCode.OK); + return await response.Content.ReadAsStringAsync(); + } + + private async Task ToolDefAsync(string tool) + { + using var content = new StringContent("""{"jsonrpc":"2.0","id":1,"method":"tools/list"}""", Encoding.UTF8, "application/json"); + using var response = await test.Client.PostAsync("/mcp", content); + var tools = JsonNode.Parse(await response.Content.ReadAsStringAsync())!["result"]!["tools"]!.AsArray(); + return tools.First(t => t!["name"]!.GetValue() == tool)!.ToJsonString(); + } + + [Fact] + public async Task Set_with_one_named_column_is_items_of_objects() + { + (await CallAsync("shape_one_column")).Should().Be( + """{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"{\"items\":[{\"val\":\"a\"}]}"}],"isError":false,"structuredContent":{"items":[{"val":"a"}]}}}"""); + (await ToolDefAsync("shape_one_column")).Should().Be( + """{"name":"shape_one_column","description":"A set of rows with one column.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true},"outputSchema":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"val":{"type":["string","null"]}}}}}}}"""); + } + + [Fact] + public async Task Single_row_with_one_named_column_is_the_object_itself() + { + (await CallAsync("shape_one_column_single")).Should().Be( + """{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"{\"val\":\"a\"}"}],"isError":false,"structuredContent":{"val":"a"}}}"""); + (await ToolDefAsync("shape_one_column_single")).Should().Be( + """{"name":"shape_one_column_single","description":"One row with one column.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true},"outputSchema":{"type":"object","properties":{"val":{"type":["string","null"]}}}}"""); + } + + [Fact] + public async Task Single_value_of_a_set_is_wrapped_as_value() + { + (await CallAsync("shape_value_single")).Should().Be( + """{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"{\"value\":\"a\"}"}],"isError":false,"structuredContent":{"value":"a"}}}"""); + (await ToolDefAsync("shape_value_single")).Should().Be( + """{"name":"shape_value_single","description":"One value of a set.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true},"outputSchema":{"type":"object","properties":{"value":{"type":["string","null"]}}}}"""); + } + + [Fact] + public async Task Void_annotation_has_no_structured_content_and_no_output_schema() + { + (await CallAsync("shape_void")).Should().Be( + """{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":""}],"isError":false}}"""); + (await ToolDefAsync("shape_void")).Should().Be( + """{"name":"shape_void","description":"Runs and returns nothing.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true}}"""); + } +} diff --git a/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs new file mode 100644 index 00000000..36a74c64 --- /dev/null +++ b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs @@ -0,0 +1,341 @@ +using System.Text.Json.Nodes; + +namespace NpgsqlRestTests +{ + public static partial class Database + { + public static void OpenApiResponseShapeTests() + { + script.Append(""" +create function oas_shape_register_thing() +returns table (thing_id int, name text) +language sql +as $$ +select 1, 'a'; +$$; +comment on function oas_shape_register_thing() is ' +@http POST /api/oas-shape/things +@single +Registers a thing.'; + +create function oas_shape_rows() returns table (thing_id int, name text) language sql as $$ select 1, 'a' $$; +comment on function oas_shape_rows() is 'HTTP GET'; + +create function oas_shape_values() returns setof text language sql as $$ select * from (values ('a'), ('b')) t(v) $$; +comment on function oas_shape_values() is 'HTTP GET'; + +create function oas_shape_single_value() returns setof text language sql as $$ select * from (values ('a'), ('b')) t(v) $$; +comment on function oas_shape_single_value() is ' +HTTP GET +@single'; + +create function oas_shape_one_column() returns table (val text) language sql as $$ select 'a' $$; +comment on function oas_shape_one_column() is 'HTTP GET'; + +create function oas_shape_void_annotation() returns table (thing_id int, name text) language sql as $$ select 1, 'a' $$; +comment on function oas_shape_void_annotation() is ' +HTTP GET +@void'; + +create function oas_shape_void() returns void language plpgsql as $$ begin end $$; +comment on function oas_shape_void() is 'HTTP GET'; + +create function oas_shape_text() returns text language sql as $$ select 'x' $$; +comment on function oas_shape_text() is 'HTTP GET'; + +create function oas_shape_int() returns int language sql as $$ select 42 $$; +comment on function oas_shape_int() is 'HTTP GET'; + +create function oas_shape_bool() returns boolean language sql as $$ select true $$; +comment on function oas_shape_bool() is 'HTTP GET'; + +create function oas_shape_json() returns json language sql as $$ select '[1,2]'::json $$; +comment on function oas_shape_json() is 'HTTP GET'; + +create function oas_shape_int_array() returns int[] language sql as $$ select array[1,2] $$; +comment on function oas_shape_int_array() is 'HTTP GET'; + +create function oas_shape_raw() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function oas_shape_raw() is ' +HTTP GET +raw +separator ,'; + +create function oas_shape_bytes() returns bytea language sql as $$ select 'abc'::bytea $$; +comment on function oas_shape_bytes() is 'HTTP GET'; + +create function oas_shape_record() returns record language sql as $$ select 1, 'a'::text $$; +comment on function oas_shape_record() is 'HTTP GET'; + +create function oas_shape_json_column() returns table (id int, data json) language sql as $$ select 1, '[1,2]'::json $$; +comment on function oas_shape_json_column() is 'HTTP GET'; + +create type oas_shape_part as (id int, label text); + +create function oas_shape_parts() returns table (id int, parts oas_shape_part[]) +language sql as $$ select 1, array[row(10, 'x')::oas_shape_part] $$; +comment on function oas_shape_parts() is 'HTTP GET'; + +create function oas_shape_part_flat() returns table (code int, part oas_shape_part) +language sql as $$ select 1, row(10, 'x')::oas_shape_part $$; +comment on function oas_shape_part_flat() is 'HTTP GET'; + +create function oas_shape_part_nested() returns table (code int, part oas_shape_part) +language sql as $$ select 1, row(10, 'x')::oas_shape_part $$; +comment on function oas_shape_part_nested() is ' +HTTP GET +nested'; + +create function oas_shape_html() returns table (id int, name text) language sql as $$ select 1, 'a' $$; +comment on function oas_shape_html() is ' +HTTP GET +@table_format = html'; + +create function oas_shape_cached() returns table (id int, name text) language sql as $$ select 1, 'a' $$; +comment on function oas_shape_cached() is ' +HTTP GET +cached'; + +create function oas_shape_proxy() returns void language plpgsql as $$ begin raise exception 'not called'; end $$; +comment on function oas_shape_proxy() is 'HTTP GET +proxy GET /api/oas-shape-text'; + +create function oas_shape_content_type(_type text) returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function oas_shape_content_type(text) is ' +HTTP GET +raw +separator , +Content-Type: {_type}'; + +create function oas_shape_login() returns table (name_identifier int, name text) language sql as $$ select 1, 'user' $$; +comment on function oas_shape_login() is ' +HTTP POST +login'; +"""); + } + } +} + +namespace NpgsqlRestTests.OpenApiTests +{ + // What the OpenAPI document says an endpoint answers with, next to what the endpoint answers with. + // https://github.com/NpgsqlRest/NpgsqlRest/issues/36 + [Collection("TestFixture")] + public class ResponseShapeTests(TestFixture test) + { + private static readonly Lazy Document = new(() => + { + var filePath = Path.Combine(Setup.Program.OpenApiOutputPath, "openapi.json"); + File.Exists(filePath).Should().BeTrue($"Expected file at {filePath}"); + return JsonNode.Parse(File.ReadAllText(filePath))!; + }); + + /// The "responses" of an operation in the document. + private static string Documented(string path, string method = "get") + { + var operation = Document.Value["paths"]?[path]?[method]; + operation.Should().NotBeNull($"{method} {path} should be documented"); + return operation!["responses"]!.ToJsonString(); + } + + /// What the endpoint answers with: status, content type and body. + private async Task Answered(string path, string method = "GET") + { + using var request = new HttpRequestMessage(new HttpMethod(method), path); + using var response = await test.Client.SendAsync(request); + return $"{(int)response.StatusCode} {response.Content.Headers.ContentType?.MediaType} {await response.Content.ReadAsStringAsync()}"; + } + + private const string ThingProperties = """{"thingId":{"type":"integer","format":"int32"},"name":{"type":"string"}}"""; + + private static string Ok(string contentType, string schema) => + "{\"200\":{\"description\":\"Successful response\",\"content\":{\"" + contentType + "\":{\"schema\":" + schema + "}}}}"; + + private const string NoContent = """{"204":{"description":"No content"}}"""; + + [Fact] + public async Task Single_on_a_set_of_rows_is_one_object() + { + (await Answered("/api/oas-shape/things", "POST")).Should().Be("""200 application/json {"thingId":1,"name":"a"}"""); + Documented("/api/oas-shape/things", "post").Should().Be( + Ok("application/json", """{"type":"object","properties":""" + ThingProperties + "}")); + } + + [Fact] + public async Task Set_of_rows_is_an_array_of_objects() + { + (await Answered("/api/oas-shape-rows")).Should().Be("""200 application/json [{"thingId":1,"name":"a"}]"""); + Documented("/api/oas-shape-rows").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":""" + ThingProperties + "}}")); + } + + [Fact] + public async Task Set_of_values_is_an_array_of_values() + { + (await Answered("/api/oas-shape-values")).Should().Be("""200 application/json ["a","b"]"""); + Documented("/api/oas-shape-values").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"string"}}""")); + } + + [Fact] + public async Task Single_on_a_set_of_values_is_one_value() + { + (await Answered("/api/oas-shape-single-value")).Should().Be("""200 application/json "a" """.TrimEnd()); + Documented("/api/oas-shape-single-value").Should().Be(Ok("application/json", """{"type":"string"}""")); + } + + [Fact] + public async Task Set_with_one_named_column_is_an_array_of_objects() + { + (await Answered("/api/oas-shape-one-column")).Should().Be("""200 application/json [{"val":"a"}]"""); + Documented("/api/oas-shape-one-column").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":{"val":{"type":"string"}}}}""")); + } + + [Fact] + public async Task Void_annotation_has_no_body() + { + (await Answered("/api/oas-shape-void-annotation")).Should().Be("204 "); + Documented("/api/oas-shape-void-annotation").Should().Be(NoContent); + } + + [Fact] + public async Task Routine_that_returns_nothing_has_no_body() + { + (await Answered("/api/oas-shape-void")).Should().Be("204 "); + Documented("/api/oas-shape-void").Should().Be(NoContent); + } + + [Fact] + public async Task Text_value_is_plain_text() + { + (await Answered("/api/oas-shape-text")).Should().Be("200 text/plain x"); + Documented("/api/oas-shape-text").Should().Be(Ok("text/plain", """{"type":"string"}""")); + } + + [Fact] + public async Task Number_value_is_plain_text() + { + (await Answered("/api/oas-shape-int")).Should().Be("200 text/plain 42"); + Documented("/api/oas-shape-int").Should().Be(Ok("text/plain", """{"type":"integer","format":"int32"}""")); + } + + [Fact] + public async Task Boolean_value_is_plain_text_t_or_f() + { + (await Answered("/api/oas-shape-bool")).Should().Be("200 text/plain t"); + Documented("/api/oas-shape-bool").Should().Be(Ok("text/plain", """{"type":"string","enum":["t","f"]}""")); + } + + [Fact] + public async Task Json_value_is_any_json() + { + (await Answered("/api/oas-shape-json")).Should().Be("200 application/json [1,2]"); + Documented("/api/oas-shape-json").Should().Be(Ok("application/json", "{}")); + } + + [Fact] + public async Task Array_value_is_a_json_array() + { + (await Answered("/api/oas-shape-int-array")).Should().Be("200 application/json [1,2]"); + Documented("/api/oas-shape-int-array").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"integer","format":"int32"}}""")); + } + + [Fact] + public async Task Raw_is_text_and_not_an_array() + { + (await Answered("/api/oas-shape-raw")).Should().Be("""200 application/json 1,"x" """.TrimEnd()); + Documented("/api/oas-shape-raw").Should().Be(Ok("application/json", """{"type":"string"}""")); + } + + [Fact] + public async Task Bytea_value_is_bytes() + { + (await Answered("/api/oas-shape-bytes")).Should().Be("200 application/octet-stream abc"); + Documented("/api/oas-shape-bytes").Should().Be( + Ok("application/octet-stream", """{"type":"string","format":"binary"}""")); + } + + [Fact] + public async Task Record_without_columns_is_an_array_of_texts() + { + (await Answered("/api/oas-shape-record")).Should().Be("""200 application/json ["1","a"]"""); + Documented("/api/oas-shape-record").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"string"}}""")); + } + + [Fact] + public async Task Json_column_is_any_json() + { + (await Answered("/api/oas-shape-json-column")).Should().Be("""200 application/json [{"id":1,"data":[1,2]}]"""); + Documented("/api/oas-shape-json-column").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"data":{}}}}""")); + } + + [Fact] + public async Task Array_of_composite_values_is_an_array_of_objects() + { + (await Answered("/api/oas-shape-parts")).Should().Be("""200 application/json [{"id":1,"parts":[{"id":10,"label":"x"}]}]"""); + Documented("/api/oas-shape-parts").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"parts":{"type":"array","items":{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"label":{"type":"string"}}}}}}}""")); + } + + [Fact] + public async Task Composite_value_is_its_fields_in_the_row() + { + (await Answered("/api/oas-shape-part-flat")).Should().Be("""200 application/json [{"code":1,"id":10,"label":"x"}]"""); + Documented("/api/oas-shape-part-flat").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":{"code":{"type":"integer","format":"int32"},"id":{"type":"integer","format":"int32"},"label":{"type":"string"}}}}""")); + } + + [Fact] + public async Task Nested_composite_value_is_an_object_in_the_row() + { + (await Answered("/api/oas-shape-part-nested")).Should().Be("""200 application/json [{"code":1,"part":{"id":10,"label":"x"}}]"""); + Documented("/api/oas-shape-part-nested").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":{"code":{"type":"integer","format":"int32"},"part":{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"label":{"type":"string"}}}}}}""")); + } + + [Fact] + public async Task Table_format_is_the_content_type_of_the_format() + { + (await Answered("/api/oas-shape-html")).Should().StartWith("200 text/html "); + Documented("/api/oas-shape-html").Should().Be(Ok("text/html; charset=utf-8", """{"type":"string"}""")); + } + + [Fact] + public async Task Cache_invalidation_endpoint_says_whether_it_removed_something() + { + (await Answered("/api/oas-shape-cached/invalidate")).Should().Be("""200 application/json {"invalidated":false}"""); + Documented("/api/oas-shape-cached/invalidate").Should().Be( + """{"200":{"description":"Whether a cached response was removed","content":{"application/json":{"schema":{"type":"object","properties":{"invalidated":{"type":"boolean"}}}}}}}"""); + // the cached endpoint itself answers with the routine's rows + Documented("/api/oas-shape-cached").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"name":{"type":"string"}}}}""")); + } + + [Fact] + public async Task Proxy_of_a_routine_that_returns_nothing_is_the_upstream_response() + { + (await Answered("/api/oas-shape-proxy")).Should().Be("200 text/plain x"); + Documented("/api/oas-shape-proxy").Should().Be( + """{"200":{"description":"The response of the upstream service","content":{"*/*":{}}}}"""); + } + + [Fact] + public async Task Content_type_from_a_parameter_is_not_known_in_advance() + { + (await Answered("/api/oas-shape-content-type?type=text/csv")).Should().Be("""200 text/csv 1,"x" """.TrimEnd()); + Documented("/api/oas-shape-content-type").Should().Be( + """{"200":{"description":"Successful response","content":{"*/*":{"schema":{"type":"string"}}}}}"""); + } + + [Fact] + public void Login_body_depends_on_the_authentication_scheme() + { + Documented("/api/oas-shape-login", "post").Should().Be( + """{"200":{"description":"Signed in. The body depends on the authentication scheme","content":{"*/*":{}}}}"""); + } + } +} diff --git a/NpgsqlRestTests/OpenApiTests/SpecVersion32Tests.cs b/NpgsqlRestTests/OpenApiTests/SpecVersion32Tests.cs index 882bae4c..c003514a 100644 --- a/NpgsqlRestTests/OpenApiTests/SpecVersion32Tests.cs +++ b/NpgsqlRestTests/OpenApiTests/SpecVersion32Tests.cs @@ -152,21 +152,21 @@ public void Query_operation_with_its_parameters_in_the_body() public void Query_operation_without_parameters() { Doc32["paths"]!["/api/openapi-q32-no-params"]!.ToJsonString().Should().Be( - """{"query":{"summary":"Function public.openapi_q32_no_params","tags":["public"],"operationId":"public_openapi_q32_no_params_query","responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"string"}}}}}}}"""); + """{"query":{"summary":"Function public.openapi_q32_no_params","tags":["public"],"operationId":"public_openapi_q32_no_params_query","responses":{"200":{"description":"Successful response","content":{"text/plain":{"schema":{"type":"string"}}}}}}}"""); } [Fact] public void Query_operation_with_a_path_parameter() { Doc32["paths"]!["/api/openapi-q32/{_category}/search"]!.ToJsonString().Should().Be( - """{"query":{"summary":"Function public.openapi_q32_in_path","tags":["public"],"operationId":"public_openapi_q32_in_path_query","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"term":{"type":"string"}},"required":["term"]}}}},"parameters":[{"name":"category","in":"path","required":true,"schema":{"type":"integer","format":"int32"}}],"responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"string"}}}}}}}"""); + """{"query":{"summary":"Function public.openapi_q32_in_path","tags":["public"],"operationId":"public_openapi_q32_in_path_query","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"term":{"type":"string"}},"required":["term"]}}}},"parameters":[{"name":"category","in":"path","required":true,"schema":{"type":"integer","format":"int32"}}],"responses":{"200":{"description":"Successful response","content":{"text/plain":{"schema":{"type":"string"}}}}}}}"""); } [Fact] public void Query_operation_with_parameters_in_the_query_string() { Doc32["paths"]!["/api/openapi-q32-query-string"]!.ToJsonString().Should().Be( - """{"query":{"summary":"Function public.openapi_q32_query_string","tags":["public"],"operationId":"public_openapi_q32_query_string_query","parameters":[{"name":"term","in":"query","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"string"}}}}}}}"""); + """{"query":{"summary":"Function public.openapi_q32_query_string","tags":["public"],"operationId":"public_openapi_q32_query_string_query","parameters":[{"name":"term","in":"query","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Successful response","content":{"text/plain":{"schema":{"type":"string"}}}}}}}"""); } [Fact] diff --git a/NpgsqlRestTests/SqlFileSourceTests/OpenApiTests/OpenApiSqlFileResponseTests.cs b/NpgsqlRestTests/SqlFileSourceTests/OpenApiTests/OpenApiSqlFileResponseTests.cs new file mode 100644 index 00000000..192e19cf --- /dev/null +++ b/NpgsqlRestTests/SqlFileSourceTests/OpenApiTests/OpenApiSqlFileResponseTests.cs @@ -0,0 +1,87 @@ +using System.Text.Json.Nodes; +using NpgsqlRestTests.Setup; + +namespace NpgsqlRestTests.SqlFileSourceTests; + +public static partial class SqlFiles +{ + public static void OpenApiSqlFileResponseTests() + { + // One statement, one row + File.WriteAllText(Path.Combine(Dir, "oas_sf_single.sql"), """ + -- HTTP GET + -- @single + select 1 as id, 'a' as name; + """); + + // Several statements: a single row, a skipped statement, a statement that returns nothing, a set + File.WriteAllText(Path.Combine(Dir, "oas_sf_multi.sql"), """ + -- HTTP POST + -- @single + -- @result thing + select 1 as id, 'a' as name; + -- @skip + select 1; + -- @result changed + update sql_describe_test set active = active where false; + -- @result things + select 2 as id, 'b' as name; + """); + + // Several statements with the void annotation: all are run, nothing is returned + File.WriteAllText(Path.Combine(Dir, "oas_sf_multi_void.sql"), """ + -- HTTP POST + -- @void + select 1 as id; + select 2 as id; + """); + } +} + +// What the OpenAPI document says an SQL file endpoint answers with, next to what the endpoint answers with. +// https://github.com/NpgsqlRest/NpgsqlRest/issues/36 +[Collection("SqlFileSourceFixture")] +public class OpenApiSqlFileResponseTests(SqlFileSourceTestFixture test) +{ + private string Documented(string path, string method) + { + File.Exists(test.OpenApiFile).Should().BeTrue($"Expected file at {test.OpenApiFile}"); + var operation = JsonNode.Parse(File.ReadAllText(test.OpenApiFile))!["paths"]?[path]?[method]; + operation.Should().NotBeNull($"{method} {path} should be documented"); + return operation!["responses"]!.ToJsonString(); + } + + private async Task Answered(string path, string method) + { + using var request = new HttpRequestMessage(new HttpMethod(method), path); + using var response = await test.Client.SendAsync(request); + return $"{(int)response.StatusCode} {response.Content.Headers.ContentType?.MediaType} {await response.Content.ReadAsStringAsync()}"; + } + + private const string Thing = """{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"name":{"type":"string"}}}"""; + + [Fact] + public async Task Single_statement_with_single_is_one_object() + { + (await Answered("/api/oas-sf-single", "GET")).Should().Be("""200 application/json {"id":1,"name":"a"}"""); + Documented("/api/oas-sf-single", "get").Should().Be( + """{"200":{"description":"Successful response","content":{"application/json":{"schema":""" + Thing + "}}}}"); + } + + [Fact] + public async Task Several_statements_are_an_object_with_a_property_for_each() + { + (await Answered("/api/oas-sf-multi", "POST")).Should().Be( + """200 application/json {"thing":{"id":1,"name":"a"},"changed":0,"things":[{"id":2,"name":"b"}]}"""); + Documented("/api/oas-sf-multi", "post").Should().Be( + """{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"object","properties":{"thing":""" + + Thing + ""","changed":{"type":"integer"},"things":{"type":"array","items":""" + Thing + "}}}}}}}"); + } + + [Fact] + public async Task Several_statements_with_void_have_no_body() + { + (await Answered("/api/oas-sf-multi-void", "POST")).Should().Be("204 "); + Documented("/api/oas-sf-multi-void", "post").Should().Be("""{"204":{"description":"No content"}}"""); + } +} diff --git a/NpgsqlRestTests/SqlFileSourceTests/Setup/SqlFileSourceTestFixture.cs b/NpgsqlRestTests/SqlFileSourceTests/Setup/SqlFileSourceTestFixture.cs index 67db469c..431782d1 100644 --- a/NpgsqlRestTests/SqlFileSourceTests/Setup/SqlFileSourceTestFixture.cs +++ b/NpgsqlRestTests/SqlFileSourceTests/Setup/SqlFileSourceTestFixture.cs @@ -32,6 +32,7 @@ public class SqlFileSourceTestFixture : IDisposable public WebApplication App => _app; public string SqlDir => _sqlDir; public string TsClientDir => _tsClientDir; + public string OpenApiFile => Path.Combine(_tsClientDir, "openapi.json"); /// /// Create a fresh HttpClient with its own cookie container (for auth test isolation). @@ -146,6 +147,13 @@ public SqlFileSourceTestFixture() FilePath = Path.Combine(_tsClientDir, "{0}.ts"), BySchema = true, IncludeStatusCode = false, + }), + // The OpenAPI document of the SQL file endpoints (OpenApiSqlFileResponseTests) + new NpgsqlRest.OpenAPI.OpenApi(new NpgsqlRest.OpenAPI.OpenApiOptions + { + FileName = OpenApiFile, + FileOverwrite = true, + AddCurrentServer = false }) ], }); diff --git a/NpgsqlRestTests/TsClientTests/ResponseShapeTests.cs b/NpgsqlRestTests/TsClientTests/ResponseShapeTests.cs new file mode 100644 index 00000000..c878a4af --- /dev/null +++ b/NpgsqlRestTests/TsClientTests/ResponseShapeTests.cs @@ -0,0 +1,199 @@ +namespace NpgsqlRestTests +{ + public static partial class Database + { + public static void TsClientResponseShapeTests() + { + script.Append(""" +create schema if not exists tsclient_test; + +create function tsclient_test.shape_raw() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function tsclient_test.shape_raw() is ' +tsclient_module=shape +raw +separator ,'; + +create function tsclient_test.shape_void() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function tsclient_test.shape_void() is ' +tsclient_module=shape +@void'; + +create function tsclient_test.shape_html() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function tsclient_test.shape_html() is ' +tsclient_module=shape +@table_format = html'; + +create function tsclient_test.shape_bytes() returns bytea language sql as $$ select 'abc'::bytea $$; +comment on function tsclient_test.shape_bytes() is ' +tsclient_module=shape'; + +create function tsclient_test.shape_cached() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function tsclient_test.shape_cached() is ' +tsclient_module=shape +cached'; +"""); + } + } +} + +namespace NpgsqlRestTests.TsClientTests +{ + // What the generated functions return, for endpoints that do not answer with the routine's rows as JSON. + // https://github.com/NpgsqlRest/NpgsqlRest/issues/36 + [Collection("TestFixture")] + public class ResponseShapeTests + { + private const string Expected = """ +const baseUrl = ""; + +interface ITsclientTestShapeCachedResponse { + a: number | null; + b: string | null; +} + + +/** +* function tsclient_test.shape_bytes() +* returns bytea +* +* @remarks +* comment on function tsclient_test.shape_bytes is 'tsclient_module=shape +* +* @returns {Response} +* +* @see FUNCTION tsclient_test.shape_bytes +*/ +export async function tsclientTestShapeBytes() : Promise { + const response = await fetch(baseUrl + "/api/tsclient-test/shape-bytes", { + method: "POST", + }); + return response; +} + +/** +* function tsclient_test.shape_cached() +* returns table( +* a integer, +* b text +* ) +* +* @remarks +* comment on function tsclient_test.shape_cached is 'tsclient_module=shape +* cached'; +* +* @returns {ITsclientTestShapeCachedResponse[]} +* +* @see FUNCTION tsclient_test.shape_cached +*/ +export async function tsclientTestShapeCached() : Promise { + const response = await fetch(baseUrl + "/api/tsclient-test/shape-cached", { + method: "POST", + headers: { + "Content-Type": "application/json" + }, + }); + return await response.json() as ITsclientTestShapeCachedResponse[]; +} + +/** +* function tsclient_test.shape_cached() +* returns table( +* a integer, +* b text +* ) +* +* @remarks +* comment on function tsclient_test.shape_cached is 'tsclient_module=shape +* cached'; +* +* @returns { invalidated: boolean } +* +* @see FUNCTION tsclient_test.shape_cached +*/ +export async function tsclientTestShapeCachedInvalidate() : Promise<{ invalidated: boolean }> { + const response = await fetch(baseUrl + "/api/tsclient-test/shape-cached/invalidate", { + method: "POST", + }); + return await response.json() as { invalidated: boolean }; +} + +/** +* function tsclient_test.shape_html() +* returns table( +* a integer, +* b text +* ) +* +* @remarks +* comment on function tsclient_test.shape_html is 'tsclient_module=shape +* table_format = html'; +* +* @returns {Response} +* +* @see FUNCTION tsclient_test.shape_html +*/ +export async function tsclientTestShapeHtml() : Promise { + const response = await fetch(baseUrl + "/api/tsclient-test/shape-html", { + method: "POST", + }); + return response; +} + +/** +* function tsclient_test.shape_raw() +* returns table( +* a integer, +* b text +* ) +* +* @remarks +* comment on function tsclient_test.shape_raw is 'tsclient_module=shape +* raw +* separator ,'; +* +* @returns {string} +* +* @see FUNCTION tsclient_test.shape_raw +*/ +export async function tsclientTestShapeRaw() : Promise { + const response = await fetch(baseUrl + "/api/tsclient-test/shape-raw", { + method: "POST", + }); + return await response.text(); +} + +/** +* function tsclient_test.shape_void() +* returns table( +* a integer, +* b text +* ) +* +* @remarks +* comment on function tsclient_test.shape_void is 'tsclient_module=shape +* void'; +* +* @returns {void} +* +* @see FUNCTION tsclient_test.shape_void +*/ +export async function tsclientTestShapeVoid() : Promise { + await fetch(baseUrl + "/api/tsclient-test/shape-void", { + method: "POST", + }); +} + + +"""; + + [Fact] + public void Test_ResponseShape_GeneratedFile() + { + var filePath = Path.Combine(Setup.Program.TsClientOutputPath, "shape.ts"); + File.Exists(filePath).Should().BeTrue($"Expected file at {filePath}"); + + var content = File.ReadAllText(filePath); + content.Should().Be(Expected); + } + } +} diff --git a/changelog/v4.1.1.md b/changelog/v4.1.1.md new file mode 100644 index 00000000..be8460c1 --- /dev/null +++ b/changelog/v4.1.1.md @@ -0,0 +1,92 @@ +# Changelog v4.1.1 + +## Version [4.1.1](https://github.com/NpgsqlRest/NpgsqlRest/tree/4.1.1) (not released yet) + +[Full Changelog](https://github.com/NpgsqlRest/NpgsqlRest/compare/4.1.0...4.1.1) + +Patch release. What the generators say an endpoint answers with now matches what the endpoint answers with: the OpenAPI document, the generated TypeScript and Dart clients, and the MCP tool schemas. Reported in [#36](https://github.com/NpgsqlRest/NpgsqlRest/issues/36) for one case (`@single` in the OpenAPI document). The other cases were found by calling every endpoint of the test suite and comparing each answer with the document. No endpoint answers differently than before, and no configuration key was added or changed. + +**Who should upgrade:** everyone who generates clients from `openapi.json`, and everyone who uses `raw`, `table_format`, `bytea` results, the `void` annotation or cache invalidation endpoints with the generated TypeScript or Dart clients or with MCP tools. + +**After upgrading:** regenerate the OpenAPI document and the clients. The descriptions of some endpoints change (the list is below), so clients generated from them change as well. + +### Fixes + +#### OpenAPI: the described response did not match the response + +The document decided the response from the routine alone and did not look at the endpoint's annotations. Before the fix, 482 of the 1,271 answers of the test suite's endpoints that could be compared were not what the document said. What is left are answers that depend on data (a `NULL` result has no body) and arrays of more than one dimension (the number of dimensions is not part of a PostgreSQL array type). + +| Endpoint | The document said | The endpoint answers with, and the document now says | +|---|---|---| +| `single` on a set of rows ([#36](https://github.com/NpgsqlRest/NpgsqlRest/issues/36)) | an array of objects | one object | +| `single` on a set of values (`returns setof text`) | an array of objects | one value | +| a set of values (`returns setof text`) | an array of objects | an array of values | +| `void` annotation, or a routine that returns nothing | `200` | `204`, no body | +| a single value that is not `json` or an array (`returns text`, `int`, `boolean`...) | `application/json` | `text/plain`; a boolean is `t` or `f` | +| `bytea` | `application/json`, a string | `application/octet-stream` | +| `raw` | an array of objects | a string | +| `table_format` (HTML, Excel) | `application/json`, an array of objects | the content type of the format | +| `json` and `jsonb` values and columns | an object | any JSON value | +| a column that is an array of a composite type | an array of strings | an array of objects with the type's fields | +| `nested` composite columns | the fields of the type as columns of the row | one object under the column name | +| `returns record` | an object | an array of strings | +| SQL files with several statements | the columns of the first statement | an object with a property for each statement: its rows (one object with `single`), or the number of rows it affected | +| cache invalidation endpoint (`InvalidateCacheSuffix`) | the response of the cached endpoint | `{"invalidated": true}` or `{"invalidated": false}` | +| `proxy` with a routine that returns nothing, and `proxy_out` | no body | the response of the upstream service (`*/*`) | +| `login` | the routine's columns | a body that depends on the authentication scheme (`*/*`) | +| a content type taken from a parameter (`Content-Type: {_type}`) | the content type `{_type}` | `*/*` | + +For the function in the report + +```sql +create function api.register_thing() +returns table (thing_id uuid, name text) +language sql +begin atomic + select gen_random_uuid(), 'a'; +end; +comment on function api.register_thing() is ' +@http POST /api/things +@single +Registers a thing.'; +``` + +the response in `openapi.json` was + +```json +"200": { "description": "Successful response", "content": { "application/json": { "schema": { + "type": "array", "items": { "type": "object", "properties": { "thingId": { "type": "string", "format": "uuid" }, "name": { "type": "string" } } } +} } } } +``` + +and is now + +```json +"200": { "description": "Successful response", "content": { "application/json": { "schema": { + "type": "object", "properties": { "thingId": { "type": "string", "format": "uuid" }, "name": { "type": "string" } } +} } } } +``` + +#### TypeScript and Dart clients: functions that read the wrong kind of response + +- **`raw`.** The function read the response as JSON (`response.json()`, `jsonDecode`) and failed, because a `raw` endpoint answers with text. It now returns the text (`string`, `String`). +- **`table_format` and `bytea`.** The function read an HTML table or an Excel file as JSON, and bytes as text. It now returns the response itself (`Response`, `http.Response`), as functions of proxy endpoints do, so the caller reads it as text or as bytes. +- **Cache invalidation endpoints.** The function was typed as the cached endpoint's response. It now returns `{ invalidated: boolean }` (`Map` in Dart). It is also written to the same module as the function of the cached endpoint, and the other `tsclient_...` and `dartclient_...` annotations of that endpoint apply to it. Before, they did not, and the function went to the default module. +- **Dart, `void` annotation.** The function read a body from an endpoint that answers `204` without one. The TypeScript client was already correct. + +#### MCP: `outputSchema` and `structuredContent` for four return shapes + +- **A set with one named column** (`returns table (val text)`): the schema said `items` are values, and they are objects (`{"val": ...}`). +- **`single` on a set with one named column:** the row was wrapped as text (`{"value": "{\"val\":\"a\"}"}`). It is now the object itself (`{"val": "a"}`). +- **`single` on a set of values:** a text value kept its JSON quotes (`{"value": "\"a\""}`). It is now the value (`{"value": "a"}`). +- **`void` annotation:** the tool declared an `outputSchema` and returned no `structuredContent`. It now declares none. + +### For plugin authors + +`RoutineEndpoint.GetResponseKind(NpgsqlRestOptions?)` returns what kind of response an endpoint gives (`EndpointResponseKind`: `Routine`, `NoContent`, `RawText`, `Binary`, `TableFormat`, `Upstream`, `CacheInvalidation`). The four generators above now use it instead of each deciding on its own, which is how they came to disagree. A custom `IEndpointCreateHandler` that describes responses should use it as well. + +### Not changed, found on the way + +- A `money` column in a set of rows is written without quotes (`"price":$1.00`), which is not valid JSON. +- A `raw` endpoint with no content type set answers with the content type `application/json`. The document now describes its body as a string under that content type. +- The cache invalidation endpoint of an endpoint that is hidden from the document (`openapi hide`) is still in the document. diff --git a/plugins/NpgsqlRest.DartClient/DartClient.cs b/plugins/NpgsqlRest.DartClient/DartClient.cs index 0fe00906..1406636e 100644 --- a/plugins/NpgsqlRest.DartClient/DartClient.cs +++ b/plugins/NpgsqlRest.DartClient/DartClient.cs @@ -396,7 +396,9 @@ bool Handle(RoutineEndpoint endpoint) var routineType = routine.Type; var paramCount = routine.ParamCount; - var isVoid = routine.IsVoid; + // endpoint.Void: the void annotation. The endpoint answers 204 with no body whatever the routine + // returns, so the client function must not read a body from it. + var isVoid = routine.IsVoid || endpoint.Void; var returnsSet = routine.ReturnsSet; var columnCount = routine.ColumnCount; var returnsRecordType = routine.ReturnsRecordType; @@ -511,14 +513,31 @@ bool Handle(RoutineEndpoint endpoint) // to upstream). Void proxy pass-through likewise. There is no typed Dart shape for those, // so the generated function returns http.Response directly. Transform proxies (non-void // @proxy routines) return processed data and fall through to normal handling. - if ((endpoint.IsProxyOut || (endpoint.IsProxy && routine.IsVoid)) && !urlOnly) + // What the endpoint answers with is decided in one place for all generators (GetResponseKind). The same + // goes for rows in a table format (an HTML table, an Excel file) and for bytes (bytea). + var responseKind = endpoint.Login || endpoint.Logout + ? EndpointResponseKind.Routine + : endpoint.GetResponseKind(_npgsqlRestoptions); + if (responseKind is EndpointResponseKind.Upstream or EndpointResponseKind.TableFormat or EndpointResponseKind.Binary && !urlOnly) { responseIsRaw = true; includeStatusCode = false; responseName = "http.Response"; payloadLines = ["response"]; } - else if (routine.IsMultiCommand && routine.MultiCommandInfo is not null && !urlOnly) + else if (responseKind == EndpointResponseKind.CacheInvalidation && !urlOnly) + { + // the cache invalidation endpoint of a cached endpoint: {"invalidated": true|false}; the routine is not run + responseName = "Map"; + payloadLines = [$"{JsonDecodeExpr} as Map"]; + } + else if (responseKind == EndpointResponseKind.RawText && !urlOnly) + { + // the raw annotation: the values as text, not JSON + responseName = "String"; + payloadLines = ["utf8.decode(response.bodyBytes)"]; + } + else if (routine.IsMultiCommand && routine.MultiCommandInfo is not null && !urlOnly && !endpoint.Void) { // Multi-command SQL file: generate response class with one field per command result List mcFields = []; diff --git a/plugins/NpgsqlRest.Mcp/McpServer.cs b/plugins/NpgsqlRest.Mcp/McpServer.cs index 577568b3..ff80598a 100644 --- a/plugins/NpgsqlRest.Mcp/McpServer.cs +++ b/plugins/NpgsqlRest.Mcp/McpServer.cs @@ -476,65 +476,105 @@ private async Task HandleToolCallAsync(HttpContext context, JsonNode? request, J private static JsonObject? BuildStructuredContent(RoutineEndpoint endpoint, string? body) { var routine = endpoint.Routine; - if (routine.IsVoid || string.IsNullOrWhiteSpace(body)) + if (string.IsNullOrWhiteSpace(body)) { return null; } - // A set returns a JSON array → wrap as { "items": [...] }. (`single` collapses a set to one row.) - if (routine.ReturnsSet && !endpoint.ReturnSingleRecord) + switch (ShapeOf(endpoint)) { - return TryParseJson(body) switch - { - JsonArray array => new JsonObject { ["items"] = array }, + case OutputShape.Items: + // A set returns a JSON array → wrap as { "items": [...] }. + return TryParseJson(body) is JsonArray array ? new JsonObject { ["items"] = array } : null; + case OutputShape.Results: // A multi-command SQL file returns an object keyed per result set ({ "result1": [...], … }) — // already a valid structuredContent object. - JsonObject obj => obj, - _ => null, - }; - } - - // A single scalar value → { "value": ... }; a single record/composite → the object itself. - if (routine.ColumnCount == 1 && !routine.ReturnsRecordType) - { - var type = routine.ColumnsTypeDescriptor.Length > 0 ? routine.ColumnsTypeDescriptor[0] : null; - return new JsonObject { ["value"] = ScalarValue(body, type) }; + return TryParseJson(body) as JsonObject; + case OutputShape.Value: + // One value. A routine returning a single value answers with it as text; one row of a set of + // values (`single`) answers with it as JSON. + if (routine.ReturnsSet || routine.ReturnsRecordType) + { + return new JsonObject { ["value"] = TryParseJson(body) ?? JsonValue.Create(body) }; + } + var type = routine.ColumnsTypeDescriptor.Length > 0 ? routine.ColumnsTypeDescriptor[0] : null; + return new JsonObject { ["value"] = ScalarValue(body, type) }; + case OutputShape.Record: + return TryParseJson(body) as JsonObject; + default: + return null; } + } - return TryParseJson(body) as JsonObject; + /// The shape of a tool's structuredContent: decided once, for the result and for its schema. + private enum OutputShape + { + /// Nothing to structure: no body, text that is not JSON, bytes, another service's response. + None, + /// { "items": [ … ] }: a set of rows or values. + Items, + /// { "value": … }: one value. + Value, + /// The object itself: one row. + Record, + /// The object itself: a property for each statement of a multi-command SQL file. + Results } /// - /// Builds the tool's outputSchema (declared in tools/list) describing the structuredContent it - /// returns. Mirrors 's shape decisions exactly so results always - /// conform (MCP 2025-11-25: when an outputSchema is provided, results MUST conform). Returns null for - /// void/raw routines (which emit no structuredContent). Leaf value schemas allow null (PG columns are - /// nullable); array/json/composite columns use a permissive schema so conformance is guaranteed. + /// The same decisions as the request handling makes (see RoutineEndpoint.GetResponseKind): the `void` + /// annotation means no body whatever the routine returns, `single` means one row and not an array, and a set + /// with one named column is a set of objects - only a set of unnamed values is a set of values. /// - private static JsonObject? BuildOutputSchema(RoutineEndpoint endpoint) + private static OutputShape ShapeOf(RoutineEndpoint endpoint) { var routine = endpoint.Routine; - // No schema for void/raw, or for a multi-command SQL file (its per-result-set object shape, e.g. - // { "result1": […], "result2": […] }, can't be derived from the single-set column metadata). - if (routine.IsVoid || endpoint.Raw || routine.IsMultiCommand) + if (endpoint.GetResponseKind() != EndpointResponseKind.Routine + || endpoint.CustomParameters?.ContainsKey("table_format") is true) { - return null; + return OutputShape.None; + } + if (routine.IsMultiCommand) + { + return OutputShape.Results; } - if (routine.ReturnsSet && !endpoint.ReturnSingleRecord) { - var element = routine.ColumnCount == 1 && !routine.ReturnsRecordType - ? NullableValueSchema(ColumnType(routine, 0)) // set of scalar values - : RecordSchema(routine); // set of rows - return ObjectSchema("items", new JsonObject { ["type"] = "array", ["items"] = element }); + return OutputShape.Items; } - - if (routine.ColumnCount == 1 && !routine.ReturnsRecordType) + if (routine.ReturnsUnnamedSet || (routine.ReturnsSet is false && routine.ColumnCount == 1 && !routine.ReturnsRecordType)) { - return ObjectSchema("value", NullableValueSchema(ColumnType(routine, 0))); + return OutputShape.Value; } + return OutputShape.Record; + } - return RecordSchema(routine); + /// + /// Builds the tool's outputSchema (declared in tools/list) describing the structuredContent it + /// returns. Uses the same shape decision as () so + /// results always conform (MCP 2025-11-25: when an outputSchema is provided, results MUST conform). Returns + /// null for routines that emit no structuredContent (void, raw...) and for a multi-command SQL file (its + /// per-result-set object shape, e.g. { "result1": […], "result2": […] }, is not derived from the single-set + /// column metadata). Leaf value schemas allow null (PG columns are nullable); array/json/composite columns + /// use a permissive schema so conformance is guaranteed. + /// + private static JsonObject? BuildOutputSchema(RoutineEndpoint endpoint) + { + var routine = endpoint.Routine; + switch (ShapeOf(endpoint)) + { + case OutputShape.Items: + var element = routine.ReturnsUnnamedSet + ? NullableValueSchema(ColumnType(routine, 0)) // set of values + : RecordSchema(routine); // set of rows + return ObjectSchema("items", new JsonObject { ["type"] = "array", ["items"] = element }); + case OutputShape.Value: + return ObjectSchema("value", NullableValueSchema(ColumnType(routine, 0))); + case OutputShape.Record: + return RecordSchema(routine); + default: + return null; + } } private static JsonObject ObjectSchema(string property, JsonNode propertySchema) => new() @@ -562,7 +602,8 @@ private static JsonObject RecordSchema(Routine routine) /// private static JsonNode NullableValueSchema(TypeDescriptor? type) { - if (type is null || type.IsArray || type.IsJson || type.IsCompositeType) + // (a record with no declared columns is written as an array of its values) + if (type is null || type.IsArray || type.IsJson || type.IsCompositeType || type.Type == "record") { return new JsonObject(); } diff --git a/plugins/NpgsqlRest.OpenApi/OpenApi.cs b/plugins/NpgsqlRest.OpenApi/OpenApi.cs index 11b9b7bb..29a5d629 100644 --- a/plugins/NpgsqlRest.OpenApi/OpenApi.cs +++ b/plugins/NpgsqlRest.OpenApi/OpenApi.cs @@ -55,6 +55,7 @@ internal static string ResolveSpecVersion(string? specVersion) } private IApplicationBuilder _builder = default!; + private NpgsqlRestOptions? _options; private JsonObject _document = default!; private JsonObject _paths = default!; // For tools (EndpointReport): the operation id written for each endpoint. @@ -69,6 +70,7 @@ internal static string ResolveSpecVersion(string? specVersion) public void Setup(IApplicationBuilder builder, NpgsqlRestOptions options) { _builder = builder; + _options = options; // Initialize OpenAPI document structure var info = new JsonObject @@ -448,43 +450,9 @@ public void Handle(RoutineEndpoint endpoint) } } - // Add responses - var responses = new JsonObject - { - ["200"] = new JsonObject - { - ["description"] = "Successful response" - } - }; - - // Add response content if not void - if (!endpoint.Routine.IsVoid) - { - var responseContent = new JsonObject(); - var contentType = endpoint.ResponseContentType ?? "application/json"; - - if (contentType.Contains("json", StringComparison.OrdinalIgnoreCase)) - { - var responseSchema = GetResponseSchema(endpoint.Routine); - responseContent[contentType] = new JsonObject - { - ["schema"] = responseSchema - }; - } - else - { - // For non-JSON responses - responseContent[contentType] = new JsonObject - { - ["schema"] = new JsonObject - { - ["type"] = "string" - } - }; - } - - (responses["200"] as JsonObject)!["content"] = responseContent; - } + // The response: what the endpoint answers with (see OpenApiResponse) + var (status, response) = OpenApiResponse.Describe(endpoint, _options); + var responses = new JsonObject { [status] = response }; operation["responses"] = responses; @@ -659,59 +627,6 @@ public void Cleanup() } } - private JsonObject GetResponseSchema(Routine routine) - { - if (routine.ReturnsSet) - { - // Returns array of objects - var itemSchema = new JsonObject - { - ["type"] = "object", - ["properties"] = new JsonObject() - }; - - var properties = itemSchema["properties"] as JsonObject; - for (int i = 0; i < routine.ColumnCount; i++) - { - properties![routine.ColumnNames[i]] = SchemaMapper.GetSchemaForType(routine.ColumnsTypeDescriptor[i]); - } - - return new JsonObject - { - ["type"] = "array", - ["items"] = itemSchema - }; - } - else if (routine.ColumnCount > 1 || routine.ReturnsRecordType) - { - // Returns single object - var schema = new JsonObject - { - ["type"] = "object", - ["properties"] = new JsonObject() - }; - - var properties = schema["properties"] as JsonObject; - for (int i = 0; i < routine.ColumnCount; i++) - { - properties![routine.ColumnNames[i]] = SchemaMapper.GetSchemaForType(routine.ColumnsTypeDescriptor[i]); - } - - return schema; - } - else if (routine.ColumnCount == 1) - { - // Returns single value - return SchemaMapper.GetSchemaForType(routine.ColumnsTypeDescriptor[0]); - } - - // Default - return new JsonObject - { - ["type"] = "object" - }; - } - private string GetHost() { string? host = null; diff --git a/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs b/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs new file mode 100644 index 00000000..4b4ce86a --- /dev/null +++ b/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs @@ -0,0 +1,281 @@ +using System.Text.Json.Nodes; +using NpgsqlRest.Common; + +namespace NpgsqlRest.OpenAPI; + +/// +/// What an endpoint answers with, for the OpenAPI document: the status code, the content type and the schema of the +/// body. It follows the same decisions, in the same order, as the code that writes the response +/// (NpgsqlRestEndpoint), so that the document and the response agree: an endpoint annotated single answers +/// with one object and not with an array, one annotated void has no body, a function returning text answers +/// with text/plain, and so on. +/// +internal static class OpenApiResponse +{ + private const string Json = "application/json"; + private const string Text = "text/plain"; + private const string Octet = "application/octet-stream"; + private const string Any = "*/*"; + private const string TableFormat = "table_format"; + + /// The response's status code (the key under "responses") and its description object. + public static (string Status, JsonObject Response) Describe(RoutineEndpoint endpoint, NpgsqlRestOptions? options) + { + var routine = endpoint.Routine; + + // The body of a login depends on the authentication scheme: none with cookies, tokens with bearer or JWT. + if (endpoint.Login) + { + return Ok("Signed in. The body depends on the authentication scheme", Any, null); + } + if (endpoint.Logout) + { + return ("200", new JsonObject { ["description"] = "Signed out" }); + } + + // One decision for all generators (see RoutineEndpoint.GetResponseKind); what follows describes each kind. + switch (endpoint.GetResponseKind(options)) + { + case EndpointResponseKind.CacheInvalidation: + return Ok("Whether a cached response was removed", Json, new JsonObject + { + ["type"] = "object", + ["properties"] = new JsonObject { ["invalidated"] = new JsonObject { ["type"] = "boolean" } } + }); + case EndpointResponseKind.Upstream: + return Ok("The response of the upstream service", Any, null); + case EndpointResponseKind.NoContent: + return ("204", new JsonObject { ["description"] = "No content" }); + case EndpointResponseKind.Binary: + return Ok(ContentType(endpoint, Octet), Binary()); + case EndpointResponseKind.TableFormat: + // an HTML table, an Excel file... or a format taken from a parameter of the request + if (options?.TableFormatHandlers is not null + && endpoint.CustomParameters is not null + && endpoint.CustomParameters.TryGetValue(TableFormat, out var format) + && options.TableFormatHandlers.TryGetValue(format, out var handler)) + { + return Ok(handler.ContentType, + handler.ContentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) ? String() : Binary()); + } + return Ok(Any, null); + } + + if (routine.IsMultiCommand && routine.MultiCommandInfo is not null) + { + // One property for each statement that is not skipped: its rows, or the number of rows it affected. + var properties = new JsonObject(); + foreach (var command in routine.MultiCommandInfo) + { + if (command.IsSkipped) + { + continue; + } + if (command.ColumnCount == 0) + { + properties[command.Name] = new JsonObject { ["type"] = "integer" }; + continue; + } + var row = command.ReturnsUnnamedSet + ? ValueSchema(command.ColumnTypeDescriptors[0]) + : RowSchema(endpoint, command.ColumnNames, command.ColumnTypeDescriptors, command.ColumnCount, routineColumns: false); + properties[command.Name] = command.IsSingle ? row : ArrayOf(row); + } + return Ok(Json, new JsonObject { ["type"] = "object", ["properties"] = properties }); + } + + // One value + if (routine.ReturnsSet is false && routine.ColumnCount == 1 && routine.ReturnsRecordType is false + && routine.ColumnsTypeDescriptor is { Length: > 0 }) + { + var descriptor = routine.ColumnsTypeDescriptor[0]; + if (descriptor.IsArray && endpoint.Raw is false) + { + return Ok(ContentType(endpoint, Json), ValueSchema(descriptor)); + } + if (descriptor.IsJson) + { + return Ok(ContentType(endpoint, Json), new JsonObject()); + } + var contentType = ContentType(endpoint, descriptor.IsArray ? Json : Text); + if (IsJson(contentType)) + { + // text that the endpoint declares to be JSON: any JSON value + return Ok(contentType, endpoint.Raw ? String() : new JsonObject()); + } + // The value as text. A boolean is written as PostgreSQL writes it: t or f. + if (descriptor.IsBoolean) + { + return Ok(contentType, new JsonObject { ["type"] = "string", ["enum"] = new JsonArray((JsonNode)"t", (JsonNode)"f") }); + } + return Ok(contentType, descriptor.IsArray ? String() : SchemaMapper.GetSchemaForType(descriptor)); + } + + // Rows + if (endpoint.Raw) + { + return Ok(ContentType(endpoint, Json), String()); + } + + var rowSchema = routine.ReturnsUnnamedSet && routine.ColumnsTypeDescriptor is { Length: > 0 } + ? ValueSchema(routine.ColumnsTypeDescriptor[0]) + : RowSchema(endpoint, routine.ColumnNames ?? [], routine.ColumnsTypeDescriptor ?? [], routine.ColumnCount, routineColumns: true); + + return Ok(ContentType(endpoint, Json), + routine.ReturnsSet && endpoint.ReturnSingleRecord is false ? ArrayOf(rowSchema) : rowSchema); + } + + private static (string, JsonObject) Ok(string contentType, JsonObject? schema) => Ok("Successful response", contentType, schema); + + private static (string, JsonObject) Ok(string description, string contentType, JsonObject? schema) + { + var media = new JsonObject(); + if (schema is not null) + { + media["schema"] = schema; + } + return ("200", new JsonObject + { + ["description"] = description, + ["content"] = new JsonObject { [contentType] = media } + }); + } + + /// + /// The content type the endpoint sets, or the one the response gets by default. A content type built from a + /// parameter of the request ("{_type}") is not known in advance. + /// + private static string ContentType(RoutineEndpoint endpoint, string byDefault) + { + var contentType = endpoint.ResponseContentType; + if (string.IsNullOrWhiteSpace(contentType)) + { + return byDefault; + } + return contentType.Contains('{') ? Any : contentType; + } + + private static bool IsJson(string contentType) => contentType.Contains("json", StringComparison.OrdinalIgnoreCase); + + private static JsonObject String() => new() { ["type"] = "string" }; + + private static JsonObject Binary() => new() { ["type"] = "string", ["format"] = "binary" }; + + private static JsonObject ArrayOf(JsonObject items) => new() { ["type"] = "array", ["items"] = items }; + + /// A row as a JSON object: a property for each column. + private static JsonObject RowSchema( + RoutineEndpoint endpoint, + string[] columnNames, + TypeDescriptor[] descriptors, + int columnCount, + bool routineColumns) + { + var routine = endpoint.Routine; + var nested = endpoint.NestedJsonForCompositeTypes == true; + var properties = new JsonObject(); + + // With nested composite types, the columns a composite value was expanded into are one property again. + var composites = nested ? routine.CompositeColumnInfo : null; + HashSet? expanded = null; + if (composites is not null) + { + expanded = []; + foreach (var info in composites.Values) + { + foreach (var index in info.ExpandedColumnIndices) + { + if (index < columnCount) + { + expanded.Add(index); + } + } + } + } + + for (var i = 0; i < columnCount && i < columnNames.Length && i < descriptors.Length; i++) + { + if (composites is not null && composites.TryGetValue(i, out var composite)) + { + properties[composite.ConvertedColumnName] = ObjectOf(composite.FieldNames, composite.FieldDescriptors); + continue; + } + if (expanded is not null && expanded.Contains(i)) + { + continue; + } + + var descriptor = descriptors[i]; + if (routineColumns + && routine.ArrayCompositeColumnInfo is not null + && routine.ArrayCompositeColumnInfo.TryGetValue(i, out var elements)) + { + properties[columnNames[i]] = ArrayOf(ObjectOf(elements.FieldNames, elements.FieldDescriptors)); + continue; + } + + // A composite value in the result of an SQL file: one property, or its fields in place of it. + if (descriptor.CompositeFieldNames is not null && descriptor.CompositeFieldDescriptors is not null) + { + if (nested) + { + properties[columnNames[i]] = ObjectOf(descriptor.CompositeFieldNames, descriptor.CompositeFieldDescriptors); + } + else + { + AddFields(properties, descriptor.CompositeFieldNames, descriptor.CompositeFieldDescriptors); + } + continue; + } + + properties[columnNames[i]] = ValueSchema(descriptor); + } + + return new JsonObject { ["type"] = "object", ["properties"] = properties }; + } + + private static JsonObject ObjectOf(string[] fieldNames, TypeDescriptor[] fieldDescriptors) + { + var properties = new JsonObject(); + AddFields(properties, fieldNames, fieldDescriptors); + return new JsonObject { ["type"] = "object", ["properties"] = properties }; + } + + private static void AddFields(JsonObject properties, string[] fieldNames, TypeDescriptor[] fieldDescriptors) + { + for (var i = 0; i < fieldNames.Length && i < fieldDescriptors.Length; i++) + { + properties[fieldNames[i]] = ValueSchema(fieldDescriptors[i]); + } + } + + /// One value in a JSON response. + private static JsonObject ValueSchema(TypeDescriptor descriptor) + { + if (descriptor.ArrayCompositeFieldNames is not null && descriptor.ArrayCompositeFieldDescriptors is not null) + { + return ArrayOf(ObjectOf(descriptor.ArrayCompositeFieldNames, descriptor.ArrayCompositeFieldDescriptors)); + } + if (descriptor.CompositeFieldNames is not null && descriptor.CompositeFieldDescriptors is not null) + { + return ObjectOf(descriptor.CompositeFieldNames, descriptor.CompositeFieldDescriptors); + } + if (descriptor.IsArray) + { + // An array of json values holds any JSON values. The number of dimensions is not part of a PostgreSQL + // array type, so an array of more than one dimension is described as one of a single dimension. + return ArrayOf(descriptor.IsJson ? new JsonObject() : SchemaMapper.GetSchemaForType(new TypeDescriptor(descriptor.Type))); + } + if (descriptor.IsJson) + { + // json and jsonb hold any JSON value: an object, an array, a string, a number... + return new JsonObject(); + } + if (string.Equals(descriptor.Type, "record", StringComparison.OrdinalIgnoreCase)) + { + // a record with no declared columns: an array of its values, as text + return ArrayOf(String()); + } + return SchemaMapper.GetSchemaForType(descriptor); + } +} diff --git a/plugins/NpgsqlRest.TsClient/TsClient.cs b/plugins/NpgsqlRest.TsClient/TsClient.cs index 46b30e74..d138ab55 100644 --- a/plugins/NpgsqlRest.TsClient/TsClient.cs +++ b/plugins/NpgsqlRest.TsClient/TsClient.cs @@ -627,13 +627,31 @@ string GetReturnExp(string responseExp) // proxy_out: always returns raw upstream response (function runs first, then proxies to upstream). // proxy pass-through: when the routine is void, returns raw upstream response. // Transform proxies (non-void @proxy routines) return processed data — fall through to normal handling. + // What the endpoint answers with is decided in one place for all generators (GetResponseKind). A response + // that is not JSON or text of the routine's value is returned as it is: the response of an upstream + // service, rows in a table format (an HTML table, an Excel file) and bytes (bytea). + var responseKind = endpoint.Login || endpoint.Logout + ? EndpointResponseKind.Routine + : endpoint.GetResponseKind(_npgsqlRestoptions); var rawResponse = false; - if ((endpoint.IsProxyOut || (endpoint.IsProxy && routine.IsVoid)) && !urlOnly) + if (responseKind is EndpointResponseKind.Upstream or EndpointResponseKind.TableFormat or EndpointResponseKind.Binary && !urlOnly) { responseName = "Response"; returnExp = "return response;"; rawResponse = true; } + else if (responseKind == EndpointResponseKind.CacheInvalidation && !urlOnly) + { + // the cache invalidation endpoint of a cached endpoint: the routine is not run + responseName = "{ invalidated: boolean }"; + returnExp = GetReturnExp(options.SkipTypes ? "await response.json()" : $"await response.json() as {responseName}"); + } + else if (responseKind == EndpointResponseKind.RawText && !urlOnly) + { + // the raw annotation: the values as text, not JSON + responseName = "string"; + returnExp = GetReturnExp("await response.text()"); + } else if (routine.IsMultiCommand && routine.MultiCommandInfo is not null && !urlOnly && !endpoint.Void) { // Multi-command SQL file: generate response interface with one property per command result From 6b492b2948185475a200e24f0875b53daf60eb77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Wed, 2 Dec 2026 09:21:24 +0100 Subject: [PATCH 2/9] fix: money values are JSON strings in responses A money value in a row, an array or a composite field was written without quotes ($1,234.50), which is not valid JSON. It is a string now, as PostgreSQL writes it (lc_monetary). Parameters still take a number or a decimal string. Generated clients, OpenAPI and MCP type money as a string. --- NpgsqlRest/TypeCategory.cs | 7 +- .../DartClientTests/NumericSplitTests.cs | 12 +-- NpgsqlRestTests/ReturnTests/MoneyTests.cs | 85 +++++++++++++++++++ 3 files changed, 96 insertions(+), 8 deletions(-) create mode 100644 NpgsqlRestTests/ReturnTests/MoneyTests.cs diff --git a/NpgsqlRest/TypeCategory.cs b/NpgsqlRest/TypeCategory.cs index 8d80f53d..e1d9b073 100644 --- a/NpgsqlRest/TypeCategory.cs +++ b/NpgsqlRest/TypeCategory.cs @@ -11,7 +11,7 @@ namespace NpgsqlRest; public enum TypeCategory : ushort { None = 0, - /// Smallint, Integer, Bigint, Numeric, Real, Double, Money + /// Smallint, Integer, Bigint, Numeric, Real, Double Numeric = 1 << 0, /// Boolean Boolean = 1 << 1, @@ -54,7 +54,10 @@ static TypeCategoryLookup() _lookup[(int)NpgsqlDbType.Numeric] = TypeCategory.Numeric; _lookup[(int)NpgsqlDbType.Real] = TypeCategory.Numeric; _lookup[(int)NpgsqlDbType.Double] = TypeCategory.Numeric; - _lookup[(int)NpgsqlDbType.Money] = TypeCategory.Numeric; + // Money is not a number in a response: PostgreSQL writes it as text in the format of lc_monetary ("$1,234.50", + // "1.234,50 €"), which is not a JSON number. It is written as a JSON string. (As a parameter it is still + // parsed as a decimal: see ParameterParsers.) + _lookup[(int)NpgsqlDbType.Money] = TypeCategory.NeedsEscape; // Boolean _lookup[(int)NpgsqlDbType.Boolean] = TypeCategory.Boolean; diff --git a/NpgsqlRestTests/DartClientTests/NumericSplitTests.cs b/NpgsqlRestTests/DartClientTests/NumericSplitTests.cs index 3d4d0c56..f0ab5bee 100644 --- a/NpgsqlRestTests/DartClientTests/NumericSplitTests.cs +++ b/NpgsqlRestTests/DartClientTests/NumericSplitTests.cs @@ -7,8 +7,8 @@ public static void DartClientNumericSplitTests() script.Append(""" create schema if not exists dartclient_test; --- Dart distinguishes int (smallint/integer/bigint) from double (real/double precision/numeric/money), --- unlike TypeScript where every numeric is just `number`. +-- Dart distinguishes int (smallint/integer/bigint) from double (real/double precision/numeric), +-- unlike TypeScript where every numeric is just `number`. money is a String: PostgreSQL writes it as text ("$1,234.50"). create function dartclient_test.numeric_split( _small smallint, _regular int, @@ -98,7 +98,7 @@ class DartclientTestNumericSplitRequest { final double? real; final double? double_; final double? numeric; - final double? money; + final String? money; const DartclientTestNumericSplitRequest({ this.small, @@ -118,7 +118,7 @@ factory DartclientTestNumericSplitRequest.fromJson(Map json) { real: (json['real'] as num?)?.toDouble(), double_: (json['double'] as num?)?.toDouble(), numeric: (json['numeric'] as num?)?.toDouble(), - money: (json['money'] as num?)?.toDouble(), + money: json['money'] as String?, ); } @@ -142,7 +142,7 @@ class DartclientTestNumericSplitResponse { final double? realCol; final double? doubleCol; final double? numericCol; - final double? moneyCol; + final String? moneyCol; const DartclientTestNumericSplitResponse({ this.smallCol, @@ -162,7 +162,7 @@ factory DartclientTestNumericSplitResponse.fromJson(Map json) { realCol: (json['realCol'] as num?)?.toDouble(), doubleCol: (json['doubleCol'] as num?)?.toDouble(), numericCol: (json['numericCol'] as num?)?.toDouble(), - moneyCol: (json['moneyCol'] as num?)?.toDouble(), + moneyCol: json['moneyCol'] as String?, ); } diff --git a/NpgsqlRestTests/ReturnTests/MoneyTests.cs b/NpgsqlRestTests/ReturnTests/MoneyTests.cs new file mode 100644 index 00000000..285ed2cc --- /dev/null +++ b/NpgsqlRestTests/ReturnTests/MoneyTests.cs @@ -0,0 +1,85 @@ +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void MoneyTests() + { + script.Append(""" + create function money_rows() returns table (id int, price money) language sql + as $$ select * from (values (1, 1234.5::money), (2, null::money)) t(id, price) $$; + comment on function money_rows() is 'HTTP GET'; + + create function money_value() returns money language sql as $$ select 1234.5::money $$; + comment on function money_value() is 'HTTP GET'; + + create function money_array() returns table (prices money[]) language sql as $$ select array[1.5::money, 2::money] $$; + comment on function money_array() is 'HTTP GET'; + + create type money_item as (label text, price money); + create function money_items() returns table (items money_item[]) language sql + as $$ select array[row('a', 1.5::money)::money_item] $$; + comment on function money_items() is 'HTTP GET'; + + create function money_echo(_price money) returns table (price money) language sql as $$ select _price $$; + comment on function money_echo(money) is 'HTTP POST'; + """); + } +} + +// A money value is written by PostgreSQL as text ("$1,234.50"), so in JSON it is a string. It used to be written +// without quotes, which made the whole response invalid JSON. +[Collection("TestFixture")] +public class MoneyTests(TestFixture test) +{ + private async Task Answered(HttpMethod method, string path, string? body = null) + { + using var request = new HttpRequestMessage(method, path); + if (body is not null) + { + request.Content = new StringContent(body, Encoding.UTF8, "application/json"); + } + using var response = await test.Client.SendAsync(request); + return $"{(int)response.StatusCode} {response.Content.Headers.ContentType?.MediaType} {await response.Content.ReadAsStringAsync()}"; + } + + [Fact] + public async Task Money_column_is_a_json_string() + { + (await Answered(HttpMethod.Get, "/api/money-rows")).Should().Be( + """200 application/json [{"id":1,"price":"$1,234.50"},{"id":2,"price":null}]"""); + } + + [Fact] + public async Task Money_value_is_text() + { + (await Answered(HttpMethod.Get, "/api/money-value")).Should().Be("200 text/plain $1,234.50"); + } + + [Fact] + public async Task Money_array_is_an_array_of_strings() + { + (await Answered(HttpMethod.Get, "/api/money-array")).Should().Be( + """200 application/json [{"prices":["$1.50","$2.00"]}]"""); + } + + [Fact] + public async Task Money_field_of_a_composite_value_is_a_string() + { + (await Answered(HttpMethod.Get, "/api/money-items")).Should().Be( + """200 application/json [{"items":[{"label":"a","price":"$1.50"}]}]"""); + } + + [Fact] + public async Task Money_parameter_is_a_number() + { + (await Answered(HttpMethod.Post, "/api/money-echo", """{"price": 12.5}""")).Should().Be( + """200 application/json [{"price":"$12.50"}]"""); + } + + [Fact] + public async Task Money_parameter_is_also_accepted_as_a_decimal_in_a_string() + { + (await Answered(HttpMethod.Post, "/api/money-echo", """{"price": "12.5"}""")).Should().Be( + """200 application/json [{"price":"$12.50"}]"""); + } +} From fd378b28486c58bb208040a5e1616613e13a7c4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Wed, 2 Dec 2026 09:21:24 +0100 Subject: [PATCH 3/9] fix: raw responses are text/plain by default A raw endpoint without a content type answered as application/json, although the body is not JSON. Also for a raw routine that returns one array value. The OpenAPI document says the same. --- NpgsqlRest/NpgsqlRestEndpoint.cs | 14 ++++++++++---- .../OpenApiTests/ResponseShapeTests.cs | 16 ++++++++++++++-- .../RawContentTests/RawResponseTests.cs | 3 ++- .../RawResponseUsingParamsTests.cs | 3 ++- plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs | 4 ++-- 5 files changed, 30 insertions(+), 10 deletions(-) diff --git a/NpgsqlRest/NpgsqlRestEndpoint.cs b/NpgsqlRest/NpgsqlRestEndpoint.cs index 0b77d4e5..ead1f3f4 100644 --- a/NpgsqlRest/NpgsqlRestEndpoint.cs +++ b/NpgsqlRest/NpgsqlRestEndpoint.cs @@ -1910,7 +1910,7 @@ private async ValueTask WriteScalarAsync(RequestState s, NpgsqlDataReader reader return; } - SetScalarContentType(s.context, descriptor); + SetScalarContentType(s.context, descriptor, s.endpoint.Raw); if (utf8 is null) { // SQL NULL @@ -2067,7 +2067,7 @@ Options.AuthenticationOptions.DefaultDataProtector is not null && } } - SetScalarContentType(context, descriptor); + SetScalarContentType(context, descriptor, endpoint.Raw); // if raw if (endpoint.Raw) @@ -2294,6 +2294,11 @@ private async ValueTask WriteResultSetsAsync(RequestState s, NpgsqlDataReader re { context.Response.ContentType = Application.Octet; } + else if (endpoint.Raw) + { + // the raw annotation: values as text, not JSON (it used to be labelled application/json) + context.Response.ContentType = Text.Plain; + } else { context.Response.ContentType = Application.Json; @@ -3914,7 +3919,7 @@ private void Reset() } } - private static void SetScalarContentType(HttpContext context, TypeDescriptor descriptor) + private static void SetScalarContentType(HttpContext context, TypeDescriptor descriptor, bool raw) { if (context.Response.ContentType is null) { @@ -3922,7 +3927,8 @@ private static void SetScalarContentType(HttpContext context, TypeDescriptor des { context.Response.ContentType = Application.Octet; } - else if ((descriptor.Category & TypeCategory.Json) != 0 || descriptor.IsArray) + // An array is written as a JSON array, unless the endpoint is raw: then it is PostgreSQL's array text. + else if ((descriptor.Category & TypeCategory.Json) != 0 || (descriptor.IsArray && raw is false)) { context.Response.ContentType = Application.Json; } diff --git a/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs index 36a74c64..e3dd8c98 100644 --- a/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs +++ b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs @@ -111,6 +111,11 @@ HTTP GET comment on function oas_shape_login() is ' HTTP POST login'; + +create function oas_shape_raw_array() returns int[] language sql as $$ select array[1,2] $$; +comment on function oas_shape_raw_array() is ' +HTTP GET +raw'; """); } } @@ -245,8 +250,8 @@ public async Task Array_value_is_a_json_array() [Fact] public async Task Raw_is_text_and_not_an_array() { - (await Answered("/api/oas-shape-raw")).Should().Be("""200 application/json 1,"x" """.TrimEnd()); - Documented("/api/oas-shape-raw").Should().Be(Ok("application/json", """{"type":"string"}""")); + (await Answered("/api/oas-shape-raw")).Should().Be("""200 text/plain 1,"x" """.TrimEnd()); + Documented("/api/oas-shape-raw").Should().Be(Ok("text/plain", """{"type":"string"}""")); } [Fact] @@ -337,5 +342,12 @@ public void Login_body_depends_on_the_authentication_scheme() Documented("/api/oas-shape-login", "post").Should().Be( """{"200":{"description":"Signed in. The body depends on the authentication scheme","content":{"*/*":{}}}}"""); } + + [Fact] + public async Task Raw_array_value_is_text_and_not_a_json_array() + { + (await Answered("/api/oas-shape-raw-array")).Should().Be("200 text/plain {1,2}"); + Documented("/api/oas-shape-raw-array").Should().Be(Ok("text/plain", """{"type":"string"}""")); + } } } diff --git a/NpgsqlRestTests/RawContentTests/RawResponseTests.cs b/NpgsqlRestTests/RawContentTests/RawResponseTests.cs index 2442b405..642e55f5 100644 --- a/NpgsqlRestTests/RawContentTests/RawResponseTests.cs +++ b/NpgsqlRestTests/RawContentTests/RawResponseTests.cs @@ -91,7 +91,8 @@ public async Task Test_raw_response1() var response = await result.Content.ReadAsStringAsync(); result?.StatusCode.Should().Be(HttpStatusCode.OK); - result?.Content?.Headers?.ContentType?.MediaType.Should().Be("application/json"); + // raw is text, not JSON (it was labelled application/json before 4.1.1) + result?.Content?.Headers?.ContentType?.MediaType.Should().Be("text/plain"); response.Should().Be("1232024-01-01 00:00:00tsome text4562024-12-31 00:00:00fanother text"); } diff --git a/NpgsqlRestTests/RawContentTests/RawResponseUsingParamsTests.cs b/NpgsqlRestTests/RawContentTests/RawResponseUsingParamsTests.cs index 6e839c20..6122b4b6 100644 --- a/NpgsqlRestTests/RawContentTests/RawResponseUsingParamsTests.cs +++ b/NpgsqlRestTests/RawContentTests/RawResponseUsingParamsTests.cs @@ -91,7 +91,8 @@ public async Task Test_raw_response2() var response = await result.Content.ReadAsStringAsync(); result?.StatusCode.Should().Be(HttpStatusCode.OK); - result?.Content?.Headers?.ContentType?.MediaType.Should().Be("application/json"); + // raw is text, not JSON (it was labelled application/json before 4.1.1) + result?.Content?.Headers?.ContentType?.MediaType.Should().Be("text/plain"); response.Should().Be("1232024-01-01 00:00:00tsome text4562024-12-31 00:00:00fanother text"); } diff --git a/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs b/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs index 4b4ce86a..3e1aec0f 100644 --- a/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs +++ b/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs @@ -97,7 +97,7 @@ public static (string Status, JsonObject Response) Describe(RoutineEndpoint endp { return Ok(ContentType(endpoint, Json), new JsonObject()); } - var contentType = ContentType(endpoint, descriptor.IsArray ? Json : Text); + var contentType = ContentType(endpoint, Text); if (IsJson(contentType)) { // text that the endpoint declares to be JSON: any JSON value @@ -114,7 +114,7 @@ public static (string Status, JsonObject Response) Describe(RoutineEndpoint endp // Rows if (endpoint.Raw) { - return Ok(ContentType(endpoint, Json), String()); + return Ok(ContentType(endpoint, Text), String()); } var rowSchema = routine.ReturnsUnnamedSet && routine.ColumnsTypeDescriptor is { Length: > 0 } From 5f3e1f42ccbd0e73b3fee06231a5e54a9190ae50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Wed, 2 Dec 2026 09:21:24 +0100 Subject: [PATCH 4/9] fix: cache invalidation endpoint follows its endpoint's plugin metadata The invalidation endpoint gets the Items of the cached endpoint, so openapi hide and openapi tags apply to it. MCP does not take it for a second tool. --- NpgsqlRest/NpgsqlRestBuilder.cs | 2 ++ NpgsqlRest/RoutineEndpoint.cs | 17 ++++++++++++ .../McpTests/McpResponseShapeTests.cs | 26 +++++++++++++++++++ .../OpenApiTests/ResponseShapeTests.cs | 26 +++++++++++++++++++ NpgsqlRestTests/Setup/McpPluginTestFixture.cs | 6 +++++ plugins/NpgsqlRest.Mcp/Mcp.cs | 6 +++++ 6 files changed, 83 insertions(+) diff --git a/NpgsqlRest/NpgsqlRestBuilder.cs b/NpgsqlRest/NpgsqlRestBuilder.cs index ce720e4e..d9266fb8 100644 --- a/NpgsqlRest/NpgsqlRestBuilder.cs +++ b/NpgsqlRest/NpgsqlRestBuilder.cs @@ -518,6 +518,8 @@ private static Metadata Build(IApplicationBuilder? builder, RetryStrategy? defau CacheProfile = endpoint.CacheProfile }; + endpoint.CopyItemsTo(invalidateEndpoint); + var invalidateKey = string.Concat(method, invalidatePath); var invalidateValue = new NpgsqlRestMetadataEntry(invalidateEndpoint, formatter, invalidateKey); lookup[invalidateKey] = invalidateValue; diff --git a/NpgsqlRest/RoutineEndpoint.cs b/NpgsqlRest/RoutineEndpoint.cs index f12a1040..69b46690 100644 --- a/NpgsqlRest/RoutineEndpoint.cs +++ b/NpgsqlRest/RoutineEndpoint.cs @@ -187,6 +187,23 @@ public string? BodyParameterName /// public IDictionary Items => _items ??= new(StringComparer.Ordinal); + /// + /// Gives another endpoint the plugin metadata of this one. Used for the cache invalidation endpoint, which belongs + /// to a cached endpoint: what the plugins were told about that endpoint (hide it from the OpenAPI document, its + /// tags) applies to its invalidation endpoint as well. + /// + internal void CopyItemsTo(RoutineEndpoint other) + { + if (_items is null) + { + return; + } + foreach (var item in _items) + { + other.Items[item.Key] = item.Value; + } + } + /// /// Non-allocating read of an entry. Returns false (without allocating the /// bag) when no items have been stored. Use this for reads on the hot/common path so endpoints diff --git a/NpgsqlRestTests/McpTests/McpResponseShapeTests.cs b/NpgsqlRestTests/McpTests/McpResponseShapeTests.cs index d76185ee..44c42271 100644 --- a/NpgsqlRestTests/McpTests/McpResponseShapeTests.cs +++ b/NpgsqlRestTests/McpTests/McpResponseShapeTests.cs @@ -37,6 +37,13 @@ comment on function mcp.shape_void() is ' HTTP GET @mcp Runs and returns nothing. void'; + +-- a cached tool: its cache invalidation endpoint is not a second tool +create function mcp.shape_cached() returns table(val text) language sql as 'select ''a'''; +comment on function mcp.shape_cached() is ' +HTTP GET +@mcp A cached set of rows. +cached'; "); } } @@ -97,4 +104,23 @@ public async Task Void_annotation_has_no_structured_content_and_no_output_schema (await ToolDefAsync("shape_void")).Should().Be( """{"name":"shape_void","description":"Runs and returns nothing.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true}}"""); } + [Fact] + public async Task Cache_invalidation_endpoint_of_a_tool_is_not_a_tool() + { + using var content = new StringContent("""{"jsonrpc":"2.0","id":1,"method":"tools/list"}""", Encoding.UTF8, "application/json"); + using var response = await test.Client.PostAsync("/mcp", content); + var names = JsonNode.Parse(await response.Content.ReadAsStringAsync())!["result"]!["tools"]!.AsArray() + .Select(t => t!["name"]!.GetValue()) + .Where(n => n.StartsWith("shape_cached")) + .ToArray(); + names.Should().BeEquivalentTo(["shape_cached"]); + + // the tool is the cached endpoint: it answers with the rows + (await CallAsync("shape_cached")).Should().Be( + """{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"{\"items\":[{\"val\":\"a\"}]}"}],"isError":false,"structuredContent":{"items":[{"val":"a"}]}}}"""); + + // and the invalidation endpoint exists and works + using var invalidate = await test.Client.GetAsync("/api/mcp/shape-cached/invalidate"); + (await invalidate.Content.ReadAsStringAsync()).Should().StartWith("{\"invalidated\":"); + } } diff --git a/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs index e3dd8c98..5f29e210 100644 --- a/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs +++ b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs @@ -112,6 +112,18 @@ comment on function oas_shape_login() is ' HTTP POST login'; +create function oas_shape_hidden() returns table (id int, name text) language sql as $$ select 1, 'a' $$; +comment on function oas_shape_hidden() is ' +HTTP GET +cached +openapi hide'; + +create function oas_shape_tagged() returns table (id int, name text) language sql as $$ select 1, 'a' $$; +comment on function oas_shape_tagged() is ' +HTTP GET +cached +openapi tags Things'; + create function oas_shape_raw_array() returns int[] language sql as $$ select array[1,2] $$; comment on function oas_shape_raw_array() is ' HTTP GET @@ -343,6 +355,20 @@ public void Login_body_depends_on_the_authentication_scheme() """{"200":{"description":"Signed in. The body depends on the authentication scheme","content":{"*/*":{}}}}"""); } + [Fact] + public void Invalidation_endpoint_of_a_hidden_endpoint_is_hidden_too() + { + Document.Value["paths"]!["/api/oas-shape-hidden"].Should().BeNull(); + Document.Value["paths"]!["/api/oas-shape-hidden/invalidate"].Should().BeNull(); + } + + [Fact] + public void Invalidation_endpoint_has_the_tags_of_its_endpoint() + { + Document.Value["paths"]!["/api/oas-shape-tagged"]!["get"]!["tags"]!.ToJsonString().Should().Be("""["Things"]"""); + Document.Value["paths"]!["/api/oas-shape-tagged/invalidate"]!["get"]!["tags"]!.ToJsonString().Should().Be("""["Things"]"""); + } + [Fact] public async Task Raw_array_value_is_text_and_not_a_json_array() { diff --git a/NpgsqlRestTests/Setup/McpPluginTestFixture.cs b/NpgsqlRestTests/Setup/McpPluginTestFixture.cs index fe83cbd5..b7a9d5e5 100644 --- a/NpgsqlRestTests/Setup/McpPluginTestFixture.cs +++ b/NpgsqlRestTests/Setup/McpPluginTestFixture.cs @@ -58,11 +58,17 @@ public McpPluginTestFixture() // requests an endpoint (e.g. `mcp`). OpenApi is loaded too so we can assert that a pure // modifier (`openapi hide`) on a non-HTTP routine does NOT spawn an endpoint. CommentsMode = CommentsMode.OnlyAnnotated, + // cached endpoints get a cache invalidation endpoint (which must not become a second tool) + CacheOptions = new() { InvalidateCacheSuffix = "invalidate" }, EndpointCreateHandlers = [_mcp, new OpenApi(new OpenApiOptions())], EndpointsCreated = endpoints => { foreach (var endpoint in endpoints) { + if (endpoint.InvalidateCache) + { + continue; + } Endpoints[endpoint.Routine.Name] = endpoint; } } diff --git a/plugins/NpgsqlRest.Mcp/Mcp.cs b/plugins/NpgsqlRest.Mcp/Mcp.cs index 8371ae17..8c52468d 100644 --- a/plugins/NpgsqlRest.Mcp/Mcp.cs +++ b/plugins/NpgsqlRest.Mcp/Mcp.cs @@ -118,6 +118,12 @@ public void Handle(RoutineEndpoint endpoint) { return; } + // The cache invalidation endpoint of a cached tool endpoint carries that endpoint's metadata, but it is not + // a tool: the tool is the endpoint itself. + if (endpoint.InvalidateCache) + { + return; + } var tool = BuildTool(endpoint, info); var name = tool["name"]!.GetValue(); From cb01e67c23153cd10cc41708d411be67090651ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Wed, 2 Dec 2026 09:21:24 +0100 Subject: [PATCH 5/9] fix: upload endpoints in OpenAPI and in the generated clients OpenAPI: an upload endpoint has a multipart/form-data request body. TsClient, DartClient: the response is typed as upload metadata only when the routine returns one json value, otherwise any / dynamic. --- .../DartClientTests/ResponseShapeTests.cs | 105 ++++++++++++++++++ .../OpenApiTests/ResponseShapeTests.cs | 14 +++ .../TsClientTests/ResponseShapeTests.cs | 85 ++++++++++++++ plugins/NpgsqlRest.DartClient/DartClient.cs | 12 +- plugins/NpgsqlRest.OpenApi/OpenApi.cs | 28 +++++ plugins/NpgsqlRest.TsClient/TsClient.cs | 12 +- 6 files changed, 254 insertions(+), 2 deletions(-) diff --git a/NpgsqlRestTests/DartClientTests/ResponseShapeTests.cs b/NpgsqlRestTests/DartClientTests/ResponseShapeTests.cs index 5ee19698..6ecf3604 100644 --- a/NpgsqlRestTests/DartClientTests/ResponseShapeTests.cs +++ b/NpgsqlRestTests/DartClientTests/ResponseShapeTests.cs @@ -31,6 +31,12 @@ comment on function dartclient_test.shape_bytes() is ' comment on function dartclient_test.shape_cached() is ' dartclient_module=dart_shape cached'; + +create function dartclient_test.shape_upload(_meta json = null) returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function dartclient_test.shape_upload(json) is ' +dartclient_module=dart_shape +upload for file_system +param _meta is upload metadata'; """); } } @@ -70,6 +76,50 @@ public class ResponseShapeTests return http.Response.fromStream(await _client.send(request)); } +Future _sendMultipart( + http.MultipartRequest multipart, { + void Function(int loaded, int total)? progress, +}) async { + if (progress == null) { + return http.Response.fromStream(await _client.send(multipart)); + } + final total = multipart.contentLength; + final bytes = multipart.finalize(); + final request = http.StreamedRequest(multipart.method, multipart.url); + request.headers.addAll(multipart.headers); + request.contentLength = total; + var loaded = 0; + bytes.listen( + (chunk) { + loaded += chunk.length; + progress(loaded, total); + request.sink.add(chunk); + }, + onDone: request.sink.close, + onError: request.sink.addError, + ); + return http.Response.fromStream(await _client.send(request)); +} + +String _query(Map query) { + final parts = []; + query.forEach((key, value) { + if (value is List) { + for (final v in value) { + parts.add(v == null ? '$key=' : '$key=${Uri.encodeQueryComponent(_str(v))}'); + } + } else if (value == null) { + parts.add('$key='); + } else { + parts.add('$key=${Uri.encodeQueryComponent(_str(value))}'); + } + }); + return '?${parts.join('&')}'; +} + +String _str(Object value) => + value is DateTime ? value.toIso8601String() : value.toString(); + class DartclientTestShapeCachedResponse { final int? a; final String? b; @@ -94,6 +144,26 @@ Map toJson() { } } +class DartclientTestShapeUploadRequest { + final dynamic meta; + + const DartclientTestShapeUploadRequest({ + this.meta, + }); + + factory DartclientTestShapeUploadRequest.fromJson(Map json) { + return DartclientTestShapeUploadRequest( + meta: json['meta'], + ); + } + + Map toJson() { + return { + if (meta != null) 'meta': meta, + }; + } +} + /// function dartclient_test.shape_bytes() /// returns bytea /// @@ -189,6 +259,41 @@ Future dartclientTestShapeRaw() async { return utf8.decode(response.bodyBytes); } +/// function dartclient_test.shape_upload( +/// _meta json DEFAULT NULL::json +/// ) +/// returns table( +/// a integer, +/// b text +/// ) +/// +/// comment on function dartclient_test.shape_upload is 'dartclient_module=dart_shape +/// upload for file_system +/// param _meta is upload metadata'; +/// +/// [files] Multipart files to upload, sent as form field "file". +/// [request] Carries the endpoint parameters. +/// [progress] Optional callback reporting upload progress in bytes. +/// Returns `dynamic`. +/// +/// See FUNCTION dartclient_test.shape_upload +Future dartclientTestShapeUpload( + List files, + DartclientTestShapeUploadRequest request, { + void Function(int loaded, int total)? progress, +}) async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-upload' + _query({ + if (request.meta != null) 'meta': request.meta, + })); + final multipart = http.MultipartRequest('POST', uri); + multipart.files.addAll(files); + final response = await _sendMultipart(multipart, progress: progress); + if (response.statusCode < 200 || response.statusCode >= 300) { + throw http.ClientException(utf8.decode(response.bodyBytes), uri); + } + return jsonDecode(utf8.decode(response.bodyBytes)); +} + /// function dartclient_test.shape_void() /// returns table( /// a integer, diff --git a/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs index 5f29e210..019abf86 100644 --- a/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs +++ b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs @@ -124,6 +124,11 @@ HTTP GET cached openapi tags Things'; +create function oas_shape_upload(_meta json = null) returns json language sql as $$ select _meta $$; +comment on function oas_shape_upload(json) is ' +upload for file_system +param _meta is upload metadata'; + create function oas_shape_raw_array() returns int[] language sql as $$ select array[1,2] $$; comment on function oas_shape_raw_array() is ' HTTP GET @@ -369,6 +374,15 @@ public void Invalidation_endpoint_has_the_tags_of_its_endpoint() Document.Value["paths"]!["/api/oas-shape-tagged/invalidate"]!["get"]!["tags"]!.ToJsonString().Should().Be("""["Things"]"""); } + [Fact] + public void Upload_endpoint_takes_its_files_as_multipart_form_data() + { + Document.Value["paths"]!["/api/oas-shape-upload"]!["post"]!["requestBody"]!.ToJsonString().Should().Be( + """{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","properties":{"file":{"type":"array","items":{"type":"string","format":"binary"}}}}}}}"""); + // it answers with what its routine returns: here a json value + Documented("/api/oas-shape-upload", "post").Should().Be(Ok("application/json", "{}")); + } + [Fact] public async Task Raw_array_value_is_text_and_not_a_json_array() { diff --git a/NpgsqlRestTests/TsClientTests/ResponseShapeTests.cs b/NpgsqlRestTests/TsClientTests/ResponseShapeTests.cs index c878a4af..6c1ee644 100644 --- a/NpgsqlRestTests/TsClientTests/ResponseShapeTests.cs +++ b/NpgsqlRestTests/TsClientTests/ResponseShapeTests.cs @@ -31,6 +31,12 @@ comment on function tsclient_test.shape_bytes() is ' comment on function tsclient_test.shape_cached() is ' tsclient_module=shape cached'; + +create function tsclient_test.shape_upload(_meta json = null) returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function tsclient_test.shape_upload(json) is ' +tsclient_module=shape +upload for file_system +param _meta is upload metadata'; """); } } @@ -45,12 +51,25 @@ public class ResponseShapeTests { private const string Expected = """ const baseUrl = ""; +const parseQuery = (query: Record) => "?" + Object.keys(query ? query : {}) + .map(key => { + const value = (query[key] != null ? query[key] : "") as string; + if (Array.isArray(value)) { + return value.map((s: string) => s ? `${key}=${encodeURIComponent(s)}` : `${key}=`).join("&"); + } + return `${key}=${encodeURIComponent(value)}`; + }) + .join("&"); interface ITsclientTestShapeCachedResponse { a: number | null; b: string | null; } +interface ITsclientTestShapeUploadRequest { + meta?: any | null; +} + /** * function tsclient_test.shape_bytes() @@ -162,6 +181,72 @@ export async function tsclientTestShapeRaw() : Promise { return await response.text(); } +/** +* function tsclient_test.shape_upload( +* _meta json DEFAULT NULL::json +* ) +* returns table( +* a integer, +* b text +* ) +* +* @remarks +* comment on function tsclient_test.shape_upload is 'tsclient_module=shape +* upload for file_system +* param _meta is upload metadata'; +* +* @param request - Object containing request parameters. +* @returns {any} +* +* @see FUNCTION tsclient_test.shape_upload +*/ +export async function tsclientTestShapeUpload( + files: FileList | null, + request: ITsclientTestShapeUploadRequest, + progress?: (loaded: number, total: number) => void, +): Promise { + return new Promise((resolve, reject) => { + if (!files || files.length === 0) { + reject(new Error("No files to upload")); + return; + } + var xhr = new XMLHttpRequest(); + if (progress) { + xhr.upload.addEventListener( + "progress", + (event) => { + if (event.lengthComputable && progress) { + progress(event.loaded, event.total); + } + }, + false + ); + } + xhr.onload = function () { + if (this.status >= 200 && this.status < 300) { + resolve(JSON.parse(this.responseText) as any); + } else { + throw new Error(this.responseText); + } + }; + xhr.onerror = function () { + reject({ + xhr: this, + status: this.status, + statusText: this.statusText || 'Network error occurred', + response: this.response + }); + }; + xhr.open("POST", baseUrl + "/api/tsclient-test/shape-upload" + parseQuery(request)); + const formData = new FormData(); + for(let i = 0; i < files.length; i++) { + const file = files[i]; + formData.append("file", file, file.name); + } + xhr.send(formData); + }); +} + /** * function tsclient_test.shape_void() * returns table( diff --git a/plugins/NpgsqlRest.DartClient/DartClient.cs b/plugins/NpgsqlRest.DartClient/DartClient.cs index 1406636e..10853e4a 100644 --- a/plugins/NpgsqlRest.DartClient/DartClient.cs +++ b/plugins/NpgsqlRest.DartClient/DartClient.cs @@ -611,7 +611,17 @@ elem.Conversion is null } else if (!isVoid && !urlOnly) { - if (endpoint.Upload) + // An upload endpoint answers with what its routine returns. Routines that return a single json value + // return the upload metadata (the usual way to write them): a list of file descriptions. Any other + // routine returns something else, and the response is not described as file descriptions. + var returnsUploadMetadata = returnsSet == false && columnCount == 1 && !returnsRecordType + && columnsTypeDescriptor.Length > 0 && columnsTypeDescriptor[0].IsJson; + if (endpoint.Upload && !returnsUploadMetadata) + { + responseName = "dynamic"; + payloadLines = [JsonDecodeExpr]; + } + else if (endpoint.Upload) { var uploadName = EscapeDartClassName(string.Concat(options.ModelPrefix, pascal, "Response", options.ModelSuffix)); if (!usedModelNames.Contains(uploadName)) diff --git a/plugins/NpgsqlRest.OpenApi/OpenApi.cs b/plugins/NpgsqlRest.OpenApi/OpenApi.cs index 29a5d629..166ec26d 100644 --- a/plugins/NpgsqlRest.OpenApi/OpenApi.cs +++ b/plugins/NpgsqlRest.OpenApi/OpenApi.cs @@ -450,6 +450,34 @@ public void Handle(RoutineEndpoint endpoint) } } + // An upload endpoint takes its files as multipart/form-data (its parameters are in the query string). The + // name of the form field does not matter; the generated clients use "file". + if (endpoint.Upload && operation["requestBody"] is null) + { + operation["requestBody"] = new JsonObject + { + ["required"] = true, + ["content"] = new JsonObject + { + ["multipart/form-data"] = new JsonObject + { + ["schema"] = new JsonObject + { + ["type"] = "object", + ["properties"] = new JsonObject + { + ["file"] = new JsonObject + { + ["type"] = "array", + ["items"] = new JsonObject { ["type"] = "string", ["format"] = "binary" } + } + } + } + } + } + }; + } + // The response: what the endpoint answers with (see OpenApiResponse) var (status, response) = OpenApiResponse.Describe(endpoint, _options); var responses = new JsonObject { [status] = response }; diff --git a/plugins/NpgsqlRest.TsClient/TsClient.cs b/plugins/NpgsqlRest.TsClient/TsClient.cs index d138ab55..65ff5bb3 100644 --- a/plugins/NpgsqlRest.TsClient/TsClient.cs +++ b/plugins/NpgsqlRest.TsClient/TsClient.cs @@ -706,7 +706,17 @@ string GetReturnExp(string responseExp) } else if (!isVoid && !urlOnly) { - if (endpoint.Upload) + // An upload endpoint answers with what its routine returns. Routines that return a single json value + // return the upload metadata (the usual way to write them): a list of file descriptions. Any other + // routine returns something else, and the response is not described as file descriptions. + var returnsUploadMetadata = returnsSet == false && columnCount == 1 && !returnsRecordType + && columnsTypeDescriptor.Length > 0 && columnsTypeDescriptor[0].IsJson; + if (endpoint.Upload && !returnsUploadMetadata) + { + responseName = "any"; + returnExp = GetReturnExp("await response.json()"); + } + else if (endpoint.Upload) { responseName = $"I{pascal}Response"; StringBuilder resp = new(); From 7d1fb135b1380b7467db71794ddf9ab78ba49feb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Wed, 2 Dec 2026 09:21:24 +0100 Subject: [PATCH 6/9] fix: OpenAPI documents the 204 response for no value Endpoints with response_null_handling no_content that return a single value, or single with no row, have a 204 response next to the 200. --- .../OpenApiTests/ResponseShapeTests.cs | 27 +++++++++++++++++++ plugins/NpgsqlRest.OpenApi/OpenApi.cs | 4 +++ plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs | 17 ++++++++++++ 3 files changed, 48 insertions(+) diff --git a/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs index 019abf86..48ab0bfa 100644 --- a/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs +++ b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs @@ -129,6 +129,17 @@ comment on function oas_shape_upload(json) is ' upload for file_system param _meta is upload metadata'; +create function oas_shape_null_value() returns text language sql as $$ select null::text $$; +comment on function oas_shape_null_value() is ' +HTTP GET +response_null_handling no_content'; + +create function oas_shape_no_row() returns table (id int, name text) language sql as $$ select 1, 'a' where false $$; +comment on function oas_shape_no_row() is ' +HTTP GET +@single +response_null_handling no_content'; + create function oas_shape_raw_array() returns int[] language sql as $$ select array[1,2] $$; comment on function oas_shape_raw_array() is ' HTTP GET @@ -383,6 +394,22 @@ public void Upload_endpoint_takes_its_files_as_multipart_form_data() Documented("/api/oas-shape-upload", "post").Should().Be(Ok("application/json", "{}")); } + [Fact] + public async Task Null_value_that_is_answered_with_204_has_both_responses() + { + (await Answered("/api/oas-shape-null-value")).Should().Be("204 text/plain "); + Documented("/api/oas-shape-null-value").Should().Be( + """{"200":{"description":"Successful response","content":{"text/plain":{"schema":{"type":"string"}}}},"204":{"description":"No content: there is no value (NULL, or no row)"}}"""); + } + + [Fact] + public async Task Single_without_a_row_that_is_answered_with_204_has_both_responses() + { + (await Answered("/api/oas-shape-no-row")).Should().Be("204 application/json "); + Documented("/api/oas-shape-no-row").Should().Be( + """{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"object","properties":""" + ThingProperties.Replace("thingId", "id") + """}}}},"204":{"description":"No content: there is no value (NULL, or no row)"}}"""); + } + [Fact] public async Task Raw_array_value_is_text_and_not_a_json_array() { diff --git a/plugins/NpgsqlRest.OpenApi/OpenApi.cs b/plugins/NpgsqlRest.OpenApi/OpenApi.cs index 166ec26d..05a3ca05 100644 --- a/plugins/NpgsqlRest.OpenApi/OpenApi.cs +++ b/plugins/NpgsqlRest.OpenApi/OpenApi.cs @@ -481,6 +481,10 @@ public void Handle(RoutineEndpoint endpoint) // The response: what the endpoint answers with (see OpenApiResponse) var (status, response) = OpenApiResponse.Describe(endpoint, _options); var responses = new JsonObject { [status] = response }; + if (status == "200" && OpenApiResponse.NoContentWhenNull(endpoint, _options)) + { + responses["204"] = new JsonObject { ["description"] = "No content: there is no value (NULL, or no row)" }; + } operation["responses"] = responses; diff --git a/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs b/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs index 3e1aec0f..3d4c1ce4 100644 --- a/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs +++ b/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs @@ -125,6 +125,23 @@ public static (string Status, JsonObject Response) Describe(RoutineEndpoint endp routine.ReturnsSet && endpoint.ReturnSingleRecord is false ? ArrayOf(rowSchema) : rowSchema); } + /// + /// True when the endpoint answers 204 instead of its usual response when there is no value: a single value that + /// is NULL, or `single` with no row, on an endpoint that answers NULL with 204 (TextResponseNullHandling.NoContent). + /// + public static bool NoContentWhenNull(RoutineEndpoint endpoint, NpgsqlRestOptions? options) + { + var routine = endpoint.Routine; + if (endpoint.TextResponseNullHandling != TextResponseNullHandling.NoContent + || endpoint.Login || endpoint.Logout || routine.IsMultiCommand + || endpoint.GetResponseKind(options) is not (EndpointResponseKind.Routine or EndpointResponseKind.RawText)) + { + return false; + } + var oneValue = routine.ReturnsSet is false && routine.ColumnCount == 1 && routine.ReturnsRecordType is false; + return endpoint.ReturnSingleRecord || (oneValue && endpoint.Raw is false); + } + private static (string, JsonObject) Ok(string contentType, JsonObject? schema) => Ok("Successful response", contentType, schema); private static (string, JsonObject) Ok(string description, string contentType, JsonObject? schema) From 281e54b02e9646652c229bd017e8aff20a47199a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Wed, 2 Dec 2026 09:21:24 +0100 Subject: [PATCH 7/9] docs: 4.1.1 changelog - changes in responses, summary, contents, known limits Everything that cannot be described exactly by the generators is listed under Known limits. --- changelog/v4.1.1.md | 101 +++++++++++++++++++++++++++++++++++++++----- 1 file changed, 91 insertions(+), 10 deletions(-) diff --git a/changelog/v4.1.1.md b/changelog/v4.1.1.md index be8460c1..a76a1c17 100644 --- a/changelog/v4.1.1.md +++ b/changelog/v4.1.1.md @@ -4,17 +4,80 @@ [Full Changelog](https://github.com/NpgsqlRest/NpgsqlRest/compare/4.1.0...4.1.1) -Patch release. What the generators say an endpoint answers with now matches what the endpoint answers with: the OpenAPI document, the generated TypeScript and Dart clients, and the MCP tool schemas. Reported in [#36](https://github.com/NpgsqlRest/NpgsqlRest/issues/36) for one case (`@single` in the OpenAPI document). The other cases were found by calling every endpoint of the test suite and comparing each answer with the document. No endpoint answers differently than before, and no configuration key was added or changed. +Patch release. What the generators say an endpoint answers with now matches what the endpoint answers with: the OpenAPI document, the generated TypeScript and Dart clients, and the MCP tool schemas. Reported in [#36](https://github.com/NpgsqlRest/NpgsqlRest/issues/36) for one case (`@single` in the OpenAPI document). The other cases were found by calling every endpoint of the test suite and comparing each answer with the document. Two responses were wrong themselves and are fixed: a `money` value made the response invalid JSON, and a `raw` response was labelled as JSON. No configuration key was added or changed. -**Who should upgrade:** everyone who generates clients from `openapi.json`, and everyone who uses `raw`, `table_format`, `bytea` results, the `void` annotation or cache invalidation endpoints with the generated TypeScript or Dart clients or with MCP tools. +**Who should upgrade:** everyone who generates clients from `openapi.json`, and everyone who uses `raw`, `table_format`, `money` or `bytea` results, uploads, the `void` annotation or cache invalidation endpoints with the generated TypeScript or Dart clients or with MCP tools. -**After upgrading:** regenerate the OpenAPI document and the clients. The descriptions of some endpoints change (the list is below), so clients generated from them change as well. +**After upgrading:** regenerate the OpenAPI document and the clients. Read [Changes in responses](#changes-in-responses) first: two responses change. What still cannot be described exactly is listed in [Known limits](#known-limits). + +### Summary + +| | What | Affects | +|---|---|---| +| Changed | `money` values are JSON strings (`"$1,234.50"`); they were written without quotes, which is not valid JSON | responses, all generators | +| Changed | `raw` responses without a content type are `text/plain`; they were `application/json` | responses, OpenAPI | +| Fixed | the described response follows the endpoint's annotations and return type (`single`, `void`, single values, `bytea`, `raw`, `table_format`, `json`, composite types, SQL files with several statements, cache invalidation, `proxy`, `login`) | OpenAPI | +| Fixed | upload endpoints have a `multipart/form-data` request body | OpenAPI | +| Fixed | a `204` response is documented for endpoints that answer `NULL` or no row with it | OpenAPI | +| Fixed | the cache invalidation endpoint of a hidden endpoint is hidden, and has the tags of its endpoint | OpenAPI, MCP | +| Fixed | functions for `raw`, `table_format`, `bytea`, cache invalidation and upload endpoints read and type the response the endpoint gives | TypeScript and Dart clients | +| Fixed | `outputSchema` and `structuredContent` agree for a set with one named column, `single` and the `void` annotation | MCP | +| Documented | what cannot be described exactly | [Known limits](#known-limits) | + +### Contents + +- [Changes in responses](#changes-in-responses) + - [`money` values are JSON strings](#money-values-are-json-strings) + - [`raw` responses are `text/plain`](#raw-responses-are-textplain) +- [Fixes](#fixes) + - [OpenAPI: the described response did not match the response](#openapi-the-described-response-did-not-match-the-response) + - [OpenAPI: three more things the document did not say](#openapi-three-more-things-the-document-did-not-say) + - [TypeScript and Dart clients: functions that read the wrong kind of response](#typescript-and-dart-clients-functions-that-read-the-wrong-kind-of-response) + - [MCP: `outputSchema` and `structuredContent` for four return shapes](#mcp-outputschema-and-structuredcontent-for-four-return-shapes) +- [Known limits](#known-limits) +- [For plugin authors](#for-plugin-authors) + +### Changes in responses + +#### `money` values are JSON strings + +A `money` value in a row was written without quotes: + +```json +[{"id":1,"price":$1,234.50}] +``` + +This is not valid JSON, so no client could read a response that had a `money` column, an array of `money`, or a composite type with a `money` field. It is now a string, as PostgreSQL writes it: + +```json +[{"id":1,"price":"$1,234.50"}] +``` + +- The text is in the format of the database's `lc_monetary` setting (`$1,234.50`, `1.234,50 €`), which is why it cannot be a JSON number. To get a number, return `price::numeric` from the routine. +- A routine that returns one `money` value answers with it as `text/plain`, as before. +- A `money` **parameter** is unchanged: it is a decimal number, sent as a number (`12.5`) or as a string (`"12.5"`). +- The generators follow: `money` is `string` in the TypeScript client, `String` in the Dart client (it was `double`), and a string in the OpenAPI document and in MCP schemas. This applies to parameters as well. + +#### `raw` responses are `text/plain` + +A `raw` endpoint that does not set a content type answered with the content type `application/json`, although its body is text that is not JSON. It now answers with `text/plain`. The same goes for a `raw` routine that returns a single array value. + +**If you rely on the old header:** set it on the endpoint. + +```sql +comment on function export_users() is ' +HTTP GET +raw +Content-Type: application/json'; +``` + +Endpoints that already set a content type (`Content-Type: text/csv`) are not affected. ### Fixes #### OpenAPI: the described response did not match the response -The document decided the response from the routine alone and did not look at the endpoint's annotations. Before the fix, 482 of the 1,271 answers of the test suite's endpoints that could be compared were not what the document said. What is left are answers that depend on data (a `NULL` result has no body) and arrays of more than one dimension (the number of dimensions is not part of a PostgreSQL array type). +The document decided the response from the routine alone and did not look at the endpoint's annotations. Before the fix, 482 of the 1,271 answers of the test suite's endpoints that could be compared were not what the document said. | Endpoint | The document said | The endpoint answers with, and the document now says | |---|---|---| @@ -24,9 +87,10 @@ The document decided the response from the routine alone and did not look at the | `void` annotation, or a routine that returns nothing | `200` | `204`, no body | | a single value that is not `json` or an array (`returns text`, `int`, `boolean`...) | `application/json` | `text/plain`; a boolean is `t` or `f` | | `bytea` | `application/json`, a string | `application/octet-stream` | -| `raw` | an array of objects | a string | +| `raw` | an array of objects | a string, `text/plain` | | `table_format` (HTML, Excel) | `application/json`, an array of objects | the content type of the format | | `json` and `jsonb` values and columns | an object | any JSON value | +| `money` | a number | a string | | a column that is an array of a composite type | an array of strings | an array of objects with the type's fields | | `nested` composite columns | the fields of the type as columns of the row | one object under the column name | | `returns record` | an object | an array of strings | @@ -67,11 +131,18 @@ and is now } } } } ``` +#### OpenAPI: three more things the document did not say + +- **Uploads.** An upload endpoint had no request body in the document. It now has a `multipart/form-data` body with the files. +- **`204` for no value.** An endpoint that answers a `NULL` value, or `single` with no row, with `204` (`response_null_handling no_content`) now has a `204` response next to its `200`. +- **Hidden endpoints.** The cache invalidation endpoint of an endpoint with `openapi hide` was still in the document, so the path that was meant to be hidden was visible. It is hidden now, and an invalidation endpoint also gets the `openapi tags` of its endpoint. + #### TypeScript and Dart clients: functions that read the wrong kind of response - **`raw`.** The function read the response as JSON (`response.json()`, `jsonDecode`) and failed, because a `raw` endpoint answers with text. It now returns the text (`string`, `String`). - **`table_format` and `bytea`.** The function read an HTML table or an Excel file as JSON, and bytes as text. It now returns the response itself (`Response`, `http.Response`), as functions of proxy endpoints do, so the caller reads it as text or as bytes. - **Cache invalidation endpoints.** The function was typed as the cached endpoint's response. It now returns `{ invalidated: boolean }` (`Map` in Dart). It is also written to the same module as the function of the cached endpoint, and the other `tsclient_...` and `dartclient_...` annotations of that endpoint apply to it. Before, they did not, and the function went to the default module. +- **Uploads.** The function of every upload endpoint was typed as a list of file descriptions (the upload metadata). That is right only when the routine returns the metadata, which is a routine that returns one `json` value. For any other routine the response is now `any` (`dynamic` in Dart). - **Dart, `void` annotation.** The function read a body from an endpoint that answers `204` without one. The TypeScript client was already correct. #### MCP: `outputSchema` and `structuredContent` for four return shapes @@ -81,12 +152,22 @@ and is now - **`single` on a set of values:** a text value kept its JSON quotes (`{"value": "\"a\""}`). It is now the value (`{"value": "a"}`). - **`void` annotation:** the tool declared an `outputSchema` and returned no `structuredContent`. It now declares none. +### Known limits + +What a generator cannot know when the endpoints are built. None of these is new in this version. + +- **Arrays of more than one dimension.** The number of dimensions is not part of a PostgreSQL array type: `int[]` and `int[][]` are the same type. An array is described as one of a single dimension (`number[]`, `List`, `{"type":"array","items":{"type":"integer"}}`), also when its values are arrays themselves (`[[1,2],[3,4]]`). An array of a composite type with more than one dimension holds its values as text (`"(1,a)"`), not as objects. +- **`json` and `jsonb`.** The value can be any JSON value, so it is described as any value (`any`, `dynamic`, `{}`), not as its actual shape. +- **`NULL` and missing rows.** A single value that is `NULL`, and `single` with no row, are answered with an empty body, with `null` or with `204`, depending on `response_null_handling`. The document describes the response with a value (and the `204`, when it is configured). It does not mark values as nullable: the OpenAPI document has no nullability at all yet, for parameters or for responses. +- **Responses decided at request time.** A content type or a table format taken from a parameter (`Content-Type: {_type}`, `table_format = {_format}`), the response of a proxied upstream service, and the body of a `login` (it depends on the authentication scheme) are described as any content (`*/*`), and the generated client functions for proxies and table formats return the response itself. +- **A text value declared as JSON.** A routine that returns `text` on an endpoint with `Content-Type: application/json` is described as any JSON value. Whether the text is valid JSON is up to the routine. +- **Uploads in the generated clients.** The upload function reads the response as JSON. A routine of an upload endpoint that returns plain text (`returns text`) is answered as `text/plain`, and the function fails to read it. Return `json` from such a routine. +- **Columns with the same name.** A result with two columns of the same name is written as a JSON object with that key twice (`{"value":1,"value":2}`). The descriptions hold one property of that name. Give the columns different names. +- **`money` text depends on the database.** See [above](#money-values-are-json-strings): the same value is `$1,234.50` in one database and `1.234,50 €` in another. +- **Responses written by custom code.** A response written by a `CommandCallbackAsync` or another extension point of the library is not known to the generators. They describe what the endpoint would answer with on its own. + ### For plugin authors `RoutineEndpoint.GetResponseKind(NpgsqlRestOptions?)` returns what kind of response an endpoint gives (`EndpointResponseKind`: `Routine`, `NoContent`, `RawText`, `Binary`, `TableFormat`, `Upstream`, `CacheInvalidation`). The four generators above now use it instead of each deciding on its own, which is how they came to disagree. A custom `IEndpointCreateHandler` that describes responses should use it as well. -### Not changed, found on the way - -- A `money` column in a set of rows is written without quotes (`"price":$1.00`), which is not valid JSON. -- A `raw` endpoint with no content type set answers with the content type `application/json`. The document now describes its body as a string under that content type. -- The cache invalidation endpoint of an endpoint that is hidden from the document (`openapi hide`) is still in the document. +The cache invalidation endpoint of a cached endpoint now carries that endpoint's `CustomParameters` and `Items`, so a handler sees for it what it saw for the cached endpoint. A handler that registers something for each endpoint with its metadata (as the MCP plugin registers tools) should skip endpoints with `InvalidateCache` set. From c1b22be0569b3ac1780e6bb00136922a22f1bfd3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Wed, 2 Dec 2026 09:35:27 +0100 Subject: [PATCH 8/9] chore: upgrade package references Serilog.Sinks.OpenTelemetry 4.3.0, Microsoft.Extensions.Caching.Hybrid 11.0.1 (10.11.1 on .NET 10), JwtBearer and StackExchangeRedis 10.0.15 on .NET 10; in tests WireMock.Net 2.35.0 and Mvc.Testing 10.0.15 on .NET 10. --- NpgsqlRestClient/NpgsqlRestClient.csproj | 10 +++++----- NpgsqlRestTests/NpgsqlRestTests.csproj | 4 ++-- changelog/v4.1.1.md | 14 ++++++++++++++ 3 files changed, 21 insertions(+), 7 deletions(-) diff --git a/NpgsqlRestClient/NpgsqlRestClient.csproj b/NpgsqlRestClient/NpgsqlRestClient.csproj index 21a55f60..a369273a 100644 --- a/NpgsqlRestClient/NpgsqlRestClient.csproj +++ b/NpgsqlRestClient/NpgsqlRestClient.csproj @@ -20,14 +20,14 @@ - + - - - + + + - + diff --git a/NpgsqlRestTests/NpgsqlRestTests.csproj b/NpgsqlRestTests/NpgsqlRestTests.csproj index 0c96d625..1f2c7c78 100644 --- a/NpgsqlRestTests/NpgsqlRestTests.csproj +++ b/NpgsqlRestTests/NpgsqlRestTests.csproj @@ -19,9 +19,9 @@ - + - + diff --git a/changelog/v4.1.1.md b/changelog/v4.1.1.md index a76a1c17..355e67c2 100644 --- a/changelog/v4.1.1.md +++ b/changelog/v4.1.1.md @@ -36,6 +36,7 @@ Patch release. What the generators say an endpoint answers with now matches what - [MCP: `outputSchema` and `structuredContent` for four return shapes](#mcp-outputschema-and-structuredcontent-for-four-return-shapes) - [Known limits](#known-limits) - [For plugin authors](#for-plugin-authors) +- [Dependencies](#dependencies) ### Changes in responses @@ -171,3 +172,16 @@ What a generator cannot know when the endpoints are built. None of these is new `RoutineEndpoint.GetResponseKind(NpgsqlRestOptions?)` returns what kind of response an endpoint gives (`EndpointResponseKind`: `Routine`, `NoContent`, `RawText`, `Binary`, `TableFormat`, `Upstream`, `CacheInvalidation`). The four generators above now use it instead of each deciding on its own, which is how they came to disagree. A custom `IEndpointCreateHandler` that describes responses should use it as well. The cache invalidation endpoint of a cached endpoint now carries that endpoint's `CustomParameters` and `Items`, so a handler sees for it what it saw for the cached endpoint. A handler that registers something for each endpoint with its metadata (as the MCP plugin registers tools) should skip endpoints with `InvalidateCache` set. + +### Dependencies + +Packages of the `npgsqlrest` client (the executable and its Docker images) were upgraded to their latest versions. The `NpgsqlRest` library and the plugins have no dependency changes. + +| Package | Version | +|---|---| +| `Serilog.Sinks.OpenTelemetry` | 4.2.0 → 4.3.0 | +| `Microsoft.Extensions.Caching.Hybrid` | 11.0.0 → 11.0.1 | + +For builds of the client on .NET 10: `Microsoft.Extensions.Caching.Hybrid` 10.7.0 → 10.11.1, `Microsoft.AspNetCore.Authentication.JwtBearer` and `Microsoft.Extensions.Caching.StackExchangeRedis` 10.0.9 → 10.0.15. + +In the test project: `WireMock.Net` 2.31.0 → 2.35.0, and `Microsoft.AspNetCore.Mvc.Testing` 10.0.9 → 10.0.15 for .NET 10. The whole test suite passes on .NET 11 and on .NET 10. From 18a49ebc5f87b7378ebbf78c516208d6d29158e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Wed, 2 Dec 2026 12:00:46 +0100 Subject: [PATCH 9/9] bump version 4.1.1 --- changelog/v4.1.1.md | 15 ++++++++++++++- npm/package.json | 2 +- .../NpgsqlRest.DartClient.csproj | 8 ++++---- plugins/NpgsqlRest.Mcp/NpgsqlRest.Mcp.csproj | 8 ++++---- .../NpgsqlRest.OpenApi/NpgsqlRest.OpenApi.csproj | 8 ++++---- .../NpgsqlRest.TsClient.csproj | 8 ++++---- version.txt | 2 +- 7 files changed, 32 insertions(+), 19 deletions(-) diff --git a/changelog/v4.1.1.md b/changelog/v4.1.1.md index 355e67c2..f2915c1f 100644 --- a/changelog/v4.1.1.md +++ b/changelog/v4.1.1.md @@ -1,6 +1,6 @@ # Changelog v4.1.1 -## Version [4.1.1](https://github.com/NpgsqlRest/NpgsqlRest/tree/4.1.1) (not released yet) +## Version [4.1.1](https://github.com/NpgsqlRest/NpgsqlRest/tree/4.1.1) (2026-12-02) [Full Changelog](https://github.com/NpgsqlRest/NpgsqlRest/compare/4.1.0...4.1.1) @@ -37,6 +37,7 @@ Patch release. What the generators say an endpoint answers with now matches what - [Known limits](#known-limits) - [For plugin authors](#for-plugin-authors) - [Dependencies](#dependencies) +- [NuGet Package Upgrades](#nuget-package-upgrades) ### Changes in responses @@ -185,3 +186,15 @@ Packages of the `npgsqlrest` client (the executable and its Docker images) were For builds of the client on .NET 10: `Microsoft.Extensions.Caching.Hybrid` 10.7.0 → 10.11.1, `Microsoft.AspNetCore.Authentication.JwtBearer` and `Microsoft.Extensions.Caching.StackExchangeRedis` 10.0.9 → 10.0.15. In the test project: `WireMock.Net` 2.31.0 → 2.35.0, and `Microsoft.AspNetCore.Mvc.Testing` 10.0.9 → 10.0.15 for .NET 10. The whole test suite passes on .NET 11 and on .NET 10. + +### NuGet Package Upgrades + +| Package | Version | +|---|---| +| `NpgsqlRest` | 4.1.0 → 4.1.1 | +| `NpgsqlRest.OpenApi` | 1.4.0 → 1.4.1 | +| `NpgsqlRest.TsClient` | 1.39.0 → 1.39.1 | +| `NpgsqlRest.DartClient` | 1.2.0 → 1.2.1 | +| `NpgsqlRest.Mcp` | 1.2.1 → 1.2.2 | + +The other plugins are unchanged. diff --git a/npm/package.json b/npm/package.json index 7d699b2b..a74ea1af 100644 --- a/npm/package.json +++ b/npm/package.json @@ -1,6 +1,6 @@ { "name": "npgsqlrest", - "version": "4.1.0", + "version": "4.1.1", "description": "Automatic REST API for PostgreSQL Databases Client Build", "scripts": { "postinstall": "node postinstall.js", diff --git a/plugins/NpgsqlRest.DartClient/NpgsqlRest.DartClient.csproj b/plugins/NpgsqlRest.DartClient/NpgsqlRest.DartClient.csproj index a53c27bb..88922ce6 100644 --- a/plugins/NpgsqlRest.DartClient/NpgsqlRest.DartClient.csproj +++ b/plugins/NpgsqlRest.DartClient/NpgsqlRest.DartClient.csproj @@ -26,10 +26,10 @@ true README.MD bin\$(Configuration)\$(AssemblyName).xml - 1.2.0 - 1.2.0 - 1.2.0 - 1.2.0 + 1.2.1 + 1.2.1 + 1.2.1 + 1.2.1 15 diff --git a/plugins/NpgsqlRest.Mcp/NpgsqlRest.Mcp.csproj b/plugins/NpgsqlRest.Mcp/NpgsqlRest.Mcp.csproj index d22c43e1..c9eff41c 100644 --- a/plugins/NpgsqlRest.Mcp/NpgsqlRest.Mcp.csproj +++ b/plugins/NpgsqlRest.Mcp/NpgsqlRest.Mcp.csproj @@ -26,10 +26,10 @@ true true true - 1.2.1 - 1.2.1 - 1.2.1 - 1.2.1 + 1.2.2 + 1.2.2 + 1.2.2 + 1.2.2 15 diff --git a/plugins/NpgsqlRest.OpenApi/NpgsqlRest.OpenApi.csproj b/plugins/NpgsqlRest.OpenApi/NpgsqlRest.OpenApi.csproj index 5913cab5..d4e7c8b6 100644 --- a/plugins/NpgsqlRest.OpenApi/NpgsqlRest.OpenApi.csproj +++ b/plugins/NpgsqlRest.OpenApi/NpgsqlRest.OpenApi.csproj @@ -28,10 +28,10 @@ true README.MD bin\$(Configuration)\$(AssemblyName).xml - 1.4.0 - 1.4.0 - 1.4.0 - 1.4.0 + 1.4.1 + 1.4.1 + 1.4.1 + 1.4.1 15 diff --git a/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj b/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj index 858a6ed3..9e69dfa7 100644 --- a/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj +++ b/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj @@ -26,10 +26,10 @@ true README.MD bin\$(Configuration)\$(AssemblyName).xml - 1.39.0 - 1.39.0 - 1.39.0 - 1.39.0 + 1.39.1 + 1.39.1 + 1.39.1 + 1.39.1 15 diff --git a/version.txt b/version.txt index 99eba4de..2582dddf 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -4.1.0 \ No newline at end of file +4.1.1 \ No newline at end of file