The bash function below uses the CLI tool psqlto vacuum analyze tables in a single schema, which can be identified by passing the schema name as the first parameter to the function or setting the environment variable PG_SCHEMA:
vacuum_analyze_schema() {
local pg_schema="${1:-${PG_SCHEMA}}"
local pg_db="${2:-${PG_DB}}"
local pg_user="${3:-${PG_USER}}"
local pg_host="${4:-${PG_HOST}}"
echo "Vacuuming schema \'${pg_schema}\':"
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}" -U "${pg_user}" -h "${pg_host}" | sed -nr "${sed_str}" )
local tables_array=( $( echo "${table_names}" | tr '\n' ' ' ) )
for t in "${tables_array[@]}"; do
echo "doing table \'${t}\'..."
psql -d "${pg_db}" -U "${pg_user}" -h "${pg_host}" \
-c "VACUUM (ANALYZE) ${pg_schema}.${t};"
done
}
This function can be added to yours .bashrcto provide an opportunity to call it from the command line at any time. Like the schema, Postgres connections and database values can be set by providing them as function parameters:
vacuum_analyze_schema '<your-pg-schema>' '<your-pg-db>' '<your-pg-user>' '<your-pg-host>'
or by setting environment variables:
PG_SCHEMA='<your-pg-schema>'
PG_USER='<your-pg-user>'
PG_HOST='<your-pg-host>'
PG_DB='<your-pg-db>'
vacuum_analyze_schema
or a combination of both. Values passed as parameters will take precedence over the corresponding environment variables.
source
share