{"id":13411680,"url":"https://github.com/pawurb/rails-pg-extras","last_synced_at":"2025-05-13T19:08:25.921Z","repository":{"id":37733911,"uuid":"230088868","full_name":"pawurb/rails-pg-extras","owner":"pawurb","description":"Rails PostgreSQL database performance insights. Locks, index usage, buffer cache hit ratios, vacuum stats and more.","archived":false,"fork":false,"pushed_at":"2025-05-02T19:03:09.000Z","size":1390,"stargazers_count":1192,"open_issues_count":0,"forks_count":35,"subscribers_count":6,"default_branch":"main","last_synced_at":"2025-05-06T23:35:38.661Z","etag":null,"topics":["activerecord","postgresql","rails"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pawurb.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2019-12-25T10:53:26.000Z","updated_at":"2025-05-02T19:03:10.000Z","dependencies_parsed_at":"2024-09-24T14:22:11.024Z","dependency_job_id":"a9125ffd-bdd7-43bd-a24d-dcadb1809d46","html_url":"https://github.com/pawurb/rails-pg-extras","commit_stats":{"total_commits":169,"total_committers":13,"mean_commits":13.0,"dds":0.5088757396449703,"last_synced_commit":"df673ca9f0da19bf49ca09dbc3ee7ffeaf9469c0"},"previous_names":[],"tags_count":96,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pawurb%2Frails-pg-extras","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pawurb%2Frails-pg-extras/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pawurb%2Frails-pg-extras/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pawurb%2Frails-pg-extras/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pawurb","download_url":"https://codeload.github.com/pawurb/rails-pg-extras/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254010812,"owners_count":21998993,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["activerecord","postgresql","rails"],"created_at":"2024-07-30T20:01:15.699Z","updated_at":"2025-05-13T19:08:25.851Z","avatar_url":"https://github.com/pawurb.png","language":"Ruby","funding_links":[],"categories":["Ruby","Performances","Gems","Uncategorized"],"sub_categories":["Performance Optimization","Uncategorized"],"readme":"# Rails PG Extras [![Gem Version](https://badge.fury.io/rb/rails-pg-extras.svg)](https://badge.fury.io/rb/rails-pg-extras) [![GH Actions](https://github.com/pawurb/rails-pg-extras/actions/workflows/ci.yml/badge.svg)](https://github.com/pawurb/rails-pg-extras/actions)\n\nRails port of [Heroku PG Extras](https://github.com/heroku/heroku-pg-extras) with several additions and improvements. The goal of this project is to provide powerful insights into the PostgreSQL database for Ruby on Rails apps that are not using the Heroku PostgreSQL plugin.\n\nIncluded rake tasks and Ruby methods can be used to obtain information about a Postgres instance, that may be useful when analyzing performance issues. This includes information about locks, index usage, buffer cache hit ratios and vacuum statistics. Ruby API enables developers to easily integrate the tool into e.g. automatic monitoring tasks.\n\nYou can read this blog post for detailed step by step tutorial on how to [optimize PostgreSQL using PG Extras library](https://pawelurbanek.com/postgresql-fix-performance).\n\n**Shameless plug:** rails-pg-extras is just one of the tools that I use when conducting [Rails performance audits](https://pawelurbanek.com/optimize-rails-performance). Check out my offer if you need help with optimizing your application.\n\nOptionally you can enable a visual interface:\n\n![Web interface](https://github.com/pawurb/rails-pg-extras/raw/main/pg-extras-ui-3.png)\n\nAlternative versions:\n\n- Core dependency - [Ruby](https://github.com/pawurb/ruby-pg-extras)\n\n- [Rust](https://github.com/pawurb/rust-pg-extras)\n\n- [NodeJS](https://github.com/pawurb/node-postgres-extras)\n\n- [Elixir](https://github.com/pawurb/ecto_psql_extras)\n\n- [Python Flask](https://github.com/nickjj/flask-pg-extras)\n\n- [Haskell](https://github.com/pawurb/haskell-pg-extras)\n\n## Installation\n\nIn your Gemfile\n\n```ruby\ngem \"rails-pg-extras\"\n```\n\n`calls` and `outliers` queries require [pg_stat_statements](https://www.postgresql.org/docs/current/pgstatstatements.html) extension.\n\nYou can check if it is enabled in your database by running:\n\n```ruby\nRailsPgExtras.extensions\n```\nYou should see the similar line in the output:\n\n```bash\n| pg_stat_statements  | 1.7  | 1.7 | track execution statistics of all SQL statements executed |\n```\n\n`ssl_used` requires `sslinfo` extension, and `buffercache_usage`/`buffercache_usage` queries need `pg_buffercache`. You can enable them all by running:\n\n```ruby\nRailsPgExtras.add_extensions\n```\n\nBy default a primary ActiveRecord database connection is used for running metadata queries, rake tasks and web UI. To connect to a different database you can specify an `ENV['RAILS_PG_EXTRAS_DATABASE_URL']` value in the following format:\n\n```ruby\nENV[\"RAILS_PG_EXTRAS_DATABASE_URL\"] = \"postgresql://postgres:secret@localhost:5432/database_name\"\n```\n\n## Usage\n\nEach command can be used as a rake task, or a directly from the Ruby code.\n\n```bash\nrake pg_extras:cache_hit\n```\n\n```ruby\nRailsPgExtras.cache_hit\n```\n```bash\n+----------------+------------------------+\n|        Index and table hit rate         |\n+----------------+------------------------+\n| name           | ratio                  |\n+----------------+------------------------+\n| index hit rate | 0.97796610169491525424 |\n| table hit rate | 0.96724294813466787989 |\n+----------------+------------------------+\n```\n\n\nBy default the ASCII table is displayed, to change to format you need to specify the `in_format` parameter (`[:display_table, :hash, :array, :raw]` options are available):\n\n```ruby\nRailsPgExtras.cache_hit(in_format: :hash) =\u003e\n\n [{\"name\"=\u003e\"index hit rate\", \"ratio\"=\u003e\"0.97796610169491525424\"}, {\"name\"=\u003e\"table hit rate\", \"ratio\"=\u003e\"0.96724294813466787989\"}]\n\nRailsPgExtras.cache_hit(in_format: :array) =\u003e\n\n [[\"index hit rate\", \"0.97796610169491525424\"], [\"table hit rate\", \"0.96724294813466787989\"]]\n\nRailsPgExtras.cache_hit(in_format: :raw) =\u003e\n\n #\u003cPG::Result:0x00007f75777f7328 status=PGRES_TUPLES_OK ntuples=2 nfields=2 cmd_tuples=2\u003e\n```\n\nSome methods accept an optional `args` param allowing you to customize queries:\n\n```ruby\nRailsPgExtras.long_running_queries(args: { threshold: \"200 milliseconds\" })\n\n```\n\nBy default, queries target the `public` schema of the database. You can specify a different schema by passing the `schema` argument:\n\n```ruby\nRailsPgExtras.table_cache_hit(args: { schema: \"my_schema\" })\n```\n\nYou can customize the default `public` schema by setting `ENV['PG_EXTRAS_SCHEMA']` value.\n\n## Diagnose report\n\nThe simplest way to start using pg-extras is to execute a `diagnose` method. It runs a set of checks and prints out a report highlighting areas that may require additional investigation:\n\n```ruby\nRailsPgExtras.diagnose\n\n$ rake pg_extras:diagnose\n```\n\n![Diagnose report](https://github.com/pawurb/rails-pg-extras/raw/main/rails-pg-extras-diagnose.png)\n\nKeep reading to learn about methods that `diagnose` uses under the hood.\n\n## Visual interface\n\nYou can enable UI using a Rails engine by adding the following code in `config/routes.rb`:\n\n```ruby\n  mount RailsPgExtras::Web::Engine, at: 'pg_extras'\n```\n\nYou can enable HTTP basic auth by specifying `Rails.application.credentials.pg_extras.user` (or `RAILS_PG_EXTRAS_USER`) and `Rails.application.credentials.pg_extras.password` (or `RAILS_PG_EXTRAS_PASSWORD`) values. Authentication is mandatory unless you specify `RAILS_PG_EXTRAS_PUBLIC_DASHBOARD=true` or set `RailsPgExtras.configuration.public_dashboard = true`.\n\nYou can configure available web actions in `config/initializers/rails_pg_extras.rb`:\n\n```ruby\nRailsPgExtras.configure do |config|\n  # Rails-pg-extras does not enable all the web actions by default. You can check all available actions via `RailsPgExtras::Web::ACTIONS`.\n  # For example, you may want to enable the dangerous `kill_all` action.\n\n  config.enabled_web_actions = %i[kill_all pg_stat_statements_reset add_extensions]\nend\n```\n\n## Available methods\n\n### `measure_queries`\n\nThis method displays query types executed when running a provided Ruby snippet, with their avg., min., max., and total duration in miliseconds. It also outputs info about the snippet execution duration and the portion spent running SQL queries (`total_duration`/`sql_duration`). It can help debug N+1 issues and review the impact of configuring eager loading:\n\n```ruby\n\nRailsPgExtras.measure_queries { User.limit(10).map(\u0026:team) }\n\n{:count=\u003e11,\n :queries=\u003e\n  {\"SELECT \\\"users\\\".* FROM \\\"users\\\" LIMIT $1\"=\u003e\n    {:count=\u003e1,\n     :total_duration=\u003e1.9,\n     :min_duration=\u003e1.9,\n     :max_duration=\u003e1.9,\n     :avg_duration=\u003e1.9},\n   \"SELECT \\\"teams\\\".* FROM \\\"teams\\\" WHERE \\\"teams\\\".\\\"id\\\" = $1 LIMIT $2\"=\u003e\n    {:count=\u003e10,\n     :total_duration=\u003e0.94,\n     :min_duration=\u003e0.62,\n     :max_duration=\u003e1.37,\n     :avg_duration=\u003e0.94}},\n :total_duration=\u003e13.35,\n :sql_duration=\u003e11.34}\n\nRailsPgExtras.measure_queries { User.limit(10).includes(:team).map(\u0026:team) }\n\n{:count=\u003e2,\n :queries=\u003e\n  {\"SELECT \\\"users\\\".* FROM \\\"users\\\" LIMIT $1\"=\u003e\n    {:count=\u003e1,\n     :total_duration=\u003e3.43,\n     :min_duration=\u003e3.43,\n     :max_duration=\u003e3.43,\n    :avg_duration=\u003e3.43},\n   \"SELECT \\\"teams\\\".* FROM \\\"teams\\\" WHERE \\\"teams\\\".\\\"id\\\" IN ($1, $2, $3, $4, $5, $6, $7, $8)\"=\u003e\n    {:count=\u003e1,\n     :total_duration=\u003e2.59,\n     :min_duration=\u003e2.59,\n     :max_duration=\u003e2.59,\n     :avg_duration=\u003e2.59}},\n :total_duration=\u003e9.75,\n :sql_duration=\u003e6.02}\n\n```\n\nOptionally, by including [Marginalia gem](https://github.com/basecamp/marginalia) and configuring it to display query backtraces:\n\n`config/development.rb`\n\n```ruby\n\nMarginalia::Comment.components = [:line]\n\n```\n\nyou can add this info to the output:\n\n![Marginalia logs](https://github.com/pawurb/rails-pg-extras/raw/main/marginalia-logs.png)\n\n### `missing_fk_indexes`\n\nThis method lists columns likely to be foreign keys (i.e. column name ending in `_id` and related table exists) which don't have an index. It's recommended to always index foreign key columns because they are used for searching relation objects. \n\nYou can add indexes on the columns returned by this query and later check if they are receiving scans using the [unused_indexes method](#unused_indexes). Please remember that each index decreases write performance and autovacuuming overhead, so be careful when adding multiple indexes to often updated tables.\n\n```ruby\nRailsPgExtras.missing_fk_indexes(args: { table_name: \"users\" })\n\n+---------------------------------+\n| Missing foreign key indexes     |\n+-------------------+-------------+\n| table             | column_name |\n+-------------------+-------------+\n| feedbacks         | team_id     |\n| votes             | user_id     |\n+-------------------+-------------+\n\n```\n\n`table_name` argument is optional, if omitted, the method will display missing fk indexes for all the tables.\n\n## `missing_fk_constraints`\n\nSimilarly to the previous method, this one shows columns likely to be foreign keys that don't have a corresponding foreign key constraint. Foreign key constraints improve data integrity in the database by preventing relations with nonexisting objects. You can read more about the benefits of using foreign keys [in this blog post](https://pawelurbanek.com/rails-postgresql-data-integrity).\n\n```ruby\nRailsPgExtras.missing_fk_constraints(args: { table_name: \"users\" })\n\n+---------------------------------+\n| Missing foreign key constraints |\n+-------------------+-------------+\n| table             | column_name |\n+-------------------+-------------+\n| feedbacks         | team_id     |\n| votes             | user_id     |\n+-------------------+-------------+\n\n```\n\n`table_name` argument is optional, if omitted, method will display missing fk constraints for all the tables.\n\n### `table_schema`\n\nThis method displays structure of a selected table, listing its column names, together with types, null constraints, and default values.\n\n```ruby\nRailsPgExtras.table_schema(args: { table_name: \"users\" })\n\n+-----------------------------+-----------------------------+-------------+-----------------------------------+\n| column_name                 | data_type                   | is_nullable | column_default                    |\n+-----------------------------+-----------------------------+-------------+-----------------------------------+\n| id                          | bigint                      | NO          | nextval('users_id_seq'::regclass) |\n| team_id                     | integer                     | NO          |                                   |\n| slack_id                    | character varying           | NO          |                                   |\n| pseudonym                   | character varying           | YES         |                                   |\n\n```\n\n### `table_info`\n\nThis method displays metadata metrics for all or a selected table. You can use it to check the table's size, its cache hit metrics, and whether it is correctly indexed. Many sequential scans or no index scans are potential indicators of misconfigured indexes. This method aggregates data provided by other methods in an easy to analyze summary format.\n\n```ruby\nRailsPgExtras.table_info(args: { table_name: \"users\" })\n\n| Table name | Table size | Table cache hit   | Indexes cache hit  | Estimated rows | Sequential scans | Indexes scans |\n+------------+------------+-------------------+--------------------+----------------+------------------+---------------+\n| users      | 2432 kB    | 0.999966685701511 | 0.9988780464661853 | 16650          | 2128             | 512496        |\n\n```\n\n### `index_info`\n\nThis method returns summary info about database indexes. You can check index size, how often it is used and what percentage of its total size are NULL values. Like the previous method, it aggregates data from other helper methods in an easy-to-digest format.\n\n```ruby\n\nRailsPgExtras.index_info(args: { table_name: \"users\" })\n\n| Index name                    | Table name | Columns        | Index size | Index scans | Null frac |\n+-------------------------------+------------+----------------+------------+-------------+-----------+\n| users_pkey                    | users      | id             | 1152 kB    | 163007      | 0.00%     |\n| index_users_on_slack_id       | users      | slack_id       | 1080 kB    | 258870      | 0.00%     |\n| index_users_on_team_id        | users      | team_id        | 816 kB     | 70962       | 0.00%     |\n| index_users_on_uuid           | users      | uuid           | 1032 kB    | 0           | 0.00%     |\n| index_users_on_block_uuid     | users      | block_uuid     | 776 kB     | 19502       | 100.00%   |\n| index_users_on_api_auth_token | users      | api_auth_token | 1744 kB    | 156         | 0.00%     |\n\n```\n\n### `cache_hit`\n\n```ruby\nRailsPgExtras.cache_hit\n\n$ rake pg_extras:cache_hit\n\n      name      |         ratio\n----------------+------------------------\n index hit rate | 0.99957765013541945832\n table hit rate |                   1.00\n(2 rows)\n```\n\nThis command provides information on the efficiency of the buffer cache, for both index reads (`index hit rate`) as well as table reads (`table hit rate`). A low buffer cache hit ratio can be a sign that the Postgres instance is too small for the workload.\n\n[More info](https://pawelurbanek.com/postgresql-fix-performance#cache-hit)\n\n### `index_cache_hit`\n\n```ruby\n\nRailsPgExtras.index_cache_hit\n\n$ rake pg_extras:index_cache_hit\n\n| name                  | buffer_hits | block_reads | total_read | ratio             |\n+-----------------------+-------------+-------------+------------+-------------------+\n| teams                 | 187665      | 109         | 187774     | 0.999419514948821 |\n| subscriptions         | 5160        | 6           | 5166       | 0.99883855981417  |\n| plans                 | 5718        | 9           | 5727       | 0.998428496595076 |\n(truncated results for brevity)\n```\n\nThe same as `cache_hit` with each table's indexes cache hit info displayed separately.\n\n[More info](https://pawelurbanek.com/postgresql-fix-performance#cache-hit)\n\n### `table_cache_hit`\n\n```ruby\n\nRailsPgExtras.table_cache_hit\n\n$ rake pg_extras:table_cache_hit\n\n| name                  | buffer_hits | block_reads | total_read | ratio             |\n+-----------------------+-------------+-------------+------------+-------------------+\n| plans                 | 32123       | 2           | 32125      | 0.999937743190662 |\n| subscriptions         | 95021       | 8           | 95029      | 0.999915815172211 |\n| teams                 | 171637      | 200         | 171837     | 0.99883610631005  |\n(truncated results for brevity)\n```\n\nThe same as `cache_hit` with each table's cache hit info displayed seperately.\n\n[More info](https://pawelurbanek.com/postgresql-fix-performance#cache-hit)\n\n### `db_settings`\n\n```ruby\n\nRailsPgExtras.db_settings\n\n$ rake pg_extras:db_settings\n\n             name             | setting | unit |\n------------------------------+---------+------+\n checkpoint_completion_target | 0.7     |      |\n default_statistics_target    | 100     |      |\n effective_cache_size         | 1350000 | 8kB  |\n effective_io_concurrency     | 1       |      |\n(truncated results for brevity)\n\n```\n\nThis method displays values for selected PostgreSQL settings. You can compare them with settings recommended by [PGTune](https://pgtune.leopard.in.ua/#/) and tweak values to improve performance.\n\n[More info](https://pawelurbanek.com/postgresql-fix-performance#cache-hit)\n\n### `ssl_used`\n\n```ruby\n\nRailsPgExtras.ssl_used\n\n| ssl_is_used                     |\n+---------------------------------+\n| t                               |\n\n```\n\nReturns boolean indicating if an encrypted SSL is currently used. Connecting to the database via an unencrypted connection is a critical security risk.\n\n### `index_usage`\n\n```ruby\nRailsPgExtras.index_usage\n\n$ rake pg_extras:index_usage\n\n       relname       | percent_of_times_index_used | rows_in_table\n---------------------+-----------------------------+---------------\n events              |                          65 |       1217347\n app_infos           |                          74 |        314057\n app_infos_user_info |                           0 |        198848\n user_info           |                           5 |         94545\n delayed_jobs        |                          27 |             0\n(5 rows)\n```\n\nThis command provides information on the efficiency of indexes, represented as what percentage of total scans were index scans. A low percentage can indicate under indexing, or wrong data being indexed.\n\n### `locks`\n\n```ruby\nRailsPgExtras.locks(args: { limit: 20 })\n\n$ rake pg_extras:locks\n\n procpid | relname | transactionid | granted |     query_snippet     | mode             |       age        |   application |\n---------+---------+---------------+---------+-----------------------+------------------------------------------------------\n   31776 |         |               | t       | \u003cIDLE\u003e in transaction | ExclusiveLock    |  00:19:29.837898 |  bin/rails\n   31776 |         |          1294 | t       | \u003cIDLE\u003e in transaction | RowExclusiveLock |  00:19:29.837898 |  bin/rails\n   31912 |         |               | t       | select * from hello;  | ExclusiveLock    |  00:19:17.94259  |  bin/rails\n    3443 |         |               | t       |                      +| ExclusiveLock    |  00:00:00        |  bin/sidekiq\n         |         |               |         |    select            +|                  |                  |\n         |         |               |         |      pg_stat_activi   |                  |                  |\n(4 rows)\n```\n\nThis command displays queries that have taken out an exclusive lock on a relation. Exclusive locks typically prevent other operations on that relation from taking place, and can be a cause of \"hung\" queries that are waiting for a lock to be granted.\n\n[More info](https://pawelurbanek.com/postgresql-fix-performance#deadlocks)\n\n### `all_locks`\n\n```ruby\nRailsPgExtras.all_locks\n\n$ rake pg_extras:all_locks\n```\n\nThis command displays all the current locks, regardless of their type.\n\n### `outliers`\n\n```ruby\nRailsPgExtras.outliers(args: { limit: 20 })\n\n$ rake pg_extras:outliers\n\n                   qry                   |    exec_time     | prop_exec_time |   ncalls    | sync_io_time\n-----------------------------------------+------------------+----------------+-------------+--------------\n SELECT * FROM archivable_usage_events.. | 154:39:26.431466 | 72.2%          | 34,211,877  | 00:00:00\n COPY public.archivable_usage_events (.. | 50:38:33.198418  | 23.6%          | 13          | 13:34:21.00108\n COPY public.usage_events (id, reporte.. | 02:32:16.335233  | 1.2%           | 13          | 00:34:19.784318\n INSERT INTO usage_events (id, retaine.. | 01:42:59.436532  | 0.8%           | 12,328,187  | 00:00:00\n SELECT * FROM usage_events WHERE (alp.. | 01:18:10.754354  | 0.6%           | 102,114,301 | 00:00:00\n UPDATE usage_events SET reporter_id =.. | 00:52:35.683254  | 0.4%           | 23,786,348  | 00:00:00\n(truncated results for brevity)\n```\n\nThis command displays statements, obtained from `pg_stat_statements`, ordered by the amount of time to execute in aggregate. This includes the statement itself, the total execution time for that statement, the proportion of total execution time for all statements that statement has taken up, the number of times that statement has been called, and the amount of time that statement spent on synchronous I/O (reading/writing from the file system).\n\nTypically, an efficient query will have an appropriate ratio of calls to total execution time, with as little time spent on I/O as possible. Queries that have a high total execution time but low call count should be investigated to improve their performance. Queries that have a high proportion of execution time being spent on synchronous I/O should also be investigated.\n\n[More info](https://pawelurbanek.com/postgresql-fix-performance#missing-indexes)\n\n### `calls`\n\n```ruby\nRailsPgExtras.calls(args: { limit: 10 })\n\n$ rake pg_extras:calls\n\n                   qry                   |    exec_time     | prop_exec_time |   ncalls    | sync_io_time\n-----------------------------------------+------------------+----------------+-------------+--------------\n SELECT * FROM usage_events WHERE (alp.. | 01:18:11.073333  | 0.6%           | 102,120,780 | 00:00:00\n BEGIN                                   | 00:00:51.285988  | 0.0%           | 47,288,662  | 00:00:00\n COMMIT                                  | 00:00:52.31724   | 0.0%           | 47,288,615  | 00:00:00\n SELECT * FROM  archivable_usage_event.. | 154:39:26.431466 | 72.2%          | 34,211,877  | 00:00:00\n UPDATE usage_events SET reporter_id =.. | 00:52:35.986167  | 0.4%           | 23,788,388  | 00:00:00\n(truncated results for brevity)\n```\n\nThis command is much like `pg:outliers`, but ordered by the number of times a statement has been called.\n\n[More info](https://pawelurbanek.com/postgresql-fix-performance#missing-indexes)\n\n### `blocking`\n\n```ruby\nRailsPgExtras.blocking\n\n$ rake pg_extras:blocking\n\n blocked_pid |    blocking_statement    | blocking_duration | blocking_pid |                                        blocked_statement                           | blocked_duration\n-------------+--------------------------+-------------------+--------------+------------------------------------------------------------------------------------+------------------\n         461 | select count(*) from app | 00:00:03.838314   |        15682 | UPDATE \"app\" SET \"updated_at\" = '2013-03-04 15:07:04.746688' WHERE \"id\" = 12823149 | 00:00:03.821826\n(1 row)\n```\n\nThis command displays statements that are currently holding locks that other statements are waiting to be released. This can be used in conjunction with `pg:locks` to determine which statements need to be terminated in order to resolve lock contention.\n\n[More info](https://pawelurbanek.com/postgresql-fix-performance#deadlocks)\n\n### `total_index_size`\n\n```ruby\nRailsPgExtras.total_index_size\n\n$ rake pg_extras:total_index_size\n\n  size\n-------\n 28194 MB\n(1 row)\n```\n\nThis command displays the total size of all indexes on the database, in MB. It is calculated by taking the number of pages (reported in `relpages`) and multiplying it by the page size (8192 bytes).\n\n### `index_size`\n\n```ruby\nRailsPgExtras.index_size\n\n$ rake pg_extras:index_size\n                             name                              |  size   | schema |\n---------------------------------------------------------------+-------------------\n idx_activity_attemptable_and_type_lesson_enrollment           | 5196 MB | public |\n index_enrollment_attemptables_by_attempt_and_last_in_group    | 4045 MB | public |\n index_attempts_on_student_id                                  | 2611 MB | public |\n enrollment_activity_attemptables_pkey                         | 2513 MB | custom |\n index_attempts_on_student_id_final_attemptable_type           | 2466 MB | custom |\n attempts_pkey                                                 | 2466 MB | custom |\n index_attempts_on_response_id                                 | 2404 MB | public |\n index_attempts_on_enrollment_id                               | 1957 MB | public |\n index_enrollment_attemptables_by_enrollment_activity_id       | 1789 MB | public |\n enrollment_activities_pkey                                    |  458 MB | public |\n(truncated results for brevity)\n```\n\nThis command displays the size of each each index in the database, in MB. It is calculated by taking the number of pages (reported in `relpages`) and multiplying it by the page size (8192 bytes).\n\n### `table_size`\n\n```ruby\nRailsPgExtras.table_size\n\n$ rake pg_extras:table_size\n\n                             name                              |  size   | schema |\n---------------------------------------------------------------+-------------------\n learning_coaches                                              |  196 MB | public |\n states                                                        |  145 MB | public |\n grade_levels                                                  |  111 MB | custom |\n charities_customers                                           |   73 MB | custom |\n charities                                                     |   66 MB | public |\n(truncated results for brevity)\n```\n\nThis command displays the size of each table and materialized view in the database, in MB. It is calculated by using the system administration function `pg_table_size()`, which includes the size of the main data fork, free space map, visibility map and TOAST data.\n\n### `table_indexes_size`\n\n```ruby\nRailsPgExtras.table_indexes_size\n\n$ rake pg_extras:table_indexes_size\n\n                             table                             | indexes_size\n---------------------------------------------------------------+--------------\n learning_coaches                                              |    153 MB\n states                                                        |    125 MB\n charities_customers                                           |     93 MB\n charities                                                     |     16 MB\n grade_levels                                                  |     11 MB\n(truncated results for brevity)\n```\n\nThis command displays the total size of indexes for each table and materialized view, in MB. It is calculated by using the system administration function `pg_indexes_size()`.\n\n### `total_table_size`\n\n```ruby\nRailsPgExtras.total_table_size\n\n$ rake pg_extras:total_table_size\n\n                             name                              |  size\n---------------------------------------------------------------+---------\n learning_coaches                                              |  349 MB\n states                                                        |  270 MB\n charities_customers                                           |  166 MB\n grade_levels                                                  |  122 MB\n charities                                                     |   82 MB\n(truncated results for brevity)\n```\n\nThis command displays the total size of each table and materialized view in the database, in MB. It is calculated by using the system administration function `pg_total_relation_size()`, which includes table size, total index size and TOAST data.\n\n### `unused_indexes`\n\n```ruby\nRailsPgExtras.unused_indexes(args: { max_scans: 50 })\n\n$ rake pg_extras:unused_indexes\n\n          table      |                       index                | index_size | index_scans\n---------------------+--------------------------------------------+------------+-------------\n public.grade_levels | index_placement_attempts_on_grade_level_id | 97 MB      |           0\n public.observations | observations_attrs_grade_resources         | 33 MB      |           0\n public.messages     | user_resource_id_idx                       | 12 MB      |           0\n(3 rows)\n```\n\nThis command displays indexes that have \u003c 50 scans recorded against them, and are greater than 5 pages in size, ordered by size relative to the number of index scans. This command is generally useful for eliminating indexes that are unused, which can impact write performance, as well as read performance should they occupy space in memory.\n\n[More info](https://pawelurbanek.com/postgresql-fix-performance#unused-indexes)\n\n### `duplicate_indexes`\n\n```ruby\n\nRailsPgExtras.duplicate_indexes\n\n| size       |  idx1        |  idx2          |  idx3    |  idx4     |\n+------------+--------------+----------------+----------+-----------+\n| 128 k      | users_pkey   | index_users_id |          |           |\n```\n\nThis command displays multiple indexes that have the same set of columns, same opclass, expression and predicate - which make them equivalent. Usually it's safe to drop one of them.\n\n### `null_indexes`\n\n```ruby\n\nRailsPgExtras.null_indexes(args: { min_relation_size_mb: 10 })\n\n$ rake pg_extras:null_indexes\n\n   oid   |         index      | index_size | unique | indexed_column | null_frac | expected_saving\n---------+--------------------+------------+--------+----------------+-----------+-----------------\n  183764 | users_reset_token  | 1445 MB    | t      | reset_token    |   97.00%  | 1401 MB\n   88732 | plan_cancelled_at  | 539 MB     | f      | cancelled_at   |    8.30%  | 44 MB\n 9827345 | users_email        | 18 MB      | t      | email          |   28.67%  | 5160 kB\n\n```\n\nThis command displays indexes that contain `NULL` values. A high ratio of `NULL` values means that using a partial index excluding them will be beneficial in case they are not used for searching.\n\n[More info](https://pawelurbanek.com/postgresql-fix-performance#null-indexes)\n\n### `seq_scans`\n\n```ruby\nRailsPgExtras.seq_scans\n\n$ rake pg_extras:seq_scans\n\n               name                |  count\n-----------------------------------+----------\n learning_coaches                  | 44820063\n states                            | 36794975\n grade_levels                      | 13972293\n charities_customers               |  8615277\n charities                         |  4316276\n messages                          |  3922247\n contests_customers                |  2915972\n classroom_goals                   |  2142014\n(truncated results for brevity)\n```\n\nThis command displays the number of sequential scans recorded against all tables, descending by count of sequential scans. Tables that have very high numbers of sequential scans may be under-indexed, and it may be worth investigating queries that read from these tables.\n\n[More info](https://pawelurbanek.com/postgresql-fix-performance#missing-indexes)\n\n### `long_running_queries`\n\n```ruby\nRailsPgExtras.long_running_queries(args: { threshold: \"200 milliseconds\" })\n\n$ rake pg_extras:long_running_queries\n\n  pid  |    duration     |                                      query\n-------+-----------------+---------------------------------------------------------------------------------------\n 19578 | 02:29:11.200129 | EXPLAIN SELECT  \"students\".* FROM \"students\"  WHERE \"students\".\"id\" = 1450645 LIMIT 1\n 19465 | 02:26:05.542653 | EXPLAIN SELECT  \"students\".* FROM \"students\"  WHERE \"students\".\"id\" = 1889881 LIMIT 1\n 19632 | 02:24:46.962818 | EXPLAIN SELECT  \"students\".* FROM \"students\"  WHERE \"students\".\"id\" = 1581884 LIMIT 1\n(truncated results for brevity)\n```\n\nThis command displays currently running queries, that have been running for longer than 5 minutes, descending by duration. Very long running queries can be a source of multiple issues, such as preventing DDL statements completing or vacuum being unable to update `relfrozenxid`.\n\n### `records_rank`\n\n```ruby\nRailsPgExtras.records_rank\n\n$ rake pg_extras:records_rank\n\n               name                | estimated_count\n-----------------------------------+-----------------\n tastypie_apiaccess                |          568891\n notifications_event               |          381227\n core_todo                         |          178614\n core_comment                      |          123969\n notifications_notification        |          102101\n django_session                    |           68078\n (truncated results for brevity)\n```\n\nThis command displays an estimated count of rows per table, descending by estimated count. The estimated count is derived from `n_live_tup`, which is updated by vacuum operations. Due to the way `n_live_tup` is populated, sparse vs. dense pages can result in estimations that are significantly out from the real count of rows.\n\n### `bloat`\n\n```ruby\nRailsPgExtras.bloat\n\n$ rake pg_extras:bloat\n\n type  | schemaname |           object_name         | bloat |   waste\n-------+------------+-------------------------------+-------+----------\n table | public     | bloated_table                 |   1.1 | 98 MB\n table | public     | other_bloated_table           |   1.1 | 58 MB\n index | public     | bloated_table::bloated_index  |   3.7 | 34 MB\n table | public     | clean_table                   |   0.2 | 3808 kB\n table | public     | other_clean_table             |   0.3 | 1576 kB\n (truncated results for brevity)\n```\n\nThis command displays an estimation of table \"bloat\" – space allocated to a relation that is full of dead tuples, that has yet to be reclaimed. Tables that have a high bloat ratio, typically 10 or greater, should be investigated to see if vacuuming is aggressive enough, and can be a sign of high table churn.\n\n[More info](https://pawelurbanek.com/postgresql-fix-performance#bloat)\n\n### `vacuum_stats`\n\n```ruby\nRailsPgExtras.vacuum_stats\n\n$ rake pg_extras:vacuum_stats\n\n schema |         table         | last_vacuum | last_autovacuum  |    rowcount    | dead_rowcount  | autovacuum_threshold | expect_autovacuum\n--------+-----------------------+-------------+------------------+----------------+----------------+----------------------+-------------------\n public | log_table             |             | 2013-04-26 17:37 |         18,030 |              0 |          3,656       |\n public | data_table            |             | 2013-04-26 13:09 |             79 |             28 |             66       |\n public | other_table           |             | 2013-04-26 11:41 |             41 |             47 |             58       |\n public | queue_table           |             | 2013-04-26 17:39 |             12 |          8,228 |             52       | yes\n (truncated results for brevity)\n```\n\nThis command displays statistics related to vacuum operations for each table, including an estimation of dead rows, last autovacuum and the current autovacuum threshold. This command can be useful when determining if current vacuum thresholds require adjustments, and to determine when the table was last vacuumed.\n\n### `kill_all`\n\n```ruby\n\nRailsPgExtras.kill_all\n\n```\n\nThis commands kills all the currently active connections to the database. It can be useful as a last resort when your database is stuck in a deadlock.\n\n### `kill_pid`\n\n```ruby\n\nRailsPgExtras.kill_pid(args: { pid: 4657 })\n\n```\n\nThis commands kills currently active database connection by its `pid` number. You can use `connections` method to find the correct `pid` values.\n\n### `pg_stat_statements_reset`\n\n```ruby\nRailsPgExtras.pg_stat_statements_reset\n```\n\nThis command discards all statistics gathered so far by pg_stat_statements.\n\n### `buffercache_stats`\n\n```ruby\nRailsPgExtras.buffercache_stats(args: { limit: 10 })\n```\n\nThis command shows the relations buffered in database share buffer, ordered by percentage taken. It also shows that how much of the whole relation is buffered.\n\n### `buffercache_usage`\n\n```ruby\nRailsPgExtras.buffercache_usage(args: { limit: 20 })\n```\n\nThis command calculates how many blocks from which table are currently cached.\n\n### `extensions`\n\n```ruby\n\nRailsPgExtras.extensions\n\n$ rake pg_extras:extensions\n\n| pg_stat_statements | 1.7 | 1.7 | track execution statistics of all SQL statements executed\n (truncated results for brevity)\n\n```\n\nThis command lists all the currently installed and available PostgreSQL extensions.\n\n### `connections`\n\n```ruby\n\nRailsPgExtras.connections\n\n+----------------------------------------------------------------+\n|      Returns the list of all active database connections       |\n+------------------+--------------------------+------------------+\n| username | pid   | client_address           | application_name |\n+------------------+--------------------------+------------------+\n| postgres | 15962 | 172.31.69.166/32         | sidekiq          |\n| postgres | 16810 | 172.31.69.166/32         | bin/rails        |\n+------------------+--------------------------+------------------+\n\n```\n\nThis command returns the list of all active database connections.\n\n### mandelbrot\n\n```ruby\nRailsPgExtras.mandelbrot\n\n$ rake pg_extras:mandelbrot\n```\n\nThis command outputs the Mandelbrot set, calculated through SQL.\n\n## Testing\n\n```bash\ncp docker-compose.yml.sample docker-compose.yml\ndocker compose up -d\nrake test_all\n```\n\n## Query sources\n\n- [https://github.com/heroku/heroku-pg-extras](https://github.com/heroku/heroku-pg-extras)\n- [https://hakibenita.com/postgresql-unused-index-size](https://hakibenita.com/postgresql-unused-index-size)\n- [https://sites.google.com/site/itmyshare/database-tips-and-examples/postgres/useful-sqls-to-check-contents-of-postgresql-shared_buffer](https://sites.google.com/site/itmyshare/database-tips-and-examples/postgres/useful-sqls-to-check-contents-of-postgresql-shared_buffer)\n- [https://wiki.postgresql.org/wiki/Index_Maintenance](https://wiki.postgresql.org/wiki/Index_Maintenance)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpawurb%2Frails-pg-extras","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpawurb%2Frails-pg-extras","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpawurb%2Frails-pg-extras/lists"}