Skip to content

Check output parameters against the procedure's metadata before the run - #298

Merged
electricessence merged 6 commits into
masterfrom
feat/output-metadata-checks
Dec 2, 2026
Merged

electricessence merged 6 commits into
masterfrom
feat/output-metadata-checks

Conversation

@electricessence

@electricessence electricessence commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

A call that reads output parameters now checks them against what the database says about the procedure, before the command runs. Two mistakes that used to reach the provider are caught with a message that says what is wrong and what to do:

  • An output on an input parameter. A member (of a model, a named output or a capture) matched to a parameter whose mode is IN. The provider's own error (SQL Server 8162) came after the command was sent; now an InvalidOperationException names the member, the parameter and the procedure, and says to declare the parameter OUTPUT or drop the member.
  • A decimal output declared with a scale lower than the procedure's. The value would be rounded silently. Now an InvalidOperationException names the member, the parameter and both scales. A higher scale passes and the precision is not checked. This covers every way a scale is declared: [Column(TypeName = "decimal(p,s)")] and the precision and scale passed to a named or captured decimal form.

When metadata is not available

It is optional: a lookup never fails a call. If the provider has no ProcedureParameters collection, the connection is not a DbConnection, the answer is empty or ambiguous (no schema given and the procedure exists in several), nothing is checked and the provider's own error applies, as before. A read that fails for another reason (a refusal inside a transaction, for example) runs the call and is asked again on the next call; only a cancellation is thrown.

How it works

  • The metadata is read lazily, once per procedure name set, only for a call that has an output member (a text command, a call with no outputs and a return-code-only call never look), and kept on the name set that already holds the procedure's parameter names. They go away with it: the existing 1,024-per-source clear, and a failed check forgets the entry (the next call reads again, so the next call after an ALTER PROCEDURE reads it again). No timer.
  • The read happens where the names are resolved: a call that reads an output parameter resolves its names with ResolveDerivedNamesAndMetadataAsync (the names, then the metadata of a procedure), any other call with ResolveDerivedNamesAsync (the names only). ExecutePlainAsync gains no await and no field, and calls without outputs pay nothing.
  • Only the exact mode IN counts (INOUT and OUT do not); the scale is read as an integer, and a missing or NULL value means unknown. Rows are matched to parameters by name the way the name set finds them.

Cost

A call that reads an output parameter pays, on every call: one loop over its output members (CheckMetadata), one NameSet.Find per member and one Volatile.Read of the metadata. The first call per procedure also pays one GetSchema (a failed read, for example inside a transaction on a provider that refuses it, is asked again on each call). A call without output parameters, a call that reads only the return code, and a text command pay nothing.

Probes (SQL Server LocalDB, Microsoft.Data.SqlClient)

  • GetSchema("ProcedureParameters") inside a pending transaction works (System.Data.SqlClient refuses it, which is the "refused read" case above).
  • NUMERIC_SCALE: int/bigint 0; float, real, the date and time types and nvarchar NULL; money and smallmoney 4 (a decimal(19,2) over a money output therefore throws); decimal(12,4) 4.
  • PARAMETER_MODE: an input is IN; an OUTPUT and an input-output parameter are both INOUT; a procedure has no return-value row.

Tests

  • Against SQL Server LocalDB (14): an IN parameter read by a model member, a named output and a capture, with no command run (a scratch table stays empty); an input-output member on an IN parameter; scale lower, equal and higher, by attribute, named, decimal and captured forms; int, money and float; the call after an ALTER PROCEDURE in both directions; a SQL Server package command; a pending SqlTransaction; unknown metadata still gives the provider's 8162 after one lookup; a refused read lets the call run and is asked again.
  • Against fakes (30): one lookup for many calls, also on a pool-backed command; no lookup for the cases above; no collection, an argument error, any other failure, cancellation; two schemas; and the row reading rules (exact IN, scale parsing, name matching, missing columns, first answer wins, concurrent asks).
  • Two existing tests changed: the output on an IN parameter now throws before the run, and passes after ALTER; the decimal test declares the scale the procedure has. With the check switched off, 19 of the new and changed tests fail.

Left for a later change

Definitions: outputs and captures on definitions (DbNonQuery.Procedure(...).Output<T>(), captures on a bound definition call) arrive with the definitions change. The lookup is on the shared name set, so they get the checks with no further work.

Checks: Release 15,990 and Debug 15,969 tests pass (16 skipped), 0 build warnings, 255 sample checks, VS MSBuild 0 errors, dotnet format style and analyzers at info clean on all 28 checks, DocFX 0 warnings, the style scan clean.

🤖 Generated with Claude Code

electricessence and others added 2 commits December 2, 2026 09:49
A call that reads output parameters now asks the database, once per procedure,
whether each parameter is an input only and what its numeric scale is (the
ADO.NET ProcedureParameters schema collection), and keeps the answer on the
remembered name set. Two checks run in the build step, before the command
executes:

- a member (model member, named output, capture) on a parameter the procedure
  declares as input only throws InvalidOperationException, naming the member,
  the parameter, the procedure and the fix;
- a decimal member whose declared scale (the [Column(TypeName)] attribute, or the
  precision and scale passed to a named or captured decimal form) is lower than
  the parameter's throws, because the value would be rounded. A higher scale
  passes, and no precision is checked.

The metadata only checks: it never supplies a value, a type or a scale. It is
optional and never fails a call: a provider without the collection, a
connection that is not a DbConnection, a name that cannot be looked up and a
table with nothing usable are kept as not known; any other failure of the read
(for example a refusal inside a pending transaction) lets the call run, keeps
nothing and is asked again on the next call; only a cancellation is thrown.
Without metadata the provider's own error applies, as before. Calls without
output parameters, calls that read only the return code, text commands and
procedures whose names are not known never trigger the read. A failed check
forgets the entry, so a changed procedure heals on the next call; an ALTER
under a running process can cause one spurious failure, which the docs say.

Existing tests that declared a lower scale, or an output on an input-only
parameter, are converted to the new behaviour.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… doc sentence

- Add a test for the call that takes its connection from a pool: the input-only
  check throws before the run, the metadata is read once, and a failed check
  forgets the entry. It fails when that call site does not ask for the metadata.
- Group the argument and parameter lists logically, wrap the added lines that
  were over 80 columns, and make the members of the internal types public.
- Reword the documentation of a refused metadata read: System.Data.SqlClient
  refuses the schema collection inside a pending transaction, while
  Microsoft.Data.SqlClient answers it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
electricessence and others added 4 commits December 2, 2026 11:41
The parameter metadata a call with output parameters checks (input-only mode
and numeric scale) is now called metadata everywhere: ProcedureParameterMetadata
(was ProcedureSchemaFacts), ParameterMetadata, NameSet.Metadata and
NameSet.KeepMetadata, in code, comments, tests, release notes and documentation.
The check against that metadata is unchanged.

The flag that switched ResolveDerivedNamesAsync between reading the names only
and also reading the metadata is gone. There are two named paths instead:
ResolveDerivedNamesAsync reads the names, and
ResolveDerivedNamesAndMetadataAsync reads the names and then the metadata of a
procedure. A call chooses its path by reading an output parameter (ReadsOutputs);
the run still has one await at that point and gains no field.

Two test names that used an informal verb now say what they check.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…a-checks

# Conflicts:
#	docsite/articles/expressive-commands.md
- Say what the database reports in the words SQL Server and ADO.NET use: a
  parameter whose mode is IN (an input parameter), instead of an invented
  phrase. The member is IsModeIn; the exception message, the documentation and
  the tests follow.
- Split the schema table read into two named methods, one for a procedure name
  that included its schema and one for a name without it (which refuses a table
  that spans schemas), sharing one private method for the rows. No bool
  parameter selects the behavior.
- Correct the documentation of an ALTER under a running process: a scale
  lowered by the change is not caught and rounds silently, as without metadata,
  until the remembered metadata is dropped by an unrelated failure or eviction.
- Layout: the expression bodies of the small members, a using declaration for
  the schema table, grouped arguments.
- Cut repeated text: one statement of the provider error in the article, one
  comment per fact in the run, the constant summary and the repeated class
  remark. The scale message states the scale to declare in the procedure.
- Name the helper that returns a set whose metadata was read
  NamesWithMetadataAsync, and one test after what it proves.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@electricessence
electricessence merged commit 1a9d59a into master Dec 2, 2026
9 checks passed
electricessence added a commit that referenced this pull request Dec 2, 2026
…300)

Stored definitions can declare and read output parameters, captures work on the calls of a stored definition, and a capture takes its parameter's name from its variable.

Builds on #297.

## Outputs on a definition

A `DbNonQuery` definition declares what it reads back, once, where it is stored:

```csharp
static readonly OutputDbNonQuery<AddPostResult> AddPost
	= DbNonQuery.Procedure("[dbo].[AddPost]")
		.Output<AddPostResult>();

var result = await AddPost.Using(Blog)
	.AddParam(post)
	.ExecuteOutputAsync(cancellationToken);
```

- `Output<TOut>()` reads a model. `Output<T>(name)` and `Output<T>(name, precision, scale)` read one value, and `OutputDecimal(name, precision, scale)` reads a nullable decimal. All four also work on the typed-parameters form, `DbNonQuery.Procedure(...).Params<TParams>()`.
- The outputs are checked when the definition is declared. Every message names the definition and the model, and gives the fix.
- A bound write has `ExecuteReturnAsync<T>()` for the return code. It is refused at the call on a text definition, because a text definition has no return code.
- A definition matches and adds its outputs through the same code as the commands, so the rules are the same. Named outputs match the way `AddParam` names do: exact, ignoring case, ignoring case and underscores, then without a common prefix.
- A definition's call that reads output parameters is checked against the procedure's parameter metadata before the run, as a command's call is (#298). It reads the metadata itself, so the check does not depend on a command having called the procedure first.
- A definition's outputs are part of its equality, compared by value: two definitions of one procedure that read different outputs are different, and so are their calls.

## Captures on a definition's calls

A capture is per call, after `Using` and the parameters, and never on the stored definition:

```csharp
var rows = await PagePosts.Using(Blog)
	.AddParam(page)
	.CaptureOutput(out DbCapture<int> total)
	.ToListAsync(cancellationToken);
var count = await total;
```

- **Where captures work:** on a query made from a `DbQuery` definition (every terminal, stream, buffer, Channel and Dataflow form), and on bound write and scalar calls. A call made from `Output` has no capture members, so a capture there is a compile error.
- **Order:** a capture before or after `AddParam` gives the same call.
- **Single use:** a kept or branched call that carries a capture runs once; a second run throws.
- **Captures on the return code:**
  - `CaptureReturn` on a text definition is refused at the call.
  - `ExecuteReturnAsync` refuses a capture that also reads the return code, and runs beside a capture that reads only outputs.
- **Runner:** a definition's call fills its captures through its own runner. The runner claims the captures when the terminal is called, copies the outputs before the command is disposed, and completes every capture on every exit.
- **Cost of a call without captures:** a bound call carries one more reference, which is `null` without a capture. It is copied on each `AddParam`, and each terminal tests it once. Equality includes it by reference, and a call without one hashes as before.

## The capture name comes from the variable

`CaptureOutput(out DbCapture<int> total)` reads `@total`. The name can also be passed last: `CaptureOutput(out DbCapture<int> x, "total")`.

- The compiler supplies the variable's text. The last identifier is taken from it: a declaration, a local, `this.total`, `state.total`, `arr[0].Total`. A typed name follows the same rule: `$` and `#` are allowed, and one leading `@` or `:` is dropped.
- A discard, an element access, an empty name, or a missing compiler text is refused with the fix.
- The name is matched the way `AddParam` names are, over the name as written and without an `m_` or `s_` field prefix. A text that is not one plain name is worked out once and cached weakly.
- A model capture ignores the name. If a model member matches nothing, the message says the name was not used and gives both fixes.
- `CaptureOutput(out DbCapture<decimal> x, precision, scale, name)` replaces the generic shape overload, so a wrong type with a shape does not compile. `CaptureOutputDecimal` keeps the nullable form.
- The name-first capture forms added earlier in this release cycle are removed. They were never in a published release.

## Docs and samples

- The output samples lead with the definition form: a `static readonly` field, then the per-call chain. The ad hoc command form follows.
- New samples cover:
  - typed parameters with outputs;
  - a definition's return code;
  - a model capture;
  - write and scalar captures;
  - a pooled stream;
  - the ways a capture takes its name.
- The samples run against procedures in tempdb when LocalDB is available, and the sample checks verify what they return.
- The expressive commands article, the release notes and the what's new page describe both features.

## Tests

- **Definitions:** declaration checks and messages; the same results as a command for the same procedure; typed parameters; the return code; the metadata checks on a definition and on a capture on its call.
- **Captures through a definition:** every terminal, stream and buffer; Channel and Dataflow; a synchronous terminal (refused); `CancelOnEarlyStop()`; single use; before or after `AddParam`.
- **Capture names:** the name rules on a fake provider and on SQL Server. An output named after an input parameter is now refused before the run, from the procedure's metadata.
- **Compile tests:** in-memory, on every C# language version the repo tests. They prove that a capture on an `Output` call does not compile, that a wrong type with a decimal shape does not compile, and that `out var` with a shape infers `DbCapture<decimal>`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant