pg_backup_archiver.c 106.7 KB
Newer Older
B
Bruce Momjian 已提交
1 2 3 4 5 6 7 8 9 10
/*-------------------------------------------------------------------------
 *
 * pg_backup_archiver.c
 *
 *	Private implementation of the archiver routines.
 *
 *	See the headers to pg_restore for more details.
 *
 * Copyright (c) 2000, Philip Warner
 *	Rights are granted to use this software in any way so long
B
Bruce Momjian 已提交
11
 *	as this notice is not removed.
B
Bruce Momjian 已提交
12 13
 *
 *	The author is not responsible for loss or damages that may
14
 *	result from its use.
B
Bruce Momjian 已提交
15 16 17
 *
 *
 * IDENTIFICATION
18
 *		src/bin/pg_dump/pg_backup_archiver.c
19
 *
B
Bruce Momjian 已提交
20 21 22
 *-------------------------------------------------------------------------
 */

23
#include "pg_backup_db.h"
24
#include "dumpmem.h"
25
#include "dumputils.h"
26

27
#include <ctype.h>
28
#include <unistd.h>
29
#include <sys/stat.h>
30 31
#include <sys/types.h>
#include <sys/wait.h>
B
Bruce Momjian 已提交
32

33 34 35 36
#ifdef WIN32
#include <io.h>
#endif

37
#include "libpq/libpq-fs.h"
38

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
/*
 * Special exit values from worker children.  We reserve 0 for normal
 * success; 1 and other small values should be interpreted as crashes.
 */
#define WORKER_CREATE_DONE		10
#define WORKER_INHIBIT_DATA		11
#define WORKER_IGNORED_ERRORS	12

/*
 * Unix uses exit to return result from worker child, so function is void.
 * Windows thread result comes via function return.
 */
#ifndef WIN32
#define parallel_restore_result void
#else
#define parallel_restore_result DWORD
#endif

/* IDs for worker children are either PIDs or thread handles */
#ifndef WIN32
#define thandle pid_t
#else
#define thandle HANDLE
#endif

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
typedef struct ParallelStateEntry
{
#ifdef WIN32
	unsigned int threadId;
#else
	pid_t		pid;
#endif
	ArchiveHandle *AH;
} ParallelStateEntry;

typedef struct ParallelState
{
	int			numWorkers;
	ParallelStateEntry *pse;
} ParallelState;

80
/* Arguments needed for a worker child */
81 82 83
typedef struct _restore_args
{
	ArchiveHandle *AH;
84
	TocEntry   *te;
85
	ParallelStateEntry *pse;
86 87
} RestoreArgs;

88
/* State for each parallel activity slot */
89 90 91 92 93 94
typedef struct _parallel_slot
{
	thandle		child_id;
	RestoreArgs *args;
} ParallelSlot;

95 96 97
typedef struct ShutdownInformation
{
	ParallelState *pstate;
98
	Archive    *AHX;
99 100 101 102
} ShutdownInformation;

static ShutdownInformation shutdown_info;

103
#define NO_SLOT (-1)
104

105 106 107
#define TEXT_DUMP_HEADER "--\n-- PostgreSQL database dump\n--\n\n"
#define TEXT_DUMPALL_HEADER "--\n-- PostgreSQL database cluster dump\n--\n\n"

108 109 110 111 112 113 114
/* state needed to save/restore an archive's output target */
typedef struct _outputContext
{
	void	   *OF;
	int			gzOut;
} OutputContext;

115
static const char *modulename = gettext_noop("archiver");
116 117


B
Bruce Momjian 已提交
118 119
static ArchiveHandle *_allocAH(const char *FileSpec, const ArchiveFormat fmt,
		 const int compression, ArchiveMode mode);
120
static void _getObjectDescription(PQExpBuffer buf, TocEntry *te,
B
Bruce Momjian 已提交
121
					  ArchiveHandle *AH);
122
static void _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass);
123
static char *replace_line_endings(const char *str);
124
static void _doSetFixedOutputState(ArchiveHandle *AH);
125
static void _doSetSessionAuth(ArchiveHandle *AH, const char *user);
126
static void _doSetWithOids(ArchiveHandle *AH, const bool withOids);
127
static void _reconnectToDB(ArchiveHandle *AH, const char *dbname);
128 129
static void _becomeUser(ArchiveHandle *AH, const char *user);
static void _becomeOwner(ArchiveHandle *AH, TocEntry *te);
130
static void _selectOutputSchema(ArchiveHandle *AH, const char *schemaName);
131
static void _selectTablespace(ArchiveHandle *AH, const char *tablespace);
132 133
static void processEncodingEntry(ArchiveHandle *AH, TocEntry *te);
static void processStdStringsEntry(ArchiveHandle *AH, TocEntry *te);
134
static teReqs _tocEntryRequired(TocEntry *te, teSection curSection, RestoreOptions *ropt);
135
static bool _tocEntryIsACL(TocEntry *te);
B
Bruce Momjian 已提交
136 137
static void _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
static void _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
138
static void buildTocEntryArrays(ArchiveHandle *AH);
139
static TocEntry *getTocEntryByDumpId(ArchiveHandle *AH, DumpId id);
140
static void _moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te);
B
Bruce Momjian 已提交
141
static int	_discoverArchiveFormat(ArchiveHandle *AH);
B
Bruce Momjian 已提交
142

143
static int	RestoringToDB(ArchiveHandle *AH);
144
static void dump_lo_buf(ArchiveHandle *AH);
145
static void dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim);
146
static void SetOutput(ArchiveHandle *AH, const char *filename, int compression);
147 148
static OutputContext SaveOutput(ArchiveHandle *AH);
static void RestoreOutput(ArchiveHandle *AH, OutputContext savedContext);
149

150
static int restore_toc_entry(ArchiveHandle *AH, TocEntry *te,
151
				  RestoreOptions *ropt, bool is_parallel);
152 153 154 155
static void restore_toc_entries_parallel(ArchiveHandle *AH);
static thandle spawn_restore(RestoreArgs *args);
static thandle reap_child(ParallelSlot *slots, int n_slots, int *work_status);
static bool work_in_progress(ParallelSlot *slots, int n_slots);
156
static int	get_next_slot(ParallelSlot *slots, int n_slots);
157 158 159
static void par_list_header_init(TocEntry *l);
static void par_list_append(TocEntry *l, TocEntry *te);
static void par_list_remove(TocEntry *te);
160
static TocEntry *get_next_work_item(ArchiveHandle *AH,
161
				   TocEntry *ready_list,
162
				   ParallelSlot *slots, int n_slots);
163
static parallel_restore_result parallel_restore(RestoreArgs *args);
164 165
static void mark_work_done(ArchiveHandle *AH, TocEntry *ready_list,
			   thandle worker, int status,
166
			   ParallelSlot *slots, int n_slots);
167
static void fix_dependencies(ArchiveHandle *AH);
168
static bool has_lock_conflicts(TocEntry *te1, TocEntry *te2);
169 170
static void repoint_table_dependencies(ArchiveHandle *AH);
static void identify_locking_dependencies(ArchiveHandle *AH, TocEntry *te);
171
static void reduce_dependencies(ArchiveHandle *AH, TocEntry *te,
B
Bruce Momjian 已提交
172
					TocEntry *ready_list);
173 174 175 176 177
static void mark_create_done(ArchiveHandle *AH, TocEntry *te);
static void inhibit_data_for_failed_table(ArchiveHandle *AH, TocEntry *te);
static ArchiveHandle *CloneArchive(ArchiveHandle *AH);
static void DeCloneArchive(ArchiveHandle *AH);

178 179 180 181 182
static void setProcessIdentifier(ParallelStateEntry *pse, ArchiveHandle *AH);
static void unsetProcessIdentifier(ParallelStateEntry *pse);
static ParallelStateEntry *GetMyPSEntry(ParallelState *pstate);
static void archive_close_connection(int code, void *arg);

183

B
Bruce Momjian 已提交
184
/*
B
Bruce Momjian 已提交
185 186 187 188
 *	Wrapper functions.
 *
 *	The objective it to make writing new formats and dumpers as simple
 *	as possible, if necessary at the expense of extra function calls etc.
B
Bruce Momjian 已提交
189 190 191 192 193 194
 *
 */


/* Create a new archive */
/* Public */
195
Archive *
B
Bruce Momjian 已提交
196
CreateArchive(const char *FileSpec, const ArchiveFormat fmt,
197
			  const int compression, ArchiveMode mode)
198

B
Bruce Momjian 已提交
199
{
200
	ArchiveHandle *AH = _allocAH(FileSpec, fmt, compression, mode);
B
Bruce Momjian 已提交
201 202

	return (Archive *) AH;
B
Bruce Momjian 已提交
203 204 205 206
}

/* Open an existing archive */
/* Public */
207
Archive *
B
Bruce Momjian 已提交
208
OpenArchive(const char *FileSpec, const ArchiveFormat fmt)
B
Bruce Momjian 已提交
209
{
B
Bruce Momjian 已提交
210 211 212
	ArchiveHandle *AH = _allocAH(FileSpec, fmt, 0, archModeRead);

	return (Archive *) AH;
B
Bruce Momjian 已提交
213 214 215
}

/* Public */
B
Bruce Momjian 已提交
216 217
void
CloseArchive(Archive *AHX)
B
Bruce Momjian 已提交
218
{
B
Bruce Momjian 已提交
219 220 221 222
	int			res = 0;
	ArchiveHandle *AH = (ArchiveHandle *) AHX;

	(*AH->ClosePtr) (AH);
B
Bruce Momjian 已提交
223

B
Bruce Momjian 已提交
224 225
	/* Close the output */
	if (AH->gzOut)
226
		res = GZCLOSE(AH->OF);
B
Bruce Momjian 已提交
227
	else if (AH->OF != stdout)
228 229 230
		res = fclose(AH->OF);

	if (res != 0)
231 232
		exit_horribly(modulename, "could not close output file: %s\n",
					  strerror(errno));
B
Bruce Momjian 已提交
233 234 235
}

/* Public */
B
Bruce Momjian 已提交
236
void
237
SetArchiveRestoreOptions(Archive *AHX, RestoreOptions *ropt)
B
Bruce Momjian 已提交
238
{
B
Bruce Momjian 已提交
239
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
	TocEntry   *te;
	teSection	curSection;

	/* Save options for later access */
	AH->ropt = ropt;

	/* Decide which TOC entries will be dumped/restored, and mark them */
	curSection = SECTION_PRE_DATA;
	for (te = AH->toc->next; te != AH->toc; te = te->next)
	{
		if (te->section != SECTION_NONE)
			curSection = te->section;
		te->reqs = _tocEntryRequired(te, curSection, ropt);
	}
}

/* Public */
void
RestoreArchive(Archive *AHX)
{
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
	RestoreOptions *ropt = AH->ropt;
262
	bool		parallel_mode;
263
	TocEntry   *te;
B
Bruce Momjian 已提交
264
	OutputContext sav;
B
Bruce Momjian 已提交
265

266
	AH->stage = STAGE_INITIALIZING;
267

268 269 270
	/*
	 * Check for nonsensical option combinations.
	 *
271
	 * NB: createDB+dropSchema is useless because if you're creating the DB,
B
Bruce Momjian 已提交
272 273 274
	 * there's no need to drop individual items in it.  Moreover, if we tried
	 * to do that then we'd issue the drops in the database initially
	 * connected to, not the one we will create, which is very bad...
275
	 */
276
	if (ropt->createDB && ropt->dropSchema)
277
		exit_horribly(modulename, "-C and -c are incompatible options\n");
278

279
	/*
280
	 * -C is not compatible with -1, because we can't create a database inside
281
	 * a transaction block.
282
	 */
283
	if (ropt->createDB && ropt->single_txn)
284
		exit_horribly(modulename, "-C and -1 are incompatible options\n");
285

286 287 288 289 290 291 292 293
	/*
	 * If we're going to do parallel restore, there are some restrictions.
	 */
	parallel_mode = (ropt->number_of_jobs > 1 && ropt->useDB);
	if (parallel_mode)
	{
		/* We haven't got round to making this work for all archive formats */
		if (AH->ClonePtr == NULL || AH->ReopenPtr == NULL)
294
			exit_horribly(modulename, "parallel restore is not supported with this archive file format\n");
295 296 297

		/* Doesn't work if the archive represents dependencies as OIDs */
		if (AH->version < K_VERS_1_8)
298
			exit_horribly(modulename, "parallel restore is not supported with archives made by pre-8.0 pg_dump\n");
299 300 301 302 303 304 305 306

		/*
		 * It's also not gonna work if we can't reopen the input file, so
		 * let's try that immediately.
		 */
		(AH->ReopenPtr) (AH);
	}

307 308 309 310
	/*
	 * Make sure we won't need (de)compression we haven't got
	 */
#ifndef HAVE_LIBZ
311
	if (AH->compression != 0 && AH->PrintTocDataPtr !=NULL)
312 313 314
	{
		for (te = AH->toc->next; te != AH->toc; te = te->next)
		{
315
			if (te->hadDumper && (te->reqs & REQ_DATA) != 0)
316
				exit_horribly(modulename, "cannot restore from compressed archive (compression not supported in this installation)\n");
317 318 319 320
		}
	}
#endif

321 322 323 324 325 326 327
	/*
	 * Prepare index arrays, so we can assume we have them throughout restore.
	 * It's possible we already did this, though.
	 */
	if (AH->tocsByDumpId == NULL)
		buildTocEntryArrays(AH);

328 329 330 331 332
	/*
	 * If we're using a DB connection, then connect it.
	 */
	if (ropt->useDB)
	{
333
		ahlog(AH, 1, "connecting to database for restore\n");
334
		if (AH->version < K_VERS_1_3)
335
			exit_horribly(modulename, "direct database connections are not supported in pre-1.3 archives\n");
336

337 338 339 340
		/* XXX Should get this from the archive */
		AHX->minRemoteVersion = 070100;
		AHX->maxRemoteVersion = 999999;

341 342
		ConnectDatabase(AHX, ropt->dbname,
						ropt->pghost, ropt->pgport, ropt->username,
343
						ropt->promptPassword);
B
Bruce Momjian 已提交
344 345

		/*
B
Bruce Momjian 已提交
346 347
		 * If we're talking to the DB directly, don't send comments since they
		 * obscure SQL when displaying errors
B
Bruce Momjian 已提交
348
		 */
349
		AH->noTocComments = 1;
350 351
	}

352
	/*
B
Bruce Momjian 已提交
353 354 355 356
	 * Work out if we have an implied data-only restore. This can happen if
	 * the dump was data only or if the user has used a toc list to exclude
	 * all of the schema data. All we do is look for schema entries - if none
	 * are found then we set the dataOnly flag.
357
	 *
B
Bruce Momjian 已提交
358
	 * We could scan for wanted TABLE entries, but that is not the same as
359
	 * dataOnly. At this stage, it seems unnecessary (6-Mar-2001).
B
Bruce Momjian 已提交
360 361 362
	 */
	if (!ropt->dataOnly)
	{
B
Bruce Momjian 已提交
363
		int			impliedDataOnly = 1;
364 365

		for (te = AH->toc->next; te != AH->toc; te = te->next)
B
Bruce Momjian 已提交
366
		{
367
			if ((te->reqs & REQ_SCHEMA) != 0)
B
Bruce Momjian 已提交
368
			{					/* It's schema, and it's wanted */
369 370 371 372 373 374 375
				impliedDataOnly = 0;
				break;
			}
		}
		if (impliedDataOnly)
		{
			ropt->dataOnly = impliedDataOnly;
376
			ahlog(AH, 1, "implied data-only restore\n");
377
		}
B
Bruce Momjian 已提交
378
	}
379

380
	/*
B
Bruce Momjian 已提交
381
	 * Setup the output file if necessary.
B
Bruce Momjian 已提交
382
	 */
383
	sav = SaveOutput(AH);
B
Bruce Momjian 已提交
384
	if (ropt->filename || ropt->compression)
385
		SetOutput(AH, ropt->filename, ropt->compression);
B
Bruce Momjian 已提交
386

387
	ahprintf(AH, "--\n-- PostgreSQL database dump\n--\n\n");
B
Bruce Momjian 已提交
388

389 390
	if (AH->public.verbose)
	{
391 392 393 394 395 396
		if (AH->archiveRemoteVersion)
			ahprintf(AH, "-- Dumped from database version %s\n",
					 AH->archiveRemoteVersion);
		if (AH->archiveDumpVersion)
			ahprintf(AH, "-- Dumped by pg_dump version %s\n",
					 AH->archiveDumpVersion);
397
		dumpTimestamp(AH, "Started on", AH->createDate);
398
	}
399

400
	if (ropt->single_txn)
401 402 403 404 405 406
	{
		if (AH->connection)
			StartTransaction(AH);
		else
			ahprintf(AH, "BEGIN;\n\n");
	}
407

408 409 410 411 412
	/*
	 * Establish important parameter values right away.
	 */
	_doSetFixedOutputState(AH);

413 414
	AH->stage = STAGE_PROCESSING;

B
Bruce Momjian 已提交
415 416
	/*
	 * Drop the items at the start, in reverse order
417
	 */
B
Bruce Momjian 已提交
418 419
	if (ropt->dropSchema)
	{
420
		for (te = AH->toc->prev; te != AH->toc; te = te->prev)
B
Bruce Momjian 已提交
421
		{
422 423
			AH->currentTE = te;

424
			/* We want anything that's selected and has a dropStmt */
425
			if (((te->reqs & (REQ_SCHEMA | REQ_DATA)) != 0) && te->dropStmt)
426
			{
427
				ahlog(AH, 1, "dropping %s %s\n", te->desc, te->tag);
428
				/* Select owner and schema as necessary */
429
				_becomeOwner(AH, te);
430
				_selectOutputSchema(AH, te->namespace);
431
				/* Drop it */
432 433 434
				ahprintf(AH, "%s", te->dropStmt);
			}
		}
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449

		/*
		 * _selectOutputSchema may have set currSchema to reflect the effect
		 * of a "SET search_path" command it emitted.  However, by now we may
		 * have dropped that schema; or it might not have existed in the first
		 * place.  In either case the effective value of search_path will not
		 * be what we think.  Forcibly reset currSchema so that we will
		 * re-establish the search_path setting when needed (after creating
		 * the schema).
		 *
		 * If we treated users as pg_dump'able objects then we'd need to reset
		 * currUser here too.
		 */
		if (AH->currSchema)
			free(AH->currSchema);
450
		AH->currSchema = NULL;
B
Bruce Momjian 已提交
451
	}
B
Bruce Momjian 已提交
452

453
	/*
454 455 456
	 * In serial mode, we now process each non-ACL TOC entry.
	 *
	 * In parallel mode, turn control over to the parallel-restore logic.
457
	 */
458
	if (parallel_mode)
459 460
		restore_toc_entries_parallel(AH);
	else
B
Bruce Momjian 已提交
461
	{
462 463 464
		for (te = AH->toc->next; te != AH->toc; te = te->next)
			(void) restore_toc_entry(AH, te, ropt, false);
	}
B
Bruce Momjian 已提交
465

466 467 468
	/*
	 * Scan TOC again to output ownership commands and ACLs
	 */
469
	for (te = AH->toc->next; te != AH->toc; te = te->next)
470
	{
471 472
		AH->currentTE = te;

473
		/* Both schema and data objects might now have ownership/ACLs */
474
		if ((te->reqs & (REQ_SCHEMA | REQ_DATA)) != 0)
475
		{
P
Peter Eisentraut 已提交
476
			ahlog(AH, 1, "setting owner and privileges for %s %s\n",
477
				  te->desc, te->tag);
478 479 480 481
			_printTocEntry(AH, te, ropt, false, true);
		}
	}

482
	if (ropt->single_txn)
483 484 485 486 487 488
	{
		if (AH->connection)
			CommitTransaction(AH);
		else
			ahprintf(AH, "COMMIT;\n\n");
	}
B
Bruce Momjian 已提交
489

490 491 492
	if (AH->public.verbose)
		dumpTimestamp(AH, "Completed on", time(NULL));

493 494
	ahprintf(AH, "--\n-- PostgreSQL database dump complete\n--\n\n");

495
	/*
496
	 * Clean up & we're done.
497
	 */
498 499
	AH->stage = STAGE_FINALIZING;

500
	if (ropt->filename || ropt->compression)
501
		RestoreOutput(AH, sav);
502 503

	if (ropt->useDB)
R
Robert Haas 已提交
504
		DisconnectDatabase(&AH->public);
B
Bruce Momjian 已提交
505 506
}

507 508 509 510 511 512 513 514 515 516 517
/*
 * Restore a single TOC item.  Used in both parallel and non-parallel restore;
 * is_parallel is true if we are in a worker child process.
 *
 * Returns 0 normally, but WORKER_CREATE_DONE or WORKER_INHIBIT_DATA if
 * the parallel parent has to make the corresponding status update.
 */
static int
restore_toc_entry(ArchiveHandle *AH, TocEntry *te,
				  RestoreOptions *ropt, bool is_parallel)
{
518
	int			retval = 0;
519 520 521 522 523 524
	teReqs		reqs;
	bool		defnDumped;

	AH->currentTE = te;

	/* Work out what, if anything, we want from this entry */
525 526 527 528 529 530 531
	if (_tocEntryIsACL(te))
		reqs = 0;				/* ACLs are never restored here */
	else
		reqs = te->reqs;

	/*
	 * Ignore DATABASE entry unless we should create it.  We must check this
532 533
	 * here, not in _tocEntryRequired, because the createDB option should not
	 * affect emitting a DATABASE entry to an archive file.
534 535 536
	 */
	if (!ropt->createDB && strcmp(te->desc, "DATABASE") == 0)
		reqs = 0;
537 538 539 540 541 542 543 544 545 546 547 548

	/* Dump any relevant dump warnings to stderr */
	if (!ropt->suppressDumpWarnings && strcmp(te->desc, "WARNING") == 0)
	{
		if (!ropt->dataOnly && te->defn != NULL && strlen(te->defn) != 0)
			write_msg(modulename, "warning from original dump file: %s\n", te->defn);
		else if (te->copyStmt != NULL && strlen(te->copyStmt) != 0)
			write_msg(modulename, "warning from original dump file: %s\n", te->copyStmt);
	}

	defnDumped = false;

549
	if ((reqs & REQ_SCHEMA) != 0)		/* We want the schema */
550 551 552 553 554 555 556 557 558 559 560
	{
		ahlog(AH, 1, "creating %s %s\n", te->desc, te->tag);

		_printTocEntry(AH, te, ropt, false, false);
		defnDumped = true;

		if (strcmp(te->desc, "TABLE") == 0)
		{
			if (AH->lastErrorTE == te)
			{
				/*
561 562 563
				 * We failed to create the table. If
				 * --no-data-for-failed-tables was given, mark the
				 * corresponding TABLE DATA to be ignored.
564
				 *
565 566
				 * In the parallel case this must be done in the parent, so we
				 * just set the return value.
567 568 569 570 571 572 573 574 575 576 577 578
				 */
				if (ropt->noDataForFailedTables)
				{
					if (is_parallel)
						retval = WORKER_INHIBIT_DATA;
					else
						inhibit_data_for_failed_table(AH, te);
				}
			}
			else
			{
				/*
579 580
				 * We created the table successfully.  Mark the corresponding
				 * TABLE DATA for possible truncation.
581
				 *
582 583
				 * In the parallel case this must be done in the parent, so we
				 * just set the return value.
584 585 586 587 588 589 590 591 592 593 594 595 596
				 */
				if (is_parallel)
					retval = WORKER_CREATE_DONE;
				else
					mark_create_done(AH, te);
			}
		}

		/* If we created a DB, connect to it... */
		if (strcmp(te->desc, "DATABASE") == 0)
		{
			ahlog(AH, 1, "connecting to new database \"%s\"\n", te->tag);
			_reconnectToDB(AH, te->tag);
597
			ropt->dbname = pg_strdup(te->tag);
598 599 600 601 602 603 604 605 606
		}
	}

	/*
	 * If we have a data component, then process it
	 */
	if ((reqs & REQ_DATA) != 0)
	{
		/*
607 608 609
		 * hadDumper will be set if there is genuine data component for this
		 * node. Otherwise, we need to check the defn field for statements
		 * that need to be executed in data-only restores.
610 611 612 613 614 615
		 */
		if (te->hadDumper)
		{
			/*
			 * If we can output the data, then restore it.
			 */
616
			if (AH->PrintTocDataPtr !=NULL)
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
			{
				_printTocEntry(AH, te, ropt, true, false);

				if (strcmp(te->desc, "BLOBS") == 0 ||
					strcmp(te->desc, "BLOB COMMENTS") == 0)
				{
					ahlog(AH, 1, "restoring %s\n", te->desc);

					_selectOutputSchema(AH, "pg_catalog");

					(*AH->PrintTocDataPtr) (AH, te, ropt);
				}
				else
				{
					_disableTriggersIfNecessary(AH, te, ropt);

					/* Select owner and schema as necessary */
					_becomeOwner(AH, te);
					_selectOutputSchema(AH, te->namespace);

					ahlog(AH, 1, "restoring data for table \"%s\"\n",
						  te->tag);

					/*
641 642 643 644 645 646
					 * In parallel restore, if we created the table earlier in
					 * the run then we wrap the COPY in a transaction and
					 * precede it with a TRUNCATE.	If archiving is not on
					 * this prevents WAL-logging the COPY.	This obtains a
					 * speedup similar to that from using single_txn mode in
					 * non-parallel restores.
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
					 */
					if (is_parallel && te->created)
					{
						/*
						 * Parallel restore is always talking directly to a
						 * server, so no need to see if we should issue BEGIN.
						 */
						StartTransaction(AH);

						/*
						 * If the server version is >= 8.4, make sure we issue
						 * TRUNCATE with ONLY so that child tables are not
						 * wiped.
						 */
						ahprintf(AH, "TRUNCATE TABLE %s%s;\n\n",
								 (PQserverVersion(AH->connection) >= 80400 ?
								  "ONLY " : ""),
								 fmtId(te->tag));
					}

					/*
668
					 * If we have a copy statement, use it.
669 670 671 672
					 */
					if (te->copyStmt && strlen(te->copyStmt) > 0)
					{
						ahprintf(AH, "%s", te->copyStmt);
673
						AH->outputKind = OUTPUT_COPYDATA;
674
					}
675 676
					else
						AH->outputKind = OUTPUT_OTHERDATA;
677 678 679

					(*AH->PrintTocDataPtr) (AH, te, ropt);

680 681 682
					/*
					 * Terminate COPY if needed.
					 */
683 684 685 686
					if (AH->outputKind == OUTPUT_COPYDATA &&
						RestoringToDB(AH))
						EndDBCopyMode(AH, te);
					AH->outputKind = OUTPUT_SQLCMDS;
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706

					/* close out the transaction started above */
					if (is_parallel && te->created)
						CommitTransaction(AH);

					_enableTriggersIfNecessary(AH, te, ropt);
				}
			}
		}
		else if (!defnDumped)
		{
			/* If we haven't already dumped the defn part, do so now */
			ahlog(AH, 1, "executing %s %s\n", te->desc, te->tag);
			_printTocEntry(AH, te, ropt, false, false);
		}
	}

	return retval;
}

707 708 709 710
/*
 * Allocate a new RestoreOptions block.
 * This is mainly so we can initialize it, but also for future expansion,
 */
B
Bruce Momjian 已提交
711 712
RestoreOptions *
NewRestoreOptions(void)
B
Bruce Momjian 已提交
713
{
B
Bruce Momjian 已提交
714
	RestoreOptions *opts;
B
Bruce Momjian 已提交
715

716
	opts = (RestoreOptions *) pg_calloc(1, sizeof(RestoreOptions));
B
Bruce Momjian 已提交
717

718
	/* set any fields that shouldn't default to zeroes */
B
Bruce Momjian 已提交
719
	opts->format = archUnknown;
720
	opts->promptPassword = TRI_DEFAULT;
721
	opts->dumpSections = DUMP_UNSECTIONED;
B
Bruce Momjian 已提交
722 723 724 725

	return opts;
}

B
Bruce Momjian 已提交
726 727
static void
_disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
B
Bruce Momjian 已提交
728
{
729 730
	/* This hack is only needed in a data-only restore */
	if (!ropt->dataOnly || !ropt->disable_triggers)
731 732
		return;

733 734
	ahlog(AH, 1, "disabling triggers for %s\n", te->tag);

735
	/*
B
Bruce Momjian 已提交
736
	 * Become superuser if possible, since they are the only ones who can
737 738 739
	 * disable constraint triggers.  If -S was not given, assume the initial
	 * user identity is a superuser.  (XXX would it be better to become the
	 * table owner?)
740
	 */
741
	_becomeUser(AH, ropt->superuser);
742 743

	/*
744
	 * Disable them.
745
	 */
746
	_selectOutputSchema(AH, te->namespace);
747

748 749
	ahprintf(AH, "ALTER TABLE %s DISABLE TRIGGER ALL;\n\n",
			 fmtId(te->tag));
B
Bruce Momjian 已提交
750 751
}

B
Bruce Momjian 已提交
752 753
static void
_enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
B
Bruce Momjian 已提交
754
{
755 756
	/* This hack is only needed in a data-only restore */
	if (!ropt->dataOnly || !ropt->disable_triggers)
757 758
		return;

759 760
	ahlog(AH, 1, "enabling triggers for %s\n", te->tag);

761
	/*
B
Bruce Momjian 已提交
762
	 * Become superuser if possible, since they are the only ones who can
763 764 765
	 * disable constraint triggers.  If -S was not given, assume the initial
	 * user identity is a superuser.  (XXX would it be better to become the
	 * table owner?)
766
	 */
767
	_becomeUser(AH, ropt->superuser);
768 769

	/*
770
	 * Enable them.
771
	 */
772
	_selectOutputSchema(AH, te->namespace);
773

774 775
	ahprintf(AH, "ALTER TABLE %s ENABLE TRIGGER ALL;\n\n",
			 fmtId(te->tag));
776
}
B
Bruce Momjian 已提交
777 778

/*
779
 * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
B
Bruce Momjian 已提交
780 781 782
 */

/* Public */
P
Peter Eisentraut 已提交
783 784
size_t
WriteData(Archive *AHX, const void *data, size_t dLen)
B
Bruce Momjian 已提交
785
{
B
Bruce Momjian 已提交
786
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
B
Bruce Momjian 已提交
787

788
	if (!AH->currToc)
789
		exit_horribly(modulename, "internal error -- WriteData cannot be called outside the context of a DataDumper routine\n");
790

B
Bruce Momjian 已提交
791
	return (*AH->WriteDataPtr) (AH, data, dLen);
B
Bruce Momjian 已提交
792 793 794
}

/*
B
Bruce Momjian 已提交
795
 * Create a new TOC entry. The TOC was designed as a TOC, but is now the
B
Bruce Momjian 已提交
796 797 798 799
 * repository for all metadata. But the name has stuck.
 */

/* Public */
B
Bruce Momjian 已提交
800
void
801 802 803
ArchiveEntry(Archive *AHX,
			 CatalogId catalogId, DumpId dumpId,
			 const char *tag,
804
			 const char *namespace,
B
Bruce Momjian 已提交
805
			 const char *tablespace,
806
			 const char *owner, bool withOids,
807 808
			 const char *desc, teSection section,
			 const char *defn,
809 810
			 const char *dropStmt, const char *copyStmt,
			 const DumpId *deps, int nDeps,
B
Bruce Momjian 已提交
811
			 DataDumperPtr dumpFn, void *dumpArg)
B
Bruce Momjian 已提交
812
{
B
Bruce Momjian 已提交
813 814 815
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
	TocEntry   *newToc;

816
	newToc = (TocEntry *) pg_calloc(1, sizeof(TocEntry));
B
Bruce Momjian 已提交
817

818 819 820 821
	AH->tocCount++;
	if (dumpId > AH->maxDumpId)
		AH->maxDumpId = dumpId;

B
Bruce Momjian 已提交
822 823 824 825 826
	newToc->prev = AH->toc->prev;
	newToc->next = AH->toc;
	AH->toc->prev->next = newToc;
	AH->toc->prev = newToc;

827 828
	newToc->catalogId = catalogId;
	newToc->dumpId = dumpId;
829
	newToc->section = section;
830

831 832 833 834
	newToc->tag = pg_strdup(tag);
	newToc->namespace = namespace ? pg_strdup(namespace) : NULL;
	newToc->tablespace = tablespace ? pg_strdup(tablespace) : NULL;
	newToc->owner = pg_strdup(owner);
835
	newToc->withOids = withOids;
836 837 838 839
	newToc->desc = pg_strdup(desc);
	newToc->defn = pg_strdup(defn);
	newToc->dropStmt = pg_strdup(dropStmt);
	newToc->copyStmt = copyStmt ? pg_strdup(copyStmt) : NULL;
840

841 842
	if (nDeps > 0)
	{
843
		newToc->dependencies = (DumpId *) pg_malloc(nDeps * sizeof(DumpId));
844 845 846 847 848 849 850 851
		memcpy(newToc->dependencies, deps, nDeps * sizeof(DumpId));
		newToc->nDeps = nDeps;
	}
	else
	{
		newToc->dependencies = NULL;
		newToc->nDeps = 0;
	}
852

853 854
	newToc->dataDumper = dumpFn;
	newToc->dataDumperArg = dumpArg;
855
	newToc->hadDumper = dumpFn ? true : false;
B
Bruce Momjian 已提交
856

857
	newToc->formatData = NULL;
B
Bruce Momjian 已提交
858

B
Bruce Momjian 已提交
859
	if (AH->ArchiveEntryPtr !=NULL)
B
Bruce Momjian 已提交
860
		(*AH->ArchiveEntryPtr) (AH, newToc);
B
Bruce Momjian 已提交
861 862 863
}

/* Public */
B
Bruce Momjian 已提交
864 865
void
PrintTOCSummary(Archive *AHX, RestoreOptions *ropt)
B
Bruce Momjian 已提交
866
{
B
Bruce Momjian 已提交
867
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
868
	TocEntry   *te;
869
	teSection	curSection;
B
Bruce Momjian 已提交
870
	OutputContext sav;
871
	const char *fmtName;
B
Bruce Momjian 已提交
872

873
	sav = SaveOutput(AH);
B
Bruce Momjian 已提交
874
	if (ropt->filename)
875
		SetOutput(AH, ropt->filename, 0 /* no compression */ );
B
Bruce Momjian 已提交
876

877 878
	ahprintf(AH, ";\n; Archive created at %s", ctime(&AH->createDate));
	ahprintf(AH, ";     dbname: %s\n;     TOC Entries: %d\n;     Compression: %d\n",
B
Bruce Momjian 已提交
879
			 AH->archdbname, AH->tocCount, AH->compression);
880

B
Bruce Momjian 已提交
881 882
	switch (AH->format)
	{
883 884 885 886 887 888 889 890 891
		case archCustom:
			fmtName = "CUSTOM";
			break;
		case archTar:
			fmtName = "TAR";
			break;
		default:
			fmtName = "UNKNOWN";
	}
892 893

	ahprintf(AH, ";     Dump Version: %d.%d-%d\n", AH->vmaj, AH->vmin, AH->vrev);
894
	ahprintf(AH, ";     Format: %s\n", fmtName);
T
Tom Lane 已提交
895 896
	ahprintf(AH, ";     Integer: %d bytes\n", (int) AH->intSize);
	ahprintf(AH, ";     Offset: %d bytes\n", (int) AH->offSize);
897 898 899 900 901 902
	if (AH->archiveRemoteVersion)
		ahprintf(AH, ";     Dumped from database version: %s\n",
				 AH->archiveRemoteVersion);
	if (AH->archiveDumpVersion)
		ahprintf(AH, ";     Dumped by pg_dump version: %s\n",
				 AH->archiveDumpVersion);
903

904
	ahprintf(AH, ";\n;\n; Selected TOC Entries:\n;\n");
B
Bruce Momjian 已提交
905

906 907 908
	/* We should print DATABASE entries whether or not -C was specified */
	ropt->createDB = 1;

909
	curSection = SECTION_PRE_DATA;
910
	for (te = AH->toc->next; te != AH->toc; te = te->next)
B
Bruce Momjian 已提交
911
	{
912 913 914 915
		if (te->section != SECTION_NONE)
			curSection = te->section;
		if (ropt->verbose ||
			(_tocEntryRequired(te, curSection, ropt) & (REQ_SCHEMA | REQ_DATA)) != 0)
916
			ahprintf(AH, "%d; %u %u %s %s %s %s\n", te->dumpId,
917
					 te->catalogId.tableoid, te->catalogId.oid,
918 919
					 te->desc, te->namespace ? te->namespace : "-",
					 te->tag, te->owner);
920 921
		if (ropt->verbose && te->nDeps > 0)
		{
922
			int			i;
923 924 925 926 927 928

			ahprintf(AH, ";\tdepends on:");
			for (i = 0; i < te->nDeps; i++)
				ahprintf(AH, " %d", te->dependencies[i]);
			ahprintf(AH, "\n");
		}
B
Bruce Momjian 已提交
929
	}
B
Bruce Momjian 已提交
930

B
Bruce Momjian 已提交
931
	if (ropt->filename)
932
		RestoreOutput(AH, sav);
B
Bruce Momjian 已提交
933 934
}

935 936 937 938 939
/***********
 * BLOB Archival
 ***********/

/* Called by a dumper to signal start of a BLOB */
B
Bruce Momjian 已提交
940
int
941
StartBlob(Archive *AHX, Oid oid)
942
{
B
Bruce Momjian 已提交
943
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
944

B
Bruce Momjian 已提交
945
	if (!AH->StartBlobPtr)
946
		exit_horribly(modulename, "large-object output not supported in chosen format\n");
947

B
Bruce Momjian 已提交
948
	(*AH->StartBlobPtr) (AH, AH->currToc, oid);
949

B
Bruce Momjian 已提交
950
	return 1;
951 952 953
}

/* Called by a dumper to signal end of a BLOB */
B
Bruce Momjian 已提交
954
int
955
EndBlob(Archive *AHX, Oid oid)
956
{
B
Bruce Momjian 已提交
957
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
958

B
Bruce Momjian 已提交
959 960
	if (AH->EndBlobPtr)
		(*AH->EndBlobPtr) (AH, AH->currToc, oid);
961

B
Bruce Momjian 已提交
962
	return 1;
963 964 965 966 967 968
}

/**********
 * BLOB Restoration
 **********/

969
/*
B
Bruce Momjian 已提交
970
 * Called by a format handler before any blobs are restored
971
 */
B
Bruce Momjian 已提交
972 973
void
StartRestoreBlobs(ArchiveHandle *AH)
974
{
975 976 977 978 979 980 981
	if (!AH->ropt->single_txn)
	{
		if (AH->connection)
			StartTransaction(AH);
		else
			ahprintf(AH, "BEGIN;\n\n");
	}
982

983 984 985 986
	AH->blobCount = 0;
}

/*
B
Bruce Momjian 已提交
987
 * Called by a format handler after all blobs are restored
988
 */
B
Bruce Momjian 已提交
989 990
void
EndRestoreBlobs(ArchiveHandle *AH)
991
{
992 993 994 995 996 997 998
	if (!AH->ropt->single_txn)
	{
		if (AH->connection)
			CommitTransaction(AH);
		else
			ahprintf(AH, "COMMIT;\n\n");
	}
999

P
Peter Eisentraut 已提交
1000 1001 1002 1003
	ahlog(AH, 1, ngettext("restored %d large object\n",
						  "restored %d large objects\n",
						  AH->blobCount),
		  AH->blobCount);
1004 1005 1006
}


1007 1008 1009
/*
 * Called by a format handler to initiate restoration of a blob
 */
B
Bruce Momjian 已提交
1010
void
1011
StartRestoreBlob(ArchiveHandle *AH, Oid oid, bool drop)
1012
{
1013
	bool		old_blob_style = (AH->version < K_VERS_1_12);
1014
	Oid			loOid;
1015

1016 1017
	AH->blobCount++;

1018 1019 1020
	/* Initialize the LO Buffer */
	AH->lo_buf_used = 0;

1021 1022
	ahlog(AH, 2, "restoring large object with OID %u\n", oid);

1023 1024
	/* With an old archive we must do drop and create logic here */
	if (old_blob_style && drop)
1025
		DropBlobIfExists(AH, oid);
1026

1027
	if (AH->connection)
1028
	{
1029 1030 1031 1032
		if (old_blob_style)
		{
			loOid = lo_create(AH->connection, oid);
			if (loOid == 0 || loOid != oid)
1033 1034
				exit_horribly(modulename, "could not create large object %u: %s",
							  oid, PQerrorMessage(AH->connection));
1035
		}
1036 1037
		AH->loFd = lo_open(AH->connection, oid, INV_WRITE);
		if (AH->loFd == -1)
1038 1039
			exit_horribly(modulename, "could not open large object %u: %s",
						  oid, PQerrorMessage(AH->connection));
1040 1041 1042
	}
	else
	{
1043 1044 1045 1046 1047 1048
		if (old_blob_style)
			ahprintf(AH, "SELECT pg_catalog.lo_open(pg_catalog.lo_create('%u'), %d);\n",
					 oid, INV_WRITE);
		else
			ahprintf(AH, "SELECT pg_catalog.lo_open('%u', %d);\n",
					 oid, INV_WRITE);
1049
	}
1050

B
Bruce Momjian 已提交
1051
	AH->writingBlob = 1;
1052 1053
}

B
Bruce Momjian 已提交
1054
void
1055
EndRestoreBlob(ArchiveHandle *AH, Oid oid)
1056
{
1057 1058 1059
	if (AH->lo_buf_used > 0)
	{
		/* Write remaining bytes from the LO buffer */
1060
		dump_lo_buf(AH);
1061
	}
1062

B
Bruce Momjian 已提交
1063
	AH->writingBlob = 0;
1064

1065
	if (AH->connection)
1066
	{
1067 1068 1069 1070 1071
		lo_close(AH->connection, AH->loFd);
		AH->loFd = -1;
	}
	else
	{
1072
		ahprintf(AH, "SELECT pg_catalog.lo_close(0);\n\n");
1073
	}
1074 1075
}

B
Bruce Momjian 已提交
1076 1077 1078 1079
/***********
 * Sorting and Reordering
 ***********/

B
Bruce Momjian 已提交
1080 1081
void
SortTocFromFile(Archive *AHX, RestoreOptions *ropt)
B
Bruce Momjian 已提交
1082
{
B
Bruce Momjian 已提交
1083 1084
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
	FILE	   *fh;
1085 1086
	char		buf[100];
	bool		incomplete_line;
B
Bruce Momjian 已提交
1087 1088

	/* Allocate space for the 'wanted' array, and init it */
1089
	ropt->idWanted = (bool *) pg_malloc(sizeof(bool) * AH->maxDumpId);
1090
	memset(ropt->idWanted, 0, sizeof(bool) * AH->maxDumpId);
B
Bruce Momjian 已提交
1091

B
Bruce Momjian 已提交
1092 1093 1094
	/* Setup the file */
	fh = fopen(ropt->tocFile, PG_BINARY_R);
	if (!fh)
1095 1096
		exit_horribly(modulename, "could not open TOC file \"%s\": %s\n",
					  ropt->tocFile, strerror(errno));
B
Bruce Momjian 已提交
1097

1098
	incomplete_line = false;
1099
	while (fgets(buf, sizeof(buf), fh) != NULL)
B
Bruce Momjian 已提交
1100
	{
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
		bool		prev_incomplete_line = incomplete_line;
		int			buflen;
		char	   *cmnt;
		char	   *endptr;
		DumpId		id;
		TocEntry   *te;

		/*
		 * Some lines in the file might be longer than sizeof(buf).  This is
		 * no problem, since we only care about the leading numeric ID which
		 * can be at most a few characters; but we have to skip continuation
		 * bufferloads when processing a long line.
		 */
		buflen = strlen(buf);
		if (buflen > 0 && buf[buflen - 1] == '\n')
			incomplete_line = false;
		else
			incomplete_line = true;
		if (prev_incomplete_line)
			continue;

1122
		/* Truncate line at comment, if any */
B
Bruce Momjian 已提交
1123 1124 1125 1126
		cmnt = strchr(buf, ';');
		if (cmnt != NULL)
			cmnt[0] = '\0';

1127
		/* Ignore if all blank */
1128
		if (strspn(buf, " \t\r\n") == strlen(buf))
B
Bruce Momjian 已提交
1129 1130
			continue;

1131
		/* Get an ID, check it's valid and not already seen */
B
Bruce Momjian 已提交
1132
		id = strtol(buf, &endptr, 10);
1133 1134
		if (endptr == buf || id <= 0 || id > AH->maxDumpId ||
			ropt->idWanted[id - 1])
B
Bruce Momjian 已提交
1135
		{
1136
			write_msg(modulename, "WARNING: line ignored: %s\n", buf);
B
Bruce Momjian 已提交
1137 1138
			continue;
		}
B
Bruce Momjian 已提交
1139

B
Bruce Momjian 已提交
1140
		/* Find TOC entry */
1141
		te = getTocEntryByDumpId(AH, id);
B
Bruce Momjian 已提交
1142
		if (!te)
1143 1144
			exit_horribly(modulename, "could not find entry for ID %d\n",
						  id);
B
Bruce Momjian 已提交
1145

1146
		/* Mark it wanted */
1147
		ropt->idWanted[id - 1] = true;
B
Bruce Momjian 已提交
1148

1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
		/*
		 * Move each item to the end of the list as it is selected, so that
		 * they are placed in the desired order.  Any unwanted items will end
		 * up at the front of the list, which may seem unintuitive but it's
		 * what we need.  In an ordinary serial restore that makes no
		 * difference, but in a parallel restore we need to mark unrestored
		 * items' dependencies as satisfied before we start examining
		 * restorable items.  Otherwise they could have surprising
		 * side-effects on the order in which restorable items actually get
		 * restored.
		 */
		_moveBefore(AH, AH->toc, te);
B
Bruce Momjian 已提交
1161
	}
B
Bruce Momjian 已提交
1162

B
Bruce Momjian 已提交
1163
	if (fclose(fh) != 0)
1164 1165
		exit_horribly(modulename, "could not close TOC file: %s\n",
					  strerror(errno));
B
Bruce Momjian 已提交
1166 1167 1168 1169 1170 1171 1172 1173
}

/**********************
 * 'Convenience functions that look like standard IO functions
 * for writing data when in dump mode.
 **********************/

/* Public */
B
Bruce Momjian 已提交
1174 1175 1176 1177
int
archputs(const char *s, Archive *AH)
{
	return WriteData(AH, s, strlen(s));
B
Bruce Momjian 已提交
1178 1179 1180
}

/* Public */
B
Bruce Momjian 已提交
1181 1182
int
archprintf(Archive *AH, const char *fmt,...)
B
Bruce Momjian 已提交
1183
{
B
Bruce Momjian 已提交
1184 1185 1186 1187 1188 1189
	char	   *p = NULL;
	va_list		ap;
	int			bSize = strlen(fmt) + 256;
	int			cnt = -1;

	/*
B
Bruce Momjian 已提交
1190 1191 1192
	 * This is paranoid: deal with the possibility that vsnprintf is willing
	 * to ignore trailing null or returns > 0 even if string does not fit. It
	 * may be the case that it returns cnt = bufsize
B
Bruce Momjian 已提交
1193 1194
	 */
	while (cnt < 0 || cnt >= (bSize - 1))
B
Bruce Momjian 已提交
1195
	{
B
Bruce Momjian 已提交
1196 1197
		if (p != NULL)
			free(p);
1198
		bSize *= 2;
1199
		p = (char *) pg_malloc(bSize);
1200 1201 1202
		va_start(ap, fmt);
		cnt = vsnprintf(p, bSize, fmt, ap);
		va_end(ap);
B
Bruce Momjian 已提交
1203 1204 1205 1206
	}
	WriteData(AH, p, cnt);
	free(p);
	return cnt;
B
Bruce Momjian 已提交
1207 1208 1209 1210 1211 1212 1213
}


/*******************************
 * Stuff below here should be 'private' to the archiver routines
 *******************************/

1214
static void
1215
SetOutput(ArchiveHandle *AH, const char *filename, int compression)
B
Bruce Momjian 已提交
1216
{
1217
	int			fn;
B
Bruce Momjian 已提交
1218 1219

	if (filename)
1220
		fn = -1;
B
Bruce Momjian 已提交
1221 1222 1223 1224
	else if (AH->FH)
		fn = fileno(AH->FH);
	else if (AH->fSpec)
	{
1225
		fn = -1;
B
Bruce Momjian 已提交
1226 1227 1228 1229 1230 1231
		filename = AH->fSpec;
	}
	else
		fn = fileno(stdout);

	/* If compression explicitly requested, use gzopen */
1232
#ifdef HAVE_LIBZ
B
Bruce Momjian 已提交
1233 1234
	if (compression != 0)
	{
1235 1236 1237
		char		fmode[10];

		/* Don't use PG_BINARY_x since this is zlib */
1238
		sprintf(fmode, "wb%d", compression);
1239 1240
		if (fn >= 0)
			AH->OF = gzdopen(dup(fn), fmode);
B
Bruce Momjian 已提交
1241 1242
		else
			AH->OF = gzopen(filename, fmode);
1243
		AH->gzOut = 1;
B
Bruce Momjian 已提交
1244 1245
	}
	else
B
Bruce Momjian 已提交
1246
#endif
1247
	{							/* Use fopen */
1248 1249 1250 1251 1252 1253 1254
		if (AH->mode == archModeAppend)
		{
			if (fn >= 0)
				AH->OF = fdopen(dup(fn), PG_BINARY_A);
			else
				AH->OF = fopen(filename, PG_BINARY_A);
		}
B
Bruce Momjian 已提交
1255
		else
1256 1257 1258 1259 1260 1261
		{
			if (fn >= 0)
				AH->OF = fdopen(dup(fn), PG_BINARY_W);
			else
				AH->OF = fopen(filename, PG_BINARY_W);
		}
1262
		AH->gzOut = 0;
B
Bruce Momjian 已提交
1263
	}
B
Bruce Momjian 已提交
1264

1265
	if (!AH->OF)
1266 1267
	{
		if (filename)
1268 1269
			exit_horribly(modulename, "could not open output file \"%s\": %s\n",
						  filename, strerror(errno));
1270
		else
1271 1272
			exit_horribly(modulename, "could not open output file: %s\n",
						  strerror(errno));
1273
	}
1274 1275 1276 1277 1278 1279 1280 1281 1282
}

static OutputContext
SaveOutput(ArchiveHandle *AH)
{
	OutputContext sav;

	sav.OF = AH->OF;
	sav.gzOut = AH->gzOut;
1283

B
Bruce Momjian 已提交
1284
	return sav;
B
Bruce Momjian 已提交
1285 1286
}

1287
static void
1288
RestoreOutput(ArchiveHandle *AH, OutputContext savedContext)
B
Bruce Momjian 已提交
1289
{
B
Bruce Momjian 已提交
1290
	int			res;
1291

B
Bruce Momjian 已提交
1292
	if (AH->gzOut)
1293
		res = GZCLOSE(AH->OF);
B
Bruce Momjian 已提交
1294
	else
1295 1296 1297
		res = fclose(AH->OF);

	if (res != 0)
1298
		exit_horribly(modulename, "could not close output file: %s\n",
1299
					  strerror(errno));
B
Bruce Momjian 已提交
1300

1301 1302
	AH->gzOut = savedContext.gzOut;
	AH->OF = savedContext.OF;
B
Bruce Momjian 已提交
1303 1304 1305 1306 1307
}



/*
B
Bruce Momjian 已提交
1308
 *	Print formatted text to the output file (usually stdout).
B
Bruce Momjian 已提交
1309
 */
B
Bruce Momjian 已提交
1310 1311
int
ahprintf(ArchiveHandle *AH, const char *fmt,...)
B
Bruce Momjian 已提交
1312
{
B
Bruce Momjian 已提交
1313 1314
	char	   *p = NULL;
	va_list		ap;
1315
	int			bSize = strlen(fmt) + 256;		/* Usually enough */
B
Bruce Momjian 已提交
1316 1317 1318
	int			cnt = -1;

	/*
B
Bruce Momjian 已提交
1319
	 * This is paranoid: deal with the possibility that vsnprintf is willing
1320 1321
	 * to ignore trailing null or returns > 0 even if string does not fit. It
	 * may be the case that it returns cnt = bufsize.
B
Bruce Momjian 已提交
1322 1323
	 */
	while (cnt < 0 || cnt >= (bSize - 1))
1324
	{
B
Bruce Momjian 已提交
1325 1326
		if (p != NULL)
			free(p);
1327
		bSize *= 2;
1328
		p = (char *) pg_malloc(bSize);
1329
		va_start(ap, fmt);
1330
		cnt = vsnprintf(p, bSize, fmt, ap);
1331
		va_end(ap);
B
Bruce Momjian 已提交
1332 1333 1334 1335
	}
	ahwrite(p, 1, cnt, AH);
	free(p);
	return cnt;
B
Bruce Momjian 已提交
1336 1337
}

B
Bruce Momjian 已提交
1338 1339
void
ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
1340 1341 1342 1343 1344 1345 1346
{
	va_list		ap;

	if (AH->debugLevel < level && (!AH->public.verbose || level > 1))
		return;

	va_start(ap, fmt);
T
Tom Lane 已提交
1347
	vwrite_msg(NULL, fmt, ap);
1348 1349 1350
	va_end(ap);
}

1351 1352 1353
/*
 * Single place for logic which says 'We are restoring to a direct DB connection'.
 */
1354
static int
B
Bruce Momjian 已提交
1355
RestoringToDB(ArchiveHandle *AH)
1356 1357 1358 1359
{
	return (AH->ropt && AH->ropt->useDB && AH->connection);
}

1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
/*
 * Dump the current contents of the LO data buffer while writing a BLOB
 */
static void
dump_lo_buf(ArchiveHandle *AH)
{
	if (AH->connection)
	{
		size_t		res;

		res = lo_write(AH->connection, AH->loFd, AH->lo_buf, AH->lo_buf_used);
P
Peter Eisentraut 已提交
1371
		ahlog(AH, 5, ngettext("wrote %lu byte of large object data (result = %lu)\n",
1372
					 "wrote %lu bytes of large object data (result = %lu)\n",
P
Peter Eisentraut 已提交
1373
							  AH->lo_buf_used),
1374 1375
			  (unsigned long) AH->lo_buf_used, (unsigned long) res);
		if (res != AH->lo_buf_used)
1376
			exit_horribly(modulename,
B
Bruce Momjian 已提交
1377 1378
			"could not write to large object (result: %lu, expected: %lu)\n",
					   (unsigned long) res, (unsigned long) AH->lo_buf_used);
1379 1380 1381
	}
	else
	{
1382
		PQExpBuffer buf = createPQExpBuffer();
1383

1384 1385 1386 1387
		appendByteaLiteralAHX(buf,
							  (const unsigned char *) AH->lo_buf,
							  AH->lo_buf_used,
							  AH);
1388 1389 1390

		/* Hack: turn off writingBlob so ahwrite doesn't recurse to here */
		AH->writingBlob = 0;
1391
		ahprintf(AH, "SELECT pg_catalog.lowrite(0, %s);\n", buf->data);
1392 1393
		AH->writingBlob = 1;

1394
		destroyPQExpBuffer(buf);
1395 1396 1397 1398 1399
	}
	AH->lo_buf_used = 0;
}


B
Bruce Momjian 已提交
1400
/*
1401
 *	Write buffer to the output file (usually stdout). This is used for
B
Bruce Momjian 已提交
1402 1403
 *	outputting 'restore' scripts etc. It is even possible for an archive
 *	format to create a custom output routine to 'fake' a restore if it
1404
 *	wants to generate a script (see TAR output).
B
Bruce Momjian 已提交
1405
 */
B
Bruce Momjian 已提交
1406 1407
int
ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
B
Bruce Momjian 已提交
1408
{
P
Peter Eisentraut 已提交
1409
	size_t		res;
1410

B
Bruce Momjian 已提交
1411
	if (AH->writingBlob)
1412
	{
B
Bruce Momjian 已提交
1413
		size_t		remaining = size * nmemb;
1414 1415

		while (AH->lo_buf_used + remaining > AH->lo_buf_size)
P
Peter Eisentraut 已提交
1416
		{
1417 1418 1419 1420 1421 1422 1423
			size_t		avail = AH->lo_buf_size - AH->lo_buf_used;

			memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, avail);
			ptr = (const void *) ((const char *) ptr + avail);
			remaining -= avail;
			AH->lo_buf_used += avail;
			dump_lo_buf(AH);
P
Peter Eisentraut 已提交
1424 1425
		}

1426 1427 1428
		memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, remaining);
		AH->lo_buf_used += remaining;

P
Peter Eisentraut 已提交
1429
		return size * nmemb;
1430
	}
B
Bruce Momjian 已提交
1431
	else if (AH->gzOut)
1432
	{
1433
		res = GZWRITE(ptr, size, nmemb, AH->OF);
1434
		if (res != (nmemb * size))
1435
			exit_horribly(modulename, "could not write to output file: %s\n", strerror(errno));
1436 1437
		return res;
	}
B
Bruce Momjian 已提交
1438
	else if (AH->CustomOutPtr)
1439
	{
B
Bruce Momjian 已提交
1440 1441
		res = AH->CustomOutPtr (AH, ptr, size * nmemb);

1442
		if (res != (nmemb * size))
1443
			exit_horribly(modulename, "could not write to custom output routine\n");
1444 1445
		return res;
	}
1446 1447 1448
	else
	{
		/*
B
Bruce Momjian 已提交
1449 1450 1451
		 * If we're doing a restore, and it's direct to DB, and we're
		 * connected then send it to the DB.
		 */
1452
		if (RestoringToDB(AH))
1453
			return ExecuteSqlCommandBuf(AH, (const char *) ptr, size * nmemb);
1454
		else
1455
		{
1456
			res = fwrite(ptr, size, nmemb, AH->OF);
1457
			if (res != nmemb)
1458
				exit_horribly(modulename, "could not write to output file: %s\n",
1459
							  strerror(errno));
1460 1461
			return res;
		}
1462
	}
B
Bruce Momjian 已提交
1463
}
1464

1465 1466
/* on some error, we may decide to go on... */
void
1467
warn_or_exit_horribly(ArchiveHandle *AH,
1468
					  const char *modulename, const char *fmt,...)
1469
{
B
Bruce Momjian 已提交
1470
	va_list		ap;
1471

B
Bruce Momjian 已提交
1472 1473
	switch (AH->stage)
	{
1474 1475 1476 1477 1478 1479

		case STAGE_NONE:
			/* Do nothing special */
			break;

		case STAGE_INITIALIZING:
B
Bruce Momjian 已提交
1480
			if (AH->stage != AH->lastErrorStage)
1481 1482 1483 1484
				write_msg(modulename, "Error while INITIALIZING:\n");
			break;

		case STAGE_PROCESSING:
B
Bruce Momjian 已提交
1485
			if (AH->stage != AH->lastErrorStage)
1486 1487 1488 1489
				write_msg(modulename, "Error while PROCESSING TOC:\n");
			break;

		case STAGE_FINALIZING:
B
Bruce Momjian 已提交
1490
			if (AH->stage != AH->lastErrorStage)
1491 1492 1493
				write_msg(modulename, "Error while FINALIZING:\n");
			break;
	}
B
Bruce Momjian 已提交
1494 1495
	if (AH->currentTE != NULL && AH->currentTE != AH->lastErrorTE)
	{
1496 1497
		write_msg(modulename, "Error from TOC entry %d; %u %u %s %s %s\n",
				  AH->currentTE->dumpId,
B
Bruce Momjian 已提交
1498 1499
			 AH->currentTE->catalogId.tableoid, AH->currentTE->catalogId.oid,
			  AH->currentTE->desc, AH->currentTE->tag, AH->currentTE->owner);
1500 1501 1502 1503
	}
	AH->lastErrorStage = AH->stage;
	AH->lastErrorTE = AH->currentTE;

1504
	va_start(ap, fmt);
1505 1506 1507
	vwrite_msg(modulename, fmt, ap);
	va_end(ap);

1508
	if (AH->public.exit_on_error)
1509
		exit_nicely(1);
1510 1511 1512
	else
		AH->public.n_errors++;
}
1513

1514 1515
#ifdef NOT_USED

B
Bruce Momjian 已提交
1516 1517
static void
_moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
B
Bruce Momjian 已提交
1518
{
1519
	/* Unlink te from list */
B
Bruce Momjian 已提交
1520 1521
	te->prev->next = te->next;
	te->next->prev = te->prev;
B
Bruce Momjian 已提交
1522

1523
	/* and insert it after "pos" */
B
Bruce Momjian 已提交
1524 1525 1526 1527
	te->prev = pos;
	te->next = pos->next;
	pos->next->prev = te;
	pos->next = te;
B
Bruce Momjian 已提交
1528
}
1529
#endif
1530

B
Bruce Momjian 已提交
1531 1532
static void
_moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
B
Bruce Momjian 已提交
1533
{
1534
	/* Unlink te from list */
B
Bruce Momjian 已提交
1535 1536
	te->prev->next = te->next;
	te->next->prev = te->prev;
B
Bruce Momjian 已提交
1537

1538
	/* and insert it before "pos" */
B
Bruce Momjian 已提交
1539 1540 1541 1542
	te->prev = pos->prev;
	te->next = pos;
	pos->prev->next = te;
	pos->prev = te;
B
Bruce Momjian 已提交
1543
}
1544

1545 1546 1547 1548 1549 1550 1551
/*
 * Build index arrays for the TOC list
 *
 * This should be invoked only after we have created or read in all the TOC
 * items.
 *
 * The arrays are indexed by dump ID (so entry zero is unused).  Note that the
1552
 * array entries run only up to maxDumpId.	We might see dependency dump IDs
1553 1554 1555 1556 1557
 * beyond that (if the dump was partial); so always check the array bound
 * before trying to touch an array entry.
 */
static void
buildTocEntryArrays(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1558
{
1559
	DumpId		maxDumpId = AH->maxDumpId;
B
Bruce Momjian 已提交
1560 1561
	TocEntry   *te;

1562 1563 1564
	AH->tocsByDumpId = (TocEntry **) pg_calloc(maxDumpId + 1, sizeof(TocEntry *));
	AH->tableDataId = (DumpId *) pg_calloc(maxDumpId + 1, sizeof(DumpId));

1565
	for (te = AH->toc->next; te != AH->toc; te = te->next)
B
Bruce Momjian 已提交
1566
	{
1567 1568
		/* this check is purely paranoia, maxDumpId should be correct */
		if (te->dumpId <= 0 || te->dumpId > maxDumpId)
1569
			exit_horribly(modulename, "bad dumpId\n");
1570 1571 1572 1573 1574 1575

		/* tocsByDumpId indexes all TOCs by their dump ID */
		AH->tocsByDumpId[te->dumpId] = te;

		/*
		 * tableDataId provides the TABLE DATA item's dump ID for each TABLE
1576
		 * TOC entry that has a DATA item.	We compute this by reversing the
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
		 * TABLE DATA item's dependency, knowing that a TABLE DATA item has
		 * just one dependency and it is the TABLE item.
		 */
		if (strcmp(te->desc, "TABLE DATA") == 0 && te->nDeps > 0)
		{
			DumpId		tableId = te->dependencies[0];

			/*
			 * The TABLE item might not have been in the archive, if this was
			 * a data-only dump; but its dump ID should be less than its data
			 * item's dump ID, so there should be a place for it in the array.
			 */
			if (tableId <= 0 || tableId > maxDumpId)
1590
				exit_horribly(modulename, "bad table dumpId for TABLE DATA item\n");
1591 1592 1593

			AH->tableDataId[tableId] = te->dumpId;
		}
B
Bruce Momjian 已提交
1594
	}
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
}

static TocEntry *
getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
{
	/* build index arrays if we didn't already */
	if (AH->tocsByDumpId == NULL)
		buildTocEntryArrays(AH);

	if (id > 0 && id <= AH->maxDumpId)
		return AH->tocsByDumpId[id];

B
Bruce Momjian 已提交
1607
	return NULL;
B
Bruce Momjian 已提交
1608 1609
}

1610
teReqs
1611
TocIDRequired(ArchiveHandle *AH, DumpId id)
B
Bruce Momjian 已提交
1612
{
1613
	TocEntry   *te = getTocEntryByDumpId(AH, id);
B
Bruce Momjian 已提交
1614

B
Bruce Momjian 已提交
1615 1616
	if (!te)
		return 0;
B
Bruce Momjian 已提交
1617

1618
	return te->reqs;
B
Bruce Momjian 已提交
1619 1620
}

1621
size_t
1622
WriteOffset(ArchiveHandle *AH, pgoff_t o, int wasSet)
1623
{
B
Bruce Momjian 已提交
1624
	int			off;
1625 1626 1627 1628

	/* Save the flag */
	(*AH->WriteBytePtr) (AH, wasSet);

1629 1630
	/* Write out pgoff_t smallest byte first, prevents endian mismatch */
	for (off = 0; off < sizeof(pgoff_t); off++)
1631
	{
B
Bruce Momjian 已提交
1632
		(*AH->WriteBytePtr) (AH, o & 0xFF);
1633 1634
		o >>= 8;
	}
1635
	return sizeof(pgoff_t) + 1;
1636 1637 1638
}

int
B
Bruce Momjian 已提交
1639
ReadOffset(ArchiveHandle *AH, pgoff_t * o)
1640
{
B
Bruce Momjian 已提交
1641 1642 1643
	int			i;
	int			off;
	int			offsetFlg;
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654

	/* Initialize to zero */
	*o = 0;

	/* Check for old version */
	if (AH->version < K_VERS_1_7)
	{
		/* Prior versions wrote offsets using WriteInt */
		i = ReadInt(AH);
		/* -1 means not set */
		if (i < 0)
B
Bruce Momjian 已提交
1655
			return K_OFFSET_POS_NOT_SET;
1656
		else if (i == 0)
B
Bruce Momjian 已提交
1657
			return K_OFFSET_NO_DATA;
1658

1659 1660
		/* Cast to pgoff_t because it was written as an int. */
		*o = (pgoff_t) i;
1661 1662 1663 1664
		return K_OFFSET_POS_SET;
	}

	/*
B
Bruce Momjian 已提交
1665 1666
	 * Read the flag indicating the state of the data pointer. Check if valid
	 * and die if not.
1667
	 *
1668 1669
	 * This used to be handled by a negative or zero pointer, now we use an
	 * extra byte specifically for the state.
1670 1671 1672 1673 1674 1675 1676 1677 1678
	 */
	offsetFlg = (*AH->ReadBytePtr) (AH) & 0xFF;

	switch (offsetFlg)
	{
		case K_OFFSET_POS_NOT_SET:
		case K_OFFSET_NO_DATA:
		case K_OFFSET_POS_SET:

B
Bruce Momjian 已提交
1679
			break;
1680 1681

		default:
1682
			exit_horribly(modulename, "unexpected data offset flag %d\n", offsetFlg);
1683 1684 1685 1686 1687 1688 1689
	}

	/*
	 * Read the bytes
	 */
	for (off = 0; off < AH->offSize; off++)
	{
1690 1691
		if (off < sizeof(pgoff_t))
			*o |= ((pgoff_t) ((*AH->ReadBytePtr) (AH))) << (off * 8);
1692 1693 1694
		else
		{
			if ((*AH->ReadBytePtr) (AH) != 0)
1695
				exit_horribly(modulename, "file offset in dump file is too large\n");
1696 1697 1698 1699 1700 1701
		}
	}

	return offsetFlg;
}

P
Peter Eisentraut 已提交
1702
size_t
B
Bruce Momjian 已提交
1703
WriteInt(ArchiveHandle *AH, int i)
B
Bruce Momjian 已提交
1704
{
B
Bruce Momjian 已提交
1705 1706 1707
	int			b;

	/*
B
Bruce Momjian 已提交
1708 1709 1710 1711 1712
	 * This is a bit yucky, but I don't want to make the binary format very
	 * dependent on representation, and not knowing much about it, I write out
	 * a sign byte. If you change this, don't forget to change the file
	 * version #, and modify readInt to read the new format AS WELL AS the old
	 * formats.
B
Bruce Momjian 已提交
1713 1714 1715 1716 1717 1718
	 */

	/* SIGN byte */
	if (i < 0)
	{
		(*AH->WriteBytePtr) (AH, 1);
1719
		i = -i;
B
Bruce Momjian 已提交
1720 1721 1722 1723 1724 1725 1726
	}
	else
		(*AH->WriteBytePtr) (AH, 0);

	for (b = 0; b < AH->intSize; b++)
	{
		(*AH->WriteBytePtr) (AH, i & 0xFF);
1727
		i >>= 8;
B
Bruce Momjian 已提交
1728 1729 1730
	}

	return AH->intSize + 1;
B
Bruce Momjian 已提交
1731 1732
}

B
Bruce Momjian 已提交
1733 1734
int
ReadInt(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1735
{
B
Bruce Momjian 已提交
1736 1737 1738 1739 1740
	int			res = 0;
	int			bv,
				b;
	int			sign = 0;		/* Default positive */
	int			bitShift = 0;
B
Bruce Momjian 已提交
1741

B
Bruce Momjian 已提交
1742
	if (AH->version > K_VERS_1_0)
1743
		/* Read a sign byte */
B
Bruce Momjian 已提交
1744
		sign = (*AH->ReadBytePtr) (AH);
B
Bruce Momjian 已提交
1745

B
Bruce Momjian 已提交
1746 1747 1748
	for (b = 0; b < AH->intSize; b++)
	{
		bv = (*AH->ReadBytePtr) (AH) & 0xFF;
1749 1750 1751
		if (bv != 0)
			res = res + (bv << bitShift);
		bitShift += 8;
B
Bruce Momjian 已提交
1752
	}
B
Bruce Momjian 已提交
1753

B
Bruce Momjian 已提交
1754 1755
	if (sign)
		res = -res;
B
Bruce Momjian 已提交
1756

B
Bruce Momjian 已提交
1757
	return res;
B
Bruce Momjian 已提交
1758 1759
}

P
Peter Eisentraut 已提交
1760
size_t
1761
WriteStr(ArchiveHandle *AH, const char *c)
B
Bruce Momjian 已提交
1762
{
P
Peter Eisentraut 已提交
1763
	size_t		res;
1764 1765 1766 1767

	if (c)
	{
		res = WriteInt(AH, strlen(c));
B
Bruce Momjian 已提交
1768
		res += (*AH->WriteBufPtr) (AH, c, strlen(c));
1769 1770 1771 1772
	}
	else
		res = WriteInt(AH, -1);

B
Bruce Momjian 已提交
1773
	return res;
B
Bruce Momjian 已提交
1774 1775
}

B
Bruce Momjian 已提交
1776 1777
char *
ReadStr(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1778
{
B
Bruce Momjian 已提交
1779 1780
	char	   *buf;
	int			l;
B
Bruce Momjian 已提交
1781

B
Bruce Momjian 已提交
1782
	l = ReadInt(AH);
1783
	if (l < 0)
1784 1785 1786
		buf = NULL;
	else
	{
1787
		buf = (char *) pg_malloc(l + 1);
1788
		if ((*AH->ReadBufPtr) (AH, (void *) buf, l) != l)
1789
			exit_horribly(modulename, "unexpected end of file\n");
1790

1791 1792
		buf[l] = '\0';
	}
B
Bruce Momjian 已提交
1793

B
Bruce Momjian 已提交
1794
	return buf;
B
Bruce Momjian 已提交
1795 1796
}

T
Tom Lane 已提交
1797
static int
B
Bruce Momjian 已提交
1798
_discoverArchiveFormat(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1799
{
B
Bruce Momjian 已提交
1800 1801
	FILE	   *fh;
	char		sig[6];			/* More than enough */
P
Peter Eisentraut 已提交
1802
	size_t		cnt;
B
Bruce Momjian 已提交
1803
	int			wantClose = 0;
B
Bruce Momjian 已提交
1804

1805
#if 0
1806
	write_msg(modulename, "attempting to ascertain archive format\n");
1807
#endif
1808 1809 1810 1811 1812

	if (AH->lookahead)
		free(AH->lookahead);

	AH->lookaheadSize = 512;
1813
	AH->lookahead = pg_calloc(1, 512);
1814 1815
	AH->lookaheadLen = 0;
	AH->lookaheadPos = 0;
1816

B
Bruce Momjian 已提交
1817 1818
	if (AH->fSpec)
	{
1819
		struct stat st;
1820

1821
		wantClose = 1;
1822 1823 1824 1825 1826 1827 1828 1829

		/*
		 * Check if the specified archive is a directory. If so, check if
		 * there's a "toc.dat" (or "toc.dat.gz") file in it.
		 */
		if (stat(AH->fSpec, &st) == 0 && S_ISDIR(st.st_mode))
		{
			char		buf[MAXPGPATH];
1830

1831
			if (snprintf(buf, MAXPGPATH, "%s/toc.dat", AH->fSpec) >= MAXPGPATH)
1832 1833
				exit_horribly(modulename, "directory name too long: \"%s\"\n",
							  AH->fSpec);
1834 1835 1836 1837 1838 1839 1840 1841
			if (stat(buf, &st) == 0 && S_ISREG(st.st_mode))
			{
				AH->format = archDirectory;
				return AH->format;
			}

#ifdef HAVE_LIBZ
			if (snprintf(buf, MAXPGPATH, "%s/toc.dat.gz", AH->fSpec) >= MAXPGPATH)
1842 1843
				exit_horribly(modulename, "directory name too long: \"%s\"\n",
							  AH->fSpec);
1844 1845 1846 1847 1848 1849
			if (stat(buf, &st) == 0 && S_ISREG(st.st_mode))
			{
				AH->format = archDirectory;
				return AH->format;
			}
#endif
1850 1851
			exit_horribly(modulename, "directory \"%s\" does not appear to be a valid archive (\"toc.dat\" does not exist)\n",
						  AH->fSpec);
1852
			fh = NULL;			/* keep compiler quiet */
1853 1854 1855 1856 1857
		}
		else
		{
			fh = fopen(AH->fSpec, PG_BINARY_R);
			if (!fh)
1858 1859
				exit_horribly(modulename, "could not open input file \"%s\": %s\n",
							  AH->fSpec, strerror(errno));
1860
		}
B
Bruce Momjian 已提交
1861 1862
	}
	else
1863
	{
1864
		fh = stdin;
1865
		if (!fh)
1866 1867
			exit_horribly(modulename, "could not open input file: %s\n",
						  strerror(errno));
1868
	}
B
Bruce Momjian 已提交
1869

B
Bruce Momjian 已提交
1870
	cnt = fread(sig, 1, 5, fh);
B
Bruce Momjian 已提交
1871

B
Bruce Momjian 已提交
1872
	if (cnt != 5)
1873 1874
	{
		if (ferror(fh))
1875
			exit_horribly(modulename, "could not read input file: %s\n", strerror(errno));
1876
		else
1877 1878
			exit_horribly(modulename, "input file is too short (read %lu, expected 5)\n",
						  (unsigned long) cnt);
1879
	}
B
Bruce Momjian 已提交
1880

B
Bruce Momjian 已提交
1881
	/* Save it, just in case we need it later */
1882 1883
	strncpy(&AH->lookahead[0], sig, 5);
	AH->lookaheadLen = 5;
B
Bruce Momjian 已提交
1884

B
Bruce Momjian 已提交
1885
	if (strncmp(sig, "PGDMP", 5) == 0)
1886
	{
1887 1888 1889 1890 1891
		/*
		 * Finish reading (most of) a custom-format header.
		 *
		 * NB: this code must agree with ReadHead().
		 */
1892 1893 1894 1895 1896 1897 1898 1899
		AH->vmaj = fgetc(fh);
		AH->vmin = fgetc(fh);

		/* Save these too... */
		AH->lookahead[AH->lookaheadLen++] = AH->vmaj;
		AH->lookahead[AH->lookaheadLen++] = AH->vmin;

		/* Check header version; varies from V1.0 */
B
Bruce Momjian 已提交
1900 1901
		if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0)))		/* Version > 1.0 */
		{
1902 1903 1904 1905 1906 1907
			AH->vrev = fgetc(fh);
			AH->lookahead[AH->lookaheadLen++] = AH->vrev;
		}
		else
			AH->vrev = 0;

1908 1909 1910
		/* Make a convenient integer <maj><min><rev>00 */
		AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;

1911 1912 1913
		AH->intSize = fgetc(fh);
		AH->lookahead[AH->lookaheadLen++] = AH->intSize;

1914 1915 1916 1917 1918 1919 1920 1921
		if (AH->version >= K_VERS_1_7)
		{
			AH->offSize = fgetc(fh);
			AH->lookahead[AH->lookaheadLen++] = AH->offSize;
		}
		else
			AH->offSize = AH->intSize;

1922 1923
		AH->format = fgetc(fh);
		AH->lookahead[AH->lookaheadLen++] = AH->format;
B
Bruce Momjian 已提交
1924 1925 1926
	}
	else
	{
1927
		/*
1928 1929
		 * *Maybe* we have a tar archive format file or a text dump ... So,
		 * read first 512 byte header...
1930 1931 1932
		 */
		cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
		AH->lookaheadLen += cnt;
B
Bruce Momjian 已提交
1933

1934 1935 1936 1937
		if (AH->lookaheadLen >= strlen(TEXT_DUMPALL_HEADER) &&
			(strncmp(AH->lookahead, TEXT_DUMP_HEADER, strlen(TEXT_DUMP_HEADER)) == 0 ||
			 strncmp(AH->lookahead, TEXT_DUMPALL_HEADER, strlen(TEXT_DUMPALL_HEADER)) == 0))
		{
1938 1939 1940 1941
			/*
			 * looks like it's probably a text format dump. so suggest they
			 * try psql
			 */
1942
			exit_horribly(modulename, "input file appears to be a text format dump. Please use psql.\n");
1943 1944
		}

1945
		if (AH->lookaheadLen != 512)
1946
			exit_horribly(modulename, "input file does not appear to be a valid archive (too short?)\n");
B
Bruce Momjian 已提交
1947

1948
		if (!isValidTarHeader(AH->lookahead))
1949
			exit_horribly(modulename, "input file does not appear to be a valid archive\n");
B
Bruce Momjian 已提交
1950

1951 1952
		AH->format = archTar;
	}
B
Bruce Momjian 已提交
1953

B
Bruce Momjian 已提交
1954
	/* If we can't seek, then mark the header as read */
P
Peter Eisentraut 已提交
1955
	if (fseeko(fh, 0, SEEK_SET) != 0)
1956 1957
	{
		/*
B
Bruce Momjian 已提交
1958 1959
		 * NOTE: Formats that use the lookahead buffer can unset this in their
		 * Init routine.
1960 1961 1962 1963
		 */
		AH->readHeader = 1;
	}
	else
B
Bruce Momjian 已提交
1964
		AH->lookaheadLen = 0;	/* Don't bother since we've reset the file */
1965

B
Bruce Momjian 已提交
1966 1967
	/* Close the file */
	if (wantClose)
1968
		if (fclose(fh) != 0)
1969 1970
			exit_horribly(modulename, "could not close input file: %s\n",
						  strerror(errno));
B
Bruce Momjian 已提交
1971

B
Bruce Momjian 已提交
1972
	return AH->format;
B
Bruce Momjian 已提交
1973 1974 1975 1976 1977 1978
}


/*
 * Allocate an archive handle
 */
B
Bruce Momjian 已提交
1979 1980 1981
static ArchiveHandle *
_allocAH(const char *FileSpec, const ArchiveFormat fmt,
		 const int compression, ArchiveMode mode)
1982
{
B
Bruce Momjian 已提交
1983
	ArchiveHandle *AH;
B
Bruce Momjian 已提交
1984

1985
#if 0
1986
	write_msg(modulename, "allocating AH for %s, format %d\n", FileSpec, fmt);
1987
#endif
1988

1989
	AH = (ArchiveHandle *) pg_calloc(1, sizeof(ArchiveHandle));
B
Bruce Momjian 已提交
1990

1991 1992
	/* AH->debugLevel = 100; */

B
Bruce Momjian 已提交
1993 1994
	AH->vmaj = K_VERS_MAJOR;
	AH->vmin = K_VERS_MINOR;
1995
	AH->vrev = K_VERS_REV;
B
Bruce Momjian 已提交
1996

1997 1998 1999
	/* Make a convenient integer <maj><min><rev>00 */
	AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;

2000
	/* initialize for backwards compatible string processing */
2001
	AH->public.encoding = 0;	/* PG_SQL_ASCII */
2002 2003 2004 2005 2006 2007
	AH->public.std_strings = false;

	/* sql error handling */
	AH->public.exit_on_error = true;
	AH->public.n_errors = 0;

2008 2009
	AH->archiveDumpVersion = PG_VERSION;

2010 2011
	AH->createDate = time(NULL);

B
Bruce Momjian 已提交
2012
	AH->intSize = sizeof(int);
2013
	AH->offSize = sizeof(pgoff_t);
B
Bruce Momjian 已提交
2014 2015
	if (FileSpec)
	{
2016
		AH->fSpec = pg_strdup(FileSpec);
B
Bruce Momjian 已提交
2017

2018 2019 2020
		/*
		 * Not used; maybe later....
		 *
2021
		 * AH->workDir = pg_strdup(FileSpec); for(i=strlen(FileSpec) ; i > 0 ;
2022
		 * i--) if (AH->workDir[i-1] == '/')
2023
		 */
B
Bruce Momjian 已提交
2024 2025
	}
	else
2026
		AH->fSpec = NULL;
B
Bruce Momjian 已提交
2027

2028 2029 2030
	AH->currUser = NULL;		/* unknown */
	AH->currSchema = NULL;		/* ditto */
	AH->currTablespace = NULL;	/* ditto */
2031
	AH->currWithOids = -1;		/* force SET */
B
Bruce Momjian 已提交
2032

2033
	AH->toc = (TocEntry *) pg_calloc(1, sizeof(TocEntry));
B
Bruce Momjian 已提交
2034

B
Bruce Momjian 已提交
2035 2036 2037 2038 2039
	AH->toc->next = AH->toc;
	AH->toc->prev = AH->toc;

	AH->mode = mode;
	AH->compression = compression;
B
Bruce Momjian 已提交
2040

2041 2042
	memset(&(AH->sqlparse), 0, sizeof(AH->sqlparse));

B
Bruce Momjian 已提交
2043 2044 2045
	/* Open stdout with no compression for AH output handle */
	AH->gzOut = 0;
	AH->OF = stdout;
B
Bruce Momjian 已提交
2046

2047 2048
	/*
	 * On Windows, we need to use binary mode to read/write non-text archive
B
Bruce Momjian 已提交
2049 2050
	 * formats.  Force stdin/stdout into binary mode if that is what we are
	 * using.
2051 2052
	 */
#ifdef WIN32
2053 2054
	if (fmt != archNull &&
		(AH->fSpec == NULL || strcmp(AH->fSpec, "") == 0))
2055 2056 2057 2058 2059 2060 2061 2062
	{
		if (mode == archModeWrite)
			setmode(fileno(stdout), O_BINARY);
		else
			setmode(fileno(stdin), O_BINARY);
	}
#endif

B
Bruce Momjian 已提交
2063
	if (fmt == archUnknown)
2064 2065 2066
		AH->format = _discoverArchiveFormat(AH);
	else
		AH->format = fmt;
B
Bruce Momjian 已提交
2067

2068 2069
	AH->promptPassword = TRI_DEFAULT;

B
Bruce Momjian 已提交
2070 2071
	switch (AH->format)
	{
2072 2073 2074
		case archCustom:
			InitArchiveFmt_Custom(AH);
			break;
B
Bruce Momjian 已提交
2075

2076 2077 2078
		case archNull:
			InitArchiveFmt_Null(AH);
			break;
B
Bruce Momjian 已提交
2079

2080 2081 2082 2083
		case archDirectory:
			InitArchiveFmt_Directory(AH);
			break;

2084 2085 2086 2087 2088
		case archTar:
			InitArchiveFmt_Tar(AH);
			break;

		default:
2089
			exit_horribly(modulename, "unrecognized file format \"%d\"\n", fmt);
B
Bruce Momjian 已提交
2090
	}
B
Bruce Momjian 已提交
2091

B
Bruce Momjian 已提交
2092
	return AH;
B
Bruce Momjian 已提交
2093 2094 2095
}


B
Bruce Momjian 已提交
2096 2097
void
WriteDataChunks(ArchiveHandle *AH)
B
Bruce Momjian 已提交
2098
{
2099
	TocEntry   *te;
B
Bruce Momjian 已提交
2100 2101
	StartDataPtr startPtr;
	EndDataPtr	endPtr;
B
Bruce Momjian 已提交
2102

2103
	for (te = AH->toc->next; te != AH->toc; te = te->next)
B
Bruce Momjian 已提交
2104
	{
2105
		if (te->dataDumper != NULL && (te->reqs & REQ_DATA) != 0)
2106
		{
B
Bruce Momjian 已提交
2107 2108
			AH->currToc = te;
			/* printf("Writing data for %d (%x)\n", te->id, te); */
2109

B
Bruce Momjian 已提交
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119
			if (strcmp(te->desc, "BLOBS") == 0)
			{
				startPtr = AH->StartBlobsPtr;
				endPtr = AH->EndBlobsPtr;
			}
			else
			{
				startPtr = AH->StartDataPtr;
				endPtr = AH->EndDataPtr;
			}
B
Bruce Momjian 已提交
2120

B
Bruce Momjian 已提交
2121 2122
			if (startPtr != NULL)
				(*startPtr) (AH, te);
B
Bruce Momjian 已提交
2123

B
Bruce Momjian 已提交
2124
			/*
B
Bruce Momjian 已提交
2125
			 * printf("Dumper arg for %d is %x\n", te->id, te->dataDumperArg);
B
Bruce Momjian 已提交
2126 2127 2128 2129 2130 2131
			 */

			/*
			 * The user-provided DataDumper routine needs to call
			 * AH->WriteData
			 */
2132
			(*te->dataDumper) ((Archive *) AH, te->dataDumperArg);
B
Bruce Momjian 已提交
2133 2134 2135 2136 2137 2138

			if (endPtr != NULL)
				(*endPtr) (AH, te);
			AH->currToc = NULL;
		}
	}
B
Bruce Momjian 已提交
2139 2140
}

B
Bruce Momjian 已提交
2141 2142
void
WriteToc(ArchiveHandle *AH)
B
Bruce Momjian 已提交
2143
{
2144 2145
	TocEntry   *te;
	char		workbuf[32];
2146
	int			tocCount;
2147
	int			i;
B
Bruce Momjian 已提交
2148

2149 2150 2151 2152 2153 2154 2155 2156 2157
	/* count entries that will actually be dumped */
	tocCount = 0;
	for (te = AH->toc->next; te != AH->toc; te = te->next)
	{
		if ((te->reqs & (REQ_SCHEMA | REQ_DATA | REQ_SPECIAL)) != 0)
			tocCount++;
	}

	/* printf("%d TOC Entries to save\n", tocCount); */
B
Bruce Momjian 已提交
2158

2159
	WriteInt(AH, tocCount);
2160 2161

	for (te = AH->toc->next; te != AH->toc; te = te->next)
B
Bruce Momjian 已提交
2162
	{
2163 2164 2165
		if ((te->reqs & (REQ_SCHEMA | REQ_DATA | REQ_SPECIAL)) == 0)
			continue;

2166
		WriteInt(AH, te->dumpId);
B
Bruce Momjian 已提交
2167
		WriteInt(AH, te->dataDumper ? 1 : 0);
2168 2169 2170 2171 2172 2173

		/* OID is recorded as a string for historical reasons */
		sprintf(workbuf, "%u", te->catalogId.tableoid);
		WriteStr(AH, workbuf);
		sprintf(workbuf, "%u", te->catalogId.oid);
		WriteStr(AH, workbuf);
2174

2175
		WriteStr(AH, te->tag);
B
Bruce Momjian 已提交
2176
		WriteStr(AH, te->desc);
2177
		WriteInt(AH, te->section);
B
Bruce Momjian 已提交
2178 2179 2180
		WriteStr(AH, te->defn);
		WriteStr(AH, te->dropStmt);
		WriteStr(AH, te->copyStmt);
2181
		WriteStr(AH, te->namespace);
2182
		WriteStr(AH, te->tablespace);
B
Bruce Momjian 已提交
2183
		WriteStr(AH, te->owner);
2184
		WriteStr(AH, te->withOids ? "true" : "false");
2185 2186

		/* Dump list of dependencies */
2187
		for (i = 0; i < te->nDeps; i++)
2188
		{
2189 2190
			sprintf(workbuf, "%d", te->dependencies[i]);
			WriteStr(AH, workbuf);
2191
		}
2192
		WriteStr(AH, NULL);		/* Terminate List */
2193

B
Bruce Momjian 已提交
2194 2195 2196
		if (AH->WriteExtraTocPtr)
			(*AH->WriteExtraTocPtr) (AH, te);
	}
B
Bruce Momjian 已提交
2197 2198
}

B
Bruce Momjian 已提交
2199 2200
void
ReadToc(ArchiveHandle *AH)
B
Bruce Momjian 已提交
2201
{
B
Bruce Momjian 已提交
2202
	int			i;
2203 2204
	char	   *tmp;
	DumpId	   *deps;
2205 2206
	int			depIdx;
	int			depSize;
2207
	TocEntry   *te;
B
Bruce Momjian 已提交
2208

B
Bruce Momjian 已提交
2209
	AH->tocCount = ReadInt(AH);
2210
	AH->maxDumpId = 0;
B
Bruce Momjian 已提交
2211

B
Bruce Momjian 已提交
2212 2213
	for (i = 0; i < AH->tocCount; i++)
	{
2214
		te = (TocEntry *) pg_calloc(1, sizeof(TocEntry));
2215 2216 2217 2218
		te->dumpId = ReadInt(AH);

		if (te->dumpId > AH->maxDumpId)
			AH->maxDumpId = te->dumpId;
2219 2220

		/* Sanity check */
2221
		if (te->dumpId <= 0)
2222
			exit_horribly(modulename,
2223
					   "entry ID %d out of range -- perhaps a corrupt TOC\n",
2224
						  te->dumpId);
2225 2226

		te->hadDumper = ReadInt(AH);
2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238

		if (AH->version >= K_VERS_1_8)
		{
			tmp = ReadStr(AH);
			sscanf(tmp, "%u", &te->catalogId.tableoid);
			free(tmp);
		}
		else
			te->catalogId.tableoid = InvalidOid;
		tmp = ReadStr(AH);
		sscanf(tmp, "%u", &te->catalogId.oid);
		free(tmp);
2239

2240
		te->tag = ReadStr(AH);
2241
		te->desc = ReadStr(AH);
2242 2243 2244 2245 2246 2247 2248 2249

		if (AH->version >= K_VERS_1_11)
		{
			te->section = ReadInt(AH);
		}
		else
		{
			/*
2250 2251 2252
			 * Rules for pre-8.4 archives wherein pg_dump hasn't classified
			 * the entries into sections.  This list need not cover entry
			 * types added later than 8.4.
2253 2254
			 */
			if (strcmp(te->desc, "COMMENT") == 0 ||
2255
				strcmp(te->desc, "ACL") == 0 ||
2256
				strcmp(te->desc, "ACL LANGUAGE") == 0)
2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272
				te->section = SECTION_NONE;
			else if (strcmp(te->desc, "TABLE DATA") == 0 ||
					 strcmp(te->desc, "BLOBS") == 0 ||
					 strcmp(te->desc, "BLOB COMMENTS") == 0)
				te->section = SECTION_DATA;
			else if (strcmp(te->desc, "CONSTRAINT") == 0 ||
					 strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
					 strcmp(te->desc, "FK CONSTRAINT") == 0 ||
					 strcmp(te->desc, "INDEX") == 0 ||
					 strcmp(te->desc, "RULE") == 0 ||
					 strcmp(te->desc, "TRIGGER") == 0)
				te->section = SECTION_POST_DATA;
			else
				te->section = SECTION_PRE_DATA;
		}

2273 2274 2275 2276 2277 2278
		te->defn = ReadStr(AH);
		te->dropStmt = ReadStr(AH);

		if (AH->version >= K_VERS_1_3)
			te->copyStmt = ReadStr(AH);

2279 2280 2281
		if (AH->version >= K_VERS_1_6)
			te->namespace = ReadStr(AH);

2282 2283 2284
		if (AH->version >= K_VERS_1_10)
			te->tablespace = ReadStr(AH);

2285
		te->owner = ReadStr(AH);
2286 2287 2288 2289 2290 2291 2292 2293 2294
		if (AH->version >= K_VERS_1_9)
		{
			if (strcmp(ReadStr(AH), "true") == 0)
				te->withOids = true;
			else
				te->withOids = false;
		}
		else
			te->withOids = true;
B
Bruce Momjian 已提交
2295

2296 2297 2298 2299
		/* Read TOC entry dependencies */
		if (AH->version >= K_VERS_1_5)
		{
			depSize = 100;
2300
			deps = (DumpId *) pg_malloc(sizeof(DumpId) * depSize);
2301
			depIdx = 0;
2302
			for (;;)
2303
			{
2304 2305 2306
				tmp = ReadStr(AH);
				if (!tmp)
					break;		/* end of list */
2307
				if (depIdx >= depSize)
2308 2309
				{
					depSize *= 2;
T
Tom Lane 已提交
2310
					deps = (DumpId *) pg_realloc(deps, sizeof(DumpId) * depSize);
2311
				}
2312 2313 2314 2315
				sscanf(tmp, "%d", &deps[depIdx]);
				free(tmp);
				depIdx++;
			}
2316

2317 2318
			if (depIdx > 0)		/* We have a non-null entry */
			{
T
Tom Lane 已提交
2319
				deps = (DumpId *) pg_realloc(deps, sizeof(DumpId) * depIdx);
2320 2321 2322
				te->dependencies = deps;
				te->nDeps = depIdx;
			}
2323
			else
2324 2325
			{
				free(deps);
2326 2327
				te->dependencies = NULL;
				te->nDeps = 0;
2328
			}
2329
		}
2330
		else
2331 2332 2333 2334
		{
			te->dependencies = NULL;
			te->nDeps = 0;
		}
2335

B
Bruce Momjian 已提交
2336 2337
		if (AH->ReadExtraTocPtr)
			(*AH->ReadExtraTocPtr) (AH, te);
2338

2339 2340
		ahlog(AH, 3, "read TOC entry %d (ID %d) for %s %s\n",
			  i, te->dumpId, te->desc, te->tag);
2341

2342
		/* link completed entry into TOC circular list */
2343 2344 2345 2346
		te->prev = AH->toc->prev;
		AH->toc->prev->next = te;
		AH->toc->prev = te;
		te->next = AH->toc;
2347 2348 2349 2350 2351 2352

		/* special processing immediately upon read for some items */
		if (strcmp(te->desc, "ENCODING") == 0)
			processEncodingEntry(AH, te);
		else if (strcmp(te->desc, "STDSTRINGS") == 0)
			processStdStringsEntry(AH, te);
B
Bruce Momjian 已提交
2353
	}
B
Bruce Momjian 已提交
2354 2355
}

2356 2357 2358 2359
static void
processEncodingEntry(ArchiveHandle *AH, TocEntry *te)
{
	/* te->defn should have the form SET client_encoding = 'foo'; */
2360
	char	   *defn = pg_strdup(te->defn);
2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
	char	   *ptr1;
	char	   *ptr2 = NULL;
	int			encoding;

	ptr1 = strchr(defn, '\'');
	if (ptr1)
		ptr2 = strchr(++ptr1, '\'');
	if (ptr2)
	{
		*ptr2 = '\0';
		encoding = pg_char_to_encoding(ptr1);
		if (encoding < 0)
2373 2374
			exit_horribly(modulename, "unrecognized encoding \"%s\"\n",
						  ptr1);
2375 2376 2377
		AH->public.encoding = encoding;
	}
	else
2378 2379
		exit_horribly(modulename, "invalid ENCODING item: %s\n",
					  te->defn);
2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395

	free(defn);
}

static void
processStdStringsEntry(ArchiveHandle *AH, TocEntry *te)
{
	/* te->defn should have the form SET standard_conforming_strings = 'x'; */
	char	   *ptr1;

	ptr1 = strchr(te->defn, '\'');
	if (ptr1 && strncmp(ptr1, "'on'", 4) == 0)
		AH->public.std_strings = true;
	else if (ptr1 && strncmp(ptr1, "'off'", 5) == 0)
		AH->public.std_strings = false;
	else
2396 2397
		exit_horribly(modulename, "invalid STDSTRINGS item: %s\n",
					  te->defn);
2398 2399
}

2400
static teReqs
2401
_tocEntryRequired(TocEntry *te, teSection curSection, RestoreOptions *ropt)
B
Bruce Momjian 已提交
2402
{
2403
	teReqs		res = REQ_SCHEMA | REQ_DATA;
B
Bruce Momjian 已提交
2404

2405
	/* ENCODING and STDSTRINGS items are treated specially */
2406 2407
	if (strcmp(te->desc, "ENCODING") == 0 ||
		strcmp(te->desc, "STDSTRINGS") == 0)
2408
		return REQ_SPECIAL;
2409

B
Bruce Momjian 已提交
2410
	/* If it's an ACL, maybe ignore it */
2411
	if (ropt->aclsSkip && _tocEntryIsACL(te))
2412
		return 0;
B
Bruce Momjian 已提交
2413

R
Robert Haas 已提交
2414
	/* If it's security labels, maybe ignore it */
2415
	if (ropt->no_security_labels && strcmp(te->desc, "SECURITY LABEL") == 0)
R
Robert Haas 已提交
2416 2417
		return 0;

2418 2419
	/* Ignore it if section is not to be dumped/restored */
	switch (curSection)
2420
	{
2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434
		case SECTION_PRE_DATA:
			if (!(ropt->dumpSections & DUMP_PRE_DATA))
				return 0;
			break;
		case SECTION_DATA:
			if (!(ropt->dumpSections & DUMP_DATA))
				return 0;
			break;
		case SECTION_POST_DATA:
			if (!(ropt->dumpSections & DUMP_POST_DATA))
				return 0;
			break;
		default:
			/* shouldn't get here, really, but ignore it */
2435 2436 2437
			return 0;
	}

2438 2439 2440 2441 2442 2443 2444 2445 2446 2447
	/* Check options for selective dump/restore */
	if (ropt->schemaNames)
	{
		/* If no namespace is specified, it means all. */
		if (!te->namespace)
			return 0;
		if (strcmp(ropt->schemaNames, te->namespace) != 0)
			return 0;
	}

B
Bruce Momjian 已提交
2448 2449
	if (ropt->selTypes)
	{
2450 2451
		if (strcmp(te->desc, "TABLE") == 0 ||
			strcmp(te->desc, "TABLE DATA") == 0)
2452 2453 2454
		{
			if (!ropt->selTable)
				return 0;
2455
			if (ropt->tableNames && strcmp(ropt->tableNames, te->tag) != 0)
2456
				return 0;
B
Bruce Momjian 已提交
2457 2458 2459
		}
		else if (strcmp(te->desc, "INDEX") == 0)
		{
2460 2461
			if (!ropt->selIndex)
				return 0;
2462
			if (ropt->indexNames && strcmp(ropt->indexNames, te->tag) != 0)
2463
				return 0;
B
Bruce Momjian 已提交
2464 2465 2466
		}
		else if (strcmp(te->desc, "FUNCTION") == 0)
		{
2467 2468
			if (!ropt->selFunction)
				return 0;
2469
			if (ropt->functionNames && strcmp(ropt->functionNames, te->tag) != 0)
2470
				return 0;
B
Bruce Momjian 已提交
2471 2472 2473
		}
		else if (strcmp(te->desc, "TRIGGER") == 0)
		{
2474 2475
			if (!ropt->selTrigger)
				return 0;
2476
			if (ropt->triggerNames && strcmp(ropt->triggerNames, te->tag) != 0)
2477 2478
				return 0;
		}
B
Bruce Momjian 已提交
2479 2480
		else
			return 0;
B
Bruce Momjian 已提交
2481 2482
	}

2483
	/*
B
Bruce Momjian 已提交
2484
	 * Check if we had a dataDumper. Indicates if the entry is schema or data
2485 2486 2487 2488
	 */
	if (!te->hadDumper)
	{
		/*
B
Bruce Momjian 已提交
2489 2490 2491 2492 2493
		 * Special Case: If 'SEQUENCE SET' or anything to do with BLOBs, then
		 * it is considered a data entry.  We don't need to check for the
		 * BLOBS entry or old-style BLOB COMMENTS, because they will have
		 * hadDumper = true ... but we do need to check new-style BLOB
		 * comments.
2494
		 */
2495 2496 2497 2498 2499
		if (strcmp(te->desc, "SEQUENCE SET") == 0 ||
			strcmp(te->desc, "BLOB") == 0 ||
			(strcmp(te->desc, "ACL") == 0 &&
			 strncmp(te->tag, "LARGE OBJECT ", 13) == 0) ||
			(strcmp(te->desc, "COMMENT") == 0 &&
R
Robert Haas 已提交
2500 2501
			 strncmp(te->tag, "LARGE OBJECT ", 13) == 0) ||
			(strcmp(te->desc, "SECURITY LABEL") == 0 &&
2502
			 strncmp(te->tag, "LARGE OBJECT ", 13) == 0))
2503 2504
			res = res & REQ_DATA;
		else
2505 2506
			res = res & ~REQ_DATA;
	}
2507

2508
	/*
B
Bruce Momjian 已提交
2509 2510
	 * Special case: <Init> type with <Max OID> tag; this is obsolete and we
	 * always ignore it.
2511
	 */
2512
	if ((strcmp(te->desc, "<Init>") == 0) && (strcmp(te->tag, "Max OID") == 0))
2513
		return 0;
2514

B
Bruce Momjian 已提交
2515 2516
	/* Mask it if we only want schema */
	if (ropt->schemaOnly)
2517
		res = res & REQ_SCHEMA;
B
Bruce Momjian 已提交
2518

2519
	/* Mask it if we only want data */
2520
	if (ropt->dataOnly)
2521
		res = res & REQ_DATA;
B
Bruce Momjian 已提交
2522

2523
	/* Mask it if we don't have a schema contribution */
B
Bruce Momjian 已提交
2524
	if (!te->defn || strlen(te->defn) == 0)
2525
		res = res & ~REQ_SCHEMA;
B
Bruce Momjian 已提交
2526

2527 2528
	/* Finally, if there's a per-ID filter, limit based on that as well */
	if (ropt->idWanted && !ropt->idWanted[te->dumpId - 1])
2529
		return 0;
B
Bruce Momjian 已提交
2530

B
Bruce Momjian 已提交
2531
	return res;
B
Bruce Momjian 已提交
2532 2533
}

2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547
/*
 * Identify TOC entries that are ACLs.
 */
static bool
_tocEntryIsACL(TocEntry *te)
{
	/* "ACL LANGUAGE" was a crock emitted only in PG 7.4 */
	if (strcmp(te->desc, "ACL") == 0 ||
		strcmp(te->desc, "ACL LANGUAGE") == 0 ||
		strcmp(te->desc, "DEFAULT ACL") == 0)
		return true;
	return false;
}

2548 2549 2550 2551 2552 2553 2554
/*
 * Issue SET commands for parameters that we want to have set the same way
 * at all times during execution of a restore script.
 */
static void
_doSetFixedOutputState(ArchiveHandle *AH)
{
2555
	/* Disable statement_timeout in archive for pg_restore/psql  */
2556
	ahprintf(AH, "SET statement_timeout = 0;\n");
2557

2558 2559 2560
	/* Select the correct character set encoding */
	ahprintf(AH, "SET client_encoding = '%s';\n",
			 pg_encoding_to_char(AH->public.encoding));
2561

2562 2563 2564
	/* Select the correct string literal syntax */
	ahprintf(AH, "SET standard_conforming_strings = %s;\n",
			 AH->public.std_strings ? "on" : "off");
2565

2566 2567 2568 2569
	/* Select the role to be used during restore */
	if (AH->ropt && AH->ropt->use_role)
		ahprintf(AH, "SET ROLE %s;\n", fmtId(AH->ropt->use_role));

2570 2571 2572
	/* Make sure function checking is disabled */
	ahprintf(AH, "SET check_function_bodies = false;\n");

2573 2574
	/* Avoid annoying notices etc */
	ahprintf(AH, "SET client_min_messages = warning;\n");
2575 2576
	if (!AH->public.std_strings)
		ahprintf(AH, "SET escape_string_warning = off;\n");
2577

2578 2579 2580
	ahprintf(AH, "\n");
}

2581 2582
/*
 * Issue a SET SESSION AUTHORIZATION command.  Caller is responsible
2583 2584
 * for updating state if appropriate.  If user is NULL or an empty string,
 * the specification DEFAULT will be used.
2585 2586
 */
static void
2587
_doSetSessionAuth(ArchiveHandle *AH, const char *user)
2588
{
2589
	PQExpBuffer cmd = createPQExpBuffer();
B
Bruce Momjian 已提交
2590

2591
	appendPQExpBuffer(cmd, "SET SESSION AUTHORIZATION ");
B
Bruce Momjian 已提交
2592

2593 2594 2595 2596
	/*
	 * SQL requires a string literal here.	Might as well be correct.
	 */
	if (user && *user)
2597
		appendStringLiteralAHX(cmd, user, AH);
2598 2599 2600 2601
	else
		appendPQExpBuffer(cmd, "DEFAULT");
	appendPQExpBuffer(cmd, ";");

2602 2603 2604 2605
	if (RestoringToDB(AH))
	{
		PGresult   *res;

2606
		res = PQexec(AH->connection, cmd->data);
2607 2608

		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2609 2610 2611
			/* NOT warn_or_exit_horribly... use -O instead to skip this. */
			exit_horribly(modulename, "could not set session user to \"%s\": %s",
						  user, PQerrorMessage(AH->connection));
2612 2613 2614 2615

		PQclear(res);
	}
	else
2616 2617 2618
		ahprintf(AH, "%s\n\n", cmd->data);

	destroyPQExpBuffer(cmd);
2619 2620
}

2621

2622 2623 2624 2625 2626 2627 2628 2629 2630 2631
/*
 * Issue a SET default_with_oids command.  Caller is responsible
 * for updating state if appropriate.
 */
static void
_doSetWithOids(ArchiveHandle *AH, const bool withOids)
{
	PQExpBuffer cmd = createPQExpBuffer();

	appendPQExpBuffer(cmd, "SET default_with_oids = %s;", withOids ?
B
Bruce Momjian 已提交
2632
					  "true" : "false");
2633 2634 2635 2636 2637 2638 2639 2640

	if (RestoringToDB(AH))
	{
		PGresult   *res;

		res = PQexec(AH->connection, cmd->data);

		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2641 2642 2643
			warn_or_exit_horribly(AH, modulename,
								  "could not set default_with_oids: %s",
								  PQerrorMessage(AH->connection));
2644 2645 2646 2647 2648 2649 2650 2651 2652 2653

		PQclear(res);
	}
	else
		ahprintf(AH, "%s\n\n", cmd->data);

	destroyPQExpBuffer(cmd);
}


2654
/*
2655
 * Issue the commands to connect to the specified database.
2656 2657
 *
 * If we're currently restoring right into a database, this will
B
Bruce Momjian 已提交
2658
 * actually establish a connection. Otherwise it puts a \connect into
2659
 * the script output.
2660 2661
 *
 * NULL dbname implies reconnecting to the current DB (pretty useless).
2662
 */
B
Bruce Momjian 已提交
2663
static void
2664
_reconnectToDB(ArchiveHandle *AH, const char *dbname)
2665
{
2666
	if (RestoringToDB(AH))
2667
		ReconnectToServer(AH, dbname, NULL);
2668
	else
2669 2670 2671
	{
		PQExpBuffer qry = createPQExpBuffer();

2672
		appendPQExpBuffer(qry, "\\connect %s\n\n",
2673
						  dbname ? fmtId(dbname) : "-");
2674
		ahprintf(AH, "%s", qry->data);
2675 2676
		destroyPQExpBuffer(qry);
	}
2677

2678
	/*
B
Bruce Momjian 已提交
2679 2680
	 * NOTE: currUser keeps track of what the imaginary session user in our
	 * script is.  It's now effectively reset to the original userID.
2681
	 */
2682 2683
	if (AH->currUser)
		free(AH->currUser);
2684
	AH->currUser = NULL;
2685

2686
	/* don't assume we still know the output schema, tablespace, etc either */
2687 2688
	if (AH->currSchema)
		free(AH->currSchema);
2689 2690 2691 2692
	AH->currSchema = NULL;
	if (AH->currTablespace)
		free(AH->currTablespace);
	AH->currTablespace = NULL;
2693
	AH->currWithOids = -1;
B
Bruce Momjian 已提交
2694

2695 2696
	/* re-establish fixed state */
	_doSetFixedOutputState(AH);
2697 2698
}

2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715
/*
 * Become the specified user, and update state to avoid redundant commands
 *
 * NULL or empty argument is taken to mean restoring the session default
 */
static void
_becomeUser(ArchiveHandle *AH, const char *user)
{
	if (!user)
		user = "";				/* avoid null pointers */

	if (AH->currUser && strcmp(AH->currUser, user) == 0)
		return;					/* no need to do anything */

	_doSetSessionAuth(AH, user);

	/*
B
Bruce Momjian 已提交
2716 2717
	 * NOTE: currUser keeps track of what the imaginary session user in our
	 * script is
2718 2719 2720
	 */
	if (AH->currUser)
		free(AH->currUser);
2721
	AH->currUser = pg_strdup(user);
2722
}
2723 2724

/*
2725
 * Become the owner of the given TOC entry object.	If
2726 2727
 * changes in ownership are not allowed, this doesn't do anything.
 */
B
Bruce Momjian 已提交
2728
static void
2729
_becomeOwner(ArchiveHandle *AH, TocEntry *te)
2730
{
2731
	if (AH->ropt && (AH->ropt->noOwner || !AH->ropt->use_setsessauth))
2732 2733
		return;

2734
	_becomeUser(AH, te->owner);
2735 2736
}

2737

2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751
/*
 * Set the proper default_with_oids value for the table.
 */
static void
_setWithOids(ArchiveHandle *AH, TocEntry *te)
{
	if (AH->currWithOids != te->withOids)
	{
		_doSetWithOids(AH, te->withOids);
		AH->currWithOids = te->withOids;
	}
}


2752 2753 2754 2755 2756 2757 2758
/*
 * Issue the commands to select the specified schema as the current schema
 * in the target database.
 */
static void
_selectOutputSchema(ArchiveHandle *AH, const char *schemaName)
{
2759 2760
	PQExpBuffer qry;

2761
	if (!schemaName || *schemaName == '\0' ||
2762
		(AH->currSchema && strcmp(AH->currSchema, schemaName) == 0))
2763 2764
		return;					/* no need to do anything */

2765 2766 2767
	qry = createPQExpBuffer();

	appendPQExpBuffer(qry, "SET search_path = %s",
2768
					  fmtId(schemaName));
2769 2770 2771
	if (strcmp(schemaName, "pg_catalog") != 0)
		appendPQExpBuffer(qry, ", pg_catalog");

2772 2773 2774 2775 2776 2777 2778
	if (RestoringToDB(AH))
	{
		PGresult   *res;

		res = PQexec(AH->connection, qry->data);

		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2779 2780 2781
			warn_or_exit_horribly(AH, modulename,
								  "could not set search_path to \"%s\": %s",
								  schemaName, PQerrorMessage(AH->connection));
2782 2783 2784 2785

		PQclear(res);
	}
	else
2786
		ahprintf(AH, "%s;\n\n", qry->data);
2787 2788 2789

	if (AH->currSchema)
		free(AH->currSchema);
2790
	AH->currSchema = pg_strdup(schemaName);
2791 2792

	destroyPQExpBuffer(qry);
2793 2794
}

2795 2796 2797 2798 2799 2800 2801 2802
/*
 * Issue the commands to select the specified tablespace as the current one
 * in the target database.
 */
static void
_selectTablespace(ArchiveHandle *AH, const char *tablespace)
{
	PQExpBuffer qry;
B
Bruce Momjian 已提交
2803 2804
	const char *want,
			   *have;
2805

2806 2807 2808 2809
	/* do nothing in --no-tablespaces mode */
	if (AH->ropt->noTablespace)
		return;

2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839
	have = AH->currTablespace;
	want = tablespace;

	/* no need to do anything for non-tablespace object */
	if (!want)
		return;

	if (have && strcmp(want, have) == 0)
		return;					/* no need to do anything */

	qry = createPQExpBuffer();

	if (strcmp(want, "") == 0)
	{
		/* We want the tablespace to be the database's default */
		appendPQExpBuffer(qry, "SET default_tablespace = ''");
	}
	else
	{
		/* We want an explicit tablespace */
		appendPQExpBuffer(qry, "SET default_tablespace = %s", fmtId(want));
	}

	if (RestoringToDB(AH))
	{
		PGresult   *res;

		res = PQexec(AH->connection, qry->data);

		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2840
			warn_or_exit_horribly(AH, modulename,
2841 2842
								"could not set default_tablespace to %s: %s",
								fmtId(want), PQerrorMessage(AH->connection));
2843 2844 2845 2846 2847 2848 2849 2850

		PQclear(res);
	}
	else
		ahprintf(AH, "%s;\n\n", qry->data);

	if (AH->currTablespace)
		free(AH->currTablespace);
2851
	AH->currTablespace = pg_strdup(want);
2852 2853 2854

	destroyPQExpBuffer(qry);
}
2855

2856 2857 2858 2859 2860 2861 2862 2863
/*
 * Extract an object description for a TOC entry, and append it to buf.
 *
 * This is not quite as general as it may seem, since it really only
 * handles constructing the right thing to put into ALTER ... OWNER TO.
 *
 * The whole thing is pretty grotty, but we are kind of stuck since the
 * information used is all that's available in older dump files.
2864
 */
2865
static void
2866
_getObjectDescription(PQExpBuffer buf, TocEntry *te, ArchiveHandle *AH)
2867
{
2868 2869 2870
	const char *type = te->desc;

	/* Use ALTER TABLE for views and sequences */
2871
	if (strcmp(type, "VIEW") == 0 || strcmp(type, "SEQUENCE") == 0)
2872 2873 2874
		type = "TABLE";

	/* objects named by a schema and name */
P
Peter Eisentraut 已提交
2875 2876
	if (strcmp(type, "COLLATION") == 0 ||
		strcmp(type, "CONVERSION") == 0 ||
2877 2878
		strcmp(type, "DOMAIN") == 0 ||
		strcmp(type, "TABLE") == 0 ||
2879
		strcmp(type, "TYPE") == 0 ||
R
Robert Haas 已提交
2880
		strcmp(type, "FOREIGN TABLE") == 0 ||
2881 2882
		strcmp(type, "TEXT SEARCH DICTIONARY") == 0 ||
		strcmp(type, "TEXT SEARCH CONFIGURATION") == 0)
2883
	{
2884
		appendPQExpBuffer(buf, "%s ", type);
B
Bruce Momjian 已提交
2885
		if (te->namespace && te->namespace[0])	/* is null pre-7.3 */
2886
			appendPQExpBuffer(buf, "%s.", fmtId(te->namespace));
B
Bruce Momjian 已提交
2887

2888
		/*
B
Bruce Momjian 已提交
2889 2890 2891
		 * Pre-7.3 pg_dump would sometimes (not always) put a fmtId'd name
		 * into te->tag for an index. This check is heuristic, so make its
		 * scope as narrow as possible.
2892 2893 2894
		 */
		if (AH->version < K_VERS_1_7 &&
			te->tag[0] == '"' &&
B
Bruce Momjian 已提交
2895
			te->tag[strlen(te->tag) - 1] == '"' &&
2896 2897 2898 2899
			strcmp(type, "INDEX") == 0)
			appendPQExpBuffer(buf, "%s", te->tag);
		else
			appendPQExpBuffer(buf, "%s", fmtId(te->tag));
2900 2901
		return;
	}
2902

2903 2904
	/* objects named by just a name */
	if (strcmp(type, "DATABASE") == 0 ||
2905
		strcmp(type, "PROCEDURAL LANGUAGE") == 0 ||
2906 2907 2908 2909
		strcmp(type, "SCHEMA") == 0 ||
		strcmp(type, "FOREIGN DATA WRAPPER") == 0 ||
		strcmp(type, "SERVER") == 0 ||
		strcmp(type, "USER MAPPING") == 0)
2910 2911 2912 2913
	{
		appendPQExpBuffer(buf, "%s %s", type, fmtId(te->tag));
		return;
	}
2914

2915 2916 2917 2918 2919 2920 2921
	/* BLOBs just have a name, but it's numeric so must not use fmtId */
	if (strcmp(type, "BLOB") == 0)
	{
		appendPQExpBuffer(buf, "LARGE OBJECT %s", te->tag);
		return;
	}

B
Bruce Momjian 已提交
2922
	/*
B
Bruce Momjian 已提交
2923 2924
	 * These object types require additional decoration.  Fortunately, the
	 * information needed is exactly what's in the DROP command.
B
Bruce Momjian 已提交
2925
	 */
2926 2927 2928
	if (strcmp(type, "AGGREGATE") == 0 ||
		strcmp(type, "FUNCTION") == 0 ||
		strcmp(type, "OPERATOR") == 0 ||
2929 2930
		strcmp(type, "OPERATOR CLASS") == 0 ||
		strcmp(type, "OPERATOR FAMILY") == 0)
B
Bruce Momjian 已提交
2931
	{
2932
		/* Chop "DROP " off the front and make a modifiable copy */
2933
		char	   *first = pg_strdup(te->dropStmt + 5);
2934
		char	   *last;
2935

2936 2937
		/* point to last character in string */
		last = first + strlen(first) - 1;
2938

2939 2940 2941 2942
		/* Strip off any ';' or '\n' at the end */
		while (last >= first && (*last == '\n' || *last == ';'))
			last--;
		*(last + 1) = '\0';
B
Bruce Momjian 已提交
2943

2944
		appendPQExpBufferStr(buf, first);
B
Bruce Momjian 已提交
2945 2946

		free(first);
2947
		return;
2948 2949
	}

2950 2951
	write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
			  type);
2952 2953 2954
}

static void
2955
_printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass)
B
Bruce Momjian 已提交
2956
{
2957 2958 2959
	/* ACLs are dumped only during acl pass */
	if (acl_pass)
	{
2960
		if (!_tocEntryIsACL(te))
2961 2962 2963 2964
			return;
	}
	else
	{
2965
		if (_tocEntryIsACL(te))
2966 2967 2968 2969 2970
			return;
	}

	/*
	 * Avoid dumping the public schema, as it will already be created ...
B
Bruce Momjian 已提交
2971
	 * unless we are using --clean mode, in which case it's been deleted and
2972
	 * we'd better recreate it.  Likewise for its comment, if any.
2973
	 */
2974 2975 2976 2977 2978
	if (!ropt->dropSchema)
	{
		if (strcmp(te->desc, "SCHEMA") == 0 &&
			strcmp(te->tag, "public") == 0)
			return;
2979
		/* The comment restore would require super-user privs, so avoid it. */
2980 2981 2982 2983
		if (strcmp(te->desc, "COMMENT") == 0 &&
			strcmp(te->tag, "SCHEMA public") == 0)
			return;
	}
2984

2985
	/* Select owner, schema, and tablespace as necessary */
2986 2987
	_becomeOwner(AH, te);
	_selectOutputSchema(AH, te->namespace);
2988
	_selectTablespace(AH, te->tablespace);
2989 2990 2991 2992 2993 2994

	/* Set up OID mode too */
	if (strcmp(te->desc, "TABLE") == 0)
		_setWithOids(AH, te);

	/* Emit header comment for item */
2995
	if (!AH->noTocComments)
2996
	{
2997
		const char *pfx;
2998 2999 3000
		char	   *sanitized_name;
		char	   *sanitized_schema;
		char	   *sanitized_owner;
3001 3002 3003 3004 3005 3006 3007 3008

		if (isData)
			pfx = "Data for ";
		else
			pfx = "";

		ahprintf(AH, "--\n");
		if (AH->public.verbose)
3009
		{
3010 3011 3012 3013 3014
			ahprintf(AH, "-- TOC entry %d (class %u OID %u)\n",
					 te->dumpId, te->catalogId.tableoid, te->catalogId.oid);
			if (te->nDeps > 0)
			{
				int			i;
3015

3016 3017 3018 3019 3020
				ahprintf(AH, "-- Dependencies:");
				for (i = 0; i < te->nDeps; i++)
					ahprintf(AH, " %d", te->dependencies[i]);
				ahprintf(AH, "\n");
			}
3021
		}
3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038

		/*
		 * Zap any line endings embedded in user-supplied fields, to prevent
		 * corruption of the dump (which could, in the worst case, present an
		 * SQL injection vulnerability if someone were to incautiously load a
		 * dump containing objects with maliciously crafted names).
		 */
		sanitized_name = replace_line_endings(te->tag);
		if (te->namespace)
			sanitized_schema = replace_line_endings(te->namespace);
		else
			sanitized_schema = pg_strdup("-");
		if (!ropt->noOwner)
			sanitized_owner = replace_line_endings(te->owner);
		else
			sanitized_owner = pg_strdup("-");

3039
		ahprintf(AH, "-- %sName: %s; Type: %s; Schema: %s; Owner: %s",
3040 3041 3042 3043 3044 3045 3046
				 pfx, sanitized_name, te->desc, sanitized_schema,
				 sanitized_owner);

		free(sanitized_name);
		free(sanitized_schema);
		free(sanitized_owner);

3047
		if (te->tablespace && !ropt->noTablespace)
3048
		{
3049
			char	   *sanitized_tablespace;
3050 3051 3052 3053 3054

			sanitized_tablespace = replace_line_endings(te->tablespace);
			ahprintf(AH, "; Tablespace: %s", sanitized_tablespace);
			free(sanitized_tablespace);
		}
3055 3056
		ahprintf(AH, "\n");

B
Bruce Momjian 已提交
3057
		if (AH->PrintExtraTocPtr !=NULL)
3058 3059
			(*AH->PrintExtraTocPtr) (AH, te);
		ahprintf(AH, "--\n\n");
3060
	}
B
Bruce Momjian 已提交
3061

3062 3063 3064
	/*
	 * Actually print the definition.
	 *
B
Bruce Momjian 已提交
3065 3066 3067
	 * Really crude hack for suppressing AUTHORIZATION clause that old pg_dump
	 * versions put into CREATE SCHEMA.  We have to do this when --no-owner
	 * mode is selected.  This is ugly, but I see no other good way ...
3068
	 */
3069
	if (ropt->noOwner && strcmp(te->desc, "SCHEMA") == 0)
3070
	{
3071
		ahprintf(AH, "CREATE SCHEMA %s;\n\n\n", fmtId(te->tag));
3072
	}
3073
	else
3074
	{
3075 3076
		if (strlen(te->defn) > 0)
			ahprintf(AH, "%s\n\n", te->defn);
3077
	}
3078 3079 3080

	/*
	 * If we aren't using SET SESSION AUTH to determine ownership, we must
3081 3082 3083
	 * instead issue an ALTER OWNER command.  We assume that anything without
	 * a DROP command is not a separately ownable object.  All the categories
	 * with DROP commands must appear in one list or the other.
3084 3085
	 */
	if (!ropt->noOwner && !ropt->use_setsessauth &&
3086 3087 3088
		strlen(te->owner) > 0 && strlen(te->dropStmt) > 0)
	{
		if (strcmp(te->desc, "AGGREGATE") == 0 ||
3089
			strcmp(te->desc, "BLOB") == 0 ||
P
Peter Eisentraut 已提交
3090
			strcmp(te->desc, "COLLATION") == 0 ||
3091 3092 3093 3094 3095 3096
			strcmp(te->desc, "CONVERSION") == 0 ||
			strcmp(te->desc, "DATABASE") == 0 ||
			strcmp(te->desc, "DOMAIN") == 0 ||
			strcmp(te->desc, "FUNCTION") == 0 ||
			strcmp(te->desc, "OPERATOR") == 0 ||
			strcmp(te->desc, "OPERATOR CLASS") == 0 ||
3097
			strcmp(te->desc, "OPERATOR FAMILY") == 0 ||
3098
			strcmp(te->desc, "PROCEDURAL LANGUAGE") == 0 ||
3099 3100 3101 3102
			strcmp(te->desc, "SCHEMA") == 0 ||
			strcmp(te->desc, "TABLE") == 0 ||
			strcmp(te->desc, "TYPE") == 0 ||
			strcmp(te->desc, "VIEW") == 0 ||
3103
			strcmp(te->desc, "SEQUENCE") == 0 ||
R
Robert Haas 已提交
3104
			strcmp(te->desc, "FOREIGN TABLE") == 0 ||
3105
			strcmp(te->desc, "TEXT SEARCH DICTIONARY") == 0 ||
3106 3107 3108
			strcmp(te->desc, "TEXT SEARCH CONFIGURATION") == 0 ||
			strcmp(te->desc, "FOREIGN DATA WRAPPER") == 0 ||
			strcmp(te->desc, "SERVER") == 0)
3109 3110 3111 3112
		{
			PQExpBuffer temp = createPQExpBuffer();

			appendPQExpBuffer(temp, "ALTER ");
3113
			_getObjectDescription(temp, te, AH);
3114 3115 3116 3117 3118 3119
			appendPQExpBuffer(temp, " OWNER TO %s;", fmtId(te->owner));
			ahprintf(AH, "%s\n\n", temp->data);
			destroyPQExpBuffer(temp);
		}
		else if (strcmp(te->desc, "CAST") == 0 ||
				 strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
3120
				 strcmp(te->desc, "CONSTRAINT") == 0 ||
3121 3122
				 strcmp(te->desc, "DEFAULT") == 0 ||
				 strcmp(te->desc, "FK CONSTRAINT") == 0 ||
3123
				 strcmp(te->desc, "INDEX") == 0 ||
3124
				 strcmp(te->desc, "RULE") == 0 ||
3125 3126
				 strcmp(te->desc, "TRIGGER") == 0 ||
				 strcmp(te->desc, "USER MAPPING") == 0)
3127 3128 3129 3130 3131 3132 3133 3134
		{
			/* these object types don't have separate owners */
		}
		else
		{
			write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
					  te->desc);
		}
3135
	}
B
Bruce Momjian 已提交
3136

3137 3138
	/*
	 * If it's an ACL entry, it might contain SET SESSION AUTHORIZATION
B
Bruce Momjian 已提交
3139
	 * commands, so we can no longer assume we know the current auth setting.
3140
	 */
3141
	if (acl_pass)
3142 3143 3144 3145 3146
	{
		if (AH->currUser)
			free(AH->currUser);
		AH->currUser = NULL;
	}
B
Bruce Momjian 已提交
3147 3148
}

3149 3150 3151 3152 3153 3154 3155
/*
 * Sanitize a string to be included in an SQL comment, by replacing any
 * newlines with spaces.
 */
static char *
replace_line_endings(const char *str)
{
3156 3157
	char	   *result;
	char	   *s;
3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169

	result = pg_strdup(str);

	for (s = result; *s != '\0'; s++)
	{
		if (*s == '\n' || *s == '\r')
			*s = ' ';
	}

	return result;
}

B
Bruce Momjian 已提交
3170 3171
void
WriteHead(ArchiveHandle *AH)
B
Bruce Momjian 已提交
3172
{
B
Bruce Momjian 已提交
3173
	struct tm	crtm;
3174

B
Bruce Momjian 已提交
3175 3176 3177 3178 3179
	(*AH->WriteBufPtr) (AH, "PGDMP", 5);		/* Magic code */
	(*AH->WriteBytePtr) (AH, AH->vmaj);
	(*AH->WriteBytePtr) (AH, AH->vmin);
	(*AH->WriteBytePtr) (AH, AH->vrev);
	(*AH->WriteBytePtr) (AH, AH->intSize);
3180
	(*AH->WriteBytePtr) (AH, AH->offSize);
B
Bruce Momjian 已提交
3181
	(*AH->WriteBytePtr) (AH, AH->format);
B
Bruce Momjian 已提交
3182

3183
#ifndef HAVE_LIBZ
B
Bruce Momjian 已提交
3184
	if (AH->compression != 0)
3185
		write_msg(modulename, "WARNING: requested compression not available in this "
3186
				  "installation -- archive will be uncompressed\n");
B
Bruce Momjian 已提交
3187

B
Bruce Momjian 已提交
3188
	AH->compression = 0;
3189
#endif
B
Bruce Momjian 已提交
3190

3191 3192 3193 3194 3195 3196 3197 3198 3199 3200
	WriteInt(AH, AH->compression);

	crtm = *localtime(&AH->createDate);
	WriteInt(AH, crtm.tm_sec);
	WriteInt(AH, crtm.tm_min);
	WriteInt(AH, crtm.tm_hour);
	WriteInt(AH, crtm.tm_mday);
	WriteInt(AH, crtm.tm_mon);
	WriteInt(AH, crtm.tm_year);
	WriteInt(AH, crtm.tm_isdst);
3201
	WriteStr(AH, PQdb(AH->connection));
3202 3203
	WriteStr(AH, AH->public.remoteVersionStr);
	WriteStr(AH, PG_VERSION);
B
Bruce Momjian 已提交
3204 3205
}

B
Bruce Momjian 已提交
3206 3207
void
ReadHead(ArchiveHandle *AH)
B
Bruce Momjian 已提交
3208
{
B
Bruce Momjian 已提交
3209 3210
	char		tmpMag[7];
	int			fmt;
3211
	struct tm	crtm;
B
Bruce Momjian 已提交
3212

3213 3214 3215
	/*
	 * If we haven't already read the header, do so.
	 *
B
Bruce Momjian 已提交
3216 3217
	 * NB: this code must agree with _discoverArchiveFormat().	Maybe find a
	 * way to unify the cases?
3218
	 */
B
Bruce Momjian 已提交
3219 3220
	if (!AH->readHeader)
	{
3221
		if ((*AH->ReadBufPtr) (AH, tmpMag, 5) != 5)
3222
			exit_horribly(modulename, "unexpected end of file\n");
B
Bruce Momjian 已提交
3223

B
Bruce Momjian 已提交
3224
		if (strncmp(tmpMag, "PGDMP", 5) != 0)
3225
			exit_horribly(modulename, "did not find magic string in file header\n");
B
Bruce Momjian 已提交
3226

B
Bruce Momjian 已提交
3227 3228
		AH->vmaj = (*AH->ReadBytePtr) (AH);
		AH->vmin = (*AH->ReadBytePtr) (AH);
B
Bruce Momjian 已提交
3229

B
Bruce Momjian 已提交
3230 3231 3232
		if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0)))		/* Version > 1.0 */
			AH->vrev = (*AH->ReadBytePtr) (AH);
		else
3233
			AH->vrev = 0;
B
Bruce Momjian 已提交
3234

B
Bruce Momjian 已提交
3235
		AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
B
Bruce Momjian 已提交
3236

3237
		if (AH->version < K_VERS_1_0 || AH->version > K_VERS_MAX)
3238 3239
			exit_horribly(modulename, "unsupported version (%d.%d) in file header\n",
						  AH->vmaj, AH->vmin);
B
Bruce Momjian 已提交
3240

B
Bruce Momjian 已提交
3241
		AH->intSize = (*AH->ReadBytePtr) (AH);
3242
		if (AH->intSize > 32)
3243 3244
			exit_horribly(modulename, "sanity check on integer size (%lu) failed\n",
						  (unsigned long) AH->intSize);
B
Bruce Momjian 已提交
3245

3246
		if (AH->intSize > sizeof(int))
3247
			write_msg(modulename, "WARNING: archive was made on a machine with larger integers, some operations might fail\n");
B
Bruce Momjian 已提交
3248

3249
		if (AH->version >= K_VERS_1_7)
B
Bruce Momjian 已提交
3250
			AH->offSize = (*AH->ReadBytePtr) (AH);
3251
		else
B
Bruce Momjian 已提交
3252
			AH->offSize = AH->intSize;
3253

B
Bruce Momjian 已提交
3254
		fmt = (*AH->ReadBytePtr) (AH);
B
Bruce Momjian 已提交
3255

3256
		if (AH->format != fmt)
3257 3258
			exit_horribly(modulename, "expected format (%d) differs from format found in file (%d)\n",
						  AH->format, fmt);
B
Bruce Momjian 已提交
3259
	}
B
Bruce Momjian 已提交
3260

B
Bruce Momjian 已提交
3261 3262
	if (AH->version >= K_VERS_1_2)
	{
3263
		if (AH->version < K_VERS_1_4)
B
Bruce Momjian 已提交
3264
			AH->compression = (*AH->ReadBytePtr) (AH);
3265 3266
		else
			AH->compression = ReadInt(AH);
B
Bruce Momjian 已提交
3267 3268
	}
	else
3269
		AH->compression = Z_DEFAULT_COMPRESSION;
B
Bruce Momjian 已提交
3270

3271
#ifndef HAVE_LIBZ
B
Bruce Momjian 已提交
3272
	if (AH->compression != 0)
3273
		write_msg(modulename, "WARNING: archive is compressed, but this installation does not support compression -- no data will be available\n");
B
Bruce Momjian 已提交
3274 3275
#endif

3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289
	if (AH->version >= K_VERS_1_4)
	{
		crtm.tm_sec = ReadInt(AH);
		crtm.tm_min = ReadInt(AH);
		crtm.tm_hour = ReadInt(AH);
		crtm.tm_mday = ReadInt(AH);
		crtm.tm_mon = ReadInt(AH);
		crtm.tm_year = ReadInt(AH);
		crtm.tm_isdst = ReadInt(AH);

		AH->archdbname = ReadStr(AH);

		AH->createDate = mktime(&crtm);

B
Bruce Momjian 已提交
3290
		if (AH->createDate == (time_t) -1)
3291
			write_msg(modulename, "WARNING: invalid creation date in header\n");
3292 3293
	}

3294 3295 3296 3297 3298
	if (AH->version >= K_VERS_1_10)
	{
		AH->archiveRemoteVersion = ReadStr(AH);
		AH->archiveDumpVersion = ReadStr(AH);
	}
B
Bruce Momjian 已提交
3299 3300 3301
}


3302 3303
/*
 * checkSeek
3304
 *	  check to see if ftell/fseek can be performed.
3305 3306 3307 3308
 */
bool
checkSeek(FILE *fp)
{
3309 3310 3311
	pgoff_t		tpos;

	/*
B
Bruce Momjian 已提交
3312 3313
	 * If pgoff_t is wider than long, we must have "real" fseeko and not an
	 * emulation using fseek.  Otherwise report no seek capability.
3314 3315 3316
	 */
#ifndef HAVE_FSEEKO
	if (sizeof(pgoff_t) > sizeof(long))
3317 3318
		return false;
#endif
3319 3320 3321 3322 3323 3324 3325 3326

	/* Check that ftello works on this file */
	errno = 0;
	tpos = ftello(fp);
	if (errno)
		return false;

	/*
B
Bruce Momjian 已提交
3327
	 * Check that fseeko(SEEK_SET) works, too.	NB: we used to try to test
3328 3329 3330 3331 3332 3333 3334
	 * this with fseeko(fp, 0, SEEK_CUR).  But some platforms treat that as a
	 * successful no-op even on files that are otherwise unseekable.
	 */
	if (fseeko(fp, tpos, SEEK_SET) != 0)
		return false;

	return true;
3335
}
3336 3337 3338 3339 3340 3341 3342 3343 3344 3345


/*
 * dumpTimestamp
 */
static void
dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim)
{
	char		buf[256];

3346 3347 3348
	/*
	 * We don't print the timezone on Win32, because the names are long and
	 * localized, which means they may contain characters in various random
B
Bruce Momjian 已提交
3349 3350
	 * encodings; this has been seen to cause encoding errors when reading the
	 * dump script.
3351 3352 3353 3354 3355 3356 3357 3358
	 */
	if (strftime(buf, sizeof(buf),
#ifndef WIN32
				 "%Y-%m-%d %H:%M:%S %Z",
#else
				 "%Y-%m-%d %H:%M:%S",
#endif
				 localtime(&tim)) != 0)
3359 3360
		ahprintf(AH, "-- %s %s\n\n", msg, buf);
}
3361

3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386
static void
setProcessIdentifier(ParallelStateEntry *pse, ArchiveHandle *AH)
{
#ifdef WIN32
	pse->threadId = GetCurrentThreadId();
#else
	pse->pid = getpid();
#endif
	pse->AH = AH;
}

static void
unsetProcessIdentifier(ParallelStateEntry *pse)
{
#ifdef WIN32
	pse->threadId = 0;
#else
	pse->pid = 0;
#endif
	pse->AH = NULL;
}

static ParallelStateEntry *
GetMyPSEntry(ParallelState *pstate)
{
3387
	int			i;
3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421

	for (i = 0; i < pstate->numWorkers; i++)
#ifdef WIN32
		if (pstate->pse[i].threadId == GetCurrentThreadId())
#else
		if (pstate->pse[i].pid == getpid())
#endif
			return &(pstate->pse[i]);

	return NULL;
}

static void
archive_close_connection(int code, void *arg)
{
	ShutdownInformation *si = (ShutdownInformation *) arg;

	if (si->pstate)
	{
		ParallelStateEntry *entry = GetMyPSEntry(si->pstate);

		if (entry != NULL && entry->AH)
			DisconnectDatabase(&(entry->AH->public));
	}
	else if (si->AHX)
		DisconnectDatabase(si->AHX);
}

void
on_exit_close_archive(Archive *AHX)
{
	shutdown_info.AHX = AHX;
	on_exit_nicely(archive_close_connection, &shutdown_info);
}
3422 3423 3424 3425 3426

/*
 * Main engine for parallel restore.
 *
 * Work is done in three phases.
3427
 * First we process all SECTION_PRE_DATA tocEntries, in a single connection,
3428
 * just as for a standard restore.	Second we process the remaining non-ACL
3429 3430 3431 3432
 * steps in parallel worker children (threads on Windows, processes on Unix),
 * each of which connects separately to the database.  Finally we process all
 * the ACL entries in a single connection (that happens back in
 * RestoreArchive).
3433 3434 3435 3436 3437
 */
static void
restore_toc_entries_parallel(ArchiveHandle *AH)
{
	RestoreOptions *ropt = AH->ropt;
3438
	int			n_slots = ropt->number_of_jobs;
3439 3440 3441
	ParallelSlot *slots;
	int			work_status;
	int			next_slot;
3442
	bool		skipped_some;
3443 3444
	TocEntry	pending_list;
	TocEntry	ready_list;
3445 3446 3447
	TocEntry   *next_work_item;
	thandle		ret_child;
	TocEntry   *te;
3448 3449
	ParallelState *pstate;
	int			i;
3450

3451
	ahlog(AH, 2, "entering restore_toc_entries_parallel\n");
3452

3453 3454 3455 3456 3457 3458
	slots = (ParallelSlot *) pg_calloc(n_slots, sizeof(ParallelSlot));
	pstate = (ParallelState *) pg_malloc(sizeof(ParallelState));
	pstate->pse = (ParallelStateEntry *) pg_calloc(n_slots, sizeof(ParallelStateEntry));
	pstate->numWorkers = ropt->number_of_jobs;
	for (i = 0; i < pstate->numWorkers; i++)
		unsetProcessIdentifier(&(pstate->pse[i]));
3459 3460 3461 3462 3463

	/* Adjust dependency information */
	fix_dependencies(AH);

	/*
3464 3465 3466
	 * Do all the early stuff in a single connection in the parent. There's no
	 * great point in running it in parallel, in fact it will actually run
	 * faster in a single connection because we avoid all the connection and
3467 3468 3469
	 * setup overhead.	Also, pg_dump is not currently very good about showing
	 * all the dependencies of SECTION_PRE_DATA items, so we do not risk
	 * trying to process them out-of-order.
3470
	 */
3471
	skipped_some = false;
3472
	for (next_work_item = AH->toc->next; next_work_item != AH->toc; next_work_item = next_work_item->next)
3473
	{
3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495
		/* NB: process-or-continue logic must be the inverse of loop below */
		if (next_work_item->section != SECTION_PRE_DATA)
		{
			/* DATA and POST_DATA items are just ignored for now */
			if (next_work_item->section == SECTION_DATA ||
				next_work_item->section == SECTION_POST_DATA)
			{
				skipped_some = true;
				continue;
			}
			else
			{
				/*
				 * SECTION_NONE items, such as comments, can be processed now
				 * if we are still in the PRE_DATA part of the archive.  Once
				 * we've skipped any items, we have to consider whether the
				 * comment's dependencies are satisfied, so skip it for now.
				 */
				if (skipped_some)
					continue;
			}
		}
3496 3497 3498 3499 3500 3501 3502

		ahlog(AH, 1, "processing item %d %s %s\n",
			  next_work_item->dumpId,
			  next_work_item->desc, next_work_item->tag);

		(void) restore_toc_entry(AH, next_work_item, ropt, false);

3503 3504
		/* there should be no touch of ready_list here, so pass NULL */
		reduce_dependencies(AH, next_work_item, NULL);
3505 3506 3507
	}

	/*
3508
	 * Now close parent connection in prep for parallel steps.	We do this
3509 3510 3511
	 * mainly to ensure that we don't exceed the specified number of parallel
	 * connections.
	 */
R
Robert Haas 已提交
3512
	DisconnectDatabase(&AH->public);
3513

3514
	/*
3515 3516
	 * Set the pstate in the shutdown_info. The exit handler uses pstate if
	 * set and falls back to AHX otherwise.
3517 3518 3519
	 */
	shutdown_info.pstate = pstate;

3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531
	/* blow away any transient state from the old connection */
	if (AH->currUser)
		free(AH->currUser);
	AH->currUser = NULL;
	if (AH->currSchema)
		free(AH->currSchema);
	AH->currSchema = NULL;
	if (AH->currTablespace)
		free(AH->currTablespace);
	AH->currTablespace = NULL;
	AH->currWithOids = -1;

3532
	/*
B
Bruce Momjian 已提交
3533 3534 3535 3536 3537 3538 3539
	 * Initialize the lists of pending and ready items.  After this setup, the
	 * pending list is everything that needs to be done but is blocked by one
	 * or more dependencies, while the ready list contains items that have no
	 * remaining dependencies.	Note: we don't yet filter out entries that
	 * aren't going to be restored.  They might participate in dependency
	 * chains connecting entries that should be restored, so we treat them as
	 * live until we actually process them.
3540 3541 3542
	 */
	par_list_header_init(&pending_list);
	par_list_header_init(&ready_list);
3543
	skipped_some = false;
3544
	for (next_work_item = AH->toc->next; next_work_item != AH->toc; next_work_item = next_work_item->next)
3545
	{
3546 3547 3548 3549 3550 3551
		/* NB: process-or-continue logic must be the inverse of loop above */
		if (next_work_item->section == SECTION_PRE_DATA)
		{
			/* All PRE_DATA items were dealt with above */
			continue;
		}
3552 3553 3554
		if (next_work_item->section == SECTION_DATA ||
			next_work_item->section == SECTION_POST_DATA)
		{
3555 3556
			/* set this flag at same point that previous loop did */
			skipped_some = true;
3557
		}
3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568
		else
		{
			/* SECTION_NONE items must be processed if previous loop didn't */
			if (!skipped_some)
				continue;
		}

		if (next_work_item->depCount > 0)
			par_list_append(&pending_list, next_work_item);
		else
			par_list_append(&ready_list, next_work_item);
3569 3570
	}

3571 3572 3573 3574 3575 3576 3577
	/*
	 * main parent loop
	 *
	 * Keep going until there is no worker still running AND there is no work
	 * left to be done.
	 */

3578
	ahlog(AH, 1, "entering main parallel loop\n");
3579

3580
	while ((next_work_item = get_next_work_item(AH, &ready_list,
3581 3582 3583 3584 3585
												slots, n_slots)) != NULL ||
		   work_in_progress(slots, n_slots))
	{
		if (next_work_item != NULL)
		{
3586 3587 3588
			/* If not to be restored, don't waste time launching a worker */
			if ((next_work_item->reqs & (REQ_SCHEMA | REQ_DATA)) == 0 ||
				_tocEntryIsACL(next_work_item))
3589 3590 3591 3592 3593
			{
				ahlog(AH, 1, "skipping item %d %s %s\n",
					  next_work_item->dumpId,
					  next_work_item->desc, next_work_item->tag);

3594 3595
				par_list_remove(next_work_item);
				reduce_dependencies(AH, next_work_item, &ready_list);
3596 3597 3598 3599 3600 3601 3602

				continue;
			}

			if ((next_slot = get_next_slot(slots, n_slots)) != NO_SLOT)
			{
				/* There is work still to do and a worker slot available */
3603
				thandle		child;
3604 3605 3606 3607 3608 3609
				RestoreArgs *args;

				ahlog(AH, 1, "launching item %d %s %s\n",
					  next_work_item->dumpId,
					  next_work_item->desc, next_work_item->tag);

3610
				par_list_remove(next_work_item);
3611 3612

				/* this memory is dealloced in mark_work_done() */
3613
				args = pg_malloc(sizeof(RestoreArgs));
3614 3615
				args->AH = CloneArchive(AH);
				args->te = next_work_item;
3616
				args->pse = &pstate->pse[next_slot];
3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637

				/* run the step in a worker child */
				child = spawn_restore(args);

				slots[next_slot].child_id = child;
				slots[next_slot].args = args;

				continue;
			}
		}

		/*
		 * If we get here there must be work being done.  Either there is no
		 * work available to schedule (and work_in_progress returned true) or
		 * there are no slots available.  So we wait for a worker to finish,
		 * and process the result.
		 */
		ret_child = reap_child(slots, n_slots, &work_status);

		if (WIFEXITED(work_status))
		{
3638 3639
			mark_work_done(AH, &ready_list,
						   ret_child, WEXITSTATUS(work_status),
3640 3641 3642 3643
						   slots, n_slots);
		}
		else
		{
3644 3645
			exit_horribly(modulename, "worker process crashed: status %d\n",
						  work_status);
3646 3647 3648
		}
	}

3649
	ahlog(AH, 1, "finished main parallel loop\n");
3650

3651 3652 3653 3654 3655 3656
	/*
	 * Remove the pstate again, so the exit handler will now fall back to
	 * closing AH->connection again.
	 */
	shutdown_info.pstate = NULL;

3657 3658 3659 3660 3661
	/*
	 * Now reconnect the single parent connection.
	 */
	ConnectDatabase((Archive *) AH, ropt->dbname,
					ropt->pghost, ropt->pgport, ropt->username,
3662
					ropt->promptPassword);
3663 3664 3665 3666

	_doSetFixedOutputState(AH);

	/*
3667 3668 3669
	 * Make sure there is no non-ACL work left due to, say, circular
	 * dependencies, or some other pathological condition. If so, do it in the
	 * single parent connection.
3670
	 */
3671
	for (te = pending_list.par_next; te != &pending_list; te = te->par_next)
3672
	{
3673 3674 3675
		ahlog(AH, 1, "processing missed item %d %s %s\n",
			  te->dumpId, te->desc, te->tag);
		(void) restore_toc_entry(AH, te, ropt, false);
3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686
	}

	/* The ACLs will be handled back in RestoreArchive. */
}

/*
 * create a worker child to perform a restore step in parallel
 */
static thandle
spawn_restore(RestoreArgs *args)
{
3687
	thandle		child;
3688 3689 3690 3691 3692 3693 3694 3695 3696 3697

	/* Ensure stdio state is quiesced before forking */
	fflush(NULL);

#ifndef WIN32
	child = fork();
	if (child == 0)
	{
		/* in child process */
		parallel_restore(args);
3698 3699
		exit_horribly(modulename,
					  "parallel_restore should not return\n");
3700 3701 3702 3703
	}
	else if (child < 0)
	{
		/* fork failed */
3704 3705 3706
		exit_horribly(modulename,
					  "could not create worker process: %s\n",
					  strerror(errno));
3707 3708 3709 3710 3711
	}
#else
	child = (HANDLE) _beginthreadex(NULL, 0, (void *) parallel_restore,
									args, 0, NULL);
	if (child == 0)
3712 3713 3714
		exit_horribly(modulename,
					  "could not create worker thread: %s\n",
					  strerror(errno));
3715 3716 3717 3718 3719 3720
#endif

	return child;
}

/*
3721
 *	collect status from a completed worker child
3722 3723 3724 3725 3726 3727 3728 3729 3730
 */
static thandle
reap_child(ParallelSlot *slots, int n_slots, int *work_status)
{
#ifndef WIN32
	/* Unix is so much easier ... */
	return wait(work_status);
#else
	static HANDLE *handles = NULL;
3731 3732 3733 3734 3735
	int			hindex,
				snum,
				tnum;
	thandle		ret_child;
	DWORD		res;
3736 3737 3738

	/* first time around only, make space for handles to listen on */
	if (handles == NULL)
3739
		handles = (HANDLE *) pg_calloc(sizeof(HANDLE), n_slots);
3740 3741

	/* set up list of handles to listen to */
3742
	for (snum = 0, tnum = 0; snum < n_slots; snum++)
3743 3744 3745 3746 3747 3748 3749 3750 3751 3752
		if (slots[snum].child_id != 0)
			handles[tnum++] = slots[snum].child_id;

	/* wait for one to finish */
	hindex = WaitForMultipleObjects(tnum, handles, false, INFINITE);

	/* get handle of finished thread */
	ret_child = handles[hindex - WAIT_OBJECT_0];

	/* get the result */
3753
	GetExitCodeThread(ret_child, &res);
3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768
	*work_status = res;

	/* dispose of handle to stop leaks */
	CloseHandle(ret_child);

	return ret_child;
#endif
}

/*
 * are we doing anything now?
 */
static bool
work_in_progress(ParallelSlot *slots, int n_slots)
{
3769
	int			i;
3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784

	for (i = 0; i < n_slots; i++)
	{
		if (slots[i].child_id != 0)
			return true;
	}
	return false;
}

/*
 * find the first free parallel slot (if any).
 */
static int
get_next_slot(ParallelSlot *slots, int n_slots)
{
3785
	int			i;
3786 3787 3788 3789 3790 3791 3792 3793 3794

	for (i = 0; i < n_slots; i++)
	{
		if (slots[i].child_id == 0)
			return i;
	}
	return NO_SLOT;
}

3795 3796 3797 3798 3799 3800 3801 3802

/*
 * Check if te1 has an exclusive lock requirement for an item that te2 also
 * requires, whether or not te2's requirement is for an exclusive lock.
 */
static bool
has_lock_conflicts(TocEntry *te1, TocEntry *te2)
{
3803 3804
	int			j,
				k;
3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817

	for (j = 0; j < te1->nLockDeps; j++)
	{
		for (k = 0; k < te2->nDeps; k++)
		{
			if (te1->lockDeps[j] == te2->dependencies[k])
				return true;
		}
	}
	return false;
}


3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850
/*
 * Initialize the header of a parallel-processing list.
 *
 * These are circular lists with a dummy TocEntry as header, just like the
 * main TOC list; but we use separate list links so that an entry can be in
 * the main TOC list as well as in a parallel-processing list.
 */
static void
par_list_header_init(TocEntry *l)
{
	l->par_prev = l->par_next = l;
}

/* Append te to the end of the parallel-processing list headed by l */
static void
par_list_append(TocEntry *l, TocEntry *te)
{
	te->par_prev = l->par_prev;
	l->par_prev->par_next = te;
	l->par_prev = te;
	te->par_next = l;
}

/* Remove te from whatever parallel-processing list it's in */
static void
par_list_remove(TocEntry *te)
{
	te->par_prev->par_next = te->par_next;
	te->par_next->par_prev = te->par_prev;
	te->par_prev = NULL;
	te->par_next = NULL;
}

3851

3852 3853 3854 3855
/*
 * Find the next work item (if any) that is capable of being run now.
 *
 * To qualify, the item must have no remaining dependencies
3856 3857 3858
 * and no requirements for locks that are incompatible with
 * items currently running.  Items in the ready_list are known to have
 * no remaining dependencies, but we have to check for lock conflicts.
3859
 *
3860 3861
 * Note that the returned item has *not* been removed from ready_list.
 * The caller must do that after successfully dispatching the item.
3862 3863 3864 3865 3866 3867
 *
 * pref_non_data is for an alternative selection algorithm that gives
 * preference to non-data items if there is already a data load running.
 * It is currently disabled.
 */
static TocEntry *
3868
get_next_work_item(ArchiveHandle *AH, TocEntry *ready_list,
3869 3870
				   ParallelSlot *slots, int n_slots)
{
3871 3872 3873 3874 3875
	bool		pref_non_data = false;	/* or get from AH->ropt */
	TocEntry   *data_te = NULL;
	TocEntry   *te;
	int			i,
				k;
3876 3877 3878 3879 3880 3881

	/*
	 * Bogus heuristics for pref_non_data
	 */
	if (pref_non_data)
	{
3882
		int			count = 0;
3883

3884
		for (k = 0; k < n_slots; k++)
3885 3886 3887 3888 3889 3890 3891 3892
			if (slots[k].args->te != NULL &&
				slots[k].args->te->section == SECTION_DATA)
				count++;
		if (n_slots == 0 || count * 4 < n_slots)
			pref_non_data = false;
	}

	/*
3893
	 * Search the ready_list until we find a suitable item.
3894
	 */
3895
	for (te = ready_list->par_next; te != ready_list; te = te->par_next)
3896
	{
3897
		bool		conflicts = false;
3898 3899 3900

		/*
		 * Check to see if the item would need exclusive lock on something
3901 3902
		 * that a currently running item also needs lock on, or vice versa. If
		 * so, we don't want to schedule them together.
3903 3904 3905
		 */
		for (i = 0; i < n_slots && !conflicts; i++)
		{
3906
			TocEntry   *running_te;
3907 3908 3909 3910

			if (slots[i].args == NULL)
				continue;
			running_te = slots[i].args->te;
3911 3912 3913

			if (has_lock_conflicts(te, running_te) ||
				has_lock_conflicts(running_te, te))
3914
			{
3915 3916
				conflicts = true;
				break;
3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936
			}
		}

		if (conflicts)
			continue;

		if (pref_non_data && te->section == SECTION_DATA)
		{
			if (data_te == NULL)
				data_te = te;
			continue;
		}

		/* passed all tests, so this item can run */
		return te;
	}

	if (data_te != NULL)
		return data_te;

3937
	ahlog(AH, 2, "no item ready\n");
3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951
	return NULL;
}


/*
 * Restore a single TOC item in parallel with others
 *
 * this is the procedure run as a thread (Windows) or a
 * separate process (everything else).
 */
static parallel_restore_result
parallel_restore(RestoreArgs *args)
{
	ArchiveHandle *AH = args->AH;
3952
	TocEntry   *te = args->te;
3953
	RestoreOptions *ropt = AH->ropt;
3954
	int			retval;
3955

3956 3957
	setProcessIdentifier(args->pse, AH);

3958
	/*
3959 3960 3961 3962
	 * Close and reopen the input file so we have a private file pointer that
	 * doesn't stomp on anyone else's file pointer, if we're actually going to
	 * need to read from the file. Otherwise, just close it except on Windows,
	 * where it will possibly be needed by other threads.
3963
	 *
3964 3965
	 * Note: on Windows, since we are using threads not processes, the reopen
	 * call *doesn't* close the original file pointer but just open a new one.
3966
	 */
3967
	if (te->section == SECTION_DATA)
3968 3969 3970 3971 3972
		(AH->ReopenPtr) (AH);
#ifndef WIN32
	else
		(AH->ClosePtr) (AH);
#endif
3973 3974 3975 3976 3977 3978

	/*
	 * We need our own database connection, too
	 */
	ConnectDatabase((Archive *) AH, ropt->dbname,
					ropt->pghost, ropt->pgport, ropt->username,
3979
					ropt->promptPassword);
3980 3981 3982 3983 3984 3985 3986

	_doSetFixedOutputState(AH);

	/* Restore the TOC item */
	retval = restore_toc_entry(AH, te, ropt, true);

	/* And clean up */
R
Robert Haas 已提交
3987
	DisconnectDatabase((Archive *) AH);
3988
	unsetProcessIdentifier(args->pse);
3989

3990
	/* If we reopened the file, we are done with it, so close it now */
3991
	if (te->section == SECTION_DATA)
3992
		(AH->ClosePtr) (AH);
3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011

	if (retval == 0 && AH->public.n_errors)
		retval = WORKER_IGNORED_ERRORS;

#ifndef WIN32
	exit(retval);
#else
	return retval;
#endif
}


/*
 * Housekeeping to be done after a step has been parallel restored.
 *
 * Clear the appropriate slot, free all the extra memory we allocated,
 * update status, and reduce the dependency count of any dependent items.
 */
static void
4012 4013
mark_work_done(ArchiveHandle *AH, TocEntry *ready_list,
			   thandle worker, int status,
4014 4015
			   ParallelSlot *slots, int n_slots)
{
4016 4017
	TocEntry   *te = NULL;
	int			i;
4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033

	for (i = 0; i < n_slots; i++)
	{
		if (slots[i].child_id == worker)
		{
			slots[i].child_id = 0;
			te = slots[i].args->te;
			DeCloneArchive(slots[i].args->AH);
			free(slots[i].args);
			slots[i].args = NULL;

			break;
		}
	}

	if (te == NULL)
4034
		exit_horribly(modulename, "could not find slot of finished worker\n");
4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048

	ahlog(AH, 1, "finished item %d %s %s\n",
		  te->dumpId, te->desc, te->tag);

	if (status == WORKER_CREATE_DONE)
		mark_create_done(AH, te);
	else if (status == WORKER_INHIBIT_DATA)
	{
		inhibit_data_for_failed_table(AH, te);
		AH->public.n_errors++;
	}
	else if (status == WORKER_IGNORED_ERRORS)
		AH->public.n_errors++;
	else if (status != 0)
4049 4050
		exit_horribly(modulename, "worker process failed: exit code %d\n",
					  status);
4051

4052
	reduce_dependencies(AH, te, ready_list);
4053 4054 4055 4056 4057 4058
}


/*
 * Process the dependency information into a form useful for parallel restore.
 *
4059 4060 4061
 * This function takes care of fixing up some missing or badly designed
 * dependencies, and then prepares subsidiary data structures that will be
 * used in the main parallel-restore logic, including:
4062 4063
 * 1. We build the revDeps[] arrays of incoming dependency dumpIds.
 * 2. We set up depCount fields that are the number of as-yet-unprocessed
4064 4065 4066 4067 4068 4069 4070 4071 4072
 * dependencies for each TOC entry.
 *
 * We also identify locking dependencies so that we can avoid trying to
 * schedule conflicting items at the same time.
 */
static void
fix_dependencies(ArchiveHandle *AH)
{
	TocEntry   *te;
4073
	int			i;
4074 4075

	/*
4076 4077
	 * Initialize the depCount/revDeps/nRevDeps fields, and make sure the TOC
	 * items are marked as not being in any parallel-processing list.
4078 4079 4080 4081
	 */
	for (te = AH->toc->next; te != AH->toc; te = te->next)
	{
		te->depCount = te->nDeps;
4082 4083
		te->revDeps = NULL;
		te->nRevDeps = 0;
4084 4085
		te->par_prev = NULL;
		te->par_next = NULL;
4086 4087 4088 4089 4090
	}

	/*
	 * POST_DATA items that are shown as depending on a table need to be
	 * re-pointed to depend on that table's data, instead.  This ensures they
4091
	 * won't get scheduled until the data has been loaded.
4092
	 */
4093
	repoint_table_dependencies(AH);
4094 4095

	/*
4096 4097 4098
	 * Pre-8.4 versions of pg_dump neglected to set up a dependency from BLOB
	 * COMMENTS to BLOBS.  Cope.  (We assume there's only one BLOBS and only
	 * one BLOB COMMENTS in such files.)
4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111
	 */
	if (AH->version < K_VERS_1_11)
	{
		for (te = AH->toc->next; te != AH->toc; te = te->next)
		{
			if (strcmp(te->desc, "BLOB COMMENTS") == 0 && te->nDeps == 0)
			{
				TocEntry   *te2;

				for (te2 = AH->toc->next; te2 != AH->toc; te2 = te2->next)
				{
					if (strcmp(te2->desc, "BLOBS") == 0)
					{
4112
						te->dependencies = (DumpId *) pg_malloc(sizeof(DumpId));
4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124
						te->dependencies[0] = te2->dumpId;
						te->nDeps++;
						te->depCount++;
						break;
					}
				}
				break;
			}
		}
	}

	/*
4125 4126 4127 4128 4129 4130
	 * At this point we start to build the revDeps reverse-dependency arrays,
	 * so all changes of dependencies must be complete.
	 */

	/*
	 * Count the incoming dependencies for each item.  Also, it is possible
4131 4132
	 * that the dependencies list items that are not in the archive at all.
	 * Subtract such items from the depCounts.
4133 4134 4135 4136 4137
	 */
	for (te = AH->toc->next; te != AH->toc; te = te->next)
	{
		for (i = 0; i < te->nDeps; i++)
		{
4138 4139
			DumpId		depid = te->dependencies[i];

4140 4141
			if (depid <= AH->maxDumpId && AH->tocsByDumpId[depid] != NULL)
				AH->tocsByDumpId[depid]->nRevDeps++;
4142
			else
4143 4144 4145 4146
				te->depCount--;
		}
	}

4147
	/*
4148 4149
	 * Allocate space for revDeps[] arrays, and reset nRevDeps so we can use
	 * it as a counter below.
4150 4151 4152 4153
	 */
	for (te = AH->toc->next; te != AH->toc; te = te->next)
	{
		if (te->nRevDeps > 0)
4154
			te->revDeps = (DumpId *) pg_malloc(te->nRevDeps * sizeof(DumpId));
4155 4156 4157 4158
		te->nRevDeps = 0;
	}

	/*
4159 4160
	 * Build the revDeps[] arrays of incoming-dependency dumpIds.  This had
	 * better agree with the loops above.
4161 4162 4163 4164 4165 4166 4167
	 */
	for (te = AH->toc->next; te != AH->toc; te = te->next)
	{
		for (i = 0; i < te->nDeps; i++)
		{
			DumpId		depid = te->dependencies[i];

4168
			if (depid <= AH->maxDumpId && AH->tocsByDumpId[depid] != NULL)
4169
			{
4170
				TocEntry   *otherte = AH->tocsByDumpId[depid];
4171 4172 4173 4174 4175 4176

				otherte->revDeps[otherte->nRevDeps++] = te->dumpId;
			}
		}
	}

4177 4178 4179 4180 4181 4182 4183
	/*
	 * Lastly, work out the locking dependencies.
	 */
	for (te = AH->toc->next; te != AH->toc; te = te->next)
	{
		te->lockDeps = NULL;
		te->nLockDeps = 0;
4184
		identify_locking_dependencies(AH, te);
4185 4186 4187 4188
	}
}

/*
4189
 * Change dependencies on table items to depend on table data items instead,
4190 4191 4192
 * but only in POST_DATA items.
 */
static void
4193
repoint_table_dependencies(ArchiveHandle *AH)
4194 4195
{
	TocEntry   *te;
4196
	int			i;
4197
	DumpId		olddep;
4198 4199 4200 4201 4202 4203 4204

	for (te = AH->toc->next; te != AH->toc; te = te->next)
	{
		if (te->section != SECTION_POST_DATA)
			continue;
		for (i = 0; i < te->nDeps; i++)
		{
4205 4206 4207
			olddep = te->dependencies[i];
			if (olddep <= AH->maxDumpId &&
				AH->tableDataId[olddep] != 0)
4208
			{
4209
				te->dependencies[i] = AH->tableDataId[olddep];
4210
				ahlog(AH, 2, "transferring dependency %d -> %d to %d\n",
4211
					  te->dumpId, olddep, AH->tableDataId[olddep]);
4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222
			}
		}
	}
}

/*
 * Identify which objects we'll need exclusive lock on in order to restore
 * the given TOC entry (*other* than the one identified by the TOC entry
 * itself).  Record their dump IDs in the entry's lockDeps[] array.
 */
static void
4223
identify_locking_dependencies(ArchiveHandle *AH, TocEntry *te)
4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241
{
	DumpId	   *lockids;
	int			nlockids;
	int			i;

	/* Quick exit if no dependencies at all */
	if (te->nDeps == 0)
		return;

	/* Exit if this entry doesn't need exclusive lock on other objects */
	if (!(strcmp(te->desc, "CONSTRAINT") == 0 ||
		  strcmp(te->desc, "CHECK CONSTRAINT") == 0 ||
		  strcmp(te->desc, "FK CONSTRAINT") == 0 ||
		  strcmp(te->desc, "RULE") == 0 ||
		  strcmp(te->desc, "TRIGGER") == 0))
		return;

	/*
4242
	 * We assume the item requires exclusive lock on each TABLE DATA item
4243 4244 4245 4246
	 * listed among its dependencies.  (This was originally a dependency on
	 * the TABLE, but fix_dependencies repointed it to the data item. Note
	 * that all the entry types we are interested in here are POST_DATA, so
	 * they will all have been changed this way.)
4247
	 */
4248
	lockids = (DumpId *) pg_malloc(te->nDeps * sizeof(DumpId));
4249 4250 4251
	nlockids = 0;
	for (i = 0; i < te->nDeps; i++)
	{
4252
		DumpId		depid = te->dependencies[i];
4253

4254 4255
		if (depid <= AH->maxDumpId && AH->tocsByDumpId[depid] != NULL &&
			strcmp(AH->tocsByDumpId[depid]->desc, "TABLE DATA") == 0)
4256 4257 4258 4259 4260 4261 4262 4263 4264
			lockids[nlockids++] = depid;
	}

	if (nlockids == 0)
	{
		free(lockids);
		return;
	}

T
Tom Lane 已提交
4265
	te->lockDeps = pg_realloc(lockids, nlockids * sizeof(DumpId));
4266 4267 4268 4269 4270
	te->nLockDeps = nlockids;
}

/*
 * Remove the specified TOC entry from the depCounts of items that depend on
4271 4272
 * it, thereby possibly making them ready-to-run.  Any pending item that
 * becomes ready should be moved to the ready list.
4273 4274
 */
static void
4275
reduce_dependencies(ArchiveHandle *AH, TocEntry *te, TocEntry *ready_list)
4276
{
4277
	int			i;
4278

4279
	ahlog(AH, 2, "reducing dependencies for %d\n", te->dumpId);
4280

4281
	for (i = 0; i < te->nRevDeps; i++)
4282
	{
4283
		TocEntry   *otherte = AH->tocsByDumpId[te->revDeps[i]];
4284 4285 4286

		otherte->depCount--;
		if (otherte->depCount == 0 && otherte->par_prev != NULL)
4287
		{
4288 4289 4290 4291
			/* It must be in the pending list, so remove it ... */
			par_list_remove(otherte);
			/* ... and add to ready_list */
			par_list_append(ready_list, otherte);
4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302
		}
	}
}

/*
 * Set the created flag on the DATA member corresponding to the given
 * TABLE member
 */
static void
mark_create_done(ArchiveHandle *AH, TocEntry *te)
{
4303
	if (AH->tableDataId[te->dumpId] != 0)
4304
	{
4305 4306 4307
		TocEntry   *ted = AH->tocsByDumpId[AH->tableDataId[te->dumpId]];

		ted->created = true;
4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320
	}
}

/*
 * Mark the DATA member corresponding to the given TABLE member
 * as not wanted
 */
static void
inhibit_data_for_failed_table(ArchiveHandle *AH, TocEntry *te)
{
	ahlog(AH, 1, "table \"%s\" could not be created, will not restore its data\n",
		  te->tag);

4321
	if (AH->tableDataId[te->dumpId] != 0)
4322
	{
4323 4324 4325
		TocEntry   *ted = AH->tocsByDumpId[AH->tableDataId[te->dumpId]];

		ted->reqs = 0;
4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343
	}
}


/*
 * Clone and de-clone routines used in parallel restoration.
 *
 * Enough of the structure is cloned to ensure that there is no
 * conflict between different threads each with their own clone.
 *
 * These could be public, but no need at present.
 */
static ArchiveHandle *
CloneArchive(ArchiveHandle *AH)
{
	ArchiveHandle *clone;

	/* Make a "flat" copy */
4344
	clone = (ArchiveHandle *) pg_malloc(sizeof(ArchiveHandle));
4345 4346
	memcpy(clone, AH, sizeof(ArchiveHandle));

4347 4348
	/* Handle format-independent fields */
	memset(&(clone->sqlparse), 0, sizeof(clone->sqlparse));
4349 4350 4351 4352 4353 4354 4355 4356 4357 4358

	/* The clone will have its own connection, so disregard connection state */
	clone->connection = NULL;
	clone->currUser = NULL;
	clone->currSchema = NULL;
	clone->currTablespace = NULL;
	clone->currWithOids = -1;

	/* savedPassword must be local in case we change it while connecting */
	if (clone->savedPassword)
4359
		clone->savedPassword = pg_strdup(clone->savedPassword);
4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380

	/* clone has its own error count, too */
	clone->public.n_errors = 0;

	/* Let the format-specific code have a chance too */
	(clone->ClonePtr) (clone);

	return clone;
}

/*
 * Release clone-local storage.
 *
 * Note: we assume any clone-local connection was already closed.
 */
static void
DeCloneArchive(ArchiveHandle *AH)
{
	/* Clear format-specific state */
	(AH->DeClonePtr) (AH);

4381 4382 4383
	/* Clear state allocated by CloneArchive */
	if (AH->sqlparse.curCmd)
		destroyPQExpBuffer(AH->sqlparse.curCmd);
4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396

	/* Clear any connection-local state */
	if (AH->currUser)
		free(AH->currUser);
	if (AH->currSchema)
		free(AH->currSchema);
	if (AH->currTablespace)
		free(AH->currTablespace);
	if (AH->savedPassword)
		free(AH->savedPassword);

	free(AH);
}