-
Notifications
You must be signed in to change notification settings - Fork 0
/
pg_profile--0.0.5.sql
2890 lines (2651 loc) · 110 KB
/
pg_profile--0.0.5.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\echo Use "CREATE EXTENSION pg_profile" to load this file. \quit
/* ========= Tables ========= */
CREATE TABLE snapshots (
snap_id SERIAL PRIMARY KEY,
snap_time timestamp (0) with time zone
);
CREATE INDEX ix_snap_time ON snapshots(snap_time);
COMMENT ON TABLE snapshots IS 'Snapshot times list';
CREATE TABLE snap_params (
snap_id integer REFERENCES snapshots (snap_id) ON DELETE CASCADE,
p_name text,
setting text,
CONSTRAINT pk_snap_params PRIMARY KEY (snap_id,p_name)
);
COMMENT ON TABLE snap_params IS 'PostgreSQL parameters at time of snapshot';
CREATE TABLE baselines (
bl_id SERIAL PRIMARY KEY,
bl_name varchar (25) UNIQUE,
keep_until timestamp (0) with time zone
);
COMMENT ON TABLE baselines IS 'Baselines list';
CREATE TABLE bl_snaps (
snap_id integer REFERENCES snapshots (snap_id) ON DELETE RESTRICT,
bl_id integer REFERENCES baselines (bl_id) ON DELETE CASCADE,
CONSTRAINT bl_snaps_pk PRIMARY KEY (snap_id,bl_id)
);
CREATE INDEX ix_bl_snaps_blid ON bl_snaps(bl_id);
COMMENT ON TABLE bl_snaps IS 'Snapshots in baselines';
CREATE TABLE stmt_list(
queryid_md5 char(10),
query text,
CONSTRAINT pk_snap_users PRIMARY KEY (queryid_md5)
);
COMMENT ON TABLE stmt_list IS 'Statements, captured in snapshots';
CREATE TABLE snap_statements (
snap_id integer REFERENCES snapshots (snap_id) ON DELETE CASCADE,
userid oid,
dbid oid,
queryid bigint,
queryid_md5 char(10) REFERENCES stmt_list (queryid_md5) ON DELETE RESTRICT ON UPDATE CASCADE,
calls bigint,
total_time double precision,
min_time double precision,
max_time double precision,
mean_time double precision,
stddev_time double precision,
rows bigint,
shared_blks_hit bigint,
shared_blks_read bigint,
shared_blks_dirtied bigint,
shared_blks_written bigint,
local_blks_hit bigint,
local_blks_read bigint,
local_blks_dirtied bigint,
local_blks_written bigint,
temp_blks_read bigint,
temp_blks_written bigint,
blk_read_time double precision,
blk_write_time double precision,
CONSTRAINT pk_snap_statements_n PRIMARY KEY (snap_id,userid,dbid,queryid)
);
CREATE INDEX ix_snap_stmts_qid ON snap_statements (queryid_md5);
COMMENT ON TABLE snap_statements IS 'Snapshot statement statistics table (fields from pg_stat_statements)';
CREATE VIEW v_snap_statements AS
SELECT
st.snap_id as snap_id,
st.userid as userid,
st.dbid as dbid,
st.queryid as queryid,
queryid_md5 as queryid_md5,
st.calls as calls,
st.total_time as total_time,
st.min_time as min_time,
st.max_time as max_time,
st.mean_time as mean_time,
st.stddev_time as stddev_time,
st.rows as rows,
st.shared_blks_hit as shared_blks_hit,
st.shared_blks_read as shared_blks_read,
st.shared_blks_dirtied as shared_blks_dirtied,
st.shared_blks_written as shared_blks_written,
st.local_blks_hit as local_blks_hit,
st.local_blks_read as local_blks_read,
st.local_blks_dirtied as local_blks_dirtied,
st.local_blks_written as local_blks_written,
st.temp_blks_read as temp_blks_read,
st.temp_blks_written as temp_blks_written,
st.blk_read_time as blk_read_time,
st.blk_write_time as blk_write_time,
l.query as query
FROM
snap_statements st
JOIN stmt_list l USING (queryid_md5);
CREATE TABLE snap_statements_total (
snap_id integer REFERENCES snapshots (snap_id) ON DELETE CASCADE,
dbid oid,
calls bigint,
total_time double precision,
rows bigint,
shared_blks_hit bigint,
shared_blks_read bigint,
shared_blks_dirtied bigint,
shared_blks_written bigint,
local_blks_hit bigint,
local_blks_read bigint,
local_blks_dirtied bigint,
local_blks_written bigint,
temp_blks_read bigint,
temp_blks_written bigint,
blk_read_time double precision,
blk_write_time double precision,
statements bigint,
CONSTRAINT pk_snap_statements_total PRIMARY KEY (snap_id,dbid)
);
COMMENT ON TABLE snap_statements_total IS 'Aggregated stats for snapshot, based on pg_stat_statements';
CREATE TABLE tables_list(
relid oid,
schemaname name,
relname name,
CONSTRAINT pk_tables_list PRIMARY KEY (relid)
);
COMMENT ON TABLE tables_list IS 'Table names and scheams, captured in snapshots';
CREATE TABLE snap_stat_user_tables (
snap_id integer REFERENCES snapshots (snap_id) ON DELETE CASCADE,
dbid oid,
relid oid REFERENCES tables_list(relid) ON DELETE RESTRICT ON UPDATE RESTRICT,
seq_scan bigint,
seq_tup_read bigint,
idx_scan bigint,
idx_tup_fetch bigint,
n_tup_ins bigint,
n_tup_upd bigint,
n_tup_del bigint,
n_tup_hot_upd bigint,
n_live_tup bigint,
n_dead_tup bigint,
n_mod_since_analyze bigint,
last_vacuum timestamp with time zone,
last_autovacuum timestamp with time zone,
last_analyze timestamp with time zone,
last_autoanalyze timestamp with time zone,
vacuum_count bigint,
autovacuum_count bigint,
analyze_count bigint,
autoanalyze_count bigint,
relsize bigint,
relsize_diff bigint,
CONSTRAINT pk_snap_stat_user_tables PRIMARY KEY (snap_id,dbid,relid)
);
COMMENT ON TABLE snap_stat_user_tables IS 'Stats increments for user tables in all databases by snapshots';
CREATE VIEW v_snap_stat_user_tables AS
SELECT
snap_id,
dbid,
relid,
schemaname,
relname,
seq_scan,
seq_tup_read,
idx_scan,
idx_tup_fetch,
n_tup_ins,
n_tup_upd,
n_tup_del,
n_tup_hot_upd,
n_live_tup,
n_dead_tup,
n_mod_since_analyze,
last_vacuum,
last_autovacuum,
last_analyze,
last_autoanalyze,
vacuum_count,
autovacuum_count,
analyze_count,
autoanalyze_count,
relsize,
relsize_diff
FROM ONLY snap_stat_user_tables JOIN tables_list USING (relid);
COMMENT ON VIEW v_snap_stat_user_tables IS 'Reconstructed stats view with table names and schemas';
CREATE TABLE last_stat_user_tables AS SELECT * FROM v_snap_stat_user_tables WHERE 0=1;
COMMENT ON TABLE last_stat_user_tables IS 'Last snapshot data for calculating diffs in next snapshot';
CREATE TABLE indexes_list(
indexrelid oid,
schemaname name,
indexrelname name,
CONSTRAINT pk_indexes_list PRIMARY KEY (indexrelid)
);
COMMENT ON TABLE indexes_list IS 'Index names and scheams, captured in snapshots';
CREATE TABLE snap_stat_user_indexes (
snap_id integer REFERENCES snapshots (snap_id) ON DELETE CASCADE,
dbid oid,
relid oid REFERENCES tables_list(relid) ON DELETE RESTRICT ON UPDATE RESTRICT,
indexrelid oid REFERENCES indexes_list(indexrelid) ON DELETE RESTRICT ON UPDATE RESTRICT,
idx_scan bigint,
idx_tup_read bigint,
idx_tup_fetch bigint,
relsize bigint,
relsize_diff bigint,
indisunique bool,
CONSTRAINT pk_snap_stat_user_indexes PRIMARY KEY (snap_id,dbid,relid,indexrelid)
);
COMMENT ON TABLE snap_stat_user_indexes IS 'Stats increments for user indexes in all databases by snapshots';
CREATE VIEW v_snap_stat_user_indexes AS
SELECT
snap_id,
dbid,
s.relid,
s.indexrelid,
il.schemaname,
tl.relname,
il.indexrelname,
idx_scan,
idx_tup_read,
idx_tup_fetch,
relsize,
relsize_diff,
indisunique
FROM ONLY
snap_stat_user_indexes s
JOIN indexes_list il ON (il.indexrelid = s.indexrelid)
JOIN tables_list tl ON (tl.relid = s.relid);
COMMENT ON VIEW v_snap_stat_user_indexes IS 'Reconstructed stats view with table and index names and schemas';
CREATE TABLE last_stat_user_indexes AS SELECT * FROM v_snap_stat_user_indexes WHERE 0=1;
COMMENT ON TABLE last_stat_user_indexes IS 'Last snapshot data for calculating diffs in next snapshot';
CREATE TABLE funcs_list(
funcid oid,
schemaname name,
funcname name,
CONSTRAINT pk_funcs_list PRIMARY KEY (funcid)
);
COMMENT ON TABLE funcs_list IS 'Function names and scheams, captured in snapshots';
CREATE TABLE snap_stat_user_functions (
snap_id integer REFERENCES snapshots (snap_id) ON DELETE CASCADE,
dbid oid,
funcid oid REFERENCES funcs_list(funcid) ON DELETE RESTRICT ON UPDATE RESTRICT,
calls bigint,
total_time double precision,
self_time double precision,
CONSTRAINT pk_snap_stat_user_functions PRIMARY KEY (snap_id,dbid,funcid)
);
COMMENT ON TABLE snap_stat_user_functions IS 'Stats increments for user functions in all databases by snapshots';
CREATE VIEW v_snap_stat_user_functions AS
SELECT
snap_id,
dbid,
funcid,
schemaname,
funcname,
calls,
total_time,
self_time
FROM ONLY snap_stat_user_functions JOIN funcs_list USING (funcid);
COMMENT ON VIEW v_snap_stat_user_indexes IS 'Reconstructed stats view with function names and schemas';
CREATE TABLE last_stat_user_functions AS SELECT * FROM v_snap_stat_user_functions WHERE 0=1;
COMMENT ON TABLE last_stat_user_functions IS 'Last snapshot data for calculating diffs in next snapshot';
CREATE TABLE snap_statio_user_tables (
snap_id integer REFERENCES snapshots (snap_id) ON DELETE CASCADE,
dbid oid,
relid oid REFERENCES tables_list(relid) ON DELETE RESTRICT ON UPDATE RESTRICT,
heap_blks_read bigint,
heap_blks_hit bigint,
idx_blks_read bigint,
idx_blks_hit bigint,
toast_blks_read bigint,
toast_blks_hit bigint,
tidx_blks_read bigint,
tidx_blks_hit bigint,
relsize bigint,
relsize_diff bigint,
CONSTRAINT pk_snap_statio_user_tables PRIMARY KEY (snap_id,dbid,relid)
);
COMMENT ON TABLE snap_statio_user_tables IS 'IO Stats increments for user tables in all databases by snapshots';
CREATE VIEW v_snap_statio_user_tables AS
SELECT
snap_id,
dbid,
relid,
schemaname,
relname,
heap_blks_read,
heap_blks_hit,
idx_blks_read,
idx_blks_hit,
toast_blks_read,
toast_blks_hit,
tidx_blks_read,
tidx_blks_hit,
relsize,
relsize_diff
FROM ONLY snap_statio_user_tables JOIN tables_list USING (relid);
COMMENT ON VIEW v_snap_statio_user_tables IS 'Reconstructed stats view with table names and schemas';
CREATE TABLE last_statio_user_tables AS SELECT * FROM v_snap_statio_user_tables WHERE 0=1;
COMMENT ON TABLE last_statio_user_tables IS 'Last snapshot data for calculating diffs in next snapshot';
CREATE TABLE snap_statio_user_indexes (
snap_id integer REFERENCES snapshots (snap_id) ON DELETE CASCADE,
dbid oid,
relid oid REFERENCES tables_list(relid) ON DELETE RESTRICT ON UPDATE RESTRICT,
indexrelid oid REFERENCES indexes_list(indexrelid) ON DELETE RESTRICT ON UPDATE RESTRICT,
idx_blks_read bigint,
idx_blks_hit bigint,
relsize bigint,
relsize_diff bigint,
CONSTRAINT pk_snap_statio_user_indexes PRIMARY KEY (snap_id,dbid,relid,indexrelid)
);
COMMENT ON TABLE snap_statio_user_indexes IS 'Stats increments for user indexes in all databases by snapshots';
CREATE VIEW v_snap_statio_user_indexes AS
SELECT
snap_id,
dbid,
s.relid,
s.indexrelid,
il.schemaname,
tl.relname,
il.indexrelname,
idx_blks_read,
idx_blks_hit,
relsize,
relsize_diff
FROM
ONLY snap_statio_user_indexes s
JOIN tables_list tl ON (s.relid = tl.relid)
JOIN indexes_list il ON (s.indexrelid = il.indexrelid);
COMMENT ON VIEW v_snap_statio_user_indexes IS 'Reconstructed stats view with table and index names and schemas';
CREATE TABLE last_statio_user_indexes AS SELECT * FROM v_snap_statio_user_indexes WHERE 0=1;
COMMENT ON TABLE last_statio_user_indexes IS 'Last snapshot data for calculating diffs in next snapshot';
CREATE TABLE snap_stat_database
(
snap_id integer REFERENCES snapshots (snap_id) ON DELETE CASCADE,
datid oid,
datname name,
xact_commit bigint,
xact_rollback bigint,
blks_read bigint,
blks_hit bigint,
tup_returned bigint,
tup_fetched bigint,
tup_inserted bigint,
tup_updated bigint,
tup_deleted bigint,
conflicts bigint,
temp_files bigint,
temp_bytes bigint,
deadlocks bigint,
blk_read_time double precision,
blk_write_time double precision,
stats_reset timestamp with time zone,
datsize_delta bigint,
CONSTRAINT pk_snap_stat_database PRIMARY KEY (snap_id,datid,datname)
);
COMMENT ON TABLE snap_stat_database IS 'Snapshot database statistics table (fields from pg_stat_database)';
CREATE TABLE last_stat_database AS SELECT * FROM snap_stat_database WHERE 0=1;
COMMENT ON TABLE last_stat_database IS 'Last snapshot data for calculating diffs in next snapshot';
CREATE TABLE snap_stat_cluster
(
snap_id integer REFERENCES snapshots (snap_id) ON DELETE CASCADE,
checkpoints_timed bigint,
checkpoints_req bigint,
checkpoint_write_time double precision,
checkpoint_sync_time double precision,
buffers_checkpoint bigint,
buffers_clean bigint,
maxwritten_clean bigint,
buffers_backend bigint,
buffers_backend_fsync bigint,
buffers_alloc bigint,
stats_reset timestamp with time zone,
wal_size bigint,
CONSTRAINT pk_snap_stat_cluster PRIMARY KEY (snap_id)
);
COMMENT ON TABLE snap_stat_cluster IS 'Snapshot cluster statistics table (fields from pg_stat_bgwriter, etc.)';
CREATE TABLE last_stat_cluster AS SELECT * FROM snap_stat_cluster WHERE 0=1;
COMMENT ON TABLE last_stat_cluster IS 'Last snapshot data for calculating diffs in next snapshot';
/* ========= Snapshot functions ========= */
CREATE OR REPLACE FUNCTION snapshot() RETURNS integer SET search_path=@extschema@,public SET lock_timeout=300000 AS $$
DECLARE
id integer;
topn integer;
ret integer;
lockid bigint;
b_local_db boolean;
pg_version varchar(10);
qres record;
BEGIN
-- Only one running snapshot() function allowed!
-- Getting custom lockid
BEGIN
lockid := current_setting('pg_profile.lockid')::bigint;
EXCEPTION
WHEN OTHERS THEN lockid := 2174049485089987259;
END;
IF NOT pg_try_advisory_lock(lockid) THEN
RAISE 'Another snapshot() function is running!';
END IF;
-- Getting TopN setting
BEGIN
topn := current_setting('pg_profile.topn')::integer;
EXCEPTION
WHEN OTHERS THEN topn := 20;
END;
-- Getting retention setting
BEGIN
ret := current_setting('pg_profile.retention')::integer;
EXCEPTION
WHEN OTHERS THEN ret := 7;
END;
--Getting postgres version
SELECT setting INTO STRICT pg_version FROM pg_catalog.pg_settings WHERE name = 'server_version_num';
-- Deleting obsolete baselines
DELETE FROM baselines WHERE keep_until < now();
-- Deleting obsolote snapshots
DELETE FROM snapshots WHERE snap_time < now() - (ret || ' days')::interval
AND snap_id NOT IN (SELECT snap_id FROM bl_snaps);
-- Creating a new snapshot record
INSERT INTO snapshots(snap_time)
VALUES (now())
RETURNING snap_id INTO id;
-- Collecting postgres parameters
INSERT INTO snap_params
SELECT id,name,setting
FROM pg_catalog.pg_settings
WHERE name IN ('pg_stat_statements.max','pg_stat_statements.track');
INSERT INTO snap_params
VALUES (id,'pg_profile.topn',topn);
-- Snapshot data from pg_stat_statements for top whole cluster statements
FOR qres IN
SELECT
id,
st.userid,
st.dbid,
st.queryid,
left(md5(db.datname || r.rolname || st.query ), 10) AS queryid_md5,
st.calls,
st.total_time,
st.min_time,
st.max_time,
st.mean_time,
st.stddev_time,
st.rows,
st.shared_blks_hit,
st.shared_blks_read,
st.shared_blks_dirtied,
st.shared_blks_written,
st.local_blks_hit,
st.local_blks_read,
st.local_blks_dirtied,
st.local_blks_written,
st.temp_blks_read,
st.temp_blks_written,
st.blk_read_time,
st.blk_write_time,
regexp_replace(st.query,'\s+',' ','g') AS query
FROM pg_stat_statements st
JOIN pg_database db ON (db.oid=st.dbid)
JOIN pg_roles r ON (r.oid=st.userid)
JOIN
(SELECT
userid, dbid, md5(query) as q_md5,
row_number() over (ORDER BY sum(total_time) DESC) AS time_p,
row_number() over (ORDER BY sum(calls) DESC) AS calls_p,
row_number() over (ORDER BY sum(blk_read_time + blk_write_time) DESC) AS io_time_p,
row_number() over (ORDER BY sum(shared_blks_hit + shared_blks_read) DESC) AS gets_p,
row_number() over (ORDER BY sum(temp_blks_written + local_blks_written) DESC) AS temp_p
FROM pg_stat_statements
GROUP BY userid, dbid, md5(query)) rank_t
ON (st.userid=rank_t.userid AND st.dbid=rank_t.dbid AND md5(st.query)=rank_t.q_md5)
WHERE
time_p <= topn
OR calls_p <= topn
OR io_time_p <= topn
OR gets_p <= topn
OR temp_p <= topn
LOOP
INSERT INTO stmt_list VALUES (qres.queryid_md5,qres.query) ON CONFLICT DO NOTHING;
INSERT INTO snap_statements VALUES (
qres.id,
qres.userid,
qres.dbid,
qres.queryid,
qres.queryid_md5,
qres.calls,
qres.total_time,
qres.min_time,
qres.max_time,
qres.mean_time,
qres.stddev_time,
qres.rows,
qres.shared_blks_hit,
qres.shared_blks_read,
qres.shared_blks_dirtied,
qres.shared_blks_written,
qres.local_blks_hit,
qres.local_blks_read,
qres.local_blks_dirtied,
qres.local_blks_written,
qres.temp_blks_read,
qres.temp_blks_written,
qres.blk_read_time,
qres.blk_write_time
);
END LOOP;
-- Deleting unused statements
DELETE FROM stmt_list
WHERE queryid_md5 NOT IN
(SELECT queryid_md5 FROM snap_statements);
-- Aggregeted statistics data
INSERT INTO snap_statements_total
SELECT id,dbid,sum(calls),sum(total_time),sum(rows),sum(shared_blks_hit),sum(shared_blks_read),sum(shared_blks_dirtied),sum(shared_blks_written),
sum(local_blks_hit),sum(local_blks_read),sum(local_blks_dirtied),sum(local_blks_written),sum(temp_blks_read),sum(temp_blks_written),sum(blk_read_time),
sum(blk_write_time),count(*)
FROM pg_stat_statements
GROUP BY dbid;
-- Flushing pg_stat_statements
PERFORM pg_stat_statements_reset();
-- pg_stat_database data
INSERT INTO snap_stat_database
SELECT
id,
rs.datid,
rs.datname,
rs.xact_commit-ls.xact_commit,
rs.xact_rollback-ls.xact_rollback,
rs.blks_read-ls.blks_read,
rs.blks_hit-ls.blks_hit,
rs.tup_returned-ls.tup_returned,
rs.tup_fetched-ls.tup_fetched,
rs.tup_inserted-ls.tup_inserted,
rs.tup_updated-ls.tup_updated,
rs.tup_deleted-ls.tup_deleted,
rs.conflicts-ls.conflicts,
rs.temp_files-ls.temp_files,
rs.temp_bytes-ls.temp_bytes,
rs.deadlocks-ls.deadlocks,
rs.blk_read_time-ls.blk_read_time,
rs.blk_write_time-ls.blk_write_time,
rs.stats_reset,
pg_database_size(rs.datid)-ls.datsize_delta
FROM pg_catalog.pg_stat_database rs
JOIN ONLY(last_stat_database) ls ON (rs.datid = ls.datid AND rs.datname = ls.datname AND rs.stats_reset = ls.stats_reset AND ls.snap_id = id - 1);
PERFORM snapshot_dbobj_delta(id,topn);
TRUNCATE TABLE last_stat_database;
INSERT INTO last_stat_database (
snap_id,
datid,
datname,
xact_commit,
xact_rollback,
blks_read,
blks_hit,
tup_returned,
tup_fetched,
tup_inserted,
tup_updated,
tup_deleted,
conflicts,
temp_files,
temp_bytes,
deadlocks,
blk_read_time,
blk_write_time,
stats_reset,
datsize_delta)
SELECT
id,
datid,
datname,
xact_commit,
xact_rollback,
blks_read,
blks_hit,
tup_returned,
tup_fetched,
tup_inserted,
tup_updated,
tup_deleted,
conflicts,
temp_files,
temp_bytes,
deadlocks,
blk_read_time,
blk_write_time,
stats_reset,
pg_database_size(datid)
FROM pg_catalog.pg_stat_database;
-- pg_stat_bgwriter data
IF pg_version::integer < 100000 THEN
INSERT INTO snap_stat_cluster
SELECT
id,
rs.checkpoints_timed-ls.checkpoints_timed,
rs.checkpoints_req-ls.checkpoints_req,
rs.checkpoint_write_time-ls.checkpoint_write_time,
rs.checkpoint_sync_time-ls.checkpoint_sync_time,
rs.buffers_checkpoint-ls.buffers_checkpoint,
rs.buffers_clean-ls.buffers_clean,
rs.maxwritten_clean-ls.maxwritten_clean,
rs.buffers_backend-ls.buffers_backend,
rs.buffers_backend_fsync-ls.buffers_backend_fsync,
rs.buffers_alloc-ls.buffers_alloc,
rs.stats_reset,
pg_xlog_location_diff(pg_current_xlog_location(),'0/00000000')-ls.wal_size
FROM pg_catalog.pg_stat_bgwriter rs
JOIN ONLY(last_stat_cluster) ls ON (rs.stats_reset = ls.stats_reset AND ls.snap_id = id - 1);
ELSIF pg_version::integer >= 100000 THEN
INSERT INTO snap_stat_cluster
SELECT
id,
rs.checkpoints_timed-ls.checkpoints_timed,
rs.checkpoints_req-ls.checkpoints_req,
rs.checkpoint_write_time-ls.checkpoint_write_time,
rs.checkpoint_sync_time-ls.checkpoint_sync_time,
rs.buffers_checkpoint-ls.buffers_checkpoint,
rs.buffers_clean-ls.buffers_clean,
rs.maxwritten_clean-ls.maxwritten_clean,
rs.buffers_backend-ls.buffers_backend,
rs.buffers_backend_fsync-ls.buffers_backend_fsync,
rs.buffers_alloc-ls.buffers_alloc,
rs.stats_reset,
pg_wal_lsn_diff(pg_current_wal_lsn(),'0/00000000')-ls.wal_size
FROM pg_catalog.pg_stat_bgwriter rs
JOIN ONLY(last_stat_cluster) ls ON (rs.stats_reset = ls.stats_reset AND ls.snap_id = id - 1);
END IF;
TRUNCATE TABLE last_stat_cluster;
IF pg_version::integer < 100000 THEN
INSERT INTO last_stat_cluster (
snap_id,
checkpoints_timed,
checkpoints_req,
checkpoint_write_time,
checkpoint_sync_time,
buffers_checkpoint,
buffers_clean,
maxwritten_clean,
buffers_backend,
buffers_backend_fsync,
buffers_alloc,
stats_reset,
wal_size)
SELECT
id,
checkpoints_timed,
checkpoints_req,
checkpoint_write_time,
checkpoint_sync_time,
buffers_checkpoint,
buffers_clean,
maxwritten_clean,
buffers_backend,
buffers_backend_fsync,
buffers_alloc,
stats_reset,
pg_xlog_location_diff(pg_current_xlog_location(),'0/00000000')
FROM pg_catalog.pg_stat_bgwriter;
ELSIF pg_version::integer >= 100000 THEN
INSERT INTO last_stat_cluster (
snap_id,
checkpoints_timed,
checkpoints_req,
checkpoint_write_time,
checkpoint_sync_time,
buffers_checkpoint,
buffers_clean,
maxwritten_clean,
buffers_backend,
buffers_backend_fsync,
buffers_alloc,
stats_reset,
wal_size)
SELECT
id,
checkpoints_timed,
checkpoints_req,
checkpoint_write_time,
checkpoint_sync_time,
buffers_checkpoint,
buffers_clean,
maxwritten_clean,
buffers_backend,
buffers_backend_fsync,
buffers_alloc,
stats_reset,
pg_wal_lsn_diff(pg_current_wal_lsn(),'0/00000000')
FROM pg_catalog.pg_stat_bgwriter;
END IF;
-- Delete unused tables from tables list
DELETE FROM tables_list WHERE relid NOT IN (
SELECT relid FROM snap_stat_user_tables
UNION ALL
SELECT relid FROM snap_statio_user_tables
UNION ALL
SELECT relid FROM snap_stat_user_indexes
UNION ALL
SELECT relid FROM snap_statio_user_indexes
);
-- Delete unused indexes from indexes list
DELETE FROM indexes_list WHERE indexrelid NOT IN (
SELECT indexrelid FROM snap_stat_user_indexes
UNION ALL
SELECT indexrelid FROM snap_statio_user_indexes
);
-- Delete unused functions from functions list
DELETE FROM funcs_list WHERE funcid NOT IN (
SELECT funcid FROM snap_stat_user_functions
);
PERFORM pg_advisory_unlock(lockid);
RETURN id;
END;
$$ LANGUAGE plpgsql;
COMMENT ON FUNCTION snapshot() IS 'Statistics snapshot creation function. Must be explicitly called periodically.';
CREATE OR REPLACE FUNCTION collect_obj_stats(IN s_id integer) RETURNS integer SET search_path=@extschema@,public AS $$
DECLARE
--Cursor for db stats
c_dblist CURSOR FOR
select dbs.datid,dbs.datname,s1.setting as port from pg_catalog.pg_stat_database dbs, pg_catalog.pg_settings s1
where dbs.datname not like 'template_' and s1.name='port';
r_result RECORD;
BEGIN
-- Creating temporary tables, holding data for objects of all cluster databases
CREATE TEMPORARY TABLE IF NOT EXISTS temp_stat_user_tables (
snap_id integer,
dbid oid,
relid oid,
schemaname name,
relname name,
seq_scan bigint,
seq_tup_read bigint,
idx_scan bigint,
idx_tup_fetch bigint,
n_tup_ins bigint,
n_tup_upd bigint,
n_tup_del bigint,
n_tup_hot_upd bigint,
n_live_tup bigint,
n_dead_tup bigint,
n_mod_since_analyze bigint,
last_vacuum timestamp with time zone,
last_autovacuum timestamp with time zone,
last_analyze timestamp with time zone,
last_autoanalyze timestamp with time zone,
vacuum_count bigint,
autovacuum_count bigint,
analyze_count bigint,
autoanalyze_count bigint,
relsize bigint,
relsize_diff bigint
) ON COMMIT DROP;
CREATE TEMPORARY TABLE IF NOT EXISTS temp_stat_user_functions (
snap_id integer,
dbid oid,
funcid oid,
schemaname name,
funcname name,
calls bigint,
total_time double precision,
self_time double precision
) ON COMMIT DROP;
CREATE TEMPORARY TABLE IF NOT EXISTS temp_stat_user_indexes (
snap_id integer,
dbid oid,
relid oid,
indexrelid oid,
schemaname name,
relname name,
indexrelname name,
idx_scan bigint,
idx_tup_read bigint,
idx_tup_fetch bigint,
relsize bigint,
relsize_diff bigint,
indisunique bool
) ON COMMIT DROP;
CREATE TEMPORARY TABLE IF NOT EXISTS temp_statio_user_tables (
snap_id integer,
dbid oid,
relid oid,
schemaname name,
relname name,
heap_blks_read bigint,
heap_blks_hit bigint,
idx_blks_read bigint,
idx_blks_hit bigint,
toast_blks_read bigint,
toast_blks_hit bigint,
tidx_blks_read bigint,
tidx_blks_hit bigint,
relsize bigint,
relsize_diff bigint
) ON COMMIT DROP;
CREATE TEMPORARY TABLE IF NOT EXISTS temp_statio_user_indexes (
snap_id integer,
dbid oid,
relid oid,
indexrelid oid,
schemaname name,
relname name,
indexrelname name,
idx_blks_read bigint,
idx_blks_hit bigint,
relsize bigint,
relsize_diff bigint
) ON COMMIT DROP;
-- Load new data from statistic views of all cluster databases
FOR r_result IN c_dblist LOOP
INSERT INTO temp_stat_user_tables
SELECT s_id,r_result.datid,t.*
FROM dblink('dbname='||r_result.datname||' port='||r_result.port, 'select *,pg_relation_size(relid) relsize,0 relsize_diff from pg_catalog.pg_stat_user_tables')
AS t (
relid oid,
schemaname name,
relname name,
seq_scan bigint,
seq_tup_read bigint,
idx_scan bigint,
idx_tup_fetch bigint,
n_tup_ins bigint,
n_tup_upd bigint,
n_tup_del bigint,
n_tup_hot_upd bigint,
n_live_tup bigint,
n_dead_tup bigint,
n_mod_since_analyze bigint,
last_vacuum timestamp with time zone,
last_autovacuum timestamp with time zone,
last_analyze timestamp with time zone,
last_autoanalyze timestamp with time zone,
vacuum_count bigint,
autovacuum_count bigint,
analyze_count bigint,
autoanalyze_count bigint,
relsize bigint,
relsize_diff bigint
);
INSERT INTO temp_stat_user_indexes
SELECT s_id,r_result.datid,t.*
FROM dblink('dbname='||r_result.datname||' port='||r_result.port, 'select st.*,pg_relation_size(st.relid),0,(ix.indisunique or con.conindid IS NOT NULL) as indisunique
from pg_catalog.pg_stat_user_indexes st
join pg_catalog.pg_index ix on (ix.indexrelid = st.indexrelid)
left join pg_catalog.pg_constraint con on(con.conindid = ix.indexrelid and con.contype in (''p'',''u''))')
AS t (
relid oid,
indexrelid oid,
schemaname name,
relname name,
indexrelname name,
idx_scan bigint,
idx_tup_read bigint,
idx_tup_fetch bigint,
relsize bigint,
relsize_diff bigint,
indisunique bool
);
INSERT INTO temp_stat_user_functions
SELECT s_id,r_result.datid,t.*
FROM dblink('dbname='||r_result.datname||' port='||r_result.port, 'select * from pg_catalog.pg_stat_user_functions')
AS t (
funcid oid,
schemaname name,
funcname name,
calls bigint,
total_time double precision,
self_time double precision
);
INSERT INTO temp_statio_user_tables
SELECT s_id,r_result.datid,t.*
FROM dblink('dbname='||r_result.datname||' port='||r_result.port, 'select *,pg_relation_size(relid),0 from pg_catalog.pg_statio_user_tables')
AS t (
relid oid,
schemaname name,
relname name,
heap_blks_read bigint,
heap_blks_hit bigint,
idx_blks_read bigint,
idx_blks_hit bigint,
toast_blks_read bigint,
toast_blks_hit bigint,
tidx_blks_read bigint,
tidx_blks_hit bigint,
relsize bigint,
relsize_diff bigint
);
INSERT INTO temp_statio_user_indexes
SELECT s_id,r_result.datid,t.*
FROM dblink('dbname='||r_result.datname||' port='||r_result.port, 'select *,pg_relation_size(relid),0 from pg_catalog.pg_statio_user_indexes')
AS t (
relid oid,
indexrelid oid,
schemaname name,
relname name,
indexrelname name,
idx_blks_read bigint,
idx_blks_hit bigint,
relsize bigint,
relsize_diff bigint
);
END LOOP;
RETURN 0;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION snapshot_dbobj_delta(IN s_id integer, IN topn integer) RETURNS integer AS $$
DECLARE
qres record;
BEGIN
-- Collecting stat info for objects of all databases
PERFORM collect_obj_stats(s_id);
-- Calculating difference from previous snapshot and storing it in snap_stat_ tables
-- Stats of user tables
FOR qres IN
SELECT
snap_id,
dbid,
relid,
schemaname,
relname,
seq_scan,
seq_tup_read,
idx_scan,
idx_tup_fetch,
n_tup_ins,
n_tup_upd,
n_tup_del,
n_tup_hot_upd,
n_live_tup,
n_dead_tup,
n_mod_since_analyze,
last_vacuum,
last_autovacuum,
last_analyze,
last_autoanalyze,
vacuum_count,
autovacuum_count,
analyze_count,
autoanalyze_count,
relsize,
relsize_diff
FROM
(SELECT
t.snap_id,
t.dbid,
t.relid,