| 1 | package DBIx::Fast::Profile::Pg; | ||
| 2 | |||
| 3 | use v5.38; | ||
| 4 | use Object::Pad 0.807; | ||
| 5 | |||
| 6 | our $VERSION = '0.22'; | ||
| 7 | |||
| 8 | class DBIx::Fast::Profile::Pg :isa(DBIx::Fast::Profile::Base) { | ||
| 9 | |||
| 10 | method init () { | ||
| 11 | # Nothing to enable server-side: pg_stat_* views are always available. | ||
| 12 | } | ||
| 13 | |||
| 14 | # Same allowlist strategy as Profile::MariaDB, tuned for PostgreSQL: | ||
| 15 | # only DML/CTE heads, no terminators or comments, and no file/DoS | ||
| 16 | # functions. String literals are stripped under BOTH quoting conventions | ||
| 17 | # (standard_conforming_strings on and off) before scanning, so a crafted | ||
| 18 | # literal cannot hide a token in either server mode. | ||
| 19 | method _validate_explainable_sql ($sql_text) { | ||
| 20 | return unless defined $sql_text && length $sql_text; | ||
| 21 | |||
| 22 | $sql_text =~ s/^\s+|\s+$//g; | ||
| 23 | |||
| 24 | return unless $sql_text =~ /^(?:SELECT|INSERT|UPDATE|DELETE|TABLE|WITH|VALUES)\b/i; | ||
| 25 | |||
| 26 | return if $sql_text =~ m{;|--|/\*|\$\w*\$}; # terminators / comments / dollar-quoting | ||
| 27 | |||
| 28 | my @bare; | ||
| 29 | (my $b1 = $sql_text) =~ s/'(?:[^'\\]|\\.)*'//g; # backslash-escape parsing | ||
| 30 | $b1 =~ s/"(?:[^"\\]|\\.)*"//g; | ||
| 31 | (my $b2 = $sql_text) =~ s/'[^']*'//g; # standard_conforming_strings | ||
| 32 | $b2 =~ s/"[^"]*"//g; | ||
| 33 | |||
| 34 | for my $bare ($b1, $b2) { | ||
| 35 | # File access / server-side reads and writes | ||
| 36 | return if $bare =~ /\bpg_(?:read_file|read_binary_file|ls_dir|stat_file)\b/i; | ||
| 37 | return if $bare =~ /\blo_(?:import|export)\b/i; | ||
| 38 | # EXPLAIN-time DoS | ||
| 39 | return if $bare =~ /\bpg_sleep(?:_for|_until)?\s*\(/i; | ||
| 40 | return if $bare =~ /\bpg_advisory_lock\w*\s*\(/i; | ||
| 41 | # Remote execution | ||
| 42 | return if $bare =~ /\bdblink\w*\s*\(/i; | ||
| 43 | } | ||
| 44 | |||
| 45 | return $sql_text; | ||
| 46 | } | ||
| 47 | |||
| 48 | # Returns the plan as an arrayref of hashrefs with a single QUERY PLAN | ||
| 49 | # column (PostgreSQL's native EXPLAIN output, one row per plan line). | ||
| 50 | # Plain EXPLAIN never executes the statement. | ||
| 51 | method explain_query ($sql, @params) { | ||
| 52 | my $safe = $self->_validate_explainable_sql($sql); | ||
| 53 | return unless $safe; | ||
| 54 | return $self->dbix->all( "EXPLAIN $safe", @params ); | ||
| 55 | } | ||
| 56 | |||
| 57 | # Key names mirror Profile::MariaDB::get_table_stats where an equivalent | ||
| 58 | # exists (table_name/table_rows/data_length/index_length); engine is the | ||
| 59 | # table access method (heap unless a custom AM is in use). | ||
| 60 | method get_table_stats ($table) { | ||
| 61 | return $self->dbix->all(q{ | ||
| 62 | SELECT c.relname AS table_name, | ||
| 63 | am.amname AS engine, | ||
| 64 | c.reltuples::bigint AS table_rows, | ||
| 65 | pg_table_size(c.oid) AS data_length, | ||
| 66 | pg_indexes_size(c.oid) AS index_length | ||
| 67 | FROM pg_class c | ||
| 68 | JOIN pg_namespace n ON n.oid = c.relnamespace | ||
| 69 | LEFT JOIN pg_am am ON am.oid = c.relam | ||
| 70 | WHERE c.relname = ? | ||
| 71 | AND n.nspname = current_schema() | ||
| 72 | }, $table); | ||
| 73 | } | ||
| 74 | |||
| 75 | method get_index_stats ($table) { | ||
| 76 | return $self->dbix->all(q{ | ||
| 77 | SELECT i.relname AS index_name, | ||
| 78 | a.attname AS column_name, | ||
| 79 | array_position(ix.indkey, a.attnum) + 1 AS seq_in_index, | ||
| 80 | s.idx_scan AS scans | ||
| 81 | FROM pg_index ix | ||
| 82 | JOIN pg_class i ON i.oid = ix.indexrelid | ||
| 83 | JOIN pg_class t ON t.oid = ix.indrelid | ||
| 84 | JOIN pg_namespace n ON n.oid = t.relnamespace | ||
| 85 | JOIN pg_attribute a ON a.attrelid = t.oid | ||
| 86 | AND a.attnum = ANY (ix.indkey) | ||
| 87 | LEFT JOIN pg_stat_user_indexes s ON s.indexrelid = ix.indexrelid | ||
| 88 | WHERE t.relname = ? | ||
| 89 | AND n.nspname = current_schema() | ||
| 90 | ORDER BY i.relname, seq_in_index | ||
| 91 | }, $table); | ||
| 92 | } | ||
| 93 | |||
| 94 | # Global = pg_stat_database counters for the current database. | ||
| 95 | # Session = the current backend's row from pg_stat_activity. | ||
| 96 | method get_stats () { | ||
| 97 | my $global = $self->dbix->hash(q{ | ||
| 98 | SELECT xact_commit, xact_rollback, | ||
| 99 | blks_read, blks_hit, | ||
| 100 | tup_returned, tup_fetched, | ||
| 101 | tup_inserted, tup_updated, tup_deleted, | ||
| 102 | deadlocks, temp_files, temp_bytes | ||
| 103 | FROM pg_stat_database | ||
| 104 | WHERE datname = current_database() | ||
| 105 | }); | ||
| 106 | |||
| 107 | my $session = $self->dbix->hash(q{ | ||
| 108 | SELECT state, backend_start, xact_start, query_start | ||
| 109 | FROM pg_stat_activity | ||
| 110 | WHERE pid = pg_backend_pid() | ||
| 111 | }); | ||
| 112 | |||
| 113 | return { global => $global // {}, session => $session // {} }; | ||
| 114 | } | ||
| 115 | |||
| 116 | method print_stats () { | ||
| 117 | my $stats = $self->get_stats; | ||
| 118 | # json/callback consumers also get the session block text mode omits. | ||
| 119 | return if $self->emit( stats => $stats ); | ||
| 120 | |||
| 121 | $self->out("PostgreSQL Statistics (current database):\n"); | ||
| 122 | for my $k (sort keys %{ $stats->{global} }) { | ||
| 123 | $self->outf(" %-14s: %s\n", $k, $stats->{global}{$k} // 0); | ||
| 124 | } | ||
| 125 | } | ||
| 126 | |||
| 127 | # Same keys as Profile::MariaDB::get_current_connections. | ||
| 128 | method get_current_connections () { | ||
| 129 | return $self->dbix->hash(q{ | ||
| 130 | SELECT COUNT(*) AS total_connections, | ||
| 131 | COUNT(*) FILTER (WHERE state = 'active') AS active, | ||
| 132 | COUNT(*) FILTER (WHERE state LIKE 'idle%') AS sleeping | ||
| 133 | FROM pg_stat_activity | ||
| 134 | WHERE datname = current_database() | ||
| 135 | }); | ||
| 136 | } | ||
| 137 | |||
| 138 | method get_processes () { | ||
| 139 | return $self->dbix->all(q{ | ||
| 140 | SELECT pid AS id, | ||
| 141 | usename AS "user", | ||
| 142 | COALESCE(client_addr::text, 'local') AS host, | ||
| 143 | datname AS db, | ||
| 144 | state, | ||
| 145 | EXTRACT(EPOCH FROM (now() - query_start))::int AS seconds_running, | ||
| 146 | query | ||
| 147 | FROM pg_stat_activity | ||
| 148 | WHERE datname = current_database() | ||
| 149 | ORDER BY query_start | ||
| 150 | }); | ||
| 151 | } | ||
| 152 | |||
| 153 | # Requires the pg_stat_statements extension; returns an empty arrayref | ||
| 154 | # when it is not installed instead of dying. | ||
| 155 | method get_slow_queries () { | ||
| 156 | my $rows = eval { | ||
| 157 | $self->dbix->all(q{ | ||
| 158 | SELECT query AS sql_text, | ||
| 159 | calls AS stages, | ||
| 160 | total_exec_time / 1000 AS total_time | ||
| 161 | FROM pg_stat_statements | ||
| 162 | WHERE total_exec_time / 1000 > ? | ||
| 163 | ORDER BY total_exec_time DESC | ||
| 164 | LIMIT 20 | ||
| 165 | }, $self->slow_query); | ||
| 166 | }; | ||
| 167 | return $rows // []; | ||
| 168 | } | ||
| 169 | } | ||
| 170 | |||
| 171 | 1; | ||
| 172 | |||
| 173 | __END__ |