pg_dump
pg_dump — выгрузить базу данных PostgreSQL в виде скрипта или в архивном формате
Синтаксис
pg_dump [параметр-подключения...] [параметр...] [имя_бд]
Описание
pg_dump — это программа для создания резервных копий базы данных PostgreSQL. Она создаёт целостные копии, даже если база параллельно используется. Программа 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 следует обращать внимание на предупреждения, которые печатаются в стандартный поток ошибок, особенно ввиду рассмотренных далее ограничений.
Предупреждение
При восстановлении выгрузки в целевой точке выполняется произвольный код по выбору суперпользователей исходной точки. Для частичных выгрузок и частичных восстановлений такого ограничения нет. Если суперпользователи исходной точки не являются доверенными, выгружаемые команды SQL нужно проверять перед восстановлением. Выгрузки в нетекстовом формате можно проверить через параметр --file pg_restore. Обратите внимание, что клиенту, выполняющему выгрузку и восстановление, не нужно доверять суперпользователям исходной или целевой точки.
Параметры
Параметры командной строки для управления содержимым и форматом вывода.
имя_бдУказывает имя базы данных, из которой будут выгружаться данные. Если имя не задано, то используется значение переменной окружения
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всех выгружаемых объектов базы данных перед командами создания этих объектов. Этот параметр полезен, если при восстановлении необходимо перезаписать существующую базу данных. Если дополнительно не указать флаг--if-exists, то при восстановлении в базу данных, где некоторые объекты отсутствуют, попытка удаления несуществующего объекта будет приводить к ошибке, которую можно игнорировать.Этот параметр игнорируется, когда данные выгружаются в архивных форматах (не в текстовом). Для таких форматов данный параметр можно указать при вызове
pg_restore.-C--createСформировать в начале вывода команду для создания базы данных и затем подключения к ней. В этом случае не важно, какая база указана в параметрах подключения перед выполнением скрипта. Также, если указан ключ
--clean, то скрипт сначала удалит, а затем пересоздаст базу данных перед подключением к ней.С ключом
--createв выходной файл также включается комментарий к базе данных (если он задан) и все назначения переменных конфигурации, связанные с базой данных, то есть все командыALTER DATABASE ... SET ...иALTER ROLE ... IN DATABASE ... SET ..., ссылающиеся на эту базу данных. Также выгружаются права доступа к самой базе данных, если не добавлен ключ--no-acl.Этот параметр игнорируется, когда данные выгружаются в архивных форматах (не в текстовом). Для таких форматов данный параметр можно указать при вызове
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--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(см. Шаблоны поиска), так что несколько таблиц можно выбрать и шаблоном со знаками подстановки. Используя знаки подстановки, при необходимости заключайте шаблон в кавычки, чтобы эти знаки не разворачивала оболочка системы; см. Примеры.Помимо обычных таблиц, с этим указанием можно выгрузить определения соответствующих шаблону последовательностей, представлений, материализованных представлений и сторонних таблиц. При этом содержимое представлений и матпредставлений выгружаться не будет, а содержимое сторонних таблиц будет выгружено, только если в аргументе
--include-foreign-dataуказан соответствующий сторонний сервер.Параметры
-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в настоящий момент не поддерживает сжатие.--binary-upgradeЭтот параметр предназначен для утилит обновления сервера. Использование для иных целей не рекомендуется и не поддерживается. Поведение параметра может быть изменено в последующих версиях без предварительного уведомления.
--column-inserts--attribute-insertsВыгружать данные таблиц в виде команд
INSERTс явным указанием столбцов (INSERT INTO). Скорость восстановления при этом значительно снизится, но данный вариант оправдан, когда загружать данные нужно не в PostgreSQL. При этом в случае каких-либо ошибок при загрузке данных будут потеряны только строкитаблица(столбец, ...) VALUES ...INSERT, где возникли ошибки, но не всё содержимое таблицы.--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.--extra-float-digits=число_цифрВыводить числа с плавающей точкой не с максимальной точностью, а с заданным значением
extra_float_digits. При выгрузке данных в целях резервного копирования данный параметр использовать не следует.--if-existsИспользовать команды
DROP ... IF EXISTSдля удаления объектов в режиме--clean. При этом возможные ошибки «does not exist» (не существует) не выводятся. Этот параметр недействителен без указания--clean.--include-foreign-data=сторонний_серверВыгрузить данные всех сторонних таблиц со стороннего сервера, имя которого соответствует шаблону
сторонний_сервер. Для выгрузки данных с нескольких сторонних серверов параметр--include-foreign-dataможно использовать несколько раз. К тому же, значениесторонний_серверинтерпретируется как шаблон, согласно правилам, используемым командами\dутилиты psql (см. Шаблоны поиска ниже). Поэтому несколько сторонних серверов можно также выбрать, используя в шаблоне символы подстановки. Когда используются символы подстановки, шаблон лучше экранировать кавычками, чтобы командная оболочка ОС не интерпретировала их по-своему (см. Примеры ниже). Единственное отличие от вышеупомянутых правил — шаблон не может быть пустым.Примечание
Использование знаков подстановки в
--include-foreign-dataможет привести к доступу к неподходящим сторонним серверам. Кроме того, для безопасного использования этого параметра необходимо убедиться, что у указанного сервера есть доверенный владелец.Примечание
Когда используется параметр
--include-foreign-data, pg_dump не проверяет возможность записи в стороннюю таблицу. Таким образом, не гарантируется, что выгруженная сторонняя таблица может быть успешно восстановлена.--insertsВыгружать данные таблиц в виде команд
INSERTвместоCOPY. Скорость восстановления при этом значительно снизится, но данный вариант оправдан, когда загружать данные нужно не в PostgreSQL. При этом в случае каких-либо ошибок при загрузке данных будут потеряны только строкиINSERT, где возникли ошибки, но не всё содержимое таблицы. Заметьте, что восстановление может провалиться полностью, если у таблицы изменён порядок столбцов. В такой ситуации можно использовать параметр--column-inserts, для которого порядок столбцов не важен, но он работает ещё медленнее.--load-via-partition-rootПри выгрузке данных для секции таблицы выводить команды
COPYилиINSERT, ссылающиеся на корневую таблицу в иерархии секционирования, а не на эту секцию. В результате при загрузке данных подходящая секция будет выбираться заново для каждой строки. Это может быть полезно при восстановлении данных, когда на целевом сервере строки не всегда попадают в те же секции, в которых они находились на исходном. Это возможно, например, когда столбец секционирования имеет текстовый тип и в двух системах по-разному определено правило сортировки, по которому упорядочивается этот столбец.--lock-wait-timeout=время_ожиданияНе ждать бесконечно получения разделяемых блокировок таблиц в начале процедуры выгрузки. Вместо этого выдать ошибку, если не удастся заблокировать таблицы за указанное
время_ожидания. Это время можно задать в любом из форматов, принимаемых командойSET statement_timeout. (Допустимые форматы зависят от версии сервера, выгружающего данные, но количество миллисекунд в виде целого числа принимают все версии.)--no-commentsНе выгружать комментарии.
--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Не выгружать данные нежурналируемых таблиц. Параметр не влияет на выгрузку определений таблиц, он только подавляет вывод содержимого таблиц. С резервного сервера содержимое нежурналируемых таблиц не выгружается никогда.
--on-conflict-do-nothingДобавить предложения
ON CONFLICT DO NOTHINGв командыINSERT. Это указание допускается только при выборе режима--inserts,--column-insertsили--rows-per-insert.--quote-all-identifiersПринудительно экранировать все идентификаторы. Этот параметр рекомендуется при выгрузке базы, когда основная версия сервера PostgreSQL, с которого выгружается база, отличается от версии pg_dump, или когда выгруженная копия предназначена для загрузки на сервере с другой основной версией. По умолчанию pg_dump экранирует только те идентификаторы, которые являются зарезервированными словами в собственной основной версии. Иногда это приводит к проблемам совместимости с серверами других версий, в которых множество зарезервированных слов может быть несколько другим. Применение параметра
--quote-all-identifiersпредотвращает подобные проблемы, ценой ухудшения читаемости скрипта с выгруженными данными.--restrict-key=restrict_keyИспользовать предоставленную строку в качестве ключа
\restrictpsql в выводе выгрузки. Задать это можно только для выгрузок в нетекстовом формате, например, если для параметра--formatзадано значениеplainили параметра нет вовсе. Если ключ ограничения не указан, pg_dumpall сгенерирует случайный ключ. Ключи могут содержать только буквенные и цифровые символы.Этот параметр в основном предназначен для целей тестирования и других сценариев, требующих повторяющегося создания вывода (например, для сравнения файлов выгрузки). Параметр не рекомендуется использовать в повседневной работе, поскольку, зная принципы функционирования ключа, злоумышленник может внедрить произвольный код, который будет выполнен на машине при помощи psql и вывода выгрузки.
--rows-per-insert=число_строкВыгружать данные таблиц в виде команд
INSERTвместоCOPY. В данном параметре задаётся максимальное число строк для одной командыINSERT. Указанное в нём значение должно быть больше 0. При этом в случае каких-либо ошибок при загрузке данных будут потеряны только строкиINSERT, где возникли ошибки, но не всё содержимое таблицы.--section=имя_секцииВыгружать лишь указанную секцию. Имя секции может принимать значения
pre-data,dataилиpost-data. Для выгрузки нескольких секций, параметр можно использовать несколько раз в одной команде. По умолчанию резервируются все секции.Секция
dataсодержит непосредственно данные таблиц, больших объектов и значения последовательностей. Секцияpost-dataсодержит определения индексов, триггеров, правил и ограничений (кроме ограничений проверки, созданных безNOT VALID). Секцияpre-dataвключает определения остальных элементов.--serializable-deferrableИспользовать при выгрузке транзакцию с уровнем изоляции
serializableдля получения снимка, согласованного с последующими состояниями базы. Правда для этого нужно выждать момент, когда в потоке транзакций нет аномалий, и поэтому нет риска, что выгрузка завершится неудачно, и риска отката других транзакций с ошибкойserialization_failure. Более подробно изоляция транзакций и управление одновременным доступом описывается в Главе 13.Параметр не особо полезен в случаях, когда требуется восстановление после сбоя. Он полезен для создания копии базы данных, в которой формируются отчёты и выполняются другие операции чтения, в то время как в основной базе продолжается обычная работа. Без этого параметра выгрузка может содержать не целостное состояние базы данных. Например, если используется пакетная обработка, статус пакета может отражаться как завершённый, в то время как в выгрузке будут не все элементы пакета.
Параметр не будет влиять на результат, если во время запуска pg_dump нет активных транзакций на чтение-запись. Если же активные транзакции чтения-записи есть, то начало выгрузки может быть отложено на неопределённый период времени. После того как выгрузка началась, производительность с этим ключом или без него будет одинаковой.
--snapshot=имя_снимкаИспользовать заданный синхронный снимок при выгрузке данных из базы (за подробностями обратитесь к Таблице 9.88).
Этот параметр полезен, когда требуется синхронизировать выгружаемые данные со слотом логической репликации (см. Главу 48) или с другим одновременным сеансом.
В случае с параллельной выгрузкой будет использоваться имя снимка, определённое этим параметром; новый снимок не будет сделан.
--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Параметры подключения по умолчанию.
PG_COLORВыбирает вариант использования цвета в диагностических сообщениях. Возможные значения:
always(всегда),auto(автоматически) иnever(никогда).
Эта утилита, как и большинство других утилит PostgreSQL, также использует переменные среды, поддерживаемые libpq (см. Раздел 33.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 для достижения оптимальной производительности; за дополнительными сведениями обратитесь к Подразделу 24.1.3 и Подразделу 24.1.6.
Так как pg_dump применяется для переноса данных в новые версии PostgreSQL, предполагается, что вывод pg_dump можно загрузить на сервер PostgreSQL более новой версии, чем версия pg_dump. pg_dump может также выгружать данные серверов PostgreSQL более старых версий, чем его собственная. (В настоящее время поддерживаются версии, начиная с 8.0.) Однако утилита pg_dump не может выгружать данные с серверов PostgreSQL более новых основных версий; она не будет даже пытаться делать это, во избежание некорректной выгрузки. Также не гарантируется, что вывод pg_dump может быть загружен на сервере более старой основной версии — даже если данные были выгружены с сервера той же версии. Для загрузки такого файла на старом сервере может потребоваться вручную исправить в нём синтаксис, не воспринимаемый старой версией. Имея дело с разными версиями, рекомендуется применять параметр --quote-all-identifiers, так как он может предотвратить проблемы, возникающие при изменении множества зарезервированных слов в разных версиях PostgreSQL.
Выгружая подписки на логическую репликацию, pg_dump будет выдавать команды CREATE SUBSCRIPTION с указанием connect = false, так что при восстановлении подписки не будут устанавливаться удалённые подключения для создания слота репликации или для начального копирования таблиц. Таким образом, выгруженные данные могут быть восстановлены без сетевого доступа к удалённым серверам. Вновь активировать подписки должным образом — задача пользователя. Если задействованные серверы поменялись, возможно, придётся скорректировать строки подключения. Также может быть уместно опустошить целевые таблицы перед началом полного копирования таблиц.
Обычно рекомендуется использовать параметр -X (--no-psqlrc) при восстановлении базы данных из текстового скрипта pg_dump, чтобы обеспечить чистый процесс восстановления и избежать потенциальных конфликтов с нестандартными конфигурациями psql.
Примеры
Выгрузка базы данных mydb в файл SQL-скрипта:
$pg_dump mydb > db.sql
Восстановление из ранее полученного скрипта в чистую базу newdb:
$psql -X -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
Восстановление архива в ту же базу данных, из которой он был выгружен, с предварительным удалением текущего содержимого этой базы данных:
$pg_restore -d postgres --clean --create 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 PostgreSQL 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 PostgreSQL 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 back up an entire cluster, or to back up 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.
Warning
Restoring a dump causes the destination to execute arbitrary code of the source superusers' choice. Partial dumps and partial restores do not limit that. If the source superusers are not trusted, the dumped SQL statements must be inspected before restoring. Non-plain-text dumps can be inspected by using pg_restore's --file option. Note that the client running the dump and restore need not trust the source or destination superusers.
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-onlyis used, but not when--schema-onlyis.-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
DROPall the dumped database objects prior to outputting the commands for creating them. This option is useful when the restore is to overwrite an existing database. If any of the objects do not exist in the destination database, ignorable error messages will be reported during restore, unless--if-existsis also specified.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.With
--create, the output also includes the database's comment if any, and any configuration variable settings that are specific to this database, that is, anyALTER DATABASE ... SET ...andALTER ROLE ... IN DATABASE ... SET ...commands that mention this database. Access privileges for the database itself are also dumped, unless--no-aclis specified.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 may reduce the time needed to perform 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.-npattern--schema=patternDump only schemas matching
pattern; 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. Thepatternparameter is interpreted as a pattern according to the same rules used by psql's\dcommands (see Patterns below), 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 below.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.-Npattern--exclude-schema=patternDo not dump any schemas matching
pattern. 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--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.)-tpattern--table=patternDump only tables with names matching
pattern. Multiple tables can be selected by writing multiple-tswitches. Thepatternparameter is interpreted as a pattern according to the same rules used by psql's\dcommands (see Patterns below), 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 below.As well as tables, this option can be used to dump the definition of matching views, materialized views, foreign tables, and sequences. It will not dump the contents of views or materialized views, and the contents of foreign tables will only be dumped if the corresponding foreign server is specified with
--include-foreign-data.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.-Tpattern--exclude-table=patternDo not dump any tables matching
pattern. 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.
--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-PostgreSQL databases. Any error during restoring will cause only rows that are part of the problematictable(column, ...) VALUES ...INSERTto be lost, rather than the entire table contents.--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 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-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=patternDo not dump data for any tables matching
pattern. 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.--extra-float-digits=ndigitsUse the specified value of
extra_float_digitswhen dumping floating-point data, instead of the maximum available precision. Routine dumps made for backup purposes should not use this option.--if-existsUse
DROP ... IF EXISTScommands to drop objects in--cleanmode. This suppresses “does not exist” errors that might otherwise be reported. This option is not valid unless--cleanis also specified.--include-foreign-data=foreignserverDump the data for any foreign table with a foreign server matching
foreignserverpattern. Multiple foreign servers can be selected by writing multiple--include-foreign-dataswitches. Also, theforeignserverparameter is interpreted as a pattern according to the same rules used by psql's\dcommands (see Patterns below), so multiple foreign servers 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 below. The only exception is that an empty pattern is disallowed.Note
Using wildcards in
--include-foreign-datamay result in access to unexpected foreign servers. Also, to use this option securely, make sure that the named server must have a trusted owner.Note
When
--include-foreign-datais specified, pg_dump does not check that the foreign table is writable. Therefore, there is no guarantee that the results of a foreign table dump can be successfully restored.--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-PostgreSQL databases. Any error during restoring will cause only rows that are part of the problematicINSERTto 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.--load-via-partition-rootWhen dumping data for a table partition, make the
COPYorINSERTstatements target the root of the partitioning hierarchy that contains it, rather than the partition itself. This causes the appropriate partition to be re-determined for each row when the data is loaded. This may be useful when restoring data on a server where rows do not always fall into the same partitions as they did on the original server. That could happen, for example, if the partitioning column is of type text and the two systems have different definitions of the collation used to sort the partitioning column.--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-commentsDo not dump comments.
--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.
--on-conflict-do-nothingAdd
ON CONFLICT DO NOTHINGtoINSERTcommands. This option is not valid unless--inserts,--column-insertsor--rows-per-insertis also specified.--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.--restrict-key=restrict_keyUse the provided string as the psql
\restrictkey in the dump output. This can only be specified for plain-text dumps, i.e., when--formatis set toplainor the--formatoption is omitted. If no restrict key is specified, pg_dump will generate a random one as needed. Keys may contain only alphanumeric characters.This option is primarily intended for testing purposes and other scenarios that require repeatable output (e.g., comparing dump files). It is not recommended for general use, as a malicious server with advance knowledge of the key may be able to inject arbitrary code that will be executed on the machine that runs psql with the dump output.
--rows-per-insert=nrowsDump data as
INSERTcommands (rather thanCOPY). Controls the maximum number of rows perINSERTcommand. The value specified must be a number greater than zero. Any error during restoring will cause only rows that are part of the problematicINSERTto be lost, rather than the entire table contents.--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.88 for more details).
This option is useful when needing to synchronize the dump with a logical replication slot (see Chapter 48) 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.
PG_COLORSpecifies whether to use color in diagnostic messages. Possible values are
always,autoandnever.
This utility, like most other PostgreSQL utilities, also uses the environment variables supported by libpq (see Section 33.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 24.1.3 and Section 24.1.6 for more information.
Because pg_dump is used to transfer data to newer versions of PostgreSQL, the output of pg_dump can be expected to load into PostgreSQL server versions newer than pg_dump's version. pg_dump can also dump from PostgreSQL servers older than its own version. (Currently, servers back to version 8.0 are supported.) However, pg_dump cannot dump from PostgreSQL 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.
It is generally recommended to use the -X (--no-psqlrc) option when restoring a database from a plain-text pg_dump script to ensure a clean restore process and prevent potential conflicts with non-default psql configurations.
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 -X -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 reload an archive file into the same database it was dumped from, discarding the current contents of that database:
$pg_restore -d postgres --clean --create 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 below). 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