2 $PostgreSQL: pgsql/doc/src/sgml/backup.sgml,v 2.65 2005/04/19 01:39:50 momjian Exp $
5 <title>Backup and Restore</title>
7 <indexterm zone="backup"><primary>backup</></>
10 As with everything that contains valuable data, <productname>PostgreSQL</>
11 databases should be backed up regularly. While the procedure is
12 essentially simple, it is important to have a basic understanding of
13 the underlying techniques and assumptions.
17 There are three fundamentally different approaches to backing up
18 <productname>PostgreSQL</> data:
20 <listitem><para><acronym>SQL</> dump</para></listitem>
21 <listitem><para>File system level backup</para></listitem>
22 <listitem><para>On-line backup</para></listitem>
24 Each has its own strengths and weaknesses.
27 <sect1 id="backup-dump">
28 <title><acronym>SQL</> Dump</title>
31 The idea behind the SQL-dump method is to generate a text file with SQL
32 commands that, when fed back to the server, will recreate the
33 database in the same state as it was at the time of the dump.
34 <productname>PostgreSQL</> provides the utility program
35 <xref linkend="app-pgdump"> for this purpose. The basic usage of this
38 pg_dump <replaceable class="parameter">dbname</replaceable> > <replaceable class="parameter">outfile</replaceable>
40 As you see, <application>pg_dump</> writes its results to the
41 standard output. We will see below how this can be useful.
45 <application>pg_dump</> is a regular <productname>PostgreSQL</>
46 client application (albeit a particularly clever one). This means
47 that you can do this backup procedure from any remote host that has
48 access to the database. But remember that <application>pg_dump</>
49 does not operate with special permissions. In particular, it must
50 have read access to all tables that you want to back up, so in
51 practice you almost always have to run it as a database superuser.
55 To specify which database server <application>pg_dump</> should
56 contact, use the command line options <option>-h
57 <replaceable>host</></> and <option>-p <replaceable>port</></>. The
58 default host is the local host or whatever your
59 <envar>PGHOST</envar> environment variable specifies. Similarly,
60 the default port is indicated by the <envar>PGPORT</envar>
61 environment variable or, failing that, by the compiled-in default.
62 (Conveniently, the server will normally have the same compiled-in
67 As any other <productname>PostgreSQL</> client application,
68 <application>pg_dump</> will by default connect with the database
69 user name that is equal to the current operating system user name. To override
70 this, either specify the <option>-U</option> option or set the
71 environment variable <envar>PGUSER</envar>. Remember that
72 <application>pg_dump</> connections are subject to the normal
73 client authentication mechanisms (which are described in <xref
74 linkend="client-authentication">).
78 Dumps created by <application>pg_dump</> are internally consistent,
79 that is, updates to the database while <application>pg_dump</> is
80 running will not be in the dump. <application>pg_dump</> does not
81 block other operations on the database while it is working.
82 (Exceptions are those operations that need to operate with an
83 exclusive lock, such as <command>VACUUM FULL</command>.)
88 When your database schema relies on OIDs (for instance as foreign
89 keys) you must instruct <application>pg_dump</> to dump the OIDs
90 as well. To do this, use the <option>-o</option> command line
91 option. <quote>Large objects</> are not dumped by default,
92 either. See <xref linkend="app-pgdump">'s reference page if you
97 <sect2 id="backup-dump-restore">
98 <title>Restoring the dump</title>
101 The text files created by <application>pg_dump</> are intended to
102 be read in by the <application>psql</application> program. The
103 general command form to restore a dump is
105 psql <replaceable class="parameter">dbname</replaceable> < <replaceable class="parameter">infile</replaceable>
107 where <replaceable class="parameter">infile</replaceable> is what
108 you used as <replaceable class="parameter">outfile</replaceable>
109 for the <application>pg_dump</> command. The database <replaceable
110 class="parameter">dbname</replaceable> will not be created by this
111 command, you must create it yourself from <literal>template0</> before executing
112 <application>psql</> (e.g., with <literal>createdb -T template0
113 <replaceable class="parameter">dbname</></literal>).
114 <application>psql</> supports options similar to <application>pg_dump</>
115 for controlling the database server location and the user name. See
116 <xref linkend="app-psql">'s reference page for more information.
120 Not only must the target database already exist before starting to
121 run the restore, but so must all the users who own objects in the
122 dumped database or were granted permissions on the objects. If they
123 do not, then the restore will fail to recreate the objects with the
124 original ownership and/or permissions. (Sometimes this is what you want,
125 but usually it is not.)
129 Once restored, it is wise to run <xref linkend="sql-analyze"
130 endterm="sql-analyze-title"> on each database so the optimizer has
131 useful statistics. An easy way to do this is to run
132 <command>vacuumdb -a -z</> to
133 <command>VACUUM ANALYZE</> all databases; this is equivalent to
134 running <command>VACUUM ANALYZE</command> manually.
138 The ability of <application>pg_dump</> and <application>psql</> to
139 write to or read from pipes makes it possible to dump a database
140 directly from one server to another; for example:
142 pg_dump -h <replaceable>host1</> <replaceable>dbname</> | psql -h <replaceable>host2</> <replaceable>dbname</>
148 The dumps produced by <application>pg_dump</> are relative to
149 <literal>template0</>. This means that any languages, procedures,
150 etc. added to <literal>template1</> will also be dumped by
151 <application>pg_dump</>. As a result, when restoring, if you are
152 using a customized <literal>template1</>, you must create the
153 empty database from <literal>template0</>, as in the example
159 For advice on how to load large amounts of data into
160 <productname>PostgreSQL</productname> efficiently, refer to <xref
165 <sect2 id="backup-dump-all">
166 <title>Using <application>pg_dumpall</></title>
169 The above mechanism is cumbersome and inappropriate when backing
170 up an entire database cluster. For this reason the <xref
171 linkend="app-pg-dumpall"> program is provided.
172 <application>pg_dumpall</> backs up each database in a given
173 cluster, and also preserves cluster-wide data such as users and
174 groups. The basic usage of this command is:
176 pg_dumpall > <replaceable>outfile</>
178 The resulting dump can be restored with <application>psql</>:
180 psql -f <replaceable class="parameter">infile</replaceable> template1
182 (Actually, you can specify any existing database name to start from,
183 but if you are reloading in an empty cluster then <literal>template1</>
184 is the only available choice.) It is always necessary to have
185 database superuser access when restoring a <application>pg_dumpall</>
186 dump, as that is required to restore the user and group information.
190 <sect2 id="backup-dump-large">
191 <title>Handling large databases</title>
194 Since <productname>PostgreSQL</productname> allows tables larger
195 than the maximum file size on your system, it can be problematic
196 to dump such a table to a file, since the resulting file will likely
197 be larger than the maximum size allowed by your system. Since
198 <application>pg_dump</> can write to the standard output, you can
199 just use standard Unix tools to work around this possible problem.
203 <title>Use compressed dumps.</title>
205 You can use your favorite compression program, for example
206 <application>gzip</application>.
209 pg_dump <replaceable class="parameter">dbname</replaceable> | gzip > <replaceable class="parameter">filename</replaceable>.gz
215 createdb <replaceable class="parameter">dbname</replaceable>
216 gunzip -c <replaceable class="parameter">filename</replaceable>.gz | psql <replaceable class="parameter">dbname</replaceable>
222 cat <replaceable class="parameter">filename</replaceable>.gz | gunzip | psql <replaceable class="parameter">dbname</replaceable>
228 <title>Use <command>split</>.</title>
230 The <command>split</command> command
231 allows you to split the output into pieces that are
232 acceptable in size to the underlying file system. For example, to
233 make chunks of 1 megabyte:
236 pg_dump <replaceable class="parameter">dbname</replaceable> | split -b 1m - <replaceable class="parameter">filename</replaceable>
242 createdb <replaceable class="parameter">dbname</replaceable>
243 cat <replaceable class="parameter">filename</replaceable>* | psql <replaceable class="parameter">dbname</replaceable>
249 <title>Use the custom dump format.</title>
251 If <productname>PostgreSQL</productname> was built on a system with the
252 <application>zlib</> compression library installed, the custom dump
253 format will compress data as it writes it to the output file. This will
254 produce dump file sizes similar to using <command>gzip</command>, but it
255 has the added advantage that tables can be restored selectively. The
256 following command dumps a database using the custom dump format:
259 pg_dump -Fc <replaceable class="parameter">dbname</replaceable> > <replaceable class="parameter">filename</replaceable>
262 A custom-format dump is not a script for <application>psql</>, but
263 instead must be restored with <application>pg_restore</>.
264 See the <xref linkend="app-pgdump"> and <xref
265 linkend="app-pgrestore"> reference pages for details.
271 <sect2 id="backup-dump-caveats">
272 <title>Caveats</title>
275 For reasons of backward compatibility, <application>pg_dump</>
276 does not dump large objects by default.<indexterm><primary>large
277 object</primary><secondary>backup</secondary></indexterm> To dump
278 large objects you must use either the custom or the tar output
279 format, and use the <option>-b</> option in
280 <application>pg_dump</>. See the <xref linkend="app-pgdump"> reference
281 page for details. The
282 directory <filename>contrib/pg_dumplo</> of the
283 <productname>PostgreSQL</> source tree also contains a program
284 that can dump large objects.
288 Please familiarize yourself with the <xref linkend="app-pgdump">
294 <sect1 id="backup-file">
295 <title>File system level backup</title>
298 An alternative backup strategy is to directly copy the files that
299 <productname>PostgreSQL</> uses to store the data in the database. In
300 <xref linkend="creating-cluster"> it is explained where these files
301 are located, but you have probably found them already if you are
302 interested in this method. You can use whatever method you prefer
303 for doing usual file system backups, for example
306 tar -cf backup.tar /usr/local/pgsql/data
311 There are two restrictions, however, which make this method
312 impractical, or at least inferior to the <application>pg_dump</>
318 The database server <emphasis>must</> be shut down in order to
319 get a usable backup. Half-way measures such as disallowing all
320 connections will <emphasis>not</emphasis> work
321 (mainly because <command>tar</command> and similar tools do not take an
322 atomic snapshot of the state of the file system at a point in
323 time). Information about stopping the server can be found in
324 <xref linkend="postmaster-shutdown">. Needless to say that you
325 also need to shut down the server before restoring the data.
331 If you have dug into the details of the file system layout of the
332 database, you may be tempted to try to back up or restore only certain
333 individual tables or databases from their respective files or
334 directories. This will <emphasis>not</> work because the
335 information contained in these files contains only half the
336 truth. The other half is in the commit log files
337 <filename>pg_clog/*</filename>, which contain the commit status of
338 all transactions. A table file is only usable with this
339 information. Of course it is also impossible to restore only a
340 table and the associated <filename>pg_clog</filename> data
341 because that would render all other tables in the database
342 cluster useless. So file system backups only work for complete
343 restoration of an entire database cluster.
350 An alternative file-system backup approach is to make a
351 <quote>consistent snapshot</quote> of the data directory, if the
352 file system supports that functionality (and you are willing to
353 trust that it is implemented correctly). The typical procedure is
354 to make a <quote>frozen snapshot</> of the volume containing the
355 database, then copy the whole data directory (not just parts, see
356 above) from the snapshot to a backup device, then release the frozen
357 snapshot. This will work even while the database server is running.
358 However, a backup created in this way saves
359 the database files in a state where the database server was not
360 properly shut down; therefore, when you start the database server
361 on the backed-up data, it will think the server had crashed
362 and replay the WAL log. This is not a problem, just be aware of
363 it (and be sure to include the WAL files in your backup).
367 If your database is spread across multiple file systems, there may not
368 be any way to obtain exactly-simultaneous frozen snapshots of all
369 the volumes. For example, if your data files and WAL log are on different
370 disks, or if tablespaces are on different file systems, it might
371 not be possible to use snapshot backup because the snapshots must be
373 Read your file system documentation very carefully before trusting
374 to the consistent-snapshot technique in such situations. The safest
375 approach is to shut down the database server for long enough to
376 establish all the frozen snapshots.
380 Another option is to use <application>rsync</> to perform a file
381 system backup. This is done by first running <application>rsync</>
382 while the database server is running, then shutting down the database
383 server just long enough to do a second <application>rsync</>. The
384 second <application>rsync</> will be much quicker than the first,
385 because it has relatively little data to transfer, and the end result
386 will be consistent because the server was down. This method
387 allows a file system backup to be performed with minimal downtime.
391 Note that a file system backup will not necessarily be
392 smaller than an SQL dump. On the contrary, it will most likely be
393 larger. (<application>pg_dump</application> does not need to dump
394 the contents of indexes for example, just the commands to recreate
399 <sect1 id="backup-online">
400 <title>On-line backup and point-in-time recovery (PITR)</title>
402 <indexterm zone="backup">
403 <primary>on-line backup</primary>
406 <indexterm zone="backup">
407 <primary>point-in-time recovery</primary>
410 <indexterm zone="backup">
411 <primary>PITR</primary>
415 At all times, <productname>PostgreSQL</> maintains a
416 <firstterm>write ahead log</> (WAL) in the <filename>pg_xlog/</>
417 subdirectory of the cluster's data directory. The log describes
418 every change made to the database's data files. This log exists
419 primarily for crash-safety purposes: if the system crashes, the
420 database can be restored to consistency by <quote>replaying</> the
421 log entries made since the last checkpoint. However, the existence
422 of the log makes it possible to use a third strategy for backing up
423 databases: we can combine a file-system-level backup with backup of
424 the WAL files. If recovery is needed, we restore the backup and
425 then replay from the backed-up WAL files to bring the backup up to
426 current time. This approach is more complex to administer than
427 either of the previous approaches, but it has some significant
432 We do not need a perfectly consistent backup as the starting point.
433 Any internal inconsistency in the backup will be corrected by log
434 replay (this is not significantly different from what happens during
435 crash recovery). So we don't need file system snapshot capability,
436 just <application>tar</> or a similar archiving tool.
441 Since we can string together an indefinitely long sequence of WAL files
442 for replay, continuous backup can be achieved simply by continuing to archive
443 the WAL files. This is particularly valuable for large databases, where
444 it may not be convenient to take a full backup frequently.
449 There is nothing that says we have to replay the WAL entries all the
450 way to the end. We could stop the replay at any point and have a
451 consistent snapshot of the database as it was at that time. Thus,
452 this technique supports <firstterm>point-in-time recovery</>: it is
453 possible to restore the database to its state at any time since your base
459 If we continuously feed the series of WAL files to another
460 machine that has been loaded with the same base backup file, we
461 have a <quote>hot standby</> system: at any point we can bring up
462 the second machine and it will have a nearly-current copy of the
470 As with the plain file-system-backup technique, this method can only
471 support restoration of an entire database cluster, not a subset.
472 Also, it requires a lot of archival storage: the base backup may be bulky,
473 and a busy system will generate many megabytes of WAL traffic that
474 have to be archived. Still, it is the preferred backup technique in
475 many situations where high reliability is needed.
479 To recover successfully using an on-line backup, you need a continuous
480 sequence of archived WAL files that extends back at least as far as the
481 start time of your backup. So to get started, you should set up and test
482 your procedure for archiving WAL files <emphasis>before</> you take your
483 first base backup. Accordingly, we first discuss the mechanics of
487 <sect2 id="backup-archiving-wal">
488 <title>Setting up WAL archiving</title>
491 In an abstract sense, a running <productname>PostgreSQL</> system
492 produces an indefinitely long sequence of WAL records. The system
493 physically divides this sequence into WAL <firstterm>segment
494 files</>, which are normally 16MB apiece (although the size can be
495 altered when building <productname>PostgreSQL</>). The segment
496 files are given numeric names that reflect their position in the
497 abstract WAL sequence. When not using WAL archiving, the system
498 normally creates just a few segment files and then
499 <quote>recycles</> them by renaming no-longer-needed segment files
500 to higher segment numbers. It's assumed that a segment file whose
501 contents precede the checkpoint-before-last is no longer of
502 interest and can be recycled.
506 When archiving WAL data, we want to capture the contents of each segment
507 file once it is filled, and save that data somewhere before the segment
508 file is recycled for reuse. Depending on the application and the
509 available hardware, there could be many different ways of <quote>saving
510 the data somewhere</>: we could copy the segment files to an NFS-mounted
511 directory on another machine, write them onto a tape drive (ensuring that
512 you have a way of restoring the file with its original file name), or batch
513 them together and burn them onto CDs, or something else entirely. To
514 provide the database administrator with as much flexibility as possible,
515 <productname>PostgreSQL</> tries not to make any assumptions about how
516 the archiving will be done. Instead, <productname>PostgreSQL</> lets
517 the administrator specify a shell command to be executed to copy a
518 completed segment file to wherever it needs to go. The command could be
519 as simple as a <application>cp</>, or it could invoke a complex shell
520 script — it's all up to you.
524 The shell command to use is specified by the <xref
525 linkend="guc-archive-command"> configuration parameter, which in practice
526 will always be placed in the <filename>postgresql.conf</filename> file.
528 any <literal>%p</> is replaced by the absolute path of the file to
529 archive, while any <literal>%f</> is replaced by the file name only.
530 Write <literal>%%</> if you need to embed an actual <literal>%</>
531 character in the command. The simplest useful command is something
534 archive_command = 'cp -i %p /mnt/server/archivedir/%f </dev/null'
536 which will copy archivable WAL segments to the directory
537 <filename>/mnt/server/archivedir</>. (This is an example, not a
538 recommendation, and may not work on all platforms.)
542 The archive command will be executed under the ownership of the same
543 user that the <productname>PostgreSQL</> server is running as. Since
544 the series of WAL files being archived contains effectively everything
545 in your database, you will want to be sure that the archived data is
546 protected from prying eyes; for example, archive into a directory that
547 does not have group or world read access.
551 It is important that the archive command return zero exit status if and
552 only if it succeeded. Upon getting a zero result,
553 <productname>PostgreSQL</> will assume that the WAL segment file has been
554 successfully archived, and will remove or recycle it.
555 However, a nonzero status tells
556 <productname>PostgreSQL</> that the file was not archived; it will try
557 again periodically until it succeeds.
561 The archive command should generally be designed to refuse to overwrite
562 any pre-existing archive file. This is an important safety feature to
563 preserve the integrity of your archive in case of administrator error
564 (such as sending the output of two different servers to the same archive
566 It is advisable to test your proposed archive command to ensure that it
567 indeed does not overwrite an existing file, <emphasis>and that it returns
568 nonzero status in this case</>. We have found that <literal>cp -i</> does
569 this correctly on some platforms but not others. If the chosen command
570 does not itself handle this case correctly, you should add a command
571 to test for pre-existence of the archive file. For example, something
574 archive_command = 'test ! -f .../%f && cp %p .../%f'
576 works correctly on most Unix variants.
580 While designing your archiving setup, consider what will happen if
581 the archive command fails repeatedly because some aspect requires
582 operator intervention or the archive runs out of space. For example, this
583 could occur if you write to tape without an autochanger; when the tape
584 fills, nothing further can be archived until the tape is swapped.
585 You should ensure that any error condition or request to a human operator
586 is reported appropriately so that the situation can be
587 resolved relatively quickly. The <filename>pg_xlog/</> directory will
588 continue to fill with WAL segment files until the situation is resolved.
592 The speed of the archiving command is not important, so long as it can keep up
593 with the average rate at which your server generates WAL data. Normal
594 operation continues even if the archiving process falls a little behind.
595 If archiving falls significantly behind, this will increase the amount of
596 data that would be lost in the event of a disaster. It will also mean that
597 the <filename>pg_xlog/</> directory will contain large numbers of
598 not-yet-archived segment files, which could eventually exceed available
599 disk space. You are advised to monitor the archiving process to ensure that
600 it is working as you intend.
604 If you are concerned about being able to recover right up to the
605 current instant, you may want to take additional steps to ensure that
606 the current, partially-filled WAL segment is also copied someplace.
607 This is particularly important if your server generates only little WAL
608 traffic (or has slack periods where it does so), since it could take a
609 long time before a WAL segment file is completely filled and ready to
610 archive. One possible way to handle this is to set up a
611 <application>cron</> job that periodically (once a minute, perhaps)
612 identifies the current WAL segment file and saves it someplace safe.
613 Then the combination of the archived WAL segments and the saved current
614 segment will be enough to ensure you can always restore to within a
615 minute of current time. This behavior is not presently built into
616 <productname>PostgreSQL</> because we did not want to complicate the
617 definition of the <xref linkend="guc-archive-command"> by requiring it
618 to keep track of successively archived, but different, copies of the
619 same WAL file. The <xref linkend="guc-archive-command"> is only
620 invoked on completed WAL segments. Except in the case of retrying a
621 failure, it will be called only once for any given file name.
625 In writing your archive command, you should assume that the filenames to
626 be archived may be up to 64 characters long and may contain any
627 combination of ASCII letters, digits, and dots. It is not necessary to
628 remember the original full path (<literal>%p</>) but it is necessary to
629 remember the file name (<literal>%f</>).
633 Note that although WAL archiving will allow you to restore any
634 modifications made to the data in your <productname>PostgreSQL</> database
635 it will not restore changes made to configuration files (that is,
636 <filename>postgresql.conf</>, <filename>pg_hba.conf</> and
637 <filename>pg_ident.conf</>), since those are edited manually rather
638 than through SQL operations.
639 You may wish to keep the configuration files in a location that will
640 be backed up by your regular file system backup procedures. See
641 <xref linkend="runtime-config-file-locations"> for how to relocate the
646 <sect2 id="backup-base-backup">
647 <title>Making a Base Backup</title>
650 The procedure for making a base backup is relatively simple:
654 Ensure that WAL archiving is enabled and working.
659 Connect to the database as a superuser, and issue the command
661 SELECT pg_start_backup('label');
663 where <literal>label</> is any string you want to use to uniquely
664 identify this backup operation. (One good practice is to use the
665 full path where you intend to put the backup dump file.)
666 <function>pg_start_backup</> creates a <firstterm>backup label</> file,
667 called <filename>backup_label</>, in the cluster directory with
668 information about your backup.
672 It does not matter which database within the cluster you connect to to
673 issue this command. You can ignore the result returned by the function;
674 but if it reports an error, deal with that before proceeding.
679 Perform the backup, using any convenient file-system-backup tool
680 such as <application>tar</> or <application>cpio</>. It is neither
681 necessary nor desirable to stop normal operation of the database
687 Again connect to the database as a superuser, and issue the command
689 SELECT pg_stop_backup();
691 This should return successfully.
696 Once the WAL segment files used during the backup are archived as part
697 of normal database activity, you are done.
704 It is not necessary to be very concerned about the amount of time elapsed
705 between <function>pg_start_backup</> and the start of the actual backup,
706 nor between the end of the backup and <function>pg_stop_backup</>; a
707 few minutes' delay won't hurt anything. You
708 must however be quite sure that these operations are carried out in
709 sequence and do not overlap.
713 Be certain that your backup dump includes all of the files underneath
714 the database cluster directory (e.g., <filename>/usr/local/pgsql/data</>).
715 If you are using tablespaces that do not reside underneath this directory,
716 be careful to include them as well (and be sure that your backup dump
717 archives symbolic links as links, otherwise the restore will mess up
722 You may, however, omit from the backup dump the files within the
723 <filename>pg_xlog/</> subdirectory of the cluster directory. This
724 slight complication is worthwhile because it reduces the risk
725 of mistakes when restoring. This is easy to arrange if
726 <filename>pg_xlog/</> is a symbolic link pointing to someplace outside
727 the cluster directory, which is a common setup anyway for performance
732 To make use of this backup, you will need to keep around all the WAL
733 segment files generated during and after the file system backup.
734 To aid you in doing this, the <function>pg_stop_backup</> function
735 creates a <firstterm>backup history file</> that is immediately
736 stored into the WAL archive area. This file is named after the first
737 WAL segment file that you need to have to make use of the backup.
738 For example, if the starting WAL file is
739 <literal>0000000100001234000055CD</> the backup history file will be
741 <literal>0000000100001234000055CD.007C9330.backup</>. (The second
742 number in the file name stands for an exact position within the WAL
743 file, and can ordinarily be ignored.) Once you have safely archived
744 the file system backup and the WAL segment files used during the
745 backup (as specified in the backup history file), all archived WAL
746 segments with names numerically less are no longer needed to recover
747 the file system backup and may be deleted. However, you should
748 consider keeping several backup sets to be absolutely certain that
749 you are can recover your data. Keep in mind that only completed WAL
750 segment files are archived, so there will be delay between running
751 <function>pg_stop_backup</> and the archiving of all WAL segment
752 files needed to make the file system backup consistent.
755 The backup history file is just a small text file. It contains the
756 label string you gave to <function>pg_start_backup</>, as well as
757 the starting and ending times of the backup. If you used the label
758 to identify where the associated dump file is kept, then the
759 archived history file is enough to tell you which dump file to
760 restore, should you need to do so.
764 Since you have to keep around all the archived WAL files back to your
765 last base backup, the interval between base backups should usually be
766 chosen based on how much storage you want to expend on archived WAL
767 files. You should also consider how long you are prepared to spend
768 recovering, if recovery should be necessary — the system will have to
769 replay all those WAL segments, and that could take awhile if it has
770 been a long time since the last base backup.
774 It's also worth noting that the <function>pg_start_backup</> function
775 makes a file named <filename>backup_label</> in the database cluster
776 directory, which is then removed again by <function>pg_stop_backup</>.
777 This file will of course be archived as a part of your backup dump file.
778 The backup label file includes the label string you gave to
779 <function>pg_start_backup</>, as well as the time at which
780 <function>pg_start_backup</> was run, and the name of the starting WAL
781 file. In case of confusion it will
782 therefore be possible to look inside a backup dump file and determine
783 exactly which backup session the dump file came from.
787 It is also possible to make a backup dump while the postmaster is
788 stopped. In this case, you obviously cannot use
789 <function>pg_start_backup</> or <function>pg_stop_backup</>, and
790 you will therefore be left to your own devices to keep track of which
791 backup dump is which and how far back the associated WAL files go.
792 It is generally better to follow the on-line backup procedure above.
796 <sect2 id="backup-pitr-recovery">
797 <title>Recovering with an On-line Backup</title>
800 Okay, the worst has happened and you need to recover from your backup.
801 Here is the procedure:
805 Stop the postmaster, if it's running.
810 If you have the space to do so,
811 copy the whole cluster data directory and any tablespaces to a temporary
812 location in case you need them later. Note that this precaution will
813 require that you have enough free space on your system to hold two
814 copies of your existing database. If you do not have enough space,
815 you need at the least to copy the contents of the <filename>pg_xlog</>
816 subdirectory of the cluster data directory, as it may contain logs which
817 were not archived before the system went down.
822 Clean out all existing files and subdirectories under the cluster data
823 directory and under the root directories of any tablespaces you are using.
828 Restore the database files from your backup dump. Be careful that they
829 are restored with the right ownership (the database system user, not
830 root!) and with the right permissions. If you are using tablespaces,
831 you may want to verify that the symbolic links in <filename>pg_tblspc/</>
832 were correctly restored.
837 Remove any files present in <filename>pg_xlog/</>; these came from the
838 backup dump and are therefore probably obsolete rather than current.
839 If you didn't archive <filename>pg_xlog/</> at all, then re-create it,
840 and be sure to re-create the subdirectory
841 <filename>pg_xlog/archive_status/</> as well.
846 If you had unarchived WAL segment files that you saved in step 2,
847 copy them into <filename>pg_xlog/</>. (It is best to copy them,
848 not move them, so that you still have the unmodified files if a
849 problem occurs and you have to start over.)
854 Create a recovery command file <filename>recovery.conf</> in the cluster
855 data directory (see <xref linkend="recovery-config-settings">). You may
856 also want to temporarily modify <filename>pg_hba.conf</> to prevent
857 ordinary users from connecting until you are sure the recovery has worked.
862 Start the postmaster. The postmaster will go into recovery mode and
863 proceed to read through the archived WAL files it needs. Upon completion
864 of the recovery process, the postmaster will rename
865 <filename>recovery.conf</> to <filename>recovery.done</> (to prevent
866 accidentally re-entering recovery mode in case of a crash later) and then
867 commence normal database operations.
872 Inspect the contents of the database to ensure you have recovered to
873 where you want to be. If not, return to step 1. If all is well,
874 let in your users by restoring <filename>pg_hba.conf</> to normal.
881 The key part of all this is to set up a recovery command file that
882 describes how you want to recover and how far the recovery should
883 run. You can use <filename>recovery.conf.sample</> (normally
884 installed in the installation <filename>share/</> directory) as a
885 prototype. The one thing that you absolutely must specify in
886 <filename>recovery.conf</> is the <varname>restore_command</>,
887 which tells <productname>PostgreSQL</> how to get back archived
888 WAL file segments. Like the <varname>archive_command</>, this is
889 a shell command string. It may contain <literal>%f</>, which is
890 replaced by the name of the desired log file, and <literal>%p</>,
891 which is replaced by the absolute path to copy the log file to.
892 Write <literal>%%</> if you need to embed an actual <literal>%</>
893 character in the command. The simplest useful command is
896 restore_command = 'cp /mnt/server/archivedir/%f %p'
898 which will copy previously archived WAL segments from the directory
899 <filename>/mnt/server/archivedir</>. You could of course use something
900 much more complicated, perhaps even a shell script that requests the
901 operator to mount an appropriate tape.
905 It is important that the command return nonzero exit status on failure.
906 The command <emphasis>will</> be asked for log files that are not present
907 in the archive; it must return nonzero when so asked. This is not an
908 error condition. Be aware also that the base name of the <literal>%p</>
909 path will be different from <literal>%f</>; do not expect them to be
914 WAL segments that cannot be found in the archive will be sought in
915 <filename>pg_xlog/</>; this allows use of recent un-archived segments.
916 However segments that are available from the archive will be used in
917 preference to files in <filename>pg_xlog/</>. The system will not
918 overwrite the existing contents of <filename>pg_xlog/</> when retrieving
923 Normally, recovery will proceed through all available WAL segments,
924 thereby restoring the database to the current point in time (or as
925 close as we can get given the available WAL segments). But if you want
926 to recover to some previous point in time (say, right before the junior
927 DBA dropped your main transaction table), just specify the required
928 stopping point in <filename>recovery.conf</>. You can specify the stop
929 point, known as the <quote>recovery target</>, either by date/time or
930 by completion of a specific transaction ID. As of this writing only
931 the date/time option is very usable, since there are no tools to help
932 you identify with any accuracy which transaction ID to use.
937 The stop point must be after the ending time of the base backup (the
938 time of <function>pg_stop_backup</>). You cannot use a base backup
939 to recover to a time when that backup was still going on. (To
940 recover to such a time, you must go back to your previous base backup
941 and roll forward from there.)
945 <sect3 id="recovery-config-settings" xreflabel="Recovery Settings">
946 <title>Recovery Settings</title>
949 These settings can only be made in the <filename>recovery.conf</>
950 file, and apply only for the duration of the recovery. They must be
951 reset for any subsequent recovery you wish to perform. They cannot be
952 changed once recovery has begun.
957 <varlistentry id="restore-command" xreflabel="restore_command">
958 <term><varname>restore_command</varname> (<type>string</type>)</term>
961 The shell command to execute to retrieve an archived segment of
962 the WAL file series. This parameter is required.
963 Any <literal>%f</> in the string is
964 replaced by the name of the file to retrieve from the archive,
965 and any <literal>%p</> is replaced by the absolute path to copy
967 Write <literal>%%</> to embed an actual <literal>%</> character
971 It is important for the command to return a zero exit status if and
972 only if it succeeds. The command <emphasis>will</> be asked for file
973 names that are not present in the archive; it must return nonzero
974 when so asked. Examples:
976 restore_command = 'cp /mnt/server/archivedir/%f "%p"'
977 restore_command = 'copy /mnt/server/archivedir/%f "%p"' # Windows
983 <varlistentry id="recovery-target-time" xreflabel="recovery_target_time">
984 <term><varname>recovery_target_time</varname>
985 (<type>timestamp</type>)
989 This parameter specifies the time stamp up to which recovery
991 At most one of <varname>recovery_target_time</> and
992 <xref linkend="recovery-target-xid"> can be specified.
993 The default is to recover to the end of the WAL log.
994 The precise stopping point is also influenced by
995 <xref linkend="recovery-target-inclusive">.
1000 <varlistentry id="recovery-target-xid" xreflabel="recovery_target_xid">
1001 <term><varname>recovery_target_xid</varname> (<type>string</type>)</term>
1004 This parameter specifies the transaction ID up to which recovery
1005 will proceed. Keep in mind
1006 that while transaction IDs are assigned sequentially at transaction
1007 start, transactions can complete in a different numeric order.
1008 The transactions that will be recovered are those that committed
1009 before (and optionally including) the specified one.
1010 At most one of <varname>recovery_target_xid</> and
1011 <xref linkend="recovery-target-time"> can be specified.
1012 The default is to recover to the end of the WAL log.
1013 The precise stopping point is also influenced by
1014 <xref linkend="recovery-target-inclusive">.
1019 <varlistentry id="recovery-target-inclusive"
1020 xreflabel="recovery_target_inclusive">
1021 <term><varname>recovery_target_inclusive</varname>
1022 (<type>boolean</type>)
1026 Specifies whether we stop just after the specified recovery target
1027 (<literal>true</literal>), or just before the recovery target
1028 (<literal>false</literal>).
1029 Applies to both <xref linkend="recovery-target-time">
1030 and <xref linkend="recovery-target-xid">, whichever one is
1031 specified for this recovery. This indicates whether transactions
1032 having exactly the target commit time or ID, respectively, will
1033 be included in the recovery. Default is <literal>true</>.
1038 <varlistentry id="recovery-target-timeline"
1039 xreflabel="recovery_target_timeline">
1040 <term><varname>recovery_target_timeline</varname>
1041 (<type>string</type>)
1045 Specifies recovering into a particular timeline. The default is
1046 to recover along the same timeline that was current when the
1047 base backup was taken. You would only need to set this parameter
1048 in complex re-recovery situations, where you need to return to
1049 a state that itself was reached after a point-in-time recovery.
1050 See <xref linkend="backup-timelines"> for discussion.
1061 <sect2 id="backup-timelines">
1062 <title>Timelines</title>
1064 <indexterm zone="backup">
1065 <primary>timelines</primary>
1069 The ability to restore the database to a previous point in time creates
1070 some complexities that are akin to science-fiction stories about time
1071 travel and parallel universes. In the original history of the database,
1072 perhaps you dropped a critical table at 5:15PM on Tuesday evening.
1073 Unfazed, you get out your backup, restore to the point-in-time 5:14PM
1074 Tuesday evening, and are up and running. In <emphasis>this</> history of
1075 the database universe, you never dropped the table at all. But suppose
1076 you later realize this wasn't such a great idea after all, and would like
1077 to return to some later point in the original history. You won't be able
1078 to if, while your database was up-and-running, it overwrote some of the
1079 sequence of WAL segment files that led up to the time you now wish you
1080 could get back to. So you really want to distinguish the series of
1081 WAL records generated after you've done a point-in-time recovery from
1082 those that were generated in the original database history.
1086 To deal with these problems, <productname>PostgreSQL</> has a notion
1087 of <firstterm>timelines</>. Each time you recover to a point-in-time
1088 earlier than the end of the WAL sequence, a new timeline is created
1089 to identify the series of WAL records generated after that recovery.
1090 (If recovery proceeds all the way to the end of WAL, however, we do not
1091 start a new timeline: we just extend the existing one.) The timeline
1092 ID number is part of WAL segment file names, and so a new timeline does
1093 not overwrite the WAL data generated by previous timelines. It is
1094 in fact possible to archive many different timelines. While that might
1095 seem like a useless feature, it's often a lifesaver. Consider the
1096 situation where you aren't quite sure what point-in-time to recover to,
1097 and so have to do several point-in-time recoveries by trial and error
1098 until you find the best place to branch off from the old history. Without
1099 timelines this process would soon generate an unmanageable mess. With
1100 timelines, you can recover to <emphasis>any</> prior state, including
1101 states in timeline branches that you later abandoned.
1105 Each time a new timeline is created, <productname>PostgreSQL</> creates
1106 a <quote>timeline history</> file that shows which timeline it branched
1107 off from and when. These history files are necessary to allow the system
1108 to pick the right WAL segment files when recovering from an archive that
1109 contains multiple timelines. Therefore, they are archived into the WAL
1110 archive area just like WAL segment files. The history files are just
1111 small text files, so it's cheap and appropriate to keep them around
1112 indefinitely (unlike the segment files which are large). You can, if
1113 you like, add comments to a history file to make your own notes about
1114 how and why this particular timeline came to be. Such comments will be
1115 especially valuable when you have a thicket of different timelines as
1116 a result of experimentation.
1120 The default behavior of recovery is to recover along the same timeline
1121 that was current when the base backup was taken. If you want to recover
1122 into some child timeline (that is, you want to return to some state that
1123 was itself generated after a recovery attempt), you need to specify the
1124 target timeline ID in <filename>recovery.conf</>. You cannot recover into
1125 timelines that branched off earlier than the base backup.
1129 <sect2 id="backup-online-caveats">
1130 <title>Caveats</title>
1133 At this writing, there are several limitations of the on-line backup
1134 technique. These will probably be fixed in future releases:
1139 Operations on non-B-tree indexes (hash, R-tree, and GiST indexes) are
1140 not presently WAL-logged, so replay will not update these index types.
1141 The recommended workaround is to manually <command>REINDEX</> each
1142 such index after completing a recovery operation.
1148 <command>CREATE TABLESPACE</> commands are WAL-logged with the literal
1149 absolute path, and will therefore be replayed as tablespace creations
1150 with the same absolute path. This might be undesirable if the log is
1151 being replayed on a different machine. It can be dangerous even if
1152 the log is being replayed on the same machine, but into a new data
1153 directory: the replay will still overwrite the contents of the original
1154 tablespace. To avoid potential gotchas of this sort, the best practice
1155 is to take a new base backup after creating or dropping tablespaces.
1162 It should also be noted that the present <acronym>WAL</acronym>
1163 format is extremely bulky since it includes many disk page
1164 snapshots. This is appropriate for crash recovery purposes,
1165 since we may need to fix partially-written disk pages. It is not
1166 necessary to store so many page copies for PITR operations, however.
1167 An area for future development is to compress archived WAL data by
1168 removing unnecessary page copies. In the meantime, administrators
1169 may wish to reduce the number of page snapshots included in WAL by
1170 increasing the checkpoint interval parameters as much as feasible.
1175 <sect1 id="migration">
1176 <title>Migration Between Releases</title>
1178 <indexterm zone="migration">
1179 <primary>upgrading</primary>
1182 <indexterm zone="migration">
1183 <primary>version</primary>
1184 <secondary>compatibility</secondary>
1188 This section discusses how to migrate your database data from one
1189 <productname>PostgreSQL</> release to a newer one.
1190 The software installation procedure <foreignphrase>per se</> is not the
1191 subject of this section; those details are in <xref linkend="installation">.
1195 As a general rule, the internal data storage format is subject to
1196 change between major releases of <productname>PostgreSQL</> (where
1197 the number after the first dot changes). This does not apply to
1198 different minor releases under the same major release (where the
1199 number after the second dot changes); these always have compatible
1200 storage formats. For example, releases 7.0.1, 7.1.2, and 7.2 are
1201 not compatible, whereas 7.1.1 and 7.1.2 are. When you update
1202 between compatible versions, you can simply replace the executables
1203 and reuse the data directory on disk. Otherwise you need to back
1204 up your data and restore it on the new server. This has to be done
1205 using <application>pg_dump</>; file system level backup methods
1206 obviously won't work. There are checks in place that prevent you
1207 from using a data directory with an incompatible version of
1208 <productname>PostgreSQL</productname>, so no great harm can be done by
1209 trying to start the wrong server version on a data directory.
1213 It is recommended that you use the <application>pg_dump</> and
1214 <application>pg_dumpall</> programs from the newer version of
1215 <productname>PostgreSQL</>, to take advantage of any enhancements
1216 that may have been made in these programs. Current releases of the
1217 dump programs can read data from any server version back to 7.0.
1221 The least downtime can be achieved by installing the new server in
1222 a different directory and running both the old and the new servers
1223 in parallel, on different ports. Then you can use something like
1226 pg_dumpall -p 5432 | psql -d template1 -p 6543
1229 to transfer your data. Or use an intermediate file if you want.
1230 Then you can shut down the old server and start the new server at
1231 the port the old one was running at. You should make sure that the
1232 old database is not updated after you run <application>pg_dumpall</>,
1233 otherwise you will obviously lose that data. See <xref
1234 linkend="client-authentication"> for information on how to prohibit
1239 In practice you probably want to test your client
1240 applications on the new setup before switching over completely.
1241 This is another reason for setting up concurrent installations
1242 of old and new versions.
1246 If you cannot or do not want to run two servers in parallel you can
1247 do the backup step before installing the new version, bring down
1248 the server, move the old version out of the way, install the new
1249 version, start the new server, restore the data. For example:
1252 pg_dumpall > backup
1254 mv /usr/local/pgsql /usr/local/pgsql.old
1255 cd ~/postgresql-&version;
1257 initdb -D /usr/local/pgsql/data
1258 postmaster -D /usr/local/pgsql/data
1259 psql -f backup template1
1262 See <xref linkend="runtime"> about ways to start and stop the
1263 server and other details. The installation instructions will advise
1264 you of strategic places to perform these steps.
1269 When you <quote>move the old installation out of the way</quote>
1270 it may no longer be perfectly usable. Some of the executable programs
1271 contain absolute paths to various installed programs and data files.
1272 This is usually not a big problem but if you plan on using two
1273 installations in parallel for a while you should assign them
1274 different installation directories at build time. (This problem
1275 is rectified in <productname>PostgreSQL</> 8.0 and later, but you
1276 need to be wary of moving older installations.)
1282 <!-- Keep this comment at the end of the file
1287 sgml-minimize-attributes:nil
1288 sgml-always-quote-attributes:t
1290 sgml-indent-tabs-mode:nil
1292 sgml-parent-document:nil
1293 sgml-default-dtd-file:"./reference.ced"
1294 sgml-exposed-tags:nil
1295 sgml-local-catalogs:("/usr/share/sgml/catalog")
1296 sgml-local-ecat-files:nil