实现说明
实际执行的是 SELECT / CREATE——pg_tables、pg_prepared_statements、pg_listening_channels 是涉及的对象。
scratch_ids 是由本文件里的语句当场建出来的会话级临时表——只活在当前会话,会话结束就自动清掉。
真正干活的子句:WHERE 只放行满足条件的行进入这条语句;用 COUNT 做聚合。
常见问题
它引用了哪些表或 CTE?
引用的是 pg_tables、pg_prepared_statements、pg_listening_channels。
核心语句
CREATE TEMP TABLE scratch_ids (id integer);
PREPARE ping_stmt AS SELECT 1 AS ok;
LISTEN cache_invalidation;
代码示例
-- Create dirty session-scoped state typical of pooled application requests
CREATE TEMP TABLE scratch_ids (id integer);
PREPARE ping_stmt AS SELECT 1 AS ok;
SET app.tenant = 'acme';
LISTEN cache_invalidation;
SELECT
(SELECT count(*) FROM pg_tables WHERE schemaname LIKE 'pg_temp%' AND tablename = 'scratch_ids') AS temp_tables,
(SELECT count(*) FROM pg_prepared_statements WHERE name = 'ping_stmt') AS prepared_stmts,
current_setting('app.tenant', true) AS active_tenant,
(SELECT count(*) FROM pg_listening_channels() AS c(ch) WHERE ch = 'cache_invalidation') AS listeners;
-- DISCARD ALL resets temp tables, prepared statements, GUCs, and LISTEN channels (cannot run inside BEGIN..COMMIT)
DISCARD ALL;
SELECT
(SELECT count(*) FROM pg_tables WHERE schemaname LIKE 'pg_temp%' AND tablename = 'scratch_ids') AS temp_tables,
(SELECT count(*) FROM pg_prepared_statements WHERE name = 'ping_stmt') AS prepared_stmts,
current_setting('app.tenant', true) AS active_tenant,
(SELECT count(*) FROM pg_listening_channels() AS c(ch) WHERE ch = 'cache_invalidation') AS listeners;