amcheck Verifies Btree Index Consistency
bt_index_check verifies btree page invariants under an AccessShareLock without blocking writes; bt_index_parent_check digs deeper but takes a ShareLock.
Code
-- amcheck 扩展校验 btree 结构:页内元组必须保持逻辑顺序(按索引 collation)
CREATE EXTENSION IF NOT EXISTS amcheck;
CREATE TABLE readings (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
taken_at timestamptz NOT NULL,
value numeric NOT NULL
);
CREATE INDEX idx_readings_taken_at ON readings (taken_at);
INSERT INTO readings (taken_at, value)
SELECT now() - (g || ' minutes')::interval, g FROM generate_series(1, 500) AS g;
-- bt_index_check:只取 AccessShareLock(与普通 SELECT 同级),不阻塞并发写入;
-- 校验页内不变量,但不检查跨父/子关系的不变量
SELECT bt_index_check(index => 'idx_readings_taken_at');
-- bt_index_parent_check:更彻底(还会查缺失下链等父/子关系),
-- 但需要 ShareLock,会阻塞 INSERT/UPDATE/DELETE 与 VACUUM
SELECT bt_index_parent_check(index => 'idx_readings_taken_at');
-- 结构正常时两者都安静返回;发现损坏则直接抛错误(官方承诺无假阳性)
-- 批量巡检:跳过未就绪/失效索引,否则函数可能报错
SELECT bt_index_check(index => c.oid), c.relname, c.relpages
FROM pg_index i
JOIN pg_class c ON i.indexrelid = c.oid
WHERE c.relkind = 'i' AND i.indisready AND i.indisvalid
ORDER BY c.relpages DESC
LIMIT 10;Inside the snippet
What runs here is SELECT / INSERT / CREATE — readings, generate_series, pg_index and pg_class are the objects involved.
Breaking the statements into their working parts: one JOIN combining rows across tables; a WHERE clause that keeps only the rows a statement is meant to touch; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Putting it to use
The readings table is the working surface here, and the LIMIT bounds each probe.
Core lines
SELECT bt_index_check(index => c.oid), c.relname, c.relpages
FROM pg_index i
JOIN pg_class c ON i.indexrelid = c.oid
WHERE c.relkind = 'i' AND i.indisready AND i.indisvalid
ORDER BY c.relpages DESC
LIMIT 10;
INSERT INTO readings (taken_at, value)
SELECT now() - (g || ' minutes')::interval, g FROM generate_series(1, 500) AS g;
CREATE TABLE readings (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
taken_at timestamptz NOT NULL,
value numeric NOT NULL
);
Interactive Tools for This Topic
FAQ
- Which objects does the SQL touch?
- `readings`, `generate_series`, `pg_index`, `pg_class`, combined through a join.
Report a problem with this exampleOpens a pre-filled issue on GitHub.