Skip to content

Quote names and option values in replication commands - #6707

Merged
Brar merged 5 commits into
npgsql:mainfrom
Brar:repl/quoting
Nov 1, 2026
Merged

Brar merged 5 commits into
npgsql:mainfrom
Brar:repl/quoting

Conversation

@Brar

@Brar Brar commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

Npgsql sent slot and output plugin names unquoted, and wrapped option values and publication names in quotes without escaping them:

  • A valid slot name that starts with a digit, e.g. 1abc, failed with 42601: syntax error in every replication command, because the replication command scanner lexes it as a number followed by an identifier.
  • A name like x TEMPORARY or x WAIT changed the command.
  • An option value or publication name containing a quote broke the command. PgOutputReplicationOptions already wrapped each publication name in double quotes, so uppercase names and names with commas always worked; only quotes broke them. A ' ended the option's literal, and a " ended the identifier inside the list, so that a name like a","b subscribed to the publications a and b.

It also sent a logical replication option whose value is null as a bare key, e.g. START_REPLICATION SLOT s LOGICAL 0/0 ("proto_version"). For pgoutput's proto_version and publication_names, that crashes the walsender: pgoutput reads both values with strVal() without checking for a missing one (pgoutput.c:325 and :351 on REL_18_STABLE; the same on 10 through master), and the postmaster then terminates every other session of the server and runs crash recovery. A role with REPLICATION is enough; it doesn't have to be a superuser. This is reported to PostgreSQL as BUG #19795 (https://www.postgresql.org/message-id/flat/19795-6d7d506133b7f062%40postgresql.org). A patch that reads both options with defGetString() has been posted there but isn't committed yet. Servers without that fix keep crashing, which is why Npgsql checks.

Now:

  • Slot and plugin names are sent as quoted identifiers, after removing surrounding whitespace and lowercasing A-Z, which is what the server did with the unquoted names, so existing names keep their meaning. Two kinds of names are sent as they are: names that callers already wrapped in double quotes (so far the only way to use a slot name starting with a digit), as long as any quotes inside them are doubled, and names with non-ASCII letters that the server reads as one identifier, which the server folds by its database encoding and locale.
  • Option names are quoted identifiers, and option values are literals in which quotes are doubled, the way PostgreSQL's own clients quote them since a75bd485b5e (back-patched, released in 14.24, 15.19, 16.15, 17.11 and 18.6). The replication command scanner supports neither E'' strings nor backslash escapes, so backslashes are sent as they are.
  • publication_names becomes a literal containing a list of quoted identifiers. An empty list, which PublicationNames can still become after construction, is rejected before anything is sent: pgoutput would take it as no publication at all.
  • Null option names are rejected with an ArgumentException instead of being sent as an empty quoted identifier. Physical CreateReplicationSlot and ReadReplicationSlot throw ArgumentNullException for a null slot name, which used to cause a server syntax error.
  • Starting pgoutput with proto_version or publication_names and a null value throws an ArgumentException ("The pgoutput option '…' requires a value.") before anything is sent, so the connection stays usable. Other options and other plugins are unchanged: pgoutput reads its other options with defGetBoolean() (no value means true) or defGetString(), which raises a clean error, and test_decoding checks for a missing value itself.
  • Everywhere Npgsql builds SQL from names or values, the same internal helpers quote them: besides replication commands, that's savepoint names, the named arguments of stored procedure calls, the schemas for type loading and the GIDs of two-phase commits. A literal for SQL that contains a backslash becomes an escape string (E'…') with the backslashes doubled, as libpq's PQescapeLiteral does, so that it reads the same whether standard_conforming_strings is on or off. With it off, a backslash in a schema name for type loading made the query fail or ended the literal early. Otherwise the SQL is the same as before.

Callers who escaped quotes in option values or publication names themselves to work around this must stop doing so; the 11.0 release notes say so.

How a real server gets there

All runs on PostgreSQL 18.6, main against this PR, unless noted:

  • Slot names starting with a digit: PostgreSQL allows digits anywhere in slot names, and its own clients quote slot names, so such slots can exist; generated names (hashes, timestamps) often start with a digit. On main, the physical and logical CREATE_REPLICATION_SLOT, START_REPLICATION, READ_REPLICATION_SLOT and DROP_REPLICATION_SLOT all failed with 42601. With this PR both slots were created, streamed from, read and dropped.
  • Names that add keywords: main created a temporary slot x when asked for a persistent slot named x TEMPORARY, and dropped the existing slot x when asked to drop x WAIT. Now these names fail with 42602 or 42704, and nothing changes on the server. This takes an invalid name from the caller (a typo, a configuration value), so it is a correctness fix, not a security one; PostgreSQL fixed the same class of problem in its own clients as an ordinary bug.
  • Option values with a quote: include-xids 'it's' failed with 42601 on main. This PR sends 'it''s', and test_decoding got the value intact.
  • Publication names with quotes: with seven publications, the name with " and ' failed with 42601 on main, and a","b delivered the rows of the publications a and b. With this PR both lists were right; the other names worked on both.
  • Double quotes in option names (Mixed"Case in the unit tests) are doubled for consistency only, since every identifier goes through the same helper and main already quoted option names. No plugin has such option names.
  • Options without a value: through the public low-level StartLogicalReplication(slot, cancellationToken, walLocation, options) in Npgsql.Replication.Internal, with a null value for one of the two options, e.g. from a generic options configuration. PgOutputReplicationOptions never produces this. Main sent START_REPLICATION SLOT crash_slot LOGICAL 0/0 ("proto_version"), and the server logged "client backend … was terminated by exception 0xC0000005" and "terminating any other active server processes", then ran crash recovery. The crash reproduced on 14.24, 15.19, 16.15, 17.11 and 18.6 with both options (Windows builds), with proto_version also as a non-superuser REPLICATION role. origin without a value, as a control, gives the clean "origin requires a parameter" error.
  • Type loading with standard_conforming_strings off (a server, database, role or Options setting; PostgreSQL 19 no longer allows it): with a schema name ending in a backslash (x\) or the name x\') OR true -- in SetTypeLoadingSchemas, main's type loading failed with 42601. The same literal in a plain query (nspname IN ('pg_catalog', 'x\'') OR true --')) matched every schema in psql. With this PR the type loading reads exactly the configured schema.

Tests

  • QuotingTests (25 cases): the exact text of names, option names, option values, SQL literals and publication lists.
  • Live: ReplicationSlotNameTests<Logical|Physical>.Slot_name_starting_with_a_digit creates, streams from, reads and drops a slot named 1… through the replication protocol, and LogicalReplicationOptionTests has Publication_names_with_special_characters, Null_option_names_are_rejected and Emptied_publication_names_are_rejected. They set up their own names, because SafeReplicationTestBase lowercases names and interpolates them unquoted.
  • Live: LogicalReplicationOptionTests.Pgoutput_options_without_required_value_are_rejected expects the ArgumentException for both options, with the plugin spelled pgoutput, pgoutput and "pgoutput" (each creates a pgoutput slot, and a custom slot class may keep the spelling), and then runs IDENTIFY_SYSTEM on the same connection. It names a slot that doesn't exist, so that without the check the server answers 42704 instead of crashing, and the test server survives either way.
  • Live: ConnectionTests.Set_Schemas_with_backslashes loads the types of a schema named test_schema_\ or test_schema_\') OR true -- with standard_conforming_strings off, and checks that only that schema's type is loaded.
  • On main, all these live tests fail: 42601 for the digit-leading slots, the publication names and the schemas with backslashes, no ArgumentException for the null option name, and 42704 instead of the ArgumentException for the options without a value and of the InvalidOperationException for the emptied publication list. All 38 tests pass against PostgreSQL 18.6, in Debug and Release.
  • The other places that now use the helpers send the same SQL as before; their tests pass, among them the savepoint tests (also with quoted names), the named arguments, type loading with schema names that contain quotes, and the two-phase commits of DistributedTransactionTests.

For the reviewer

  • No public API change. The helpers are in Statics, next to EscapeLiteral: QuoteIdentifier and QuoteLiteral(value, replicationParser), each with an Append… variant for StringBuilders that doesn't build the quoted string first (AppendQuotedIdentifier for the named arguments, AppendQuotedLiteral for the schema list of the type loading), QuoteName for slot and plugin names (folded and trimmed the way the server reads unquoted names) and QuoteIdentifierList for publication_names. replicationParser says which parser reads the literal: SQL can take an escape string, while the replication command parser has neither escape strings nor backslash escapes, so there only the quotes are doubled. NpgsqlCommandBuilder.QuoteIdentifier keeps its own code, since its quote characters can be changed.
  • The replication command scanner only understands doubled double quotes in identifiers since 14.24, 15.19, 16.15, 17.11 and 18.6. Valid slot and plugin names can't contain double quotes, so on older servers this only affects names that fail anyway. Publication names are inside a literal that pgoutput splits itself, so their doubled double quotes don't depend on that change (the live test also passes on 13.23, which doesn't have it).
  • START_REPLICATION doesn't name the plugin, so the check for options without a value goes by the plugin name of the slot object the caller passes, as the server reads it (whitespace trimmed, A-Z lowercased unless quoted), compared case-insensitively. The option names are compared case-sensitively, as pgoutput does (strcmp, pgoutput.c:313 and :339).

Dependencies and merge order

It depends on no other PR. The check for options without a value was #6708 until the review; it was a separate PR only while BUG #19795 wasn't public. #6710 adds a using at the same place in PgOutputReplicationOptions.cs; whichever of the two is merged second keeps both lines.

Fixes #6693

Npgsql sent slot and output plugin names unquoted, and wrapped option
values and publication names in quotes without escaping them:
- Valid slot names starting with a digit (e.g. "1abc") failed with a
  syntax error, because they lex as a number.
- A name like "x TEMPORARY" or "x WAIT" changed the command.
- Option values or publication names containing quotes caused syntax
  errors or subscribed to a different list of publications.

Slot and plugin names are now sent as quoted identifiers, after
removing surrounding whitespace and lowercasing A-Z, which is what the
server did with the unquoted names, so existing names keep their
meaning. Names that callers already wrapped in double quotes are passed
through unchanged. Option names are quoted identifiers and option values
quoted literals in which embedded quotes are doubled, the way
PostgreSQL's own clients do it since a75bd485b5e. publication_names
becomes a literal containing a list of quoted identifiers. Callers who
escaped quotes in option values or publication names themselves to work
around this must stop doing so.

Null option names are now rejected with an ArgumentException instead of
being sent as an empty quoted identifier. Physical CreateReplicationSlot
and ReadReplicationSlot throw ArgumentNullException for a null slot
name, which used to cause a server syntax error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@roji roji left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recommendation

The quoting change is justified and takes the right approach. I found no blocking correctness issue in this PR's implementation. Keep the scope here; address the separate guard issue in #6708 there.

Problem and expected approach

#6693 describes real API failures, not just hypothetical malformed input. A valid digit-leading slot cannot be created or used, and a publication name can be interpreted as a different publication list:

await rc.CreatePgOutputReplicationSlot("1abc"); // Previously: 42601
new PgOutputReplicationOptions("a\",\"b", PgOutputProtocolVersion.V1);
// Must select one publication named a","b, not publications a and b.

Independently of the diff, I would expect small shared quoting helpers, all physical/logical command sites wired into them, and separate identifier-list escaping for publications. The replication scanner is not the normal SQL scanner: doubling quotes, without E-strings or backslash escaping, is important here.

Alignment and scope

The helper and call-site changes match that expectation. Preserving ASCII case-folding avoids breaking existing names; the small prequoted-name compatibility branch preserves the existing digit-leading-slot workaround. Publication names correctly remain case-sensitive and receive both escaping layers. No public API expansion or broader validation framework is needed. The focused unit cases and live lifecycle/publication tests cover the central requirements.

Gap

The description says the 11.0 release notes explain that callers must stop manually escaping option values and publication names. That note is absent from the current source release notes, and there is no documentation change in this diff. Please add/link a short companion note; this behavior change is worth documenting, without expanding the conceptual docs.

Manual validation

I built the merge-base and the combined #6708 head, whose quoting implementation is unchanged from this commit, and exercised them from a separate console client against a dedicated PostgreSQL 18.4 cluster. The old code failed both digit-leading slot lifecycles with 42601; the new code created, streamed, read the physical slot, and dropped both slots. A quoted option value reached test_decoding intact, including its backslash. Publications containing both quote types and the name a","b selected exactly the intended tables, with separate a/b publications present as controls. Existing uppercase/whitespace and prequoted names still worked; an input ending in TEMPORARY was rejected instead of creating a different slot. The 21 targeted tests at the combined head also passed. This was manual API validation, not just static inspection or running the PR's tests.

Posted by copilot

@roji roji left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See comment and separate agentic review but otherwise LGTM.

Looks like a good candidate for backporting to 10.

Copilot AI balanced review requested due to automatic review settings November 1, 2026 10:57
@Brar

Brar commented Nov 1, 2026

Copy link
Copy Markdown
Member Author

The release note is in npgsql/doc#478, together with those of the other replication and COPY PRs; it's a draft until they are merged.

@Brar

Brar commented Nov 1, 2026

Copy link
Copy Markdown
Member Author

Yes, it's planned for the 10.0 hotfix branch once it's merged.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

A test fails on PostgreSQL 19, and plugin name handling can reject valid options or resolve quoted and non-ASCII names incorrectly.

4 open issues
What changed in this PR

This PR addresses #6693 by centralizing quoting for replication commands and generated SQL, preserving names and values containing special characters.

Changes:

  • Quotes replication slot and plugin names, option values, and publication lists.
  • Rejects null option names and missing values for pgoutput’s two required options.
  • Reuses quoting helpers across SQL generation and adds unit and live regression tests.
File Description
test/​Npgsql.Tests/​Replication/​ReplicationQuotingTests.cs Tests digit-leading slot names, publication quoting, and option validation.
test/​Npgsql.Tests/​QuotingTests.cs Tests identifier, literal, and publication-list formatting.
test/​Npgsql.Tests/​ConnectionTests.cs Tests type loading with backslashes and nonstandard string settings.
src/​Npgsql/​VolatileResourceManager.cs Quotes prepared-transaction identifiers as SQL literals.
src/​Npgsql/​Util/​Statics.cs Adds shared identifier and parser-specific literal quoting helpers.
src/​Npgsql/​Replication/​ReplicationConnection.cs Quotes slot names in read and drop commands.
src/​Npgsql/​Replication/​PhysicalReplicationConnection.cs Quotes physical slot names and adds null checks.
src/​Npgsql/​Replication/​PgOutput/​PgOutputReplicationOptions.cs Escapes identifiers in publication lists.
src/​Npgsql/​Replication/​Internal/​LogicalReplicationConnectionExtensions.cs Quotes logical replication arguments and validates options.
src/​Npgsql/​PostgresDatabaseInfo.cs Uses backslash-safe SQL literals for schema filtering.
src/​Npgsql/​NpgsqlTransaction.cs Reuses shared quoting for savepoint names.
src/​Npgsql/​NpgsqlCommand.cs Reuses shared quoting for named procedure arguments.

Review effort: Balanced

Comment thread src/Npgsql/Util/Statics.cs Resolved
Comment thread src/Npgsql/Util/Statics.cs Resolved
Comment thread test/Npgsql.Tests/ConnectionTests.cs Resolved
- Starting pgoutput with proto_version or publication_names but no value
  is now rejected with an ArgumentException: pgoutput dereferences the
  missing value, which crashes the walsender and makes the postmaster
  terminate all sessions. The check was a PR of its own until the review.
  It recognizes pgoutput by the plugin name as the server reads it
  (QuoteName), so it also covers slots created with a padded or quoted
  spelling of pgoutput, which a custom slot class may keep.
- The quoting helpers are generic and live in Statics, next to
  EscapeLiteral; ReplicationCommandBuilder is gone. QuoteIdentifier and
  QuoteLiteral (with AppendQuotedIdentifier and AppendQuotedLiteral for
  StringBuilders), QuoteName and QuoteIdentifierList are used by the
  replication commands and also by savepoints, the named arguments of
  stored procedure calls, the schema list of the type loading and the GIDs
  of two-phase commits. NpgsqlCommandBuilder.QuoteIdentifier keeps its own
  code, since its quote characters can be changed.
- QuoteLiteral takes the parser that reads the literal. For SQL, a value with
  backslashes becomes an escape string (E'...') with its backslashes doubled,
  as libpq's PQescapeLiteral does: with standard_conforming_strings off, a
  backslash in a schema name for the type loading made the query fail or
  ended the literal early, since EscapeLiteral only doubles the quotes. The
  replication command parser has neither escape strings nor backslash escapes,
  so replication commands still only double the quotes. Otherwise the SQL is
  the same as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 1, 2026 11:18

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread src/Npgsql/Util/Statics.cs Resolved
Comment thread src/Npgsql/Util/Statics.cs Resolved
Since the names are quoted, two kinds of names that worked before were
read differently:
- A name that the caller already quoted was only kept if it had no other
  quotes, so "a""b" (the plugin a"b) was quoted again. It's kept now if
  every quote inside it is doubled. Servers with the updated replication
  scanner read it as one identifier; older ones read several quoted
  identifiers, which can't be keywords, and fail with a syntax error, as
  before.
- A name with non-ASCII letters was quoted with only A-Z lowercased,
  while the server also lowercases non-ASCII letters in single-byte
  database encodings, depending on its locale. Such a name is now sent
  as it is if the server reads it as one identifier, which can't be a
  keyword, so the server folds it as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 1, 2026 12:20

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The pgoutput guard can be bypassed, allowing options that may crash the server, while vertical-tab trimming can silently target the wrong replication slot.

No open issues 🎉

2 previously missed issues

In code that hasn't changed since last review

High severity Do not trim vertical tabs from slot names

src/​Npgsql/​Util/​Statics.cs:149

PostgreSQL 14.24 does not treat \v as replication-command whitespace, so trimming it changes the target rather than preserving the old parse. For example, DropReplicationSlot("x\v") previously failed with a syntax error on that server but now drops slot x. Handle vertical tabs according to the server version, or reject them instead of silently removing them.

Medium severity Revalidate publication names before formatting

src/​Npgsql/​Replication/​PgOutput/​PgOutputReplicationOptions.cs:151

PublicationNames is publicly mutable, so callers can clear it after the constructor's nonempty check. The new formatter then sends an empty publication_names value, which pgoutput accepts without streaming table changes instead of reporting an invalid publication. Revalidate that the list is nonempty before formatting the option.

6 resolved since last review

Review effort: Balanced

PublicationNames is a mutable list, so it can be emptied after the
constructor checked it. Since the names are quoted as a list, an empty
one went out as an empty publication_names value, which pgoutput takes
as no publication: the stream started and delivered no changes. Before,
it went out as a single empty name, which pgoutput 17 and older reject at
the first change. StartReplication now throws InvalidOperationException
before anything is sent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 1, 2026 12:46

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues remain for the replication quoting and validation changes.

No open issues 🎉

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 1, 2026 12:53

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed to evaluate whether returned slot names consistently match the identifiers queried.

No open issues 🎉

Review effort: Balanced

@Brar Brar left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On Copilot's question whether the returned slot names match the ones queried:

  • The Create*ReplicationSlot methods take the name from the server's result row (ReplicationConnection.cs:349), so they return the slot's actual name, whatever the caller passed.
  • ReadReplicationSlot can't do that, because READ_REPLICATION_SLOT returns no name (walsender.c:492-497). It returns its argument lowercased (ReplicationConnection.cs:394-395), as it does on main. That differs from the slot's name only where the server reads the input differently: surrounding whitespace, and the quotes of a name the caller quoted. Passing the returned object back to Npgsql still reaches the same slot, since its name goes through QuoteName again.

This PR changes only what is sent, not what these methods return, so I've filed the ReadReplicationSlot mismatch as #6735 rather than fixing it here.

@Brar
Brar merged commit e87d421 into npgsql:main Nov 1, 2026
13 checks passed
@Brar
Brar deleted the repl/quoting branch November 1, 2026 13:21
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.

Replication commands don't quote slot names, output plugin names and option values

3 participants