pg_dump
pg_dump — выгрузить базу данных Postgres Pro в виде скрипта или в архивном формате
Синтаксис
pg_dump [параметр-подключения...] [параметр...] [имя_бд]
Описание
pg_dump — это программа для создания резервных копий базы данных Postgres Pro. Она создаёт целостные копии, даже если база параллельно используется. Программа pg_dump не препятствует доступу других пользователей к базе данных (ни для чтения, ни для записи).
Программа pg_dump выгружает только одну базу данных. Чтобы сохранить глобальные объекты, относящиеся ко всем базам в кластере, например, роли и табличные пространства, воспользуйтесь программой pg_dumpall.
Выгружаемые данные могут быть сохранены в виде скрипта, либо в одном из архивных форматов. Скрипты представляют собой текстовые файлы, содержащие SQL-команды, необходимые для воссоздания базы данных до состояния на момент создания скрипта. Для восстановления из скрипта его содержимое можно передать psql. Скрипты можно использовать для восстановления базы на других машинах, в том числе с иной архитектурой, а с некоторыми коррективами даже в других СУБД.
Для восстановления из архивных форматов файлов используется утилита pg_restore. Эти форматы позволяют указывать pg_restore какие объекты базы данных восстановить, а также позволяют изменить порядок следования восстанавливаемых объектов. Архивные форматы файлов спроектированы так, чтобы их можно были переносить на другие платформы с другой архитектурой.
Применение архивных форматов в сочетании утилит pg_restore и pg_dump позволяет организовывать эффективный механизм архивации и переноса данных. pg_dump можно использовать для резервирования всей базы данных, а затем при применении pg_restore выбрать нужные объекты для восстановления. Наиболее гибкие форматы выходных файлов это «custom» (-Fc) и «directory» (-Fd). Они позволяют выбрать и изменить порядок объектов, поддерживают восстановление в несколько потоков, а также сжимаются по умолчанию. При этом только формат «directory» поддерживает выгрузку данных в несколько потоков.
Во время работы pg_dump следует обращать внимание на предупреждения, которые печатаются в стандартный поток ошибок, особенно ввиду рассмотренных далее ограничений.
Параметры
Параметры командной строки для управления содержимым и форматом вывода.
имя_бдУказывает имя базы данных, из которой будут выгружаться данные. Если имя не задано, то используется значение переменной окружения
PGDATABASE. Если и переменная не задана, то в качестве имени базы будет взято имя пользователя, под которым осуществляется подключение.-a--data-onlyВыводить только данные, но не схемы объектов (DDL). Будут копироваться данные таблиц, большие объекты, значения последовательностей.
Флаг похож на
--section=data, но по историческим причинам не равнозначен ему.-b--blobsВключить большие объекты в выгрузку. Это поведение по умолчанию при отсутствии ключей
--schema,--tableили--schema-only. Таким образом, ключ-bполезен, лишь когда нужно добавить большие объекты при выгрузке только избранной схемы или таблицы. Заметьте, что большие объекты относятся к данным, и поэтому будут выгружаться, когда используется ключ --data-only, но не ключ --schema-only.-B--no-blobsИсключить из выгрузки большие объекты.
Когда задаётся и
-b, и-B, большие объекты при выгрузке данных будут выводиться (см. описание ключа-b).-c--cleanВключить в выходной файл команды удаления (DROP) объектов базы данных перед командами создания (CREATE) этих объектов. Если дополнительно не указать флаг
--if-exists, то при восстановлении в базу данных, где некоторые объекты отсутствуют, попытка удаления несуществующего объекта будет приводить к ошибке, которую можно игнорировать.Этот параметр игнорируется, когда данные выгружаются в архивных форматах (не в текстовом). Для таких форматов данный параметр можно указать при вызове
pg_restore.-C--createСформировать в начале вывода команду для создания базы данных и затем подключения к ней. В этом случае не важно, какая база указана в параметрах подключения перед выполнением скрипта. Также, если указан ключ
--clean, то скрипт сначала удалит, а затем пересоздаст базу данных перед подключением к ней.Этот параметр игнорируется, когда данные выгружаются в архивных форматах (не в текстовом). Для таких форматов данный параметр можно указать при вызове
pg_restore.-Eкодировка--encoding=кодировкаСоздать копию в заданной кодировке. По умолчанию копия создаётся в кодировке, используемой базой данных. Другой способ достичь того же результата — задать желаемую кодировку в переменной окружения
PGCLIENTENCODING.-fфайл--file=файлОтправить вывод в указанный файл. Параметр можно не указывать, если используется формат с выводом в файл. В этом случае будет использован стандартный вывод. Однако для формата с выводом в каталог параметр является обязательным и должен задавать путь к каталогу. В этом случае целевой каталог будет создан командой
pg_dumpи не должен существовать заранее.-Fformat--format=formatУказывает формат вывода копии.
formatможет принимать следующие значения:pplainСформировать текстовый SQL-скрипт. Это поведение по умолчанию.
ccustomВыгрузить данные в специальном архивном формате, пригодном для дальнейшего использования утилитой pg_restore. Наряду с форматом
directoryявляется наиболее гибким форматом, позволяющим вручную выбирать и сортировать восстанавливаемые объекты. Вывод в этом формате по умолчанию сжимается.ddirectoryВыгрузить данные в формате каталога. Этот формат пригоден для дальнейшего использования утилитой pg_restore. При этом будет создан каталог, в котором для каждой таблицы и большого объекта будут созданы отдельные файлы, а также файл оглавления в машинно-читаемом формате, понятном для pg_restore. С полученной резервной копией можно работать штатными средствами Unix, например, несжатую копию можно сжать посредством gzip. Этот формат по умолчанию сжимается, а также поддерживает работу в несколько потоков.
ttarВыгрузить данные в формате
tar, для дальнейшего использования с утилитой pg_restore. Этот формат совместим с форматом вывода в каталог: если архив распаковать, получится корректная копия в формате каталога. Однако формат tar не поддерживает сжатие. Также, применяя формат tar, при восстановлении нельзя изменить относительный порядок элементов данных.
-jчисло_заданий--jobs=число_заданийОсуществить выгрузку в параллельном режиме, обрабатывая одновременно несколько таблиц (в количестве
число_заданий). Это уменьшает время работы, но увеличивает нагрузку на сервер. Этот параметр можно использовать только с форматом вывода в каталог, так как это единственный формат, позволяющий нескольким процессам записывать данные одновременно.pg_dump откроет
число_заданий+ 1 соединений с базой данных. Таким образом необходимо обеспечить достаточное значение параметра max_connections.Если во время выгрузки в несколько потоков, параллельно работающие сессии будут запрашивать эксклюзивные блокировки на объекты базы данных, то pg_dump может завершиться аварийно. Дело в том, что головной процесс pg_dump вначале запрашивает разделяемые блокировки на объекты, которые позже будут выгружать рабочие процессы. Это делается для того, чтобы никто не смог удалить объекты на время работы pg_dump. Если же другая сессия запросит эксклюзивную блокировку на объект, то запрос на блокировку будет поставлен в очередь, до тех пор пока разделяемая блокировка головного процесса pg_dump не будет снята. В последующем, любая попытка доступа к этому объекту будет вставать в очередь, вслед за эксклюзивной блокировкой. В том числе в очередь попадет и рабочий процесс pg_dump. Если не принять меры предосторожности, то получим классическую взаимоблокировку. Для предупреждения подобных конфликтов, рабочий процесс pg_dump ещё раз запрашивает разделяемую блокировку на объект с указанием
NOWAIT. И если он не смог получить блокировку, значит кто-то ещё запросил эксклюзивную блокировку объекта. А это значит, что нет возможности продолжить выгрузку, поэтому pg_dump прерывает дальнейшую работу.Для получения целостной резервной копии сервер баз данных должен поддерживать функциональность синхронизированных снимков, которая была введена в версии PostgreSQL 9.2 для ведущих серверов и в 10 для ведомых. Это позволяет разным клиентам работать с одной и той же версией данных, несмотря на использование разных подключений.
pg_dump -jиспользует множественные подключения. Первое подключение осуществляется головным процессом, а последующие — рабочими процессами. Без функциональности синхронизируемых снимков нет гарантии того, что каждое подключение увидит одни и те же данные, что может привести к несогласованности данных резервной копии.Если необходимо выполнить выгрузку в несколько потоков на сервере версии до 9.2, необходимо быть уверенным, что база данных не будет изменяться с момента подключения головного процесса и до момента, когда последний рабочий процесс подключится к базе данных. Для этого, проще всего перед запуском pg_dump остановить все процессы, модифицирующие данные (DML и DDL). Также, при запуске
pg_dump -jна сервере PostgreSQL до версии 9.2 нужно указывать параметр--no-synchronized-snapshots.-nсхема--schema=схемаВыгрузить только схемы, соответствующие шаблону
схема; вместе с этими схемами будут выгружены и все содержащиеся в них объекты. Когда этот параметр отсутствует, выгружаются все несистемные схемы в целевой базе данных. Чтобы выгрузить несколько схем, ключ-nможно указать несколько раз. Кроме того, параметрсхемаинтерпретируется по тем же правилам, что и шаблон в командах psql\d(см. Шаблоны поиска), так что несколько схем можно выбрать и шаблоном со знаками подстановки. Используя знаки подстановки, при необходимости заключайте шаблон в кавычки, чтобы эти знаки не разворачивала оболочка системы; см. Примеры.Примечание
При использовании
-n, pg_dump не выгружает объекты других схем, от которых выгружаемая схема может зависеть. Таким образом не гарантируется, что выгруженная схема будет успешно восстановлена в чистой базе данных.Примечание
Не принадлежащие схемам объекты (например, большие бинарные объекты), не выгружаются с параметром
-n. Однако можно указать--blobs, чтобы они попали в выгрузку.-Nсхема--exclude-schema=схемаНе выгружать схемы, соответствующие шаблону
схема. Шаблон интерпретируется по тем же правилам, что и для параметра-n. Параметр-Nможно использовать в команде несколько раз для исключения схем, соответствующих нескольким шаблонам.При одновременном использовании параметров
-nи-Nбудут выгружаться схемы, соответствующие шаблону параметра-nи не противоречащие шаблону параметра-N.-o--oidsВыгружать идентификаторы объектов (OIDs) вместе с данными таблиц. Используйте этот параметр, если в приложении есть ссылки на OID, например во внешних ключах. В противном случае этот параметр лучше не использовать.
-O--no-ownerНе формировать команды, устанавливающие владельца объектов базы данных. По умолчанию pg_dump генерирует команды
ALTER OWNERилиSET SESSION AUTHORIZATIONдля назначения владельцев объектов базы. Эти команды завершатся неудачно, если скрипт будет запущен не суперпользователем или не владельцем объектов. Чтобы создать скрипт, который можно выполнить при восстановлении от лица произвольного пользователя и назначить его в качестве владельца объектов восстанавливаемой базы, необходимо указать флаг-O.Этот параметр игнорируется, когда данные выгружаются в архивных форматах (не в текстовом). Для таких форматов данный параметр можно указать при вызове
pg_restore.-R--no-reconnectПараметр является устаревшим, но в целях совместимости ещё работает.
-s--schema-onlyВыгружать только определения объектов (схемы), без данных.
Действие параметра противоположно действию
--data-only. Это похоже на указание--section=pre-data --section=post-data, но по историческим причинам не равнозначно ему.(Не путайте этот параметр с
--schema, где слово «схема» используется в другом значении.)Чтобы не выгружать данные отдельных таблиц, используйте параметр
--exclude-table-data.-Sимя_пользователя--superuser=имя_пользователяУказать суперпользователя, который будет использоваться для отключения триггеров. Параметр имеет значение только вместе с
--disable-triggers. Обычно его лучше не использовать, а запускать полученный скрипт от имени суперпользователя.-tтаблица--table=таблицаВыгрузить только таблицы, соответствующие шаблону
таблица. В этом контексте под «таблицей» подразумеваются также представления, материализованные представления, последовательности и сторонние таблицы. Чтобы выбрать несколько таблиц, ключ-tможно указать несколько раз. Кроме того, параметртаблицаинтерпретируется по тем же правилам, что и шаблон в командах psql\d(см. Шаблоны поиска), так что несколько таблиц можно выбрать и с шаблоном со знаками подстановки. Используя знаки подстановки, при необходимости заключайте шаблон в кавычки, чтобы эти знаки не разворачивала оболочка системы; см. Примеры.Параметры
-nи-Nне действуют в присутствии параметра-t, так как отобранные им таблицы всё равно будут выгружены, а не табличные объекты выгружаться не будут.Примечание
При использовании
-t, pg_dump не выгружает прочие объекты, от которых выгружаемые таблицы могут зависеть. Таким образом не гарантируется, что выгруженные таблицы будут успешно восстановлены в чистой базе данных.Примечание
Поведение параметра
-tдля версий ниже чем PostgreSQL 8.2 отличается от более поздних. Прежде, указание-t таблицавключало все таблицы, соответствующие шаблонутаблица, а сейчас это приведёт к выгрузке только тех таблиц, которые будут обнаружены в текущем пути поиска. Для получения старого поведения можно использовать конструкцию вида-t '*.таблица'. Также, чтобы указать таблицу из конкретной схемы, сейчас лучше использовать-t схема.таблица, вместо старой конструкции-n схема -t таблица.-Tтаблица--exclude-table=таблицаНе выгружать таблицы, соответствующие шаблону
таблица. Шаблон интерпретируется по тем же правилам, что и для параметра-t. Параметр-Tможно использовать в команде несколько раз для исключения таблиц, соответствующих нескольким шаблонам.При одновременном использовании параметров
-tи-Tбудут выгружаться таблицы, соответствующие шаблону параметра-tи не противоречащие шаблону параметра-T.-v--verboseВключить подробный режим. pg_dump будет выводить в стандартный поток ошибок подробные комментарии к объектам, включая время начала и окончания выгрузки, а также сообщения о прогрессе выполнения.
-V--versionВывести версию pg_dump.
-x--no-privileges--no-aclНе выгружать права доступа (команды GRANT/REVOKE).
-Z0..9--compress=0..9Установить уровень сжатия данных. Ноль означает, что сжатие выключено. Для специального формата и формата каталога будут сжиматься файлы отдельных таблиц. По умолчанию применяется умеренный уровень сжатия. Если указать отличный от нулевого уровень сжатия для простого формата, то сжиматься будет весь выходной файл, как это было бы при передаче файла команде gzip. Однако по умолчанию для простого формата сжатие не производится. Формат
tarв настоящий момент не поддерживает сжатие.--add-collproviderЕсли провайдер правил сортировки для выгружаемой базы данных задаётся неявно, этот параметр добавляет явное указание провайдера в выгрузку. Этот вариант рекомендуется, если вы используете pg_dump и pg_restore для обновления с предыдущих версий Postgres Pro или любой версии PostgreSQL. Это позволяет сохранить изначальный провайдер основного правила сортировки для переносимой базы данных, если в базе
template0в новом кластере используются другие параметры правил сортировки. В противном случае ограничения-проверки, которые используют основное правило сортировки в базе данных, могут поменять поведение, и командаCOPYзавершится ошибкой. При обновлении в двоичном формате провайдер сохраняется автоматически.--binary-upgradeЭтот параметр предназначен для утилит обновления сервера. Использование для иных целей не рекомендуется и не поддерживается. Поведение параметра может быть изменено в последующих версиях без предварительного уведомления.
--column-inserts--attribute-insertsВыгружать данные таблиц в виде команд
INSERTс явным указанием столбцов (INSERT INTO). Скорость восстановления при этом значительно снизится, но данный вариант оправдан, когда загружать данные нужно не в Postgres Pro. Также, поскольку для каждой строки генерируется отдельная команда, сбой при последующей загрузке приведёт к потере конкретной строки, а не всей таблицы.таблица(столбец, ...) VALUES ...--disable-dollar-quotingЭтот параметр запрещает заключать в доллары тело функций, что оставляет возможность только заключать их в кавычки, применяя стандартный синтаксис SQL.
--disable-triggersИспользуется при выгрузке одних данных. Указывает pg_dump включать в вывод команды для временного выключения триггеров при восстановлении в целевой базе данных. Применяется в ситуациях, когда существуют проверки ссылочной целостности или другие триггеры, которые необходимо выключить на время восстановления.
В настоящее время команды, генерируемые с параметром
--disable-triggers, должны исполняться от имени суперпользователя. Таким образом, необходимо также передавать флаг-S, либо при восстановлении выполнять скрипт от имени суперпользователя.Этот параметр игнорируется, когда данные выгружаются в архивных форматах (не в текстовом). Для таких форматов данный параметр можно указать при вызове
pg_restore.--enable-row-securityЭтот параметр имеет смысл только при выгрузке содержимого таблицы, для которой включена защита строк. По умолчанию pg_dump устанавливает для row_security значение off, чтобы убедиться, что выгружаются все данные из таблицы. Если пользователь не имеет достаточных прав для обхода защиты строк, выдаётся ошибка. Этот параметр указывает pg_dump включить row_security, что позволит пользователю выгрузить часть содержимого таблицы, к которой он имеет доступ.
Заметьте, что в настоящее время для использования этого параметра обычно желательно, чтобы данные были выгружены в формате
INSERT, так как командаCOPY FROMв процессе восстановления не поддерживает защиту строк.--exclude-table-data=таблицаНе выгружать содержимое таблиц, соответствующих шаблону
таблица. Шаблон таблицы интерпретируется по тем же правилам, что и для параметра-t. Параметр--exclude-table-dataможно использовать в команде несколько раз для исключения таблиц, соответствующих нескольким шаблонам. Полезно, когда нужно получить определение таблицы, без содержимого.Чтобы не выгружать содержимое всех таблиц базы, используйте параметр
--schema-only.--if-existsПри очистке целевой базы использовать условные команды (добавлять предложение
IF EXISTS). Применяется только с параметром--clean.--insertsВыгружать данные таблиц в виде команд
INSERTвместоCOPY. Скорость восстановления при этом значительно снизится, но данный вариант оправдан, когда загружать данные нужно не в Postgres Pro. Также, поскольку для каждой строки генерируется отдельная команда, сбой при последующей загрузке приведёт к потере конкретной строки, а не всей таблицы. Заметьте, что восстановление может провалиться полностью, если у таблицы изменён порядок столбцов. В такой ситуации можно использовать параметр--column-inserts, для которого порядок столбцов не важен, но он работает ещё медленнее.--lock-wait-timeout=время_ожиданияНе ждать бесконечно получения разделяемых блокировок таблиц в начале процедуры выгрузки. Вместо этого выдать ошибку, если не удастся заблокировать таблицы за указанное
время_ожидания. Это время можно задать в любом из форматов, принимаемых командойSET statement_timeout. (Допустимые форматы зависят от версии сервера, выгружающего данные, но количество миллисекунд в виде целого числа принимают все версии.)--no-publicationsНе выгружать публикации.
--no-security-labelsНе выгружать метки безопасности.
--no-subscriptionsНе выгружать подписки.
--no-syncПо умолчанию
pg_dumpждёт, пока все файлы не будут надёжно записаны на диск. С данным параметромpg_dumpзавершается немедленно, то есть выполняется быстрее, но в случае неожиданного сбоя операционной системы выгруженные данные могут оказаться испорченными. Вообще этот параметр предназначен прежде всего для тестирования, для производственной среды он не подходит.--no-synchronized-snapshotsПозволяет запускать
pg_dump -jна серверах с версией ниже чем 9.2. Подробнее в описании параметра-j.--no-tablespacesНе формировать команды для указания табличных пространств. При восстановлении все объекты будут создаваться в табличном пространстве по умолчанию.
Этот параметр игнорируется, когда данные выгружаются в архивных форматах (не в текстовом). Для таких форматов данный параметр можно указать при вызове
pg_restore.--no-unlogged-table-dataНе выгружать данные нежурналируемых таблиц. Параметр не влияет на выгрузку определений таблиц, он только подавляет вывод содержимого таблиц. С резервного сервера содержимое нежурналируемых таблиц не выгружается никогда.
--quote-all-identifiersПринудительно экранировать все идентификаторы. Этот параметр рекомендуется при выгрузке базы, когда основная версия сервера PostgreSQL, с которого выгружается база, отличается от версии pg_dump, или когда выгруженная копия предназначена для загрузки на сервере с другой основной версией. По умолчанию pg_dump экранирует только те идентификаторы, которые являются зарезервированными словами в собственной основной версии. Иногда это приводит к проблемам совместимости с серверами других версий, в которых множество зарезервированных слов может быть несколько другим. Применение параметра
--quote-all-identifiersпредотвращает подобные проблемы, ценой ухудшения читаемости скрипта с выгруженными данными.--section=имя_секцииВыгружать лишь указанную секцию. Имя секции может принимать значения
pre-data,dataилиpost-data. Для выгрузки нескольких секций, параметр можно использовать несколько раз в одной команде. По умолчанию резервируются все секции.Секция
dataсодержит непосредственно данные таблиц, больших объектов и значения последовательностей. Секцияpost-dataсодержит определения индексов, триггеров, правил и ограничений (кроме ограничений проверки, созданных безNOT VALID). Секцияpre-dataвключает определения остальных элементов.--serializable-deferrableИспользовать при выгрузке транзакцию с уровнем изоляции
serializableдля получения снимка, согласованного с последующими состояниями базы. Правда для этого нужно выждать момент, когда в потоке транзакций нет аномалий, и поэтому нет риска, что выгрузка завершится неудачно, и риска отката других транзакций с ошибкойserialization_failure. Более подробно изоляция транзакций и управление одновременным доступом описывается в Главе 13.Параметр не особо полезен в случаях, когда требуется восстановление после сбоя. Он полезен для создания копии базы данных, в которой формируются отчёты и выполняются другие операции чтения, в то время как в основной базе продолжается обычная работа. Без этого параметра выгрузка может содержать не целостное состояние базы данных. Например, если используется пакетная обработка, статус пакета может отражаться как завершённый, в то время как в выгрузке будут не все элементы пакета.
Параметр не будет влиять на результат, если во время запуска pg_dump нет активных транзакций на чтение-запись. Если же активные транзакции чтения-записи есть, то начало выгрузки может быть отложено на неопределённый период времени. После того как выгрузка началась, производительность с этим ключом или без него будет одинаковой.
--snapshot=имя_снимкаИспользовать заданный синхронный снимок при выгрузке данных из базы (за подробностями обратитесь к Таблице 9.82).
Этот параметр полезен, когда требуется синхронизировать выгружаемые данные со слотом логической репликации (см. Главу 46) или с другим одновременным сеансом.
В случае с параллельной выгрузкой будет использоваться имя снимка, определённое этим параметром; новый снимок не будет сделан.
--strict-namesТребует, чтобы каждому указанию схемы (
-n/--schema) и таблицы (-t/--table) соответствовала минимум одна схема/таблица в выгружаемой базе данных. Заметьте, что если не находится вообще ни одной схемы/таблицы для заданных шаблонов, pg_dump выдаёт ошибку и без ключа--strict-names.Этот параметр не действует на ключи
-N/--exclude-schema,-T/--exclude-tableили--exclude-table-data. Если не находятся объекты, соответствующие шаблонам исключения, это не считается ошибкой.--use-set-session-authorizationВыводить команды
SET SESSION AUTHORIZATION, соответствующие стандарту, вместоALTER OWNER, для назначения владельцев объектов. В результате выгруженный скрипт будет более стандартизированным, но может не восстановиться корректно, в зависимости от истории объектов. Кроме того, для использованияSET SESSION AUTHORIZATIONпри восстановлении нужны права суперпользователя, в то время какALTER OWNERтребует меньших привилегий.-?--helpПоказать справку по аргументам командной строки pg_dump и завершиться.
Далее описаны параметры управления подключением.
-dимя_бд--dbname=имя_бдУказывает имя базы данных для подключения. Равнозначно указанию
имя_бдв первом аргументе, не являющемся ключом, в командной строке. Вместо имени может задаваться строка подключения. В этом случае параметры в строке подключения переопределяют одноимённые параметры, заданные в командной строке.-hсервер--host=серверУказывает имя компьютера, на котором работает сервер. Если значение начинается с косой черты, оно определяет каталог Unix-сокета. Значение по умолчанию берётся из переменной окружения
PGHOST, если она установлена. В противном случае выполняется подключение к Unix-сокету.-pпорт--port=портУказывает TCP-порт или расширение файла локального Unix-сокета, через который сервер принимает подключения. Значение по умолчанию определяется переменной окружения
PGPORT, если она установлена, либо числом, заданным при компиляции.-Uимя_пользователя--username=имя_пользователяИмя пользователя, под которым производится подключение.
-w--no-passwordНе выдавать запрос на ввод пароля. Если сервер требует аутентификацию по паролю и пароль не доступен с помощью других средств, таких как файл
.pgpass, попытка соединения не удастся. Этот параметр может быть полезен в пакетных заданиях и скриптах, где нет пользователя, который вводит пароль.-W--passwordПринудительно запрашивать пароль перед подключением к базе данных.
Это несущественный параметр, так как pg_dump запрашивает пароль автоматически, если сервер проверяет подлинность по паролю. Однако чтобы понять это, pg_dump лишний раз подключается к серверу. Поэтому иногда имеет смысл ввести
-W, чтобы исключить эту ненужную попытку подключения.--role=имя ролиЗадаёт имя роли, которая будет осуществлять выгрузку. Получив это имя, pg_dump выполнит
SET ROLEимя_ролипосле подключения к базе данных. Это полезно, когда проходящий проверку пользователь (указанный в-U) не имеет прав, необходимых для pg_dump, но может переключиться на роль, наделённую этими правами. В некоторых окружениях правила запрещают подключаться к серверу непосредственно суперпользователю, и этот параметр позволяет выполнить выгрузку, не нарушая их.
Переменные окружения
PGDATABASEPGHOSTPGOPTIONSPGPORTPGUSERПараметры подключения по умолчанию.
Эта утилита, как и большинство других утилит Postgres Pro, также использует переменные среды, поддерживаемые libpq (см. Раздел 31.14).
Диагностика
pg_dump на низком уровне выполняет команды SELECT. Если есть проблемы с работой pg_dump, убедитесь, что в базе данных можно выполнить SELECT, например из psql. Также следует учитывать, что при этом применяются все свойства подключения по умолчанию и переменные окружения, которые использует клиентская библиотека libpq.
Обычно действия pg_dump в базе данных отслеживаются сборщиком статистики. Если это нежелательно, то можно установить параметр track_counts в false в переменной окружения PGOPTIONS или в команде ALTER USER.
Замечания
Если в базу данных кластера template1 устанавливались дополнительные объекты, то следует убедиться, что выгрузка pg_dump загружается в пустую базу данных. Иначе существует вероятность возникновения ошибок дублирования создаваемых объектов. Чтобы создать пустую базу данных, копируйте её из шаблона template0, вместо template1, например:
CREATE DATABASE foo WITH TEMPLATE template0;
Если выгружаются только данные с одновременным использованием --disable-triggers, pg_dump сформирует команды для выключения табличных триггеров перед вставкой данных, а после них — команды, включающие триггеры обратно. Если восстановление будет прервано в середине процесса, системный каталог может остаться в неверном состоянии.
Сформированный pg_dump файл не содержит данных статистики, используемых планировщиком. Поэтому после восстановления следует выполнить ANALYZE для достижения оптимальной производительности; за дополнительной информацией обратитесь к Подразделу 23.1.3 и Подразделу 23.1.6. Также не выгружаются команды ALTER DATABASE ... SET. Эти свойства, вместе с данными о ролях и прочими глобальными объектами, выгружаются с помощью pg_dumpall.
Так как pg_dump применяется для переноса данных в новые версии Postgres Pro, предполагается, что вывод pg_dump можно загрузить на сервер Postgres Pro более новой версии, чем версия pg_dump. pg_dump может также выгружать данные серверов Postgres Pro более старых версий, чем его собственная. (В настоящее время поддерживаются версии, начиная с PostgreSQL 8.0.) Однако утилита pg_dump не может выгружать данные с серверов Postgres Pro более новых основных версий; она не будет даже пытаться делать это, во избежание некорректной выгрузки. Также не гарантируется, что вывод pg_dump может быть загружен на сервере более старой основной версии — даже если данные были выгружены с сервера той же версии. Для загрузки такого файла на старом сервере может потребоваться вручную исправить в нём синтаксис, не воспринимаемый старой версией. Имея дело с разными версиями, рекомендуется применять параметр --quote-all-identifiers, так как он может предотвратить проблемы, возникающие при изменении множества зарезервированных слов в разных версиях PostgreSQL.
Выгружая подписки на логическую репликацию, pg_dump будет выдавать команды CREATE SUBSCRIPTION с указанием connect = false, так что при восстановлении подписки не будут устанавливаться удалённые подключения для создания слота репликации или для начального копирования таблиц. Таким образом, выгруженные данные могут быть восстановлены без сетевого доступа к удалённым серверам. Вновь активировать подписки должным образом — задача пользователя. Если задействованные серверы поменялись, возможно, придётся скорректировать строки подключения. Также может быть уместно опустошить целевые таблицы перед началом полного копирования таблиц.
Примеры
Выгрузка базы данных mydb в файл SQL-скрипта:
$pg_dump mydb > db.sql
Восстановление из ранее полученного скрипта в чистую базу newdb:
$psql -d newdb -f db.sql
Выгрузка базы данных в специальном формате:
$pg_dump -Fc mydb > db.dump
Выгрузка базы данных в формате каталога:
$pg_dump -Fd mydb -f dumpdir
Выгрузка базы данных в формате каталога в 5 параллельных потоков:
$pg_dump -Fd mydb -j 5 -f dumpdir
Восстановление из архива в чистую новую базу данных newdb:
$pg_restore -d newdb db.dump
Выгрузка отдельной таблицы mytab:
$pg_dump -t mytab mydb > db.sql
Выгрузка всех таблиц, имена которых начинаются с emp и которые принадлежат схеме detroit, кроме таблицы employee_log:
$pg_dump -t 'detroit.emp*' -T detroit.employee_log mydb > db.sql
Выгрузка всех схем, имена которых начинаются с east или west, заканчиваются на gsm и не содержат test:
$pg_dump -n 'east*gsm' -n 'west*gsm' -N '*test*' mydb > db.sql
То же самое, но с использованием регулярного выражения:
$pg_dump -n '(east|west)*gsm' -N '*test*' mydb > db.sql
Выгрузка всех объектов базы данных, кроме таблиц, имена которых начинаются с ts_:
$pg_dump -T 'ts_*' mydb > db.sql
Чтобы указать имя в верхнем или смешанном регистре в ключе -t и связанных с ним, это имя нужно заключить в кавычки; иначе оно будет приведено к нижнему регистру (см. Шаблоны поиска). Но кавычки являются спецсимволом для оболочки, поэтому и они, в свою очередь, должны заключаться в кавычки. Так, чтобы выгрузить одну таблицу с именем в смешанном регистре, нужно написать примерно следующее:
$pg_dump -t "\"MixedCaseName\"" mydb > mytab.sql
См. также
pg_dumpall, pg_restore, psqlpg_dump
pg_dump — extract a Postgres Pro database into a script file or other archive file
Synopsis
pg_dump [connection-option...] [option...] [dbname]
Description
pg_dump is a utility for backing up a Postgres Pro database. It makes consistent backups even if the database is being used concurrently. pg_dump does not block other users accessing the database (readers or writers).
pg_dump only dumps a single database. To backup global objects that are common to all databases in a cluster, such as roles and tablespaces, use pg_dumpall.
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. 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 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.
When used with one of the archive file formats and combined with pg_restore, pg_dump provides a flexible archival and transfer mechanism. pg_dump can be used to backup an entire database, then pg_restore can be used to examine the archive and/or select which parts of the database are to be restored. The most flexible output file formats are the “custom” format (-Fc) and the “directory” format (-Fd). They allow for selection and reordering of all archived items, support parallel restoration, and are compressed by default. The “directory” format is the only format that supports parallel dumps.
While running pg_dump, one should examine the output for any warnings (printed on standard error), especially in light of the limitations listed below.
Options
The following command-line options control the content and format of the output.
dbnameSpecifies the name of the database to be dumped. If this is not specified, the environment variable
PGDATABASEis used. If that is not set, the user name specified for the connection is used.-a--data-onlyDump only the data, not the schema (data definitions). Table data, large objects, and sequence values are dumped.
This option is similar to, but for historical reasons not identical to, specifying
--section=data.-b--blobsInclude large objects in the dump. This is the default behavior except when
--schema,--table, or--schema-onlyis specified. The-bswitch is therefore only useful to add large objects to dumps where a specific schema or table has been requested. Note that blobs are considered data and therefore will be included when --data-only is used, but not when --schema-only is.-B--no-blobsExclude large objects in the dump.
When both
-band-Bare given, the behavior is to output large objects, when data is being dumped, see the-bdocumentation.-c--cleanOutput commands to clean (drop) database objects prior to outputting the commands for creating them. (Unless
--if-existsis also specified, restore might generate some harmless error messages, if any objects were not present in the destination database.)This option is ignored when emitting an archive (non-text) output file. For the archive formats, you can specify the option when you call
pg_restore.-C--createBegin the output with a command to create the database itself and reconnect to the created database. (With a script of this form, it doesn't matter which database in the destination installation you connect to before running the script.) If
--cleanis also specified, the script drops and recreates the target database before reconnecting to it.This option is ignored when emitting an archive (non-text) output file. For the archive formats, you can specify the option when you call
pg_restore.-Eencoding--encoding=encodingCreate the dump in the specified character set encoding. By default, the dump is created in the database encoding. (Another way to get the same result is to set the
PGCLIENTENCODINGenvironment variable to the desired dump encoding.)-ffile--file=fileSend output to the specified file. This parameter can be omitted for file based output formats, in which case the standard output is used. It must be given for the directory output format however, where it specifies the target directory instead of a file. In this case the directory is created by
pg_dumpand must not exist before.-Fformat--format=formatSelects the format of the output.
formatcan be one of the following:pplainOutput a plain-text SQL script file (the default).
ccustomOutput a custom-format archive suitable for input into pg_restore. Together with the directory output format, this is the most flexible output format in that it allows manual selection and reordering of archived items during restore. This format is also compressed by default.
ddirectoryOutput a directory-format archive suitable for input into pg_restore. This will create a directory with one file for each table and blob being dumped, plus a so-called Table of Contents file describing the dumped objects in a machine-readable format that pg_restore can read. A directory format archive can be manipulated with standard Unix tools; for example, files in an uncompressed archive can be compressed with the gzip tool. This format is compressed by default and also supports parallel dumps.
ttarOutput a
tar-format archive suitable for input into pg_restore. The tar format is compatible with the directory format: extracting a tar-format archive produces a valid directory-format archive. However, the tar format does not support compression. Also, when using tar format the relative order of table data items cannot be changed during restore.
-jnjobs--jobs=njobsRun the dump in parallel by dumping
njobstables simultaneously. This option reduces the time of the dump but it also increases the load on the database server. You can only use this option with the directory output format because this is the only output format where multiple processes can write their data at the same time.pg_dump will open
njobs+ 1 connections to the database, so make sure your max_connections setting is high enough to accommodate all connections.Requesting exclusive locks on database objects while running a parallel dump could cause the dump to fail. The reason is that the pg_dump master process requests shared locks on the objects that the worker processes are going to dump later in order to make sure that nobody deletes them and makes them go away while the dump is running. If another client then requests an exclusive lock on a table, that lock will not be granted but will be queued waiting for the shared lock of the master process to be released. Consequently any other access to the table will not be granted either and will queue after the exclusive lock request. This includes the worker process trying to dump the table. Without any precautions this would be a classic deadlock situation. To detect this conflict, the pg_dump worker process requests another shared lock using the
NOWAIToption. If the worker process is not granted this shared lock, somebody else must have requested an exclusive lock in the meantime and there is no way to continue with the dump, so pg_dump has no choice but to abort the dump.For a consistent backup, the database server needs to support synchronized snapshots, a feature that was introduced in PostgreSQL 9.2 for primary servers and 10 for standbys. With this feature, database clients can ensure they see the same data set even though they use different connections.
pg_dump -juses multiple database connections; it connects to the database once with the master process and once again for each worker job. Without the synchronized snapshot feature, the different worker jobs wouldn't be guaranteed to see the same data in each connection, which could lead to an inconsistent backup.If you want to run a parallel dump of a pre-9.2 server, you need to make sure that the database content doesn't change from between the time the master connects to the database until the last worker job has connected to the database. The easiest way to do this is to halt any data modifying processes (DDL and DML) accessing the database before starting the backup. You also need to specify the
--no-synchronized-snapshotsparameter when runningpg_dump -jagainst a pre-9.2 PostgreSQL server.-nschema--schema=schemaDump only schemas matching
schema; this selects both the schema itself, and all its contained objects. When this option is not specified, all non-system schemas in the target database will be dumped. Multiple schemas can be selected by writing multiple-nswitches. Also, theschemaparameter is interpreted as a pattern according to the same rules used by psql's\dcommands (see Patterns), so multiple schemas can also be selected by writing wildcard characters in the pattern. When using wildcards, be careful to quote the pattern if needed to prevent the shell from expanding the wildcards; see Examples.Note
When
-nis specified, pg_dump makes no attempt to dump any other database objects that the selected schema(s) might depend upon. Therefore, there is no guarantee that the results of a specific-schema dump can be successfully restored by themselves into a clean database.Note
Non-schema objects such as blobs are not dumped when
-nis specified. You can add blobs back to the dump with the--blobsswitch.-Nschema--exclude-schema=schemaDo not dump any schemas matching the
schemapattern. The pattern is interpreted according to the same rules as for-n.-Ncan be given more than once to exclude schemas matching any of several patterns.When both
-nand-Nare given, the behavior is to dump just the schemas that match at least one-nswitch but no-Nswitches. If-Nappears without-n, then schemas matching-Nare excluded from what is otherwise a normal dump.-o--oidsDump object identifiers (OIDs) as part of the data for every table. Use this option if your application references the OID columns in some way (e.g., in a foreign key constraint). Otherwise, this option should not be used.
-O--no-ownerDo not output commands to set ownership of objects to match the original database. By default, pg_dump issues
ALTER OWNERorSET SESSION AUTHORIZATIONstatements to set ownership of created database objects. These statements will fail when the script is run unless it is started by a superuser (or the same user that owns all of the objects in the script). To make a script that can be restored by any user, but will give that user ownership of all the objects, specify-O.This option is ignored when emitting an archive (non-text) output file. For the archive formats, you can specify the option when you call
pg_restore.-R--no-reconnectThis option is obsolete but still accepted for backwards compatibility.
-s--schema-onlyDump only the object definitions (schema), not data.
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
--schemaoption, which uses the word “schema” in a different meaning.)To exclude table data for only a subset of tables in the database, see
--exclude-table-data.-Susername--superuser=usernameSpecify the superuser user name to use when disabling triggers. This is relevant only if
--disable-triggersis used. (Usually, it's better to leave this out, and instead start the resulting script as superuser.)-ttable--table=tableDump only tables with names matching
table. For this purpose, “table” includes views, materialized views, sequences, and foreign tables. Multiple tables can be selected by writing multiple-tswitches. Also, thetableparameter is interpreted as a pattern according to the same rules used by psql's\dcommands (see Patterns), so multiple tables can also be selected by writing wildcard characters in the pattern. When using wildcards, be careful to quote the pattern if needed to prevent the shell from expanding the wildcards; see Examples.The
-nand-Nswitches have no effect when-tis used, because tables selected by-twill be dumped regardless of those switches, and non-table objects will not be dumped.Note
When
-tis specified, pg_dump makes no attempt to dump any other database objects that the selected table(s) might depend upon. Therefore, there is no guarantee that the results of a specific-table dump can be successfully restored by themselves into a clean database.Note
The behavior of the
-tswitch is not entirely upward compatible with pre-8.2 PostgreSQL versions. Formerly, writing-t tabwould dump all tables namedtab, but now it just dumps whichever one is visible in your default search path. To get the old behavior you can write-t '*.tab'. Also, you must write something like-t sch.tabto select a table in a particular schema, rather than the old locution of-n sch -t tab.-Ttable--exclude-table=tableDo not dump any tables matching the
tablepattern. The pattern is interpreted according to the same rules as for-t.-Tcan be given more than once to exclude tables matching any of several patterns.When both
-tand-Tare given, the behavior is to dump just the tables that match at least one-tswitch but no-Tswitches. If-Tappears without-t, then tables matching-Tare excluded from what is otherwise a normal dump.-v--verboseSpecifies verbose mode. This will cause pg_dump to output detailed object comments and start/stop times to the dump file, and progress messages to standard error.
-V--versionPrint the pg_dump version and exit.
-x--no-privileges--no-aclPrevent dumping of access privileges (grant/revoke commands).
-Z0..9--compress=0..9Specify the compression level to use. Zero means no compression. For the custom and directory archive formats, this specifies compression of individual table-data segments, and the default is to compress at a moderate level. For plain text output, setting a nonzero compression level causes the entire output file to be compressed, as though it had been fed through gzip; but the default is not to compress. The tar archive format currently does not support compression at all.
--add-collproviderIf the provider for the default collation of the database to be dumped is implicit, explicitly specifies this provider in the dump. This option is recommended if you are using pg_dump and pg_restore to upgrade from previous versions of Postgres Pro or any version of PostgreSQL. It allows to preserve the original provider of the default collation if the
template0database in the new cluster uses different collation settings. Otherwise, check constraints that use the default collation may change and theCOPYcommand may end with a failure. For binary upgrades, this option is used automatically.--binary-upgradeThis option is for use by in-place upgrade utilities. Its use for other purposes is not recommended or supported. The behavior of the option may change in future releases without notice.
--column-inserts--attribute-insertsDump data as
INSERTcommands with explicit column names (INSERT INTO). This will make restoration very slow; it is mainly useful for making dumps that can be loaded into non-Postgres Pro databases. However, since this option generates a separate command for each row, an error in reloading a row causes only that row to be lost rather than the entire table contents.table(column, ...) VALUES ...--disable-dollar-quotingThis option disables the use of dollar quoting for function bodies, and forces them to be quoted using SQL standard string syntax.
--disable-triggersThis option is relevant only when creating a data-only dump. It instructs pg_dump to include commands to temporarily disable triggers on the target tables while the data is reloaded. Use this if you have referential integrity checks or other triggers on the tables that you do not want to invoke during data reload.
Presently, the commands emitted for
--disable-triggersmust be done as superuser. So, you should also specify a superuser name with-S, or preferably be careful to start the resulting script as a superuser.This option is ignored when emitting an archive (non-text) output file. For the archive formats, you can specify the option when you call
pg_restore.--enable-row-securityThis option is relevant only when dumping the contents of a table which has row security. By default, pg_dump will set row_security to off, to ensure that all data is dumped from the table. If the user does not have sufficient privileges to bypass row security, then an error is thrown. This parameter instructs pg_dump to set row_security to on instead, allowing the user to dump the parts of the contents of the table that they have access to.
Note that if you use this option currently, you probably also want the dump be in
INSERTformat, as theCOPY FROMduring restore does not support row security.--exclude-table-data=tableDo not dump data for any tables matching the
tablepattern. The pattern is interpreted according to the same rules as for-t.--exclude-table-datacan be given more than once to exclude tables matching any of several patterns. This option is useful when you need the definition of a particular table even though you do not need the data in it.To exclude data for all tables in the database, see
--schema-only.--if-existsUse conditional commands (i.e., add an
IF EXISTSclause) when cleaning database objects. This option is not valid unless--cleanis also specified.--insertsDump data as
INSERTcommands (rather thanCOPY). This will make restoration very slow; it is mainly useful for making dumps that can be loaded into non-Postgres Pro databases. However, since this option generates a separate command for each row, an error in reloading a row causes only that row to be lost rather than the entire table contents. Note that the restore might fail altogether if you have rearranged column order. The--column-insertsoption is safe against column order changes, though even slower.--lock-wait-timeout=timeoutDo not wait forever to acquire shared table locks at the beginning of the dump. Instead fail if unable to lock a table within the specified
timeout. The timeout may be specified in any of the formats accepted bySET statement_timeout. (Allowed formats vary depending on the server version you are dumping from, but an integer number of milliseconds is accepted by all versions.)--no-publicationsDo not dump publications.
--no-security-labelsDo not dump security labels.
--no-subscriptionsDo not dump subscriptions.
--no-syncBy default,
pg_dumpwill wait for all files to be written safely to disk. This option causespg_dumpto return without waiting, which is faster, but means that a subsequent operating system crash can leave the dump corrupt. Generally, this option is useful for testing but should not be used when dumping data from production installation.--no-synchronized-snapshotsThis option allows running
pg_dump -jagainst a pre-9.2 server, see the documentation of the-jparameter for more details.--no-tablespacesDo not output commands to select tablespaces. With this option, all objects will be created in whichever tablespace is the default during restore.
This option is ignored when emitting an archive (non-text) output file. For the archive formats, you can specify the option when you call
pg_restore.--no-unlogged-table-dataDo not dump the contents of unlogged tables. This option has no effect on whether or not the table definitions (schema) are dumped; it only suppresses dumping the table data. Data in unlogged tables is always excluded when dumping from a standby server.
--quote-all-identifiersForce quoting of all identifiers. This option is recommended when dumping a database from a server whose PostgreSQL major version is different from pg_dump's, or when the output is intended to be loaded into a server of a different major version. By default, pg_dump quotes only identifiers that are reserved words in its own major version. This sometimes results in compatibility issues when dealing with servers of other versions that may have slightly different sets of reserved words. Using
--quote-all-identifiersprevents such issues, at the price of a harder-to-read dump script.--section=sectionnameOnly dump the named section. The section name can be
pre-data,data, orpost-data. This option can be specified more than once to select multiple sections. The default is to dump all sections.The data section contains actual table data, large-object contents, and sequence values. Post-data items include definitions of indexes, triggers, rules, and constraints other than validated check constraints. Pre-data items include all other data definition items.
--serializable-deferrableUse a
serializabletransaction for the dump, to ensure that the snapshot used is consistent with later database states; but do this by waiting for a point in the transaction stream at which no anomalies can be present, so that there isn't a risk of the dump failing or causing other transactions to roll back with aserialization_failure. See Chapter 13 for more information about transaction isolation and concurrency control.This option is not beneficial for a dump which is intended only for disaster recovery. It could be useful for a dump used to load a copy of the database for reporting or other read-only load sharing while the original database continues to be updated. Without it the dump may reflect a state which is not consistent with any serial execution of the transactions eventually committed. For example, if batch processing techniques are used, a batch may show as closed in the dump without all of the items which are in the batch appearing.
This option will make no difference if there are no read-write transactions active when pg_dump is started. If read-write transactions are active, the start of the dump may be delayed for an indeterminate length of time. Once running, performance with or without the switch is the same.
--snapshot=snapshotnameUse the specified synchronized snapshot when making a dump of the database (see Table 9.82 for more details).
This option is useful when needing to synchronize the dump with a logical replication slot (see Chapter 46) or with a concurrent session.
In the case of a parallel dump, the snapshot name defined by this option is used rather than taking a new snapshot.
--strict-namesRequire that each schema (
-n/--schema) and table (-t/--table) qualifier match at least one schema/table in the database to be dumped. Note that if none of the schema/table qualifiers find matches, pg_dump will generate an error even without--strict-names.This option has no effect on
-N/--exclude-schema,-T/--exclude-table, or--exclude-table-data. An exclude pattern failing to match any objects is not considered an error.--use-set-session-authorizationOutput SQL-standard
SET SESSION AUTHORIZATIONcommands instead ofALTER OWNERcommands 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. Also, a dump usingSET SESSION AUTHORIZATIONwill certainly require superuser privileges to restore correctly, whereasALTER OWNERrequires lesser privileges.-?--helpShow help about pg_dump command line arguments, and exit.
The following command-line options control the database connection parameters.
-ddbname--dbname=dbnameSpecifies the name of the database to connect to. This is equivalent to specifying
dbnameas the first non-option argument on the command line. Thedbnamecan be a connection string. If so, connection string parameters will override any conflicting command line options.-hhost--host=hostSpecifies 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
PGHOSTenvironment variable, if set, else a Unix domain socket connection is attempted.-pport--port=portSpecifies the TCP port or local Unix domain socket file extension on which the server is listening for connections. Defaults to the
PGPORTenvironment variable, if set, or a compiled-in default.-Uusername--username=usernameUser name to connect as.
-w--no-passwordNever issue a password prompt. If the server requires password authentication and a password is not available by other means such as a
.pgpassfile, 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--passwordForce pg_dump to prompt for a password before connecting to a database.
This option is never essential, since pg_dump will automatically prompt for a password if the server demands password authentication. However, pg_dump will waste a connection attempt finding out that the server wants a password. In some cases it is worth typing
-Wto avoid the extra connection attempt.--role=rolenameSpecifies a role name to be used to create the dump. This option causes pg_dump to issue a
SET ROLErolenamecommand after connecting to the database. It is useful when the authenticated user (specified by-U) lacks privileges needed by pg_dump, 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 dumps to be made without violating the policy.
Environment
PGDATABASEPGHOSTPGOPTIONSPGPORTPGUSERDefault connection parameters.
This utility, like most other Postgres Pro utilities, also uses the environment variables supported by libpq (see Section 31.14).
Diagnostics
pg_dump internally executes SELECT statements. If you have problems running pg_dump, make sure you are able to select information from the database using, for example, psql. Also, any default connection settings and environment variables used by the libpq front-end library will apply.
The database activity of pg_dump is normally collected by the statistics collector. If this is undesirable, you can set parameter track_counts to false via PGOPTIONS or the ALTER USER command.
Notes
If your database cluster has any local additions to the template1 database, be careful to restore the output of pg_dump into a truly empty database; otherwise you are likely to get errors due to duplicate definitions of the added objects. To make an empty database without any local additions, copy from template0 not template1, for example:
CREATE DATABASE foo WITH TEMPLATE template0;
When a data-only dump is chosen and the option --disable-triggers is used, pg_dump emits commands to disable triggers on user tables before inserting the data, and then commands to re-enable them after the data has been inserted. If the restore is stopped in the middle, the system catalogs might be left in the wrong state.
The dump file produced by pg_dump does not contain the statistics used by the optimizer to make query planning decisions. Therefore, it is wise to run ANALYZE after restoring from a dump file to ensure optimal performance; see Section 23.1.3 and Section 23.1.6 for more information. The dump file also does not contain any ALTER DATABASE ... SET commands; these settings are dumped by pg_dumpall, along with database users and other installation-wide settings.
Because pg_dump is used to transfer data to newer versions of Postgres Pro, the output of pg_dump can be expected to load into Postgres Pro server versions newer than pg_dump's version. pg_dump can also dump from Postgres Pro servers older than its own version. (Currently, servers back to version 8.0 are supported.) However, pg_dump cannot dump from Postgres Pro servers newer than its own major version; it will refuse to even try, rather than risk making an invalid dump. Also, it is not guaranteed that pg_dump's output can be loaded into a server of an older major version — not even if the dump was taken from a server of that version. Loading a dump file into an older server may require manual editing of the dump file to remove syntax not understood by the older server. Use of the --quote-all-identifiers option is recommended in cross-version cases, as it can prevent problems arising from varying reserved-word lists in different PostgreSQL versions.
When dumping logical replication subscriptions, pg_dump will generate CREATE SUBSCRIPTION commands that use the connect = false option, so that restoring the subscription does not make remote connections for creating a replication slot or for initial table copy. That way, the dump can be restored without requiring network access to the remote servers. It is then up to the user to reactivate the subscriptions in a suitable way. If the involved hosts have changed, the connection information might have to be changed. It might also be appropriate to truncate the target tables before initiating a new full table copy.
Examples
To dump a database called mydb into a SQL-script file:
$pg_dump mydb > db.sql
To reload such a script into a (freshly created) database named newdb:
$psql -d newdb -f db.sql
To dump a database into a custom-format archive file:
$pg_dump -Fc mydb > db.dump
To dump a database into a directory-format archive:
$pg_dump -Fd mydb -f dumpdir
To dump a database into a directory-format archive in parallel with 5 worker jobs:
$pg_dump -Fd mydb -j 5 -f dumpdir
To reload an archive file into a (freshly created) database named newdb:
$pg_restore -d newdb db.dump
To dump a single table named mytab:
$pg_dump -t mytab mydb > db.sql
To dump all tables whose names start with emp in the detroit schema, except for the table named employee_log:
$pg_dump -t 'detroit.emp*' -T detroit.employee_log mydb > db.sql
To dump all schemas whose names start with east or west and end in gsm, excluding any schemas whose names contain the word test:
$pg_dump -n 'east*gsm' -n 'west*gsm' -N '*test*' mydb > db.sql
The same, using regular expression notation to consolidate the switches:
$pg_dump -n '(east|west)*gsm' -N '*test*' mydb > db.sql
To dump all database objects except for tables whose names begin with ts_:
$pg_dump -T 'ts_*' mydb > db.sql
To specify an upper-case or mixed-case name in -t and related switches, you need to double-quote the name; else it will be folded to lower case (see Patterns). But double quotes are special to the shell, so in turn they must be quoted. Thus, to dump a single table with a mixed-case name, you need something like
$pg_dump -t "\"MixedCaseName\"" mydb > mytab.sql