pg_backup_archiver.c 60.2 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
 *		$PostgreSQL: pgsql/src/bin/pg_dump/pg_backup_archiver.c,v 1.124 2006/02/13 21:30:19 tgl Exp $
19
 *
B
Bruce Momjian 已提交
20 21 22 23
 *-------------------------------------------------------------------------
 */

#include "pg_backup.h"
24
#include "pg_dump.h"
B
Bruce Momjian 已提交
25
#include "pg_backup_archiver.h"
26
#include "pg_backup_db.h"
27
#include "dumputils.h"
28

29
#include <ctype.h>
30 31

#ifndef WIN32_CLIENT_ONLY
32
#include <unistd.h>
33
#endif
B
Bruce Momjian 已提交
34

35 36 37 38
#ifdef WIN32
#include <io.h>
#endif

39 40
#include "pqexpbuffer.h"
#include "libpq/libpq-fs.h"
41

42

43
const char *progname;
44

45 46 47
static char *modulename = gettext_noop("archiver");


B
Bruce Momjian 已提交
48 49
static ArchiveHandle *_allocAH(const char *FileSpec, const ArchiveFormat fmt,
		 const int compression, ArchiveMode mode);
50
static void _getObjectDescription(PQExpBuffer buf, TocEntry *te,
B
Bruce Momjian 已提交
51
					  ArchiveHandle *AH);
52
static void _printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass);
53

54

55
static void _doSetFixedOutputState(ArchiveHandle *AH);
56
static void _doSetSessionAuth(ArchiveHandle *AH, const char *user);
57
static void _doSetWithOids(ArchiveHandle *AH, const bool withOids);
58
static void _reconnectToDB(ArchiveHandle *AH, const char *dbname);
59 60
static void _becomeUser(ArchiveHandle *AH, const char *user);
static void _becomeOwner(ArchiveHandle *AH, TocEntry *te);
61
static void _selectOutputSchema(ArchiveHandle *AH, const char *schemaName);
62
static void _selectTablespace(ArchiveHandle *AH, const char *tablespace);
63

64
static teReqs _tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool include_acls);
B
Bruce Momjian 已提交
65 66
static void _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
static void _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
67
static TocEntry *getTocEntryByDumpId(ArchiveHandle *AH, DumpId id);
B
Bruce Momjian 已提交
68 69
static void _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te);
static int	_discoverArchiveFormat(ArchiveHandle *AH);
B
Bruce Momjian 已提交
70

71
static void dump_lo_buf(ArchiveHandle *AH);
72 73
static void _write_msg(const char *modulename, const char *fmt, va_list ap);
static void _die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap);
74

75 76
static void dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim);

77

B
Bruce Momjian 已提交
78
/*
B
Bruce Momjian 已提交
79 80 81 82
 *	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 已提交
83 84 85 86 87 88
 *
 */


/* Create a new archive */
/* Public */
89
Archive *
B
Bruce Momjian 已提交
90 91
CreateArchive(const char *FileSpec, const ArchiveFormat fmt,
			  const int compression)
92

B
Bruce Momjian 已提交
93
{
B
Bruce Momjian 已提交
94 95 96
	ArchiveHandle *AH = _allocAH(FileSpec, fmt, compression, archModeWrite);

	return (Archive *) AH;
B
Bruce Momjian 已提交
97 98 99 100
}

/* Open an existing archive */
/* Public */
101
Archive *
B
Bruce Momjian 已提交
102
OpenArchive(const char *FileSpec, const ArchiveFormat fmt)
B
Bruce Momjian 已提交
103
{
B
Bruce Momjian 已提交
104 105 106
	ArchiveHandle *AH = _allocAH(FileSpec, fmt, 0, archModeRead);

	return (Archive *) AH;
B
Bruce Momjian 已提交
107 108 109
}

/* Public */
B
Bruce Momjian 已提交
110 111
void
CloseArchive(Archive *AHX)
B
Bruce Momjian 已提交
112
{
B
Bruce Momjian 已提交
113 114 115 116
	int			res = 0;
	ArchiveHandle *AH = (ArchiveHandle *) AHX;

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

B
Bruce Momjian 已提交
118 119
	/* Close the output */
	if (AH->gzOut)
120
		res = GZCLOSE(AH->OF);
B
Bruce Momjian 已提交
121
	else if (AH->OF != stdout)
122 123 124
		res = fclose(AH->OF);

	if (res != 0)
125
		die_horribly(AH, modulename, "could not close output archive file\n");
B
Bruce Momjian 已提交
126 127 128
}

/* Public */
B
Bruce Momjian 已提交
129 130
void
RestoreArchive(Archive *AHX, RestoreOptions *ropt)
B
Bruce Momjian 已提交
131
{
B
Bruce Momjian 已提交
132
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
133
	TocEntry   *te;
134
	teReqs		reqs;
B
Bruce Momjian 已提交
135
	OutputContext sav;
136
	bool		defnDumped;
B
Bruce Momjian 已提交
137

138
	AH->ropt = ropt;
139
	AH->stage = STAGE_INITIALIZING;
140

141 142 143 144
	/*
	 * Check for nonsensical option combinations.
	 *
	 * NB: create+dropSchema is useless because if you're creating the DB,
B
Bruce Momjian 已提交
145 146 147
	 * 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...
148 149 150 151
	 */
	if (ropt->create && ropt->dropSchema)
		die_horribly(AH, modulename, "-C and -c are incompatible options\n");

152 153 154 155 156
	/*
	 * If we're using a DB connection, then connect it.
	 */
	if (ropt->useDB)
	{
157
		ahlog(AH, 1, "connecting to database for restore\n");
158
		if (AH->version < K_VERS_1_3)
159
			die_horribly(AH, modulename, "direct database connections are not supported in pre-1.3 archives\n");
160

161 162 163 164
		/* XXX Should get this from the archive */
		AHX->minRemoteVersion = 070100;
		AHX->maxRemoteVersion = 999999;

165 166
		ConnectDatabase(AHX, ropt->dbname,
						ropt->pghost, ropt->pgport, ropt->username,
B
Bruce Momjian 已提交
167
						ropt->requirePassword, ropt->ignoreVersion);
B
Bruce Momjian 已提交
168 169

		/*
B
Bruce Momjian 已提交
170 171
		 * If we're talking to the DB directly, don't send comments since they
		 * obscure SQL when displaying errors
B
Bruce Momjian 已提交
172
		 */
173
		AH->noTocComments = 1;
174 175
	}

176
	/*
B
Bruce Momjian 已提交
177 178 179 180
	 * 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.
181
	 *
B
Bruce Momjian 已提交
182
	 * We could scan for wanted TABLE entries, but that is not the same as
183
	 * dataOnly. At this stage, it seems unnecessary (6-Mar-2001).
B
Bruce Momjian 已提交
184 185 186
	 */
	if (!ropt->dataOnly)
	{
B
Bruce Momjian 已提交
187
		int			impliedDataOnly = 1;
188 189

		for (te = AH->toc->next; te != AH->toc; te = te->next)
B
Bruce Momjian 已提交
190
		{
191
			reqs = _tocEntryRequired(te, ropt, true);
192
			if ((reqs & REQ_SCHEMA) != 0)
B
Bruce Momjian 已提交
193
			{					/* It's schema, and it's wanted */
194 195 196 197 198 199 200
				impliedDataOnly = 0;
				break;
			}
		}
		if (impliedDataOnly)
		{
			ropt->dataOnly = impliedDataOnly;
201
			ahlog(AH, 1, "implied data-only restore\n");
202
		}
B
Bruce Momjian 已提交
203
	}
204

205
	/*
B
Bruce Momjian 已提交
206
	 * Setup the output file if necessary.
207
	 */
B
Bruce Momjian 已提交
208
	if (ropt->filename || ropt->compression)
209
		sav = SetOutput(AH, ropt->filename, ropt->compression);
B
Bruce Momjian 已提交
210

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

213 214 215
	if (AH->public.verbose)
		dumpTimestamp(AH, "Started on", AH->createDate);

216 217 218
	if (ropt->single_txn)
		ahprintf(AH, "BEGIN;\n\n");

219 220 221 222 223
	/*
	 * Establish important parameter values right away.
	 */
	_doSetFixedOutputState(AH);

224 225
	AH->stage = STAGE_PROCESSING;

B
Bruce Momjian 已提交
226 227
	/*
	 * Drop the items at the start, in reverse order
228
	 */
B
Bruce Momjian 已提交
229 230
	if (ropt->dropSchema)
	{
231
		for (te = AH->toc->prev; te != AH->toc; te = te->prev)
B
Bruce Momjian 已提交
232
		{
233 234
			AH->currentTE = te;

B
Bruce Momjian 已提交
235
			reqs = _tocEntryRequired(te, ropt, false /* needn't drop ACLs */ );
236
			if (((reqs & REQ_SCHEMA) != 0) && te->dropStmt)
237 238
			{
				/* We want the schema */
239
				ahlog(AH, 1, "dropping %s %s\n", te->desc, te->tag);
240
				/* Select owner and schema as necessary */
241
				_becomeOwner(AH, te);
242
				_selectOutputSchema(AH, te->namespace);
243
				/* Drop it */
244 245 246
				ahprintf(AH, "%s", te->dropStmt);
			}
		}
B
Bruce Momjian 已提交
247
	}
B
Bruce Momjian 已提交
248

249
	/*
250
	 * Now process each non-ACL TOC entry
251
	 */
252
	for (te = AH->toc->next; te != AH->toc; te = te->next)
B
Bruce Momjian 已提交
253
	{
254 255
		AH->currentTE = te;

256
		/* Work out what, if anything, we want from this entry */
257
		reqs = _tocEntryRequired(te, ropt, false);
258

259 260 261
		/* Dump any relevant dump warnings to stderr */
		if (!ropt->suppressDumpWarnings && strcmp(te->desc, "WARNING") == 0)
		{
262
			if (!ropt->dataOnly && te->defn != NULL && strlen(te->defn) != 0)
263 264 265
				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);
266
		}
267

268 269
		defnDumped = false;

270
		if ((reqs & REQ_SCHEMA) != 0)	/* We want the schema */
271
		{
272
			ahlog(AH, 1, "creating %s %s\n", te->desc, te->tag);
273

274
			_printTocEntry(AH, te, ropt, false, false);
275
			defnDumped = true;
276 277

			/* If we created a DB, connect to it... */
B
Bruce Momjian 已提交
278
			if (strcmp(te->desc, "DATABASE") == 0)
279
			{
280 281
				ahlog(AH, 1, "connecting to new database \"%s\"\n", te->tag);
				_reconnectToDB(AH, te->tag);
282
			}
283
		}
B
Bruce Momjian 已提交
284

B
Bruce Momjian 已提交
285
		/*
286
		 * If we have a data component, then process it
287
		 */
288
		if ((reqs & REQ_DATA) != 0)
B
Bruce Momjian 已提交
289
		{
290
			/*
B
Bruce Momjian 已提交
291 292 293
			 * 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.
294
			 */
295
			if (te->hadDumper)
296 297
			{
				/*
298
				 * If we can output the data, then restore it.
299
				 */
B
Bruce Momjian 已提交
300
				if (AH->PrintTocDataPtr !=NULL && (reqs & REQ_DATA) != 0)
301 302 303
				{
#ifndef HAVE_LIBZ
					if (AH->compression != 0)
304
						die_horribly(AH, modulename, "cannot restore from compressed archive (not configured for compression support)\n");
305
#endif
306

307
					_printTocEntry(AH, te, ropt, true, false);
308

309
					if (strcmp(te->desc, "BLOBS") == 0)
310
					{
P
Peter Eisentraut 已提交
311
						ahlog(AH, 1, "restoring large object data\n");
312

313 314 315
						_selectOutputSchema(AH, "pg_catalog");

						(*AH->PrintTocDataPtr) (AH, te, ropt);
316 317 318 319 320
					}
					else
					{
						_disableTriggersIfNecessary(AH, te, ropt);

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

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

						/*
B
Bruce Momjian 已提交
329 330 331 332
						 * If we have a copy statement, use it. As of V1.3,
						 * these are separate to allow easy import from
						 * withing a database connection. Pre 1.3 archives can
						 * not use DB connections and are sent to output only.
333
						 *
334 335 336
						 * For V1.3+, the table data MUST have a copy
						 * statement so that we can go into appropriate mode
						 * with libpq.
337 338
						 */
						if (te->copyStmt && strlen(te->copyStmt) > 0)
339
						{
340
							ahprintf(AH, "%s", te->copyStmt);
341 342
							AH->writingCopyData = true;
						}
343 344 345

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

346 347
						AH->writingCopyData = false;

348 349 350
						_enableTriggersIfNecessary(AH, te, ropt);
					}
				}
351 352 353 354
			}
			else if (!defnDumped)
			{
				/* If we haven't already dumped the defn part, do so now */
355
				ahlog(AH, 1, "executing %s %s\n", te->desc, te->tag);
356
				_printTocEntry(AH, te, ropt, false, false);
357 358
			}
		}
B
Bruce Momjian 已提交
359
	}							/* end loop over TOC entries */
B
Bruce Momjian 已提交
360

361 362 363
	/*
	 * Scan TOC again to output ownership commands and ACLs
	 */
364
	for (te = AH->toc->next; te != AH->toc; te = te->next)
365
	{
366 367
		AH->currentTE = te;

368 369 370 371 372
		/* Work out what, if anything, we want from this entry */
		reqs = _tocEntryRequired(te, ropt, true);

		if ((reqs & REQ_SCHEMA) != 0)	/* We want the schema */
		{
P
Peter Eisentraut 已提交
373
			ahlog(AH, 1, "setting owner and privileges for %s %s\n",
374
				  te->desc, te->tag);
375 376 377 378
			_printTocEntry(AH, te, ropt, false, true);
		}
	}

379
	if (ropt->single_txn)
B
Bruce Momjian 已提交
380 381
		ahprintf(AH, "COMMIT;\n\n");

382 383 384
	if (AH->public.verbose)
		dumpTimestamp(AH, "Completed on", time(NULL));

385 386
	ahprintf(AH, "--\n-- PostgreSQL database dump complete\n--\n\n");

387
	/*
388
	 * Clean up & we're done.
389
	 */
390 391
	AH->stage = STAGE_FINALIZING;

392 393 394 395 396 397 398
	if (ropt->filename || ropt->compression)
		ResetOutput(AH, sav);

	if (ropt->useDB)
	{
		PQfinish(AH->connection);
		AH->connection = NULL;
399
	}
B
Bruce Momjian 已提交
400 401
}

402 403 404 405
/*
 * Allocate a new RestoreOptions block.
 * This is mainly so we can initialize it, but also for future expansion,
 */
B
Bruce Momjian 已提交
406 407
RestoreOptions *
NewRestoreOptions(void)
B
Bruce Momjian 已提交
408
{
B
Bruce Momjian 已提交
409
	RestoreOptions *opts;
B
Bruce Momjian 已提交
410

B
Bruce Momjian 已提交
411
	opts = (RestoreOptions *) calloc(1, sizeof(RestoreOptions));
B
Bruce Momjian 已提交
412 413

	opts->format = archUnknown;
414
	opts->suppressDumpWarnings = false;
415
	opts->exit_on_error = false;
B
Bruce Momjian 已提交
416 417 418 419

	return opts;
}

B
Bruce Momjian 已提交
420 421
static void
_disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
B
Bruce Momjian 已提交
422
{
423 424
	/* This hack is only needed in a data-only restore */
	if (!ropt->dataOnly || !ropt->disable_triggers)
425 426
		return;

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

429
	/*
B
Bruce Momjian 已提交
430
	 * Become superuser if possible, since they are the only ones who can
431 432 433
	 * 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?)
434
	 */
435
	_becomeUser(AH, ropt->superuser);
436 437

	/*
438
	 * Disable them.
439
	 */
440
	_selectOutputSchema(AH, te->namespace);
441

442 443
	ahprintf(AH, "ALTER TABLE %s DISABLE TRIGGER ALL;\n\n",
			 fmtId(te->tag));
B
Bruce Momjian 已提交
444 445
}

B
Bruce Momjian 已提交
446 447
static void
_enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
B
Bruce Momjian 已提交
448
{
449 450
	/* This hack is only needed in a data-only restore */
	if (!ropt->dataOnly || !ropt->disable_triggers)
451 452
		return;

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

455
	/*
B
Bruce Momjian 已提交
456
	 * Become superuser if possible, since they are the only ones who can
457 458 459
	 * 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?)
460
	 */
461
	_becomeUser(AH, ropt->superuser);
462 463

	/*
464
	 * Enable them.
465
	 */
466
	_selectOutputSchema(AH, te->namespace);
467

468 469
	ahprintf(AH, "ALTER TABLE %s ENABLE TRIGGER ALL;\n\n",
			 fmtId(te->tag));
470
}
B
Bruce Momjian 已提交
471 472

/*
473
 * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
B
Bruce Momjian 已提交
474 475 476
 */

/* Public */
P
Peter Eisentraut 已提交
477 478
size_t
WriteData(Archive *AHX, const void *data, size_t dLen)
B
Bruce Momjian 已提交
479
{
B
Bruce Momjian 已提交
480
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
B
Bruce Momjian 已提交
481

482
	if (!AH->currToc)
483
		die_horribly(AH, modulename, "internal error -- WriteData cannot be called outside the context of a DataDumper routine\n");
484

B
Bruce Momjian 已提交
485
	return (*AH->WriteDataPtr) (AH, data, dLen);
B
Bruce Momjian 已提交
486 487 488
}

/*
B
Bruce Momjian 已提交
489
 * Create a new TOC entry. The TOC was designed as a TOC, but is now the
B
Bruce Momjian 已提交
490 491 492 493
 * repository for all metadata. But the name has stuck.
 */

/* Public */
B
Bruce Momjian 已提交
494
void
495 496 497
ArchiveEntry(Archive *AHX,
			 CatalogId catalogId, DumpId dumpId,
			 const char *tag,
498
			 const char *namespace,
B
Bruce Momjian 已提交
499
			 const char *tablespace,
500
			 const char *owner, bool withOids,
501 502 503
			 const char *desc, const char *defn,
			 const char *dropStmt, const char *copyStmt,
			 const DumpId *deps, int nDeps,
B
Bruce Momjian 已提交
504
			 DataDumperPtr dumpFn, void *dumpArg)
B
Bruce Momjian 已提交
505
{
B
Bruce Momjian 已提交
506 507 508 509 510
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
	TocEntry   *newToc;

	newToc = (TocEntry *) calloc(1, sizeof(TocEntry));
	if (!newToc)
511
		die_horribly(AH, modulename, "out of memory\n");
B
Bruce Momjian 已提交
512

513 514 515 516
	AH->tocCount++;
	if (dumpId > AH->maxDumpId)
		AH->maxDumpId = dumpId;

B
Bruce Momjian 已提交
517 518 519 520 521
	newToc->prev = AH->toc->prev;
	newToc->next = AH->toc;
	AH->toc->prev->next = newToc;
	AH->toc->prev = newToc;

522 523
	newToc->catalogId = catalogId;
	newToc->dumpId = dumpId;
524

525
	newToc->tag = strdup(tag);
526
	newToc->namespace = namespace ? strdup(namespace) : NULL;
527
	newToc->tablespace = tablespace ? strdup(tablespace) : NULL;
528
	newToc->owner = strdup(owner);
529
	newToc->withOids = withOids;
B
Bruce Momjian 已提交
530
	newToc->desc = strdup(desc);
531 532 533
	newToc->defn = strdup(defn);
	newToc->dropStmt = strdup(dropStmt);
	newToc->copyStmt = copyStmt ? strdup(copyStmt) : NULL;
534

535 536 537 538 539 540 541 542 543 544 545
	if (nDeps > 0)
	{
		newToc->dependencies = (DumpId *) malloc(nDeps * sizeof(DumpId));
		memcpy(newToc->dependencies, deps, nDeps * sizeof(DumpId));
		newToc->nDeps = nDeps;
	}
	else
	{
		newToc->dependencies = NULL;
		newToc->nDeps = 0;
	}
546

547 548
	newToc->dataDumper = dumpFn;
	newToc->dataDumperArg = dumpArg;
549
	newToc->hadDumper = dumpFn ? true : false;
B
Bruce Momjian 已提交
550

551
	newToc->formatData = NULL;
B
Bruce Momjian 已提交
552

B
Bruce Momjian 已提交
553
	if (AH->ArchiveEntryPtr !=NULL)
B
Bruce Momjian 已提交
554
		(*AH->ArchiveEntryPtr) (AH, newToc);
B
Bruce Momjian 已提交
555 556 557
}

/* Public */
B
Bruce Momjian 已提交
558 559
void
PrintTOCSummary(Archive *AHX, RestoreOptions *ropt)
B
Bruce Momjian 已提交
560
{
B
Bruce Momjian 已提交
561 562 563 564
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
	TocEntry   *te = AH->toc->next;
	OutputContext sav;
	char	   *fmtName;
B
Bruce Momjian 已提交
565

B
Bruce Momjian 已提交
566
	if (ropt->filename)
B
Bruce Momjian 已提交
567
		sav = SetOutput(AH, ropt->filename, 0 /* no compression */ );
B
Bruce Momjian 已提交
568

569 570
	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 已提交
571
			 AH->archdbname, AH->tocCount, AH->compression);
572

B
Bruce Momjian 已提交
573 574
	switch (AH->format)
	{
575 576 577 578 579 580 581 582 583 584 585 586
		case archFiles:
			fmtName = "FILES";
			break;
		case archCustom:
			fmtName = "CUSTOM";
			break;
		case archTar:
			fmtName = "TAR";
			break;
		default:
			fmtName = "UNKNOWN";
	}
587 588

	ahprintf(AH, ";     Dump Version: %d.%d-%d\n", AH->vmaj, AH->vmin, AH->vrev);
589
	ahprintf(AH, ";     Format: %s\n", fmtName);
T
Tom Lane 已提交
590 591
	ahprintf(AH, ";     Integer: %d bytes\n", (int) AH->intSize);
	ahprintf(AH, ";     Offset: %d bytes\n", (int) AH->offSize);
592 593 594 595 596 597
	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);
598

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

B
Bruce Momjian 已提交
601 602
	while (te != AH->toc)
	{
603
		if (_tocEntryRequired(te, ropt, true) != 0)
604
			ahprintf(AH, "%d; %u %u %s %s %s %s\n", te->dumpId,
605
					 te->catalogId.tableoid, te->catalogId.oid,
606 607
					 te->desc, te->namespace ? te->namespace : "-",
					 te->tag, te->owner);
B
Bruce Momjian 已提交
608
		te = te->next;
B
Bruce Momjian 已提交
609
	}
B
Bruce Momjian 已提交
610

B
Bruce Momjian 已提交
611 612
	if (ropt->filename)
		ResetOutput(AH, sav);
B
Bruce Momjian 已提交
613 614
}

615 616 617 618 619
/***********
 * BLOB Archival
 ***********/

/* Called by a dumper to signal start of a BLOB */
B
Bruce Momjian 已提交
620
int
621
StartBlob(Archive *AHX, Oid oid)
622
{
B
Bruce Momjian 已提交
623
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
624

B
Bruce Momjian 已提交
625
	if (!AH->StartBlobPtr)
626
		die_horribly(AH, modulename, "large-object output not supported in chosen format\n");
627

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

B
Bruce Momjian 已提交
630
	return 1;
631 632 633
}

/* Called by a dumper to signal end of a BLOB */
B
Bruce Momjian 已提交
634
int
635
EndBlob(Archive *AHX, Oid oid)
636
{
B
Bruce Momjian 已提交
637
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
638

B
Bruce Momjian 已提交
639 640
	if (AH->EndBlobPtr)
		(*AH->EndBlobPtr) (AH, AH->currToc, oid);
641

B
Bruce Momjian 已提交
642
	return 1;
643 644 645 646 647 648
}

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

649
/*
B
Bruce Momjian 已提交
650
 * Called by a format handler before any blobs are restored
651
 */
B
Bruce Momjian 已提交
652 653
void
StartRestoreBlobs(ArchiveHandle *AH)
654
{
655 656 657 658 659
	if (AH->connection)
		StartTransaction(AH);
	else
		ahprintf(AH, "BEGIN;\n\n");

660 661 662 663
	AH->blobCount = 0;
}

/*
B
Bruce Momjian 已提交
664
 * Called by a format handler after all blobs are restored
665
 */
B
Bruce Momjian 已提交
666 667
void
EndRestoreBlobs(ArchiveHandle *AH)
668
{
669
	if (AH->connection)
670
		CommitTransaction(AH);
671 672
	else
		ahprintf(AH, "COMMIT;\n\n");
673

674
	ahlog(AH, 1, "restored %d large objects\n", AH->blobCount);
675 676 677
}


678 679 680
/*
 * Called by a format handler to initiate restoration of a blob
 */
B
Bruce Momjian 已提交
681
void
682
StartRestoreBlob(ArchiveHandle *AH, Oid oid)
683
{
684
	Oid			loOid;
685

686 687
	AH->blobCount++;

688 689 690
	/* Initialize the LO Buffer */
	AH->lo_buf_used = 0;

691 692 693
	ahlog(AH, 2, "restoring large object with OID %u\n", oid);

	if (AH->connection)
694
	{
695 696 697 698 699 700 701 702 703 704 705 706
		loOid = lo_create(AH->connection, oid);
		if (loOid == 0 || loOid != oid)
			die_horribly(AH, modulename, "could not create large object %u\n",
						 oid);

		AH->loFd = lo_open(AH->connection, oid, INV_WRITE);
		if (AH->loFd == -1)
			die_horribly(AH, modulename, "could not open large object\n");
	}
	else
	{
		ahprintf(AH, "SELECT lo_open(lo_create(%u), %d);\n", oid, INV_WRITE);
707
	}
708

B
Bruce Momjian 已提交
709
	AH->writingBlob = 1;
710 711
}

B
Bruce Momjian 已提交
712
void
713
EndRestoreBlob(ArchiveHandle *AH, Oid oid)
714
{
715 716 717
	if (AH->lo_buf_used > 0)
	{
		/* Write remaining bytes from the LO buffer */
718
		dump_lo_buf(AH);
719
	}
720

B
Bruce Momjian 已提交
721
	AH->writingBlob = 0;
722

723
	if (AH->connection)
724
	{
725 726 727 728 729 730
		lo_close(AH->connection, AH->loFd);
		AH->loFd = -1;
	}
	else
	{
		ahprintf(AH, "SELECT lo_close(0);\n\n");
731
	}
732 733
}

B
Bruce Momjian 已提交
734 735 736 737
/***********
 * Sorting and Reordering
 ***********/

B
Bruce Momjian 已提交
738 739
void
SortTocFromFile(Archive *AHX, RestoreOptions *ropt)
B
Bruce Momjian 已提交
740
{
B
Bruce Momjian 已提交
741 742 743 744 745
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
	FILE	   *fh;
	char		buf[1024];
	char	   *cmnt;
	char	   *endptr;
746
	DumpId		id;
B
Bruce Momjian 已提交
747 748 749 750
	TocEntry   *te;
	TocEntry   *tePrev;

	/* Allocate space for the 'wanted' array, and init it */
751 752 753
	ropt->idWanted = (bool *) malloc(sizeof(bool) * AH->maxDumpId);
	memset(ropt->idWanted, 0, sizeof(bool) * AH->maxDumpId);
	ropt->limitToList = true;
B
Bruce Momjian 已提交
754

B
Bruce Momjian 已提交
755 756
	/* Set prev entry as head of list */
	tePrev = AH->toc;
B
Bruce Momjian 已提交
757

B
Bruce Momjian 已提交
758 759 760
	/* Setup the file */
	fh = fopen(ropt->tocFile, PG_BINARY_R);
	if (!fh)
761
		die_horribly(AH, modulename, "could not open TOC file\n");
B
Bruce Momjian 已提交
762

763
	while (fgets(buf, sizeof(buf), fh) != NULL)
B
Bruce Momjian 已提交
764
	{
765
		/* Truncate line at comment, if any */
B
Bruce Momjian 已提交
766 767 768 769
		cmnt = strchr(buf, ';');
		if (cmnt != NULL)
			cmnt[0] = '\0';

770 771
		/* Ignore if all blank */
		if (strspn(buf, " \t\r") == strlen(buf))
B
Bruce Momjian 已提交
772 773
			continue;

774
		/* Get an ID, check it's valid and not already seen */
B
Bruce Momjian 已提交
775
		id = strtol(buf, &endptr, 10);
776 777
		if (endptr == buf || id <= 0 || id > AH->maxDumpId ||
			ropt->idWanted[id - 1])
B
Bruce Momjian 已提交
778
		{
779
			write_msg(modulename, "WARNING: line ignored: %s\n", buf);
B
Bruce Momjian 已提交
780 781
			continue;
		}
B
Bruce Momjian 已提交
782

B
Bruce Momjian 已提交
783
		/* Find TOC entry */
784
		te = getTocEntryByDumpId(AH, id);
B
Bruce Momjian 已提交
785
		if (!te)
786 787
			die_horribly(AH, modulename, "could not find entry for ID %d\n",
						 id);
B
Bruce Momjian 已提交
788

789
		ropt->idWanted[id - 1] = true;
B
Bruce Momjian 已提交
790

B
Bruce Momjian 已提交
791 792 793
		_moveAfter(AH, tePrev, te);
		tePrev = te;
	}
B
Bruce Momjian 已提交
794

B
Bruce Momjian 已提交
795
	if (fclose(fh) != 0)
796 797
		die_horribly(AH, modulename, "could not close TOC file: %s\n",
					 strerror(errno));
B
Bruce Momjian 已提交
798 799 800 801 802 803 804 805
}

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

/* Public */
B
Bruce Momjian 已提交
806 807 808 809
int
archputs(const char *s, Archive *AH)
{
	return WriteData(AH, s, strlen(s));
B
Bruce Momjian 已提交
810 811 812
}

/* Public */
B
Bruce Momjian 已提交
813 814
int
archprintf(Archive *AH, const char *fmt,...)
B
Bruce Momjian 已提交
815
{
B
Bruce Momjian 已提交
816 817 818 819 820 821
	char	   *p = NULL;
	va_list		ap;
	int			bSize = strlen(fmt) + 256;
	int			cnt = -1;

	/*
B
Bruce Momjian 已提交
822 823 824
	 * 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 已提交
825 826
	 */
	while (cnt < 0 || cnt >= (bSize - 1))
B
Bruce Momjian 已提交
827
	{
B
Bruce Momjian 已提交
828 829
		if (p != NULL)
			free(p);
830
		bSize *= 2;
B
Bruce Momjian 已提交
831
		p = (char *) malloc(bSize);
832
		if (p == NULL)
833
			exit_horribly(AH, modulename, "out of memory\n");
834 835 836
		va_start(ap, fmt);
		cnt = vsnprintf(p, bSize, fmt, ap);
		va_end(ap);
B
Bruce Momjian 已提交
837 838 839 840
	}
	WriteData(AH, p, cnt);
	free(p);
	return cnt;
B
Bruce Momjian 已提交
841 842 843 844 845 846 847
}


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

B
Bruce Momjian 已提交
848 849
OutputContext
SetOutput(ArchiveHandle *AH, char *filename, int compression)
B
Bruce Momjian 已提交
850
{
B
Bruce Momjian 已提交
851
	OutputContext sav;
852
	int			fn;
B
Bruce Momjian 已提交
853 854 855 856 857 858

	/* Replace the AH output file handle */
	sav.OF = AH->OF;
	sav.gzOut = AH->gzOut;

	if (filename)
859
		fn = -1;
B
Bruce Momjian 已提交
860 861 862 863
	else if (AH->FH)
		fn = fileno(AH->FH);
	else if (AH->fSpec)
	{
864
		fn = -1;
B
Bruce Momjian 已提交
865 866 867 868 869 870
		filename = AH->fSpec;
	}
	else
		fn = fileno(stdout);

	/* If compression explicitly requested, use gzopen */
871
#ifdef HAVE_LIBZ
B
Bruce Momjian 已提交
872 873
	if (compression != 0)
	{
874 875 876
		char		fmode[10];

		/* Don't use PG_BINARY_x since this is zlib */
877
		sprintf(fmode, "wb%d", compression);
878 879
		if (fn >= 0)
			AH->OF = gzdopen(dup(fn), fmode);
B
Bruce Momjian 已提交
880 881
		else
			AH->OF = gzopen(filename, fmode);
882
		AH->gzOut = 1;
B
Bruce Momjian 已提交
883 884
	}
	else
B
Bruce Momjian 已提交
885
#endif
886 887
	{							/* Use fopen */
		if (fn >= 0)
888
			AH->OF = fdopen(dup(fn), PG_BINARY_W);
B
Bruce Momjian 已提交
889
		else
890 891
			AH->OF = fopen(filename, PG_BINARY_W);
		AH->gzOut = 0;
B
Bruce Momjian 已提交
892
	}
B
Bruce Momjian 已提交
893

894
	if (!AH->OF)
895
		die_horribly(AH, modulename, "could not open output file: %s\n", strerror(errno));
896

B
Bruce Momjian 已提交
897
	return sav;
B
Bruce Momjian 已提交
898 899
}

B
Bruce Momjian 已提交
900 901
void
ResetOutput(ArchiveHandle *AH, OutputContext sav)
B
Bruce Momjian 已提交
902
{
B
Bruce Momjian 已提交
903
	int			res;
904

B
Bruce Momjian 已提交
905
	if (AH->gzOut)
906
		res = GZCLOSE(AH->OF);
B
Bruce Momjian 已提交
907
	else
908 909 910
		res = fclose(AH->OF);

	if (res != 0)
911 912
		die_horribly(AH, modulename, "could not close output file: %s\n",
					 strerror(errno));
B
Bruce Momjian 已提交
913

B
Bruce Momjian 已提交
914 915
	AH->gzOut = sav.gzOut;
	AH->OF = sav.OF;
B
Bruce Momjian 已提交
916 917 918 919 920
}



/*
B
Bruce Momjian 已提交
921
 *	Print formatted text to the output file (usually stdout).
B
Bruce Momjian 已提交
922
 */
B
Bruce Momjian 已提交
923 924
int
ahprintf(ArchiveHandle *AH, const char *fmt,...)
B
Bruce Momjian 已提交
925
{
B
Bruce Momjian 已提交
926 927 928 929 930 931
	char	   *p = NULL;
	va_list		ap;
	int			bSize = strlen(fmt) + 256;		/* Should be enough */
	int			cnt = -1;

	/*
B
Bruce Momjian 已提交
932 933
	 * This is paranoid: deal with the possibility that vsnprintf is willing
	 * to ignore trailing null
B
Bruce Momjian 已提交
934 935 936
	 */

	/*
B
Bruce Momjian 已提交
937 938
	 * or returns > 0 even if string does not fit. It may be the case that it
	 * returns cnt = bufsize
B
Bruce Momjian 已提交
939 940
	 */
	while (cnt < 0 || cnt >= (bSize - 1))
941
	{
B
Bruce Momjian 已提交
942 943
		if (p != NULL)
			free(p);
944
		bSize *= 2;
B
Bruce Momjian 已提交
945
		p = (char *) malloc(bSize);
946
		if (p == NULL)
947
			die_horribly(AH, modulename, "out of memory\n");
948
		va_start(ap, fmt);
949
		cnt = vsnprintf(p, bSize, fmt, ap);
950
		va_end(ap);
B
Bruce Momjian 已提交
951 952 953 954
	}
	ahwrite(p, 1, cnt, AH);
	free(p);
	return cnt;
B
Bruce Momjian 已提交
955 956
}

B
Bruce Momjian 已提交
957 958
void
ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
959 960 961 962 963 964 965
{
	va_list		ap;

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

	va_start(ap, fmt);
966
	_write_msg(NULL, fmt, ap);
967 968 969
	va_end(ap);
}

970 971 972
/*
 * Single place for logic which says 'We are restoring to a direct DB connection'.
 */
B
Bruce Momjian 已提交
973 974
int
RestoringToDB(ArchiveHandle *AH)
975 976 977 978
{
	return (AH->ropt && AH->ropt->useDB && AH->connection);
}

979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
/*
 * 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);
		ahlog(AH, 5, "wrote %lu bytes of large object data (result = %lu)\n",
			  (unsigned long) AH->lo_buf_used, (unsigned long) res);
		if (res != AH->lo_buf_used)
			die_horribly(AH, modulename,
B
Bruce Momjian 已提交
994 995
			"could not write to large object (result: %lu, expected: %lu)\n",
					   (unsigned long) res, (unsigned long) AH->lo_buf_used);
996 997 998 999
	}
	else
	{
		unsigned char *str;
B
Bruce Momjian 已提交
1000
		size_t		len;
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017

		str = PQescapeBytea((const unsigned char *) AH->lo_buf,
							AH->lo_buf_used, &len);
		if (!str)
			die_horribly(AH, modulename, "out of memory\n");

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

		free(str);
	}
	AH->lo_buf_used = 0;
}


B
Bruce Momjian 已提交
1018
/*
B
Bruce Momjian 已提交
1019 1020 1021
 *	Write buffer to the output file (usually stdout). This is user for
 *	outputting 'restore' scripts etc. It is even possible for an archive
 *	format to create a custom output routine to 'fake' a restore if it
1022
 *	wants to generate a script (see TAR output).
B
Bruce Momjian 已提交
1023
 */
B
Bruce Momjian 已提交
1024 1025
int
ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
B
Bruce Momjian 已提交
1026
{
P
Peter Eisentraut 已提交
1027
	size_t		res;
1028

B
Bruce Momjian 已提交
1029
	if (AH->writingBlob)
1030
	{
B
Bruce Momjian 已提交
1031
		size_t		remaining = size * nmemb;
1032 1033

		while (AH->lo_buf_used + remaining > AH->lo_buf_size)
P
Peter Eisentraut 已提交
1034
		{
1035 1036 1037 1038 1039 1040 1041
			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 已提交
1042 1043
		}

1044 1045 1046
		memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, remaining);
		AH->lo_buf_used += remaining;

P
Peter Eisentraut 已提交
1047
		return size * nmemb;
1048
	}
B
Bruce Momjian 已提交
1049
	else if (AH->gzOut)
1050
	{
B
Bruce Momjian 已提交
1051
		res = GZWRITE((void *) ptr, size, nmemb, AH->OF);
1052
		if (res != (nmemb * size))
1053
			die_horribly(AH, modulename, "could not write to compressed archive\n");
1054 1055
		return res;
	}
B
Bruce Momjian 已提交
1056
	else if (AH->CustomOutPtr)
1057
	{
B
Bruce Momjian 已提交
1058 1059
		res = AH->CustomOutPtr (AH, ptr, size * nmemb);

1060
		if (res != (nmemb * size))
1061
			die_horribly(AH, modulename, "could not write to custom output routine\n");
1062 1063
		return res;
	}
1064 1065 1066
	else
	{
		/*
B
Bruce Momjian 已提交
1067 1068 1069
		 * If we're doing a restore, and it's direct to DB, and we're
		 * connected then send it to the DB.
		 */
1070
		if (RestoringToDB(AH))
B
Bruce Momjian 已提交
1071
			return ExecuteSqlCommandBuf(AH, (void *) ptr, size * nmemb);		/* Always 1, currently */
1072
		else
1073
		{
B
Bruce Momjian 已提交
1074
			res = fwrite((void *) ptr, size, nmemb, AH->OF);
1075
			if (res != nmemb)
P
Peter Eisentraut 已提交
1076 1077
				die_horribly(AH, modulename, "could not write to output file (%lu != %lu)\n",
							 (unsigned long) res, (unsigned long) nmemb);
1078 1079
			return res;
		}
1080
	}
B
Bruce Momjian 已提交
1081
}
1082 1083

/* Common exit code */
B
Bruce Momjian 已提交
1084
static void
1085
_write_msg(const char *modulename, const char *fmt, va_list ap)
1086
{
1087
	if (modulename)
1088
		fprintf(stderr, "%s: [%s] ", progname, _(modulename));
1089 1090
	else
		fprintf(stderr, "%s: ", progname);
1091
	vfprintf(stderr, _(fmt), ap);
1092 1093 1094
}

void
1095
write_msg(const char *modulename, const char *fmt,...)
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
{
	va_list		ap;

	va_start(ap, fmt);
	_write_msg(modulename, fmt, ap);
	va_end(ap);
}


static void
_die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt, va_list ap)
{
	_write_msg(modulename, fmt, ap);
1109

B
Bruce Momjian 已提交
1110 1111
	if (AH)
	{
1112 1113
		if (AH->public.verbose)
			write_msg(NULL, "*** aborted because of error\n");
B
Bruce Momjian 已提交
1114 1115
		if (AH->connection)
			PQfinish(AH->connection);
1116
	}
1117

B
Bruce Momjian 已提交
1118
	exit(1);
B
Bruce Momjian 已提交
1119 1120
}

1121
/* External use */
B
Bruce Momjian 已提交
1122
void
1123
exit_horribly(Archive *AH, const char *modulename, const char *fmt,...)
1124
{
B
Bruce Momjian 已提交
1125
	va_list		ap;
1126

B
Bruce Momjian 已提交
1127
	va_start(ap, fmt);
1128
	_die_horribly((ArchiveHandle *) AH, modulename, fmt, ap);
1129
	va_end(ap);
1130
}
B
Bruce Momjian 已提交
1131

1132
/* Archiver use (just different arg declaration) */
B
Bruce Momjian 已提交
1133
void
1134
die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt,...)
B
Bruce Momjian 已提交
1135
{
B
Bruce Momjian 已提交
1136
	va_list		ap;
B
Bruce Momjian 已提交
1137

B
Bruce Momjian 已提交
1138
	va_start(ap, fmt);
1139
	_die_horribly(AH, modulename, fmt, ap);
1140
	va_end(ap);
B
Bruce Momjian 已提交
1141 1142
}

1143 1144
/* on some error, we may decide to go on... */
void
B
Bruce Momjian 已提交
1145 1146
warn_or_die_horribly(ArchiveHandle *AH,
					 const char *modulename, const char *fmt,...)
1147
{
B
Bruce Momjian 已提交
1148
	va_list		ap;
1149

B
Bruce Momjian 已提交
1150 1151
	switch (AH->stage)
	{
1152 1153 1154 1155 1156 1157

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

		case STAGE_INITIALIZING:
B
Bruce Momjian 已提交
1158
			if (AH->stage != AH->lastErrorStage)
1159 1160 1161 1162
				write_msg(modulename, "Error while INITIALIZING:\n");
			break;

		case STAGE_PROCESSING:
B
Bruce Momjian 已提交
1163
			if (AH->stage != AH->lastErrorStage)
1164 1165 1166 1167
				write_msg(modulename, "Error while PROCESSING TOC:\n");
			break;

		case STAGE_FINALIZING:
B
Bruce Momjian 已提交
1168
			if (AH->stage != AH->lastErrorStage)
1169 1170 1171
				write_msg(modulename, "Error while FINALIZING:\n");
			break;
	}
B
Bruce Momjian 已提交
1172 1173
	if (AH->currentTE != NULL && AH->currentTE != AH->lastErrorTE)
	{
1174 1175
		write_msg(modulename, "Error from TOC entry %d; %u %u %s %s %s\n",
				  AH->currentTE->dumpId,
B
Bruce Momjian 已提交
1176 1177
			 AH->currentTE->catalogId.tableoid, AH->currentTE->catalogId.oid,
			  AH->currentTE->desc, AH->currentTE->tag, AH->currentTE->owner);
1178 1179 1180 1181
	}
	AH->lastErrorStage = AH->stage;
	AH->lastErrorTE = AH->currentTE;

1182
	va_start(ap, fmt);
1183
	if (AH->public.exit_on_error)
1184 1185 1186 1187 1188 1189 1190 1191
		_die_horribly(AH, modulename, fmt, ap);
	else
	{
		_write_msg(modulename, fmt, ap);
		AH->public.n_errors++;
	}
	va_end(ap);
}
1192

B
Bruce Momjian 已提交
1193 1194
static void
_moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
B
Bruce Momjian 已提交
1195
{
B
Bruce Momjian 已提交
1196 1197
	te->prev->next = te->next;
	te->next->prev = te->prev;
B
Bruce Momjian 已提交
1198

B
Bruce Momjian 已提交
1199 1200
	te->prev = pos;
	te->next = pos->next;
B
Bruce Momjian 已提交
1201

B
Bruce Momjian 已提交
1202 1203
	pos->next->prev = te;
	pos->next = te;
B
Bruce Momjian 已提交
1204 1205
}

1206 1207
#ifdef NOT_USED

B
Bruce Momjian 已提交
1208 1209
static void
_moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
B
Bruce Momjian 已提交
1210
{
B
Bruce Momjian 已提交
1211 1212
	te->prev->next = te->next;
	te->next->prev = te->prev;
B
Bruce Momjian 已提交
1213

B
Bruce Momjian 已提交
1214 1215 1216 1217
	te->prev = pos->prev;
	te->next = pos;
	pos->prev->next = te;
	pos->prev = te;
B
Bruce Momjian 已提交
1218
}
1219 1220
#endif

B
Bruce Momjian 已提交
1221
static TocEntry *
1222
getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
B
Bruce Momjian 已提交
1223
{
B
Bruce Momjian 已提交
1224 1225 1226 1227 1228
	TocEntry   *te;

	te = AH->toc->next;
	while (te != AH->toc)
	{
1229
		if (te->dumpId == id)
B
Bruce Momjian 已提交
1230 1231 1232 1233
			return te;
		te = te->next;
	}
	return NULL;
B
Bruce Momjian 已提交
1234 1235
}

1236
teReqs
1237
TocIDRequired(ArchiveHandle *AH, DumpId id, RestoreOptions *ropt)
B
Bruce Momjian 已提交
1238
{
1239
	TocEntry   *te = getTocEntryByDumpId(AH, id);
B
Bruce Momjian 已提交
1240

B
Bruce Momjian 已提交
1241 1242
	if (!te)
		return 0;
B
Bruce Momjian 已提交
1243

1244
	return _tocEntryRequired(te, ropt, true);
B
Bruce Momjian 已提交
1245 1246
}

1247 1248 1249
size_t
WriteOffset(ArchiveHandle *AH, off_t o, int wasSet)
{
B
Bruce Momjian 已提交
1250
	int			off;
1251 1252 1253 1254 1255 1256 1257

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

	/* Write out off_t smallest byte first, prevents endian mismatch */
	for (off = 0; off < sizeof(off_t); off++)
	{
B
Bruce Momjian 已提交
1258
		(*AH->WriteBytePtr) (AH, o & 0xFF);
1259 1260 1261 1262 1263 1264 1265 1266
		o >>= 8;
	}
	return sizeof(off_t) + 1;
}

int
ReadOffset(ArchiveHandle *AH, off_t *o)
{
B
Bruce Momjian 已提交
1267 1268 1269
	int			i;
	int			off;
	int			offsetFlg;
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280

	/* 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 已提交
1281
			return K_OFFSET_POS_NOT_SET;
1282
		else if (i == 0)
B
Bruce Momjian 已提交
1283
			return K_OFFSET_NO_DATA;
1284 1285

		/* Cast to off_t because it was written as an int. */
B
Bruce Momjian 已提交
1286
		*o = (off_t) i;
1287 1288 1289 1290
		return K_OFFSET_POS_SET;
	}

	/*
B
Bruce Momjian 已提交
1291 1292
	 * Read the flag indicating the state of the data pointer. Check if valid
	 * and die if not.
1293
	 *
1294 1295
	 * This used to be handled by a negative or zero pointer, now we use an
	 * extra byte specifically for the state.
1296 1297 1298 1299 1300 1301 1302 1303 1304
	 */
	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 已提交
1305
			break;
1306 1307

		default:
B
Bruce Momjian 已提交
1308
			die_horribly(AH, modulename, "Unexpected data offset flag %d\n", offsetFlg);
1309 1310 1311 1312 1313 1314 1315 1316
	}

	/*
	 * Read the bytes
	 */
	for (off = 0; off < AH->offSize; off++)
	{
		if (off < sizeof(off_t))
1317
			*o |= ((off_t) ((*AH->ReadBytePtr) (AH))) << (off * 8);
1318 1319 1320
		else
		{
			if ((*AH->ReadBytePtr) (AH) != 0)
B
Bruce Momjian 已提交
1321
				die_horribly(AH, modulename, "file offset in dump file is too large\n");
1322 1323 1324 1325 1326 1327
		}
	}

	return offsetFlg;
}

P
Peter Eisentraut 已提交
1328
size_t
B
Bruce Momjian 已提交
1329
WriteInt(ArchiveHandle *AH, int i)
B
Bruce Momjian 已提交
1330
{
B
Bruce Momjian 已提交
1331 1332 1333
	int			b;

	/*
B
Bruce Momjian 已提交
1334 1335 1336 1337 1338
	 * 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 已提交
1339 1340 1341 1342 1343 1344
	 */

	/* SIGN byte */
	if (i < 0)
	{
		(*AH->WriteBytePtr) (AH, 1);
1345
		i = -i;
B
Bruce Momjian 已提交
1346 1347 1348 1349 1350 1351 1352
	}
	else
		(*AH->WriteBytePtr) (AH, 0);

	for (b = 0; b < AH->intSize; b++)
	{
		(*AH->WriteBytePtr) (AH, i & 0xFF);
1353
		i >>= 8;
B
Bruce Momjian 已提交
1354 1355 1356
	}

	return AH->intSize + 1;
B
Bruce Momjian 已提交
1357 1358
}

B
Bruce Momjian 已提交
1359 1360
int
ReadInt(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1361
{
B
Bruce Momjian 已提交
1362 1363 1364 1365 1366
	int			res = 0;
	int			bv,
				b;
	int			sign = 0;		/* Default positive */
	int			bitShift = 0;
B
Bruce Momjian 已提交
1367

B
Bruce Momjian 已提交
1368
	if (AH->version > K_VERS_1_0)
1369
		/* Read a sign byte */
B
Bruce Momjian 已提交
1370
		sign = (*AH->ReadBytePtr) (AH);
B
Bruce Momjian 已提交
1371

B
Bruce Momjian 已提交
1372 1373 1374
	for (b = 0; b < AH->intSize; b++)
	{
		bv = (*AH->ReadBytePtr) (AH) & 0xFF;
1375 1376 1377
		if (bv != 0)
			res = res + (bv << bitShift);
		bitShift += 8;
B
Bruce Momjian 已提交
1378
	}
B
Bruce Momjian 已提交
1379

B
Bruce Momjian 已提交
1380 1381
	if (sign)
		res = -res;
B
Bruce Momjian 已提交
1382

B
Bruce Momjian 已提交
1383
	return res;
B
Bruce Momjian 已提交
1384 1385
}

P
Peter Eisentraut 已提交
1386
size_t
1387
WriteStr(ArchiveHandle *AH, const char *c)
B
Bruce Momjian 已提交
1388
{
P
Peter Eisentraut 已提交
1389
	size_t		res;
1390 1391 1392 1393

	if (c)
	{
		res = WriteInt(AH, strlen(c));
B
Bruce Momjian 已提交
1394
		res += (*AH->WriteBufPtr) (AH, c, strlen(c));
1395 1396 1397 1398
	}
	else
		res = WriteInt(AH, -1);

B
Bruce Momjian 已提交
1399
	return res;
B
Bruce Momjian 已提交
1400 1401
}

B
Bruce Momjian 已提交
1402 1403
char *
ReadStr(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1404
{
B
Bruce Momjian 已提交
1405 1406
	char	   *buf;
	int			l;
B
Bruce Momjian 已提交
1407

B
Bruce Momjian 已提交
1408
	l = ReadInt(AH);
1409 1410 1411 1412
	if (l == -1)
		buf = NULL;
	else
	{
B
Bruce Momjian 已提交
1413
		buf = (char *) malloc(l + 1);
1414
		if (!buf)
1415
			die_horribly(AH, modulename, "out of memory\n");
1416

B
Bruce Momjian 已提交
1417
		(*AH->ReadBufPtr) (AH, (void *) buf, l);
1418 1419
		buf[l] = '\0';
	}
B
Bruce Momjian 已提交
1420

B
Bruce Momjian 已提交
1421
	return buf;
B
Bruce Momjian 已提交
1422 1423
}

T
Tom Lane 已提交
1424
static int
B
Bruce Momjian 已提交
1425
_discoverArchiveFormat(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1426
{
B
Bruce Momjian 已提交
1427 1428
	FILE	   *fh;
	char		sig[6];			/* More than enough */
P
Peter Eisentraut 已提交
1429
	size_t		cnt;
B
Bruce Momjian 已提交
1430
	int			wantClose = 0;
B
Bruce Momjian 已提交
1431

1432
#if 0
1433
	write_msg(modulename, "attempting to ascertain archive format\n");
1434
#endif
1435 1436 1437 1438 1439 1440 1441 1442

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

	AH->lookaheadSize = 512;
	AH->lookahead = calloc(1, 512);
	AH->lookaheadLen = 0;
	AH->lookaheadPos = 0;
1443

B
Bruce Momjian 已提交
1444 1445
	if (AH->fSpec)
	{
1446 1447
		wantClose = 1;
		fh = fopen(AH->fSpec, PG_BINARY_R);
B
Bruce Momjian 已提交
1448 1449
	}
	else
1450
		fh = stdin;
B
Bruce Momjian 已提交
1451

B
Bruce Momjian 已提交
1452
	if (!fh)
1453
		die_horribly(AH, modulename, "could not open input file: %s\n", strerror(errno));
B
Bruce Momjian 已提交
1454

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

B
Bruce Momjian 已提交
1457
	if (cnt != 5)
1458 1459 1460 1461
	{
		if (ferror(fh))
			die_horribly(AH, modulename, "could not read input file: %s\n", strerror(errno));
		else
P
Peter Eisentraut 已提交
1462 1463
			die_horribly(AH, modulename, "input file is too short (read %lu, expected 5)\n",
						 (unsigned long) cnt);
1464
	}
B
Bruce Momjian 已提交
1465

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

B
Bruce Momjian 已提交
1470
	if (strncmp(sig, "PGDMP", 5) == 0)
1471 1472 1473 1474 1475 1476 1477 1478 1479
	{
		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 已提交
1480 1481
		if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0)))		/* Version > 1.0 */
		{
1482 1483 1484 1485 1486 1487
			AH->vrev = fgetc(fh);
			AH->lookahead[AH->lookaheadLen++] = AH->vrev;
		}
		else
			AH->vrev = 0;

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

1491 1492 1493
		AH->intSize = fgetc(fh);
		AH->lookahead[AH->lookaheadLen++] = AH->intSize;

1494 1495 1496 1497 1498 1499 1500 1501
		if (AH->version >= K_VERS_1_7)
		{
			AH->offSize = fgetc(fh);
			AH->lookahead[AH->lookaheadLen++] = AH->offSize;
		}
		else
			AH->offSize = AH->intSize;

1502 1503
		AH->format = fgetc(fh);
		AH->lookahead[AH->lookaheadLen++] = AH->format;
B
Bruce Momjian 已提交
1504 1505 1506
	}
	else
	{
1507
		/*
B
Bruce Momjian 已提交
1508 1509
		 * *Maybe* we have a tar archive format file... So, read first 512
		 * byte header...
1510 1511 1512
		 */
		cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
		AH->lookaheadLen += cnt;
B
Bruce Momjian 已提交
1513

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

1517
		if (!isValidTarHeader(AH->lookahead))
1518
			die_horribly(AH, modulename, "input file does not appear to be a valid archive\n");
B
Bruce Momjian 已提交
1519

1520 1521
		AH->format = archTar;
	}
B
Bruce Momjian 已提交
1522

B
Bruce Momjian 已提交
1523
	/* If we can't seek, then mark the header as read */
P
Peter Eisentraut 已提交
1524
	if (fseeko(fh, 0, SEEK_SET) != 0)
1525 1526
	{
		/*
B
Bruce Momjian 已提交
1527 1528
		 * NOTE: Formats that use the lookahead buffer can unset this in their
		 * Init routine.
1529 1530 1531 1532
		 */
		AH->readHeader = 1;
	}
	else
B
Bruce Momjian 已提交
1533
		AH->lookaheadLen = 0;	/* Don't bother since we've reset the file */
1534

1535
#if 0
P
Peter Eisentraut 已提交
1536 1537
	write_msg(modulename, "read %lu bytes into lookahead buffer\n",
			  (unsigned long) AH->lookaheadLen);
1538
#endif
B
Bruce Momjian 已提交
1539

B
Bruce Momjian 已提交
1540 1541
	/* Close the file */
	if (wantClose)
1542
		if (fclose(fh) != 0)
1543 1544
			die_horribly(AH, modulename, "could not close the input file after reading header: %s\n",
						 strerror(errno));
B
Bruce Momjian 已提交
1545

B
Bruce Momjian 已提交
1546
	return AH->format;
B
Bruce Momjian 已提交
1547 1548 1549 1550 1551 1552
}


/*
 * Allocate an archive handle
 */
B
Bruce Momjian 已提交
1553 1554 1555
static ArchiveHandle *
_allocAH(const char *FileSpec, const ArchiveFormat fmt,
		 const int compression, ArchiveMode mode)
1556
{
B
Bruce Momjian 已提交
1557
	ArchiveHandle *AH;
B
Bruce Momjian 已提交
1558

1559
#if 0
1560
	write_msg(modulename, "allocating AH for %s, format %d\n", FileSpec, fmt);
1561
#endif
1562

B
Bruce Momjian 已提交
1563 1564
	AH = (ArchiveHandle *) calloc(1, sizeof(ArchiveHandle));
	if (!AH)
1565
		die_horribly(AH, modulename, "out of memory\n");
B
Bruce Momjian 已提交
1566

1567 1568
	/* AH->debugLevel = 100; */

B
Bruce Momjian 已提交
1569 1570
	AH->vmaj = K_VERS_MAJOR;
	AH->vmin = K_VERS_MINOR;
1571
	AH->vrev = K_VERS_REV;
B
Bruce Momjian 已提交
1572

1573 1574
	AH->createDate = time(NULL);

B
Bruce Momjian 已提交
1575
	AH->intSize = sizeof(int);
1576
	AH->offSize = sizeof(off_t);
B
Bruce Momjian 已提交
1577 1578
	if (FileSpec)
	{
1579
		AH->fSpec = strdup(FileSpec);
B
Bruce Momjian 已提交
1580

1581 1582 1583
		/*
		 * Not used; maybe later....
		 *
1584 1585
		 * AH->workDir = strdup(FileSpec); for(i=strlen(FileSpec) ; i > 0 ;
		 * i--) if (AH->workDir[i-1] == '/')
1586
		 */
B
Bruce Momjian 已提交
1587 1588
	}
	else
1589
		AH->fSpec = NULL;
B
Bruce Momjian 已提交
1590

B
Bruce Momjian 已提交
1591 1592
	AH->currUser = strdup("");	/* So it's valid, but we can free() it later
								 * if necessary */
B
Bruce Momjian 已提交
1593
	AH->currSchema = strdup("");	/* ditto */
1594
	AH->currWithOids = -1;		/* force SET */
B
Bruce Momjian 已提交
1595

B
Bruce Momjian 已提交
1596 1597
	AH->toc = (TocEntry *) calloc(1, sizeof(TocEntry));
	if (!AH->toc)
1598
		die_horribly(AH, modulename, "out of memory\n");
B
Bruce Momjian 已提交
1599

B
Bruce Momjian 已提交
1600 1601 1602 1603 1604
	AH->toc->next = AH->toc;
	AH->toc->prev = AH->toc;

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

1606 1607
	AH->pgCopyBuf = createPQExpBuffer();
	AH->sqlBuf = createPQExpBuffer();
B
Bruce Momjian 已提交
1608

B
Bruce Momjian 已提交
1609 1610 1611
	/* Open stdout with no compression for AH output handle */
	AH->gzOut = 0;
	AH->OF = stdout;
B
Bruce Momjian 已提交
1612

1613 1614
	/*
	 * On Windows, we need to use binary mode to read/write non-text archive
B
Bruce Momjian 已提交
1615 1616
	 * formats.  Force stdin/stdout into binary mode if that is what we are
	 * using.
1617 1618
	 */
#ifdef WIN32
1619 1620
	if (fmt != archNull &&
		(AH->fSpec == NULL || strcmp(AH->fSpec, "") == 0))
1621 1622 1623 1624 1625 1626 1627 1628
	{
		if (mode == archModeWrite)
			setmode(fileno(stdout), O_BINARY);
		else
			setmode(fileno(stdin), O_BINARY);
	}
#endif

1629
#if 0
1630
	write_msg(modulename, "archive format is %d\n", fmt);
1631
#endif
1632

B
Bruce Momjian 已提交
1633
	if (fmt == archUnknown)
1634 1635 1636
		AH->format = _discoverArchiveFormat(AH);
	else
		AH->format = fmt;
B
Bruce Momjian 已提交
1637

B
Bruce Momjian 已提交
1638 1639
	switch (AH->format)
	{
1640 1641 1642
		case archCustom:
			InitArchiveFmt_Custom(AH);
			break;
B
Bruce Momjian 已提交
1643

1644 1645 1646
		case archFiles:
			InitArchiveFmt_Files(AH);
			break;
B
Bruce Momjian 已提交
1647

1648 1649 1650
		case archNull:
			InitArchiveFmt_Null(AH);
			break;
B
Bruce Momjian 已提交
1651

1652 1653 1654 1655 1656
		case archTar:
			InitArchiveFmt_Tar(AH);
			break;

		default:
1657
			die_horribly(AH, modulename, "unrecognized file format \"%d\"\n", fmt);
B
Bruce Momjian 已提交
1658
	}
B
Bruce Momjian 已提交
1659

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

B
Bruce Momjian 已提交
1664
	return AH;
B
Bruce Momjian 已提交
1665 1666 1667
}


B
Bruce Momjian 已提交
1668 1669
void
WriteDataChunks(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1670
{
B
Bruce Momjian 已提交
1671 1672 1673
	TocEntry   *te = AH->toc->next;
	StartDataPtr startPtr;
	EndDataPtr	endPtr;
B
Bruce Momjian 已提交
1674

B
Bruce Momjian 已提交
1675 1676 1677
	while (te != AH->toc)
	{
		if (te->dataDumper != NULL)
1678
		{
B
Bruce Momjian 已提交
1679 1680
			AH->currToc = te;
			/* printf("Writing data for %d (%x)\n", te->id, te); */
1681

B
Bruce Momjian 已提交
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
			if (strcmp(te->desc, "BLOBS") == 0)
			{
				startPtr = AH->StartBlobsPtr;
				endPtr = AH->EndBlobsPtr;
			}
			else
			{
				startPtr = AH->StartDataPtr;
				endPtr = AH->EndDataPtr;
			}
B
Bruce Momjian 已提交
1692

B
Bruce Momjian 已提交
1693 1694
			if (startPtr != NULL)
				(*startPtr) (AH, te);
B
Bruce Momjian 已提交
1695

B
Bruce Momjian 已提交
1696
			/*
B
Bruce Momjian 已提交
1697
			 * printf("Dumper arg for %d is %x\n", te->id, te->dataDumperArg);
B
Bruce Momjian 已提交
1698 1699 1700 1701 1702 1703
			 */

			/*
			 * The user-provided DataDumper routine needs to call
			 * AH->WriteData
			 */
1704
			(*te->dataDumper) ((Archive *) AH, te->dataDumperArg);
B
Bruce Momjian 已提交
1705 1706 1707 1708 1709

			if (endPtr != NULL)
				(*endPtr) (AH, te);
			AH->currToc = NULL;
		}
1710
		te = te->next;
B
Bruce Momjian 已提交
1711
	}
B
Bruce Momjian 已提交
1712 1713
}

B
Bruce Momjian 已提交
1714 1715
void
WriteToc(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1716
{
1717 1718
	TocEntry   *te;
	char		workbuf[32];
1719
	int			i;
B
Bruce Momjian 已提交
1720 1721 1722 1723

	/* printf("%d TOC Entries to save\n", AH->tocCount); */

	WriteInt(AH, AH->tocCount);
1724 1725

	for (te = AH->toc->next; te != AH->toc; te = te->next)
B
Bruce Momjian 已提交
1726
	{
1727
		WriteInt(AH, te->dumpId);
B
Bruce Momjian 已提交
1728
		WriteInt(AH, te->dataDumper ? 1 : 0);
1729 1730 1731 1732 1733 1734

		/* 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);
1735

1736
		WriteStr(AH, te->tag);
B
Bruce Momjian 已提交
1737 1738 1739 1740
		WriteStr(AH, te->desc);
		WriteStr(AH, te->defn);
		WriteStr(AH, te->dropStmt);
		WriteStr(AH, te->copyStmt);
1741
		WriteStr(AH, te->namespace);
1742
		WriteStr(AH, te->tablespace);
B
Bruce Momjian 已提交
1743
		WriteStr(AH, te->owner);
1744
		WriteStr(AH, te->withOids ? "true" : "false");
1745 1746

		/* Dump list of dependencies */
1747
		for (i = 0; i < te->nDeps; i++)
1748
		{
1749 1750
			sprintf(workbuf, "%d", te->dependencies[i]);
			WriteStr(AH, workbuf);
1751
		}
1752
		WriteStr(AH, NULL);		/* Terminate List */
1753

B
Bruce Momjian 已提交
1754 1755 1756
		if (AH->WriteExtraTocPtr)
			(*AH->WriteExtraTocPtr) (AH, te);
	}
B
Bruce Momjian 已提交
1757 1758
}

B
Bruce Momjian 已提交
1759 1760
void
ReadToc(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1761
{
B
Bruce Momjian 已提交
1762
	int			i;
1763 1764
	char	   *tmp;
	DumpId	   *deps;
1765 1766
	int			depIdx;
	int			depSize;
B
Bruce Momjian 已提交
1767

B
Bruce Momjian 已提交
1768
	TocEntry   *te = AH->toc->next;
B
Bruce Momjian 已提交
1769

B
Bruce Momjian 已提交
1770
	AH->tocCount = ReadInt(AH);
1771
	AH->maxDumpId = 0;
B
Bruce Momjian 已提交
1772

B
Bruce Momjian 已提交
1773 1774 1775
	for (i = 0; i < AH->tocCount; i++)
	{
		te = (TocEntry *) calloc(1, sizeof(TocEntry));
1776 1777 1778 1779
		te->dumpId = ReadInt(AH);

		if (te->dumpId > AH->maxDumpId)
			AH->maxDumpId = te->dumpId;
1780 1781

		/* Sanity check */
1782 1783
		if (te->dumpId <= 0)
			die_horribly(AH, modulename,
B
Bruce Momjian 已提交
1784
					   "entry ID %d out of range -- perhaps a corrupt TOC\n",
1785
						 te->dumpId);
1786 1787

		te->hadDumper = ReadInt(AH);
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799

		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);
1800

1801
		te->tag = ReadStr(AH);
1802 1803 1804 1805 1806 1807 1808
		te->desc = ReadStr(AH);
		te->defn = ReadStr(AH);
		te->dropStmt = ReadStr(AH);

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

1809 1810 1811
		if (AH->version >= K_VERS_1_6)
			te->namespace = ReadStr(AH);

1812 1813 1814
		if (AH->version >= K_VERS_1_10)
			te->tablespace = ReadStr(AH);

1815
		te->owner = ReadStr(AH);
1816 1817 1818 1819 1820 1821 1822 1823 1824
		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 已提交
1825

1826 1827 1828 1829
		/* Read TOC entry dependencies */
		if (AH->version >= K_VERS_1_5)
		{
			depSize = 100;
1830
			deps = (DumpId *) malloc(sizeof(DumpId) * depSize);
1831
			depIdx = 0;
1832
			for (;;)
1833
			{
1834 1835 1836
				tmp = ReadStr(AH);
				if (!tmp)
					break;		/* end of list */
1837
				if (depIdx >= depSize)
1838 1839
				{
					depSize *= 2;
1840
					deps = (DumpId *) realloc(deps, sizeof(DumpId) * depSize);
1841
				}
1842 1843 1844 1845
				sscanf(tmp, "%d", &deps[depIdx]);
				free(tmp);
				depIdx++;
			}
1846

1847 1848 1849 1850 1851 1852
			if (depIdx > 0)		/* We have a non-null entry */
			{
				deps = (DumpId *) realloc(deps, sizeof(DumpId) * depIdx);
				te->dependencies = deps;
				te->nDeps = depIdx;
			}
1853
			else
1854 1855
			{
				free(deps);
1856 1857
				te->dependencies = NULL;
				te->nDeps = 0;
1858
			}
1859
		}
1860
		else
1861 1862 1863 1864
		{
			te->dependencies = NULL;
			te->nDeps = 0;
		}
1865

B
Bruce Momjian 已提交
1866 1867
		if (AH->ReadExtraTocPtr)
			(*AH->ReadExtraTocPtr) (AH, te);
1868

1869 1870
		ahlog(AH, 3, "read TOC entry %d (ID %d) for %s %s\n",
			  i, te->dumpId, te->desc, te->tag);
1871 1872 1873 1874 1875

		te->prev = AH->toc->prev;
		AH->toc->prev->next = te;
		AH->toc->prev = te;
		te->next = AH->toc;
B
Bruce Momjian 已提交
1876
	}
B
Bruce Momjian 已提交
1877 1878
}

1879
static teReqs
1880
_tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool include_acls)
B
Bruce Momjian 已提交
1881
{
1882
	teReqs		res = REQ_ALL;
B
Bruce Momjian 已提交
1883

1884 1885 1886 1887
	/* ENCODING objects are dumped specially, so always reject here */
	if (strcmp(te->desc, "ENCODING") == 0)
		return 0;

B
Bruce Momjian 已提交
1888
	/* If it's an ACL, maybe ignore it */
1889
	if ((!include_acls || ropt->aclsSkip) && strcmp(te->desc, "ACL") == 0)
1890
		return 0;
B
Bruce Momjian 已提交
1891

B
Bruce Momjian 已提交
1892
	if (!ropt->create && strcmp(te->desc, "DATABASE") == 0)
1893 1894
		return 0;

B
Bruce Momjian 已提交
1895 1896 1897
	/* Check if tablename only is wanted */
	if (ropt->selTypes)
	{
1898 1899 1900 1901 1902
		if (ropt->schemaNames)
		{
			/* If no namespace is specified, it means all. */
			if (!te->namespace)
				return 0;
B
Bruce Momjian 已提交
1903
			if (strcmp(ropt->schemaNames, te->namespace) != 0)
1904 1905
				return 0;
		}
1906 1907
		if (strcmp(te->desc, "TABLE") == 0 ||
			strcmp(te->desc, "TABLE DATA") == 0)
1908 1909 1910
		{
			if (!ropt->selTable)
				return 0;
1911
			if (ropt->tableNames && strcmp(ropt->tableNames, te->tag) != 0)
1912
				return 0;
B
Bruce Momjian 已提交
1913 1914 1915
		}
		else if (strcmp(te->desc, "INDEX") == 0)
		{
1916 1917
			if (!ropt->selIndex)
				return 0;
1918
			if (ropt->indexNames && strcmp(ropt->indexNames, te->tag) != 0)
1919
				return 0;
B
Bruce Momjian 已提交
1920 1921 1922
		}
		else if (strcmp(te->desc, "FUNCTION") == 0)
		{
1923 1924
			if (!ropt->selFunction)
				return 0;
1925
			if (ropt->functionNames && strcmp(ropt->functionNames, te->tag) != 0)
1926
				return 0;
B
Bruce Momjian 已提交
1927 1928 1929
		}
		else if (strcmp(te->desc, "TRIGGER") == 0)
		{
1930 1931
			if (!ropt->selTrigger)
				return 0;
1932
			if (ropt->triggerNames && strcmp(ropt->triggerNames, te->tag) != 0)
1933 1934
				return 0;
		}
B
Bruce Momjian 已提交
1935 1936
		else
			return 0;
B
Bruce Momjian 已提交
1937 1938
	}

1939
	/*
B
Bruce Momjian 已提交
1940
	 * Check if we had a dataDumper. Indicates if the entry is schema or data
1941 1942 1943 1944
	 */
	if (!te->hadDumper)
	{
		/*
B
Bruce Momjian 已提交
1945
		 * Special Case: If 'SEQUENCE SET' then it is considered a data entry
1946 1947 1948 1949
		 */
		if (strcmp(te->desc, "SEQUENCE SET") == 0)
			res = res & REQ_DATA;
		else
1950 1951
			res = res & ~REQ_DATA;
	}
1952

1953
	/*
B
Bruce Momjian 已提交
1954 1955
	 * Special case: <Init> type with <Max OID> tag; this is obsolete and we
	 * always ignore it.
1956
	 */
1957
	if ((strcmp(te->desc, "<Init>") == 0) && (strcmp(te->tag, "Max OID") == 0))
1958
		return 0;
1959

B
Bruce Momjian 已提交
1960 1961
	/* Mask it if we only want schema */
	if (ropt->schemaOnly)
1962
		res = res & REQ_SCHEMA;
B
Bruce Momjian 已提交
1963

B
Bruce Momjian 已提交
1964
	/* Mask it we only want data */
1965
	if (ropt->dataOnly)
1966
		res = res & REQ_DATA;
B
Bruce Momjian 已提交
1967

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

B
Bruce Momjian 已提交
1972
	/* Finally, if we used a list, limit based on that as well */
1973
	if (ropt->limitToList && !ropt->idWanted[te->dumpId - 1])
1974
		return 0;
B
Bruce Momjian 已提交
1975

B
Bruce Momjian 已提交
1976
	return res;
B
Bruce Momjian 已提交
1977 1978
}

1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002
/*
 * 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)
{
	TocEntry   *te;

	/* If we have an encoding setting, emit that */
	te = AH->toc->next;
	while (te != AH->toc)
	{
		if (strcmp(te->desc, "ENCODING") == 0)
		{
			ahprintf(AH, "%s", te->defn);
			break;
		}
		te = te->next;
	}

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

2003 2004 2005
	/* Avoid annoying notices etc */
	ahprintf(AH, "SET client_min_messages = warning;\n");

2006 2007 2008
	ahprintf(AH, "\n");
}

2009 2010
/*
 * Issue a SET SESSION AUTHORIZATION command.  Caller is responsible
2011 2012
 * for updating state if appropriate.  If user is NULL or an empty string,
 * the specification DEFAULT will be used.
2013 2014
 */
static void
2015
_doSetSessionAuth(ArchiveHandle *AH, const char *user)
2016
{
2017
	PQExpBuffer cmd = createPQExpBuffer();
B
Bruce Momjian 已提交
2018

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

2021 2022 2023 2024
	/*
	 * SQL requires a string literal here.	Might as well be correct.
	 */
	if (user && *user)
2025 2026 2027 2028 2029
		appendStringLiteral(cmd, user, false);
	else
		appendPQExpBuffer(cmd, "DEFAULT");
	appendPQExpBuffer(cmd, ";");

2030 2031 2032 2033
	if (RestoringToDB(AH))
	{
		PGresult   *res;

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

		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2037
			/* NOT warn_or_die_horribly... use -O instead to skip this. */
2038
			die_horribly(AH, modulename, "could not set session user to \"%s\": %s",
2039
						 user, PQerrorMessage(AH->connection));
2040 2041 2042 2043

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

	destroyPQExpBuffer(cmd);
2047 2048
}

2049

2050 2051 2052 2053 2054 2055 2056 2057 2058 2059
/*
 * 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 已提交
2060
					  "true" : "false");
2061 2062 2063 2064 2065 2066 2067 2068

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

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

		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
B
Bruce Momjian 已提交
2069
			warn_or_die_horribly(AH, modulename,
2070 2071
								 "could not set default_with_oids: %s",
								 PQerrorMessage(AH->connection));
2072 2073 2074 2075 2076 2077 2078 2079 2080 2081

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

	destroyPQExpBuffer(cmd);
}


2082
/*
2083
 * Issue the commands to connect to the specified database.
2084 2085
 *
 * If we're currently restoring right into a database, this will
B
Bruce Momjian 已提交
2086
 * actually establish a connection. Otherwise it puts a \connect into
2087
 * the script output.
2088 2089
 *
 * NULL dbname implies reconnecting to the current DB (pretty useless).
2090
 */
B
Bruce Momjian 已提交
2091
static void
2092
_reconnectToDB(ArchiveHandle *AH, const char *dbname)
2093
{
2094
	if (RestoringToDB(AH))
2095
		ReconnectToServer(AH, dbname, NULL);
2096
	else
2097 2098 2099
	{
		PQExpBuffer qry = createPQExpBuffer();

2100
		appendPQExpBuffer(qry, "\\connect %s\n\n",
2101
						  dbname ? fmtId(dbname) : "-");
2102
		ahprintf(AH, "%s", qry->data);
2103 2104
		destroyPQExpBuffer(qry);
	}
2105

2106
	/*
B
Bruce Momjian 已提交
2107 2108
	 * NOTE: currUser keeps track of what the imaginary session user in our
	 * script is.  It's now effectively reset to the original userID.
2109
	 */
2110 2111 2112
	if (AH->currUser)
		free(AH->currUser);

2113
	AH->currUser = strdup("");
2114 2115 2116 2117 2118

	/* don't assume we still know the output schema */
	if (AH->currSchema)
		free(AH->currSchema);
	AH->currSchema = strdup("");
2119
	AH->currWithOids = -1;
B
Bruce Momjian 已提交
2120

2121 2122
	/* re-establish fixed state */
	_doSetFixedOutputState(AH);
2123 2124
}

2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141
/*
 * 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 已提交
2142 2143
	 * NOTE: currUser keeps track of what the imaginary session user in our
	 * script is
2144 2145 2146 2147 2148 2149
	 */
	if (AH->currUser)
		free(AH->currUser);

	AH->currUser = strdup(user);
}
2150 2151

/*
B
Bruce Momjian 已提交
2152
 * Become the owner of the the given TOC entry object.	If
2153 2154
 * changes in ownership are not allowed, this doesn't do anything.
 */
B
Bruce Momjian 已提交
2155
static void
2156
_becomeOwner(ArchiveHandle *AH, TocEntry *te)
2157
{
2158
	if (AH->ropt && (AH->ropt->noOwner || !AH->ropt->use_setsessauth))
2159 2160
		return;

2161
	_becomeUser(AH, te->owner);
2162 2163
}

2164

2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178
/*
 * 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;
	}
}


2179 2180 2181 2182 2183 2184 2185
/*
 * Issue the commands to select the specified schema as the current schema
 * in the target database.
 */
static void
_selectOutputSchema(ArchiveHandle *AH, const char *schemaName)
{
2186 2187
	PQExpBuffer qry;

2188 2189 2190 2191
	if (!schemaName || *schemaName == '\0' ||
		strcmp(AH->currSchema, schemaName) == 0)
		return;					/* no need to do anything */

2192 2193 2194
	qry = createPQExpBuffer();

	appendPQExpBuffer(qry, "SET search_path = %s",
2195
					  fmtId(schemaName));
2196 2197 2198
	if (strcmp(schemaName, "pg_catalog") != 0)
		appendPQExpBuffer(qry, ", pg_catalog");

2199 2200 2201 2202 2203 2204 2205
	if (RestoringToDB(AH))
	{
		PGresult   *res;

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

		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
B
Bruce Momjian 已提交
2206
			warn_or_die_horribly(AH, modulename,
B
Bruce Momjian 已提交
2207 2208
								 "could not set search_path to \"%s\": %s",
								 schemaName, PQerrorMessage(AH->connection));
2209 2210 2211 2212

		PQclear(res);
	}
	else
2213
		ahprintf(AH, "%s;\n\n", qry->data);
2214 2215 2216 2217

	if (AH->currSchema)
		free(AH->currSchema);
	AH->currSchema = strdup(schemaName);
2218 2219

	destroyPQExpBuffer(qry);
2220 2221
}

2222 2223 2224 2225 2226 2227 2228 2229
/*
 * 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 已提交
2230 2231
	const char *want,
			   *have;
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262

	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)
B
Bruce Momjian 已提交
2263
			warn_or_die_horribly(AH, modulename,
2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277
								 "could not set default_tablespace to %s: %s",
								 fmtId(want), PQerrorMessage(AH->connection));

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

	if (AH->currTablespace)
		free(AH->currTablespace);
	AH->currTablespace = strdup(want);

	destroyPQExpBuffer(qry);
}
2278

2279 2280 2281 2282 2283 2284 2285 2286
/*
 * 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.
2287
 */
2288
static void
2289
_getObjectDescription(PQExpBuffer buf, TocEntry *te, ArchiveHandle *AH)
2290
{
2291 2292 2293
	const char *type = te->desc;

	/* Use ALTER TABLE for views and sequences */
2294
	if (strcmp(type, "VIEW") == 0 || strcmp(type, "SEQUENCE") == 0)
2295 2296 2297 2298 2299 2300 2301 2302
		type = "TABLE";

	/* objects named by a schema and name */
	if (strcmp(type, "CONVERSION") == 0 ||
		strcmp(type, "DOMAIN") == 0 ||
		strcmp(type, "TABLE") == 0 ||
		strcmp(type, "TYPE") == 0)
	{
2303
		appendPQExpBuffer(buf, "%s ", type);
B
Bruce Momjian 已提交
2304
		if (te->namespace && te->namespace[0])	/* is null pre-7.3 */
2305
			appendPQExpBuffer(buf, "%s.", fmtId(te->namespace));
B
Bruce Momjian 已提交
2306

2307
		/*
B
Bruce Momjian 已提交
2308 2309 2310
		 * 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.
2311 2312 2313
		 */
		if (AH->version < K_VERS_1_7 &&
			te->tag[0] == '"' &&
B
Bruce Momjian 已提交
2314
			te->tag[strlen(te->tag) - 1] == '"' &&
2315 2316 2317 2318
			strcmp(type, "INDEX") == 0)
			appendPQExpBuffer(buf, "%s", te->tag);
		else
			appendPQExpBuffer(buf, "%s", fmtId(te->tag));
2319 2320
		return;
	}
2321

2322 2323 2324 2325 2326 2327 2328
	/* objects named by just a name */
	if (strcmp(type, "DATABASE") == 0 ||
		strcmp(type, "SCHEMA") == 0)
	{
		appendPQExpBuffer(buf, "%s %s", type, fmtId(te->tag));
		return;
	}
2329

B
Bruce Momjian 已提交
2330
	/*
B
Bruce Momjian 已提交
2331 2332
	 * These object types require additional decoration.  Fortunately, the
	 * information needed is exactly what's in the DROP command.
B
Bruce Momjian 已提交
2333
	 */
2334 2335 2336 2337
	if (strcmp(type, "AGGREGATE") == 0 ||
		strcmp(type, "FUNCTION") == 0 ||
		strcmp(type, "OPERATOR") == 0 ||
		strcmp(type, "OPERATOR CLASS") == 0)
B
Bruce Momjian 已提交
2338
	{
2339 2340 2341
		/* Chop "DROP " off the front and make a modifiable copy */
		char	   *first = strdup(te->dropStmt + 5);
		char	   *last;
2342

2343 2344
		/* point to last character in string */
		last = first + strlen(first) - 1;
2345

2346 2347 2348 2349
		/* Strip off any ';' or '\n' at the end */
		while (last >= first && (*last == '\n' || *last == ';'))
			last--;
		*(last + 1) = '\0';
B
Bruce Momjian 已提交
2350

2351
		appendPQExpBufferStr(buf, first);
B
Bruce Momjian 已提交
2352 2353

		free(first);
2354
		return;
2355 2356
	}

2357 2358
	write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
			  type);
2359 2360 2361
}

static void
2362
_printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass)
B
Bruce Momjian 已提交
2363
{
2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377
	/* ACLs are dumped only during acl pass */
	if (acl_pass)
	{
		if (strcmp(te->desc, "ACL") != 0)
			return;
	}
	else
	{
		if (strcmp(te->desc, "ACL") == 0)
			return;
	}

	/*
	 * Avoid dumping the public schema, as it will already be created ...
B
Bruce Momjian 已提交
2378 2379
	 * unless we are using --clean mode, in which case it's been deleted and
	 * we'd better recreate it.
2380 2381 2382 2383 2384
	 */
	if (!ropt->dropSchema &&
		strcmp(te->desc, "SCHEMA") == 0 && strcmp(te->tag, "public") == 0)
		return;

2385
	/* Select owner, schema, and tablespace as necessary */
2386 2387
	_becomeOwner(AH, te);
	_selectOutputSchema(AH, te->namespace);
2388
	_selectTablespace(AH, te->tablespace);
2389 2390 2391 2392 2393 2394

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

	/* Emit header comment for item */
2395
	if (!AH->noTocComments)
2396
	{
2397 2398 2399 2400 2401 2402 2403 2404 2405
		const char *pfx;

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

		ahprintf(AH, "--\n");
		if (AH->public.verbose)
2406
		{
2407 2408 2409 2410 2411
			ahprintf(AH, "-- TOC entry %d (class %u OID %u)\n",
					 te->dumpId, te->catalogId.tableoid, te->catalogId.oid);
			if (te->nDeps > 0)
			{
				int			i;
2412

2413 2414 2415 2416 2417
				ahprintf(AH, "-- Dependencies:");
				for (i = 0; i < te->nDeps; i++)
					ahprintf(AH, " %d", te->dependencies[i]);
				ahprintf(AH, "\n");
			}
2418
		}
2419
		ahprintf(AH, "-- %sName: %s; Type: %s; Schema: %s; Owner: %s",
2420 2421
				 pfx, te->tag, te->desc,
				 te->namespace ? te->namespace : "-",
2422
				 ropt->noOwner ? "-" : te->owner);
B
Bruce Momjian 已提交
2423
		if (te->tablespace)
2424 2425 2426
			ahprintf(AH, "; Tablespace: %s", te->tablespace);
		ahprintf(AH, "\n");

B
Bruce Momjian 已提交
2427
		if (AH->PrintExtraTocPtr !=NULL)
2428 2429
			(*AH->PrintExtraTocPtr) (AH, te);
		ahprintf(AH, "--\n\n");
2430
	}
B
Bruce Momjian 已提交
2431

2432 2433 2434
	/*
	 * Actually print the definition.
	 *
B
Bruce Momjian 已提交
2435 2436 2437
	 * 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 ...
2438
	 */
2439
	if (ropt->noOwner && strcmp(te->desc, "SCHEMA") == 0)
2440
	{
2441
		ahprintf(AH, "CREATE SCHEMA %s;\n\n\n", fmtId(te->tag));
2442
	}
2443
	else
2444
	{
2445 2446
		if (strlen(te->defn) > 0)
			ahprintf(AH, "%s\n\n", te->defn);
2447
	}
2448 2449 2450

	/*
	 * If we aren't using SET SESSION AUTH to determine ownership, we must
2451 2452 2453
	 * 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.
2454 2455
	 */
	if (!ropt->noOwner && !ropt->use_setsessauth &&
2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473
		strlen(te->owner) > 0 && strlen(te->dropStmt) > 0)
	{
		if (strcmp(te->desc, "AGGREGATE") == 0 ||
			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 ||
			strcmp(te->desc, "SCHEMA") == 0 ||
			strcmp(te->desc, "TABLE") == 0 ||
			strcmp(te->desc, "TYPE") == 0 ||
			strcmp(te->desc, "VIEW") == 0 ||
			strcmp(te->desc, "SEQUENCE") == 0)
		{
			PQExpBuffer temp = createPQExpBuffer();

			appendPQExpBuffer(temp, "ALTER ");
2474
			_getObjectDescription(temp, te, AH);
2475 2476 2477 2478 2479 2480
			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 ||
2481
				 strcmp(te->desc, "CONSTRAINT") == 0 ||
2482 2483
				 strcmp(te->desc, "DEFAULT") == 0 ||
				 strcmp(te->desc, "FK CONSTRAINT") == 0 ||
2484
				 strcmp(te->desc, "INDEX") == 0 ||
2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495
				 strcmp(te->desc, "PROCEDURAL LANGUAGE") == 0 ||
				 strcmp(te->desc, "RULE") == 0 ||
				 strcmp(te->desc, "TRIGGER") == 0)
		{
			/* 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);
		}
2496
	}
B
Bruce Momjian 已提交
2497

2498 2499
	/*
	 * If it's an ACL entry, it might contain SET SESSION AUTHORIZATION
B
Bruce Momjian 已提交
2500
	 * commands, so we can no longer assume we know the current auth setting.
2501 2502 2503 2504 2505 2506 2507
	 */
	if (strncmp(te->desc, "ACL", 3) == 0)
	{
		if (AH->currUser)
			free(AH->currUser);
		AH->currUser = NULL;
	}
B
Bruce Momjian 已提交
2508 2509
}

B
Bruce Momjian 已提交
2510 2511
void
WriteHead(ArchiveHandle *AH)
B
Bruce Momjian 已提交
2512
{
B
Bruce Momjian 已提交
2513
	struct tm	crtm;
2514

B
Bruce Momjian 已提交
2515 2516 2517 2518 2519
	(*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);
2520
	(*AH->WriteBytePtr) (AH, AH->offSize);
B
Bruce Momjian 已提交
2521
	(*AH->WriteBytePtr) (AH, AH->format);
B
Bruce Momjian 已提交
2522

2523
#ifndef HAVE_LIBZ
B
Bruce Momjian 已提交
2524
	if (AH->compression != 0)
2525
		write_msg(modulename, "WARNING: requested compression not available in this "
2526
				  "installation -- archive will be uncompressed\n");
B
Bruce Momjian 已提交
2527

B
Bruce Momjian 已提交
2528
	AH->compression = 0;
2529
#endif
B
Bruce Momjian 已提交
2530

2531 2532 2533 2534 2535 2536 2537 2538 2539 2540
	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);
2541
	WriteStr(AH, PQdb(AH->connection));
2542 2543
	WriteStr(AH, AH->public.remoteVersionStr);
	WriteStr(AH, PG_VERSION);
B
Bruce Momjian 已提交
2544 2545
}

B
Bruce Momjian 已提交
2546 2547
void
ReadHead(ArchiveHandle *AH)
B
Bruce Momjian 已提交
2548
{
B
Bruce Momjian 已提交
2549 2550
	char		tmpMag[7];
	int			fmt;
2551
	struct tm	crtm;
B
Bruce Momjian 已提交
2552

2553
	/* If we haven't already read the header... */
B
Bruce Momjian 已提交
2554 2555
	if (!AH->readHeader)
	{
B
Bruce Momjian 已提交
2556

B
Bruce Momjian 已提交
2557
		(*AH->ReadBufPtr) (AH, tmpMag, 5);
B
Bruce Momjian 已提交
2558

B
Bruce Momjian 已提交
2559
		if (strncmp(tmpMag, "PGDMP", 5) != 0)
2560
			die_horribly(AH, modulename, "did not find magic string in file header\n");
B
Bruce Momjian 已提交
2561

B
Bruce Momjian 已提交
2562 2563
		AH->vmaj = (*AH->ReadBytePtr) (AH);
		AH->vmin = (*AH->ReadBytePtr) (AH);
B
Bruce Momjian 已提交
2564

B
Bruce Momjian 已提交
2565 2566 2567
		if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0)))		/* Version > 1.0 */
			AH->vrev = (*AH->ReadBytePtr) (AH);
		else
2568
			AH->vrev = 0;
B
Bruce Momjian 已提交
2569

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


2573
		if (AH->version < K_VERS_1_0 || AH->version > K_VERS_MAX)
2574 2575
			die_horribly(AH, modulename, "unsupported version (%d.%d) in file header\n",
						 AH->vmaj, AH->vmin);
B
Bruce Momjian 已提交
2576

B
Bruce Momjian 已提交
2577
		AH->intSize = (*AH->ReadBytePtr) (AH);
2578
		if (AH->intSize > 32)
P
Peter Eisentraut 已提交
2579 2580
			die_horribly(AH, modulename, "sanity check on integer size (%lu) failed\n",
						 (unsigned long) AH->intSize);
B
Bruce Momjian 已提交
2581

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

2585
		if (AH->version >= K_VERS_1_7)
B
Bruce Momjian 已提交
2586
			AH->offSize = (*AH->ReadBytePtr) (AH);
2587
		else
B
Bruce Momjian 已提交
2588
			AH->offSize = AH->intSize;
2589

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

2592
		if (AH->format != fmt)
2593 2594
			die_horribly(AH, modulename, "expected format (%d) differs from format found in file (%d)\n",
						 AH->format, fmt);
B
Bruce Momjian 已提交
2595
	}
B
Bruce Momjian 已提交
2596

B
Bruce Momjian 已提交
2597 2598
	if (AH->version >= K_VERS_1_2)
	{
2599
		if (AH->version < K_VERS_1_4)
B
Bruce Momjian 已提交
2600
			AH->compression = (*AH->ReadBytePtr) (AH);
2601 2602
		else
			AH->compression = ReadInt(AH);
B
Bruce Momjian 已提交
2603 2604
	}
	else
2605
		AH->compression = Z_DEFAULT_COMPRESSION;
B
Bruce Momjian 已提交
2606

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

2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625
	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 已提交
2626
		if (AH->createDate == (time_t) -1)
2627
			write_msg(modulename, "WARNING: invalid creation date in header\n");
2628 2629
	}

2630 2631 2632 2633 2634 2635
	if (AH->version >= K_VERS_1_10)
	{
		AH->archiveRemoteVersion = ReadStr(AH);
		AH->archiveDumpVersion = ReadStr(AH);
	}

B
Bruce Momjian 已提交
2636 2637 2638
}


2639 2640 2641 2642 2643 2644 2645 2646 2647
/*
 * checkSeek
 *	  check to see if fseek can be performed.
 */

bool
checkSeek(FILE *fp)
{

B
Bruce Momjian 已提交
2648
	if (fseeko(fp, 0, SEEK_CUR) != 0)
2649 2650
		return false;
	else if (sizeof(off_t) > sizeof(long))
B
Bruce Momjian 已提交
2651 2652

		/*
B
Bruce Momjian 已提交
2653 2654
		 * At this point, off_t is too large for long, so we return based on
		 * whether an off_t version of fseek is available.
B
Bruce Momjian 已提交
2655
		 */
2656 2657 2658 2659 2660 2661 2662 2663
#ifdef HAVE_FSEEKO
		return true;
#else
		return false;
#endif
	else
		return true;
}
2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676


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

	if (strftime(buf, 256, "%Y-%m-%d %H:%M:%S %Z", localtime(&tim)) != 0)
		ahprintf(AH, "-- %s %s\n\n", msg, buf);
}