Execute Format Safe Dynamic Sql
Build dynamic statements server-side with EXECUTE format: %I quotes identifiers and %L escapes literals, so stray apostrophes cannot break or inject the SQL.
Code
-- 服务端拼动态语句(plpgsql EXECUTE)时,标识符与字面量必须分开引用:
-- %I = quote_ident:给标识符加引号、双写内部双引号
-- %L = quote_literal:给字面量加引号、转义内部单引号
CREATE TABLE "user's orders" (id int, status text);
INSERT INTO "user's orders" VALUES (1, 'it''s active'), (2, 'it''s active');
DO $$
DECLARE
target_table text := 'user''s orders';
status text := 'it''s active';
n bigint;
BEGIN
EXECUTE format('SELECT count(*) FROM %I WHERE status = %L',
target_table, status)
INTO n;
RAISE NOTICE 'matching rows: %', n;
END $$;
-- 对照:裸拼接在 ' 处把字符串提前终结 → 语法错误,也是注入入口
-- EXECUTE 'SELECT count(*) FROM ' || target_table
-- || ' WHERE status = ''' || status || '''';How the snippet works
At its core this is a single CREATE statement against n.
Applying it
The n table is the working surface here.
Statements that matter
DO $$
DECLARE
target_table text := 'user''s orders';
status text := 'it''s active';
n bigint;
BEGIN
EXECUTE format('SELECT count(*) FROM %I WHERE status = %L',
target_table, status)
INTO n;
RAISE NOTICE 'matching rows: %', n;
END $$;
INSERT INTO "user's orders" VALUES (1, 'it''s active'), (2, 'it''s active');
CREATE TABLE "user's orders" (id int, status text);
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.
FAQ
- What relations does the SQL touch?
- The references are `n`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.