← 输入框|github.com|刷新
Skip to content

Releases

NpgsqlRest v4.1.1

Choose a tag to compare

@github-actions github-actions released this 02 Dec 11:14

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 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, 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. Read Changes in responses first: two responses change. What still cannot be described exactly is listed in Known limits.

Changelog

Install

  • Binaries (below): npgsqlrest-linux64, npgsqlrest-linux-arm64, npgsqlrest-osx-arm64, npgsqlrest-win64.exe, and the default appsettings.json
  • npm: npm install npgsqlrest@4.1.1
  • Docker: docker pull vbilopav/npgsqlrest:v4.1.1 (also -aot, -jit, -arm, -bun)
  • NuGet: dotnet add package NpgsqlRest --version 4.1.1
  • Installation guide

NpgsqlRest v4.1.0

Choose a tag to compare

@github-actions github-actions released this 21 Nov 10:02

This release makes NpgsqlRest easier to work with from an editor or any other tool, and moves it to Npgsql 11.

  • "Why is there no endpoint?" has an answer. npgsqlrest --inspect lists every routine and SQL file that was looked at and did not become an endpoint, each with the reason and what to change. It also says which files were generated for each endpoint, with the name and the line.
  • npgsqlrest --parse reads a comment the way the server does, without a database: which lines are annotations, which are text, which are written as annotations and read by nothing.
  • RequireAtPrefix: an optional strict reading of comments in which only a line that begins with @ is an annotation. It is off by default, so nothing changes for existing projects.
  • Npgsql 11. Performance is the same as 4.0.1 (measured, as JIT and as native AOT).
  • Fixes: an upload that ended the server process, a tab between the words of an annotation, quoted identifiers and $1$2 in SQL files, logout without a valid token in an application that only uses JWT, and the NpgsqlRest.Mcp package, which had never been published to NuGet.

Nothing changes in the behavior of an existing application unless it has one of the four things listed under What to check.

Changelog

Install

  • Binaries (below): npgsqlrest-linux64, npgsqlrest-linux-arm64, npgsqlrest-osx-arm64, npgsqlrest-win64.exe, and the default appsettings.json
  • npm: npm install npgsqlrest@4.1.0
  • Docker: docker pull vbilopav/npgsqlrest:v4.1.0 (also -aot, -jit, -arm, -bun)
  • NuGet: dotnet add package NpgsqlRest --version 4.1.0
  • Installation guide

NpgsqlRest v4.0.1

Choose a tag to compare

@github-actions github-actions released this 20 Nov 14:27

Patch release. It fixes one regression of 4.0.0 (password login failed on endpoints that use user parameters), one problem that 4.0.0 made visible (role checks failed for JWT sign-ins), and five older bugs. All of them were found by upgrading the examples to 4.0.0 and running every one of them. No configuration key was added, removed or renamed.

Who should upgrade: everyone on 4.0.0 who uses UseUserParameters (or user_params) together with a login endpoint, or who signs users in with JWT and uses roles.

Changelog

Install

  • Binaries (below): npgsqlrest-linux64, npgsqlrest-linux-arm64, npgsqlrest-osx-arm64, npgsqlrest-win64.exe, and the default appsettings.json
  • npm: npm install npgsqlrest@4.0.1
  • Docker: docker pull vbilopav/npgsqlrest:v4.0.1 (also -aot, -jit, -arm, -bun)
  • NuGet: dotnet add package NpgsqlRest --version 4.0.1
  • Installation guide

NpgsqlRest v4.0.0

Choose a tag to compare

@github-actions github-actions released this 20 Nov 13:08

This is a major version. The number went from 3.21 to 4.0 because this release contains breaking changes: security fixes that change how logins, authorize, proxies, antiforgery and uploads behave, and a move of the npgsqlrest executable to .NET 11. Read the upgrade notes before upgrading; most applications need no change, and the ones that do will find it there. (During development this release was called 3.22.0.)

This release moves NpgsqlRest to .NET 11 (the library and plugins also keep supporting .NET 10) and is a security release. A full review of the codebase found several vulnerabilities, including one critical issue in password login. Everyone should upgrade. Some security fixes change behavior that applications may rely on. Each is described below, with what to check before upgrading.

It is also a performance release. Compared with 3.21.0, NpgsqlRest serves 21–24% more row requests per second with 28–36% less CPU and a half to a quarter of the memory, because rows are written as UTF-8 bytes straight from the database through one pooled request state and sent in larger network writes. Endpoints with user_context now send their context together with the routine in one database round trip instead of two, so they serve 41–69% more requests per second and answer about 120 µs sooner, and connections are reset between requests only when an endpoint actually leaves something on them. The measurements, as JIT and as native AOT, are under Performance.

Changelog

Install

  • Binaries (below): npgsqlrest-linux64, npgsqlrest-linux-arm64, npgsqlrest-osx-arm64, npgsqlrest-win64.exe, and the default appsettings.json
  • npm: npm install npgsqlrest@4.0.0
  • Docker: docker pull vbilopav/npgsqlrest:v4.0.0 (also -aot, -jit, -arm, -bun)
  • NuGet: dotnet add package NpgsqlRest --version 4.0.0
  • Installation guide

NpgsqlRest v3.21.0

Choose a tag to compare

@github-actions github-actions released this 12 Jul 10:43

Version 3.21.0 (2026-07-12)

Full Changelog

Features

Per-connection routine discovery: ReadMetadataFromConnections

Until now, routine metadata (functions and procedures) was always discovered on a single connection, while the connection annotation only changed where a request executes. That silently assumed every named connection has identical routine metadata — true for read replicas and shards, but wrong for setups where different databases host different routines (OLTP + OLAP/DW): a routine living only on the OLAP database had to be duplicated on the default database (with its annotation) just to be discovered, even though it was never called there.

That requirement is gone:

{
  "ConnectionStrings": {
    "Default": "Host=localhost;Port=5432;Database=oltp;Username=postgres;Password=postgres",
    "olap": "Host=warehouse;Port=5432;Database=olap;Username=postgres;Password=postgres"
  },
  "NpgsqlRest": {
    "RoutineOptions": {
      "ReadMetadataFromConnections": [ "Default", "olap" ]
    }
  }
}
  • Routine metadata is read from each listed connection (one routine source per name; all other RoutineOptions settings and the global schema/name filters are shared).
  • Endpoints execute on the connection they were discovered from — a routine on the olap database is discovered there and runs there, annotations included, with nothing extra to configure. An explicit connection comment annotation still wins.
  • The list replaces the default — include the main connection's name (as above) to keep serving its routines.
  • Setting the key implicitly enables multiple connections — no UseMultipleConnections: true required (an Information log notes it).
  • null or absent = exactly the previous behavior (single discovery connection).
  • Every listed name must exist in ConnectionStrings — an unknown name stops startup with an error listing the available names.
  • Composite types now resolve per database: two databases can have a same-named composite type with different fields and each source serializes with its own definition.
  • Watch mode (--watch) polls each discovery connection: a routine created/dropped/commented on any listed connection triggers the restart, not just the primary.
  • For library (middleware) users: RoutineSource (and IEndpointSource via a default interface member) gains a ConnectionName property, and CreateAndOpenSourceConnection accepts an optional per-source connection name that overrides MetadataQueryConnectionName.

When two sources discover the same path (a routine existing on both databases), the later source wins and a startup warning names both sources and connections — use schema/name filters or a path annotation to disambiguate.

Use ReadMetadataFromConnections when databases host different routines. For identical databases (replicas, shards), keep using UseMultipleConnections with the connection annotation — single discovery is correct and cheaper there.

Routed endpoint verification: VerifyRoutedEndpoints

Endpoints routed by the connection annotation to a different connection than they were discovered on assume the target database has the same routines. Nothing checked that assumption until the first failing request. Now, opt-in:

{
  "NpgsqlRest": {
    "RoutineOptions": {
      "VerifyRoutedEndpoints": "Warn"
    }
  }
}
  • "None" (default) — no verification.
  • "Warn" — at startup, one batched existence check per distinct target connection (to_regprocedure for functions/procedures; to_regclass for tables/views when composing CrudSource in the library); every missing routine is logged as a warning naming the routine, the connection, and the endpoints that need it.
  • "Fail" — same check, but any missing routine stops startup with an aggregated error.

This checks content (does the routine exist over there?) — connectivity of every connection string remains a separate concern covered by ConnectionSettings:TestConnectionStrings (opens and closes the connection). The check verifies existence/signature only (result shapes are not compared), and SQL-file endpoints are skipped (no catalog name to check). Cost: one connection and one round-trip per distinct annotated target connection, only when enabled.

Environment variable fallback values: {!NAME:fallback}

Environment variable placeholders now support an inline fallback value, completing the placeholder grammar:

Form Behavior
{NAME} Optional — replaced when the variable is set, left untouched otherwise.
{!NAME} Required — replaced when the variable is set, startup fails otherwise.
{!NAME:fallback} Replaced when the variable is set, otherwise the literal fallback text is used — never fails.

The fallback starts after the first : and runs to the closing brace, so it may itself contain : (e.g. {!BASE_URL:http://localhost:5000}), but not }. Only the {! form takes a fallback — a plain {NAME:...} is never treated as an env placeholder, which keeps brace-colon content like Serilog format specifiers ({Timestamp:HH:mm:ss}), inline CSS (td{border:1px solid}), and TypeScript object types ({status: number}) intact.

The default connection string now uses fallbacks matching the standard PostgreSQL defaults for everything except the database name, which stays required:

{
  "ConnectionStrings": {
    "Default": "Host={!PGHOST:localhost};Port={!PGPORT:5432};Database={!PGDATABASE};Username={!PGUSER:postgres};Password={!PGPASSWORD:postgres}"
  }
}

With no environment configured at all, startup fails with exactly one actionable error — Required environment variable 'PGDATABASE' (referenced as '{!PGDATABASE}' in configuration) is not set. Setting only PGDATABASE connects to localhost:5432 as postgres/postgres.

Notes:

  • The --config output and --validate resolve fallbacks (the fallback is the value the running application will use), while unset {!NAME} placeholders without a fallback are still kept as literals so the configuration can always be inspected before the environment is set up.
  • Works in every configuration value (connection strings, test-runner connections, any typed value — e.g. "Port": "{!PORT:5432}").

The same placeholder rules in static content and annotation values

The {!NAME} and {!NAME:fallback} forms now also work in the two request-time substitution systems, with the same grammar and their existing allowlist security model unchanged:

  • Static files ({ "StaticFiles": { "ParseContentOptions": { "AvailableEnvVars": [...] } } }): {!NAME} resolves like {NAME} for listed names; {!NAME:fallback} uses the inline fallback when the listed variable is unset and has no configured default. The same applies to claims: {!claim_name:fallback} uses the fallback when the claim is absent (e.g. anonymous requests). Unlisted names are always left untouched — the strict forms never widen the allowlist.
  • Comment annotations and HTTP Custom Types ({ "NpgsqlRest": { "AvailableEnvVars": [...] } }): same rules for response headers, custom parameters, and HTTP custom type URL/body/header values. Routine parameters keep precedence over env vars in both forms, and a null parameter value now yields the inline fallback: X-Plan: {!_plan:free} sends free when _plan is null.
  • The build-time unknown-placeholder warning understands the new forms and validates the name part, so a typo in {!NAME:fallback} is still caught at startup.
  • For library (middleware) users populating NpgsqlRestOptions.SubstitutionEnvironmentVariables directly: register a second "!NAME" key alongside each "NAME" entry that resolved to a real value — the standalone client does this automatically. See the property documentation.

.env file loaded by default ("EnvFile": "./.env")

The default configuration now ships with:

{
  "Config": {
    "EnvFile": "./.env"
  }
}

Combined with the new fallback connection string, this makes the minimal setup a single file — create .env next to the configuration with one line, PGDATABASE=mydb, and run npgsqlrest.

Behavior:

  • Variables already present in the process environment always win — the file only fills in missing ones (the standard dotenv convention). ⚠️ This is a behavior change for existing EnvFile users: before 3.21.0 the file overwrote the environment. Within the file itself, a repeated key keeps its last value.
  • The default ./.env (relative to the working directory) is optional: when the file does not exist, startup logs an information message — Env file ./.env not found, skipping (set Config:EnvFile to null to disable env file loading) — never a warning, so clean production deployments (env vars from the orchestrator, no file) stay warning-free.
  • A custom EnvFile path that does not exist logs a warning — you explicitly named a file that is not there.
  • When the file loads, startup logs how many variables it contributed and how many were kept from the real environment: Loaded 3 environment variable(s) from env file ./.env (1 already set in the environment and kept).
  • Set "EnvFile": null to disable loading entirely. Configurations that omit the EnvFile key keep the previous behavior (no file is loaded) — the ./.env default comes from the shipped configuration file, not from code.

--install-skill: install the Claude Code skill from the CLI

The official Claude Code skill can now be installed directly from the binary, replacing the platform-specific curl/Invoke-WebRequest instructions:

npgsqlrest --install-skill          # project scope: ./.claude/skills/npgsqlrest (commit it for the wh...
Read more

NpgsqlRest v3.20.0

Choose a tag to compare

@github-actions github-actions released this 09 Jul 11:19

Version 3.20.0 (2026-07-09)

Full Changelog

This release introduces the Dart client code generator — a new NpgsqlRest.DartClient plugin that generates Dart fetch modules for Flutter projects, the same way NpgsqlRest.TsClient generates TypeScript modules. Also included: TanStack Query (React Query) hooks generation for the TypeScript client, function-calling schemas (OpenAI/Anthropic) and llms.txt generated from the MCP tool set, support for the HTTP QUERY method, and a configurable OpenAPI specification version (3.0 / 3.1) for the OpenAPI plugin.


1. Dart client code generation (NpgsqlRest.DartClient 1.0.0)

For every NpgsqlRest endpoint the generator emits idiomatic Dart built on package:http (no other dependencies, works on all Flutter targets — mobile, desktop, web):

  • Request classes with toJson() — one field per routine parameter, optional-named constructor parameters. Parameters with PostgreSQL defaults are omitted from the JSON body and query string when null (so the database default applies), mirroring the TypeScript client's optional-property semantics.
  • Response classes with a fromJson() factory — one field per column, snake_case columns become lowerCamelCase fields with the raw wire name kept as the JSON key. Composite type columns become nested model classes (flat or nested per the endpoint's nested annotation).
  • Async functions wrapping the HTTP call: query-string building (_query helper with URL encoding, repeated keys for arrays, ISO 8601 for DateTime), path-parameter interpolation resolved to the generated request fields, JSON bodies, custom headers, and @body_parameter_name handling.
  • ApiResult<T> / ApiError wrappers carrying the HTTP status code and problem-details errors (IncludeStatusCode option or the dartclient_status_code annotation).
  • Multipart upload functions for upload endpoints (http.MultipartRequest, files sent as form field file, optional progress callback reporting uploaded bytes, optional XSRF token header).
  • Server-sent events (SSE) support: SSE endpoints generate create{Name}EventSource factories returning an SseSubscription (built on streamed package:http responses — no extra dependency) and SSE-aware functions with onMessage/id/closeAfterMs/awaitConnectionMs parameters that attach the execution-id header to the triggering request — including combined upload+SSE endpoints.
  • Raw responses for proxies: proxy_out and void proxy pass-through endpoints return Future<http.Response> directly.
  • Per-call rewrite hooks: IncludeParseUrlParam/IncludeParseRequestParam options (and dartclient_parse_url/dartclient_parse_request annotations) add optional parseUrl/parseRequest named parameters that can rewrite the URI or request before sending.
  • Login/logout special-casing: login endpoints return the token String, logout endpoints return void.
  • Testability: each generated module exposes a top-level http.Client? httpClient variable — assign a MockClient from package:http/testing.dart to intercept requests in tests.

Type mapping

Unlike TypeScript (where every numeric is number), Dart distinguishes integers from floating point:

PostgreSQL Dart
smallint, integer, bigint int
real, double precision, numeric, money double
boolean bool
json, jsonb dynamic (configurable via DefaultJsonType)
date, timestamp, timestamptz DateTime (configurable via UseDateTimeType)
everything else String
arrays List<T>

Dart reserved words and dart:core type names used as parameter or column names are escaped with a trailing underscore (class → class_, double → double_) while JSON keys keep the raw wire names.

Configuration

New NpgsqlRest:DartClientCodeGen configuration section (sibling of ClientCodeGen, which is unchanged). Full section with defaults:

{
  "NpgsqlRest": {
    "DartClientCodeGen": {
      "Enabled": false,
      "FilePath": null,
      "FileOverwrite": true,
      "IncludeHost": true,
      "CustomHost": null,
      "CommentHeader": "Simple",
      "CommentHeaderIncludeComments": true,
      "BySchema": true,
      "IncludeStatusCode": true,
      "SeparateModelsFile": false,
      "ImportBaseUrlFrom": null,
      "HeaderLines": ["// autogenerated at {0}", ""],
      "SkipRoutineNames": [],
      "SkipFunctionNames": [],
      "SkipPaths": [],
      "SkipSchemas": [],
      "DefaultJsonType": "dynamic",
      "UseRoutineNameInsteadOfEndpoint": false,
      "ExportUrls": false,
      "UniqueModels": false,
      "XsrfTokenHeaderName": null,
      "ExportEventSources": true,
      "IncludeParseUrlParam": false,
      "IncludeParseRequestParam": false,
      "CustomImports": [],
      "CustomHeaders": {},
      "IncludeSchemaInNames": true,
      "ErrorTypeName": "ApiError",
      "ResultTypeName": "ApiResult",
      "OmitAutomaticParameters": false,
      "ModelPrefix": null,
      "ModelSuffix": null,
      "UseDateTimeType": true
    }
  }
}

Set Enabled to true and point FilePath at your Flutter project, e.g. "../my_app/lib/api/{0}.dart" — {0} is the PostgreSQL schema name (snake case) or the module name from the dartclient_module annotation (with BySchema).

Most options carry the same meaning as their ClientCodeGen counterparts. Dart-specific options:

  • SeparateModelsFile — emit request/response (and composite) model classes into a separate {name}_models.dart file; the client file imports and re-exports it so consumers keep a single import (the Dart analog of CreateSeparateTypeFile/ExportTypes).
  • ModelPrefix / ModelSuffix — namespace generated model class names to avoid collisions when several generated modules are imported into one file (there is no TypeScript-style I prefix).
  • UseDateTimeType — when true (default), date/timestamp/timestamptz map to DateTime (DateTime.parse in fromJson, toIso8601String in toJson); when false, they map to String.
  • ErrorTypeName / ResultTypeName — names of the generated status-wrapper classes (replaces TypeScript's free-text ErrorExpression/ErrorType, which cannot be safely injected into Dart).
  • ExportEventSources — when false, SSE event source factories get a private (underscore) name instead of a public one (the Dart analog of not exporting them).
  • IncludeParseUrlParam / IncludeParseRequestParam — add the per-call parseUrl/parseRequest rewrite hooks to every generated function.

ClientCodeGen options with no Dart counterpart (intentionally dropped): SkipTypes (there is no untyped Dart), ExportTypes (every non-underscore Dart declaration is already public), and ImportParseQueryFrom (the generated helpers are underscore-private and cannot be imported across Dart files; use ImportBaseUrlFrom for the shared baseUrl).

Comment annotations

Per-endpoint overrides in routine comments:

  • dartclient = off — exclude the endpoint from generation.
  • dartclient_module=name — group endpoints into a module file (falls back to tsclient_module, so SQL-file directory grouping applies to both generators).
  • dartclient_status_code=true — wrap this endpoint's response in ApiResult<T>.
  • dartclient_events=false — generate a plain function for an SSE endpoint (no event-source parameters).
  • dartclient_parse_url=true / dartclient_parse_request=true — add the per-call rewrite hooks to this endpoint.
  • dartclient_export_url=true — also emit a {name}Url() URL-builder function.
  • dartclient_url_only=true — emit only the URL-builder function.

Known limits

  • numeric/money map to double (the JSON wire format already carries a JSON number); Dart int on Flutter Web is limited to 2^53.
  • Multi-dimensional arrays are typed as one-dimensional List<T> (PostgreSQL does not expose array dimensionality — same limitation as the TypeScript client).

Other changes

  • docker/Dockerfile.jit: the dependency-restore layer now copies the NpgsqlRest.SqlFileSource and NpgsqlRest.Mcp project files (previously missing, breaking dotnet restore in the JIT image build), along with the new NpgsqlRest.DartClient.

2. Configurable OpenAPI specification version (NpgsqlRest.OpenApi)

The OpenAPI plugin previously always emitted "openapi": "3.0.3". A new SpecVersion option selects the specification version of the generated document:

{
  "NpgsqlRest": {
    "OpenApiOptions": {
      // OpenAPI specification version of the generated document: "3.0" or "3.1".
      // "3.0" emits openapi: 3.0.3 (default, backward compatible),
      // "3.1" emits openapi: 3.1.1 (JSON Schema 2020-12 alignment).
      // This is the spec version, not your API version (that is DocumentVersion).
      "SpecVersion": "3.0"
    }
  }
}
  • "3.0" (default) emits openapi: 3.0.3 — output is unchanged from previous releases.
  • "3.1" emits openapi: 3.1.1. The emitter uses no keyword whose semantics differ between OpenAPI 3.0 and 3.1 (nullable, exclusiveMinimum/exclusiveMaximum, ...), so the rest of the document is identical — the setting matters for toolchains that require a 3.1 document (JSON Schema 2020-12 alignment).
  • Values are trimmed and case-insensitive; any other value fails fast at startup with an error listing the valid values — no silent fallback.
  • The emitted version strings are exposed as constants (OpenApiSpecVersions.V30 / V31) instead of inline literals.

3. TanStack Query (React Query) hooks generation (NpgsqlRest.TsClient)

The TypeScript client generator can now emit a TanStack Query v5 hooks module alongside each generated client module: useQuery hooks for GET endpoints and...

Read more

NpgsqlRest v3.19.0

Choose a tag to compare

@github-actions github-actions released this 03 Jul 19:20

Version 3.19.0 (2026-07-03)

Full Changelog

This release introduces the SQL test runner (npgsqlrest --test) — write tests for your endpoints as plain .sql files, invoke endpoints in-process from inside a test, and assert on both the HTTP response and the database state, all within the test's own transaction. Also included: watch mode (--watch — re-run tests or restart the server on SQL and configuration changes), named parameters in SQL files (:name), a skip glob for the SQL file source, and the ability to mute an individual logger.


1. SQL test runner (--test)

npgsqlrest ./config.json --test

The runner discovers .sql test files, executes each on its own isolated connection, and reports per-assertion results to the console (and optionally JUnit XML for CI). A test file is ordinary SQL — arrange data, call an endpoint, assert on the result:

-- tests/get_users_excludes_caller.test.sql
begin;

insert into app.users (id, email, name) values (100, 'x@example.com', 'Fixture');

/*
GET /api/get-users
# @claim user_id=1
*/
select (select status from _response) = 200,
       'authenticated caller gets 200';
select (select body::jsonb @> '[{"email": "x@example.com"}]' from _response),
       'the fixture user is listed';

rollback;
NpgsqlRest test runner — 9 file(s)
PASS  tests/get_users_excludes_caller.test.sql  (2 assertions, 52ms)
...
19 passed, 0 failed, 0 error(s)  —  19 assertions in 9 files

How it works

In --test mode the client builds the full endpoint middleware exactly as in normal operation (endpoints from database routines and/or SQL files, authentication, custom parameters — everything), but instead of starting the web server it runs the test files and exits with a result code. Endpoint calls made from a test are in-process: no network, no running server — the complete endpoint pipeline (routing, authorization, parameter binding, execution, serialization) runs against a synthetic HTTP context.

The critical property is connection affinity: the in-process endpoint call runs on the test's own connection, inside the test's own transaction. A test can begin, insert fixture rows, call an endpoint that sees those uncommitted rows, assert on the response, and rollback — leaving no trace. Each test file gets its own non-pooled physical connection (fresh session: no temp-table, GUC, or prepared-statement carryover), and files run in parallel (MaxParallelism, default = processor count). If a file never rolls back, closing its physical connection aborts the open transaction — that is the safety net.

Test-mode invariants, applied automatically:

  • WrapInTransaction is forced off (the test file owns transaction control — the runner never injects BEGIN/COMMIT/ROLLBACK).
  • Response caching is disabled (a test never sees another test's cached response).
  • Code generation (HTTP files, TypeScript client, OpenAPI) is skipped — a test run never rewrites generated artifacts.

Test file anatomy

A test file is a sequence of SQL statements and HTTP blocks, executed strictly in order. Files are executed statement by statement (like psql): each statement runs in autocommit unless the file opens its own transaction. Semicolon splitting understands line/block comments, string literals with '' escapes, and dollar-quoted bodies — a do $$ … $$; block stays whole.

Assertions — a reported test is one of:

  • A boolean-returning SELECT. If the first column is boolean, the statement is an assertion: the first row's value must be true (false or null fails; zero rows passes vacuously; only the first row is examined). The optional second column is the assertion's name/message, shown in the report and used as the JUnit test-case name:
    select count(*) = 3, 'exactly three users are seeded' from app.users;
  • A do block. Passes unless it raises — assert inside a DO block raises SQLSTATE P0004, reported as a failure with the assert message. One DO block = one reported test (multiple asserts inside it are opaque to the runner):
    do $$ begin
        assert app.normalize_email(' X@Y.z ') = 'x@y.z', 'should trim and lowercase';
    end $$;

Any other statement is arrange/act — not counted as a test; it only surfaces if it errors. Any SQL error (other than an assert) is reported as an error with its SQLSTATE, message, statement text, and file:line.

Failing behavior is fail-fast per file: after the first failed/errored assertion the rest of the file does not run (a failed DO-block assert aborts the transaction anyway). Assertions that passed before the failure are still credited.

HTTP blocks — invoking endpoints

An HTTP request is embedded in a block comment whose first non-comment line is a request line — a single-request subset of the standard .http file syntax:

/*
POST /api/create-user
Content-Type: application/json
# @claim user_id=42
# @claim roles=admin
# @response created

{"name": "Grace Hopper", "email": "grace@example.com"}
*/

Syntax rules:

  • Request line: [HTTP] METHOD /path[?query] [HTTP/x] — the method is one of GET, POST, PUT, DELETE (the methods NpgsqlRest endpoints support); the path must start with / and must equal the endpoint's full path including UrlPathPrefix (default /api); the leading HTTP keyword and a trailing HTTP-version token are optional. A block comment whose first line is not a valid request line is an ordinary SQL comment — ignored.
  • Headers: Name: Value lines after the request line. Content-Type is picked up for the request body.
  • Directives (lines starting with # @ or // @, placed after the request line, before the body):
    • # @claim name=value — adds a claim to the acting principal. Repeatable, including the same claim type twice (e.g. two roles claims). Any # @claim makes the request authenticated; no # @claim means anonymous (an @authorize endpoint returns 401). Role checks and claim-to-parameter mappings (@user_parameters, ParameterNameClaimsMapping) work exactly as in production — tests exercise the real authorization path.
    • # @response name — capture this block's response into a temp table with the given name instead of the default.
  • Body: everything after the first blank line, verbatim. (Limitation: a literal */ inside the body ends the SQL comment early.)
  • Plain # or // lines are comments; unknown @ directives are ignored.

An HTTP block is an act step, not an assertion — it captures the response and produces no test result of its own. The assertions are the SQL statements that follow it. One request per block; use multiple blocks for multiple calls.

Endpoint kinds that cannot work meaningfully in-process are rejected with a clear error: SSE, upload, login/logout (inject the principal with # @claim instead), and outbound proxy/HTTP-type endpoints (tests must not call external services). A request whose path matches no endpoint still runs (a test may assert the 404 deliberately) but logs a warning — the most common cause is a path typo or a missing /api prefix.

The response temp table

Each HTTP block's response is captured into its own temp table on the test's connection, created fresh (no IF NOT EXISTS — a duplicate name, e.g. a repeated # @response name, fails the test loudly). Default columns:

Column Type Content
status int HTTP status code
body text response body (cast to ::jsonb to assert on JSON)
content_type text response content type
headers jsonb response headers
is_success boolean true for 2xx

Naming: a file with one HTTP block uses ResponseTempTable.Name (default _response); a file with two or more uses ResponseTempTable.MultiNamePattern (default _response_{n}) where {n} is the block's 1-based position — _response_1, _response_2, … A block with # @response name uses that name instead (it still counts in the numbering of the others). Column names are configurable; setting one to null/empty omits that column.

select (select body::jsonb ->> 'email' from _response) = 'grace@example.com',
       'email is normalized to lowercase';

Debugging captured responses — temp tables vanish with the test's rollback and connection, so you cannot inspect them afterwards (and re-issuing the request from an .http file cannot reproduce a response that depended on the test's uncommitted fixtures). Set ResponseTempTable.DebugTable (e.g. "_responses_debug"; default null = off) and every captured response is also mirrored into a permanent table — written on a separate autocommit connection, immune to rollbacks, recreated at the start of every run so it always holds the last run. One table covers everything: each HTTP block adds one row, with test_file, block (that block's response-table name — _response, a _response_{n} ordinal, or the # @response name), method, path, status, body, content_type, headers, is_success, and captured_at — so after a run you can open a query editor and dig into any response with jsonb operators. The temp-table semantics are unchanged; enabling it prints a loud warning (debugging aid — do not enable in CI). In the fresh-test-database workflow combine it with Keep: true, or teardown drops the database and the mirror with it.

Reusing scripts: \i and \ir includes

Shared SQL — fixture inserts, utility scripts — can be spliced into any test with psql's include syntax on its own line:

begin;

\ir fixtures/extra_users.sql    -- path relative to THIS file (psql \ir semantics)
\i  ./shared/reset_counters.sql -- path relative ...
Read more

NpgsqlRest v3.18.2

Choose a tag to compare

@github-actions github-actions released this 26 Jun 13:01

Version 3.18.2 (2026-06-26)

Full Changelog

Patch release with fixes for proxy endpoints that forward auto-filled parameters (v3.18.1) and the generated TypeScript client, plus a new opt-in option to omit server-filled parameters from generated request shapes. All surfaced by combining a @proxy with an HTTP Custom Type parameter.

What changed

1. Large auto-filled values no longer break the proxy query string

New option ProxyOptions.MaxForwardedQueryParamLength (default 2048). When a server-filled parameter is appended to the proxy upstream query string, a value longer than this limit is now skipped with a warning instead of being percent-encoded into the URL.

Previously, an HTTP Custom Type whose body field held a large payload (e.g. a scraped HTML page) was percent-encoded into the upstream query string, producing an oversized request line that the upstream rejected (HTTP 414 / 431) or that reset the connection. To forward such a value, use a body-carrying proxy method (POST/PUT/PATCH) so it travels in the request body instead. Set the option to 0 to disable the guard.

2. @body_parameter_name reliably matches HTTP Custom Type fields

@body_parameter_name now matches case-insensitively and accepts any of the parameter's names. For an HTTP Custom Type field expanded out of a composite parameter, all of these now resolve to the same field:

  • the converted (API) name — e.g. responseBody
  • the expanded signature name — e.g. _response_body (the name shown in the generated signature / .http file)
  • the base composite name — e.g. _response (shared by all expanded fields; resolves to the first one)

Previously the annotation value was force-lowercased and compared case-sensitively, so the camelCase converted name never matched, and the expanded signature name (_response_body) matched nothing at all — it is stored as neither the actual nor the converted name. This made it impossible to redirect a single expanded HTTP-type field (such as the response body) into the proxy request body.

Body-parameter resolution is now a single shared rule on the core endpoint (RoutineEndpoint.IsBodyParameter) used by request handling and every code generator, so they no longer drift. This also fixes the HTTP file and OpenAPI generators, which previously left a @body_parameter_name field (e.g. responseBody) in the query string / query parameters instead of moving it to the request body.

3. TypeScript client generation for @body_parameter_name

The generated TypeScript client was broken for an endpoint with @body_parameter_name:

  • the body expression was emitted as request.responseBody? — a syntax error (the TS optional ? suffix leaked into the runtime property name);
  • the query-string exclusion key was ["responseBody?"], so the body parameter was not stripped from the query string;
  • a body was emitted even for a GET request, which fetch forbids.

The generator now uses the parameter's bare name for the body expression and the exclusion key, only emits a fetch body for methods that can carry one (not GET), and — like the server — matches @body_parameter_name against the converted, actual, or expanded signature name of an HTTP Custom Type field (e.g. responseBody, _response, or _response_body).

4. Opt-in: omit automatic (server-filled) parameters from generated request shapes

New option OmitAutomaticParameters on all three generators — TsClientOptions, HttpFileOptions, and OpenApiOptions (default false, so generated output is unchanged unless you opt in).

When enabled, a parameter is omitted from the generated request (TypeScript request interface, .http query/body, OpenAPI query parameters / request body) when it is automatic (filled server-side, so a client value would be ignored) and optional. Automatic covers: HTTP Custom Type fields, resolved-parameter expressions, upload-metadata parameters, and — on endpoints that use user parameters — IP-address and user-claim parameters. The shared rule lives on the core endpoint (RoutineEndpoint.OmitParameterFromGeneratedRequest), so the three generators stay consistent. When every parameter is omitted, the generated request collapses cleanly (no-argument TS function, bare .http URL, no OpenAPI parameters/requestBody).

This is the proper fix for the misleading case where, e.g., an HTTP Custom Type's responseBody field appeared as a settable request parameter even though the server always overrides it.

Why these go together

The pattern "fetch with an HTTP Custom Type, then @proxy to an upstream" now works cleanly end to end — server and generated client: redirect the (large) body field into the upstream request body with @body_parameter_name, while the remaining small fields travel on the query string under the new length guard.

Notes

  • ProxyOptions.MaxForwardedQueryParamLength is wired through the client config (appsettings.json, JSON schema, and the --config template).
  • No parameter ActualName semantics changed: expanded HTTP-type fields still share the composite base name so they reassemble into the single SQL argument; the per-field name is matched via an internal alias only.

Tests

NpgsqlRestTests/ProxyTests/ProxyHttpTypeProbeTest.cs adds three cases (WireMock proxy target echoing the received URL / body): body redirect by converted name (responseBody), body redirect by expanded signature name (_response_body), and an oversized HTTP-type body field skipped from the proxy query string. NpgsqlRestTests/TsClientTests/BodyParamGetTests.cs covers the generated client for @body_parameter_name endpoints: a GET case (no ?-suffixed name, parameter excluded from the query, no fetch body on GET) and a POST HTTP-Custom-Type case targeted by the expanded name _response_body (body emitted as request.responseBody, excluded from the query). The HTTP file and OpenAPI generators are covered for the same expanded-name body redirect (BodyParamToBodyTests). OmitAutomaticParameters is covered for each generator (TsClient: all-omitted no-arg function + mixed-params; HttpFiles and OpenAPI: query/body omission of HTTP Custom Type fields). Full suite green (2301).

NpgsqlRest v3.18.1

Choose a tag to compare

@github-actions github-actions released this 23 Jun 12:19

Version 3.18.1 (2026-06-23)

Full Changelog

Patch release that makes all automatic (server-filled) parameters forward to proxy endpoints consistently, in the endpoint's native parameter shape.

What changed

When an endpoint is a proxy, the parameters that NpgsqlRest fills server-side are now forwarded to the upstream uniformly, regardless of source:

  • user claims (claim-mapped parameters),
  • IP address parameter,
  • HTTP Custom Type fields (the auto-filled responseBody / responseStatusCode / … on a routine with an HTTP Custom Type parameter),
  • resolved-parameter expressions (values looked up server-side via SQL).

All of them follow the same placement rule, which mirrors how the endpoint itself receives parameters — not the HTTP verb:

  • The parameter designated as the body parameter (@body_parameter_name) carries the raw request body.
  • Otherwise placement follows the endpoint's RequestParamType: QueryString → appended to the proxy query string; BodyJson → merged into the proxy JSON body (typed: numbers, booleans, embedded JSON, or strings), when the proxy method can carry a JSON body.

This is additive: the verbatim incoming request is still forwarded; the automatic parameters are added on top, so the upstream receives the same parameter set the routine would have.

Why

Previously the behavior was inconsistent: user-claim and IP parameters were always appended to the query string, HTTP Custom Type fields and resolved parameters were not forwarded at all, and a passthrough proxy discarded the auto-filled values entirely (the outbound HTTP Custom Type call fired but its result went nowhere). Now every automatic parameter behaves the same way.

Behavior change to note

User-claim and IP parameters now follow RequestParamType like every other automatic parameter. For a QueryString endpoint (the default for GET) they remain in the query string, exactly as before. For a BodyJson endpoint they are now merged into the JSON body rather than forced onto the query string. Method does not decide placement — RequestParamType does (a POST endpoint can use param_type query and its parameters then go to the query string).

Notes

  • Body merging applies only when the forwarded request carries a JSON content type; multipart and non-JSON bodies are forwarded verbatim.
  • Only the expanded per-field HTTP Custom Type parameters (DB-function shape) are forwarded; single-composite HTTP parameters (SQL-file shape) are not.

Tests

NpgsqlRestTests/ProxyTests/ProxyHttpTypeProbeTest.cs covers, via a WireMock proxy target that echoes the received URL / body: HTTP-type fields forwarded on the query (GET) and merged into the JSON body (POST, typed); placement following RequestParamType rather than the verb (a param_type query POST forwards to the query, not the body); and a resolved-parameter expression forwarded consistently. Existing user-claim / IP proxy tests continue to pass unchanged (GET → query string). Full suite green (2288).

NpgsqlRest v3.18.0

Choose a tag to compare

@github-actions github-actions released this 23 Jun 10:48

Version 3.18.0 (2026-06-23)

Full Changelog

The headline of this release is HTTP Custom Type response caching — outbound HTTP calls made by HTTP Custom Types can now be cached and reused, eliminating repeated calls to the same upstream within a configurable time window. The release also fixes a duplicate-outbound-call bug for HTTP types on database-function endpoints.

New Features

HTTP Custom Type response caching — @cache directive

An HTTP Custom Type can now opt into response caching with a @cache directive in its type comment, alongside the existing @timeout and @retry_delay directives. Directives appear before the request line:

comment on type books_api is '@cache 5m
GET https://books.toscrape.com/';

A cached type fires one outbound call for a given request shape; subsequent matching requests are served from the in-memory cache until the TTL elapses. For a type with no per-request placeholders (a constant URL/headers/body), that means a single shared upstream call per TTL window across the whole application — instead of one call per inbound request.

Behavior and safety rules:

  • Opt-in, GET-only. Caching is enabled per type by @cache. A @cache directive on any non-GET method is ignored with a startup warning — caching a mutating call is almost always a mistake.
  • TTL. @cache <interval> accepts the same formats as @timeout (5m, 30s, 1h, 00:05:00, or a bare number of seconds). A bare @cache (no interval) caches with no expiration (until the process restarts) and warns.
  • Success-only. Only successful (2xx) responses are cached, so a transient upstream failure is never pinned for the whole TTL — the next request re-fetches.
  • Stampede protection. A burst of concurrent requests for the same cache key coalesces into a single outbound call; the rest await the in-flight result (same Lazy<Task> coalescing model as the routine cache).
  • Cache key = HTTP method + resolved URL + resolved content-type + resolved headers + resolved body. Placeholders are resolved first, so per-request values vary the key naturally.

Configuration (HttpClientOptions):

  • CacheEnabled (default true) — global kill switch. When false, @cache directives are ignored and every request fires a fresh call.
  • MaxCacheEntries (default 10000) — bounds memory; once full, new responses are not cached (existing entries still serve and expire normally).
  • CachePruneIntervalSeconds (default 60) — how often expired entries are pruned.

Fixes

HTTP Custom Type request fired once per composite field on database-function endpoints

An endpoint backed by a database function/procedure whose parameter is an HTTP Custom Type fired one outbound HTTP call per field of the type on every inbound request (a 4-field type → 4 identical calls; a 6-field type → 6), multiplying latency and load on the target. SQL-file endpoints were not affected.

Cause. A composite function parameter is expanded into one parameter per field, each carrying the same TypeDescriptor.CustomType (the HTTP type name). The per-request list of HTTP types therefore held the same name N times, and the firing loop in HttpClientTypeHandler.InvokeAllAsync called InvokeAsync once per entry — while the fill loop immediately below resolves handlers by distinct type name. The design already assumes one call per distinct type; the firing loop just failed to match.

Fix. A guard in the firing loop requests each distinct HTTP type once, reusing the dictionary the fill loop already keys on. The established contract is preserved: one call per distinct HTTP type, shared from one response — two parameters referencing the same type still share a single call, and two different types remain two separate calls.

HTTP type directives after the headers were silently ignored

The @timeout, @retry_delay, and @cache directives are now parsed both before the request line and after the headers. Previously only the leading position (before the request line) was recognized, so a directive placed after the headers — as the documentation and examples showed — was silently dropped (e.g. a @timeout that never applied). Both placements are now equivalent. Real HTTP headers are unaffected: a header whose name merely starts with a directive keyword (e.g. Cache-Control) is still treated as a header.

Tests

  • Regression tests count actual outbound calls via WireMock response callbacks (the prior suite asserted content but never call counts): a 6-field type fires exactly one call (was 6), and two distinct types fire one call each.
  • Caching tests cover: cache hit reduces to one call, 6-field dedup + caching combined, error responses not cached, @cache ignored on POST, and TTL expiry. Parse-level tests cover the @cache directive forms and GET-only enforcement.