current_setting Reads Session GUCs

Read and write session parameters with current_setting and set_config: missing_ok returns NULL for unknown keys, and is_local scopes writes to one transaction.

SqlConfig Management

Code

snippet
-- current_setting 读当前值;未知设置默认报错,missing_ok=true 返回 NULL
SELECT current_setting('datestyle') AS datestyle,
       current_setting('no.such.key', true) AS unknown_is_null;

-- 两段名(含点号)的自定义参数是合法占位符:不需要扩展,应用可当会话便签用
SELECT set_config('app.tenant', 'acme_corp', false) AS written;
SELECT current_setting('app.tenant') AS tenant;

-- set_config 第三参数 is_local:true 等价 SET LOCAL,事务结束即失效
BEGIN;
SELECT set_config('app.mode', 'maintenance', true) AS local_write;
SELECT current_setting('app.mode') AS inside_txn;
COMMIT;
-- 提交后 app.mode 不再可见(is_local=false 才会留存到会话结束)
SELECT current_setting('app.mode', true) AS after_commit;

-- NULL 作为新值表示"重置为默认",因为设置本身不允许 NULL
SELECT set_config('app.mode', NULL, false) AS reset_to_default;

How it works

The file mixes SELECT statements with a short transaction. Nothing is read from or written to a table; the subject is the session’s own parameter store.

Two-段 names such as app.tenant are legal placeholders without any extension installed, which is why the file can use them as a per-session scratch note.

Scope of a write

set_config(name, value, is_local) takes the scope as its third argument. With is_local = true the value lives exactly as long as the enclosing transaction: BEGIN opens it, COMMIT closes it, and the follow-up read falls back to the default.

Key statements

SELECT current_setting('no.such.key', true) AS unknown_is_null;
SELECT set_config('app.mode', 'maintenance', true) AS local_write;

Interactive Tools for This Topic