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.

SqlSecurity Boundaries

Code

snippet
-- 服务端拼动态语句(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

FAQ

What relations does the SQL touch?
The references are `n`.