PostgreSQL Source Code  git master
pg_restore.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * pg_restore.c
4  * pg_restore is an utility extracting postgres database definitions
5  * from a backup archive created by pg_dump using the archiver
6  * interface.
7  *
8  * pg_restore will read the backup archive and
9  * dump out a script that reproduces
10  * the schema of the database in terms of
11  * user-defined types
12  * user-defined functions
13  * tables
14  * indexes
15  * aggregates
16  * operators
17  * ACL - grant/revoke
18  *
19  * the output script is SQL that is understood by PostgreSQL
20  *
21  * Basic process in a restore operation is:
22  *
23  * Open the Archive and read the TOC.
24  * Set flags in TOC entries, and *maybe* reorder them.
25  * Generate script to stdout
26  * Exit
27  *
28  * Copyright (c) 2000, Philip Warner
29  * Rights are granted to use this software in any way so long
30  * as this notice is not removed.
31  *
32  * The author is not responsible for loss or damages that may
33  * result from its use.
34  *
35  *
36  * IDENTIFICATION
37  * src/bin/pg_dump/pg_restore.c
38  *
39  *-------------------------------------------------------------------------
40  */
41 #include "postgres_fe.h"
42 
43 #include <ctype.h>
44 #ifdef HAVE_TERMIOS_H
45 #include <termios.h>
46 #endif
47 
48 #include "dumputils.h"
49 #include "fe_utils/option_utils.h"
50 #include "getopt_long.h"
51 #include "parallel.h"
52 #include "pg_backup_utils.h"
53 
54 static void usage(const char *progname);
55 
56 int
57 main(int argc, char **argv)
58 {
60  int c;
61  int exit_code;
62  int numWorkers = 1;
63  Archive *AH;
64  char *inputFileSpec;
65  static int disable_triggers = 0;
66  static int enable_row_security = 0;
67  static int if_exists = 0;
68  static int no_data_for_failed_tables = 0;
69  static int outputNoTableAm = 0;
70  static int outputNoTablespaces = 0;
71  static int use_setsessauth = 0;
72  static int no_comments = 0;
73  static int no_publications = 0;
74  static int no_security_labels = 0;
75  static int no_subscriptions = 0;
76  static int strict_names = 0;
77 
78  struct option cmdopts[] = {
79  {"clean", 0, NULL, 'c'},
80  {"create", 0, NULL, 'C'},
81  {"data-only", 0, NULL, 'a'},
82  {"dbname", 1, NULL, 'd'},
83  {"exit-on-error", 0, NULL, 'e'},
84  {"exclude-schema", 1, NULL, 'N'},
85  {"file", 1, NULL, 'f'},
86  {"format", 1, NULL, 'F'},
87  {"function", 1, NULL, 'P'},
88  {"host", 1, NULL, 'h'},
89  {"index", 1, NULL, 'I'},
90  {"jobs", 1, NULL, 'j'},
91  {"list", 0, NULL, 'l'},
92  {"no-privileges", 0, NULL, 'x'},
93  {"no-acl", 0, NULL, 'x'},
94  {"no-owner", 0, NULL, 'O'},
95  {"no-reconnect", 0, NULL, 'R'},
96  {"port", 1, NULL, 'p'},
97  {"no-password", 0, NULL, 'w'},
98  {"password", 0, NULL, 'W'},
99  {"schema", 1, NULL, 'n'},
100  {"schema-only", 0, NULL, 's'},
101  {"superuser", 1, NULL, 'S'},
102  {"table", 1, NULL, 't'},
103  {"trigger", 1, NULL, 'T'},
104  {"use-list", 1, NULL, 'L'},
105  {"username", 1, NULL, 'U'},
106  {"verbose", 0, NULL, 'v'},
107  {"single-transaction", 0, NULL, '1'},
108 
109  /*
110  * the following options don't have an equivalent short option letter
111  */
112  {"disable-triggers", no_argument, &disable_triggers, 1},
113  {"enable-row-security", no_argument, &enable_row_security, 1},
114  {"if-exists", no_argument, &if_exists, 1},
115  {"no-data-for-failed-tables", no_argument, &no_data_for_failed_tables, 1},
116  {"no-table-access-method", no_argument, &outputNoTableAm, 1},
117  {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
118  {"role", required_argument, NULL, 2},
119  {"section", required_argument, NULL, 3},
120  {"strict-names", no_argument, &strict_names, 1},
121  {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
122  {"no-comments", no_argument, &no_comments, 1},
123  {"no-publications", no_argument, &no_publications, 1},
124  {"no-security-labels", no_argument, &no_security_labels, 1},
125  {"no-subscriptions", no_argument, &no_subscriptions, 1},
126 
127  {NULL, 0, NULL, 0}
128  };
129 
130  pg_logging_init(argv[0]);
132  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
133 
135 
137 
138  progname = get_progname(argv[0]);
139 
140  if (argc > 1)
141  {
142  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
143  {
144  usage(progname);
145  exit_nicely(0);
146  }
147  if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
148  {
149  puts("pg_restore (PostgreSQL) " PG_VERSION);
150  exit_nicely(0);
151  }
152  }
153 
154  while ((c = getopt_long(argc, argv, "acCd:ef:F:h:I:j:lL:n:N:Op:P:RsS:t:T:U:vwWx1",
155  cmdopts, NULL)) != -1)
156  {
157  switch (c)
158  {
159  case 'a': /* Dump data only */
160  opts->dataOnly = 1;
161  break;
162  case 'c': /* clean (i.e., drop) schema prior to create */
163  opts->dropSchema = 1;
164  break;
165  case 'C':
166  opts->createDB = 1;
167  break;
168  case 'd':
169  opts->cparams.dbname = pg_strdup(optarg);
170  break;
171  case 'e':
172  opts->exit_on_error = true;
173  break;
174  case 'f': /* output file name */
175  opts->filename = pg_strdup(optarg);
176  break;
177  case 'F':
178  if (strlen(optarg) != 0)
179  opts->formatName = pg_strdup(optarg);
180  break;
181  case 'h':
182  if (strlen(optarg) != 0)
183  opts->cparams.pghost = pg_strdup(optarg);
184  break;
185 
186  case 'j': /* number of restore jobs */
187  if (!option_parse_int(optarg, "-j/--jobs", 1,
188  PG_MAX_JOBS,
189  &numWorkers))
190  exit(1);
191  break;
192 
193  case 'l': /* Dump the TOC summary */
194  opts->tocSummary = 1;
195  break;
196 
197  case 'L': /* input TOC summary file name */
198  opts->tocFile = pg_strdup(optarg);
199  break;
200 
201  case 'n': /* Dump data for this schema only */
202  simple_string_list_append(&opts->schemaNames, optarg);
203  break;
204 
205  case 'N': /* Do not dump data for this schema */
206  simple_string_list_append(&opts->schemaExcludeNames, optarg);
207  break;
208 
209  case 'O':
210  opts->noOwner = 1;
211  break;
212 
213  case 'p':
214  if (strlen(optarg) != 0)
215  opts->cparams.pgport = pg_strdup(optarg);
216  break;
217  case 'R':
218  /* no-op, still accepted for backwards compatibility */
219  break;
220  case 'P': /* Function */
221  opts->selTypes = 1;
222  opts->selFunction = 1;
223  simple_string_list_append(&opts->functionNames, optarg);
224  break;
225  case 'I': /* Index */
226  opts->selTypes = 1;
227  opts->selIndex = 1;
228  simple_string_list_append(&opts->indexNames, optarg);
229  break;
230  case 'T': /* Trigger */
231  opts->selTypes = 1;
232  opts->selTrigger = 1;
233  simple_string_list_append(&opts->triggerNames, optarg);
234  break;
235  case 's': /* dump schema only */
236  opts->schemaOnly = 1;
237  break;
238  case 'S': /* Superuser username */
239  if (strlen(optarg) != 0)
240  opts->superuser = pg_strdup(optarg);
241  break;
242  case 't': /* Dump specified table(s) only */
243  opts->selTypes = 1;
244  opts->selTable = 1;
245  simple_string_list_append(&opts->tableNames, optarg);
246  break;
247 
248  case 'U':
249  opts->cparams.username = pg_strdup(optarg);
250  break;
251 
252  case 'v': /* verbose */
253  opts->verbose = 1;
255  break;
256 
257  case 'w':
258  opts->cparams.promptPassword = TRI_NO;
259  break;
260 
261  case 'W':
262  opts->cparams.promptPassword = TRI_YES;
263  break;
264 
265  case 'x': /* skip ACL dump */
266  opts->aclsSkip = 1;
267  break;
268 
269  case '1': /* Restore data in a single transaction */
270  opts->single_txn = true;
271  opts->exit_on_error = true;
272  break;
273 
274  case 0:
275 
276  /*
277  * This covers the long options without a short equivalent.
278  */
279  break;
280 
281  case 2: /* SET ROLE */
282  opts->use_role = pg_strdup(optarg);
283  break;
284 
285  case 3: /* section */
286  set_dump_section(optarg, &(opts->dumpSections));
287  break;
288 
289  default:
290  /* getopt_long already emitted a complaint */
291  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
292  exit_nicely(1);
293  }
294  }
295 
296  /* Get file name from command line */
297  if (optind < argc)
298  inputFileSpec = argv[optind++];
299  else
300  inputFileSpec = NULL;
301 
302  /* Complain if any arguments remain */
303  if (optind < argc)
304  {
305  pg_log_error("too many command-line arguments (first is \"%s\")",
306  argv[optind]);
307  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
308  exit_nicely(1);
309  }
310 
311  /* Complain if neither -f nor -d was specified (except if dumping TOC) */
312  if (!opts->cparams.dbname && !opts->filename && !opts->tocSummary)
313  pg_fatal("one of -d/--dbname and -f/--file must be specified");
314 
315  /* Should get at most one of -d and -f, else user is confused */
316  if (opts->cparams.dbname)
317  {
318  if (opts->filename)
319  {
320  pg_log_error("options -d/--dbname and -f/--file cannot be used together");
321  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
322  exit_nicely(1);
323  }
324  opts->useDB = 1;
325  }
326 
327  if (opts->dataOnly && opts->schemaOnly)
328  pg_fatal("options -s/--schema-only and -a/--data-only cannot be used together");
329 
330  if (opts->dataOnly && opts->dropSchema)
331  pg_fatal("options -c/--clean and -a/--data-only cannot be used together");
332 
333  /*
334  * -C is not compatible with -1, because we can't create a database inside
335  * a transaction block.
336  */
337  if (opts->createDB && opts->single_txn)
338  pg_fatal("options -C/--create and -1/--single-transaction cannot be used together");
339 
340  /* Can't do single-txn mode with multiple connections */
341  if (opts->single_txn && numWorkers > 1)
342  pg_fatal("cannot specify both --single-transaction and multiple jobs");
343 
344  opts->disable_triggers = disable_triggers;
345  opts->enable_row_security = enable_row_security;
346  opts->noDataForFailedTables = no_data_for_failed_tables;
347  opts->noTableAm = outputNoTableAm;
348  opts->noTablespace = outputNoTablespaces;
349  opts->use_setsessauth = use_setsessauth;
350  opts->no_comments = no_comments;
351  opts->no_publications = no_publications;
352  opts->no_security_labels = no_security_labels;
353  opts->no_subscriptions = no_subscriptions;
354 
355  if (if_exists && !opts->dropSchema)
356  pg_fatal("option --if-exists requires option -c/--clean");
357  opts->if_exists = if_exists;
359 
360  if (opts->formatName)
361  {
362  switch (opts->formatName[0])
363  {
364  case 'c':
365  case 'C':
366  opts->format = archCustom;
367  break;
368 
369  case 'd':
370  case 'D':
371  opts->format = archDirectory;
372  break;
373 
374  case 't':
375  case 'T':
376  opts->format = archTar;
377  break;
378 
379  default:
380  pg_fatal("unrecognized archive format \"%s\"; please specify \"c\", \"d\", or \"t\"",
381  opts->formatName);
382  }
383  }
384 
385  AH = OpenArchive(inputFileSpec, opts->format);
386 
387  SetArchiveOptions(AH, NULL, opts);
388 
389  /*
390  * We don't have a connection yet but that doesn't matter. The connection
391  * is initialized to NULL and if we terminate through exit_nicely() while
392  * it's still NULL, the cleanup function will just be a no-op.
393  */
395 
396  /* Let the archiver know how noisy to be */
397  AH->verbose = opts->verbose;
398 
399  /*
400  * Whether to keep submitting sql commands as "pg_restore ... | psql ... "
401  */
402  AH->exit_on_error = opts->exit_on_error;
403 
404  if (opts->tocFile)
405  SortTocFromFile(AH);
406 
407  AH->numWorkers = numWorkers;
408 
409  if (opts->tocSummary)
410  PrintTOCSummary(AH);
411  else
412  {
414  RestoreArchive(AH);
415  }
416 
417  /* done, print a summary of ignored errors */
418  if (AH->n_errors)
419  pg_log_warning("errors ignored on restore: %d", AH->n_errors);
420 
421  /* AH may be freed in CloseArchive? */
422  exit_code = AH->n_errors ? 1 : 0;
423 
424  CloseArchive(AH);
425 
426  return exit_code;
427 }
428 
429 static void
430 usage(const char *progname)
431 {
432  printf(_("%s restores a PostgreSQL database from an archive created by pg_dump.\n\n"), progname);
433  printf(_("Usage:\n"));
434  printf(_(" %s [OPTION]... [FILE]\n"), progname);
435 
436  printf(_("\nGeneral options:\n"));
437  printf(_(" -d, --dbname=NAME connect to database name\n"));
438  printf(_(" -f, --file=FILENAME output file name (- for stdout)\n"));
439  printf(_(" -F, --format=c|d|t backup file format (should be automatic)\n"));
440  printf(_(" -l, --list print summarized TOC of the archive\n"));
441  printf(_(" -v, --verbose verbose mode\n"));
442  printf(_(" -V, --version output version information, then exit\n"));
443  printf(_(" -?, --help show this help, then exit\n"));
444 
445  printf(_("\nOptions controlling the restore:\n"));
446  printf(_(" -a, --data-only restore only the data, no schema\n"));
447  printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
448  printf(_(" -C, --create create the target database\n"));
449  printf(_(" -e, --exit-on-error exit on error, default is to continue\n"));
450  printf(_(" -I, --index=NAME restore named index\n"));
451  printf(_(" -j, --jobs=NUM use this many parallel jobs to restore\n"));
452  printf(_(" -L, --use-list=FILENAME use table of contents from this file for\n"
453  " selecting/ordering output\n"));
454  printf(_(" -n, --schema=NAME restore only objects in this schema\n"));
455  printf(_(" -N, --exclude-schema=NAME do not restore objects in this schema\n"));
456  printf(_(" -O, --no-owner skip restoration of object ownership\n"));
457  printf(_(" -P, --function=NAME(args) restore named function\n"));
458  printf(_(" -s, --schema-only restore only the schema, no data\n"));
459  printf(_(" -S, --superuser=NAME superuser user name to use for disabling triggers\n"));
460  printf(_(" -t, --table=NAME restore named relation (table, view, etc.)\n"));
461  printf(_(" -T, --trigger=NAME restore named trigger\n"));
462  printf(_(" -x, --no-privileges skip restoration of access privileges (grant/revoke)\n"));
463  printf(_(" -1, --single-transaction restore as a single transaction\n"));
464  printf(_(" --disable-triggers disable triggers during data-only restore\n"));
465  printf(_(" --enable-row-security enable row security\n"));
466  printf(_(" --if-exists use IF EXISTS when dropping objects\n"));
467  printf(_(" --no-comments do not restore comments\n"));
468  printf(_(" --no-data-for-failed-tables do not restore data of tables that could not be\n"
469  " created\n"));
470  printf(_(" --no-publications do not restore publications\n"));
471  printf(_(" --no-security-labels do not restore security labels\n"));
472  printf(_(" --no-subscriptions do not restore subscriptions\n"));
473  printf(_(" --no-table-access-method do not restore table access methods\n"));
474  printf(_(" --no-tablespaces do not restore tablespace assignments\n"));
475  printf(_(" --section=SECTION restore named section (pre-data, data, or post-data)\n"));
476  printf(_(" --strict-names require table and/or schema include patterns to\n"
477  " match at least one entity each\n"));
478  printf(_(" --use-set-session-authorization\n"
479  " use SET SESSION AUTHORIZATION commands instead of\n"
480  " ALTER OWNER commands to set ownership\n"));
481 
482  printf(_("\nConnection options:\n"));
483  printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
484  printf(_(" -p, --port=PORT database server port number\n"));
485  printf(_(" -U, --username=NAME connect as specified database user\n"));
486  printf(_(" -w, --no-password never prompt for password\n"));
487  printf(_(" -W, --password force password prompt (should happen automatically)\n"));
488  printf(_(" --role=ROLENAME do SET ROLE before restore\n"));
489 
490  printf(_("\n"
491  "The options -I, -n, -N, -P, -t, -T, and --section can be combined and specified\n"
492  "multiple times to select multiple objects.\n"));
493  printf(_("\nIf no input file name is supplied, then standard input is used.\n\n"));
494  printf(_("Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);
495  printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
496 }
void on_exit_close_archive(Archive *AHX)
Definition: parallel.c:328
void init_parallel_dump_utils(void)
Definition: parallel.c:236
#define PG_MAX_JOBS
Definition: parallel.h:48
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1204
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:436
#define _(x)
Definition: elog.c:91
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:57
#define no_argument
Definition: getopt_long.h:24
#define required_argument
Definition: getopt_long.h:25
exit(1)
void pg_logging_increase_verbosity(void)
Definition: logging.c:182
void pg_logging_init(const char *argv0)
Definition: logging.c:83
void pg_logging_set_level(enum pg_log_level new_level)
Definition: logging.c:173
#define pg_log_error(...)
Definition: logging.h:106
#define pg_log_error_hint(...)
Definition: logging.h:112
@ PG_LOG_WARNING
Definition: logging.h:38
const char * progname
Definition: main.c:45
bool option_parse_int(const char *optarg, const char *optname, int min_range, int max_range, int *result)
Definition: option_utils.c:50
static AmcheckOptions opts
Definition: pg_amcheck.c:110
void ProcessArchiveRestoreOptions(Archive *AHX)
RestoreOptions * NewRestoreOptions(void)
void CloseArchive(Archive *AHX)
void SortTocFromFile(Archive *AHX)
void PrintTOCSummary(Archive *AHX)
void SetArchiveOptions(Archive *AH, DumpOptions *dopt, RestoreOptions *ropt)
void RestoreArchive(Archive *AHX)
@ archTar
Definition: pg_backup.h:42
@ archCustom
Definition: pg_backup.h:41
@ archDirectory
Definition: pg_backup.h:44
Archive * OpenArchive(const char *FileSpec, const ArchiveFormat fmt)
void set_dump_section(const char *arg, int *dumpSections)
#define pg_fatal(...)
static int strict_names
Definition: pg_dump.c:106
static int if_exists
Definition: pg_dumpall.c:98
static int disable_triggers
Definition: pg_dumpall.c:97
#define exit_nicely(code)
Definition: pg_dumpall.c:124
static int no_comments
Definition: pg_dumpall.c:103
static int no_publications
Definition: pg_dumpall.c:104
static int no_security_labels
Definition: pg_dumpall.c:105
static int use_setsessauth
Definition: pg_dumpall.c:102
static int no_subscriptions
Definition: pg_dumpall.c:106
PGDLLIMPORT int optind
Definition: getopt.c:50
PGDLLIMPORT char * optarg
Definition: getopt.c:52
static void usage(const char *progname)
Definition: pg_restore.c:430
int main(int argc, char **argv)
Definition: pg_restore.c:57
#define pg_log_warning(...)
Definition: pgfnames.c:24
const char * get_progname(const char *argv0)
Definition: path.c:574
#define printf(...)
Definition: port.h:244
char * c
void simple_string_list_append(SimpleStringList *list, const char *val)
Definition: simple_list.c:63
bool strict_names
Definition: pg_amcheck.c:60
bool exit_on_error
Definition: pg_backup.h:234
int n_errors
Definition: pg_backup.h:235
int numWorkers
Definition: pg_backup.h:222
int verbose
Definition: pg_backup.h:214
@ TRI_YES
Definition: vacuumlo.c:38
@ TRI_NO
Definition: vacuumlo.c:37