Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
150 commits
Select commit Hold shift + click to select a range
ee6c20f
fix(core): refuse AuthenticationOk before the SCRAM exchange completes
sehrope Oct 23, 2026
d2780f2
test(core): pin the refusal of an early AuthenticationOk during SCRAM
sehrope Oct 23, 2026
5b6e5eb
fix(compat): carry the property bag into the pooling data source
sehrope Oct 23, 2026
8aa7256
test(compat): pin that every compat data source honors sslmode
sehrope Oct 23, 2026
37a0432
fix(core): refuse a startup that skips authentication
sehrope Oct 23, 2026
195d782
test(core): pin the refusal of a startup that skips authentication
sehrope Oct 23, 2026
96c334b
fix(core): mark the connection broken on an unmappable client_encoding
sehrope Oct 23, 2026
0358665
test(core): pin that an unmappable client_encoding breaks the connection
sehrope Oct 23, 2026
b99512c
fix(core): bound the nesting depth of text-format arrays
sehrope Oct 23, 2026
877ef6c
test(core): pin the text array nesting bound
sehrope Oct 23, 2026
b2e9929
fix(jdbc): stop serverName and databaseName injecting URL parameters
sehrope Oct 23, 2026
9ebeaf5
test(jdbc): pin that data source fields cannot inject URL parameters
sehrope Oct 23, 2026
fda2241
fix(jdbc): redact the URL PgSimpleDataSource quotes in its rejection
sehrope Oct 23, 2026
6b99781
test(jdbc): pin the redaction of a rejected data source URL
sehrope Oct 23, 2026
99336f8
fix(compat): stop server names and bag keys injecting URL parameters
sehrope Oct 23, 2026
5f8f287
test(compat): pin that server names and bag keys cannot inject URL pa…
sehrope Oct 23, 2026
9f2f416
fix(compat): split URL userinfo off in BaseDataSource.setUrl
sehrope Oct 23, 2026
ddcf3f0
test(compat): pin URL userinfo handling in BaseDataSource.setUrl
sehrope Oct 23, 2026
3e521e6
fix(core): quote the composite type name lookup as an E'' literal
sehrope Oct 23, 2026
9ae7243
test(core): pin the escaping of the composite type name lookup
sehrope Oct 23, 2026
bdc80a0
fix(compat): double backslashes in escapeLiteral when strings are not…
sehrope Oct 23, 2026
0daf9bd
test(compat): pin escapeLiteral under standard_conforming_strings=off
sehrope Oct 23, 2026
fb434e4
fix(core): report a malformed SCRAM server message as an auth failure
sehrope Oct 23, 2026
5b39e96
test(core): pin the exception type for a malformed SCRAM server-first
sehrope Oct 23, 2026
20a32de
fix(core): read TLS material and pgpass only from bounded regular files
sehrope Oct 23, 2026
b35031e
test(core): pin the refusal of special files as TLS material or pgpass
sehrope Oct 23, 2026
271f748
docs(core): state that socketFactory trusts the classpath
sehrope Oct 23, 2026
0396aea
fix(core): refuse a second AuthenticationSASL during one login
sehrope Oct 23, 2026
83979cb
test(core): pin the refusal of a restarted SASL exchange
sehrope Oct 23, 2026
ef852f5
fix(core): read the DataRows of a zero-column result
sehrope Oct 23, 2026
0418781
test(core): pin reading the rows of a zero-column result
sehrope Oct 23, 2026
8854394
fix(core): keep the row phase of a zero-column prepared statement
sehrope Oct 23, 2026
7d8a907
test(core): pin zero-column rows on the named prepared path
sehrope Oct 23, 2026
1e41ec8
fix(core): surface malformed server values as PgException
sehrope Oct 23, 2026
64b57f7
test(core): pin PgException for malformed server values and catalog rows
sehrope Oct 23, 2026
b3bacd5
fix(core): redact URL passwords that contain '/', '@', '?' or spaces
sehrope Oct 23, 2026
c9cefba
test(core): pin redaction of passwords with awkward characters
sehrope Oct 23, 2026
4fbe275
fix(core): bound the depth of catalog-driven type resolution
sehrope Oct 23, 2026
d365c89
test(core): pin the type resolution depth bound
sehrope Oct 23, 2026
030e80e
fix(core): check the width of a binary bool before reading it
sehrope Oct 23, 2026
1c4f344
test(core): pin the binary bool width check
sehrope Oct 23, 2026
cece889
fix(jdbc): accept custom batch rewriter classes only from Properties
sehrope Oct 23, 2026
7cfa860
test(jdbc): pin where a custom batch rewriter class may be named
sehrope Oct 23, 2026
0640789
fix(compat): translate pgjdbc spellings for the pooling and XA sources
sehrope Oct 23, 2026
03ebf39
test(compat): pin requireAuth enforcement through every compat data s…
sehrope Oct 23, 2026
8e00d00
fix(compat): load ObjectFactory classes without initializing them
sehrope Oct 23, 2026
ca0a6ce
test(compat): pin that a wrong-typed ObjectFactory class is not initi…
sehrope Oct 23, 2026
497cc3c
fix(compat): read a repeated URL key the same way everywhere
sehrope Oct 23, 2026
35c4789
test(compat): pin repeated URL keys resolving alike in both paths
sehrope Oct 23, 2026
39bb3ba
fix(core): close the connection when standard_conforming_strings turn…
sehrope Oct 23, 2026
02801a1
test(core): pin that turning standard_conforming_strings off closes t…
sehrope Oct 23, 2026
24dc34a
fix(compat): send currentSchema as its own search_path parameter
sehrope Oct 23, 2026
d39b094
test(compat): pin currentSchema translating to search_path
sehrope Oct 23, 2026
4913b01
fix(core): refuse an lo_read reply longer than requested
sehrope Oct 23, 2026
1c4bfce
test(core): pin the lo_read reply length check
sehrope Oct 23, 2026
69ea029
docs(plans): record currentSchema as a search_path mapping
sehrope Oct 23, 2026
864bf65
fix(compat): encode spaces in data source URLs as %20, not '+'
sehrope Oct 23, 2026
e7bb012
test(compat): pin spaces in data source URL values
sehrope Oct 23, 2026
1353e73
docs(adr): limit custom batch rewriter class names to Properties
sehrope Oct 23, 2026
6c37c11
fix(compat): load the JNDI Reference's class without initializing it
sehrope Oct 23, 2026
acd6ab4
test(compat): pin that PGObjectFactory does not initialize a foreign …
sehrope Oct 23, 2026
9425acc
fix(core): reject malformed %-escapes and keep non-ASCII in URL decoding
sehrope Oct 23, 2026
5b396a5
test(core): pin URL percent-decoding of malformed escapes and non-ASCII
sehrope Oct 23, 2026
2425ff0
fix(compat): decode URL escapes with the shared core decoder
sehrope Oct 23, 2026
4ba09fe
test(compat): pin URL percent-decoding in connect and parseURL
sehrope Oct 23, 2026
3c32298
fix(core): require the postgresql ALPN protocol on direct TLS
sehrope Oct 23, 2026
7e9a6b6
test(core): pin the ALPN check on direct TLS
sehrope Oct 23, 2026
8a66893
fix(core): refuse a protocol negotiation that does not go down
sehrope Oct 23, 2026
f0f6f83
test(core): pin the refusal of an upward protocol negotiation
sehrope Oct 23, 2026
335dc0f
fix(core): escape server text before it is logged
sehrope Oct 23, 2026
2500c60
test(core): pin the escaping of server text for logs
sehrope Oct 23, 2026
01456be
fix(core): keep the last value of a repeated connection-string key
sehrope Oct 23, 2026
9d5b43d
test(core): pin last-wins for repeated connection-string keys
sehrope Oct 23, 2026
2c421f6
fix(jdbc): match JDBC-only URL keys after percent-decoding them
sehrope Oct 23, 2026
2a4d799
test(jdbc): pin percent-encoded JDBC-only keys being recognized
sehrope Oct 23, 2026
c2c0325
fix(compat): pass the whole host list to the pooling and XA sources
sehrope Oct 23, 2026
d0e8484
test(compat): pin multi-host failover through the pooling and XA sources
sehrope Oct 23, 2026
3db56f4
fix(compat): give pooled and XA handles what Driver.connect gives
sehrope Oct 23, 2026
6f5d305
test(compat): pin the finishing of pooled and XA logical handles
sehrope Oct 23, 2026
bfde3ff
fix(core): answer a stray CopyInResponse with CopyFail
sehrope Oct 23, 2026
797fd81
test(core): pin CopyFail for a stray CopyInResponse
sehrope Oct 23, 2026
0c63a70
fix(jdbc): scope Statement.setQueryTimeout to the statement's execute
sehrope Oct 23, 2026
23c9231
test(jdbc): pin the clearing of a statement's query timeout
sehrope Oct 23, 2026
3dd16f0
fix(jdbc): keep literal arguments in a {call ...} escape
sehrope Oct 23, 2026
0daaf1c
test(jdbc): pin literal and expression arguments in call escapes
sehrope Oct 23, 2026
ec05b94
fix(jdbc): step over all of PostgreSQL's quoting in {fn ...} arguments
sehrope Oct 23, 2026
2c30119
test(jdbc): pin {fn} argument splitting and the x$e'' lexing case
sehrope Oct 23, 2026
4b4cd0d
fix(compat): key the base column name cache by the whole column pair
sehrope Oct 23, 2026
8a18140
test(compat): pin distinct base column names for formerly colliding p…
sehrope Oct 23, 2026
af4d441
fix(jdbc): handle null and malformed catalog values in DatabaseMetaData
sehrope Oct 23, 2026
4399ce0
test(jdbc): pin DatabaseMetaData handling of null and large catalog v…
sehrope Oct 23, 2026
a60a8a1
fix(compat): report malformed hstore and interval text as bad input
sehrope Oct 23, 2026
a24212d
test(compat): pin errors for malformed hstore and interval text
sehrope Oct 23, 2026
dc6b297
fix(compat): stop sharing the copy-in transfer buffer across calls
sehrope Oct 23, 2026
59f7b1a
test(compat): pin a fresh copy-in buffer per call
sehrope Oct 23, 2026
52b25df
fix(compat): decode BaseDataSource URLs with the drivers' own decoder
sehrope Oct 23, 2026
881eeda
test(compat): pin '+' handling in BaseDataSource.setUrl
sehrope Oct 23, 2026
d5e7cca
fix(core): send only parseable names to the composite type lookup
sehrope Oct 23, 2026
1d5ea70
test(core): pin that unparseable composite names are never looked up
sehrope Oct 23, 2026
ac0da7d
fix(core): refuse an embedded NUL in startup values at config build
sehrope Oct 23, 2026
7614d44
test(core): pin the refusal of embedded NUL in startup values
sehrope Oct 23, 2026
5934175
fix(core): take the channel-binding hash of a PSS certificate from it…
sehrope Oct 23, 2026
02c1607
test(core): pin the channel-binding hash for PSS certificates
sehrope Oct 23, 2026
6cebef7
fix(compat): classify logServerErrorDetail as emulated
sehrope Oct 23, 2026
37618c0
test(compat): pin logServerErrorDetail as an emulated property
sehrope Oct 23, 2026
80d1cb6
docs: mark the logServerErrorDetail classification follow-up resolved
sehrope Oct 23, 2026
10dfbe0
fix(compat): warn when the duplicate-pgjdbc check cannot run
sehrope Oct 23, 2026
017c971
test(compat): pin the unreadable-classpath case of the duplicate check
sehrope Oct 23, 2026
62394bf
fix(core): read NegotiateProtocolVersion's version as a whole code
sehrope Oct 23, 2026
5971ab6
test(core): send whole version codes from the mock NegotiateProtocolV…
sehrope Oct 23, 2026
8b28f70
fix(core): qualify operators and functions in internal catalog queries
sehrope Nov 29, 2026
12d5c18
test(core): pin catalog queries against search_path shadowing
sehrope Nov 29, 2026
33cce6e
fix(jdbc): qualify operators and functions in catalog queries
sehrope Nov 29, 2026
b7c54fd
test(jdbc): pin metadata queries against search_path shadowing
sehrope Nov 29, 2026
df7a4ff
fix(compat): qualify operators in catalog queries
sehrope Nov 29, 2026
b74e1ab
test(compat): pin catalog lookups against search_path shadowing
sehrope Nov 29, 2026
eabc691
fix(core): refuse an ssl value that is neither true nor false
sehrope Nov 29, 2026
1514732
test(core): cover unrecognised and false ssl values
sehrope Nov 29, 2026
e4a75b4
fix(core): refuse a BigDecimal outside numeric's range
sehrope Nov 29, 2026
8918fe6
test(core): cover BigDecimal values outside numeric's range
sehrope Nov 29, 2026
0900bd6
fix(core): refuse client encodings that embed ASCII in multibyte char…
sehrope Nov 29, 2026
281cd4d
test(core): cover refusing ASCII-unsafe client encodings
sehrope Nov 29, 2026
7aa3667
fix(jdbc): keep the newline after a comment in an escape argument
sehrope Nov 29, 2026
db75c0a
test(jdbc): cover a comment in an escape argument
sehrope Nov 29, 2026
9ffa4b8
fix(compat): resolve hstore to the extension's type
sehrope Nov 29, 2026
24ed75f
test(compat): pin the hstore OID against a same-named domain
sehrope Nov 29, 2026
e650d1a
fix(compat): refuse service instead of ignoring it
sehrope Nov 29, 2026
b28df76
test(compat): cover refusing service
sehrope Nov 29, 2026
e6857bc
fix(core): mark the connection broken on a malformed message
sehrope Nov 29, 2026
5db39ec
test(core): pin that a malformed message breaks the connection
sehrope Nov 29, 2026
ffffa92
fix(jdbc): treat a failed batch inside BEGIN as rolled back under aut…
sehrope Nov 29, 2026
5a6a630
test(jdbc): cover a failed batch inside BEGIN under autocommit
sehrope Nov 29, 2026
f892a46
fix(jdbc): lex string continuations, $ in identifiers and surrogates …
sehrope Nov 29, 2026
7c72031
test(jdbc): cover continuations, $ in identifiers and surrogates in t…
sehrope Nov 29, 2026
6bf1eea
fix(jdbc): count $ and non-ASCII characters as identifier characters …
sehrope Nov 29, 2026
b512bf6
test(jdbc): cover keyword search past identifiers ending in the keyword
sehrope Nov 29, 2026
caa2488
fix(protocol): cap frame buffer growth below the JVM array limit
sehrope Nov 29, 2026
99dff3e
test(protocol): cover frame buffer growth near the array limit
sehrope Nov 29, 2026
cb930de
fix(core): bound the number of messages read during startup
sehrope Nov 29, 2026
2141f81
test(core): cover a server that never finishes startup
sehrope Nov 29, 2026
b7d1501
fix(core): cap messages at 30000 bytes before authentication
sehrope Nov 29, 2026
01072a6
test(core): cover the message length limit before authentication
sehrope Nov 29, 2026
801d1b5
fix(jdbc): do not record a stack trace for each server warning
sehrope Nov 29, 2026
2ad0dc1
test(jdbc): pin that server warnings carry no stack trace
sehrope Nov 29, 2026
f558009
fix(core): let the server reject statements in an aborted transaction
sehrope Nov 29, 2026
576e814
docs: rename requireUsableTransaction in life-of-a-query
sehrope Nov 29, 2026
29bb1ae
test(jdbc): cover ending a failed BEGIN block under autocommit
sehrope Nov 29, 2026
534c157
test(core): load the encrypted client key from an openssl-made fixture
sehrope Nov 29, 2026
9018c39
test(core): report full JFR detail when the pinning IT fails
sehrope Nov 29, 2026
6a9b735
test(core): warm up the JDK socket poller before the pinning IT records
sehrope Nov 29, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,14 @@ jobs:
cache: maven
- name: Integration tests (Testcontainers)
run: ./mvnw -B -ntp verify -Pintegration-tests -Dpg.it.image=postgres:${{ matrix.pg }}
# VirtualThreadPinningIT keeps its JFR recording under target/jfr only when it fails.
- name: Upload pinning JFR recording
if: failure()
uses: actions/upload-artifact@v4
with:
name: pinning-jfr-postgres-${{ matrix.pg }}
path: postgresql-client/target/jfr/*.jfr
if-no-files-found: ignore

# One integration leg on the current LTS. The server matrix above sweeps PostgreSQL
# versions on the JDK floor; this sweeps the other axis once, so JDK-dependent
Expand All @@ -150,6 +158,13 @@ jobs:
cache: maven
- name: Integration tests (Testcontainers)
run: ./mvnw -B -ntp verify -Pintegration-tests -Dpg.it.image=postgres:17
- name: Upload pinning JFR recording
if: failure()
uses: actions/upload-artifact@v4
with:
name: pinning-jfr-jdk25
path: postgresql-client/target/jfr/*.jfr
if-no-files-found: ignore

# Protocol 3.2 (PG18) is a distinct negotiation path -- StartupMessage requests 3.2,
# the server may answer NegotiateProtocolVersion, and the cancellation key becomes
Expand All @@ -172,3 +187,10 @@ jobs:
./mvnw -B -ntp verify -Pintegration-tests
-Dpg.it.image=postgres:18
-Dpg.it.protocolVersion=latest
- name: Upload pinning JFR recording
if: failure()
uses: actions/upload-artifact@v4
with:
name: pinning-jfr-protocol-3-2
path: postgresql-client/target/jfr/*.jfr
if-no-files-found: ignore
4 changes: 3 additions & 1 deletion docs/adr/ADR-0014-batch-array-rewrite.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,9 @@ lookup), unless rewriters pin element types via casts.
- unset / `off` / `false` / `no` / `0` -- disabled (**default**);
- `on` / `yes` / `true` / `1` / `latest` / `default` -- the latest built-in rewriter;
- any other token -- a pinned built-in version/id, or a fully-qualified class name of
a custom `BatchArrayRewriter`.
a custom `BatchArrayRewriter`. A class name is accepted only from the connection
`Properties`; one in the URL query fails the connection, as for
`authenticationPluginClassName` (N2.9), because a class name is code to run.

The default binding for "on" pins to a **fixed** built-in version, not "whatever is
latest at runtime": a driver upgrade must never silently start rewriting a statement
Expand Down
2 changes: 2 additions & 0 deletions docs/adr/ADR-0016-batch-multi-values-rewrite.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ compat layer's `reWriteBatchedInserts` translation onto it.
rewriter, pinned to a **fixed** version so a driver upgrade never silently changes
which statements are rewritten;
- any other token -- a pinned built-in version/id, or a fully-qualified custom class name.
As for `rewriteBatchUsingArrays`, a class name is accepted only from the connection
`Properties`, never from the URL query.

Like `rewriteBatchUsingArrays`, it is a JDBC-only knob: `PgDriver` reads and strips it
before building the core config, so the core parser never sees it as a bogus server
Expand Down
4 changes: 3 additions & 1 deletion docs/follow-up.md
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,9 @@ surfaced two mapping-table inconsistencies in
- **`logServerErrorDetail` is implemented but classified `unsupported`.** The
behavior ships (`ServerErrorRedaction`, wired via `Driver.vendorSettings()`
and consulted in `CompatStatements`), yet the mapping entry still emits a
misleading "not supported" WARN on every use. Reclassify it as mapped.
misleading "not supported" WARN on every use. **RESOLVED (2026-10-23):**
reclassified as emulated (6cebef72) -- not mapped, since forwarding it would
send it to the server as a startup parameter.
- **`sslcrl` is warn-dropped though core accepts it.** Core's
`ConnectionStringParser` and `SslMaterials` handle a CRL file, but
`PgPropertyMappings` has no entry, so the property falls into the
Expand Down
3 changes: 2 additions & 1 deletion docs/life-of-a-query.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,8 @@ never buffers. The buffering is a JDBC-layer policy applied on top of it.
`CoreConnection.execute(String)` is the native entry point:

```java
requireOpen(); requireIdle(); requireUsableTransaction(); // connection-busy contract (ADR-0005)
requireOpen(); requireIdle(); // connection-busy contract (ADR-0005)
recoverAutosave(); // autosave=always: undo a failed statement
invalidateCachesForSessionCommand(sql); // SET search_path / DISCARD / DEALLOCATE ALL
ensureTransactionOpen(); // lazy BEGIN when autocommit is off
return sendArmed(disarm -> { // arms the query timeout, un-busies on a failed send
Expand Down
14 changes: 8 additions & 6 deletions docs/plans/pgjdbc-wrapper.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,10 @@ Three sinks for a translated property, in order of preference:
`PgConnectionConfig.Builder` programmatically. **Decision:** add the missing
parser keys to core (one commit, W-A0) so both drivers gain them and the shim
stays string-based.
3. **Shim-side emulation** (`currentSchema` -> `options=-c search_path=...`,
`readOnly` -> post-connect `SET`/`Connection.setReadOnly`, `tcpKeepAlive` ->
core socket option): handled in the compat layer or a small core knob.
3. **Shim-side emulation** (`readOnly` -> post-connect `SET`/`Connection.setReadOnly`,
`tcpKeepAlive` -> core socket option): handled in the compat layer or a small
core knob. `currentSchema` started here too, folded into `options`; it is now a
plain mapping to a `search_path` startup parameter (see 3.3).

### 3.3 Unknown / unsupported property policy (replaces silent drop)

Expand Down Expand Up @@ -187,9 +188,10 @@ The 80% of real-world configs. Land these first after A0/A1.
- [x] `sslnegotiation` -> `sslnegotiation` (MAP): `postgres|direct`, identical.
- [x] `sslrootcert`/`sslcert`/`sslkey`/`sslpassword`/`sslcrl` already (MAP); add
`sslmode` aliasing of pgjdbc-only nuance where `ssl=true` implies verify-full. *(2026-07-28: partial -- sslcrl absent from PgPropertyMappings, warn-dropped though core accepts it)*
- [x] `currentSchema` -> EMULATE: fold into `options=-c search_path=<v>` (merge
with any existing options) (SHIM). Consider a first-class `search_path` core
knob later.
- [x] `currentSchema` -> MAP to a `search_path` startup parameter, as pgjdbc sends
it. It was first folded into `options=-c search_path=<v>`, which the server
splits on whitespace, so the value could carry further `-c` settings and
`app, public` was rejected.
- [x] `readOnly` + `readOnlyMode` -> EMULATE: set JDBC read-only / issue
`SET default_transaction_read_only`; map `readOnlyMode=always|ignore|transaction`
semantics (SHIM/CORE). *(2026-07-28: partial -- readOnlyMode unsupported, no always/ignore/transaction semantics)*
Expand Down
8 changes: 6 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -394,9 +394,13 @@
<!-- Resolve jdk.jfr and let the patched test module read it for the
non-pinning IT (N1.7); failsafe patches test classes into
org.postgresql.client.core, which does not `requires jdk.jfr`.
@{argLine} preserves the JaCoCo integration agent's argLine. -->
@{argLine} preserves the JaCoCo integration agent's argLine.
The JFR stack depth (default 64) is a JVM-startup option the
Recording API cannot set; 128 frames keeps the pinning IT's
failure report from cutting off above the driver frames. -->
<argLine>@{argLine} --add-modules jdk.jfr
--add-reads org.postgresql.client.core=jdk.jfr</argLine>
--add-reads org.postgresql.client.core=jdk.jfr
-XX:FlightRecorderOptions=stackdepth=128</argLine>
</configuration>
<executions>
<execution>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package org.postgresql.client.jdbc;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.postgresql.client.jdbc.sql.SqlLexing;

/**
* Rebuilds the argument list of a {@code {call f(...)}} escape for the native call, keeping every
* argument as written. A bare {@code ?} is a parameter, which may be OUT-only; any other argument
* is an expression (a literal such as the {@code 1} in {@code f(?, 1)}, or {@code ? + 1}) whose
* {@code ?} placeholders are IN parameters. Placeholders are numbered left to right as JDBC
* numbers them, and renumbered {@code $1..$n} over the values actually sent.
*/
final class CallArguments {

private CallArguments() {}

/**
* The native argument list (without parentheses), appending the value for each {@code $n} to
* {@code values}. An unbound OUT-only parameter is dropped under {@code SELECT}, which does not
* take OUT arguments, and sent as NULL under {@code CALL}, which needs one per parameter.
*/
static String rebuild(
String argumentText,
boolean callMode,
Set<Integer> outParameters,
boolean[] bound,
Object[] parameters,
List<Object> values)
throws SQLException {
List<String> out = new ArrayList<>();
int placeholder = 0;
for (String argument : split(argumentText)) {
String trimmed = strip(argument);
if (trimmed.equals("?")) {
placeholder++;
if (!bound[placeholder - 1] && outParameters.contains(placeholder)) {
if (!callMode) {
continue;
}
values.add(null);
} else {
values.add(requireBound(placeholder, bound, parameters));
}
out.add("$" + values.size());
continue;
}
StringBuilder expression = new StringBuilder();
int end = trimmed.length();
int i = 0;
while (i < end) {
char c = trimmed.charAt(i);
int next = SqlLexing.skipLexeme(trimmed, i, end);
if (next > i) {
expression.append(trimmed, i, next);
i = next;
} else if (c == '?' && i + 1 < end && trimmed.charAt(i + 1) == '?') {
expression.append('?'); // ?? is an escaped literal question mark, as in SqlParser
i += 2;
} else if (c == '?') {
placeholder++;
values.add(requireBound(placeholder, bound, parameters));
expression.append('$').append(values.size());
i++;
} else {
expression.append(c);
i++;
}
}
out.add(expression.toString());
}
return String.join(", ", out);
}

/**
* The argument without surrounding whitespace, except that one ending in a {@code --} comment
* keeps a newline: the arguments are rejoined on one line, where the comment would otherwise run
* on over whatever follows.
*/
static String strip(String argument) {
String stripped = argument.strip();
int end = stripped.length();
int i = 0;
while (i < end) {
int next = SqlLexing.skipLexeme(stripped, i, end);
if (next == end && stripped.startsWith("--", i)) {
return stripped + "\n";
}
i = next > i ? next : i + 1;
}
return stripped;
}

private static Object requireBound(int placeholder, boolean[] bound, Object[] parameters) throws SQLException {
if (placeholder > bound.length || !bound[placeholder - 1]) {
throw new SQLException("parameter " + placeholder + " is not set");
}
return parameters[placeholder - 1];
}

/** Splits the argument list at commas outside quotes, comments, parentheses and brackets. */
static List<String> split(String text) {
List<String> arguments = new ArrayList<>();
if (text.isBlank()) {
return arguments;
}
int depth = 0;
int start = 0;
int end = text.length();
int i = 0;
while (i < end) {
int next = SqlLexing.skipLexeme(text, i, end);
if (next > i) {
i = next;
continue;
}
char c = text.charAt(i);
if (c == '(' || c == '[') {
depth++;
} else if (c == ')' || c == ']') {
depth--;
} else if (c == ',' && depth == 0) {
arguments.add(text.substring(start, i));
start = i + 1;
}
i++;
}
arguments.add(text.substring(start));
return arguments;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ static SourceColumn sourceColumn(Connection connection, int tableOid, int attrib
+ " OR COALESCE(pg_catalog.pg_get_expr(d.adbin, d.adrelid), '') LIKE 'nextval(%'"
+ " FROM pg_catalog.pg_attribute a"
+ " LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum"
+ " WHERE a.attrelid = ? AND a.attnum = ?";
+ " WHERE a.attrelid OPERATOR(pg_catalog.=) ? AND a.attnum = ?";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setInt(1, tableOid);
ps.setInt(2, attributeNumber);
Expand Down Expand Up @@ -72,7 +72,7 @@ record CatalogType(String name, char typtype, boolean isArray, int elementOid, c
static CatalogType catalogType(Connection connection, int typeOid) throws SQLException {
String sql = "SELECT t.typname, t.typtype, t.typcategory, t.typelem,"
+ " COALESCE(e.typdelim, ',') FROM pg_catalog.pg_type t"
+ " LEFT JOIN pg_catalog.pg_type e ON e.oid = t.typelem WHERE t.oid = ?";
+ " LEFT JOIN pg_catalog.pg_type e ON e.oid = t.typelem WHERE t.oid OPERATOR(pg_catalog.=) ?";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setInt(1, typeOid);
try (ResultSet rs = ps.executeQuery()) {
Expand All @@ -98,7 +98,7 @@ static CatalogType catalogType(Connection connection, int typeOid) throws SQLExc
*/
static String[] tableName(Connection connection, int tableOid) throws SQLException {
String sql = "SELECT n.nspname, c.relname FROM pg_catalog.pg_class c"
+ " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.oid = ?";
+ " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.oid OPERATOR(pg_catalog.=) ?";
try (PreparedStatement ps = connection.prepareStatement(sql)) {
ps.setInt(1, tableOid);
try (ResultSet rs = ps.executeQuery()) {
Expand Down
Loading
Loading