-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpg
More file actions
executable file
·4338 lines (3980 loc) · 116 KB
/
pg
File metadata and controls
executable file
·4338 lines (3980 loc) · 116 KB
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
#!/bin/bash
#
# PostgreSQL Database Diagnostic Tool (pg)
# Similar to Oracle's ora tool but for PostgreSQL
#
# Tool Version: 2.1.0 (2026-01-27)
#
TOOL_VERSION="2.1.1"
TOOL_BUILD_DATE="2026-02-03"
PG_VERSION=""
PG_MAJOR_VERSION=""
PGS_TOTAL_COL=""
PGS_MEAN_COL=""
PGS_MAX_COL=""
PG_TMP="/tmp"
EXEC_NAME=$(basename "$0")
DBHOST="${PGHOST:-localhost}"
DBPORT="${PGPORT:-5432}"
DBUSER="${PGUSER:-postgres}"
DBNAME="${PGDATABASE:-postgres}"
DBPASSWORD="${PGPASSWORD:-}"
TOP_N=10
USE_PASSWORD_FILE=""
# Enhanced password handling
setup_password()
{
# First check PGPASSWORD environment variable
if [ -n "$PGPASSWORD" ]; then
export PGPASSWORD="$PGPASSWORD"
return 0
fi
# Check for password file option
if [ -n "$USE_PASSWORD_FILE" ]; then
if [ -f "$USE_PASSWORD_FILE" ]; then
chmod 600 "$USE_PASSWORD_FILE" 2>/dev/null
DBPASSWORD=$(cat "$USE_PASSWORD_FILE")
export PGPASSWORD="$DBPASSWORD"
return 0
else
echo -e "${RED}Error: Password file not found: $USE_PASSWORD_FILE${NC}"
return 1
fi
fi
# Check for .pgpass file
local pgpass_file="$HOME/.pgpass"
if [ -f "$pgpass_file" ]; then
chmod 600 "$pgpass_file" 2>/dev/null
export PGPASSFILE="$pgpass_file"
return 0
fi
# Check for .pgpass in current directory
local local_pgpass="$(pwd)/.pgpass"
if [ -f "$local_pgpass" ]; then
chmod 600 "$local_pgpass" 2>/dev/null
export PGPASSFILE="$local_pgpass"
return 0
fi
return 1
}
setup_password
# Color output support with terminal detection
use_color=true
if [ ! -t 1 ] || [ "$TERM" = "dumb" ]; then
use_color=false
fi
colorize()
{
local color=$1
local text="$2"
if [ "$use_color" = true ]; then
case "$color" in
red) printf "\033[0;31m%s\033[0m\n" "$text" ;;
green) printf "\033[0;32m%s\033[0m\n" "$text" ;;
yellow) printf "\033[1;33m%s\033[0m\n" "$text" ;;
blue) printf "\033[0;34m%s\033[0m\n" "$text" ;;
*) echo "$text" ;;
esac
else
echo "$text"
fi
}
# Colors for output (legacy)
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Get PostgreSQL version
get_version()
{
local version_output
version_output=$(psql -h "$DBHOST" -p "$DBPORT" -U "$DBUSER" -d "$DBNAME" -t -A -c "SELECT version();" 2>/dev/null)
if [ $? -eq 0 ]; then
PG_VERSION=$(echo "$version_output" | sed -n 's/^PostgreSQL \([0-9.]*\).*/\1/p' | head -1)
PG_MAJOR_VERSION=$(echo "$PG_VERSION" | cut -d. -f1)
else
echo "Error: Could not connect to PostgreSQL"
exit 1
fi
}
# Format bytes to human readable
format_bytes()
{
local bytes=$1
if [ "$bytes" -lt 1024 ]; then
echo "${bytes}B"
elif [ "$bytes" -lt 1048576 ]; then
echo "$((bytes / 1024))KB"
elif [ "$bytes" -lt 1073741824 ]; then
echo "$((bytes / 1048576))MB"
else
echo "$((bytes / 1073741824))GB"
fi
}
# Format time duration
format_duration()
{
local seconds=$1
if [ "$seconds" -lt 60 ]; then
echo "${seconds}s"
elif [ "$seconds" -lt 3600 ]; then
echo "$((seconds / 60))m$((seconds % 60))s"
else
local hours=$((seconds / 3600))
local mins=$(((seconds % 3600) / 60))
echo "${hours}h${mins}m"
fi
}
usage()
{
local header=$(colorize blue "PostgreSQL Database Diagnostic Tool")
cat << EOF
$header
Version: $TOOL_VERSION | Build: $TOOL_BUILD_DATE
Usage: $EXEC_NAME [options] <command> [arguments]
Options:
-h, --host <host> Database host (default: localhost)
-p, --port <port> Database port (default: 5432)
-u, --user <user> Database user (default: postgres)
-d, --dbname <name> Database name (default: postgres)
-P, --password-file <file> Password file (default: ~/.pgpass)
-n, --top <num> Limit output to top N results (default: 10)
Commands:
=== Session & Query Monitoring ===
sessions List all active sessions
running Currently running queries
blocked Blocked or blocking sessions
locks Current lock status
kill <pid> Kill a session by PID
cancel <pid> Cancel a query by PID
=== Query Analysis ===
fulltext <pid> Show full SQL text for a query
explain <sql> Get execution plan for SQL
explain_analyze <sql> Get execution plan with actual statistics
query_stats Query performance statistics
top_calls Top queries by calls
top_time Top queries by total time
top_rows Top queries by rows processed
buffer_stats Buffer usage statistics
=== Performance & Statistics ===
pg_stat_activity Show pg_stat_activity details
pg_stat_database Database statistics
pg_stat_tables Table access statistics
pg_stat_indexes Index usage statistics
pg_stat_functions Function execution statistics
pg_stat_replication Replication statistics
=== Memory & Cache ===
pg_buffercache Buffer cache contents
pg_cache General cache statistics
shared_buffers Shared buffer usage
local_stats Local statistics
=== Table & Index Analysis ===
table_size [pattern] Show table sizes
index_size [pattern] Show index sizes
bloat_tables Table bloat analysis
bloat_indexes Index bloat analysis
seq_scans Tables with sequential scans
missing_indexes Potentially missing indexes
unused_indexes Unused indexes
duplicate_indexes Duplicate/redundant indexes
=== Vacuum & Autovacuum ===
vacuum_status Vacuum and autovacuum status
dead_tuples Tables with many dead tuples
autovacuum_config Autovacuum configuration
vacuum_progress Vacuum operation progress
=== Lock & Blocking ===
lock_wait Sessions waiting for locks
lock_holder Sessions holding locks
lock_tree Lock wait tree
blocking_queries Queries blocking others
blocked_queries Queries being blocked
=== Connection & Process ===
connections Connection statistics
pg_backends Backend process details
pg_stat_bgwriter Background writer stats
pg_stat_checkpointer Checkpointer statistics
pg_stat_wal WAL statistics
=== Configuration ===
config [pattern] Server configuration
all_settings All configuration settings
pg_settings_filter <pattern> Filter settings by pattern
reload_config Reload configuration without restart
=== Transaction & WAL ===
pg_stat_progress_* Progress information
wal_info WAL information
wal_lsn_info Current WAL LSN
slot_info Replication slot info
=== System & Size ===
database_size Database sizes
tablespace_size Tablespace sizes
relation_size Relation sizes
function_size Function sizes
=== Version & Info ===
version PostgreSQL version
server_info Server information
extension_list Installed extensions
=== Repeat & Monitoring ===
repeat <interval> <count|forever> <command>
Repeat a command (like watch)
=== Advanced Analysis ===
slow_queries Queries running longer than 5 seconds
longest_running Longest running sessions
idle_in_tx Sessions idle in transaction
cache_hit_ratio Database cache hit ratios
table_bloat_estimated Table bloat estimation
index_usage Index usage analysis
query_plan_stats Query plan statistics
io_stats I/O statistics
temp_files Temporary file usage
checkpoint_stats Checkpoint statistics
replication_lag Replication lag info
function_usage Function usage statistics
top_tables_by_size Largest tables
top_indexes_by_size Largest indexes
table_access_stats Table access patterns
index_efficiency Index efficiency analysis
wait_events Wait event statistics
connection_history Connection history
schema_size Schema sizes
long_running_transactions Long running transactions
table_statistics Detailed table statistics
index_statistics Detailed index statistics
database_statistics Database statistics
system_summary System summary overview
top_queries_by_io Top queries by I/O
=== Security & Users ===
users List all database users
roles List all roles
privileges User privileges
grants Grant information
=== Schema Objects ===
tables [pattern] List tables (with optional pattern)
columns <table> Show columns of a table
primary_keys List all primary keys
foreign_keys List all foreign keys
triggers [pattern] List triggers (with optional pattern)
functions [pattern] List functions (with optional pattern)
procedures [pattern] List procedures (with optional pattern)
views [pattern] List views (with optional pattern)
=== System Resources ===
system_info Operating system information
load_stats System load statistics
cpu_usage CPU usage information
memory_usage Memory usage information
disk_usage Disk usage information
=== Performance Tuning ===
tuning_recommendations Performance tuning recommendations
index_rebuild_recommendations Index rebuild recommendations
vacuum_recommendations Vacuum recommendations
connection_pooling_stats Connection pooling statistics
=== Table Maintenance ===
analyze <table> Analyze table
vacuum <table> Vacuum table
vacuum_full <table> Vacuum table (full)
reindex <table> Reindex table
cluster <table> Cluster table
=== Backup & Restore ===
backup_database [output_dir] Backup entire database
backup_schema <schema> [output_dir] Backup schema
backup_table <table> [output_dir] Backup single table
restore <backup_file> [target_db] Restore from backup
=== Data Analysis ===
rowcount <table> Get row count of a table
all_row_counts Row counts for all tables
largest_tables Show largest tables
table_growth_report Table growth and activity report
=== Monitoring & Health ===
health_check Complete health check
resource_usage Resource usage summary
query_performance_summary Query performance summary
session_summary Session summary
transaction_status Transaction status monitoring
lock_summary Lock summary
temp_tables Temporary table usage
unlogged_tables Unlogged tables
partitioned_tables Partitioned tables
server_uptime Server uptime
replication_status Replication status
checkpoint_history Checkpoint history
=== Advanced Index Analysis ===
index_usage_summary Detailed index usage
missing_indexes_detailed Detailed missing indexes
=== Schema Info ===
function_dependencies Function dependencies
constraint_info Constraint information
enum_types Enum types
composite_types Composite types
search_path Show search path
set_search_path Set search path
=== Utility ===
export_csv <query> <output> Export query to CSV
list_databases List all databases
list_schemas List all schemas
list_extensions List installed extensions
Examples:
$EXEC_NAME sessions
$EXEC_NAME running
$EXEC_NAME blocked
$EXEC_NAME table_size my%
$EXEC_NAME explain "SELECT * FROM users WHERE id = 1"
$EXEC_NAME top_time -n 20
$EXEC_NAME repeat 5 10 sessions
Environment Variables:
PGHOST, PGPORT, PGUSER, PGDATABASE, PGPASSWORD
Password Options (to avoid typing password):
1. Set PGPASSWORD environment variable:
export PGPASSWORD=your_password
2. Create ~/.pgpass file with correct permissions:
echo "localhost:5432:*:username:password" > ~/.pgpass
chmod 600 ~/.pgpass
Format: hostname:port:database:username:password
3. Use -P option to specify a password file:
$EXEC_NAME -P /path/to/password.txt sessions
EOF
exit 1
}
# Parse command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
-h|--host)
DBHOST="$2"
shift 2
;;
-p|--port)
DBPORT="$2"
shift 2
;;
-u|--user)
DBUSER="$2"
shift 2
;;
-d|--dbname)
DBNAME="$2"
shift 2
;;
-P|--password-file)
USE_PASSWORD_FILE="$2"
shift 2
;;
-n|--top)
TOP_N="$2"
shift 2
;;
--help)
usage
;;
*)
break
;;
esac
done
# Build psql command with password handling
# Use -w/--no-password when password is configured via env var or file
if [ -n "$PGPASSWORD" ] || [ -n "$PGPASSFILE" ] || [ -n "$USE_PASSWORD_FILE" ]; then
PSQL_CMD="psql -h $DBHOST -p $DBPORT -U $DBUSER -d $DBNAME -w"
else
PSQL_CMD="psql -h $DBHOST -p $DBPORT -U $DBUSER -d $DBNAME"
fi
# Check if we can connect
get_version
if [ $# -lt 1 ]; then
usage
fi
COMMAND="$1"
shift
# ============================================
# PARAMETER PARSING HELPER FUNCTIONS
# ============================================
# Parse schema/database/table parameters for flexible queries
# Usage: parse_params "$@"
# Sets global vars: PARAM_DB, PARAM_SCHEMA, PARAM_TABLE, PARAM_PATTERN
parse_params()
{
PARAM_DB=""
PARAM_SCHEMA=""
PARAM_TABLE=""
PARAM_PATTERN=""
local last_arg=""
while [ $# -gt 0 ]; do
case "$1" in
-d|--database)
if [ $# -lt 2 ]; then
echo "Error: -d requires a database name" >&2
return 1
fi
PARAM_DB="$2"
shift 2
;;
-s|--schema)
if [ $# -lt 2 ]; then
echo "Error: -s requires a schema name" >&2
return 1
fi
PARAM_SCHEMA="$2"
shift 2
;;
-t|--table)
if [ $# -lt 2 ]; then
echo "Error: -t requires a table name" >&2
return 1
fi
PARAM_TABLE="$2"
shift 2
;;
*)
last_arg="$1"
shift
;;
esac
done
# Last positional arg becomes pattern (if provided)
if [ -n "$last_arg" ]; then
PARAM_PATTERN="$last_arg"
fi
}
# Build WHERE clause fragment for schema filtering
# Usage: build_schema_where_clause "tablename"
# Returns: WHERE clause fragment (empty if no schema specified)
build_schema_where_clause()
{
local table_alias="${1:-.}"
if [ -n "$PARAM_SCHEMA" ]; then
# Sanitize schema name to prevent SQL injection
local sanitized_schema=$(echo "$PARAM_SCHEMA" | sed 's/[^a-zA-Z0-9_]/_/g')
echo "AND ${table_alias}schemaname = '$sanitized_schema'"
fi
}
# Build WHERE clause fragment for table/pattern filtering
build_table_where_clause()
{
local table_alias="${1:-.}"
if [ -n "$PARAM_TABLE" ]; then
# Sanitize table name to prevent SQL injection
local sanitized_table=$(echo "$PARAM_TABLE" | sed 's/[^a-zA-Z0-9_]/_/g')
echo "AND ${table_alias}tablename = '$sanitized_table'"
elif [ -n "$PARAM_PATTERN" ]; then
# Sanitize pattern to prevent SQL injection
local sanitized_pattern=$(echo "$PARAM_PATTERN" | sed "s/'/''/g" | sed 's/[^a-zA-Z0-9_ %]/_/g')
echo "AND ${table_alias}tablename LIKE '%${sanitized_pattern}%'"
fi
}
# Get PSQL_CMD for specific database (if -d specified, create new connection)
get_psql_for_db()
{
if [ -n "$PARAM_DB" ]; then
if [ -n "$PGPASSWORD" ] || [ -n "$PGPASSFILE" ] || [ -n "$USE_PASSWORD_FILE" ]; then
echo "psql -h $DBHOST -p $DBPORT -U $DBUSER -d \"$PARAM_DB\" -w"
else
echo "psql -h $DBHOST -p $DBPORT -U $DBUSER -d \"$PARAM_DB\""
fi
else
echo "$PSQL_CMD"
fi
}
# pg_stat_statements column detection (version compatibility)
init_pg_stat_statements_columns()
{
if [ -n "$PGS_TOTAL_COL" ] && [ -n "$PGS_MEAN_COL" ] && [ -n "$PGS_MAX_COL" ]; then
return 0
fi
local rel_exists
rel_exists=$(echo "SELECT 1 FROM pg_class WHERE relname = 'pg_stat_statements' AND relkind IN ('v','r');" | $PSQL_CMD -t -A 2>/dev/null)
if [ -z "$rel_exists" ]; then
return 1
fi
local has_new
has_new=$(echo "SELECT 1 FROM pg_attribute WHERE attrelid = 'pg_stat_statements'::regclass AND attname = 'total_exec_time';" | $PSQL_CMD -t -A 2>/dev/null)
if [ -n "$has_new" ]; then
PGS_TOTAL_COL="total_exec_time"
PGS_MEAN_COL="mean_exec_time"
PGS_MAX_COL="max_exec_time"
else
PGS_TOTAL_COL="total_time"
PGS_MEAN_COL="mean_time"
PGS_MAX_COL="max_time"
fi
}
pgs_ms_to_sec_expr()
{
local col="$1"
echo "(${col} / 1000.0)"
}
# ============================================
# SESSION & QUERY MONITORING
# ============================================
cmd_sessions()
{
cat << 'EOF' | $PSQL_CMD -x
SELECT pid,
usename,
application_name,
client_addr,
state,
query_start,
state_change,
wait_event_type,
wait_event,
LEFT(query, 100) AS query_preview
FROM pg_stat_activity
WHERE state IS NOT NULL
ORDER BY query_start;
EOF
}
cmd_running()
{
local limit=${1:-$TOP_N}
cat << EOF | $PSQL_CMD
SELECT pid,
usename,
application_name,
now() - query_start AS duration,
wait_event_type,
wait_event,
LEFT(query, 200) AS query
FROM pg_stat_activity
WHERE state = 'active'
AND query NOT LIKE '%pg_stat_activity%'
ORDER BY query_start
LIMIT $limit;
EOF
}
cmd_blocked()
{
cat << 'EOF' | $PSQL_CMD
SELECT blocked_locks.pid AS blocked_pid,
blocked_activity.usename AS blocked_user,
blocking_locks.pid AS blocking_pid,
blocking_activity.usename AS blocking_user,
blocked_activity.query AS blocked_statement,
blocking_activity.query AS current_statement_in_blocking_process,
blocked_activity.application_name AS blocked_application,
blocking_activity.application_name AS blocking_application
FROM pg_catalog.pg_locks blocked_locks
JOIN pg_catalog.pg_stat_activity blocked_activity ON blocked_activity.pid = blocked_locks.pid
JOIN pg_catalog.pg_locks blocking_locks
ON blocking_locks.locktype = blocked_locks.locktype
AND blocking_locks.DATABASE IS NOT DISTINCT FROM blocked_locks.DATABASE
AND blocking_locks.relation IS NOT DISTINCT FROM blocked_locks.relation
AND blocking_locks.page IS NOT DISTINCT FROM blocked_locks.page
AND blocking_locks.tuple IS NOT DISTINCT FROM blocked_locks.tuple
AND blocking_locks.virtualxid IS NOT DISTINCT FROM blocked_locks.virtualxid
AND blocking_locks.transactionid IS NOT DISTINCT FROM blocked_locks.transactionid
AND blocking_locks.classid IS NOT DISTINCT FROM blocked_locks.classid
AND blocking_locks.objid IS NOT DISTINCT FROM blocked_locks.objid
AND blocking_locks.objsubid IS NOT DISTINCT FROM blocked_locks.objsubid
AND blocking_locks.pid != blocked_locks.pid
JOIN pg_catalog.pg_stat_activity blocking_activity ON blocking_activity.pid = blocking_locks.pid
WHERE NOT blocked_locks.GRANTED;
EOF
}
cmd_locks()
{
cat << 'EOF' | $PSQL_CMD
SELECT t.schemaname||'.'||t.relname AS relation,
l.locktype,
l.mode,
l.granted,
a.usename,
a.query,
a.pid
FROM pg_locks l
JOIN pg_stat_activity a ON l.pid = a.pid
LEFT JOIN pg_class t ON l.relation = t.oid
WHERE l.relation IS NOT NULL
ORDER BY relation;
EOF
}
cmd_kill()
{
local pid=$1
if [ -z "$pid" ]; then
echo "Usage: $EXEC_NAME kill <pid>"
exit 1
fi
# Validate PID is numeric to prevent SQL injection
if ! echo "$pid" | grep -q '^[0-9]\+$'; then
echo "Error: PID must be a number"
exit 1
fi
echo "SELECT pg_terminate_backend($pid);" | $PSQL_CMD
}
cmd_cancel()
{
local pid=$1
if [ -z "$pid" ]; then
echo "Usage: $EXEC_NAME cancel <pid>"
exit 1
fi
# Validate PID is numeric to prevent SQL injection
if ! echo "$pid" | grep -q '^[0-9]\+$'; then
echo "Error: PID must be a number"
exit 1
fi
echo "SELECT pg_cancel_backend($pid);" | $PSQL_CMD
}
# ============================================
# QUERY ANALYSIS
# ============================================
cmd_fulltext()
{
local pid=$1
if [ -z "$pid" ]; then
echo "Usage: $EXEC_NAME fulltext <pid>"
exit 1
fi
# Validate PID is numeric to prevent SQL injection
if ! echo "$pid" | grep -q '^[0-9]\+$'; then
echo "Error: PID must be a number"
exit 1
fi
cat << EOF | $PSQL_CMD
SELECT pid, query
FROM pg_stat_activity
WHERE pid = $pid;
EOF
}
cmd_explain()
{
local sql="$*"
if [ -z "$sql" ]; then
echo "Usage: $EXEC_NAME explain \"<SQL>\""
exit 1
fi
echo "EXPLAIN $sql" | $PSQL_CMD
}
cmd_explain_analyze()
{
local sql="$*"
if [ -z "$sql" ]; then
echo "Usage: $EXEC_NAME explain_analyze \"<SQL>\""
exit 1
fi
echo "EXPLAIN (ANALYZE, BUFFERS, VERBOSE) $sql" | $PSQL_CMD
}
cmd_query_stats()
{
local limit=${1:-$TOP_N}
execute_with_extension_check "pg_stat_statements" "$(get_stat_statements_query "total_exec_time" "$limit" "" "")" "pg_stat_statements extension is not installed."
}
cmd_top_calls()
{
local limit=${1:-$TOP_N}
execute_with_extension_check "pg_stat_statements" "$(get_stat_statements_query "calls" "$limit" "" "")" "pg_stat_statements extension is not installed."
}
cmd_top_time()
{
local limit=${1:-$TOP_N}
execute_with_extension_check "pg_stat_statements" "$(get_stat_statements_query "total_exec_time" "$limit" "" "")" "pg_stat_statements extension is not installed."
}
cmd_top_rows()
{
local limit=${1:-$TOP_N}
execute_with_extension_check "pg_stat_statements" "$(get_stat_statements_query "rows" "$limit" "" "")" "pg_stat_statements extension is not installed."
}
cmd_buffer_stats()
{
local limit=${1:-$TOP_N}
cat << EOF | $PSQL_CMD
SELECT relid::regclass AS relation,
heap_blks_read,
heap_blks_hit,
round(heap_blks_hit::numeric / NULLIF(heap_blks_read + heap_blks_hit, 0) * 100, 2) AS cache_hit_ratio,
idx_blks_read,
idx_blks_hit,
round(idx_blks_hit::numeric / NULLIF(idx_blks_read + idx_blks_hit, 0) * 100, 2) AS idx_cache_hit_ratio
FROM pg_statio_user_tables
ORDER BY heap_blks_read DESC
LIMIT $limit;
EOF
}
# ============================================
# PERFORMANCE & STATISTICS
# ============================================
cmd_pg_stat_activity()
{
cat << 'EOF' | $PSQL_CMD
SELECT pid,
datname,
usename,
application_name,
client_addr,
state,
query_start,
state_change,
wait_event_type,
wait_event,
LEFT(query, 200) AS query
FROM pg_stat_activity
ORDER BY state, query_start;
EOF
}
cmd_pg_stat_database()
{
cat << 'EOF' | $PSQL_CMD
SELECT datname,
numbackends,
xact_commit,
xact_rollback,
blks_read,
blks_hit,
tup_returned,
tup_fetched,
tup_inserted,
tup_updated,
tup_deleted,
conflicts,
temp_files,
temp_bytes,
deadlocks
FROM pg_stat_database
ORDER BY datname;
EOF
}
cmd_pg_stat_tables()
{
local limit=${1:-$TOP_N}
get_stat_table "user_tables" "" "$limit" "" | $PSQL_CMD
}
cmd_pg_stat_indexes()
{
local limit=${1:-$TOP_N}
get_stat_table "user_indexes" "" "$limit" "" | $PSQL_CMD
}
cmd_pg_stat_functions()
{
local limit=${1:-$TOP_N}
get_stat_table "user_functions" "" "$limit" "" | $PSQL_CMD
}
cmd_pg_stat_replication()
{
cat << 'EOF' | $PSQL_CMD
SELECT pid,
usesysid,
usename,
application_name,
client_addr,
client_hostname,
client_port,
backend_start,
state,
sent_lsn,
write_lsn,
flush_lsn,
replay_lsn,
sync_state
FROM pg_stat_replication;
EOF
}
# ============================================
# MEMORY & CACHE
# ============================================
cmd_pg_buffercache()
{
# Check if pg_buffercache extension exists
local extension_check=$(echo "SELECT 1 FROM pg_extension WHERE extname = 'pg_buffercache';" | $PSQL_CMD -t -A 2>/dev/null)
if [ -z "$extension_check" ]; then
echo "Error: pg_buffercache extension is not installed."
echo "Run: CREATE EXTENSION pg_buffercache;"
return 1
fi
cat << 'EOF' | $PSQL_CMD
SELECT c.relname,
count(*) AS buffers,
round(count(*) * 8.0 / 1024, 2) AS MB
FROM pg_buffercache b
JOIN pg_class c ON b.relfilenode = c.relfilenode
GROUP BY c.relname
ORDER BY buffers DESC
LIMIT 20;
EOF
}
cmd_pg_cache()
{
cat << 'EOF' | $PSQL_CMD
SELECT heap_blks_read,
heap_blks_hit,
round(heap_blks_hit::numeric / NULLIF(heap_blks_read + heap_blks_hit, 0) * 100, 2) AS heap_hit_ratio,
idx_blks_read,
idx_blks_hit,
round(idx_blks_hit::numeric / NULLIF(idx_blks_read + idx_blks_hit, 0) * 100, 2) AS idx_hit_ratio,
toast_blks_read,
toast_blks_hit,
round(toast_blks_hit::numeric / NULLIF(toast_blks_read + toast_blks_hit, 0) * 100, 2) AS toast_hit_ratio,
tidx_blks_read,
tidx_blks_hit,
round(tidx_blks_hit::numeric / NULLIF(tidx_blks_read + tidx_blks_hit, 0) * 100, 2) AS tidx_hit_ratio
FROM pg_stat_database
WHERE datname = current_database();
EOF
}
cmd_shared_buffers()
{
cat << 'EOF' | $PSQL_CMD
SELECT name,
setting,
unit,
source
FROM pg_settings
WHERE name = 'shared_buffers';
EOF
}
# ============================================
# TABLE & INDEX ANALYSIS
# ============================================
cmd_table_size()
{
if ! parse_params "$@"; then
return 1
fi
local cmd=$(get_psql_for_db)
local schema_filter=$(build_schema_where_clause "t.")
local table_filter=$(build_table_where_clause "t.")
# Build combined filter
local combined_filter=""
if [ -n "$schema_filter" ]; then
combined_filter="$schema_filter"
fi
if [ -n "$table_filter" ]; then
combined_filter="$combined_filter $table_filter"
fi
get_size_query "table" "" "$combined_filter" "" | $cmd
}
cmd_index_size()
{
if ! parse_params "$@"; then
return 1
fi
local cmd=$(get_psql_for_db)
local schema_filter=$(build_schema_where_clause "i.")
local table_filter=$(build_table_where_clause "i.")
cat << EOF | $cmd
SELECT i.schemaname,
i.tablename,
i.indexname,
pg_size_pretty(pg_relation_size(i.indexrelid)) AS index_size
FROM pg_stat_user_indexes i
WHERE i.schemaname NOT IN ('pg_catalog', 'information_schema')
$schema_filter
$table_filter
ORDER BY pg_relation_size(i.indexrelid) DESC;
EOF
}
cmd_bloat_tables()
{
if ! parse_params "$@"; then
return 1
fi
local cmd=$(get_psql_for_db)
local limit=${PARAM_PATTERN:-$TOP_N}
local schema_filter=$(build_schema_where_clause "t.")
cat << EOF | $cmd
SELECT t.schemaname,
t.tablename,
pg_size_pretty(pg_total_relation_size(t.schemaname||'.'||t.tablename)) AS total_size,
t.n_dead_tup,
t.n_live_tup,
round(t.n_dead_tup::numeric / NULLIF(t.n_live_tup, 0) * 100, 2) AS dead_ratio
FROM pg_stat_user_tables t
WHERE t.n_dead_tup > 0
AND t.schemaname NOT IN ('pg_catalog', 'information_schema')
$schema_filter
ORDER BY t.n_dead_tup DESC
LIMIT $limit;
EOF
}
cmd_bloat_indexes()
{
if ! parse_params "$@"; then
return 1
fi
local cmd=$(get_psql_for_db)
local limit=${PARAM_PATTERN:-$TOP_N}
local schema_filter=$(build_schema_where_clause "i.")
cat << EOF | $cmd
SELECT i.schemaname,
i.tablename,
i.indexname,