Skip to content

chore: Review #526 and #539 - #674

Closed
krlmlr wants to merge 1 commit into
mainfrom
claude/review-526
Closed

krlmlr wants to merge 1 commit into
mainfrom
claude/review-526

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member

Review of #526 (Multiple queries must use the same column names. with pg_duckdb) and its proposed fix #539 ("Do not enforce types when preparing query"), as asked. This PR changes no code; it only records the findings and the open decisions. Nothing was posted on #526 or #539.

Summary

Cause

RPostgres prepares every non-immediate query, reads its result shape with PQdescribePrepared(), and fixes the column cache from that description (_cache::set() sets initialized_ = true). Every later result is compared against it. pg_duckdb describes queries over DuckDB table functions with placeholder columns and resolves the real ones only at execution: SELECT * FROM read_csv(...) describes as one column read_csv of type duckdb.row (hence the "column names" error), and SELECT r['id'] AS id ... as id of type duckdb.unresolved_type (hence a "column types" error). The comparison exists for multi-statement immediate queries, which a prepared statement can never be.

Reprex on main

library(DBI)
# pg_duckdb 1.0.0 in Docker: docker run -p 55432:5432 -e POSTGRES_PASSWORD=duck pgduckdb/pgduckdb:17-v1.0.0
# with a CSV created in the container: printf "id,name\n1,a\n2,b\n" > /tmp/x.csv
con <- dbConnect(
  RPostgres::Postgres(),
  host = "localhost", port = 55432, user = "postgres", password = "duck"
)
packageVersion("RPostgres")
#> [1] '1.4.10.9021'

# Query from the issue.
# Expected: a data frame with 7100 rows and 10 columns.
res <- try(dbGetQuery(con, "SELECT * FROM read_parquet('s3://us-prd-motherduck-open-datasets/netflix/netflix_daily_top_10.parquet')"))
#> Error : Multiple queries must use the same column names.
if (is.data.frame(res)) dim(res)

# Same without network access. The server describes the prepared query
# as one column `read_csv` of type duckdb.row (psql: \gdesc).
# Expected: a data frame with columns `id` and `name`, two rows.
try(dbGetQuery(con, "SELECT * FROM read_csv('/tmp/x.csv')"))
#> Error : Multiple queries must use the same column names.

# Selected column: described as `id` of type duckdb.unresolved_type.
# Expected: a data frame with one column `id`, two rows.
try(dbGetQuery(con, "SELECT r['id'] AS id FROM read_csv('/tmp/x.csv') r"))
#> Error : Multiple queries must use the same column types.

# Parametrized, bound to two parameter rows.
# Expected: two rows, one per parameter value.
try(dbGetQuery(con, "SELECT r['id'] AS id, r['name'] AS name FROM read_csv('/tmp/x.csv') r WHERE r['id'] = $1::int", params = list(1:2)))
#> Error : Multiple queries must use the same column types.

# Workaround: immediate = TRUE skips the prepare step.
# Expected: columns `id` and `name`, two rows.
dbGetQuery(con, "SELECT * FROM read_csv('/tmp/x.csv')", immediate = TRUE)
#>   id name
#> 1  1    a
#> 2  2    b

dbDisconnect(con)

CRAN 1.4.10 gives the same output, except for the version and one extra "Closing open result set" warning.

Same reprex with #539 merged onto main

# Query from the issue.
# Expected: a data frame with 7100 rows and 10 columns.
res <- try(dbGetQuery(con, "SELECT * FROM read_parquet('s3://us-prd-motherduck-open-datasets/netflix/netflix_daily_top_10.parquet')"))
if (is.data.frame(res)) dim(res)
#> [1] 7100   10

# Same without network access. The server describes the prepared query
# as one column `read_csv` of type duckdb.row (psql: \gdesc).
# Expected: a data frame with columns `id` and `name`, two rows.
try(dbGetQuery(con, "SELECT * FROM read_csv('/tmp/x.csv')"))
#>   id name
#> 1  1    a
#> 2  2    b

# Selected column: described as `id` of type duckdb.unresolved_type.
# Expected: a data frame with one column `id`, two rows.
try(dbGetQuery(con, "SELECT r['id'] AS id FROM read_csv('/tmp/x.csv') r"))
#>   id
#> 1  1
#> 2  2

# Parametrized, bound to two parameter rows.
# Expected: two rows, one per parameter value.
try(dbGetQuery(con, "SELECT r['id'] AS id, r['name'] AS name FROM read_csv('/tmp/x.csv') r WHERE r['id'] = $1::int", params = list(1:2)))
#>   id name
#> 1  1    a
#> 2  2    b

# Workaround: immediate = TRUE skips the prepare step.
# Expected: columns `id` and `name`, two rows.
dbGetQuery(con, "SELECT * FROM read_csv('/tmp/x.csv')", immediate = TRUE)
#>   id name
#> 1  1    a
#> 2  2    b

dbDisconnect(con)

Edge cases with #539 (zero rows, a first parameter row without matches, rebinding):

library(DBI)
con <- dbConnect(
  RPostgres::Postgres(),
  host = "localhost", port = 55432, user = "postgres", password = "duck"
)
packageVersion("RPostgres")
#> [1] '1.4.10.9021'
sql <- "SELECT r['id'] AS id, r['name'] AS name FROM read_csv('/tmp/x.csv') r WHERE r['id'] = $1::int"

# Zero rows: the cache is never refreshed from an execution.
# Expected: zero rows, columns `id` and `name` (types may be unknown).
str(dbGetQuery(con, "SELECT * FROM read_csv('/tmp/x.csv') LIMIT 0"))
#> 'data.frame':    0 obs. of  1 variable:
#>  $ read_csv: 'pq_row' chr

# First parameter row matches nothing, second one does.
# Expected: one row, id 2.
dbGetQuery(con, sql, params = list(c(99L, 2L)))
#>   id name
#> 1  2    b

# Rebinding the same result.
# Expected: id 1, then id 2.
rs <- dbSendQuery(con, sql)
dbColumnInfo(rs)[, 1:3]
#>   name      type  .oid
#> 1   id character 16432
#> 2 name character 16432
dbBind(rs, list(1L))
dbFetch(rs)
#>   id name
#> 1  1    a
dbBind(rs, list(2L))
dbFetch(rs)
#>   id name
#> 1  2    b
dbClearResult(rs)

dbDisconnect(con)

On main, the last two cases fail with "Multiple queries must use the same column types."

Evaluation of #539

  • Change: _cache::set() gets an enforce_result flag; the prepare step passes false, so the description fills the cache without fixing it, and the first execution result passes true, so the server's real shape becomes the reference for all later parameter rows and rebinds. 5 lines in two files; it applies to main cleanly (its head 10dcae2 already contains main).
  • Result-type caching: the type check is not dropped, only its reference moves from the description to the first execution. For plain PostgreSQL both are identical, so the behavior there does not change. The cache is filled once more per result (two small vectors), which is negligible.
  • Prepared statement reuse and dbBind() with changing types: RPostgres uses the unnamed statement only; parameter types come from the prepare step and are not touched by feat: Do not enforce types when preparing query for compatibility with pg_duckdb #539. Rebinding a result and binding several parameter rows still compare later results against the first one (see edge cases above).
  • Redshift: same code path; Redshift describes prepared statements like PostgreSQL, so nothing changes there. Not tested against a Redshift cluster.
  • Before the first execution (dbColumnInfo() on an unbound parametrized result), the placeholder description still shows. That is what the server reports and cannot be improved without executing.
  • Zero-row results keep the placeholder shape, with and without feat: Do not enforce types when preparing query for compatibility with pg_duckdb #539: a result set without rows arrives as PGRES_TUPLES_OK and returns before the cache is refreshed, so SELECT * FROM read_csv(...) LIMIT 0 gives one read_csv column instead of id and name. Refreshing the cache from that result too fixes this (tried in a scratch build: zero rows then give id and name, full suite still green), but for immediate multi-statement queries it adds a new error when an earlier statement returns no rows:
library(DBI)
con <- dbConnect(RPostgres::Postgres(), host = "localhost", user = "runner", password = "test123", dbname = "testdb")
# Immediate multi-statement query whose first statement returns no rows.
try(dbGetQuery(con, "SELECT 1 AS a WHERE false; SELECT 'x' AS b", immediate = TRUE))
#> Error : Multiple queries must use the same column names.
try(dbGetQuery(con, "SELECT 1 AS a WHERE false; SELECT 2 AS a", immediate = TRUE))
#>   a
#> 1 2
try(dbGetQuery(con, "SELECT 1 AS a; SELECT 2 AS a", immediate = TRUE))
#>   a
#> 1 1
#> 2 2
dbDisconnect(con)

On main and with #539, the first of these returns column b. Restricting the refresh to prepared queries avoids that. This is a separate, smaller issue and not needed for #526.

library(DBI)
con <- dbConnect(RPostgres::Postgres(), host = "localhost", user = "runner", password = "test123", dbname = "testdb")
con2 <- dbConnect(RPostgres::Postgres(), host = "localhost", user = "runner", password = "test123", dbname = "testdb")
dbExecute(con, "DROP TABLE IF EXISTS t526")
#> NOTICE:  table "t526" does not exist, skipping
#> [1] 0
dbExecute(con, "CREATE TABLE t526 (a int)")
#> [1] 0
dbExecute(con, "INSERT INTO t526 VALUES (1)")
#> [1] 1
# Can plain PostgreSQL change a prepared query's result shape between
# prepare and execute? Prepare, change the table from another connection, bind.
rs <- dbSendQuery(con, "SELECT * FROM t526 WHERE a = $1")
dbExecute(con2, "ALTER TABLE t526 ALTER COLUMN a TYPE bigint")
#> [1] 0
# Expected: the server refuses, so RPostgres never sees a different shape.
try(dbBind(rs, list(1L)))
#> Error in dbBind(rs, list(1L)) : 
#>   Failed to fetch row : cached plan must not change result type
#> ℹ SQLSTATE: 0A000
dbClearResult(rs)
dbExecute(con, "DROP TABLE t526")
#> [1] 0
dbDisconnect(con); dbDisconnect(con2)

So a test needs pg_duckdb (or another extension that resolves result types at execution). CI uses ankane/setup-postgres without extensions.

Recommendation

Merge #539's approach with a regression test that skips unless the server has pg_duckdb, run by one Linux CI job against the pgduckdb/pgduckdb image, plus a NEWS bullet. Treat zero-row results as a follow-up. The decisions are in the question comments below.

Related: #526, #539.


Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Resolved: How should #539 land?

#539 fixes #526 with a 5-line change that is inert for plain PostgreSQL (full suite unchanged on main), see the evaluation in the PR body. It still lacks the test you asked for on 2026-02-05 and a NEWS bullet; the contributor has not answered the test question, but merged main into the branch today. You have the say as maintainer. If nobody decides, #539 stays open and #526 stays broken; users can only work around it with immediate = TRUE.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Question: What test covers #526?

Plain PostgreSQL cannot make a prepared query's execution differ from its description: the server refuses with "cached plan must not change result type", so the "pedestrian" test asked about on #539 does not exist (reprex in the PR body). A test needs pg_duckdb, for example SELECT r['id'] AS id FROM read_csv(...) r and SELECT * FROM read_csv(...) on a local CSV, which fail on main and pass with #539 (no network needed). CI currently uses ankane/setup-postgres without extensions. A Linux job with a pgduckdb/pgduckdb:17-v1.0.0 service container costs nothing in this public repository beyond a few minutes per run. If nobody decides, the fix lands untested or not at all.

  • A testthat test that skips unless the server has the pg_duckdb extension, plus one Linux CI job running the suite against the pgduckdb/pgduckdb image (recommended)
  • The same skipping test, without a CI job (runs only where a developer has pg_duckdb, so effectively never in CI)
  • No test; rely on the reprex in this PR

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Resolved: Also fix zero-row results from pg_duckdb?

With and without #539, a pg_duckdb query that returns no rows keeps the placeholder shape from the prepare step: SELECT * FROM read_csv(...) LIMIT 0 gives one read_csv column instead of id and name, because a result without rows returns before the cache is refreshed. Refreshing the cache from that result too fixed it in a scratch build with the full suite green, but for immediate multi-statement queries it turns SELECT 1 AS a WHERE false; SELECT 'x' AS b from returning column b into an error, so it would have to be limited to prepared queries (a few more lines). It is not needed for #526. If nobody decides, empty pg_duckdb results keep the wrong columns, which nobody has reported.

Kirill decided: separate PR, stacked on top of #539 (#674 (comment): "Stacked PR on top for the zero-rows fix. No testing needed. I'll merge myself.").


Generated by Claude Code

@krlmlr

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Stacked PR on top for the zero-rows fix. No testing needed. I'll merge myself.

@krlmlr

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Prepare the PR now, open after I merge.

@krlmlr

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

PR merged.

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Opened the zero-row fix as #676 on top of the merged #539 (6 lines in src/PqResultImpl.cpp, clean review done, accepted limitations posted there).


Generated by Claude Code

@krlmlr krlmlr closed this Nov 29, 2026
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.

2 participants