如何备份和恢复一个PostgreSQL数据库?

nhhxz33t  于 2023-06-22  发布在  PostgreSQL
关注(0)|答案(2)|浏览(157)

我需要备份和恢复一个PostgreSQL数据库。我的操作系统版本是Ubuntu-14.04 64bit,PostgreSQL是:

gid: ~/works $ pg_config --version
PostgreSQL 9.3.15

我使用pg_dump备份数据库:

gid: ~/works $ pg_dump -U db_name_user -F t db_name > db_name.tar

我尝试使用pg_restore来恢复数据库,但失败了:

gid: ~/works $ pg_restore -U db_name_user -F t -d db_name db_name.tar

pg_restore: [archiver (db)] Error while PROCESSING TOC:
pg_restore: [archiver (db)] Error from TOC entry 3621; 0 0 COMMENT EXTENSION plpgsql 
pg_restore: [archiver (db)] could not execute query: ERROR:  must be owner of extension plpgsql
Command was: COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';

pg_restore: WARNING:  no privileges could be revoked for "public"
pg_restore: WARNING:  no privileges could be revoked for "public"
pg_restore: WARNING:  no privileges were granted for "public"
pg_restore: WARNING:  no privileges were granted for "public"
WARNING: errors ignored on restore: 1

我不知道这是什么意思?如何备份和恢复PostgreSQL数据库?
多谢了。

  • ----------------------更新1--------------------
    即使我在pg_dump和pg_restore中添加了"--no-owner"选项,我仍然得到了相同的错误消息:
gid:~/works $ pg_restore -U db_name_user -O -Ft -d db_name db_name.tar 
pg_restore: [archiver (db)] Error while PROCESSING TOC:
pg_restore: [archiver (db)] Error from TOC entry 3621; 0 0 COMMENT EXTENSION plpgsql 
pg_restore: [archiver (db)] could not execute query: ERROR:  must be owner of extension plpgsql
    Command was: COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';  

pg_restore: WARNING:  no privileges could be revoked for "public"
pg_restore: WARNING:  no privileges could be revoked for "public"
pg_restore: WARNING:  no privileges were granted for "public"
pg_restore: WARNING:  no privileges were granted for "public"
WARNING: errors ignored on restore: 1
dy1byipe

dy1byipe1#

你可以忽略注解语言的错误--它不会影响你的代码。还可以考虑使用无所有者来避免此类警告。但请记住,所有者将是您在pg_restore上连接的用户,而不是原始用户。请阅读docs:https://www.postgresql.org/docs/current/static/app-pgrestore.html

--no-owner不输出设置对象所有权匹配原数据库的命令。默认情况下,pg_restore发出ALTER OWNER或SET SESSION AUTHORIZATION语句来设置创建的架构元素的所有权。除非超级用户(或拥有脚本中所有对象的同一个用户)与数据库进行初始连接,否则这些语句将失败。使用-O,任何用户名都可以用于初始连接,并且该用户将拥有所有创建的对象。

8oomwypt

8oomwypt2#

#!/bin/bash

<<LICENSE
MIT License

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.

LICENSE

# Initial PostgreSQL configuration directory
PG_CONFIG_DIR_INITIAL="/etc/postgresql"

# The directory where the backup will be placed
BACKUP_DIR="/tmp"

# Check if the backup directory exists and is writable
if [ ! -d "${BACKUP_DIR}" ]; then
    echo "The backup directory (${BACKUP_DIR}) does not exist."
    echo "Would you like to create it? (y/n)"
    read create_dir
    if [[ "$create_dir" == "y" ]]; then
      mkdir -p $BACKUP_DIR
    else
      echo "Backup operation cancelled."
      exit 1
    fi
elif [ ! -w "${BACKUP_DIR}" ]; then
    echo "The backup directory (${BACKUP_DIR}) is not writable."
    exit 1
fi

# Dump all PostgreSQL databases, users and their passwords into a SQL commands file
dump_databases() {
    echo "Dumping all databases..."
    if ! sudo -u ${DB_USER} pg_dumpall > "${BACKUP_DIR}/alldb.sql"; then
        echo "Failed to dump databases."
        exit 1
    fi
}

# Backup PostgreSQL configuration files and databases
backup() {
    PG_CONFIG_DIR="${PG_CONFIG_DIR_INITIAL}/${POSTGRES_VERSION}/main"
    BACKUP_FILENAME="postgresql_${POSTGRES_VERSION}_backup_$(date +'%Y%m%d_%H%M%S').tar.gz"
    BACKUP_FILE="${BACKUP_DIR}/${BACKUP_FILENAME}"

    # Check if the PostgreSQL configuration directory exists
    if [ ! -d "${PG_CONFIG_DIR}" ]; then
        echo "The PostgreSQL configuration directory (${PG_CONFIG_DIR}) does not exist."
        exit 1
    fi

    echo "Starting backup for version ${POSTGRES_VERSION}..."

    dump_databases

    # Create a tarball of the configuration directory and databases SQL file
    if ! sudo tar -czvf ${BACKUP_FILE} ${PG_CONFIG_DIR} "${BACKUP_DIR}/alldb.sql"; then
        echo "Failed to create backup."
        exit 1
    fi

    # Verify backup integrity
    echo "Verifying backup integrity..."
    if ! sudo tar -tzf ${BACKUP_FILE} > /dev/null; then
        echo "Backup integrity check failed."
        exit 1
    fi

    echo "Backup created successfully at ${BACKUP_FILE}"
}

# Restore PostgreSQL configuration files and databases
restore() {
    echo "Please enter the full path to the backup file:"
    read BACKUP_FILE

    # Check if the backup file exists
    if [ ! -f "${BACKUP_FILE}" ]; then
        echo "The backup file (${BACKUP_FILE}) does not exist."
        exit 1
    fi

    # Unpack the tarball to the backup directory
    if ! sudo tar -xzvf ${BACKUP_FILE} -C ${BACKUP_DIR}; then
        echo "Failed to extract backup."
        exit 1
    fi

    PG_CONFIG_DIR="${PG_CONFIG_DIR_INITIAL}/${POSTGRES_VERSION}/main"

    # Copy the PostgreSQL configuration files back
    if ! sudo cp -r "${BACKUP_DIR}/main" ${PG_CONFIG_DIR}; then
        echo "Failed to restore configuration files."
        exit 1
    fi

    # Restore all databases
    if ! sudo -u ${DB_USER} psql < "${BACKUP_DIR}/alldb.sql"; then
        echo "Failed to restore databases."
        exit 1
    fi

    # Verify data restoration
    echo "Verifying data restoration..."
    if ! sudo -u ${DB_USER} psql -c "SELECT 1 FROM pg_database LIMIT 1" | grep -q "1"; then
        echo "Data restoration verification failed."
        exit 1
    fi

    # Delete the extracted backup files
    if ! sudo rm -rf "${BACKUP_DIR}/main" "${BACKUP_DIR}/alldb.sql"; then
        echo "Failed to delete extracted backup files."
        exit 1
    fi

    echo "Restore completed successfully for version ${POSTGRES_VERSION}."
}

# Ensure script is run with superuser privileges
if [ "$(id -u)" -ne 0 ]; then
    echo "This script must be run as root"
    exit 1
fi

echo "************************************************************************"
echo "*                      PostgreSQL Backup/Restore                       *"
echo "***********************************************************************"
echo "*                                                                      *"
echo "*  This script allows you to backup and restore PostgreSQL             *"
echo "*  configuration files and databases. Please select an action:         *"
echo "*                                                                      *"
echo "*  1) Backup: Backup PostgreSQL configuration files and databases      *"
echo "*  2) Restore: Restore PostgreSQL configuration files and databases    *"
echo "*                                                                      *"
echo "************************************************************************"

read -p "Choose an action (1 or 2): " ACTION

case $ACTION in
1)
    read -p "Enter PostgreSQL version for backup: " POSTGRES_VERSION
    read -p "Enter PostgreSQL user for backup: " DB_USER
    backup
    ;;
2)
    read -p "Enter PostgreSQL version for restore: " POSTGRES_VERSION
    read -p "Enter PostgreSQL user for restore: " DB_USER
    restore
    ;;
*)
    echo "Invalid action. Exiting."
    exit 1
    ;;
esac

相关问题