pg_backup_archiver.c 60.9 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.113 2005/08/22 19:40:37 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
#include <unistd.h>
B
Bruce Momjian 已提交
31

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

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

39

40
const char *progname;
41

42 43 44
static char *modulename = gettext_noop("archiver");


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

51

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

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

68
static void dump_lo_buf(ArchiveHandle *AH);
69 70
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);
71

72 73
static void dumpTimestamp(ArchiveHandle *AH, const char *msg, time_t tim);

74

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


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

B
Bruce Momjian 已提交
90
{
B
Bruce Momjian 已提交
91 92 93
	ArchiveHandle *AH = _allocAH(FileSpec, fmt, compression, archModeWrite);

	return (Archive *) AH;
B
Bruce Momjian 已提交
94 95 96 97
}

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

	return (Archive *) AH;
B
Bruce Momjian 已提交
104 105 106
}

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

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

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

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

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

135
	AH->ropt = ropt;
136
	AH->stage = STAGE_INITIALIZING;
137

138 139 140 141 142
	/*
	 * Check for nonsensical option combinations.
	 *
	 * NB: create+dropSchema is useless because if you're creating the DB,
	 * there's no need to drop individual items in it.  Moreover, if we
143 144 145
	 * 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...
146 147 148 149
	 */
	if (ropt->create && ropt->dropSchema)
		die_horribly(AH, modulename, "-C and -c are incompatible options\n");

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

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

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

		/*
		 * If we're talking to the DB directly, don't send comments since
		 * they obscure SQL when displaying errors
		 */
171
		AH->noTocComments = 1;
172 173
	}

174
	/*
B
Bruce Momjian 已提交
175 176
	 * 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
B
Bruce Momjian 已提交
177 178
	 * exclude all of the schema data. All we do is look for schema
	 * entries - if none are found then we set the dataOnly flag.
179
	 *
B
Bruce Momjian 已提交
180
	 * We could scan for wanted TABLE entries, but that is not the same as
181
	 * dataOnly. At this stage, it seems unnecessary (6-Mar-2001).
B
Bruce Momjian 已提交
182 183 184
	 */
	if (!ropt->dataOnly)
	{
185 186 187
		int		impliedDataOnly = 1;

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

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

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

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

214 215 216 217 218
	/*
	 * Establish important parameter values right away.
	 */
	_doSetFixedOutputState(AH);

219 220
	AH->stage = STAGE_PROCESSING;

B
Bruce Momjian 已提交
221 222
	/*
	 * Drop the items at the start, in reverse order
223
	 */
B
Bruce Momjian 已提交
224 225
	if (ropt->dropSchema)
	{
226
		for (te = AH->toc->prev; te != AH->toc; te = te->prev)
B
Bruce Momjian 已提交
227
		{
228 229
			AH->currentTE = te;

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

244
	/*
245
	 * Now process each non-ACL TOC entry
246
	 */
247
	for (te = AH->toc->next; te != AH->toc; te = te->next)
B
Bruce Momjian 已提交
248
	{
249 250
		AH->currentTE = te;

251
		/* Work out what, if anything, we want from this entry */
252
		reqs = _tocEntryRequired(te, ropt, false);
253

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

263 264
		defnDumped = false;

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

269
			_printTocEntry(AH, te, ropt, false, false);
270
			defnDumped = true;
271 272

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

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

303
					_printTocEntry(AH, te, ropt, true, false);
304

305
					if (strcmp(te->desc, "BLOBS") == 0)
306
					{
307
						ahlog(AH, 1, "restoring blob data\n");
308

309 310 311
						_selectOutputSchema(AH, "pg_catalog");

						(*AH->PrintTocDataPtr) (AH, te, ropt);
312 313 314 315 316
					}
					else
					{
						_disableTriggersIfNecessary(AH, te, ropt);

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

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

						/*
325 326 327 328 329
						 * 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.
330
						 *
331 332 333
						 * For V1.3+, the table data MUST have a copy
						 * statement so that we can go into appropriate
						 * mode with libpq.
334 335
						 */
						if (te->copyStmt && strlen(te->copyStmt) > 0)
336
							ahprintf(AH, "%s", te->copyStmt);
337 338 339 340 341 342

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

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

353 354 355
	/*
	 * Scan TOC again to output ownership commands and ACLs
	 */
356
	for (te = AH->toc->next; te != AH->toc; te = te->next)
357
	{
358 359
		AH->currentTE = te;

360 361 362 363 364
		/* 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 已提交
365
			ahlog(AH, 1, "setting owner and privileges for %s %s\n",
366
				  te->desc, te->tag);
367 368 369 370
			_printTocEntry(AH, te, ropt, false, true);
		}
	}

371 372 373
	if (AH->public.verbose)
		dumpTimestamp(AH, "Completed on", time(NULL));

374 375
	ahprintf(AH, "--\n-- PostgreSQL database dump complete\n--\n\n");

376
	/*
377
	 * Clean up & we're done.
378
	 */
379 380
	AH->stage = STAGE_FINALIZING;

381 382 383 384 385 386 387
	if (ropt->filename || ropt->compression)
		ResetOutput(AH, sav);

	if (ropt->useDB)
	{
		PQfinish(AH->connection);
		AH->connection = NULL;
388
	}
B
Bruce Momjian 已提交
389 390
}

391 392 393 394
/*
 * Allocate a new RestoreOptions block.
 * This is mainly so we can initialize it, but also for future expansion,
 */
B
Bruce Momjian 已提交
395 396
RestoreOptions *
NewRestoreOptions(void)
B
Bruce Momjian 已提交
397
{
B
Bruce Momjian 已提交
398
	RestoreOptions *opts;
B
Bruce Momjian 已提交
399

B
Bruce Momjian 已提交
400
	opts = (RestoreOptions *) calloc(1, sizeof(RestoreOptions));
B
Bruce Momjian 已提交
401 402

	opts->format = archUnknown;
403
	opts->suppressDumpWarnings = false;
404
	opts->exit_on_error = false;
B
Bruce Momjian 已提交
405 406 407 408

	return opts;
}

B
Bruce Momjian 已提交
409 410
static void
_disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
B
Bruce Momjian 已提交
411
{
412 413
	/* This hack is only needed in a data-only restore */
	if (!ropt->dataOnly || !ropt->disable_triggers)
414 415 416
		return;

	/*
B
Bruce Momjian 已提交
417
	 * Become superuser if possible, since they are the only ones who can
B
Bruce Momjian 已提交
418 419
	 * update pg_class.  If -S was not given, assume the initial user
	 * identity is a superuser.
420
	 */
421
	_becomeUser(AH, ropt->superuser);
422

423
	ahlog(AH, 1, "disabling triggers\n");
424 425

	/*
B
Bruce Momjian 已提交
426 427
	 * Disable them. This is a hack. Needs to be done via an appropriate
	 * 'SET' command when one is available.
428
	 */
B
Bruce Momjian 已提交
429
	ahprintf(AH, "-- Disable triggers\n");
430 431

	/*
432 433
	 * Just update the AFFECTED table, if known.  Otherwise update all
	 * non-system tables.
434
	 */
435
	if (te && te->tag && strlen(te->tag) > 0)
436 437
		ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = 0 "
				 "WHERE oid = '%s'::pg_catalog.regclass;\n\n",
438
				 fmtId(te->tag));
439
	else
440
		ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = 0 FROM pg_catalog.pg_namespace "
441
				 "WHERE relnamespace = pg_namespace.oid AND nspname !~ '^pg_';\n\n");
B
Bruce Momjian 已提交
442 443
}

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

	/*
B
Bruce Momjian 已提交
452
	 * Become superuser if possible, since they are the only ones who can
B
Bruce Momjian 已提交
453 454
	 * update pg_class.  If -S was not given, assume the initial user
	 * identity is a superuser.
455
	 */
456
	_becomeUser(AH, ropt->superuser);
457

458
	ahlog(AH, 1, "enabling triggers\n");
459 460

	/*
B
Bruce Momjian 已提交
461 462
	 * Enable them. This is a hack. Needs to be done via an appropriate
	 * 'SET' command when one is available.
463
	 */
B
Bruce Momjian 已提交
464
	ahprintf(AH, "-- Enable triggers\n");
465 466

	/*
467 468
	 * Just update the AFFECTED table, if known.  Otherwise update all
	 * non-system tables.
469
	 */
470
	if (te && te->tag && strlen(te->tag) > 0)
471
		ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = "
472
				 "(SELECT pg_catalog.count(*) FROM pg_catalog.pg_trigger where pg_class.oid = tgrelid) "
473
				 "WHERE oid = '%s'::pg_catalog.regclass;\n\n",
474
				 fmtId(te->tag));
B
Bruce Momjian 已提交
475
	else
476
		ahprintf(AH, "UPDATE pg_catalog.pg_class SET reltriggers = "
477
				 "(SELECT pg_catalog.count(*) FROM pg_catalog.pg_trigger where pg_class.oid = tgrelid) "
478
				 "FROM pg_catalog.pg_namespace "
479
				 "WHERE relnamespace = pg_namespace.oid AND nspname !~ '^pg_';\n\n");
480
}
B
Bruce Momjian 已提交
481 482

/*
483
 * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
B
Bruce Momjian 已提交
484 485 486
 */

/* Public */
P
Peter Eisentraut 已提交
487 488
size_t
WriteData(Archive *AHX, const void *data, size_t dLen)
B
Bruce Momjian 已提交
489
{
B
Bruce Momjian 已提交
490
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
B
Bruce Momjian 已提交
491

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

B
Bruce Momjian 已提交
495
	return (*AH->WriteDataPtr) (AH, data, dLen);
B
Bruce Momjian 已提交
496 497 498
}

/*
B
Bruce Momjian 已提交
499
 * Create a new TOC entry. The TOC was designed as a TOC, but is now the
B
Bruce Momjian 已提交
500 501 502 503
 * repository for all metadata. But the name has stuck.
 */

/* Public */
B
Bruce Momjian 已提交
504
void
505 506 507
ArchiveEntry(Archive *AHX,
			 CatalogId catalogId, DumpId dumpId,
			 const char *tag,
508 509 510
			 const char *namespace,
			 const char *tablespace, 
			 const char *owner, bool withOids,
511 512 513
			 const char *desc, const char *defn,
			 const char *dropStmt, const char *copyStmt,
			 const DumpId *deps, int nDeps,
B
Bruce Momjian 已提交
514
			 DataDumperPtr dumpFn, void *dumpArg)
B
Bruce Momjian 已提交
515
{
B
Bruce Momjian 已提交
516 517 518 519 520
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
	TocEntry   *newToc;

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

523 524 525 526
	AH->tocCount++;
	if (dumpId > AH->maxDumpId)
		AH->maxDumpId = dumpId;

B
Bruce Momjian 已提交
527 528 529 530 531
	newToc->prev = AH->toc->prev;
	newToc->next = AH->toc;
	AH->toc->prev->next = newToc;
	AH->toc->prev = newToc;

532 533
	newToc->catalogId = catalogId;
	newToc->dumpId = dumpId;
534

535
	newToc->tag = strdup(tag);
536
	newToc->namespace = namespace ? strdup(namespace) : NULL;
537
	newToc->tablespace = tablespace ? strdup(tablespace) : NULL;
538
	newToc->owner = strdup(owner);
539
	newToc->withOids = withOids;
B
Bruce Momjian 已提交
540
	newToc->desc = strdup(desc);
541 542 543
	newToc->defn = strdup(defn);
	newToc->dropStmt = strdup(dropStmt);
	newToc->copyStmt = copyStmt ? strdup(copyStmt) : NULL;
544

545 546 547 548 549 550 551 552 553 554 555
	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;
	}
556

557 558
	newToc->dataDumper = dumpFn;
	newToc->dataDumperArg = dumpArg;
559
	newToc->hadDumper = dumpFn ? true : false;
B
Bruce Momjian 已提交
560

561
	newToc->formatData = NULL;
B
Bruce Momjian 已提交
562

B
Bruce Momjian 已提交
563
	if (AH->ArchiveEntryPtr !=NULL)
B
Bruce Momjian 已提交
564
		(*AH->ArchiveEntryPtr) (AH, newToc);
B
Bruce Momjian 已提交
565 566 567
}

/* Public */
B
Bruce Momjian 已提交
568 569
void
PrintTOCSummary(Archive *AHX, RestoreOptions *ropt)
B
Bruce Momjian 已提交
570
{
B
Bruce Momjian 已提交
571 572 573 574
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
	TocEntry   *te = AH->toc->next;
	OutputContext sav;
	char	   *fmtName;
B
Bruce Momjian 已提交
575

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

579 580
	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 已提交
581
			 AH->archdbname, AH->tocCount, AH->compression);
582

B
Bruce Momjian 已提交
583 584
	switch (AH->format)
	{
585 586 587 588 589 590 591 592 593 594 595 596
		case archFiles:
			fmtName = "FILES";
			break;
		case archCustom:
			fmtName = "CUSTOM";
			break;
		case archTar:
			fmtName = "TAR";
			break;
		default:
			fmtName = "UNKNOWN";
	}
597 598

	ahprintf(AH, ";     Dump Version: %d.%d-%d\n", AH->vmaj, AH->vmin, AH->vrev);
599
	ahprintf(AH, ";     Format: %s\n", fmtName);
T
Tom Lane 已提交
600 601
	ahprintf(AH, ";     Integer: %d bytes\n", (int) AH->intSize);
	ahprintf(AH, ";     Offset: %d bytes\n", (int) AH->offSize);
602 603 604 605 606 607
	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);
608

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

B
Bruce Momjian 已提交
611 612
	while (te != AH->toc)
	{
613
		if (_tocEntryRequired(te, ropt, true) != 0)
614
			ahprintf(AH, "%d; %u %u %s %s %s %s\n", te->dumpId,
615
					 te->catalogId.tableoid, te->catalogId.oid,
616 617
					 te->desc, te->namespace ? te->namespace : "-",
					 te->tag, te->owner);
B
Bruce Momjian 已提交
618
		te = te->next;
B
Bruce Momjian 已提交
619
	}
B
Bruce Momjian 已提交
620

B
Bruce Momjian 已提交
621 622
	if (ropt->filename)
		ResetOutput(AH, sav);
B
Bruce Momjian 已提交
623 624
}

625 626 627 628 629
/***********
 * BLOB Archival
 ***********/

/* Called by a dumper to signal start of a BLOB */
B
Bruce Momjian 已提交
630
int
631
StartBlob(Archive *AHX, Oid oid)
632
{
B
Bruce Momjian 已提交
633
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
634

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

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

B
Bruce Momjian 已提交
640
	return 1;
641 642 643
}

/* Called by a dumper to signal end of a BLOB */
B
Bruce Momjian 已提交
644
int
645
EndBlob(Archive *AHX, Oid oid)
646
{
B
Bruce Momjian 已提交
647
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
648

B
Bruce Momjian 已提交
649 650
	if (AH->EndBlobPtr)
		(*AH->EndBlobPtr) (AH, AH->currToc, oid);
651

B
Bruce Momjian 已提交
652
	return 1;
653 654 655 656 657 658
}

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

659
/*
B
Bruce Momjian 已提交
660
 * Called by a format handler before any blobs are restored
661
 */
B
Bruce Momjian 已提交
662 663
void
StartRestoreBlobs(ArchiveHandle *AH)
664
{
665 666 667 668 669
	if (AH->connection)
		StartTransaction(AH);
	else
		ahprintf(AH, "BEGIN;\n\n");

670 671 672 673
	AH->blobCount = 0;
}

/*
B
Bruce Momjian 已提交
674
 * Called by a format handler after all blobs are restored
675
 */
B
Bruce Momjian 已提交
676 677
void
EndRestoreBlobs(ArchiveHandle *AH)
678
{
679
	if (AH->connection)
680
		CommitTransaction(AH);
681 682
	else
		ahprintf(AH, "COMMIT;\n\n");
683

684
	ahlog(AH, 1, "restored %d large objects\n", AH->blobCount);
685 686 687
}


688 689 690
/*
 * Called by a format handler to initiate restoration of a blob
 */
B
Bruce Momjian 已提交
691
void
692
StartRestoreBlob(ArchiveHandle *AH, Oid oid)
693
{
694
	Oid			loOid;
695

696 697
	AH->blobCount++;

698 699 700
	/* Initialize the LO Buffer */
	AH->lo_buf_used = 0;

701 702 703
	ahlog(AH, 2, "restoring large object with OID %u\n", oid);

	if (AH->connection)
704
	{
705 706 707 708 709 710 711 712 713 714 715 716
		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);
717
	}
718

B
Bruce Momjian 已提交
719
	AH->writingBlob = 1;
720 721
}

B
Bruce Momjian 已提交
722
void
723
EndRestoreBlob(ArchiveHandle *AH, Oid oid)
724
{
725 726 727
	if (AH->lo_buf_used > 0)
	{
		/* Write remaining bytes from the LO buffer */
728
		dump_lo_buf(AH);
729
	}
730

B
Bruce Momjian 已提交
731
	AH->writingBlob = 0;
732

733
	if (AH->connection)
734
	{
735 736 737 738 739 740
		lo_close(AH->connection, AH->loFd);
		AH->loFd = -1;
	}
	else
	{
		ahprintf(AH, "SELECT lo_close(0);\n\n");
741
	}
742 743
}

B
Bruce Momjian 已提交
744 745 746 747
/***********
 * Sorting and Reordering
 ***********/

B
Bruce Momjian 已提交
748 749
void
SortTocFromFile(Archive *AHX, RestoreOptions *ropt)
B
Bruce Momjian 已提交
750
{
B
Bruce Momjian 已提交
751 752 753 754 755
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
	FILE	   *fh;
	char		buf[1024];
	char	   *cmnt;
	char	   *endptr;
756
	DumpId		id;
B
Bruce Momjian 已提交
757 758 759 760
	TocEntry   *te;
	TocEntry   *tePrev;

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

B
Bruce Momjian 已提交
765 766
	/* Set prev entry as head of list */
	tePrev = AH->toc;
B
Bruce Momjian 已提交
767

B
Bruce Momjian 已提交
768 769 770
	/* Setup the file */
	fh = fopen(ropt->tocFile, PG_BINARY_R);
	if (!fh)
771
		die_horribly(AH, modulename, "could not open TOC file\n");
B
Bruce Momjian 已提交
772

773
	while (fgets(buf, sizeof(buf), fh) != NULL)
B
Bruce Momjian 已提交
774
	{
775
		/* Truncate line at comment, if any */
B
Bruce Momjian 已提交
776 777 778 779
		cmnt = strchr(buf, ';');
		if (cmnt != NULL)
			cmnt[0] = '\0';

780 781
		/* Ignore if all blank */
		if (strspn(buf, " \t\r") == strlen(buf))
B
Bruce Momjian 已提交
782 783
			continue;

784
		/* Get an ID, check it's valid and not already seen */
B
Bruce Momjian 已提交
785
		id = strtol(buf, &endptr, 10);
786 787
		if (endptr == buf || id <= 0 || id > AH->maxDumpId ||
			ropt->idWanted[id - 1])
B
Bruce Momjian 已提交
788
		{
789
			write_msg(modulename, "WARNING: line ignored: %s\n", buf);
B
Bruce Momjian 已提交
790 791
			continue;
		}
B
Bruce Momjian 已提交
792

B
Bruce Momjian 已提交
793
		/* Find TOC entry */
794
		te = getTocEntryByDumpId(AH, id);
B
Bruce Momjian 已提交
795
		if (!te)
796 797
			die_horribly(AH, modulename, "could not find entry for ID %d\n",
						 id);
B
Bruce Momjian 已提交
798

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

B
Bruce Momjian 已提交
801 802 803
		_moveAfter(AH, tePrev, te);
		tePrev = te;
	}
B
Bruce Momjian 已提交
804

B
Bruce Momjian 已提交
805
	if (fclose(fh) != 0)
806 807
		die_horribly(AH, modulename, "could not close TOC file: %s\n",
					 strerror(errno));
B
Bruce Momjian 已提交
808 809 810 811 812 813 814 815
}

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

/* Public */
B
Bruce Momjian 已提交
816 817 818 819
int
archputs(const char *s, Archive *AH)
{
	return WriteData(AH, s, strlen(s));
B
Bruce Momjian 已提交
820 821 822
}

/* Public */
B
Bruce Momjian 已提交
823 824
int
archprintf(Archive *AH, const char *fmt,...)
B
Bruce Momjian 已提交
825
{
B
Bruce Momjian 已提交
826 827 828 829 830 831 832
	char	   *p = NULL;
	va_list		ap;
	int			bSize = strlen(fmt) + 256;
	int			cnt = -1;

	/*
	 * This is paranoid: deal with the possibility that vsnprintf is
B
Bruce Momjian 已提交
833 834
	 * 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 已提交
835 836
	 */
	while (cnt < 0 || cnt >= (bSize - 1))
B
Bruce Momjian 已提交
837
	{
B
Bruce Momjian 已提交
838 839
		if (p != NULL)
			free(p);
840
		bSize *= 2;
B
Bruce Momjian 已提交
841
		p = (char *) malloc(bSize);
842
		if (p == NULL)
843
			exit_horribly(AH, modulename, "out of memory\n");
844 845 846
		va_start(ap, fmt);
		cnt = vsnprintf(p, bSize, fmt, ap);
		va_end(ap);
B
Bruce Momjian 已提交
847 848 849 850
	}
	WriteData(AH, p, cnt);
	free(p);
	return cnt;
B
Bruce Momjian 已提交
851 852 853 854 855 856 857
}


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

B
Bruce Momjian 已提交
858 859
OutputContext
SetOutput(ArchiveHandle *AH, char *filename, int compression)
B
Bruce Momjian 已提交
860
{
B
Bruce Momjian 已提交
861
	OutputContext sav;
862
	int			fn;
B
Bruce Momjian 已提交
863 864 865 866 867 868

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

	if (filename)
869
		fn = -1;
B
Bruce Momjian 已提交
870 871 872 873
	else if (AH->FH)
		fn = fileno(AH->FH);
	else if (AH->fSpec)
	{
874
		fn = -1;
B
Bruce Momjian 已提交
875 876 877 878 879 880
		filename = AH->fSpec;
	}
	else
		fn = fileno(stdout);

	/* If compression explicitly requested, use gzopen */
881
#ifdef HAVE_LIBZ
B
Bruce Momjian 已提交
882 883
	if (compression != 0)
	{
884 885 886
		char		fmode[10];

		/* Don't use PG_BINARY_x since this is zlib */
887
		sprintf(fmode, "wb%d", compression);
888 889
		if (fn >= 0)
			AH->OF = gzdopen(dup(fn), fmode);
B
Bruce Momjian 已提交
890 891
		else
			AH->OF = gzopen(filename, fmode);
892
		AH->gzOut = 1;
B
Bruce Momjian 已提交
893 894
	}
	else
B
Bruce Momjian 已提交
895
#endif
896 897
	{							/* Use fopen */
		if (fn >= 0)
898
			AH->OF = fdopen(dup(fn), PG_BINARY_W);
B
Bruce Momjian 已提交
899
		else
900 901
			AH->OF = fopen(filename, PG_BINARY_W);
		AH->gzOut = 0;
B
Bruce Momjian 已提交
902
	}
B
Bruce Momjian 已提交
903

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

B
Bruce Momjian 已提交
907
	return sav;
B
Bruce Momjian 已提交
908 909
}

B
Bruce Momjian 已提交
910 911
void
ResetOutput(ArchiveHandle *AH, OutputContext sav)
B
Bruce Momjian 已提交
912
{
B
Bruce Momjian 已提交
913
	int			res;
914

B
Bruce Momjian 已提交
915
	if (AH->gzOut)
916
		res = GZCLOSE(AH->OF);
B
Bruce Momjian 已提交
917
	else
918 919 920
		res = fclose(AH->OF);

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

B
Bruce Momjian 已提交
924 925
	AH->gzOut = sav.gzOut;
	AH->OF = sav.OF;
B
Bruce Momjian 已提交
926 927 928 929 930
}



/*
B
Bruce Momjian 已提交
931
 *	Print formatted text to the output file (usually stdout).
B
Bruce Momjian 已提交
932
 */
B
Bruce Momjian 已提交
933 934
int
ahprintf(ArchiveHandle *AH, const char *fmt,...)
B
Bruce Momjian 已提交
935
{
B
Bruce Momjian 已提交
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
	char	   *p = NULL;
	va_list		ap;
	int			bSize = strlen(fmt) + 256;		/* Should be enough */
	int			cnt = -1;

	/*
	 * 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
	 */
	while (cnt < 0 || cnt >= (bSize - 1))
951
	{
B
Bruce Momjian 已提交
952 953
		if (p != NULL)
			free(p);
954
		bSize *= 2;
B
Bruce Momjian 已提交
955
		p = (char *) malloc(bSize);
956
		if (p == NULL)
957
			die_horribly(AH, modulename, "out of memory\n");
958
		va_start(ap, fmt);
959
		cnt = vsnprintf(p, bSize, fmt, ap);
960
		va_end(ap);
B
Bruce Momjian 已提交
961 962 963 964
	}
	ahwrite(p, 1, cnt, AH);
	free(p);
	return cnt;
B
Bruce Momjian 已提交
965 966
}

B
Bruce Momjian 已提交
967 968
void
ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
969 970 971 972 973 974 975
{
	va_list		ap;

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

	va_start(ap, fmt);
976
	_write_msg(NULL, fmt, ap);
977 978 979
	va_end(ap);
}

980 981 982
/*
 * Single place for logic which says 'We are restoring to a direct DB connection'.
 */
B
Bruce Momjian 已提交
983 984
int
RestoringToDB(ArchiveHandle *AH)
985 986 987 988
{
	return (AH->ropt && AH->ropt->useDB && AH->connection);
}

989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
/*
 * 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,
						 "could not write to large object (result: %lu, expected: %lu)\n",
						 (unsigned long) res, (unsigned long) AH->lo_buf_used);
	}
	else
	{
		unsigned char *str;
		size_t	len;

		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 已提交
1028
/*
B
Bruce Momjian 已提交
1029 1030 1031
 *	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
1032
 *	wants to generate a script (see TAR output).
B
Bruce Momjian 已提交
1033
 */
B
Bruce Momjian 已提交
1034 1035
int
ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
B
Bruce Momjian 已提交
1036
{
P
Peter Eisentraut 已提交
1037
	size_t		res;
1038

B
Bruce Momjian 已提交
1039
	if (AH->writingBlob)
1040
	{
1041 1042 1043
		size_t	remaining = size * nmemb;

		while (AH->lo_buf_used + remaining > AH->lo_buf_size)
P
Peter Eisentraut 已提交
1044
		{
1045 1046 1047 1048 1049 1050 1051
			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 已提交
1052 1053
		}

1054 1055 1056
		memcpy((char *) AH->lo_buf + AH->lo_buf_used, ptr, remaining);
		AH->lo_buf_used += remaining;

P
Peter Eisentraut 已提交
1057
		return size * nmemb;
1058
	}
B
Bruce Momjian 已提交
1059
	else if (AH->gzOut)
1060
	{
B
Bruce Momjian 已提交
1061
		res = GZWRITE((void *) ptr, size, nmemb, AH->OF);
1062
		if (res != (nmemb * size))
1063
			die_horribly(AH, modulename, "could not write to compressed archive\n");
1064 1065
		return res;
	}
B
Bruce Momjian 已提交
1066
	else if (AH->CustomOutPtr)
1067
	{
B
Bruce Momjian 已提交
1068 1069
		res = AH->CustomOutPtr (AH, ptr, size * nmemb);

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

/* Common exit code */
B
Bruce Momjian 已提交
1094
static void
1095
_write_msg(const char *modulename, const char *fmt, va_list ap)
1096
{
1097
	if (modulename)
1098
		fprintf(stderr, "%s: [%s] ", progname, _(modulename));
1099 1100
	else
		fprintf(stderr, "%s: ", progname);
1101
	vfprintf(stderr, _(fmt), ap);
1102 1103 1104
}

void
1105
write_msg(const char *modulename, const char *fmt,...)
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
{
	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);
1119

B
Bruce Momjian 已提交
1120 1121
	if (AH)
	{
1122 1123
		if (AH->public.verbose)
			write_msg(NULL, "*** aborted because of error\n");
B
Bruce Momjian 已提交
1124 1125
		if (AH->connection)
			PQfinish(AH->connection);
1126
	}
1127

B
Bruce Momjian 已提交
1128
	exit(1);
B
Bruce Momjian 已提交
1129 1130
}

1131
/* External use */
B
Bruce Momjian 已提交
1132
void
1133
exit_horribly(Archive *AH, const char *modulename, const char *fmt,...)
1134
{
B
Bruce Momjian 已提交
1135
	va_list		ap;
1136

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

1142
/* Archiver use (just different arg declaration) */
B
Bruce Momjian 已提交
1143
void
1144
die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt,...)
B
Bruce Momjian 已提交
1145
{
B
Bruce Momjian 已提交
1146
	va_list		ap;
B
Bruce Momjian 已提交
1147

B
Bruce Momjian 已提交
1148
	va_start(ap, fmt);
1149
	_die_horribly(AH, modulename, fmt, ap);
1150
	va_end(ap);
B
Bruce Momjian 已提交
1151 1152
}

1153 1154
/* on some error, we may decide to go on... */
void
B
Bruce Momjian 已提交
1155 1156
warn_or_die_horribly(ArchiveHandle *AH,
					 const char *modulename, const char *fmt,...)
1157
{
B
Bruce Momjian 已提交
1158
	va_list		ap;
1159

B
Bruce Momjian 已提交
1160 1161
	switch (AH->stage)
	{
1162 1163 1164 1165 1166 1167

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

		case STAGE_INITIALIZING:
B
Bruce Momjian 已提交
1168
			if (AH->stage != AH->lastErrorStage)
1169 1170 1171 1172
				write_msg(modulename, "Error while INITIALIZING:\n");
			break;

		case STAGE_PROCESSING:
B
Bruce Momjian 已提交
1173
			if (AH->stage != AH->lastErrorStage)
1174 1175 1176 1177
				write_msg(modulename, "Error while PROCESSING TOC:\n");
			break;

		case STAGE_FINALIZING:
B
Bruce Momjian 已提交
1178
			if (AH->stage != AH->lastErrorStage)
1179 1180 1181
				write_msg(modulename, "Error while FINALIZING:\n");
			break;
	}
B
Bruce Momjian 已提交
1182 1183
	if (AH->currentTE != NULL && AH->currentTE != AH->lastErrorTE)
	{
1184 1185
		write_msg(modulename, "Error from TOC entry %d; %u %u %s %s %s\n",
				  AH->currentTE->dumpId,
B
Bruce Momjian 已提交
1186 1187
		 AH->currentTE->catalogId.tableoid, AH->currentTE->catalogId.oid,
		  AH->currentTE->desc, AH->currentTE->tag, AH->currentTE->owner);
1188 1189 1190 1191
	}
	AH->lastErrorStage = AH->stage;
	AH->lastErrorTE = AH->currentTE;

1192
	va_start(ap, fmt);
1193
	if (AH->public.exit_on_error)
1194 1195 1196 1197 1198 1199 1200 1201
		_die_horribly(AH, modulename, fmt, ap);
	else
	{
		_write_msg(modulename, fmt, ap);
		AH->public.n_errors++;
	}
	va_end(ap);
}
1202

B
Bruce Momjian 已提交
1203 1204
static void
_moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
B
Bruce Momjian 已提交
1205
{
B
Bruce Momjian 已提交
1206 1207
	te->prev->next = te->next;
	te->next->prev = te->prev;
B
Bruce Momjian 已提交
1208

B
Bruce Momjian 已提交
1209 1210
	te->prev = pos;
	te->next = pos->next;
B
Bruce Momjian 已提交
1211

B
Bruce Momjian 已提交
1212 1213
	pos->next->prev = te;
	pos->next = te;
B
Bruce Momjian 已提交
1214 1215
}

1216 1217
#ifdef NOT_USED

B
Bruce Momjian 已提交
1218 1219
static void
_moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
B
Bruce Momjian 已提交
1220
{
B
Bruce Momjian 已提交
1221 1222
	te->prev->next = te->next;
	te->next->prev = te->prev;
B
Bruce Momjian 已提交
1223

B
Bruce Momjian 已提交
1224 1225 1226 1227
	te->prev = pos->prev;
	te->next = pos;
	pos->prev->next = te;
	pos->prev = te;
B
Bruce Momjian 已提交
1228
}
1229 1230
#endif

B
Bruce Momjian 已提交
1231
static TocEntry *
1232
getTocEntryByDumpId(ArchiveHandle *AH, DumpId id)
B
Bruce Momjian 已提交
1233
{
B
Bruce Momjian 已提交
1234 1235 1236 1237 1238
	TocEntry   *te;

	te = AH->toc->next;
	while (te != AH->toc)
	{
1239
		if (te->dumpId == id)
B
Bruce Momjian 已提交
1240 1241 1242 1243
			return te;
		te = te->next;
	}
	return NULL;
B
Bruce Momjian 已提交
1244 1245
}

1246
teReqs
1247
TocIDRequired(ArchiveHandle *AH, DumpId id, RestoreOptions *ropt)
B
Bruce Momjian 已提交
1248
{
1249
	TocEntry   *te = getTocEntryByDumpId(AH, id);
B
Bruce Momjian 已提交
1250

B
Bruce Momjian 已提交
1251 1252
	if (!te)
		return 0;
B
Bruce Momjian 已提交
1253

1254
	return _tocEntryRequired(te, ropt, true);
B
Bruce Momjian 已提交
1255 1256
}

1257 1258 1259
size_t
WriteOffset(ArchiveHandle *AH, off_t o, int wasSet)
{
B
Bruce Momjian 已提交
1260
	int			off;
1261 1262 1263 1264 1265 1266 1267

	/* 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 已提交
1268
		(*AH->WriteBytePtr) (AH, o & 0xFF);
1269 1270 1271 1272 1273 1274 1275 1276
		o >>= 8;
	}
	return sizeof(off_t) + 1;
}

int
ReadOffset(ArchiveHandle *AH, off_t *o)
{
B
Bruce Momjian 已提交
1277 1278 1279
	int			i;
	int			off;
	int			offsetFlg;
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290

	/* 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 已提交
1291
			return K_OFFSET_POS_NOT_SET;
1292
		else if (i == 0)
B
Bruce Momjian 已提交
1293
			return K_OFFSET_NO_DATA;
1294 1295

		/* Cast to off_t because it was written as an int. */
B
Bruce Momjian 已提交
1296
		*o = (off_t) i;
1297 1298 1299 1300
		return K_OFFSET_POS_SET;
	}

	/*
B
Bruce Momjian 已提交
1301 1302
	 * Read the flag indicating the state of the data pointer. Check if
	 * valid and die if not.
1303
	 *
B
Bruce Momjian 已提交
1304 1305
	 * This used to be handled by a negative or zero pointer, now we use an
	 * extra byte specifically for the state.
1306 1307 1308 1309 1310 1311 1312 1313 1314
	 */
	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 已提交
1315
			break;
1316 1317

		default:
B
Bruce Momjian 已提交
1318
			die_horribly(AH, modulename, "Unexpected data offset flag %d\n", offsetFlg);
1319 1320 1321 1322 1323 1324 1325 1326
	}

	/*
	 * Read the bytes
	 */
	for (off = 0; off < AH->offSize; off++)
	{
		if (off < sizeof(off_t))
1327
			*o |= ((off_t) ((*AH->ReadBytePtr) (AH))) << (off * 8);
1328 1329 1330
		else
		{
			if ((*AH->ReadBytePtr) (AH) != 0)
B
Bruce Momjian 已提交
1331
				die_horribly(AH, modulename, "file offset in dump file is too large\n");
1332 1333 1334 1335 1336 1337
		}
	}

	return offsetFlg;
}

P
Peter Eisentraut 已提交
1338
size_t
B
Bruce Momjian 已提交
1339
WriteInt(ArchiveHandle *AH, int i)
B
Bruce Momjian 已提交
1340
{
B
Bruce Momjian 已提交
1341 1342 1343 1344
	int			b;

	/*
	 * This is a bit yucky, but I don't want to make the binary format
1345
	 * very dependent on representation, and not knowing much about it, I
B
Bruce Momjian 已提交
1346 1347 1348 1349 1350 1351 1352 1353 1354
	 * 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.
	 */

	/* SIGN byte */
	if (i < 0)
	{
		(*AH->WriteBytePtr) (AH, 1);
1355
		i = -i;
B
Bruce Momjian 已提交
1356 1357 1358 1359 1360 1361 1362
	}
	else
		(*AH->WriteBytePtr) (AH, 0);

	for (b = 0; b < AH->intSize; b++)
	{
		(*AH->WriteBytePtr) (AH, i & 0xFF);
1363
		i >>= 8;
B
Bruce Momjian 已提交
1364 1365 1366
	}

	return AH->intSize + 1;
B
Bruce Momjian 已提交
1367 1368
}

B
Bruce Momjian 已提交
1369 1370
int
ReadInt(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1371
{
B
Bruce Momjian 已提交
1372 1373 1374 1375 1376
	int			res = 0;
	int			bv,
				b;
	int			sign = 0;		/* Default positive */
	int			bitShift = 0;
B
Bruce Momjian 已提交
1377

B
Bruce Momjian 已提交
1378
	if (AH->version > K_VERS_1_0)
1379
		/* Read a sign byte */
B
Bruce Momjian 已提交
1380
		sign = (*AH->ReadBytePtr) (AH);
B
Bruce Momjian 已提交
1381

B
Bruce Momjian 已提交
1382 1383 1384
	for (b = 0; b < AH->intSize; b++)
	{
		bv = (*AH->ReadBytePtr) (AH) & 0xFF;
1385 1386 1387
		if (bv != 0)
			res = res + (bv << bitShift);
		bitShift += 8;
B
Bruce Momjian 已提交
1388
	}
B
Bruce Momjian 已提交
1389

B
Bruce Momjian 已提交
1390 1391
	if (sign)
		res = -res;
B
Bruce Momjian 已提交
1392

B
Bruce Momjian 已提交
1393
	return res;
B
Bruce Momjian 已提交
1394 1395
}

P
Peter Eisentraut 已提交
1396
size_t
1397
WriteStr(ArchiveHandle *AH, const char *c)
B
Bruce Momjian 已提交
1398
{
P
Peter Eisentraut 已提交
1399
	size_t		res;
1400 1401 1402 1403

	if (c)
	{
		res = WriteInt(AH, strlen(c));
B
Bruce Momjian 已提交
1404
		res += (*AH->WriteBufPtr) (AH, c, strlen(c));
1405 1406 1407 1408
	}
	else
		res = WriteInt(AH, -1);

B
Bruce Momjian 已提交
1409
	return res;
B
Bruce Momjian 已提交
1410 1411
}

B
Bruce Momjian 已提交
1412 1413
char *
ReadStr(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1414
{
B
Bruce Momjian 已提交
1415 1416
	char	   *buf;
	int			l;
B
Bruce Momjian 已提交
1417

B
Bruce Momjian 已提交
1418
	l = ReadInt(AH);
1419 1420 1421 1422
	if (l == -1)
		buf = NULL;
	else
	{
B
Bruce Momjian 已提交
1423
		buf = (char *) malloc(l + 1);
1424
		if (!buf)
1425
			die_horribly(AH, modulename, "out of memory\n");
1426

B
Bruce Momjian 已提交
1427
		(*AH->ReadBufPtr) (AH, (void *) buf, l);
1428 1429
		buf[l] = '\0';
	}
B
Bruce Momjian 已提交
1430

B
Bruce Momjian 已提交
1431
	return buf;
B
Bruce Momjian 已提交
1432 1433
}

T
Tom Lane 已提交
1434
static int
B
Bruce Momjian 已提交
1435
_discoverArchiveFormat(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1436
{
B
Bruce Momjian 已提交
1437 1438
	FILE	   *fh;
	char		sig[6];			/* More than enough */
P
Peter Eisentraut 已提交
1439
	size_t		cnt;
B
Bruce Momjian 已提交
1440
	int			wantClose = 0;
B
Bruce Momjian 已提交
1441

1442
#if 0
1443
	write_msg(modulename, "attempting to ascertain archive format\n");
1444
#endif
1445 1446 1447 1448 1449 1450 1451 1452

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

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

B
Bruce Momjian 已提交
1454 1455
	if (AH->fSpec)
	{
1456 1457
		wantClose = 1;
		fh = fopen(AH->fSpec, PG_BINARY_R);
B
Bruce Momjian 已提交
1458 1459
	}
	else
1460
		fh = stdin;
B
Bruce Momjian 已提交
1461

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

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

B
Bruce Momjian 已提交
1467
	if (cnt != 5)
1468 1469 1470 1471
	{
		if (ferror(fh))
			die_horribly(AH, modulename, "could not read input file: %s\n", strerror(errno));
		else
P
Peter Eisentraut 已提交
1472 1473
			die_horribly(AH, modulename, "input file is too short (read %lu, expected 5)\n",
						 (unsigned long) cnt);
1474
	}
B
Bruce Momjian 已提交
1475

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

B
Bruce Momjian 已提交
1480
	if (strncmp(sig, "PGDMP", 5) == 0)
1481 1482 1483 1484 1485 1486 1487 1488 1489
	{
		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 已提交
1490 1491
		if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0)))		/* Version > 1.0 */
		{
1492 1493 1494 1495 1496 1497
			AH->vrev = fgetc(fh);
			AH->lookahead[AH->lookaheadLen++] = AH->vrev;
		}
		else
			AH->vrev = 0;

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

1501 1502 1503
		AH->intSize = fgetc(fh);
		AH->lookahead[AH->lookaheadLen++] = AH->intSize;

1504 1505 1506 1507 1508 1509 1510 1511
		if (AH->version >= K_VERS_1_7)
		{
			AH->offSize = fgetc(fh);
			AH->lookahead[AH->lookaheadLen++] = AH->offSize;
		}
		else
			AH->offSize = AH->intSize;

1512 1513
		AH->format = fgetc(fh);
		AH->lookahead[AH->lookaheadLen++] = AH->format;
B
Bruce Momjian 已提交
1514 1515 1516
	}
	else
	{
1517
		/*
B
Bruce Momjian 已提交
1518 1519
		 * *Maybe* we have a tar archive format file... So, read first 512
		 * byte header...
1520 1521 1522
		 */
		cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
		AH->lookaheadLen += cnt;
B
Bruce Momjian 已提交
1523

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

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

1530 1531
		AH->format = archTar;
	}
B
Bruce Momjian 已提交
1532

B
Bruce Momjian 已提交
1533
	/* If we can't seek, then mark the header as read */
P
Peter Eisentraut 已提交
1534
	if (fseeko(fh, 0, SEEK_SET) != 0)
1535 1536
	{
		/*
1537
		 * NOTE: Formats that use the lookahead buffer can unset this in
B
Bruce Momjian 已提交
1538
		 * their Init routine.
1539 1540 1541 1542
		 */
		AH->readHeader = 1;
	}
	else
B
Bruce Momjian 已提交
1543
		AH->lookaheadLen = 0;	/* Don't bother since we've reset the file */
1544

1545
#if 0
P
Peter Eisentraut 已提交
1546 1547
	write_msg(modulename, "read %lu bytes into lookahead buffer\n",
			  (unsigned long) AH->lookaheadLen);
1548
#endif
B
Bruce Momjian 已提交
1549

B
Bruce Momjian 已提交
1550 1551
	/* Close the file */
	if (wantClose)
1552
		if (fclose(fh) != 0)
1553 1554
			die_horribly(AH, modulename, "could not close the input file after reading header: %s\n",
						 strerror(errno));
B
Bruce Momjian 已提交
1555

B
Bruce Momjian 已提交
1556
	return AH->format;
B
Bruce Momjian 已提交
1557 1558 1559 1560 1561 1562
}


/*
 * Allocate an archive handle
 */
B
Bruce Momjian 已提交
1563 1564 1565
static ArchiveHandle *
_allocAH(const char *FileSpec, const ArchiveFormat fmt,
		 const int compression, ArchiveMode mode)
1566
{
B
Bruce Momjian 已提交
1567
	ArchiveHandle *AH;
B
Bruce Momjian 已提交
1568

1569
#if 0
1570
	write_msg(modulename, "allocating AH for %s, format %d\n", FileSpec, fmt);
1571
#endif
1572

B
Bruce Momjian 已提交
1573 1574
	AH = (ArchiveHandle *) calloc(1, sizeof(ArchiveHandle));
	if (!AH)
1575
		die_horribly(AH, modulename, "out of memory\n");
B
Bruce Momjian 已提交
1576

1577 1578
	/* AH->debugLevel = 100; */

B
Bruce Momjian 已提交
1579 1580
	AH->vmaj = K_VERS_MAJOR;
	AH->vmin = K_VERS_MINOR;
1581
	AH->vrev = K_VERS_REV;
B
Bruce Momjian 已提交
1582

1583 1584
	AH->createDate = time(NULL);

B
Bruce Momjian 已提交
1585
	AH->intSize = sizeof(int);
1586
	AH->offSize = sizeof(off_t);
B
Bruce Momjian 已提交
1587 1588
	if (FileSpec)
	{
1589
		AH->fSpec = strdup(FileSpec);
B
Bruce Momjian 已提交
1590

1591 1592 1593
		/*
		 * Not used; maybe later....
		 *
B
Bruce Momjian 已提交
1594 1595
		 * AH->workDir = strdup(FileSpec); for(i=strlen(FileSpec) ; i > 0 ;
		 * i--) if (AH->workDir[i-1] == '/')
1596
		 */
B
Bruce Momjian 已提交
1597 1598
	}
	else
1599
		AH->fSpec = NULL;
B
Bruce Momjian 已提交
1600

B
Bruce Momjian 已提交
1601 1602
	AH->currUser = strdup("");	/* So it's valid, but we can free() it
								 * later if necessary */
B
Bruce Momjian 已提交
1603
	AH->currSchema = strdup("");	/* ditto */
1604
	AH->currWithOids = -1;		/* force SET */
B
Bruce Momjian 已提交
1605

B
Bruce Momjian 已提交
1606 1607
	AH->toc = (TocEntry *) calloc(1, sizeof(TocEntry));
	if (!AH->toc)
1608
		die_horribly(AH, modulename, "out of memory\n");
B
Bruce Momjian 已提交
1609

B
Bruce Momjian 已提交
1610 1611 1612 1613 1614
	AH->toc->next = AH->toc;
	AH->toc->prev = AH->toc;

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

1616 1617
	AH->pgCopyBuf = createPQExpBuffer();
	AH->sqlBuf = createPQExpBuffer();
B
Bruce Momjian 已提交
1618

B
Bruce Momjian 已提交
1619 1620 1621
	/* Open stdout with no compression for AH output handle */
	AH->gzOut = 0;
	AH->OF = stdout;
B
Bruce Momjian 已提交
1622

1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
	/*
	 * On Windows, we need to use binary mode to read/write non-text archive
	 * formats.  Force stdin/stdout into binary mode in case that is what
	 * we are using.
	 */
#ifdef WIN32
	if (fmt != archNull)
	{
		if (mode == archModeWrite)
			setmode(fileno(stdout), O_BINARY);
		else
			setmode(fileno(stdin), O_BINARY);
	}
#endif

1638
#if 0
1639
	write_msg(modulename, "archive format is %d\n", fmt);
1640
#endif
1641

B
Bruce Momjian 已提交
1642
	if (fmt == archUnknown)
1643 1644 1645
		AH->format = _discoverArchiveFormat(AH);
	else
		AH->format = fmt;
B
Bruce Momjian 已提交
1646

B
Bruce Momjian 已提交
1647 1648
	switch (AH->format)
	{
1649 1650 1651
		case archCustom:
			InitArchiveFmt_Custom(AH);
			break;
B
Bruce Momjian 已提交
1652

1653 1654 1655
		case archFiles:
			InitArchiveFmt_Files(AH);
			break;
B
Bruce Momjian 已提交
1656

1657 1658 1659
		case archNull:
			InitArchiveFmt_Null(AH);
			break;
B
Bruce Momjian 已提交
1660

1661 1662 1663 1664 1665
		case archTar:
			InitArchiveFmt_Tar(AH);
			break;

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

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

B
Bruce Momjian 已提交
1673
	return AH;
B
Bruce Momjian 已提交
1674 1675 1676
}


B
Bruce Momjian 已提交
1677 1678
void
WriteDataChunks(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1679
{
B
Bruce Momjian 已提交
1680 1681 1682
	TocEntry   *te = AH->toc->next;
	StartDataPtr startPtr;
	EndDataPtr	endPtr;
B
Bruce Momjian 已提交
1683

B
Bruce Momjian 已提交
1684 1685 1686
	while (te != AH->toc)
	{
		if (te->dataDumper != NULL)
1687
		{
B
Bruce Momjian 已提交
1688 1689
			AH->currToc = te;
			/* printf("Writing data for %d (%x)\n", te->id, te); */
1690

B
Bruce Momjian 已提交
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
			if (strcmp(te->desc, "BLOBS") == 0)
			{
				startPtr = AH->StartBlobsPtr;
				endPtr = AH->EndBlobsPtr;
			}
			else
			{
				startPtr = AH->StartDataPtr;
				endPtr = AH->EndDataPtr;
			}
B
Bruce Momjian 已提交
1701

B
Bruce Momjian 已提交
1702 1703
			if (startPtr != NULL)
				(*startPtr) (AH, te);
B
Bruce Momjian 已提交
1704

B
Bruce Momjian 已提交
1705 1706 1707 1708 1709 1710 1711 1712 1713
			/*
			 * printf("Dumper arg for %d is %x\n", te->id,
			 * te->dataDumperArg);
			 */

			/*
			 * The user-provided DataDumper routine needs to call
			 * AH->WriteData
			 */
1714
			(*te->dataDumper) ((Archive *) AH, te->dataDumperArg);
B
Bruce Momjian 已提交
1715 1716 1717 1718 1719

			if (endPtr != NULL)
				(*endPtr) (AH, te);
			AH->currToc = NULL;
		}
1720
		te = te->next;
B
Bruce Momjian 已提交
1721
	}
B
Bruce Momjian 已提交
1722 1723
}

B
Bruce Momjian 已提交
1724 1725
void
WriteToc(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1726
{
1727 1728
	TocEntry   *te;
	char		workbuf[32];
1729
	int			i;
B
Bruce Momjian 已提交
1730 1731 1732 1733

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

	WriteInt(AH, AH->tocCount);
1734 1735

	for (te = AH->toc->next; te != AH->toc; te = te->next)
B
Bruce Momjian 已提交
1736
	{
1737
		WriteInt(AH, te->dumpId);
B
Bruce Momjian 已提交
1738
		WriteInt(AH, te->dataDumper ? 1 : 0);
1739 1740 1741 1742 1743 1744

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

1746
		WriteStr(AH, te->tag);
B
Bruce Momjian 已提交
1747 1748 1749 1750
		WriteStr(AH, te->desc);
		WriteStr(AH, te->defn);
		WriteStr(AH, te->dropStmt);
		WriteStr(AH, te->copyStmt);
1751
		WriteStr(AH, te->namespace);
1752
		WriteStr(AH, te->tablespace);
B
Bruce Momjian 已提交
1753
		WriteStr(AH, te->owner);
1754
		WriteStr(AH, te->withOids ? "true" : "false");
1755 1756

		/* Dump list of dependencies */
1757
		for (i = 0; i < te->nDeps; i++)
1758
		{
1759 1760
			sprintf(workbuf, "%d", te->dependencies[i]);
			WriteStr(AH, workbuf);
1761
		}
1762
		WriteStr(AH, NULL);		/* Terminate List */
1763

B
Bruce Momjian 已提交
1764 1765 1766
		if (AH->WriteExtraTocPtr)
			(*AH->WriteExtraTocPtr) (AH, te);
	}
B
Bruce Momjian 已提交
1767 1768
}

B
Bruce Momjian 已提交
1769 1770
void
ReadToc(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1771
{
B
Bruce Momjian 已提交
1772
	int			i;
1773 1774
	char	   *tmp;
	DumpId	   *deps;
1775 1776
	int			depIdx;
	int			depSize;
B
Bruce Momjian 已提交
1777

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

B
Bruce Momjian 已提交
1780
	AH->tocCount = ReadInt(AH);
1781
	AH->maxDumpId = 0;
B
Bruce Momjian 已提交
1782

B
Bruce Momjian 已提交
1783 1784 1785
	for (i = 0; i < AH->tocCount; i++)
	{
		te = (TocEntry *) calloc(1, sizeof(TocEntry));
1786 1787 1788 1789
		te->dumpId = ReadInt(AH);

		if (te->dumpId > AH->maxDumpId)
			AH->maxDumpId = te->dumpId;
1790 1791

		/* Sanity check */
1792 1793
		if (te->dumpId <= 0)
			die_horribly(AH, modulename,
B
Bruce Momjian 已提交
1794
				   "entry ID %d out of range -- perhaps a corrupt TOC\n",
1795
						 te->dumpId);
1796 1797

		te->hadDumper = ReadInt(AH);
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809

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

1811
		te->tag = ReadStr(AH);
1812 1813 1814 1815 1816 1817 1818
		te->desc = ReadStr(AH);
		te->defn = ReadStr(AH);
		te->dropStmt = ReadStr(AH);

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

1819 1820 1821
		if (AH->version >= K_VERS_1_6)
			te->namespace = ReadStr(AH);

1822 1823 1824
		if (AH->version >= K_VERS_1_10)
			te->tablespace = ReadStr(AH);

1825
		te->owner = ReadStr(AH);
1826 1827 1828 1829 1830 1831 1832 1833 1834
		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 已提交
1835

1836 1837 1838 1839
		/* Read TOC entry dependencies */
		if (AH->version >= K_VERS_1_5)
		{
			depSize = 100;
1840
			deps = (DumpId *) malloc(sizeof(DumpId) * depSize);
1841
			depIdx = 0;
1842
			for (;;)
1843
			{
1844 1845 1846
				tmp = ReadStr(AH);
				if (!tmp)
					break;		/* end of list */
1847
				if (depIdx >= depSize)
1848 1849
				{
					depSize *= 2;
1850
					deps = (DumpId *) realloc(deps, sizeof(DumpId) * depSize);
1851
				}
1852 1853 1854 1855
				sscanf(tmp, "%d", &deps[depIdx]);
				free(tmp);
				depIdx++;
			}
1856

1857 1858 1859 1860 1861 1862
			if (depIdx > 0)		/* We have a non-null entry */
			{
				deps = (DumpId *) realloc(deps, sizeof(DumpId) * depIdx);
				te->dependencies = deps;
				te->nDeps = depIdx;
			}
1863
			else
1864 1865
			{
				free(deps);
1866 1867
				te->dependencies = NULL;
				te->nDeps = 0;
1868
			}
1869
		}
1870
		else
1871 1872 1873 1874
		{
			te->dependencies = NULL;
			te->nDeps = 0;
		}
1875

B
Bruce Momjian 已提交
1876 1877
		if (AH->ReadExtraTocPtr)
			(*AH->ReadExtraTocPtr) (AH, te);
1878

1879 1880
		ahlog(AH, 3, "read TOC entry %d (ID %d) for %s %s\n",
			  i, te->dumpId, te->desc, te->tag);
1881 1882 1883 1884 1885

		te->prev = AH->toc->prev;
		AH->toc->prev->next = te;
		AH->toc->prev = te;
		te->next = AH->toc;
B
Bruce Momjian 已提交
1886
	}
B
Bruce Momjian 已提交
1887 1888
}

1889
static teReqs
1890
_tocEntryRequired(TocEntry *te, RestoreOptions *ropt, bool include_acls)
B
Bruce Momjian 已提交
1891
{
1892
	teReqs		res = REQ_ALL;
B
Bruce Momjian 已提交
1893

1894 1895 1896 1897
	/* ENCODING objects are dumped specially, so always reject here */
	if (strcmp(te->desc, "ENCODING") == 0)
		return 0;

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

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

B
Bruce Momjian 已提交
1905 1906 1907
	/* Check if tablename only is wanted */
	if (ropt->selTypes)
	{
1908 1909 1910 1911 1912 1913 1914 1915
		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 已提交
1916
		if ((strcmp(te->desc, "TABLE") == 0) || (strcmp(te->desc, "TABLE DATA") == 0))
1917 1918 1919
		{
			if (!ropt->selTable)
				return 0;
1920
			if (ropt->tableNames && strcmp(ropt->tableNames, te->tag) != 0)
1921
				return 0;
B
Bruce Momjian 已提交
1922 1923 1924
		}
		else if (strcmp(te->desc, "INDEX") == 0)
		{
1925 1926
			if (!ropt->selIndex)
				return 0;
1927
			if (ropt->indexNames && strcmp(ropt->indexNames, te->tag) != 0)
1928
				return 0;
B
Bruce Momjian 已提交
1929 1930 1931
		}
		else if (strcmp(te->desc, "FUNCTION") == 0)
		{
1932 1933
			if (!ropt->selFunction)
				return 0;
1934
			if (ropt->functionNames && strcmp(ropt->functionNames, te->tag) != 0)
1935
				return 0;
B
Bruce Momjian 已提交
1936 1937 1938
		}
		else if (strcmp(te->desc, "TRIGGER") == 0)
		{
1939 1940
			if (!ropt->selTrigger)
				return 0;
1941
			if (ropt->triggerNames && strcmp(ropt->triggerNames, te->tag) != 0)
1942 1943
				return 0;
		}
B
Bruce Momjian 已提交
1944 1945
		else
			return 0;
B
Bruce Momjian 已提交
1946 1947
	}

1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
	/*
	 * Check if we had a dataDumper. Indicates if the entry is schema or
	 * data
	 */
	if (!te->hadDumper)
	{
		/*
		 * Special Case: If 'SEQUENCE SET' then it is considered a data
		 * entry
		 */
		if (strcmp(te->desc, "SEQUENCE SET") == 0)
			res = res & REQ_DATA;
		else
1961 1962
			res = res & ~REQ_DATA;
	}
1963

1964
	/*
1965 1966
	 * Special case: <Init> type with <Max OID> tag; this is obsolete
	 * and we always ignore it.
1967
	 */
1968
	if ((strcmp(te->desc, "<Init>") == 0) && (strcmp(te->tag, "Max OID") == 0))
1969
		return 0;
1970

B
Bruce Momjian 已提交
1971 1972
	/* Mask it if we only want schema */
	if (ropt->schemaOnly)
1973
		res = res & REQ_SCHEMA;
B
Bruce Momjian 已提交
1974

B
Bruce Momjian 已提交
1975
	/* Mask it we only want data */
1976
	if (ropt->dataOnly)
1977
		res = res & REQ_DATA;
B
Bruce Momjian 已提交
1978

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

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

B
Bruce Momjian 已提交
1987
	return res;
B
Bruce Momjian 已提交
1988 1989
}

1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
/*
 * 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");

2014 2015 2016
	/* Avoid annoying notices etc */
	ahprintf(AH, "SET client_min_messages = warning;\n");

2017 2018 2019
	ahprintf(AH, "\n");
}

2020 2021
/*
 * Issue a SET SESSION AUTHORIZATION command.  Caller is responsible
2022 2023
 * for updating state if appropriate.  If user is NULL or an empty string,
 * the specification DEFAULT will be used.
2024 2025
 */
static void
2026
_doSetSessionAuth(ArchiveHandle *AH, const char *user)
2027
{
2028
	PQExpBuffer cmd = createPQExpBuffer();
B
Bruce Momjian 已提交
2029

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

2032 2033 2034 2035
	/*
	 * SQL requires a string literal here.	Might as well be correct.
	 */
	if (user && *user)
2036 2037 2038 2039 2040
		appendStringLiteral(cmd, user, false);
	else
		appendPQExpBuffer(cmd, "DEFAULT");
	appendPQExpBuffer(cmd, ";");

2041 2042 2043 2044
	if (RestoringToDB(AH))
	{
		PGresult   *res;

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

		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
2048
			/* NOT warn_or_die_horribly... use -O instead to skip this. */
2049
			die_horribly(AH, modulename, "could not set session user to \"%s\": %s",
2050
						 user, PQerrorMessage(AH->connection));
2051 2052 2053 2054

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

	destroyPQExpBuffer(cmd);
2058 2059
}

2060

2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
/*
 * 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 已提交
2071
					  "true" : "false");
2072 2073 2074 2075 2076 2077 2078 2079

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

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

		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
B
Bruce Momjian 已提交
2080
			warn_or_die_horribly(AH, modulename,
2081 2082
								 "could not set default_with_oids: %s",
								 PQerrorMessage(AH->connection));
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092

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

	destroyPQExpBuffer(cmd);
}


2093
/*
2094
 * Issue the commands to connect to the specified database.
2095 2096
 *
 * If we're currently restoring right into a database, this will
B
Bruce Momjian 已提交
2097
 * actually establish a connection. Otherwise it puts a \connect into
2098
 * the script output.
2099 2100
 *
 * NULL dbname implies reconnecting to the current DB (pretty useless).
2101
 */
B
Bruce Momjian 已提交
2102
static void
2103
_reconnectToDB(ArchiveHandle *AH, const char *dbname)
2104
{
2105
	if (RestoringToDB(AH))
2106
		ReconnectToServer(AH, dbname, NULL);
2107
	else
2108 2109 2110
	{
		PQExpBuffer qry = createPQExpBuffer();

2111
		appendPQExpBuffer(qry, "\\connect %s\n\n",
2112
						  dbname ? fmtId(dbname) : "-");
2113
		ahprintf(AH, "%s", qry->data);
2114 2115
		destroyPQExpBuffer(qry);
	}
2116

2117 2118
	/*
	 * NOTE: currUser keeps track of what the imaginary session user in
2119
	 * our script is.  It's now effectively reset to the original userID.
2120
	 */
2121 2122 2123
	if (AH->currUser)
		free(AH->currUser);

2124
	AH->currUser = strdup("");
2125 2126 2127 2128 2129

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

2132 2133
	/* re-establish fixed state */
	_doSetFixedOutputState(AH);
2134 2135
}

2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
/*
 * 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);

	/*
	 * NOTE: currUser keeps track of what the imaginary session user in
	 * our script is
	 */
	if (AH->currUser)
		free(AH->currUser);

	AH->currUser = strdup(user);
}
2161 2162

/*
B
Bruce Momjian 已提交
2163
 * Become the owner of the the given TOC entry object.	If
2164 2165
 * changes in ownership are not allowed, this doesn't do anything.
 */
B
Bruce Momjian 已提交
2166
static void
2167
_becomeOwner(ArchiveHandle *AH, TocEntry *te)
2168
{
2169
	if (AH->ropt && (AH->ropt->noOwner || !AH->ropt->use_setsessauth))
2170 2171
		return;

2172
	_becomeUser(AH, te->owner);
2173 2174
}

2175

2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
/*
 * 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;
	}
}


2190 2191 2192 2193 2194 2195 2196
/*
 * Issue the commands to select the specified schema as the current schema
 * in the target database.
 */
static void
_selectOutputSchema(ArchiveHandle *AH, const char *schemaName)
{
2197 2198
	PQExpBuffer qry;

2199 2200 2201 2202
	if (!schemaName || *schemaName == '\0' ||
		strcmp(AH->currSchema, schemaName) == 0)
		return;					/* no need to do anything */

2203 2204 2205
	qry = createPQExpBuffer();

	appendPQExpBuffer(qry, "SET search_path = %s",
2206
					  fmtId(schemaName));
2207 2208 2209
	if (strcmp(schemaName, "pg_catalog") != 0)
		appendPQExpBuffer(qry, ", pg_catalog");

2210 2211 2212 2213 2214 2215 2216
	if (RestoringToDB(AH))
	{
		PGresult   *res;

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

		if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
B
Bruce Momjian 已提交
2217 2218 2219
			warn_or_die_horribly(AH, modulename,
							   "could not set search_path to \"%s\": %s",
							 schemaName, PQerrorMessage(AH->connection));
2220 2221 2222 2223

		PQclear(res);
	}
	else
2224
		ahprintf(AH, "%s;\n\n", qry->data);
2225 2226 2227 2228

	if (AH->currSchema)
		free(AH->currSchema);
	AH->currSchema = strdup(schemaName);
2229 2230

	destroyPQExpBuffer(qry);
2231 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 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287
/*
 * 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;
	const char	*want, *have;

	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)
			warn_or_die_horribly(AH, modulename, 
								 "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);
}
2288

2289 2290 2291 2292 2293 2294 2295 2296
/*
 * 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.
2297
 */
2298
static void
2299
_getObjectDescription(PQExpBuffer buf, TocEntry *te, ArchiveHandle *AH)
2300
{
2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313
	const char *type = te->desc;

	/* Use ALTER TABLE for views and sequences */
	if (strcmp(type, "VIEW") == 0 ||
		strcmp(type, "SEQUENCE") == 0)
		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)
	{
2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329
		appendPQExpBuffer(buf, "%s ", type);
		if (te->namespace && te->namespace[0])			/* is null pre-7.3 */
			appendPQExpBuffer(buf, "%s.", fmtId(te->namespace));
		/*
		 * 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.
		 */
		if (AH->version < K_VERS_1_7 &&
			te->tag[0] == '"' &&
			te->tag[strlen(te->tag)-1] == '"' &&
			strcmp(type, "INDEX") == 0)
			appendPQExpBuffer(buf, "%s", te->tag);
		else
			appendPQExpBuffer(buf, "%s", fmtId(te->tag));
2330 2331
		return;
	}
2332

2333 2334 2335 2336 2337 2338 2339
	/* objects named by just a name */
	if (strcmp(type, "DATABASE") == 0 ||
		strcmp(type, "SCHEMA") == 0)
	{
		appendPQExpBuffer(buf, "%s %s", type, fmtId(te->tag));
		return;
	}
2340

B
Bruce Momjian 已提交
2341
	/*
2342 2343
	 * These object types require additional decoration.  Fortunately,
	 * the information needed is exactly what's in the DROP command.
B
Bruce Momjian 已提交
2344
	 */
2345 2346 2347 2348
	if (strcmp(type, "AGGREGATE") == 0 ||
		strcmp(type, "FUNCTION") == 0 ||
		strcmp(type, "OPERATOR") == 0 ||
		strcmp(type, "OPERATOR CLASS") == 0)
B
Bruce Momjian 已提交
2349
	{
2350 2351 2352
		/* Chop "DROP " off the front and make a modifiable copy */
		char	   *first = strdup(te->dropStmt + 5);
		char	   *last;
2353

2354 2355
		/* point to last character in string */
		last = first + strlen(first) - 1;
2356

2357 2358 2359 2360
		/* Strip off any ';' or '\n' at the end */
		while (last >= first && (*last == '\n' || *last == ';'))
			last--;
		*(last + 1) = '\0';
B
Bruce Momjian 已提交
2361

2362
		appendPQExpBufferStr(buf, first);
B
Bruce Momjian 已提交
2363 2364

		free(first);
2365
		return;
2366 2367
	}

2368 2369
	write_msg(modulename, "WARNING: don't know how to set owner for object type %s\n",
			  type);
2370 2371 2372
}

static void
2373
_printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData, bool acl_pass)
B
Bruce Momjian 已提交
2374
{
2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395
	/* 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 ...
	 * unless we are using --clean mode, in which case it's been deleted
	 * and we'd better recreate it.
	 */
	if (!ropt->dropSchema &&
		strcmp(te->desc, "SCHEMA") == 0 && strcmp(te->tag, "public") == 0)
		return;

2396
	/* Select owner, schema, and tablespace as necessary */
2397 2398
	_becomeOwner(AH, te);
	_selectOutputSchema(AH, te->namespace);
2399
	_selectTablespace(AH, te->tablespace);
2400 2401 2402 2403 2404 2405

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

	/* Emit header comment for item */
2406
	if (!AH->noTocComments)
2407
	{
2408 2409 2410 2411 2412 2413 2414 2415 2416
		const char *pfx;

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

		ahprintf(AH, "--\n");
		if (AH->public.verbose)
2417
		{
2418 2419 2420 2421 2422
			ahprintf(AH, "-- TOC entry %d (class %u OID %u)\n",
					 te->dumpId, te->catalogId.tableoid, te->catalogId.oid);
			if (te->nDeps > 0)
			{
				int			i;
2423

2424 2425 2426 2427 2428
				ahprintf(AH, "-- Dependencies:");
				for (i = 0; i < te->nDeps; i++)
					ahprintf(AH, " %d", te->dependencies[i]);
				ahprintf(AH, "\n");
			}
2429
		}
2430
		ahprintf(AH, "-- %sName: %s; Type: %s; Schema: %s; Owner: %s",
2431 2432 2433
				 pfx, te->tag, te->desc,
				 te->namespace ? te->namespace : "-",
				 te->owner);
2434 2435 2436 2437
		if (te->tablespace) 
			ahprintf(AH, "; Tablespace: %s", te->tablespace);
		ahprintf(AH, "\n");

2438 2439 2440
		if (AH->PrintExtraTocPtr != NULL)
			(*AH->PrintExtraTocPtr) (AH, te);
		ahprintf(AH, "--\n\n");
2441
	}
B
Bruce Momjian 已提交
2442

2443 2444 2445
	/*
	 * Actually print the definition.
	 *
2446 2447 2448
	 * 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
B
Bruce Momjian 已提交
2449
	 * no other good way ...
2450
	 */
2451
	if (ropt->noOwner && strcmp(te->desc, "SCHEMA") == 0)
2452
	{
2453
		ahprintf(AH, "CREATE SCHEMA %s;\n\n\n", fmtId(te->tag));
2454
	}
2455
	else
2456
	{
2457 2458
		if (strlen(te->defn) > 0)
			ahprintf(AH, "%s\n\n", te->defn);
2459
	}
2460 2461 2462

	/*
	 * If we aren't using SET SESSION AUTH to determine ownership, we must
2463 2464 2465
	 * 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.
2466 2467
	 */
	if (!ropt->noOwner && !ropt->use_setsessauth &&
2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485
		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 ");
2486
			_getObjectDescription(temp, te, AH);
2487 2488 2489 2490 2491 2492
			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 ||
2493
				 strcmp(te->desc, "CONSTRAINT") == 0 ||
2494 2495
				 strcmp(te->desc, "DEFAULT") == 0 ||
				 strcmp(te->desc, "FK CONSTRAINT") == 0 ||
2496
				 strcmp(te->desc, "INDEX") == 0 ||
2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507
				 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);
		}
2508
	}
B
Bruce Momjian 已提交
2509

2510 2511
	/*
	 * If it's an ACL entry, it might contain SET SESSION AUTHORIZATION
B
Bruce Momjian 已提交
2512 2513
	 * commands, so we can no longer assume we know the current auth
	 * setting.
2514 2515 2516 2517 2518 2519 2520
	 */
	if (strncmp(te->desc, "ACL", 3) == 0)
	{
		if (AH->currUser)
			free(AH->currUser);
		AH->currUser = NULL;
	}
B
Bruce Momjian 已提交
2521 2522
}

B
Bruce Momjian 已提交
2523 2524
void
WriteHead(ArchiveHandle *AH)
B
Bruce Momjian 已提交
2525
{
B
Bruce Momjian 已提交
2526
	struct tm	crtm;
2527

B
Bruce Momjian 已提交
2528 2529 2530 2531 2532
	(*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);
2533
	(*AH->WriteBytePtr) (AH, AH->offSize);
B
Bruce Momjian 已提交
2534
	(*AH->WriteBytePtr) (AH, AH->format);
B
Bruce Momjian 已提交
2535

2536
#ifndef HAVE_LIBZ
B
Bruce Momjian 已提交
2537
	if (AH->compression != 0)
2538
		write_msg(modulename, "WARNING: requested compression not available in this "
2539
				  "installation -- archive will be uncompressed\n");
B
Bruce Momjian 已提交
2540

B
Bruce Momjian 已提交
2541
	AH->compression = 0;
2542
#endif
B
Bruce Momjian 已提交
2543

2544 2545 2546 2547 2548 2549 2550 2551 2552 2553
	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);
2554
	WriteStr(AH, PQdb(AH->connection));
2555 2556
	WriteStr(AH, AH->public.remoteVersionStr);
	WriteStr(AH, PG_VERSION);
B
Bruce Momjian 已提交
2557 2558
}

B
Bruce Momjian 已提交
2559 2560
void
ReadHead(ArchiveHandle *AH)
B
Bruce Momjian 已提交
2561
{
B
Bruce Momjian 已提交
2562 2563
	char		tmpMag[7];
	int			fmt;
2564
	struct tm	crtm;
B
Bruce Momjian 已提交
2565

2566
	/* If we haven't already read the header... */
B
Bruce Momjian 已提交
2567 2568
	if (!AH->readHeader)
	{
B
Bruce Momjian 已提交
2569

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

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

B
Bruce Momjian 已提交
2575 2576
		AH->vmaj = (*AH->ReadBytePtr) (AH);
		AH->vmin = (*AH->ReadBytePtr) (AH);
B
Bruce Momjian 已提交
2577

B
Bruce Momjian 已提交
2578 2579 2580
		if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0)))		/* Version > 1.0 */
			AH->vrev = (*AH->ReadBytePtr) (AH);
		else
2581
			AH->vrev = 0;
B
Bruce Momjian 已提交
2582

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


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

B
Bruce Momjian 已提交
2590
		AH->intSize = (*AH->ReadBytePtr) (AH);
2591
		if (AH->intSize > 32)
P
Peter Eisentraut 已提交
2592 2593
			die_horribly(AH, modulename, "sanity check on integer size (%lu) failed\n",
						 (unsigned long) AH->intSize);
B
Bruce Momjian 已提交
2594

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

2598
		if (AH->version >= K_VERS_1_7)
B
Bruce Momjian 已提交
2599
			AH->offSize = (*AH->ReadBytePtr) (AH);
2600
		else
B
Bruce Momjian 已提交
2601
			AH->offSize = AH->intSize;
2602

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

2605
		if (AH->format != fmt)
2606 2607
			die_horribly(AH, modulename, "expected format (%d) differs from format found in file (%d)\n",
						 AH->format, fmt);
B
Bruce Momjian 已提交
2608
	}
B
Bruce Momjian 已提交
2609

B
Bruce Momjian 已提交
2610 2611
	if (AH->version >= K_VERS_1_2)
	{
2612
		if (AH->version < K_VERS_1_4)
B
Bruce Momjian 已提交
2613
			AH->compression = (*AH->ReadBytePtr) (AH);
2614 2615
		else
			AH->compression = ReadInt(AH);
B
Bruce Momjian 已提交
2616 2617
	}
	else
2618
		AH->compression = Z_DEFAULT_COMPRESSION;
B
Bruce Momjian 已提交
2619

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

2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638
	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 已提交
2639
		if (AH->createDate == (time_t) -1)
2640
			write_msg(modulename, "WARNING: invalid creation date in header\n");
2641 2642
	}

2643 2644 2645 2646 2647 2648
	if (AH->version >= K_VERS_1_10)
	{
		AH->archiveRemoteVersion = ReadStr(AH);
		AH->archiveDumpVersion = ReadStr(AH);
	}

B
Bruce Momjian 已提交
2649 2650 2651
}


2652 2653 2654 2655 2656 2657 2658 2659 2660
/*
 * checkSeek
 *	  check to see if fseek can be performed.
 */

bool
checkSeek(FILE *fp)
{

B
Bruce Momjian 已提交
2661
	if (fseeko(fp, 0, SEEK_CUR) != 0)
2662 2663
		return false;
	else if (sizeof(off_t) > sizeof(long))
B
Bruce Momjian 已提交
2664 2665 2666 2667 2668

		/*
		 * At this point, off_t is too large for long, so we return based
		 * on whether an off_t version of fseek is available.
		 */
2669 2670 2671 2672 2673 2674 2675 2676
#ifdef HAVE_FSEEKO
		return true;
#else
		return false;
#endif
	else
		return true;
}
2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689


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