perf(psql): use EXISTS for view checks - #735
Conversation
|
Will this work with a complex query that contains a CTE? |
|
For SELECT-based CTEs, yes. SELECT EXISTS ((
WITH matching AS (...)
SELECT ...
FROM matching
WHERE ...
))
I do not want to overstate the coverage, though: PostgreSQL requires data-modifying CTEs ( |
The prior assertion only checked that "WITH" appeared somewhere in the rendered query, which would also pass if the clause were hoisted ahead of EXISTS. Assert instead that WITH is rendered inside the EXISTS subquery, matching the SELECT-CTE guarantee the EXISTS optimization relies on. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
|
Withdrawn in This follow-up was based on an incorrect rationale. The ordering assertion encoded the current SQL shape as a requirement, even though relative I reverted the assertion; the original PostgreSQL-backed test remains unchanged. A correction is posted below for visibility. |
Revert bb8a396, which treated nested WITH placement as a semantic requirement. The PostgreSQL-backed test already verifies SELECT-based CTE behavior. Hoisting can be valid for SELECT CTEs and is required for data-modifying CTEs, which PostgreSQL permits only at the top level; an ordering assertion would encode an implementation detail and block a correct future implementation.
|
Correction: I reverted The follow-up ordering assertion was too strict, and its rationale about data-modifying CTEs was incorrect. For the SELECT-based CTE covered by this PR, nesting the complete query inside The revert restores the original test and makes no production-code change. Sorry for the confusion. |
Summary
ViewQuery.Existscurrently delegates toCount, so PostgreSQL computes acount(1)aggregate even though callers only need to know whether one matching row exists.This change:
EXISTSexpression and scans the single boolean result;EXISTSis emitted instead ofcount(1).Fixes #731.
Validation
Passed locally on Windows with Go 1.25.0, PostgreSQL via testcontainers, and CGO enabled with GCC 16.1.0:
go test -race -run '^TestSomeViewExistsUsesExistsExpression$' ./dialect/psqlgo test -race ./dialect/psqlgo build ./...go vet ./...golangci-lint run --new-from-rev=HEAD(0 issues)git diff --checkA full
go test ./...run passed every package except the unrelated existingTestLibSQLDocker Desktop path, where the Windows host connection to the libsql container was reset during schema migration. The CGO-dependent SQLitemattngenerator tests passed when run separately.Coordination
Open PR #657 also touches
dialect/psql/view.goas part of a much larger immutable-query refactor, but it does not implement #731 and is currently conflicted withmain. If that refactor lands first, this focused change will need a small rebase onto its newViewQueryrepresentation.