Windows postgresql восстановить базу из бэкапа

pg_restore accepts the following command line arguments.

filename

Specifies the location of the archive file (or directory, for a directory-format archive) to be restored. If not specified, the standard input is used.

-a
--data-only

Restore only the data, not the schema (data definitions). Table data, large objects, and sequence values are restored, if present in the archive.

This option is similar to, but for historical reasons not identical to, specifying --section=data.

-c
--clean

Clean (drop) database objects before recreating them. (Unless --if-exists is used, this might generate some harmless error messages, if any objects were not present in the destination database.)

-C
--create

Create the database before restoring into it. If --clean is also specified, drop and recreate the target database before connecting to it.

With --create, pg_restore also restores the database’s comment if any, and any configuration variable settings that are specific to this database, that is, any ALTER DATABASE ... SET ... and ALTER ROLE ... IN DATABASE ... SET ... commands that mention this database. Access privileges for the database itself are also restored, unless --no-acl is specified.

When this option is used, the database named with -d is used only to issue the initial DROP DATABASE and CREATE DATABASE commands. All data is restored into the database name that appears in the archive.

-d dbname
--dbname=dbname

Connect to database dbname and restore directly into the database. The dbname can be a connection string. If so, connection string parameters will override any conflicting command line options.

-e
--exit-on-error

Exit if an error is encountered while sending SQL commands to the database. The default is to continue and to display a count of errors at the end of the restoration.

-f filename
--file=filename

Specify output file for generated script, or for the listing when used with -l. Use - for stdout.

-F format
--format=format

Specify format of the archive. It is not necessary to specify the format, since pg_restore will determine the format automatically. If specified, it can be one of the following:

c
custom

The archive is in the custom format of pg_dump.

d
directory

The archive is a directory archive.

t
tar

The archive is a tar archive.

-I index
--index=index

Restore definition of named index only. Multiple indexes may be specified with multiple -I switches.

-j number-of-jobs
--jobs=number-of-jobs

Run the most time-consuming steps of pg_restore — those that load data, create indexes, or create constraints — concurrently, using up to number-of-jobs concurrent sessions. This option can dramatically reduce the time to restore a large database to a server running on a multiprocessor machine. This option is ignored when emitting a script rather than connecting directly to a database server.

Each job is one process or one thread, depending on the operating system, and uses a separate connection to the server.

The optimal value for this option depends on the hardware setup of the server, of the client, and of the network. Factors include the number of CPU cores and the disk setup. A good place to start is the number of CPU cores on the server, but values larger than that can also lead to faster restore times in many cases. Of course, values that are too high will lead to decreased performance because of thrashing.

Only the custom and directory archive formats are supported with this option. The input must be a regular file or directory (not, for example, a pipe or standard input). Also, multiple jobs cannot be used together with the option --single-transaction.

-l
--list

List the table of contents of the archive. The output of this operation can be used as input to the -L option. Note that if filtering switches such as -n or -t are used with -l, they will restrict the items listed.

-L list-file
--use-list=list-file

Restore only those archive elements that are listed in list-file, and restore them in the order they appear in the file. Note that if filtering switches such as -n or -t are used with -L, they will further restrict the items restored.

list-file is normally created by editing the output of a previous -l operation. Lines can be moved or removed, and can also be commented out by placing a semicolon (;) at the start of the line. See below for examples.

-n schema
--schema=schema

Restore only objects that are in the named schema. Multiple schemas may be specified with multiple -n switches. This can be combined with the -t option to restore just a specific table.

-N schema
--exclude-schema=schema

Do not restore objects that are in the named schema. Multiple schemas to be excluded may be specified with multiple -N switches.

When both -n and -N are given for the same schema name, the -N switch wins and the schema is excluded.

-O
--no-owner

Do not output commands to set ownership of objects to match the original database. By default, pg_restore issues ALTER OWNER or SET SESSION AUTHORIZATION statements to set ownership of created schema elements. These statements will fail unless the initial connection to the database is made by a superuser (or the same user that owns all of the objects in the script). With -O, any user name can be used for the initial connection, and this user will own all the created objects.

-P function-name(argtype [, ...])
--function=function-name(argtype [, ...])

Restore the named function only. Be careful to spell the function name and arguments exactly as they appear in the dump file’s table of contents. Multiple functions may be specified with multiple -P switches.

-R
--no-reconnect

This option is obsolete but still accepted for backwards compatibility.

-s
--schema-only

Restore only the schema (data definitions), not data, to the extent that schema entries are present in the archive.

This option is the inverse of --data-only. It is similar to, but for historical reasons not identical to, specifying --section=pre-data --section=post-data.

(Do not confuse this with the --schema option, which uses the word schema in a different meaning.)

-S username
--superuser=username

Specify the superuser user name to use when disabling triggers. This is relevant only if --disable-triggers is used.

-t table
--table=table

Restore definition and/or data of only the named table. For this purpose, table includes views, materialized views, sequences, and foreign tables. Multiple tables can be selected by writing multiple -t switches. This option can be combined with the -n option to specify table(s) in a particular schema.

Note

When -t is specified, pg_restore makes no attempt to restore any other database objects that the selected table(s) might depend upon. Therefore, there is no guarantee that a specific-table restore into a clean database will succeed.

Note

This flag does not behave identically to the -t flag of pg_dump. There is not currently any provision for wild-card matching in pg_restore, nor can you include a schema name within its -t. And, while pg_dump‘s -t flag will also dump subsidiary objects (such as indexes) of the selected table(s), pg_restore‘s -t flag does not include such subsidiary objects.

Note

In versions prior to PostgreSQL 9.6, this flag matched only tables, not any other type of relation.

-T trigger
--trigger=trigger

Restore named trigger only. Multiple triggers may be specified with multiple -T switches.

-v
--verbose

Specifies verbose mode. This will cause pg_restore to output detailed object comments and start/stop times to the output file, and progress messages to standard error. Repeating the option causes additional debug-level messages to appear on standard error.

-V
--version

Print the pg_restore version and exit.

-x
--no-privileges
--no-acl

Prevent restoration of access privileges (grant/revoke commands).

-1
--single-transaction

Execute the restore as a single transaction (that is, wrap the emitted commands in BEGIN/COMMIT). This ensures that either all the commands complete successfully, or no changes are applied. This option implies --exit-on-error.

--disable-triggers

This option is relevant only when performing a data-only restore. It instructs pg_restore to execute commands to temporarily disable triggers on the target tables while the data is restored. Use this if you have referential integrity checks or other triggers on the tables that you do not want to invoke during data restore.

Presently, the commands emitted for --disable-triggers must be done as superuser. So you should also specify a superuser name with -S or, preferably, run pg_restore as a PostgreSQL superuser.

--enable-row-security

This option is relevant only when restoring the contents of a table which has row security. By default, pg_restore will set row_security to off, to ensure that all data is restored in to the table. If the user does not have sufficient privileges to bypass row security, then an error is thrown. This parameter instructs pg_restore to set row_security to on instead, allowing the user to attempt to restore the contents of the table with row security enabled. This might still fail if the user does not have the right to insert the rows from the dump into the table.

Note that this option currently also requires the dump be in INSERT format, as COPY FROM does not support row security.

--if-exists

Use conditional commands (i.e., add an IF EXISTS clause) to drop database objects. This option is not valid unless --clean is also specified.

--no-comments

Do not output commands to restore comments, even if the archive contains them.

--no-data-for-failed-tables

By default, table data is restored even if the creation command for the table failed (e.g., because it already exists). With this option, data for such a table is skipped. This behavior is useful if the target database already contains the desired table contents. For example, auxiliary tables for PostgreSQL extensions such as PostGIS might already be loaded in the target database; specifying this option prevents duplicate or obsolete data from being loaded into them.

This option is effective only when restoring directly into a database, not when producing SQL script output.

--no-publications

Do not output commands to restore publications, even if the archive contains them.

--no-security-labels

Do not output commands to restore security labels, even if the archive contains them.

--no-subscriptions

Do not output commands to restore subscriptions, even if the archive contains them.

--no-table-access-method

Do not output commands to select table access methods. With this option, all objects will be created with whichever access method is the default during restore.

--no-tablespaces

Do not output commands to select tablespaces. With this option, all objects will be created in whichever tablespace is the default during restore.

--section=sectionname

Only restore the named section. The section name can be pre-data, data, or post-data. This option can be specified more than once to select multiple sections. The default is to restore all sections.

The data section contains actual table data as well as large-object definitions. Post-data items consist of definitions of indexes, triggers, rules and constraints other than validated check constraints. Pre-data items consist of all other data definition items.

--strict-names

Require that each schema (-n/--schema) and table (-t/--table) qualifier match at least one schema/table in the backup file.

--use-set-session-authorization

Output SQL-standard SET SESSION AUTHORIZATION commands instead of ALTER OWNER commands to determine object ownership. This makes the dump more standards-compatible, but depending on the history of the objects in the dump, might not restore properly.

-?
--help

Show help about pg_restore command line arguments, and exit.

pg_restore also accepts the following command line arguments for connection parameters:

-h host
--host=host

Specifies the host name of the machine on which the server is running. If the value begins with a slash, it is used as the directory for the Unix domain socket. The default is taken from the PGHOST environment variable, if set, else a Unix domain socket connection is attempted.

-p port
--port=port

Specifies the TCP port or local Unix domain socket file extension on which the server is listening for connections. Defaults to the PGPORT environment variable, if set, or a compiled-in default.

-U username
--username=username

User name to connect as.

-w
--no-password

Never issue a password prompt. If the server requires password authentication and a password is not available by other means such as a .pgpass file, the connection attempt will fail. This option can be useful in batch jobs and scripts where no user is present to enter a password.

-W
--password

Force pg_restore to prompt for a password before connecting to a database.

This option is never essential, since pg_restore will automatically prompt for a password if the server demands password authentication. However, pg_restore will waste a connection attempt finding out that the server wants a password. In some cases it is worth typing -W to avoid the extra connection attempt.

--role=rolename

Specifies a role name to be used to perform the restore. This option causes pg_restore to issue a SET ROLE rolename command after connecting to the database. It is useful when the authenticated user (specified by -U) lacks privileges needed by pg_restore, but can switch to a role with the required rights. Some installations have a policy against logging in directly as a superuser, and use of this option allows restores to be performed without violating the policy.

Время на прочтение
5 мин

Количество просмотров 17K

PostgreSQL
PostgreSQL

Автор статьи: технический руководитель проектов внедрения 1С:ERP Внедренческого центра «Раздолье» Дмитрий Малышев.

Введение

pgAdmin — это интерфейс для администрирования баз данных PostgreSQL, в моём понимании это аналог MS SQL Management Studio. Ставится pgAdmin отдельно от PostgreSQL. Инструкцию установки найдите, пожалуйста, в интернет поисковиках. В данной инструкции будет описано как с помощью pgAdmin, bat-файлов и Планировщика заданий Windows организовать резервное копирование, восстановление и хранение копий баз данных.

psql-1.png

psql-1.png

Открытие pgAdmin

Через пуск или в проводнике открываем приложение.

psql-2.png

psql-2.png

«C:\Program Files\pgAdmin 4\v6\pgAdmin4.ico»

psql-3.png

psql-3.png

Вводим пароль доступа (за дается ранее пользователем).

psql-4.png

psql-4.png

Откроется интерфейс управления базами данных.

psql-1.png

psql-1.png

Создание резервной копии

Рассмотрим создание резервной копии из pgAdmin и командным bat-файлом.

2.1. С помощью pgAdmin

Выбираем базу в дереве, правой кнопкой мыши открываем контекстное меню, где выбираем создание резервной копии/Backup… Указываем полный путь для сохранения копии, формат Custom и жмем [Создать / Create].

psql-5.png

psql-5.png

***

psql-6.png

psql-6.png

***

psql-7.png

psql-7.png

2.2. С помощью командного файла *.bat

Запускаем двойным кликом мыши командный файл backup_pdadmin_UH_IMD_everyday.bat, в котором уже прописан вызов архиватора формат и путь файла копии.

psql-8.png

psql-8.png

Копии сохраняются сюда.

psql-9.png

psql-9.png

Содержимое командного файла:

REM СОЗДАНИЯ РЕЗЕРВНОЙ КОПИИ БАЗЫ ДАННЫХ POSTGRESQL

CLS

ECHO OFF

CHCP 1251

REM Установка переменных окружения

SET PGDATABASE=IMD_UH

SET PGHOST=localhost

SET PGPORT=5432

SET PGUSER=postgres

SET PGPASSWORD=ЗДЕСЬ_УКАЖИТЕ_ПАРОЛЬ_для_пользователя_postgres

REM Формирование имени файла резервной копии и файла-отчета

SET DATETIME=%DATE:~6,4%-%DATE:~3,2%-%DATE:~0,2% %TIME:~0,2%-%TIME:~3,2%-%TIME:~6,2%

SET DUMPFILE=%PGDATABASE% %DATETIME%.backup

SET LOGFILE=%PGDATABASE% %DATETIME%.log

SET DUMPPATH=»E:\UH_IMD\Backup\%DUMPFILE%»

SET LOGPATH=»E:\UH_IMD\Backup\%LOGFILE%»

REM Создание резервной копии

IF NOT EXIST Backup MD Backup

CALL «C:\Program Files\pgAdmin 4\v6\runtime\pg_dump.exe» —format=custom —verbose —file=%DUMPPATH% 2>%LOGPATH%

REM Анализ кода завершения

IF NOT %ERRORLEVEL%==0 GOTO Error

GOTO Successfull

REM В случае ошибки удаляется поврежденная резервная копия и делается соответствующая запись в журнале

:Error

DEL %DUMPPATH%

MSG * «ERROR to create backup!!! See the information E:\UH_IMD\Backup\backup.log.»

ECHO %DATETIME% Ошибка при создании резервной копии %DUMPFILE%. Смотрите %LOGFILE%. >> backup.log

GOTO End

REM В случае удачного резервного копирования просто делается запись в журнал

:Successfull

ECHO %DATETIME% Успешное создание резервной копии %DUMPFILE% >> backup.log

GOTO End

:End

Пояснения:

SET PGDATABASE=IMD_UH — здесь имя базы данных на СУБД равно IMD_UH, у вас будет свое поменяйте обязательно.

E:\UH_IMD\Backup — здесь путь хранения backup у вас будет свой, поменяйте.

C:\Program Files\pgAdmin 4\v6\runtime — папка утилиты pg_dump.exe для создания дампов, пусть может чуть отличаться, например, вместо v6 будет v4. И не забудьте pgAdmin установить, он ставится отдельно.

SET PGPASSWORD=ЗДЕСЬ_УКАЖИТЕ_ПАРОЛЬ_для_пользователя_postgres — тут укажите реальный пароль от пользователя postgres СУБД PostgreSQL

Восстановление резервной копии

Есть несколько способов: Из командной строки, из pgAdmin, заранее подготовленным командным файлом. Мы рассмотрим: pgAdmin.

3.1. С помощью pgAdmin

3.1.1. В существующую базу

Выбираем базу, вызываем правой кнопкой ее контекстное меню, где выбираем действие Восстановить / Restore.

psql-10.png

psql-10.png

Далее указываем путь к резервной копии, и в настройках ставим предварительно очищать существующую базу (иначе она не восстановится из-за конфликта таблиц).

psql-11.png

psql-11.png

***

psql-12.png

psql-12.png

***

psql-13.png

psql-13.png

***

ps-14.png

ps-14.png

3.1.2. В новую базу

3.1.2.1. Создаем новую базу в PostgreSQL

На корне дерева баз вызываем правой кнопкой мыши контекстное меню и действие Создать / Create – Базу данных / Database.

psql-14.png

psql-14.png

Задаем имя новой базы.

psql-16.png

psql-16.png

Выбираем обязательно схему создания template0 (иначе на следующем шаге база не развернется из backup из-за конфликта таблиц).

psql-16.png

psql-16.png

Для контроля смотрим итоговый запрос, и жмем кнопку [Сохранить]/[Save].

psql-17.png

psql-17.png

3.1.2.2. Восстанавливаем базу из архива в PostgreSQL

После создания пустой новой базы, её нужно восстановить из архива. Для этого смотрите пункт выше 3.1.1. Для восстановления в существующую базу, выполняем всё тоже самое только для базы с именем NewBaseName

3.1.2.3. Создаем новую базу 1С NewBaseName

После того как развернули базу на СУБД PostgreSQL её требуется опубликовать на сервере 1С, чтобы пользователи получили к ней доступ. Для этого выполним действия по созданию базы 1С и связывании её с существующей базой на СУБД.

psql-18.png

psql-18.png

***

psql-19.png

psql-19.png

***

psql-20.png

psql-20.png

***

psql-21.png

psql-21.png

***

psql-22.png

psql-22.png

Не забываем ставь флаг «Установить блокировку регламентных заданий», если это копия.

Удаление старых резервных копий

4.1. Вручную

Удаляем архивы старше 30 дней вручную. Затем чистим корзину на рабочем столе.

В проводнике папка E:\UH_IMD\Backup.

psql-23.png

psql-23.png

***

psql-24.png

psql-24.png

4.2. С помощью командного файла *.bat

Запускаем двойным щелчком мыши командный файл. В файле указана очистка в каталоге файлов старше 30 дней.

psql-25.png

psql-25.png

Его содержимое:

forfiles /p «E:\UH_IMD\Backup» /S /D -30 /C «cmd /c del /f /a /q @file»

Пояснения:

E:\UH_IMD\Backup — здесь путь хранения backup’ов, у вас будет свое поменяйте обязательно.

30 — срок в днях хранения backup’ов

Автоматическое выполнение резервного копирования

Использован стандартный планировщик заданий Windows каждый день в 5:00 утра запуск, выполнения командного файла (архив рабочей базы примерно 1 час создается).

psql-25.png

psql-25.png

***

psql-26.png

psql-26.png

***

psql-27.png

psql-27.png

***

psql-28.png

psql-28.png

***

psql-29.png

psql-29.png

***

psql-30.png

psql-30.png

***

psql-31.png

psql-31.png

Автоматическое выполнение очистки копий старше 30 дней

Использован стандартный планировщик заданий Windows каждую субботу в 10:00 утра запуск, выполнения командного файла.

psql-32.png

psql-32.png

***

psql-33.png

psql-33.png

***

psql-34.png

psql-34.png

***

psql-35.png

psql-35.png

***

psql-36.png

psql-36.png

***

psql-37.png

psql-37.png

***

psql-38.png

psql-38.png

Приложения

Пример содержимого общего файла логов backup.log.

psql-39.png

psql-39.png

Пример содержимого файла лога конкретной выгрузки UH_IMD 2022-10-07 5-00-00.log

psql-40.png

psql-40.png

P.S. Коллеги, сразу скажу, что я не системный администратор, а программист 1С. Системщик решил бы, может быть, элегантнее. 

Хотя ситуация сложилась такая, что я делал настройки и эту инструкцию с bat-никами по просьбе системных администраторов (как бы странно это ни звучало). Нечасто такими настройками занимаюсь, поэтому не судите строго. 

Добавил 2 батника, по обновлению статистики и реиндексации:

Они для регламентного обслуживания. 1С завершать для их работы не обязательно, но 1С будет притормаживать или пойдет блокировка на период реиндексации. В планировщик заданий Windows на эти батники добавьте задачи раз в неделю на свои базы, в Нерабочее время. Также есть служебная база postgres на нее тоже раз в неделю добавьте обслуживание.

Файл vacuumdb_BaseName.bat — обновление статистики.

Его содержимое:

vacuumdb -d UH_IMD -Z -v -j 1

Пояснения:

Обновление статистики базы с именем UH_IMD (тут поставьте свою) в 1 поток.

Можно поменять на обновление статистики во всех базах в 4 потока, тогда будет текст:

vacuumdb -a -Z -v -j 4

Файл reindexdb_BaseName.bat — реиндексация таблиц в базе.

Его содержимое:

reindexdb -d UH_IMD -v -j 1

Пояснения:

Обновление индексов в базе с именем UH_IMD (тут поставьте свою) в 1 поток.

Можно поменять на обновление статистики во всех базах в 4 потока, тогда будет текст:

reindexdb -a -v -j 4

Также обратите внимание на программу Effector Saver — программа резервного копирования 1С:Предприятия (поищите в инете).

Делает копии в MS и PostgreSQL, настройка хранения и удаления. Есть возможность подключать скрипты и выполнять тестирование исправление 1С. Есть бесплатная версия (которой должно хватить), и есть также платная с плюшками.

Ищите для работы вот этот материал с инструкциями для скачивания и использования:

  • backup_pgadmin_BaseName_everyday.bat

  • delete_backup_BaseName_older than 30 days.bat

  • Резервное копирование и восстановление баз PostgreSQL в Windows с помощью pgAdmin, bat-файлов и планировщика.docx

  • vacuumdb_BaseName.bat

  • reindexdb_BaseName.bat

Обновлено Обновлено:
Опубликовано Опубликовано:

Тематические термины: PostgreSQL, SQL

В данной инструкции рассмотрены варианты и примеры создания резервных копий и восстановления баз СУБД PostgreSQL.

Создание копий
    Базовая команда
    Пользователь и пароль
    Сжатие данных
    Скрипт
    На удаленном сервере
    Дамп определенной таблицы
    Каждая таблица в свой файл
    Для определенной схемы
    Только схемы
    Только данные
    pgAdmin
    Не текстовые форматы
    pg_basebackup
    pg_dumpall (все базы данных)
Восстановление
    Базовая команда
    С авторизацией
    Из файла gz
    Определенную базу
    Определенную таблицу
    С помощью pgAdmin
    pg_restore (бинарные бэкапы)
Работа с CSV
Возможные проблемы
    Input file appears to be a text format dump. please use psql
    No matching tables were found
    Too many command-line arguments
    Aborting because of server version mismatch
    No password supplied
    Неверная команда \

Все команды, которые приводятся ниже, должны выполняться из командной строки. В Linux — это окно терминала, в Windows — командная строка (cmd.exe) с переходом в папку установки PostgreSQL.

Создание резервных копий

Базовая команда

Синтаксис:

pg_dump <параметры> <имя базы> > <файл, куда сохранить дамп>

Пример:

pg_dump users > /tmp/users.dump

Пользователь и пароль

Если резервная копия выполняется не от учетной записи postgres, необходимо добавить опцию -U с указанием пользователя:

pg_dump -U dmosk -W users > /tmp/users.dump

* где dmosk — имя учетной записи; опция W потребует ввода пароля.

Сжатие данных

Для экономии дискового пространства или более быстрой передачи по сети можно сжать наш архив:

pg_dump users | gzip > users.dump.gz

Скрипт для автоматического резервного копирования

Рассмотрим 2 варианта написания скрипта для резервирования баз PostgreSQL. Первый вариант — запуск скрипта от пользователя root для резервирования одной базы. Второй — запуск от пользователя postgres для резервирования всех баз, созданных в СУБД.

Для начала, создадим каталог, в котором разместим скрипт, например:

mkdir /scripts

И сам скрипт: 

vi /scripts/postgresql_dump.sh

Вариант 1. Запуск от пользователя root; одна база.

#!/bin/sh
PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin

PGPASSWORD=password
export PGPASSWORD
pathB=/backup
dbUser=dbuser
database=db

find $pathB \( -name «*-1[^5].*» -o -name «*-[023]?.*» \) -ctime +61 -delete
pg_dump -U $dbUser $database | gzip > $pathB/pgsql_$(date «+%Y-%m-%d»).sql.gz

unset PGPASSWORD

* где password — пароль для подключения к postgresql; /backup — каталог, в котором будут храниться резервные копии; dbuser — имя учетной записи для подключения к БУБД; pathB — путь до каталога, где будут храниться резервные копии.
* данный скрипт сначала удалит все резервные копии, старше 61 дня, но оставит от 15-о числа как длительный архив. После при помощи утилиты pg_dump будет выполнено подключение и резервирование базы db. Пароль экспортируется в системную переменную на момент выполнения задачи.

Для запуска резервного копирования по расписанию, сохраняем скрипт в файл, например, /scripts/postgresql_dump.sh и создаем задание в планировщике:

crontab -e

3 0 * * * /scripts/postgresql_dump.sh

* наш скрипт будет запускаться каждый день в 03:00.

Вариант 2. Запуск от пользователя postgres; все базы.

#!/bin/bash
PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin

pathB=/backup/postgres

find $pathB \( -name «*-1[^5].*» -o -name «*-[023]?.*» \) -ctime +61 -delete

for dbname in `echo «SELECT datname FROM pg_database;» | psql | tail -n +3 | head -n -2 | egrep -v ‘template0|template1|postgres’`; do
    pg_dump $dbname | gzip > $pathB/$dbname-$(date «+%Y-%m-%d»).sql.gz
done;

* где /backup — каталог, в котором будут храниться резервные копии; pathB — путь до каталога, где будут храниться резервные копии.
* данный скрипт сначала удалит все резервные копии, старше 61 дня, но оставит от 15-о числа как длительный архив. После найдет все созданные в СУБД базы, кроме служебных и при помощи утилиты pg_dump будет выполнено резервирование каждой найденной базы. Пароль нам не нужен, так как по умолчанию, пользователь postgres имеет возможность подключаться к базе без пароля.

Необходимо убедиться, что у пользователя postgre будет разрешение на запись в каталог назначения, в нашем примере, /backup/postgres.

Зададим в качестве владельца файла, пользователя postgres:

chown postgres:postgres /scripts/postgresql_dump.sh

Для запуска резервного копирования по расписанию, сохраняем скрипт в файл, например, /scripts/postgresql_dump.sh и создаем задание в планировщике:

crontab -e -u postgres

* мы откроем на редактирование cron для пользователя postgres.

3 0 * * * /scripts/postgresql_dump.sh

* наш скрипт будет запускаться каждый день в 03:00.

Права и запуск

Разрешаем запуск скрипта, как исполняемого файла:

chmod +x /scripts/postgresql_dump.sh

Единоразово можно запустить задание на выполнение резервной копии:

/scripts/postgresql_dump.sh

… или от пользователя postgres:

su — postgres -c «/scripts/postgresql_dump.sh»

На удаленном сервере

Если сервер баз данных находится на другом сервере, просто добавляем опцию -h:

pg_dump -h 192.168.0.15 users > /tmp/users.dump

* необходимо убедиться, что сама СУБД разрешает удаленное подключение. Подробнее читайте инструкцию Как настроить удаленное подключение к PostgreSQL.

Дамп определенной таблицы

Запускается с опцией -t <table> или —table=<table>:

pg_dump -t students users > /tmp/students.dump

* где students — таблица; users — база данных.

Если наша таблица находится в определенной схеме, то она указывается вместе с ней, например:

pg_dump -t public.students users > /tmp/students.dump

* где public — схема; students — таблица; users — база данных.

Размещение каждой таблицы в отдельный файл

Также называется резервированием в каталог. Данный способ удобен при больших размерах базы или необходимости восстанавливать отдельные таблицы. Выполняется с ипользованием ключа -d:

pg_dump -d customers > /tmp/folder

* где /tmp/folder — путь до каталога, в котором разместяться файлы дампа для каждой таблицы.

Для определенной схемы

В нашей базе может быть несколько схем. Если мы хотим сделать дамп только для определенной схемы, то используем опцию -n, например:

pg_dump -n public peoples > /tmp/peoples.public.sql

* в данном примере мы заархивируем схему public базы данных peoples.

Только схемы (структуры)

Для резервного копирования без данных (только таблицы и их структуры):

pg_dump —schema-only users > /tmp/users.schema.dump

Также, внутри каждой базы могут быть свои схемы с данными. Если нам нужно сделать дамп именно той схемы, которая внутри базы, используем ключ -n:

pg_dump —schema-only users -n production > /tmp/users.schema_production.dump

* в данном примере мы создадим дамп структуры базы данных users только для схемы production.

Или полный дамп с данными для схемы внутри базы данных:

pg_dump users -n production > /tmp/users.production.dump

Только данные

pg_dump —data-only users > /tmp/users.data.dump

Использование pgAdmin

Данный метод хорошо подойдет для компьютеров с Windows и для быстрого создания резервных копий из графического интерфейса.

Запускаем pgAdmin — подключаемся к серверу — кликаем правой кнопкой мыши по базе, для которой хотим сделать дамп — выбираем Резервная копия:

Выбираем операцию резервного копирования для базы Postgresql

В открывшемся окне выбираем путь для сохранения данных и настраиваемый формат:

Настраиваем путь для резервного копирования

При желании, можно изучить дополнительные параметры для резервного копирования:

Дополнительные опции

После нажимаем Резервная копия — ждем окончания процесса и кликаем по Завершено.

Не текстовые форматы дампа

Другие форматы позволяют делать частичное восстановление, работать в несколько потоков и сжимать данные.

Бинарный с компрессией:

pg_dump -Fc users > users.bak

Тарбол:

pg_dump -Ft users > users.tar

Directory-формат:

pg_dump -Fd users > users.dir

Использование pg_basebackup

pg_basebackup позволяет создать резервную копию для кластера PostgreSQL.

pg_basebackup -h node1 -D /backup

* в данном примере создается резервная копия для сервера node1 с сохранением в каталог /backup.

pg_dumpall

Данная утилита делает выгрузку всех баз данных, в том числе системных. На выходе получаем файл для восстановления в формате скрипта.

pg_dumpall > cluster.bak

Утилиту удобно использовать с ключом -g (—globals-only) — выгрузка только глобальных объектов (ролей и табличных пространств).

Для создание резервного копирования со сжатием:

pg_dumpall | gzip > cluster.tar.gz

Восстановление

Может понадобиться создать базу данных. Это можно сделать SQL-запросом:

=# CREATE DATABASE users WITH ENCODING=’UTF-8′;

* где users — имя базы; UTF-8 — используемая кодировка.

Если мы получим ошибку:

ERROR:  encoding «UTF8» does not match locale «en_US»
DETAIL:  The chosen LC_CTYPE setting requires encoding «LATIN1».

Указываем больше параметров при создании базы:

CREATE DATABASE users WITH OWNER ‘postgres’ ENCODING ‘UTF8’ LC_COLLATE = ‘ru_RU.UTF-8’ LC_CTYPE = ‘ru_RU.UTF-8’ TEMPLATE = template0;

Базовая команда

Синтаксис:

psql <имя базы> < <файл с дампом>

Пример:

psql users < /tmp/users.dump

С авторизацией

При необходимости авторизоваться при подключении к базе вводим:

psql -U dmosk -W users < /tmp/users.dump

* где dmosk — имя учетной записи; опция W потребует ввода пароля.

Из файла gz

Сначала распаковываем файл, затем запускаем восстановление:

gunzip users.dump.gz

psql users < users.dump

Или одной командой:

zcat users.dump.gz | psql users

Определенную базу

Если резервная копия делалась для определенной базы, запускаем восстановление:

psql users < /tmp/database.dump

Если делался полный дамп (всех баз), восстановить определенную можно при помощи утилиты pg_restore с параметром -d:

pg_restore -d users cluster.bak

Определенную таблицу

Если резервная копия делалась для определенной таблицы, можно просто запустить восстановление:

psql users < /tmp/students.dump

Если делался полный дамп, восстановить определенную таблицу можно при помощи утилиты pg_restore с параметром -t:

pg_restore -a -t students users.dump

С помощью pgAdmin

Запускаем pgAdmin — подключаемся к серверу — кликаем правой кнопкой мыши по базе, для которой хотим восстановить данные — выбираем Восстановить:

Выбираем восстановление базы данных

Выбираем наш файл с дампом:

Выбираем файл с дампом

И кликаем по Восстановить:

Восстанавливаем данные

Использование pg_restore

Данная утилита предназначена для восстановления данных не текстового формата (в одном из примеров создания копий мы тоже делали резервную копию не текстового формата).

Из бинарника:

pg_restore -Fc users.bak

Из тарбола:

pg_restore -Ft users.tar

С созданием новой базы:

pg_restore -Ft -C users.tar

Мы можем использовать опцию d для указания подключения к конкретному серверу и базе, например:

pg_restore -d «postgresql://dmosk_user:dmosk_pass@localhost/dmosk_base» -Fc users.bak

* в данном примере мы подключимся к локальной базе (localhost) с названием dmosk_base от пользователя dmosk_user с паролем dmosk_pass.

Работа с CSV

Мы можем переносить данные с использованием файлов csv. Это нельзя назвать напрямую резервным копированием, но в рамках данной инструкции материал будет интересен.

Создание файла CSV (экспорт)

Пример запроса (выполняется в командной оболочке SQL):

> COPY (SELECT * FROM public.users WHERE name LIKE ‘А%’) TO ‘/tmp/users.csv’ WITH CSV DELIMITER ‘;’ HEADER;

* в данном примере мы выгрузим все данные для таблицы users в схеме public, где значение поля name начинается с буквы А. Результат будет сохранен в файл /tmp/users.csv. Также мы указываем, что в качестве разделителя данных нужно использовать точку с запятой и первой строкой сделать заголовок.

Также мы можем сделать выгрузку, но сделать вывод в оболочку и перенаправить его в файл:

psql -d «postgresql://pg_user:pg_pass@localhost:5432/pg_databasename» -c «COPY (SELECT * FROM public.users WHERE name LIKE ‘А%’) TO STDIN WITH CSV DELIMITER ‘;’ HEADER;» > /tmp/users.csv

Импорт данных из файла CSV

Также можно выполнить запрос в оболочке SQL:

> COPY public.users FROM ‘/tmp/test.csv’ DELIMITER ‘;’ CSV HEADER;

Или перенаправить запрос через STDOUT из файла:

psql -d «postgresql://pg_user:pg_pass@localhost:5432/pg_databasename» -c «COPY public.users FROM STDOUT DELIMITER ‘;’ CSV HEADER;» < /tmp/users.csv

* в нашем примере мы выполним импорт данных из ранее созданного файла /tmp/users.csv в таблицу users.

Возможные ошибки

Рассмотрим некоторые проблемы, с которыми можно столкнуться при работе с дампами PostgreSQL.

Input file appears to be a text format dump. please use psql.

Причина: дамп сделан в текстовом формате, поэтому нельзя использовать утилиту pg_restore.

Решение: восстановить данные можно командой psql <имя базы> < <файл с дампом> или выполнив SQL, открыв файл, скопировав его содержимое и вставив в SQL-редактор.

No matching tables were found

Причина: Таблица, для которой создается дамп не существует. Утилита pg_dump чувствительна к лишним пробелам, порядку ключей и регистру.

Решение: проверьте, что правильно написано название таблицы и нет лишних пробелов.

Too many command-line arguments

Причина: Утилита pg_dump чувствительна к лишним пробелам.

Решение: проверьте, что нет лишних пробелов.

Aborting because of server version mismatch

Причина: несовместимая версия сервера и утилиты pg_dump. Может возникнуть после обновления или при выполнении резервного копирования с удаленной консоли.

Решение: нужная версия утилиты хранится в каталоге /usr/lib/postgresql/<version>/bin/. Необходимо найти нужный каталог, если их несколько и запускать нужную версию. При отсутствии последней, установить.

No password supplied

Причина: нет системной переменной PGPASSWORD или она пустая.

Решение: либо настройте сервер для предоставление доступа без пароля в файле pg_hba.conf либо экспортируйте переменную PGPASSWORD (export PGPASSWORD или set PGPASSWORD).

Неверная команда \

Причина: при выполнении восстановления возникла ошибка, которую СУБД не показывает при стандартных параметрах восстановления.

Решение: запускаем восстановление с опцией -v ON_ERROR_STOP=1, например:

psql -v ON_ERROR_STOP=1 users < /tmp/users.dump

Теперь, когда возникнет ошибка, система прекратит выполнять операцию и выведет сообщение на экран.

Locally, I use pgadmin3. On the remote server, however, I have no such luxury.

I’ve already created the backup of the database and copied it over, but is there a way to restore a backup from the command line? I only see things related to GUI or to pg_dumps.

starball's user avatar

starball

22.1k8 gold badges47 silver badges286 bronze badges

asked Apr 28, 2010 at 19:18

TwixxyKit's user avatar

There are two tools to look at, depending on how you created the dump file.

Your first source of reference should be the man page pg_dump as that is what creates the dump itself. It says:

Dumps can be output in script or
archive file formats. Script dumps are
plain-text files containing the SQL
commands required to reconstruct
the database to the state it was
in at the time it was saved. To
restore from such a script, feed it to
psql(1). Script files can be used
to reconstruct the database even
on other machines and other
architectures; with some modifications
even on other SQL database products.

The alternative archive file formats
must be used with pg_restore(1) to
rebuild the database. They allow
pg_restore to be selective about what
is restored, or even to reorder the
items prior to being restored. The
archive file formats are designed to
be portable across architectures.

So depends on the way it was dumped out. If using Linux/Unix, you can probably figure it out using the excellent file(1) command — if it mentions ASCII text and/or SQL, it should be restored with psql otherwise you should probably use pg_restore.

Restoring is pretty easy:

psql -U username -d dbname < filename.sql

-- For Postgres versions 9.0 or earlier
psql -U username -d dbname -1 -f filename.sql

or

pg_restore -U username -d dbname -1 filename.dump

Check out their respective manpages — there’s quite a few options that affect how the restore works. You may have to clean out your «live» databases or recreate them from template0 (as pointed out in a comment) before restoring, depending on how the dumps were generated.

Steve Chambers's user avatar

answered Apr 28, 2010 at 19:25

Steven Schlansker's user avatar

Steven SchlanskerSteven Schlansker

37.7k14 gold badges82 silver badges101 bronze badges

16

create backup

pg_dump -h localhost -p 5432 -U postgres -F c -b -v -f 
"/usr/local/backup/10.70.0.61.backup" old_db

-F c is custom format (compressed, and able to do in parallel with -j N) -b is including blobs, -v is verbose, -f is the backup file name.

restore from backup

pg_restore -h localhost -p 5432 -U postgres -d old_db -v 
"/usr/local/backup/10.70.0.61.backup"

important to set -h localhost — option

Eduardo Cuomo's user avatar

answered May 28, 2012 at 8:55

Alex Deemann's user avatar

Alex DeemannAlex Deemann

3,6162 gold badges14 silver badges9 bronze badges

4

You might need to be logged in as postgres in order to have full privileges on databases.

su - postgres
psql -l                      # will list all databases on Postgres cluster

pg_dump/pg_restore

  pg_dump -U username -f backup.dump database_name -Fc 

switch -F specify format of backup file:

  • c will use custom PostgreSQL format which is compressed and results in smallest backup file size
  • d for directory where each file is one table
  • t for TAR archive (bigger than custom format)
  • -h/--host Specifies the host name of the machine on which the server is running
  • -W/--password Force pg_dump to prompt for a password before connecting to a database

restore backup:

   pg_restore -d database_name -U username -C backup.dump

Parameter -C should create database before importing data. If it doesn’t work you can always create database eg. with command (as user postgres or other account that has rights to create databases) createdb db_name -O owner

pg_dump/psql

In case that you didn’t specify the argument -F default plain text SQL format was used (or with -F p). Then you can’t use pg_restore. You can import data with psql.

backup:

pg_dump -U username -f backup.sql database_name

restore:

psql -d database_name -f backup.sql

answered Aug 31, 2013 at 8:42

Tombart's user avatar

TombartTombart

30.7k16 gold badges123 silver badges137 bronze badges

5

POSTGRESQL 9.1.12

DUMP:

pg_dump -U user db_name > archive_name.sql

put the user password and press enter.

RESTORE:

psql -U user db_name < /directory/archive.sql

put the user password and press enter.

Aamir's user avatar

Aamir

16.4k10 gold badges59 silver badges65 bronze badges

answered Sep 12, 2014 at 22:14

Natan Medeiros's user avatar

Natan MedeirosNatan Medeiros

1,3491 gold badge11 silver badges15 bronze badges

1

Below is my version of pg_dump which I use to restore the database:

pg_restore -h localhost -p 5432 -U postgres -d my_new_database my_old_database.backup

or use psql:

psql -h localhost -U postgres -p 5432 my_new_database < my_old_database.backup

where -h host, -p port, -u login username, -d name of database

Eduardo Cuomo's user avatar

answered Aug 24, 2016 at 12:43

Yahor M's user avatar

Yahor MYahor M

6278 silver badges8 bronze badges

2

Backup and restore with GZIP

For larger size database this is very good

backup

pg_dump -U user -d mydb | gzip > mydb.pgsql.gz

restore

gunzip -c mydb.pgsql.gz | psql dbname -U user

https://www.postgresql.org/docs/14/backup-dump.html

answered Oct 14, 2016 at 7:13

Sarath Ak's user avatar

Sarath AkSarath Ak

7,9512 gold badges47 silver badges48 bronze badges

3

This worked for me:

pg_restore --verbose --clean --no-acl --no-owner --host=localhost --dbname=db_name --username=username latest.dump

Andreas Baumgart's user avatar

answered Aug 10, 2019 at 6:40

Francesco's user avatar

FrancescoFrancesco

3213 silver badges2 bronze badges

1

Backup:  $ pg_dump -U {user-name} {source_db} -f {dumpfilename.sql}

Restore: $ psql -U {user-name} -d {desintation_db} -f {dumpfilename.sql}

answered Feb 25, 2014 at 15:20

Aaron Lelevier's user avatar

Aaron LelevierAaron Lelevier

19.9k11 gold badges77 silver badges111 bronze badges

0

Backup & Restore

This is the combo I’m using to backup, drop, create and restore my database (on macOS and Linux):

sudo -u postgres pg_dump -Fc mydb > ./mydb.sql
sudo -u postgres dropdb mydb
sudo -u postgres createdb -O db_user mydb
sudo -u postgres pg_restore -d mydb < ./mydb.sql

Misc

  • -Fc will compress the database (Format custom)
  • List PostgreSQL users: sudo -u postgres psql -c "\du+"
  • You may want to add hostname and date to ./mydb.sql, then change it by:
    ./`hostname`_mydb_`date +"%Y%m%d_%H%M"`.sql
    

answered Oct 7, 2020 at 13:09

DevonDahon's user avatar

DevonDahonDevonDahon

7,4926 gold badges72 silver badges117 bronze badges

1

try this:

psql -U <username> -d <dbname> -f <filename>.sql

Restore DB psql from .sql file

Ehsan's user avatar

Ehsan

6147 silver badges21 bronze badges

answered Nov 19, 2018 at 9:52

Faysal Maqsood's user avatar

1

1. Open the Terminal.

2. Backup your database with following command

your postgres bin -> /opt/PostgreSQL/9.1/bin/

your source database server -> 192.168.1.111

your backup file location and name -> /home/dinesh/db/mydb.backup

your source db name -> mydatabase

/opt/PostgreSQL/9.1/bin/pg_dump --host '192.168.1.111' --port 5432 --username "postgres" --no-password  --format custom --blobs --file "/home/dinesh/db/mydb.backup" "mydatabase"

3. Restore mydb.backup file into destination.

your destination server -> localhost

your destination database name -> mydatabase

Create database for restore the backup.

/opt/PostgreSQL/9.1/bin/psql -h 'localhost' -p 5432 -U postgres -c "CREATE DATABASE mydatabase"

Restore the backup.

/opt/PostgreSQL/9.1/bin/pg_restore --host 'localhost' --port 5432 --username "postgres" --dbname "mydatabase" --no-password --clean "/home/dinesh/db/mydb.backup"

Kayvan Mazaheri's user avatar

answered Oct 11, 2013 at 6:09

Dinesh Appuhami's user avatar

Dinesh AppuhamiDinesh Appuhami

7101 gold badge11 silver badges24 bronze badges

If you create a backup using pg_dump you can easily restore it in the following way:

  1. Open command line window
  2. Go to Postgres bin folder. For example: cd "C:\ProgramFiles\PostgreSQL\9.5\bin"
  3. Enter the command to restore your database. For example: psql.exe -U postgres -d YourDatabase -f D:\Backup\.sql
  4. Type password for your postgres user
  5. Check the restore process

answered May 30, 2017 at 10:46

I didnt see here mentions about dump file extension (*.dump).

This solution worked for me:

I got a dump file and needed to recover it.

First I tried to do this with pg_restore and got:

pg_restore: error: input file appears to be a text format dump. Please use psql.

I did it with psql and worked well:

psql -U myUser -d myDataBase < path_to_the_file/file.dump

answered Jun 23, 2020 at 14:47

Igr Pn's user avatar

Igr PnIgr Pn

1312 silver badges3 bronze badges

To restore a dump file

psql -d [Dbname] -U [UserName] -p 5432 < [FileLocation]

To restore a .SQL file

pg_restore -U [Username] -d [Dbname] -1 [FileLocation]

If you get user authentication errors, go to the file pg_hba.conf which is in PSQL/data folder in your program files, and change the «METHOD» to «Trust».
Restart you psql serive in windows services(Win + R —> services.msc).

answered Oct 6, 2021 at 2:44

Harrish Selvarajah's user avatar

1) Open psql terminal.

2) Unzip/ untar the dump file.

3) Create an empty database.

4) use the following command to restore the .dump file

<database_name>-# \i <path_to_.dump_file>

answered Oct 22, 2018 at 6:56

Vaibhav Desai's user avatar

Vaibhav DesaiVaibhav Desai

2,3322 gold badges25 silver badges29 bronze badges

If you are using docker, this answer may be helpful.

  1. Start the container
    docker start <postgres_container_id>
    
  2. Access bash inside container
    docker exec -it <postgres_container_id> bash
    
  3. Copy the .tar backup file to docker container (In another window)
    docker cp postgres_dump.tar <postgres_container_id>:/
    
  4. Restore the backup
    pg_restore -c -U <postgres-user> -d <database-name>  -v "postgres_dump.tar" -W
    
  5. Enter password

Chris Edwards's user avatar

answered Oct 19, 2022 at 12:40

Henshal B's user avatar

Henshal BHenshal B

1,58812 silver badges13 bronze badges

try:

pg_restore -h localhost -p 5432 -U <username> -d <dbname> -1 <filename>

answered Nov 19, 2018 at 18:44

Cristhian Gonzalez's user avatar

Restoring a postgres backup file depends on how did you take the backup in the first place.

If you used pg_dump with -F c or -F d you need to use pg_restore otherwise you can just use

psql -h localhost -p 5432 -U postgres < backupfile

9 ways to backup and restore postgres databases

answered Oct 14, 2014 at 17:22

Prashant Kumar's user avatar

1

The shortest way with no password prompt

psql "postgresql://<db_user>:<db_pass>@<ip>:<port>/<db_name>" < "backup.sql"

If you are using Windows OS

psql.exe "postgresql://<db_user>:<db_pass>@<ip>:<port>/<db_name>" < "backup.sql"

answered Dec 8, 2021 at 13:51

Masih Jahangiri's user avatar

Masih JahangiriMasih Jahangiri

9,6473 gold badges46 silver badges51 bronze badges

Sorry for the necropost, but these solutions did not work for me. I’m on postgres 10. On Linux:

  1. I had to change directory to my pg_hba.conf.
  2. I had to edit the file to change method from peer to md5 as stated here
  3. Restart the service: service postgresql-10 restart
  4. Change directory to where my backup.sql was located and execute:
    psql postgres -d database_name -1 -f backup.sql

    -database_name is the name of my database

    -backup.sql is the name of my .sql backup file.

answered Jan 13, 2020 at 21:43

Tim's user avatar

TimTim

4884 silver badges15 bronze badges

Save and restore the exact same state with compressed dump

Other answers gave all the key bits separately, but hopefully this will provide be the «just works save and restore to exact state» command pair.

Dump to file mydb.psql:

PGPASSWORD=mypassword pg_dump -U my_username -h localhost mydb -Fc -f mydb.psql

Restore:

PGPASSWORD=mypassword pg_restore -U my_username -h localhost \
  --clean -d mydb -v mydb.psql

Some of the flags:

  • -Fc: Format Compressed, as opposed to plaintext.

    file tmp.psql says:

    tmp.psql: PostgreSQL custom database dump - v1.14-0
    
  • --clean: destroy the target DB before restoring it, thus returning to the exact same pristine state.

    Any data created after the dump will be lost.

PGPASSWORD, -U and -h can of course be modified depending on your login method, e.g. without PGPASSWORD you’re prompted for a password, and none of those are needed if you set up peer auth locally.

Tested on Ubuntu 22.04, PostgreSQL 14.5.

answered Nov 18, 2022 at 18:57

Ciro Santilli OurBigBook.com's user avatar

Try to see if the following commands can help you:

sudo su - yourdbuser
psql
\i yourbackupfile

Fabien's user avatar

Fabien

4,8622 gold badges19 silver badges33 bronze badges

answered Aug 9, 2017 at 14:27

Dr. Mehmet Ali ATICI's user avatar

If you have a backup SQL file then you can easily Restore it.
Just follow the instructions, given in the below

1. At first, create a database using pgAdmin or whatever you want (for example my_db is our created db name)
2. Now Open command line window
3. Go to Postgres bin folder. For example:  cd "C:\ProgramFiles\PostgreSQL\pg10\bin"
4. Enter the following command to restore your database: psql.exe -U postgres -d my_db -f D:\Backup\backup_file_name.sql 

Type password for your postgres user if needed and let Postgres to do its work. Then you can check the restore process.

answered Mar 20, 2019 at 12:38

Omar's user avatar

OmarOmar

91111 silver badges14 bronze badges

I was having authentication problems running pg_dump, so I moved my dump file

mv database_dump /tmp

into the temp directory and then ran

su -u postgres
cd /tmp
pg_restore database_dump

If you have a large database dump, you may just want to create another directory where your current user and the postgres user can access and putting the database dump file into that.

answered Jul 19, 2017 at 3:04

user1876508's user avatar

user1876508user1876508

12.9k21 gold badges68 silver badges105 bronze badges

Backup==>

Option1: To take backup along with password in cmd
1.PGPASSWORD="mypassword" pg_dump -U postgres -h localhost --inserts mydb>mydb.sql
Option2: To take backup without password in cmd
2. pg_dump -U postgres -h localhost --inserts mydb>mydb.sql
Option3: To take backup as gzip(if database is huge)
3. pg_dump -U postgres -h localhost mydb --inserts | gzip > mydb.gz

Restore:
1. psql -h localhost -d mydb -U postgres -p 5432 < mydb.sql

answered Sep 21, 2020 at 7:56

Ramesh Ponnusamy's user avatar

This solution only works for Windows.

First, ensure you have already added the postgres bin folder to the «Path» environment variable (in my case this folder is C:\Program Files\PostgreSQL\12\bin).

Then, open the Windows command interpreter (cmd), go to the folder where you have the .sql file and execute this command:

pg_restore -U userName -d database-1 backupfile.sql

For example:

pg_restore -U sam -d SamDataBase -1 SamDataBaseBackup.sql

(It can ask you for the password of the user so ensure to type it correctly and then click enter)

Pura vida!

answered Jun 14, 2021 at 6:20

Johnny Chacon's user avatar

If you have created a new database named mydb, To restore a .sql dump to that database with psql,

psql --file=dump.sql --username=postgres --host=localhost --port=5432 mydb

the password will be prompted by psql

The connection options are

  -h, --host=HOSTNAME      database server host or socket directory (default: "/var/run/postgresql")
  -p, --port=PORT          database server port (default: "5432")
  -U, --username=USERNAME  database user name (default: "xyz")
  -w, --no-password        never prompt for password
  -W, --password           force password prompt (should happen automatically)

answered Aug 25, 2021 at 14:13

All Іѕ Vаиітy's user avatar

All Іѕ VаиітyAll Іѕ Vаиітy

25k16 gold badges88 silver badges111 bronze badges

If you want to backup your data or restore data from a backup, you can run the following commands:

  1. To create backup of your data, go to your postgres \bin\ directory like C:\programfiles\postgres\10\bin\ and then type the following command:

    pg_dump -FC -U ngb -d ngb -p 5432 >C:\BACK_UP\ngb.090718_after_readUpload.backup
    
  2. To restore data from a backup, go to your postgres \bin\ directory like C:\programfiles\postgres\10\bin\ and then type below command:

    C:\programFiles\postgres\10\bin> pg_restore -Fc -U ngb -d ngb -p 5432 <C:\ngb.130918.backup
    

    Please make sure that the backup file exists.

tripleee's user avatar

tripleee

176k34 gold badges275 silver badges318 bronze badges

answered Sep 17, 2018 at 8:23

Girjesh Kumar Suryawanshi's user avatar

Maybe try this command it will work

psql -U postgres -W -d Test2 < E:\SampleProject\samplebackup.sql

answered Sep 27 at 7:35

SDR's user avatar

Restoring a database, is the action of copying the backed up data and restoring it at its original or new place. We perform restore action on a database so as to return the data to its original state before being lost, stolen or corrupted. There are several causes due to which one needs to restore a database like – due as human errors sometimes data gets corrupted; some malicious attacks on the database might infect it; due to power outages; natural calamities like floods, storms etc. Thus, in these cases, a data restore makes a usable copy of data and ensures that restored backup data is inline and consistent with the state of the data before the damage occurred.

Approach:

In PostgreSQL also, we can back up and restore the data. To restore a database, we have 2 main approaches:

  1. To restore via PgAdmin4 GUI
  2. To restore via command line

Here we are going to see both the approaches in detail.

1. Using PgAdmin GUI 

In the first approach, we are going to restore our database from the pgAdmin4. This is a very simple and straightforward process. For this we are going to follow the steps listed as below –

1. Start the pgAdmin database server and login to the pgAdmin4 control panel via valid credentials.

2. Expand the Servers section and navigate till Databases. Now, here you will find all your databases the server is currently hosting (if any).

3. Now we need to create a new database which will serve as a placeholder for our database which is to be restored. For this, right click on the Databases section, select Create -> Database.

4. In the General tab specify the name of your database which is to be restored. Owner must be same as the current postgres Admin username. You  can also add optional comments.

5. Now to go Definition tab, select appropriate character encoding, tablespaces etc. Fill all the required details of any in similar ways on the alongside tabs like Security, Parameters tabs as well.

6. After filling all necessary details, select Save option. Database will now be created successfully and will be listed alongside the existing databases in the Databases section.

7. Right-click on the newly created database by you and select Restore option from the list.

8. After clicking Restore option, a new pop-up dialogue box menu of Restore will show up on the screen as below.

9. Now specify the Format of the file. Right-click on the horizontal kebab menu to browse for the location of file, select the role name as postgres (root owner). Hit Restore button.

10. A new restore job is now created on the pgAdmin4 server and usually appears in the bottom right corner of the window. 

11. After successful restore operation is a success prompt is displayed at the same position as said above with the success message. In case of a failure of the restore option, a failure message is also given when we click on the More Details (i) button.

12. Success !! Our PostgreSQL database is now completely restored. It is now in fully up and running state.

2. Restoration via command line

To restore a database via the command line, we are going to follow the following procedure –

1. Firstly, we need to login to the PostgreSQL terminal via command line. To do so, type in the following command :-

psql -U <username>

2. We can now see that we are successfully logged into the psql client terminal and have got the postgres command line input prompt.

3. We will now follow the same process as we followed in the above part I, the only difference being here is that, we are going to do this time via the command line terminal of PostgreSQL.

4.  Let’s now create a placeholder database for our purpose which will be used to restore the backup. To do so, run the below script.

CREATE DATABASE BackupDB ENCODING='UTF-8' OWNER='postgres';

5. Database is now created. Let us restore it now. To restore the database, we are going to use the pg_restore command supplied with some arguments. It is important to note here that, we need to exit from the psql terminal in order to run pg_restore command. To exit from psql terminal, type “\q” to exit.

6. Key in the pg_restore command with the following arguments –

pg_restore -U postgres -d backupdb -v "D:\Backup.sql"

The detailed explanation of the arguments for PostgreSQL can be found on the PostgreSQL’s official website on the documentation section of pg_restore.

7. After successful restoration of  database, we will se that our schema are restored alongwith the tables and their data.

Thus, in this article, we have successfully explored the two ways of successfully restoring the database.

Last Updated :
28 Jul, 2021

Like Article

Save Article

  • Windows powershell как перейти в папку
  • Windows powershell прекращена работа программы
  • Windows post install для windows 10
  • Windows player plugin скачать бесплатно
  • Windows powershell для windows 2003 server