Created
December 16, 2021 19:45
-
-
Save linuxmalaysia/0684b2a6ffed751e069250ed69165c2b to your computer and use it in GitHub Desktop.
vacuum analyze only the tables in the specified schema
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| #https://stackoverflow.com/questions/29710618/vacuum-analyze-all-tables-in-a-schema-postgres | |
| # this is to be run from postgis user | |
| # 20211216 | |
| PG_SCHEMA='yourschema' | |
| PG_USER='postgres' | |
| PG_HOST='localhost' | |
| PG_DB='yourdb' | |
| PG_PASS='' | |
| vacuum_analyze_schema() { | |
| # vacuum analyze only the tables in the specified schema | |
| # postgres info can be supplied by either passing it as parameters to this | |
| # function, setting environment variables or a combination of the two | |
| local pg_schema="${1:-${PG_SCHEMA}}" | |
| local pg_db="${2:-${PG_DB}}" | |
| local pg_user="${3:-${PG_USER}}" | |
| local pg_host="${4:-${PG_HOST}}" | |
| local pg_pass="${5:-${PG_PASS}}" | |
| export PGPASSWORD="" | |
| echo "Vacuuming schema \`${pg_schema}\`:" | |
| # extract schema table names from psql output and put them in a bash array | |
| local psql_tbls="\dt ${pg_schema}.*" | |
| local sed_str="s/${pg_schema}\s+\|\s+(\w+)\s+\|.*/\1/p" | |
| local table_names=$( echo "${psql_tbls}" | psql -d "${pg_db}" | sed -nr "${sed_str}" ) | |
| local tables_array=( $( echo "${table_names}" | tr '\n' ' ' ) ) | |
| # loop through the table names creating and executing a vacuum | |
| # command for each one | |
| for t in "${tables_array[@]}"; do | |
| echo "doing table \`${t}\`..." | |
| psql -d "${pg_db}" \ | |
| -c "VACUUM (VERBOSE,ANALYZE) ${pg_schema}.${t};" | |
| done | |
| # loop through the table names creating and executing a REINDEX TABLES | |
| # command for each one | |
| for t in "${tables_array[@]}"; do | |
| echo "doing table \`${t}\`..." | |
| psql -d "${pg_db}" \ | |
| -c "REINDEX TABLE ${pg_schema}.${t};" | |
| done | |
| # loop through the table names creating and executing a ANALYZE | |
| # command for each one | |
| for t in "${tables_array[@]}"; do | |
| echo "doing table \`${t}\`..." | |
| psql -d "${pg_db}" \ | |
| -c "ANALYZE ${pg_schema}.${t};" | |
| done | |
| } | |
| vacuum_analyze_schema | |
| exit |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Codes improve by ChatGPT and Google Bard