CREATE VIEW accepts a bind variable, and every query on the view inherits it
Summary
CREATE VIEW v AS (SELECT x FROM t WHERE x = $1) succeeds. The view stores its text with $1
in it. Every later statement that reads the view compiles that text with the reader's own bind
variables. So $1 in the view is silently the reader's first parameter.
PostgreSQL rejects the same DDL with there is no parameter $1.
Reproduction (PostgreSQL wire protocol)
Q "CREATE TABLE t AS (SELECT x FROM long_sequence(3))"
Q "CREATE VIEW v2 AS (SELECT x FROM t WHERE x = $1)" -> C[OK]
P '' "SELECT x FROM v2" (no parameter types)
B '' '' (no values)
E '' 0
S -> E[bind message supplies 0 parameters, but prepared statement requires 1]
P '' "SELECT x FROM v2"
B '' '' '2'
E '' 0
S -> D(2) C[SELECT 1]CREATE VIEW v AS (SELECT x, $1 AS y FROM t) also succeeds, and SELECT x, y FROM v then needs one
value.
Impact
- A reader's statement text has no
$n, but the statement still needs a value, and the ParameterDescription reports a parameter the client never wrote. - A reader whose statement has its own
$1binds the same value into the view's filter. For example,SELECT x FROM v2 WHERE x > $1uses one value for both conditions. The query then returns rows that differ from the rows the author meant. - Any client can create such a view. The problem shows up only when someone reads the view.
Expected
CREATE VIEW (and ALTER VIEW / CREATE MATERIALIZED VIEW, if they have the same gap)
rejects a definition that contains an indexed ($n) or named (:name) bind variable. The error
position points at the bind variable.
Notes
This is not new in the PG wire Deallocate PR (#7680). That PR's Bind parameter-count check makes
it visible. At the PR base, copyParameterValuesToBindVariableService() defined $1 and left it
NULL when the Bind sent no value, so SELECT x FROM v2 should return no rows and no error (read
from the base code, not run).
Location
core/src/main/java/io/questdb/griffin/SqlCompilerImpl.java:5031executeCreateView(); the view definition is built incore/src/main/java/io/questdb/griffin/engine/ops/CreateViewOperationBuilderImpl.java. Neither the PR base (e756069d95) nor the PR head has a check that rejects bind variables in a view definition.
Suggested fix
Reject indexed ($n) and named (:name) bind variables while compiling a CREATE VIEW (and ALTER VIEW)
definition, with the error position at the first bind variable, as PostgreSQL does.
Found while reviewing PR #7680 (branch vi_pgwire_deallocate).
Source: questdb/questdb