PostgreSQL Extended Query Protocol: Plan Reuse, Injection Prevention, and Pipelining
Patch the client to use extended protocol for plan reuse and injection safety.
Patch the client to use extended protocol for plan reuse and injection safety.
Summary
PostgreSQL’s extended query protocol splits a query into four messages—P (parse), B (bind), E (execute), and S (sync)—allowing the server to parse and analyze the SQL template once and reuse the plan for subsequent executions. The protocol introduces prepared statements, which cache the parse tree and analysis results, enabling plan reuse and reducing parsing overhead for repeated queries. Injection protection is achieved by separating the SQL template from the parameter values; values are sent in binary or text form and never parsed as SQL, preventing malicious input from being interpreted as code. The protocol also supports pipelining: multiple B/E pairs can be sent before a sync, allowing a batch of queries to be executed in a single round‑trip. PostgreSQL’s plan cache policy uses the first five executions to collect cost statistics, then compares custom and generic plans to decide which to cache, with the plan_cache_mode GUC controlling the behavior. Custom plans are recomputed on each execute, while generic plans are cached and reused, and the policy can be overridden with force_custom_plan or force_generic_plan. The extended protocol therefore improves performance, security, and network efficiency for high‑throughput applications.
Key changes
- Extended protocol splits a query into four messages: P, B, E, and S.
- Prepared statements cache the parse tree and analysis results for plan reuse.
- Injection protection is achieved by separating SQL template from parameter values.
- Pipelining allows multiple B/E pairs to be sent before a sync, batching queries.
- Plan cache policy uses the first five executions to collect cost statistics.
- Custom plans are recomputed each execute; generic plans are cached.
- The plan_cache_mode GUC can force custom or generic plans.
- Extended protocol improves performance, security, and network efficiency.