]> granicus.if.org Git - postgresql/blob - src/bin/pg_dump/pg_restore.c
Logical replication
[postgresql] / src / bin / pg_dump / pg_restore.c
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 "getopt_long.h"
44
45 #include "dumputils.h"
46 #include "parallel.h"
47 #include "pg_backup_utils.h"
48
49 #include <ctype.h>
50
51 #ifdef HAVE_TERMIOS_H
52 #include <termios.h>
53 #endif
54
55 #ifdef ENABLE_NLS
56 #include <locale.h>
57 #endif
58
59
60 static void usage(const char *progname);
61
62 typedef struct option optType;
63
64 int
65 main(int argc, char **argv)
66 {
67         RestoreOptions *opts;
68         int                     c;
69         int                     exit_code;
70         int                     numWorkers = 1;
71         Archive    *AH;
72         char       *inputFileSpec;
73         static int      disable_triggers = 0;
74         static int      enable_row_security = 0;
75         static int      include_subscriptions = 0;
76         static int      if_exists = 0;
77         static int      no_data_for_failed_tables = 0;
78         static int      outputNoTablespaces = 0;
79         static int      use_setsessauth = 0;
80         static int      no_security_labels = 0;
81         static int      strict_names = 0;
82
83         struct option cmdopts[] = {
84                 {"clean", 0, NULL, 'c'},
85                 {"create", 0, NULL, 'C'},
86                 {"data-only", 0, NULL, 'a'},
87                 {"dbname", 1, NULL, 'd'},
88                 {"exit-on-error", 0, NULL, 'e'},
89                 {"exclude-schema", 1, NULL, 'N'},
90                 {"file", 1, NULL, 'f'},
91                 {"format", 1, NULL, 'F'},
92                 {"function", 1, NULL, 'P'},
93                 {"host", 1, NULL, 'h'},
94                 {"index", 1, NULL, 'I'},
95                 {"jobs", 1, NULL, 'j'},
96                 {"list", 0, NULL, 'l'},
97                 {"no-privileges", 0, NULL, 'x'},
98                 {"no-acl", 0, NULL, 'x'},
99                 {"no-owner", 0, NULL, 'O'},
100                 {"no-reconnect", 0, NULL, 'R'},
101                 {"port", 1, NULL, 'p'},
102                 {"no-password", 0, NULL, 'w'},
103                 {"password", 0, NULL, 'W'},
104                 {"schema", 1, NULL, 'n'},
105                 {"schema-only", 0, NULL, 's'},
106                 {"superuser", 1, NULL, 'S'},
107                 {"table", 1, NULL, 't'},
108                 {"trigger", 1, NULL, 'T'},
109                 {"use-list", 1, NULL, 'L'},
110                 {"username", 1, NULL, 'U'},
111                 {"verbose", 0, NULL, 'v'},
112                 {"single-transaction", 0, NULL, '1'},
113
114                 /*
115                  * the following options don't have an equivalent short option letter
116                  */
117                 {"disable-triggers", no_argument, &disable_triggers, 1},
118                 {"enable-row-security", no_argument, &enable_row_security, 1},
119                 {"if-exists", no_argument, &if_exists, 1},
120                 {"include-subscriptions", no_argument, &include_subscriptions, 1},
121                 {"no-data-for-failed-tables", no_argument, &no_data_for_failed_tables, 1},
122                 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
123                 {"role", required_argument, NULL, 2},
124                 {"section", required_argument, NULL, 3},
125                 {"strict-names", no_argument, &strict_names, 1},
126                 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
127                 {"no-security-labels", no_argument, &no_security_labels, 1},
128
129                 {NULL, 0, NULL, 0}
130         };
131
132         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
133
134         init_parallel_dump_utils();
135
136         opts = NewRestoreOptions();
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->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->pghost = pg_strdup(optarg);
184                                 break;
185
186                         case 'j':                       /* number of restore jobs */
187                                 numWorkers = atoi(optarg);
188                                 break;
189
190                         case 'l':                       /* Dump the TOC summary */
191                                 opts->tocSummary = 1;
192                                 break;
193
194                         case 'L':                       /* input TOC summary file name */
195                                 opts->tocFile = pg_strdup(optarg);
196                                 break;
197
198                         case 'n':                       /* Dump data for this schema only */
199                                 simple_string_list_append(&opts->schemaNames, optarg);
200                                 break;
201
202                         case 'N':                       /* Do not dump data for this schema */
203                                 simple_string_list_append(&opts->schemaExcludeNames, optarg);
204                                 break;
205
206                         case 'O':
207                                 opts->noOwner = 1;
208                                 break;
209
210                         case 'p':
211                                 if (strlen(optarg) != 0)
212                                         opts->pgport = pg_strdup(optarg);
213                                 break;
214                         case 'R':
215                                 /* no-op, still accepted for backwards compatibility */
216                                 break;
217                         case 'P':                       /* Function */
218                                 opts->selTypes = 1;
219                                 opts->selFunction = 1;
220                                 simple_string_list_append(&opts->functionNames, optarg);
221                                 break;
222                         case 'I':                       /* Index */
223                                 opts->selTypes = 1;
224                                 opts->selIndex = 1;
225                                 simple_string_list_append(&opts->indexNames, optarg);
226                                 break;
227                         case 'T':                       /* Trigger */
228                                 opts->selTypes = 1;
229                                 opts->selTrigger = 1;
230                                 simple_string_list_append(&opts->triggerNames, optarg);
231                                 break;
232                         case 's':                       /* dump schema only */
233                                 opts->schemaOnly = 1;
234                                 break;
235                         case 'S':                       /* Superuser username */
236                                 if (strlen(optarg) != 0)
237                                         opts->superuser = pg_strdup(optarg);
238                                 break;
239                         case 't':                       /* Dump specified table(s) only */
240                                 opts->selTypes = 1;
241                                 opts->selTable = 1;
242                                 simple_string_list_append(&opts->tableNames, optarg);
243                                 break;
244
245                         case 'U':
246                                 opts->username = pg_strdup(optarg);
247                                 break;
248
249                         case 'v':                       /* verbose */
250                                 opts->verbose = 1;
251                                 break;
252
253                         case 'w':
254                                 opts->promptPassword = TRI_NO;
255                                 break;
256
257                         case 'W':
258                                 opts->promptPassword = TRI_YES;
259                                 break;
260
261                         case 'x':                       /* skip ACL dump */
262                                 opts->aclsSkip = 1;
263                                 break;
264
265                         case '1':                       /* Restore data in a single transaction */
266                                 opts->single_txn = true;
267                                 opts->exit_on_error = true;
268                                 break;
269
270                         case 0:
271
272                                 /*
273                                  * This covers the long options without a short equivalent.
274                                  */
275                                 break;
276
277                         case 2:                         /* SET ROLE */
278                                 opts->use_role = pg_strdup(optarg);
279                                 break;
280
281                         case 3:                         /* section */
282                                 set_dump_section(optarg, &(opts->dumpSections));
283                                 break;
284
285                         default:
286                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
287                                 exit_nicely(1);
288                 }
289         }
290
291         /* Get file name from command line */
292         if (optind < argc)
293                 inputFileSpec = argv[optind++];
294         else
295                 inputFileSpec = NULL;
296
297         /* Complain if any arguments remain */
298         if (optind < argc)
299         {
300                 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
301                                 progname, argv[optind]);
302                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
303                                 progname);
304                 exit_nicely(1);
305         }
306
307         /* Should get at most one of -d and -f, else user is confused */
308         if (opts->dbname)
309         {
310                 if (opts->filename)
311                 {
312                         fprintf(stderr, _("%s: options -d/--dbname and -f/--file cannot be used together\n"),
313                                         progname);
314                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
315                                         progname);
316                         exit_nicely(1);
317                 }
318                 opts->useDB = 1;
319         }
320
321         if (opts->dataOnly && opts->schemaOnly)
322         {
323                 fprintf(stderr, _("%s: options -s/--schema-only and -a/--data-only cannot be used together\n"),
324                                 progname);
325                 exit_nicely(1);
326         }
327
328         if (opts->dataOnly && opts->dropSchema)
329         {
330                 fprintf(stderr, _("%s: options -c/--clean and -a/--data-only cannot be used together\n"),
331                                 progname);
332                 exit_nicely(1);
333         }
334
335         if (numWorkers <= 0)
336         {
337                 fprintf(stderr, _("%s: invalid number of parallel jobs\n"), progname);
338                 exit(1);
339         }
340
341         /* See comments in pg_dump.c */
342 #ifdef WIN32
343         if (numWorkers > MAXIMUM_WAIT_OBJECTS)
344         {
345                 fprintf(stderr, _("%s: maximum number of parallel jobs is %d\n"),
346                                 progname, MAXIMUM_WAIT_OBJECTS);
347                 exit(1);
348         }
349 #endif
350
351         /* Can't do single-txn mode with multiple connections */
352         if (opts->single_txn && numWorkers > 1)
353         {
354                 fprintf(stderr, _("%s: cannot specify both --single-transaction and multiple jobs\n"),
355                                 progname);
356                 exit_nicely(1);
357         }
358
359         opts->disable_triggers = disable_triggers;
360         opts->enable_row_security = enable_row_security;
361         opts->include_subscriptions = include_subscriptions;
362         opts->noDataForFailedTables = no_data_for_failed_tables;
363         opts->noTablespace = outputNoTablespaces;
364         opts->use_setsessauth = use_setsessauth;
365         opts->no_security_labels = no_security_labels;
366
367         if (if_exists && !opts->dropSchema)
368         {
369                 fprintf(stderr, _("%s: option --if-exists requires option -c/--clean\n"),
370                                 progname);
371                 exit_nicely(1);
372         }
373         opts->if_exists = if_exists;
374         opts->strict_names = strict_names;
375
376         if (opts->formatName)
377         {
378                 switch (opts->formatName[0])
379                 {
380                         case 'c':
381                         case 'C':
382                                 opts->format = archCustom;
383                                 break;
384
385                         case 'd':
386                         case 'D':
387                                 opts->format = archDirectory;
388                                 break;
389
390                         case 't':
391                         case 'T':
392                                 opts->format = archTar;
393                                 break;
394
395                         default:
396                                 write_msg(NULL, "unrecognized archive format \"%s\"; please specify \"c\", \"d\", or \"t\"\n",
397                                                   opts->formatName);
398                                 exit_nicely(1);
399                 }
400         }
401
402         AH = OpenArchive(inputFileSpec, opts->format);
403
404         SetArchiveOptions(AH, NULL, opts);
405
406         /*
407          * We don't have a connection yet but that doesn't matter. The connection
408          * is initialized to NULL and if we terminate through exit_nicely() while
409          * it's still NULL, the cleanup function will just be a no-op.
410          */
411         on_exit_close_archive(AH);
412
413         /* Let the archiver know how noisy to be */
414         AH->verbose = opts->verbose;
415
416         /*
417          * Whether to keep submitting sql commands as "pg_restore ... | psql ... "
418          */
419         AH->exit_on_error = opts->exit_on_error;
420
421         if (opts->tocFile)
422                 SortTocFromFile(AH);
423
424         AH->numWorkers = numWorkers;
425
426         if (opts->tocSummary)
427                 PrintTOCSummary(AH);
428         else
429         {
430                 ProcessArchiveRestoreOptions(AH);
431                 RestoreArchive(AH);
432         }
433
434         /* done, print a summary of ignored errors */
435         if (AH->n_errors)
436                 fprintf(stderr, _("WARNING: errors ignored on restore: %d\n"),
437                                 AH->n_errors);
438
439         /* AH may be freed in CloseArchive? */
440         exit_code = AH->n_errors ? 1 : 0;
441
442         CloseArchive(AH);
443
444         return exit_code;
445 }
446
447 static void
448 usage(const char *progname)
449 {
450         printf(_("%s restores a PostgreSQL database from an archive created by pg_dump.\n\n"), progname);
451         printf(_("Usage:\n"));
452         printf(_("  %s [OPTION]... [FILE]\n"), progname);
453
454         printf(_("\nGeneral options:\n"));
455         printf(_("  -d, --dbname=NAME        connect to database name\n"));
456         printf(_("  -f, --file=FILENAME      output file name\n"));
457         printf(_("  -F, --format=c|d|t       backup file format (should be automatic)\n"));
458         printf(_("  -l, --list               print summarized TOC of the archive\n"));
459         printf(_("  -v, --verbose            verbose mode\n"));
460         printf(_("  -V, --version            output version information, then exit\n"));
461         printf(_("  -?, --help               show this help, then exit\n"));
462
463         printf(_("\nOptions controlling the restore:\n"));
464         printf(_("  -a, --data-only              restore only the data, no schema\n"));
465         printf(_("  -c, --clean                  clean (drop) database objects before recreating\n"));
466         printf(_("  -C, --create                 create the target database\n"));
467         printf(_("  -e, --exit-on-error          exit on error, default is to continue\n"));
468         printf(_("  -I, --index=NAME             restore named index\n"));
469         printf(_("  -j, --jobs=NUM               use this many parallel jobs to restore\n"));
470         printf(_("  -L, --use-list=FILENAME      use table of contents from this file for\n"
471                          "                               selecting/ordering output\n"));
472         printf(_("  -n, --schema=NAME            restore only objects in this schema\n"));
473         printf(_("  -N, --exclude-schema=NAME    do not restore objects in this schema\n"));
474         printf(_("  -O, --no-owner               skip restoration of object ownership\n"));
475         printf(_("  -P, --function=NAME(args)    restore named function\n"));
476         printf(_("  -s, --schema-only            restore only the schema, no data\n"));
477         printf(_("  -S, --superuser=NAME         superuser user name to use for disabling triggers\n"));
478         printf(_("  -t, --table=NAME             restore named relation (table, view, etc.)\n"));
479         printf(_("  -T, --trigger=NAME           restore named trigger\n"));
480         printf(_("  -x, --no-privileges          skip restoration of access privileges (grant/revoke)\n"));
481         printf(_("  -1, --single-transaction     restore as a single transaction\n"));
482         printf(_("  --disable-triggers           disable triggers during data-only restore\n"));
483         printf(_("  --enable-row-security        enable row security\n"));
484         printf(_("  --if-exists                  use IF EXISTS when dropping objects\n"));
485         printf(_("  --no-data-for-failed-tables  do not restore data of tables that could not be\n"
486                          "                               created\n"));
487         printf(_("  --no-security-labels         do not restore security labels\n"));
488         printf(_("  --no-tablespaces             do not restore tablespace assignments\n"));
489         printf(_("  --section=SECTION            restore named section (pre-data, data, or post-data)\n"));
490         printf(_("  --strict-names               require table and/or schema include patterns to\n"
491                  "                               match at least one entity each\n"));
492         printf(_("  --use-set-session-authorization\n"
493                          "                               use SET SESSION AUTHORIZATION commands instead of\n"
494                          "                               ALTER OWNER commands to set ownership\n"));
495
496         printf(_("\nConnection options:\n"));
497         printf(_("  -h, --host=HOSTNAME      database server host or socket directory\n"));
498         printf(_("  -p, --port=PORT          database server port number\n"));
499         printf(_("  -U, --username=NAME      connect as specified database user\n"));
500         printf(_("  -w, --no-password        never prompt for password\n"));
501         printf(_("  -W, --password           force password prompt (should happen automatically)\n"));
502         printf(_("  --role=ROLENAME          do SET ROLE before restore\n"));
503
504         printf(_("\n"
505                          "The options -I, -n, -P, -t, -T, and --section can be combined and specified\n"
506                          "multiple times to select multiple objects.\n"));
507         printf(_("\nIf no input file name is supplied, then standard input is used.\n\n"));
508         printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
509 }