Skip to content

Instantly share code, notes, and snippets.

@exhuma
Last active November 25, 2015 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save exhuma/4c6ee9349f74f82cfb1d to your computer and use it in GitHub Desktop.
Save exhuma/4c6ee9349f74f82cfb1d to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# Script to find lingering PostgreSQL data files.
#
# Those files can usually be safely removed from disk.
#
# Use at your own risk!
#
# Based on http://dba.stackexchange.com/a/121876/34652
#
# ----------------------------------------------------------------------------
# Copyright (c) 2015 Michel Albert
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ----------------------------------------------------------------------------
PGUSER=postgres
BASEDIR=/var/lib/postgresql/9.1/main/base
PSQLOPTS="-XtAF ; -U ${PGUSER}"
DBS=$(psql ${PSQLOPTS} -c "SELECT oid, datname FROM pg_database WHERE NOT datistemplate")
for line in ${DBS}; do
ROW=(${line//;/ })
tmpdir=$(mktemp -d --suffix pglinger)
ls ${BASEDIR}/${ROW[0]} | \
grep -E '^[0-9]+$' \
| sort -n > ${tmpdir}/list-of-files.txt
echo "### Database: ${ROW[1]}, OID=${ROW[0]}, data-dir=${BASEDIR}/${ROW[0]}"
RELATIONS=$(psql ${PSQLOPTS} -o ${tmpdir}/list-of-relations.txt -c "SELECT pg_relation_filenode(oid) FROM pg_class WHERE relkind IN ('i','r','t','S','m') AND reltablespace=0 ORDER BY 1" ${ROW[1]})
diff -u \
${tmpdir}/list-of-files.txt \
${tmpdir}/list-of-relations.txt && echo "No diffs"
rm -rf ${tmpdir}
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment