Skip to content

Commit 978f572

Browse files
authored
Merge pull request #66 from konturio/feat-cleanup-invalid-indexes
cleanup invalid indexes before reindex
2 parents eb020c8 + d673887 commit 978f572

File tree

3 files changed

+34
-2
lines changed

3 files changed

+34
-2
lines changed

Makefile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ remove_outated_indicators_loop:
2727

2828
.PHONY: reindex_btree_loop
2929
reindex_btree_loop:
30+
psql -qf scripts/drop_invalid_indexes.sql
3031
$(SHELL) scripts/reindex-bloated-btrees.sh
3132

3233
.PHONY: remove_failed_upload_loop

scripts/btree_bloat-superuser.sql

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
-- below is modified version of https://github.com/ioguix/pgsql-bloat-estimation/blob/master/btree/btree_bloat-superuser.sql
2626
-- it returns names of the tables that have bloated btree indexes (>50%)
2727

28-
SELECT
28+
SELECT DISTINCT
2929
tblname
3030
FROM (
3131
SELECT coalesce(1 +
@@ -102,4 +102,4 @@ FROM (
102102
) AS rows_hdr_pdg_stats
103103
) AS relation_stats
104104
WHERE 100 * (relpages-est_pages_ff)::float / relpages > 50 -- bloat_pct
105-
ORDER BY idxname
105+
ORDER BY 1

scripts/drop_invalid_indexes.sql

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
DO $$
2+
DECLARE
3+
idx RECORD;
4+
BEGIN
5+
FOR idx IN
6+
SELECT n.nspname AS schema_name,
7+
c.relname AS index_name,
8+
t.oid AS table_oid,
9+
t.relname AS table_name
10+
FROM pg_index i
11+
JOIN pg_class c ON c.oid = i.indexrelid
12+
JOIN pg_namespace n ON n.oid = c.relnamespace
13+
JOIN pg_class t ON t.oid = i.indrelid
14+
WHERE NOT i.indisvalid
15+
LOOP
16+
BEGIN
17+
-- try to take an ACCESS EXCLUSIVE lock on the table, without waiting
18+
EXECUTE format('LOCK TABLE %I.%I IN ACCESS EXCLUSIVE MODE NOWAIT',
19+
idx.schema_name, idx.table_name);
20+
21+
-- if lock succeeds, drop index
22+
RAISE NOTICE 'Dropping invalid index: %.%', idx.schema_name, idx.index_name;
23+
EXECUTE format('DROP INDEX IF EXISTS %I.%I;', idx.schema_name, idx.index_name);
24+
25+
EXCEPTION WHEN lock_not_available THEN
26+
RAISE NOTICE 'Skipped index %.% (table %.% is busy)',
27+
idx.schema_name, idx.index_name, idx.schema_name, idx.table_name;
28+
END;
29+
END LOOP;
30+
END;
31+
$$ LANGUAGE plpgsql;

0 commit comments

Comments
 (0)