pg_backup_archiver.c 50.3 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 14 15 16 17
 *
 *	The author is not responsible for loss or damages that may
 *	result from it's use.
 *
 *
 * IDENTIFICATION
18
 *		$Header: /cvsroot/pgsql/src/bin/pg_dump/pg_backup_archiver.c,v 1.32 2001/08/22 20:23:23 petere Exp $
B
Bruce Momjian 已提交
19 20 21
 *
 * Modifications - 28-Jun-2000 - pjw@rhyme.com.au
 *
B
Bruce Momjian 已提交
22
 *		Initial version.
23 24 25
 *
 * Modifications - 31-Jul-2000 - pjw@rhyme.com.au (1.46, 1.47)
 *		Fixed version number initialization in _allocAH (pg_backup_archiver.c)
B
Bruce Momjian 已提交
26
 *
27 28 29 30
 *
 * Modifications - 30-Oct-2000 - pjw@rhyme.com.au
 *		Added {Start,End}RestoreBlobs to allow extended TX during BLOB restore.
 *
31
 * Modifications - 04-Jan-2001 - pjw@rhyme.com.au
B
Bruce Momjian 已提交
32 33 34
 *	  - strdup() the current user just in case it's deallocated from it's TOC
 *		entry. Should *never* happen, but that's what they said about the
 *		Titanic...
35 36 37
 *
 *	  - Check results of IO routines more carefully.
 *
38 39 40
 * Modifications - 27-Jan-2001 - pjw@rhyme.com.au
 *	  - When dropping the schema, reconnect as owner of each object.
 *
41 42 43
 * Modifications - 6-Mar-2001 - pjw@rhyme.com.au
 *	  - Only disable triggers in DataOnly (or implied data-only) restores.
 *
44 45 46 47 48 49 50 51 52 53
 * Modifications - 31-Mar-2001 - pjw@rhyme.com.au
 * 
 *	  - Rudimentary support for dependencies in archives. Current implementation
 *		uses dependencies to modify the OID used in sorting TOC entries.
 *		This will NOT handle multi-level dependencies, but will manage simple
 *		relationships like UDTs & their functions.
 *
 *	  - Treat OIDs with more respect (avoid using ints, use macros for 
 *		conversion & comparison).
 *
54 55 56 57 58 59
 * Modifications - 10-May-2001 - pjw@rhyme.com.au
 *	  - Treat SEQUENCE SET TOC entries as data entries rather than schema
 *		entries.
 *	  - Make allowance for data entries that did not have a data dumper
 * 		routine (eg. SEQUENCE SET)
 *
B
Bruce Momjian 已提交
60 61 62 63 64
 *-------------------------------------------------------------------------
 */

#include "pg_backup.h"
#include "pg_backup_archiver.h"
65 66
#include "pg_backup_db.h"

67
#include <errno.h>
B
Bruce Momjian 已提交
68
#include <unistd.h>				/* for dup */
B
Bruce Momjian 已提交
69

70 71 72
#include "pqexpbuffer.h"
#include "libpq/libpq-fs.h"

B
Bruce Momjian 已提交
73 74 75 76 77
static void _SortToc(ArchiveHandle *AH, TocSortCompareFn fn);
static int	_tocSortCompareByOIDNum(const void *p1, const void *p2);
static int	_tocSortCompareByIDNum(const void *p1, const void *p2);
static ArchiveHandle *_allocAH(const char *FileSpec, const ArchiveFormat fmt,
		 const int compression, ArchiveMode mode);
78
static int	_printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData);
79

B
Bruce Momjian 已提交
80
static void _reconnectAsOwner(ArchiveHandle *AH, const char *dbname, TocEntry *te);
81
static void _reconnectAsUser(ArchiveHandle *AH, const char *dbname, const char *user);
82

B
Bruce Momjian 已提交
83 84 85 86 87 88 89
static int	_tocEntryRequired(TocEntry *te, RestoreOptions *ropt);
static void _disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
static void _enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
static TocEntry *_getTocEntry(ArchiveHandle *AH, int id);
static void _moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te);
static void _moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te);
static int	_discoverArchiveFormat(ArchiveHandle *AH);
90 91
static void _fixupOidInfo(TocEntry *te);
static Oid _findMaxOID(const char *((*deps)[]));
92

93
const char *progname;
94
static char *modulename = gettext_noop("archiver");
B
Bruce Momjian 已提交
95

96 97
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);
98

B
Bruce Momjian 已提交
99 100
static int	_canRestoreBlobs(ArchiveHandle *AH);
static int	_restoringToDB(ArchiveHandle *AH);
101

B
Bruce Momjian 已提交
102
/*
B
Bruce Momjian 已提交
103 104 105 106
 *	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 已提交
107 108 109 110 111 112
 *
 */


/* Create a new archive */
/* Public */
B
Bruce Momjian 已提交
113 114 115
Archive    *
CreateArchive(const char *FileSpec, const ArchiveFormat fmt,
			  const int compression)
116

B
Bruce Momjian 已提交
117
{
B
Bruce Momjian 已提交
118 119 120
	ArchiveHandle *AH = _allocAH(FileSpec, fmt, compression, archModeWrite);

	return (Archive *) AH;
B
Bruce Momjian 已提交
121 122 123 124
}

/* Open an existing archive */
/* Public */
B
Bruce Momjian 已提交
125 126
Archive    *
OpenArchive(const char *FileSpec, const ArchiveFormat fmt)
B
Bruce Momjian 已提交
127
{
B
Bruce Momjian 已提交
128 129 130
	ArchiveHandle *AH = _allocAH(FileSpec, fmt, 0, archModeRead);

	return (Archive *) AH;
B
Bruce Momjian 已提交
131 132 133
}

/* Public */
B
Bruce Momjian 已提交
134 135
void
CloseArchive(Archive *AHX)
B
Bruce Momjian 已提交
136
{
B
Bruce Momjian 已提交
137 138 139 140
	int			res = 0;
	ArchiveHandle *AH = (ArchiveHandle *) AHX;

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

B
Bruce Momjian 已提交
142 143
	/* Close the output */
	if (AH->gzOut)
144
		res = GZCLOSE(AH->OF);
B
Bruce Momjian 已提交
145
	else if (AH->OF != stdout)
146 147 148
		res = fclose(AH->OF);

	if (res != 0)
149
		die_horribly(AH, modulename, "could not close the output file in CloseArchive\n");
B
Bruce Momjian 已提交
150 151 152
}

/* Public */
B
Bruce Momjian 已提交
153 154
void
RestoreArchive(Archive *AHX, RestoreOptions *ropt)
B
Bruce Momjian 已提交
155
{
B
Bruce Momjian 已提交
156 157 158 159 160
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
	TocEntry   *te = AH->toc->next;
	int			reqs;
	OutputContext sav;
	int			impliedDataOnly;
161
	bool		defnDumped;
B
Bruce Momjian 已提交
162

163 164
	AH->ropt = ropt;

165
	if (ropt->create && ropt->noReconnect)
166
		die_horribly(AH, modulename, "-C and -R are incompatible options\n");
167

168 169 170 171 172
	/*
	 * If we're using a DB connection, then connect it.
	 */
	if (ropt->useDB)
	{
173
		ahlog(AH, 1, "connecting to database for restore\n");
174
		if (AH->version < K_VERS_1_3)
175
			die_horribly(AH, modulename, "direct database connections are not supported in pre-1.3 archives\n");
176

177 178 179 180
		/* XXX Should get this from the archive */
		AHX->minRemoteVersion = 070100;
		AHX->maxRemoteVersion = 999999;

181
		ConnectDatabase(AHX, ropt->dbname, ropt->pghost, ropt->pgport, ropt->username,
B
Bruce Momjian 已提交
182
						ropt->requirePassword, ropt->ignoreVersion);
183 184

		/*
B
Bruce Momjian 已提交
185 186
		 * If no superuser was specified then see if the current user will
		 * do...
187 188 189 190 191 192 193
		 */
		if (!ropt->superuser)
		{
			if (UserIsSuperuser(AH, ConnectedUser(AH)))
				ropt->superuser = strdup(ConnectedUser(AH));
		}

194 195
	}

196
	/*
B
Bruce Momjian 已提交
197 198 199 200
	 * Work out if we have an implied data-only retore. 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.
201
	 *
B
Bruce Momjian 已提交
202
	 * We could scan for wanted TABLE entries, but that is not the same as
203
	 * dataOnly. At this stage, it seems unnecessary (6-Mar-2001).
B
Bruce Momjian 已提交
204 205 206
	 */
	if (!ropt->dataOnly)
	{
207 208
		te = AH->toc->next;
		impliedDataOnly = 1;
B
Bruce Momjian 已提交
209 210
		while (te != AH->toc)
		{
211
			reqs = _tocEntryRequired(te, ropt);
B
Bruce Momjian 已提交
212 213
			if ((reqs & 1) != 0)
			{					/* It's schema, and it's wanted */
214 215 216 217 218 219 220 221
				impliedDataOnly = 0;
				break;
			}
			te = te->next;
		}
		if (impliedDataOnly)
		{
			ropt->dataOnly = impliedDataOnly;
222
			ahlog(AH, 1, "implied data-only restore\n");
223
		}
B
Bruce Momjian 已提交
224
	}
225

226
	if (!ropt->superuser)
227 228 229 230
		write_msg(modulename, "WARNING:\n"
				  "  Data restoration may fail because existing triggers cannot be disabled\n"
				  "  (no superuser user name specified).  This is only a problem when\n"
				  "  restoring into a database with already existing triggers.\n");
231

232
	/*
B
Bruce Momjian 已提交
233
	 * Setup the output file if necessary.
234
	 */
B
Bruce Momjian 已提交
235
	if (ropt->filename || ropt->compression)
236
		sav = SetOutput(AH, ropt->filename, ropt->compression);
B
Bruce Momjian 已提交
237

B
Bruce Momjian 已提交
238
	ahprintf(AH, "--\n-- Selected TOC Entries:\n--\n");
B
Bruce Momjian 已提交
239

B
Bruce Momjian 已提交
240 241
	/*
	 * Drop the items at the start, in reverse order
242
	 */
B
Bruce Momjian 已提交
243 244
	if (ropt->dropSchema)
	{
245
		te = AH->toc->prev;
B
Bruce Momjian 已提交
246 247
		while (te != AH->toc)
		{
248
			reqs = _tocEntryRequired(te, ropt);
B
Bruce Momjian 已提交
249
			if (((reqs & 1) != 0) && te->dropStmt)
250 251 252
			{
				/* We want the schema */
				ahlog(AH, 1, "dropping %s %s\n", te->desc, te->name);
253
				/* Reconnect if necessary */
254
				_reconnectAsOwner(AH, NULL, te);
255
				/* Drop it */
256 257 258 259
				ahprintf(AH, "%s", te->dropStmt);
			}
			te = te->prev;
		}
B
Bruce Momjian 已提交
260
	}
B
Bruce Momjian 已提交
261

262 263 264
	/*
	 * Now process each TOC entry
	 */
B
Bruce Momjian 已提交
265 266 267
	te = AH->toc->next;
	while (te != AH->toc)
	{
B
Bruce Momjian 已提交
268

269 270 271
		/* Work out what, if anything, we want from this entry */
		reqs = _tocEntryRequired(te, ropt);

272 273 274 275
		/* Dump any relevant dump warnings to stderr */
		if (!ropt->suppressDumpWarnings && strcmp(te->desc, "WARNING") == 0)
		{
			if (!ropt->dataOnly && te->defn != NULL && strlen(te->defn) != 0) 
276 277 278
				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);
279 280
	 	}

281 282
		defnDumped = false;

B
Bruce Momjian 已提交
283
		if ((reqs & 1) != 0)	/* We want the schema */
284
		{
285
			/* Reconnect if necessary */
286
			_reconnectAsOwner(AH, NULL, te);
287

288
			ahlog(AH, 1, "creating %s %s\n", te->desc, te->name);
289
			_printTocEntry(AH, te, ropt, false);
290
			defnDumped = true;
291 292

			/* If we created a DB, connect to it... */
B
Bruce Momjian 已提交
293
			if (strcmp(te->desc, "DATABASE") == 0)
294
			{
295
				ahlog(AH, 1, "connecting to new database %s as user %s\n", te->name, te->owner);
296 297
				_reconnectAsUser(AH, te->name, te->owner);
			}
298
		}	
B
Bruce Momjian 已提交
299

B
Bruce Momjian 已提交
300
		/*
301
		 * If we have a data component, then process it
302
		 */
303
		if ( (reqs & 2) != 0 )
B
Bruce Momjian 已提交
304
		{
305 306 307
			/* 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.
308
			 */
309
			if (te->hadDumper) 
310 311
			{
				/*
312
				 * If we can output the data, then restore it.
313
				 */
314 315 316 317
				if (AH->PrintTocDataPtr !=NULL && (reqs & 2) != 0)
				{
#ifndef HAVE_LIBZ
					if (AH->compression != 0)
318
						die_horribly(AH, modulename, "unable to restore from compressed archive (not configured for compression support)\n");
319
#endif
320

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
					_printTocEntry(AH, te, ropt, true);

					/*
					 * Maybe we can't do BLOBS, so check if this node is for BLOBS
					 */
					if ((strcmp(te->desc, "BLOBS") == 0) && !_canRestoreBlobs(AH))
					{
						ahprintf(AH, "--\n-- SKIPPED \n--\n\n");

						/*
						 * This is a bit nasty - we assume, for the moment, that
						 * if a custom output is used, then we don't want
						 * warnings.
						 */
						if (!AH->CustomOutPtr)
336
							write_msg(modulename, "WARNING: skipping BLOB restoration\n");
337 338 339 340 341 342 343 344 345 346 347

					}
					else
					{

						_disableTriggersIfNecessary(AH, te, ropt);

						/*
						 * Reconnect if necessary (_disableTriggers may have
						 * reconnected)
						 */
348
						_reconnectAsOwner(AH, NULL, te);
349

350
						ahlog(AH, 1, "restoring data for table %s\n", te->name);
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370

						/*
						 * 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.
						 *
						 * For V1.3+, the table data MUST have a copy statement so
						 * that we can go into appropriate mode with libpq.
						 */
						if (te->copyStmt && strlen(te->copyStmt) > 0)
							ahprintf(AH, te->copyStmt);

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

						_enableTriggersIfNecessary(AH, te, ropt);
					}
				}
			} else if (!defnDumped) {
				/* If we haven't already dumped the defn part, do so now */ 
371
				ahlog(AH, 1, "executing %s %s\n", te->desc, te->name);
372
				_printTocEntry(AH, te, ropt, false);
373 374 375
			}
		}
		te = te->next;
B
Bruce Momjian 已提交
376
	}
B
Bruce Momjian 已提交
377

378
	/*
B
Bruce Momjian 已提交
379 380
	 * Now use blobs_xref (if used) to fixup any refs for tables that we
	 * loaded
381 382 383
	 */
	if (_canRestoreBlobs(AH) && AH->createdBlobXref)
	{
384
		/* NULL parameter means disable ALL user triggers */
385
		_disableTriggersIfNecessary(AH, NULL, ropt);
386

387
		te = AH->toc->next;
B
Bruce Momjian 已提交
388 389
		while (te != AH->toc)
		{
390 391

			/* Is it table data? */
B
Bruce Momjian 已提交
392 393
			if (strcmp(te->desc, "TABLE DATA") == 0)
			{
394

395
				ahlog(AH, 2, "checking whether we loaded %s\n", te->name);
396 397 398

				reqs = _tocEntryRequired(te, ropt);

B
Bruce Momjian 已提交
399
				if ((reqs & 2) != 0)	/* We loaded the data */
400
				{
401
					ahlog(AH, 1, "fixing up BLOB reference for %s\n", te->name);
402 403 404 405
					FixupBlobRefs(AH, te->name);
				}
			}
			else
406
				ahlog(AH, 2, "ignoring BLOB cross-references for %s %s\n", te->desc, te->name);
407 408 409

			te = te->next;
		}
410 411

		/* NULL parameter means enable ALL user triggers */
412
		_enableTriggersIfNecessary(AH, NULL, ropt);
413 414 415 416 417
	}

	/*
	 * Clean up & we're done.
	 */
B
Bruce Momjian 已提交
418
	if (ropt->filename)
419
		ResetOutput(AH, sav);
B
Bruce Momjian 已提交
420

421 422 423 424
	if (ropt->useDB)
	{
		PQfinish(AH->connection);
		AH->connection = NULL;
425 426 427 428 429 430

		if (AH->blobConnection)
		{
			PQfinish(AH->blobConnection);
			AH->blobConnection = NULL;
		}
431
	}
B
Bruce Momjian 已提交
432 433
}

434 435 436 437
/*
 * Allocate a new RestoreOptions block.
 * This is mainly so we can initialize it, but also for future expansion,
 */
B
Bruce Momjian 已提交
438 439
RestoreOptions *
NewRestoreOptions(void)
B
Bruce Momjian 已提交
440
{
B
Bruce Momjian 已提交
441
	RestoreOptions *opts;
B
Bruce Momjian 已提交
442

B
Bruce Momjian 已提交
443
	opts = (RestoreOptions *) calloc(1, sizeof(RestoreOptions));
B
Bruce Momjian 已提交
444 445

	opts->format = archUnknown;
446
	opts->suppressDumpWarnings = false;
B
Bruce Momjian 已提交
447 448 449 450

	return opts;
}

451 452 453 454
/*
 * Returns true if we're restoring directly to the database (and
 * aren't just making a psql script that can do the restoration).
 */
B
Bruce Momjian 已提交
455 456
static int
_restoringToDB(ArchiveHandle *AH)
457 458 459 460
{
	return (AH->ropt->useDB && AH->connection);
}

B
Bruce Momjian 已提交
461 462
static int
_canRestoreBlobs(ArchiveHandle *AH)
463 464 465 466
{
	return _restoringToDB(AH);
}

B
Bruce Momjian 已提交
467 468
static void
_disableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
B
Bruce Momjian 已提交
469
{
B
Bruce Momjian 已提交
470
	char	   *oldUser = NULL;
471 472

	/* Can't do much if we're connected & don't have a superuser */
B
Bruce Momjian 已提交
473 474
	/* Also, don't bother with triggers unless a data-only retore. */
	if (!ropt->dataOnly || (_restoringToDB(AH) && !ropt->superuser))
475 476 477
		return;

	/*
B
Bruce Momjian 已提交
478
	 * Reconnect as superuser if possible, since they are the only ones
479 480 481 482
	 * who can update pg_class...
	 */
	if (ropt->superuser)
	{
483 484
		if (!_restoringToDB(AH) || !ConnectedUserIsSuperuser(AH))
		{
B
Bruce Momjian 已提交
485 486 487 488 489

			/*
			 * If we're not allowing changes for ownership, then remember
			 * the user so we can change it back here. Otherwise, let
			 * _reconnectAsOwner do what it has to do.
490 491 492
			 */
			if (ropt->noOwner)
				oldUser = strdup(ConnectedUser(AH));
493
			_reconnectAsUser(AH, NULL, ropt->superuser);
494
		}
495 496
	}

497
	ahlog(AH, 1, "disabling triggers\n");
498 499

	/*
B
Bruce Momjian 已提交
500 501
	 * Disable them. This is a hack. Needs to be done via an appropriate
	 * 'SET' command when one is available.
502
	 */
B
Bruce Momjian 已提交
503
	ahprintf(AH, "-- Disable triggers\n");
504 505 506 507 508 509

	/*
	 * Just update the AFFECTED table, if known.
	 */

	if (te && te->name && strlen(te->name) > 0)
B
Bruce Momjian 已提交
510 511
		ahprintf(AH, "UPDATE \"pg_class\" SET \"reltriggers\" = 0 WHERE \"relname\" = '%s';\n\n",
				 te->name);
512 513
	else
		ahprintf(AH, "UPDATE \"pg_class\" SET \"reltriggers\" = 0 WHERE \"relname\" !~ '^pg_';\n\n");
514 515

	/*
B
Bruce Momjian 已提交
516 517
	 * Restore the user connection from the start of this procedure if
	 * _reconnectAsOwner is disabled.
518 519 520
	 */
	if (ropt->noOwner && oldUser)
	{
521
		_reconnectAsUser(AH, NULL, oldUser);
522 523
		free(oldUser);
	}
B
Bruce Momjian 已提交
524 525
}

B
Bruce Momjian 已提交
526 527
static void
_enableTriggersIfNecessary(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
B
Bruce Momjian 已提交
528
{
B
Bruce Momjian 已提交
529
	char	   *oldUser = NULL;
530 531

	/* Can't do much if we're connected & don't have a superuser */
532
	/* Also, don't bother with triggers unless a data-only retore. */
B
Bruce Momjian 已提交
533
	if (!ropt->dataOnly || (_restoringToDB(AH) && !ropt->superuser))
534 535 536 537 538 539 540 541
		return;

	/*
	 * Reconnect as superuser if possible, since they are the only ones
	 * who can update pg_class...
	 */
	if (ropt->superuser)
	{
542 543
		if (!_restoringToDB(AH) || !ConnectedUserIsSuperuser(AH))
		{
B
Bruce Momjian 已提交
544 545 546 547 548

			/*
			 * If we're not allowing changes for ownership, then remember
			 * the user so we can change it back here. Otherwise, let
			 * _reconnectAsOwner do what it has to do
549 550 551
			 */
			if (ropt->noOwner)
				oldUser = strdup(ConnectedUser(AH));
552

553
			_reconnectAsUser(AH, NULL, ropt->superuser);
554
		}
555 556
	}

557
	ahlog(AH, 1, "enabling triggers\n");
558 559

	/*
B
Bruce Momjian 已提交
560 561
	 * Enable them. This is a hack. Needs to be done via an appropriate
	 * 'SET' command when one is available.
562
	 */
B
Bruce Momjian 已提交
563
	ahprintf(AH, "-- Enable triggers\n");
564 565 566
	if (te && te->name && strlen(te->name) > 0)
	{
		ahprintf(AH, "UPDATE pg_class SET reltriggers = "
B
Bruce Momjian 已提交
567
		"(SELECT count(*) FROM pg_trigger where pg_class.oid = tgrelid) "
568
				 "WHERE relname = '%s';\n\n",
B
Bruce Momjian 已提交
569 570 571 572
				 te->name);
	}
	else
	{
573
		ahprintf(AH, "UPDATE \"pg_class\" SET \"reltriggers\" = "
B
Bruce Momjian 已提交
574
		"(SELECT count(*) FROM pg_trigger where pg_class.oid = tgrelid) "
575 576
				 "WHERE \"relname\" !~ '^pg_';\n\n");
	}
B
Bruce Momjian 已提交
577

578
	/*
B
Bruce Momjian 已提交
579 580
	 * Restore the user connection from the start of this procedure if
	 * _reconnectAsOwner is disabled.
581 582 583
	 */
	if (ropt->noOwner && oldUser)
	{
584
		_reconnectAsUser(AH, NULL, oldUser);
585 586 587
		free(oldUser);
	}
}
B
Bruce Momjian 已提交
588 589

/*
590
 * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
B
Bruce Momjian 已提交
591 592 593
 */

/* Public */
B
Bruce Momjian 已提交
594 595
int
WriteData(Archive *AHX, const void *data, int dLen)
B
Bruce Momjian 已提交
596
{
B
Bruce Momjian 已提交
597
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
B
Bruce Momjian 已提交
598

599
	if (!AH->currToc)
600
		die_horribly(AH, modulename, "WriteData cannot be called outside the context of a DataDumper routine\n");
601

B
Bruce Momjian 已提交
602
	return (*AH->WriteDataPtr) (AH, data, dLen);
B
Bruce Momjian 已提交
603 604 605
}

/*
B
Bruce Momjian 已提交
606
 * Create a new TOC entry. The TOC was designed as a TOC, but is now the
B
Bruce Momjian 已提交
607 608 609 610
 * repository for all metadata. But the name has stuck.
 */

/* Public */
B
Bruce Momjian 已提交
611 612
void
ArchiveEntry(Archive *AHX, const char *oid, const char *name,
613
			 const char *desc, const char *((*deps)[]), const char *defn,
B
Bruce Momjian 已提交
614 615
		   const char *dropStmt, const char *copyStmt, const char *owner,
			 DataDumperPtr dumpFn, void *dumpArg)
B
Bruce Momjian 已提交
616
{
B
Bruce Momjian 已提交
617 618 619 620 621 622 623 624
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
	TocEntry   *newToc;

	AH->lastID++;
	AH->tocCount++;

	newToc = (TocEntry *) calloc(1, sizeof(TocEntry));
	if (!newToc)
625
		die_horribly(AH, modulename, "out of memory\n");
B
Bruce Momjian 已提交
626 627 628 629 630 631 632

	newToc->prev = AH->toc->prev;
	newToc->next = AH->toc;
	AH->toc->prev->next = newToc;
	AH->toc->prev = newToc;

	newToc->id = AH->lastID;
633

B
Bruce Momjian 已提交
634 635
	newToc->name = strdup(name);
	newToc->desc = strdup(desc);
636 637 638 639 640 641

	newToc->oid = strdup(oid);
	newToc->depOid = deps;
	_fixupOidInfo(newToc);


B
Bruce Momjian 已提交
642 643
	newToc->defn = strdup(defn);
	newToc->dropStmt = strdup(dropStmt);
644
	newToc->copyStmt = copyStmt ? strdup(copyStmt) : NULL;
B
Bruce Momjian 已提交
645 646 647 648 649
	newToc->owner = strdup(owner);
	newToc->printed = 0;
	newToc->formatData = NULL;
	newToc->dataDumper = dumpFn,
		newToc->dataDumperArg = dumpArg;
B
Bruce Momjian 已提交
650

B
Bruce Momjian 已提交
651
	newToc->hadDumper = dumpFn ? 1 : 0;
B
Bruce Momjian 已提交
652

B
Bruce Momjian 已提交
653 654
	if (AH->ArchiveEntryPtr !=NULL)
		(*AH->ArchiveEntryPtr) (AH, newToc);
B
Bruce Momjian 已提交
655

B
Bruce Momjian 已提交
656 657 658 659
	/*
	 * printf("New toc owned by '%s', oid %d\n", newToc->owner,
	 * newToc->oidVal);
	 */
B
Bruce Momjian 已提交
660 661 662
}

/* Public */
B
Bruce Momjian 已提交
663 664
void
PrintTOCSummary(Archive *AHX, RestoreOptions *ropt)
B
Bruce Momjian 已提交
665
{
B
Bruce Momjian 已提交
666 667 668 669
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
	TocEntry   *te = AH->toc->next;
	OutputContext sav;
	char	   *fmtName;
B
Bruce Momjian 已提交
670

B
Bruce Momjian 已提交
671 672
	if (ropt->filename)
		sav = SetOutput(AH, ropt->filename, ropt->compression);
B
Bruce Momjian 已提交
673

674 675
	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 已提交
676
			 AH->archdbname, AH->tocCount, AH->compression);
677

B
Bruce Momjian 已提交
678 679
	switch (AH->format)
	{
680 681 682 683 684 685 686 687 688 689 690 691
		case archFiles:
			fmtName = "FILES";
			break;
		case archCustom:
			fmtName = "CUSTOM";
			break;
		case archTar:
			fmtName = "TAR";
			break;
		default:
			fmtName = "UNKNOWN";
	}
692 693

	ahprintf(AH, ";     Dump Version: %d.%d-%d\n", AH->vmaj, AH->vmin, AH->vrev);
694 695
	ahprintf(AH, ";     Format: %s\n;\n", fmtName);

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

B
Bruce Momjian 已提交
698 699 700 701
	while (te != AH->toc)
	{
		if (_tocEntryRequired(te, ropt) != 0)
			ahprintf(AH, "%d; %d %s %s %s\n", te->id, te->oidVal, te->desc, te->name, te->owner);
B
Bruce Momjian 已提交
702
		te = te->next;
B
Bruce Momjian 已提交
703
	}
B
Bruce Momjian 已提交
704

B
Bruce Momjian 已提交
705 706
	if (ropt->filename)
		ResetOutput(AH, sav);
B
Bruce Momjian 已提交
707 708
}

709 710 711 712 713
/***********
 * BLOB Archival
 ***********/

/* Called by a dumper to signal start of a BLOB */
B
Bruce Momjian 已提交
714
int
715
StartBlob(Archive *AHX, Oid oid)
716
{
B
Bruce Momjian 已提交
717
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
718

B
Bruce Momjian 已提交
719
	if (!AH->StartBlobPtr)
720
		die_horribly(AH, modulename, "BLOB output not supported in chosen format\n");
721

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

B
Bruce Momjian 已提交
724
	return 1;
725 726 727
}

/* Called by a dumper to signal end of a BLOB */
B
Bruce Momjian 已提交
728
int
729
EndBlob(Archive *AHX, Oid oid)
730
{
B
Bruce Momjian 已提交
731
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
732

B
Bruce Momjian 已提交
733 734
	if (AH->EndBlobPtr)
		(*AH->EndBlobPtr) (AH, AH->currToc, oid);
735

B
Bruce Momjian 已提交
736
	return 1;
737 738 739 740 741 742
}

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

743
/*
B
Bruce Momjian 已提交
744
 * Called by a format handler before any blobs are restored
745
 */
B
Bruce Momjian 已提交
746 747
void
StartRestoreBlobs(ArchiveHandle *AH)
748 749 750 751 752
{
	AH->blobCount = 0;
}

/*
B
Bruce Momjian 已提交
753
 * Called by a format handler after all blobs are restored
754
 */
B
Bruce Momjian 已提交
755 756
void
EndRestoreBlobs(ArchiveHandle *AH)
757 758 759
{
	if (AH->txActive)
	{
760
		ahlog(AH, 2, "committing BLOB transactions\n");
761 762 763 764 765 766
		CommitTransaction(AH);
	}

	if (AH->blobTxActive)
		CommitTransactionXref(AH);

767
	ahlog(AH, 1, "restored %d BLOBs\n", AH->blobCount);
768 769 770
}


771 772 773
/*
 * Called by a format handler to initiate restoration of a blob
 */
B
Bruce Momjian 已提交
774
void
775
StartRestoreBlob(ArchiveHandle *AH, Oid oid)
776
{
777
	Oid			loOid;
778

779 780
	AH->blobCount++;

781 782 783
	if (!AH->createdBlobXref)
	{
		if (!AH->connection)
784
			die_horribly(AH, modulename, "cannot restore BLOBs without a database connection\n");
785 786 787 788 789

		CreateBlobXrefTable(AH);
		AH->createdBlobXref = 1;
	}

790 791 792 793 794
	/*
	 * Start long-running TXs if necessary
	 */
	if (!AH->txActive)
	{
795
		ahlog(AH, 2, "starting BLOB transactions\n");
796 797 798 799
		StartTransaction(AH);
	}
	if (!AH->blobTxActive)
		StartTransactionXref(AH);
800

801 802
	loOid = lo_creat(AH->connection, INV_READ | INV_WRITE);
	if (loOid == 0)
803
		die_horribly(AH, modulename, "could not create BLOB\n");
804

805
	ahlog(AH, 2, "restoring BLOB oid %u as %u\n", oid, loOid);
806 807 808 809 810

	InsertBlobXref(AH, oid, loOid);

	AH->loFd = lo_open(AH->connection, loOid, INV_WRITE);
	if (AH->loFd == -1)
811
		die_horribly(AH, modulename, "could not open BLOB\n");
812

B
Bruce Momjian 已提交
813
	AH->writingBlob = 1;
814 815
}

B
Bruce Momjian 已提交
816
void
817
EndRestoreBlob(ArchiveHandle *AH, Oid oid)
818
{
B
Bruce Momjian 已提交
819 820
	lo_close(AH->connection, AH->loFd);
	AH->writingBlob = 0;
821

822 823 824
	/*
	 * Commit every BLOB_BATCH_SIZE blobs...
	 */
B
Bruce Momjian 已提交
825
	if (((AH->blobCount / BLOB_BATCH_SIZE) * BLOB_BATCH_SIZE) == AH->blobCount)
826
	{
827
		ahlog(AH, 2, "committing BLOB transactions\n");
828 829 830
		CommitTransaction(AH);
		CommitTransactionXref(AH);
	}
831 832
}

B
Bruce Momjian 已提交
833 834 835 836 837 838 839
/***********
 * Sorting and Reordering
 ***********/

/*
 * Move TOC entries of the specified type to the START of the TOC.
 */
840

B
Bruce Momjian 已提交
841
/* Public */
B
Bruce Momjian 已提交
842 843
void
MoveToStart(Archive *AHX, char *oType)
B
Bruce Momjian 已提交
844
{
B
Bruce Momjian 已提交
845 846 847
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
	TocEntry   *te = AH->toc->next;
	TocEntry   *newTe;
B
Bruce Momjian 已提交
848

B
Bruce Momjian 已提交
849 850
	while (te != AH->toc)
	{
B
Bruce Momjian 已提交
851 852 853
		te->_moved = 0;
		te = te->next;
	}
B
Bruce Momjian 已提交
854 855 856 857 858 859 860

	te = AH->toc->prev;
	while (te != AH->toc && !te->_moved)
	{
		newTe = te->prev;
		if (strcmp(te->desc, oType) == 0)
			_moveAfter(AH, AH->toc, te);
B
Bruce Momjian 已提交
861
		te = newTe;
B
Bruce Momjian 已提交
862
	}
B
Bruce Momjian 已提交
863 864 865 866 867 868 869
}


/*
 * Move TOC entries of the specified type to the end of the TOC.
 */
/* Public */
B
Bruce Momjian 已提交
870 871
void
MoveToEnd(Archive *AHX, char *oType)
B
Bruce Momjian 已提交
872
{
B
Bruce Momjian 已提交
873 874 875 876 877 878 879 880
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
	TocEntry   *te = AH->toc->next;
	TocEntry   *newTe;

	while (te != AH->toc)
	{
		te->_moved = 0;
		te = te->next;
B
Bruce Momjian 已提交
881
	}
B
Bruce Momjian 已提交
882 883 884 885 886 887 888

	te = AH->toc->next;
	while (te != AH->toc && !te->_moved)
	{
		newTe = te->next;
		if (strcmp(te->desc, oType) == 0)
			_moveBefore(AH, AH->toc, te);
B
Bruce Momjian 已提交
889
		te = newTe;
B
Bruce Momjian 已提交
890
	}
B
Bruce Momjian 已提交
891 892
}

B
Bruce Momjian 已提交
893
/*
B
Bruce Momjian 已提交
894 895 896
 * Sort TOC by OID
 */
/* Public */
B
Bruce Momjian 已提交
897 898
void
SortTocByOID(Archive *AHX)
B
Bruce Momjian 已提交
899
{
B
Bruce Momjian 已提交
900 901 902
	ArchiveHandle *AH = (ArchiveHandle *) AHX;

	_SortToc(AH, _tocSortCompareByOIDNum);
B
Bruce Momjian 已提交
903 904 905 906 907 908
}

/*
 * Sort TOC by ID
 */
/* Public */
B
Bruce Momjian 已提交
909 910
void
SortTocByID(Archive *AHX)
B
Bruce Momjian 已提交
911
{
B
Bruce Momjian 已提交
912 913 914
	ArchiveHandle *AH = (ArchiveHandle *) AHX;

	_SortToc(AH, _tocSortCompareByIDNum);
B
Bruce Momjian 已提交
915 916
}

B
Bruce Momjian 已提交
917 918
void
SortTocFromFile(Archive *AHX, RestoreOptions *ropt)
B
Bruce Momjian 已提交
919
{
B
Bruce Momjian 已提交
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
	ArchiveHandle *AH = (ArchiveHandle *) AHX;
	FILE	   *fh;
	char		buf[1024];
	char	   *cmnt;
	char	   *endptr;
	int			id;
	TocEntry   *te;
	TocEntry   *tePrev;
	int			i;

	/* Allocate space for the 'wanted' array, and init it */
	ropt->idWanted = (int *) malloc(sizeof(int) * AH->tocCount);
	for (i = 0; i < AH->tocCount; i++)
		ropt->idWanted[i] = 0;

	ropt->limitToList = 1;

	/* Mark all entries as 'not moved' */
	te = AH->toc->next;
	while (te != AH->toc)
	{
		te->_moved = 0;
		te = te->next;
	}
B
Bruce Momjian 已提交
944

B
Bruce Momjian 已提交
945 946
	/* Set prev entry as head of list */
	tePrev = AH->toc;
B
Bruce Momjian 已提交
947

B
Bruce Momjian 已提交
948 949 950
	/* Setup the file */
	fh = fopen(ropt->tocFile, PG_BINARY_R);
	if (!fh)
951
		die_horribly(AH, modulename, "could not open TOC file\n");
B
Bruce Momjian 已提交
952

B
Bruce Momjian 已提交
953
	while (fgets(buf, 1024, fh) != NULL)
B
Bruce Momjian 已提交
954
	{
B
Bruce Momjian 已提交
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
		/* Find a comment */
		cmnt = strchr(buf, ';');
		if (cmnt == buf)
			continue;

		/* End string at comment */
		if (cmnt != NULL)
			cmnt[0] = '\0';

		/* Skip if all spaces */
		if (strspn(buf, " \t") == strlen(buf))
			continue;

		/* Get an ID */
		id = strtol(buf, &endptr, 10);
		if (endptr == buf)
		{
972
			write_msg(modulename, "WARNING: line ignored: %s\n", buf);
B
Bruce Momjian 已提交
973 974
			continue;
		}
B
Bruce Momjian 已提交
975

B
Bruce Momjian 已提交
976 977 978
		/* Find TOC entry */
		te = _getTocEntry(AH, id);
		if (!te)
979
			die_horribly(AH, modulename, "could not find entry for id %d\n", id);
B
Bruce Momjian 已提交
980

B
Bruce Momjian 已提交
981
		ropt->idWanted[id - 1] = 1;
B
Bruce Momjian 已提交
982

B
Bruce Momjian 已提交
983 984 985
		_moveAfter(AH, tePrev, te);
		tePrev = te;
	}
B
Bruce Momjian 已提交
986

B
Bruce Momjian 已提交
987
	if (fclose(fh) != 0)
988
		die_horribly(AH, modulename, "could not close TOC file: %s\n", strerror(errno));
B
Bruce Momjian 已提交
989 990 991 992 993 994 995 996
}

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

/* Public */
B
Bruce Momjian 已提交
997 998 999 1000
int
archputs(const char *s, Archive *AH)
{
	return WriteData(AH, s, strlen(s));
B
Bruce Momjian 已提交
1001 1002 1003
}

/* Public */
B
Bruce Momjian 已提交
1004 1005 1006 1007
int
archputc(const char c, Archive *AH)
{
	return WriteData(AH, &c, 1);
B
Bruce Momjian 已提交
1008 1009 1010
}

/* Public */
B
Bruce Momjian 已提交
1011 1012
int
archprintf(Archive *AH, const char *fmt,...)
B
Bruce Momjian 已提交
1013
{
B
Bruce Momjian 已提交
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
	char	   *p = NULL;
	va_list		ap;
	int			bSize = strlen(fmt) + 256;
	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))
B
Bruce Momjian 已提交
1029
	{
B
Bruce Momjian 已提交
1030 1031
		if (p != NULL)
			free(p);
1032
		bSize *= 2;
B
Bruce Momjian 已提交
1033
		p = (char *) malloc(bSize);
1034
		if (p == NULL)
1035
			exit_horribly(AH, modulename, "out of memory\n");
1036 1037 1038
		va_start(ap, fmt);
		cnt = vsnprintf(p, bSize, fmt, ap);
		va_end(ap);
B
Bruce Momjian 已提交
1039 1040 1041 1042
	}
	WriteData(AH, p, cnt);
	free(p);
	return cnt;
B
Bruce Momjian 已提交
1043 1044 1045 1046 1047 1048 1049
}


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

B
Bruce Momjian 已提交
1050 1051
OutputContext
SetOutput(ArchiveHandle *AH, char *filename, int compression)
B
Bruce Momjian 已提交
1052
{
B
Bruce Momjian 已提交
1053 1054
	OutputContext sav;

1055
#ifdef HAVE_LIBZ
B
Bruce Momjian 已提交
1056 1057
	char		fmode[10];

B
Bruce Momjian 已提交
1058
#endif
B
Bruce Momjian 已提交
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
	int			fn = 0;

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

	if (filename)
		fn = 0;
	else if (AH->FH)
		fn = fileno(AH->FH);
	else if (AH->fSpec)
	{
		fn = 0;
		filename = AH->fSpec;
	}
	else
		fn = fileno(stdout);

	/* If compression explicitly requested, use gzopen */
1078
#ifdef HAVE_LIBZ
B
Bruce Momjian 已提交
1079 1080
	if (compression != 0)
	{
1081
		sprintf(fmode, "wb%d", compression);
B
Bruce Momjian 已提交
1082 1083 1084 1085
		if (fn)
		{
			AH->OF = gzdopen(dup(fn), fmode);	/* Don't use PG_BINARY_x
												 * since this is zlib */
1086
		}
B
Bruce Momjian 已提交
1087 1088
		else
			AH->OF = gzopen(filename, fmode);
1089
		AH->gzOut = 1;
B
Bruce Momjian 已提交
1090 1091 1092
	}
	else
	{							/* Use fopen */
B
Bruce Momjian 已提交
1093
#endif
B
Bruce Momjian 已提交
1094
		if (fn)
1095
			AH->OF = fdopen(dup(fn), PG_BINARY_W);
B
Bruce Momjian 已提交
1096
		else
1097 1098
			AH->OF = fopen(filename, PG_BINARY_W);
		AH->gzOut = 0;
1099
#ifdef HAVE_LIBZ
B
Bruce Momjian 已提交
1100
	}
B
Bruce Momjian 已提交
1101 1102
#endif

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

B
Bruce Momjian 已提交
1106
	return sav;
B
Bruce Momjian 已提交
1107 1108
}

B
Bruce Momjian 已提交
1109 1110
void
ResetOutput(ArchiveHandle *AH, OutputContext sav)
B
Bruce Momjian 已提交
1111
{
B
Bruce Momjian 已提交
1112
	int			res;
1113

B
Bruce Momjian 已提交
1114
	if (AH->gzOut)
1115
		res = GZCLOSE(AH->OF);
B
Bruce Momjian 已提交
1116
	else
1117 1118 1119
		res = fclose(AH->OF);

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

B
Bruce Momjian 已提交
1122 1123
	AH->gzOut = sav.gzOut;
	AH->OF = sav.OF;
B
Bruce Momjian 已提交
1124 1125 1126 1127 1128
}



/*
B
Bruce Momjian 已提交
1129
 *	Print formatted text to the output file (usually stdout).
B
Bruce Momjian 已提交
1130
 */
B
Bruce Momjian 已提交
1131 1132
int
ahprintf(ArchiveHandle *AH, const char *fmt,...)
B
Bruce Momjian 已提交
1133
{
B
Bruce Momjian 已提交
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
	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))
1149
	{
B
Bruce Momjian 已提交
1150 1151
		if (p != NULL)
			free(p);
1152
		bSize *= 2;
B
Bruce Momjian 已提交
1153
		p = (char *) malloc(bSize);
1154
		if (p == NULL)
1155
			die_horribly(AH, modulename, "out of memory\n");
1156
		va_start(ap, fmt);
1157
		cnt = vsnprintf(p, bSize, fmt, ap);
1158
		va_end(ap);
B
Bruce Momjian 已提交
1159 1160 1161 1162
	}
	ahwrite(p, 1, cnt, AH);
	free(p);
	return cnt;
B
Bruce Momjian 已提交
1163 1164
}

B
Bruce Momjian 已提交
1165 1166
void
ahlog(ArchiveHandle *AH, int level, const char *fmt,...)
1167 1168 1169 1170 1171 1172 1173
{
	va_list		ap;

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

	va_start(ap, fmt);
1174
	_write_msg(NULL, fmt, ap);
1175 1176 1177
	va_end(ap);
}

1178 1179 1180
/*
 * Single place for logic which says 'We are restoring to a direct DB connection'.
 */
B
Bruce Momjian 已提交
1181 1182
int
RestoringToDB(ArchiveHandle *AH)
1183 1184 1185 1186
{
	return (AH->ropt && AH->ropt->useDB && AH->connection);
}

B
Bruce Momjian 已提交
1187
/*
B
Bruce Momjian 已提交
1188 1189 1190
 *	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
1191
 *	wants to generate a script (see TAR output).
B
Bruce Momjian 已提交
1192
 */
B
Bruce Momjian 已提交
1193 1194
int
ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle *AH)
B
Bruce Momjian 已提交
1195
{
B
Bruce Momjian 已提交
1196
	int			res;
1197

B
Bruce Momjian 已提交
1198
	if (AH->writingBlob)
1199
	{
B
Bruce Momjian 已提交
1200
		res = lo_write(AH->connection, AH->loFd, (void *) ptr, size * nmemb);
1201
		ahlog(AH, 5, "wrote %d bytes of BLOB data (result = %d)\n", size * nmemb, res);
1202
		if (res < size * nmemb)
1203 1204
			die_horribly(AH, modulename, "could not write to large object (result: %d, expected: %d)\n",
						 res, size * nmemb);
1205

1206 1207
		return res;
	}
B
Bruce Momjian 已提交
1208
	else if (AH->gzOut)
1209
	{
B
Bruce Momjian 已提交
1210
		res = GZWRITE((void *) ptr, size, nmemb, AH->OF);
1211
		if (res != (nmemb * size))
1212
			die_horribly(AH, modulename, "could not write to compressed archive\n");
1213 1214
		return res;
	}
B
Bruce Momjian 已提交
1215
	else if (AH->CustomOutPtr)
1216
	{
B
Bruce Momjian 已提交
1217 1218
		res = AH->CustomOutPtr (AH, ptr, size * nmemb);

1219
		if (res != (nmemb * size))
1220
			die_horribly(AH, modulename, "could not write to custom output routine\n");
1221 1222
		return res;
	}
1223 1224
	else
	{
B
Bruce Momjian 已提交
1225

1226
		/*
B
Bruce Momjian 已提交
1227 1228 1229
		 * If we're doing a restore, and it's direct to DB, and we're
		 * connected then send it to the DB.
		 */
1230
		if (RestoringToDB(AH))
B
Bruce Momjian 已提交
1231
			return ExecuteSqlCommandBuf(AH, (void *) ptr, size * nmemb);		/* Always 1, currently */
1232
		else
1233
		{
B
Bruce Momjian 已提交
1234
			res = fwrite((void *) ptr, size, nmemb, AH->OF);
1235
			if (res != nmemb)
1236
				die_horribly(AH, modulename, "could not write to output file (%d != %d)\n", res, nmemb);
1237 1238
			return res;
		}
1239
	}
B
Bruce Momjian 已提交
1240
}
1241 1242

/* Common exit code */
B
Bruce Momjian 已提交
1243
static void
1244
_write_msg(const char *modulename, const char *fmt, va_list ap)
1245
{
1246
	if (modulename)
1247
		fprintf(stderr, "%s: [%s] ", progname, gettext(modulename));
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
	else
		fprintf(stderr, "%s: ", progname);
	vfprintf(stderr, gettext(fmt), ap);
}

void
write_msg(const char *modulename, const char *fmt, ...)
{
	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);
1268 1269
	if (AH->public.verbose)
		write_msg(NULL, "*** aborted because of error\n");
1270

B
Bruce Momjian 已提交
1271 1272 1273
	if (AH)
		if (AH->connection)
			PQfinish(AH->connection);
1274 1275
	if (AH->blobConnection)
		PQfinish(AH->blobConnection);
1276

B
Bruce Momjian 已提交
1277
	exit(1);
B
Bruce Momjian 已提交
1278 1279
}

1280
/* External use */
B
Bruce Momjian 已提交
1281
void
1282
exit_horribly(Archive *AH, const char *modulename, const char *fmt,...)
1283
{
B
Bruce Momjian 已提交
1284
	va_list		ap;
1285

B
Bruce Momjian 已提交
1286
	va_start(ap, fmt);
1287
	_die_horribly((ArchiveHandle *) AH, modulename, fmt, ap);
1288
}
B
Bruce Momjian 已提交
1289

1290
/* Archiver use (just different arg declaration) */
B
Bruce Momjian 已提交
1291
void
1292
die_horribly(ArchiveHandle *AH, const char *modulename, const char *fmt,...)
B
Bruce Momjian 已提交
1293
{
B
Bruce Momjian 已提交
1294
	va_list		ap;
B
Bruce Momjian 已提交
1295

B
Bruce Momjian 已提交
1296
	va_start(ap, fmt);
1297
	_die_horribly(AH, modulename, fmt, ap);
B
Bruce Momjian 已提交
1298 1299
}

1300

B
Bruce Momjian 已提交
1301 1302
static void
_moveAfter(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
B
Bruce Momjian 已提交
1303
{
B
Bruce Momjian 已提交
1304 1305
	te->prev->next = te->next;
	te->next->prev = te->prev;
B
Bruce Momjian 已提交
1306

B
Bruce Momjian 已提交
1307 1308
	te->prev = pos;
	te->next = pos->next;
B
Bruce Momjian 已提交
1309

B
Bruce Momjian 已提交
1310 1311
	pos->next->prev = te;
	pos->next = te;
B
Bruce Momjian 已提交
1312

B
Bruce Momjian 已提交
1313
	te->_moved = 1;
B
Bruce Momjian 已提交
1314 1315
}

B
Bruce Momjian 已提交
1316 1317
static void
_moveBefore(ArchiveHandle *AH, TocEntry *pos, TocEntry *te)
B
Bruce Momjian 已提交
1318
{
B
Bruce Momjian 已提交
1319 1320
	te->prev->next = te->next;
	te->next->prev = te->prev;
B
Bruce Momjian 已提交
1321

B
Bruce Momjian 已提交
1322 1323 1324 1325
	te->prev = pos->prev;
	te->next = pos;
	pos->prev->next = te;
	pos->prev = te;
B
Bruce Momjian 已提交
1326

B
Bruce Momjian 已提交
1327
	te->_moved = 1;
B
Bruce Momjian 已提交
1328 1329
}

B
Bruce Momjian 已提交
1330 1331
static TocEntry *
_getTocEntry(ArchiveHandle *AH, int id)
B
Bruce Momjian 已提交
1332
{
B
Bruce Momjian 已提交
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
	TocEntry   *te;

	te = AH->toc->next;
	while (te != AH->toc)
	{
		if (te->id == id)
			return te;
		te = te->next;
	}
	return NULL;
B
Bruce Momjian 已提交
1343 1344
}

B
Bruce Momjian 已提交
1345 1346
int
TocIDRequired(ArchiveHandle *AH, int id, RestoreOptions *ropt)
B
Bruce Momjian 已提交
1347
{
B
Bruce Momjian 已提交
1348
	TocEntry   *te = _getTocEntry(AH, id);
B
Bruce Momjian 已提交
1349

B
Bruce Momjian 已提交
1350 1351
	if (!te)
		return 0;
B
Bruce Momjian 已提交
1352

B
Bruce Momjian 已提交
1353
	return _tocEntryRequired(te, ropt);
B
Bruce Momjian 已提交
1354 1355
}

B
Bruce Momjian 已提交
1356 1357
int
WriteInt(ArchiveHandle *AH, int i)
B
Bruce Momjian 已提交
1358
{
B
Bruce Momjian 已提交
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
	int			b;

	/*
	 * This is a bit yucky, but I don't want to make the binary format
	 * very dependant 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.
	 */

	/* SIGN byte */
	if (i < 0)
	{
		(*AH->WriteBytePtr) (AH, 1);
1373
		i = -i;
B
Bruce Momjian 已提交
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
	}
	else
		(*AH->WriteBytePtr) (AH, 0);

	for (b = 0; b < AH->intSize; b++)
	{
		(*AH->WriteBytePtr) (AH, i & 0xFF);
		i = i / 256;
	}

	return AH->intSize + 1;
B
Bruce Momjian 已提交
1385 1386
}

B
Bruce Momjian 已提交
1387 1388
int
ReadInt(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1389
{
B
Bruce Momjian 已提交
1390 1391 1392 1393 1394
	int			res = 0;
	int			bv,
				b;
	int			sign = 0;		/* Default positive */
	int			bitShift = 0;
B
Bruce Momjian 已提交
1395

B
Bruce Momjian 已提交
1396
	if (AH->version > K_VERS_1_0)
1397
		/* Read a sign byte */
B
Bruce Momjian 已提交
1398
		sign = (*AH->ReadBytePtr) (AH);
B
Bruce Momjian 已提交
1399

B
Bruce Momjian 已提交
1400 1401 1402
	for (b = 0; b < AH->intSize; b++)
	{
		bv = (*AH->ReadBytePtr) (AH) & 0xFF;
1403 1404 1405
		if (bv != 0)
			res = res + (bv << bitShift);
		bitShift += 8;
B
Bruce Momjian 已提交
1406
	}
B
Bruce Momjian 已提交
1407

B
Bruce Momjian 已提交
1408 1409
	if (sign)
		res = -res;
B
Bruce Momjian 已提交
1410

B
Bruce Momjian 已提交
1411
	return res;
B
Bruce Momjian 已提交
1412 1413
}

B
Bruce Momjian 已提交
1414
int
1415
WriteStr(ArchiveHandle *AH, const char *c)
B
Bruce Momjian 已提交
1416
{
B
Bruce Momjian 已提交
1417
	int			res;
1418 1419 1420 1421

	if (c)
	{
		res = WriteInt(AH, strlen(c));
B
Bruce Momjian 已提交
1422
		res += (*AH->WriteBufPtr) (AH, c, strlen(c));
1423 1424 1425 1426
	}
	else
		res = WriteInt(AH, -1);

B
Bruce Momjian 已提交
1427
	return res;
B
Bruce Momjian 已提交
1428 1429
}

B
Bruce Momjian 已提交
1430 1431
char *
ReadStr(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1432
{
B
Bruce Momjian 已提交
1433 1434
	char	   *buf;
	int			l;
B
Bruce Momjian 已提交
1435

B
Bruce Momjian 已提交
1436
	l = ReadInt(AH);
1437 1438 1439 1440
	if (l == -1)
		buf = NULL;
	else
	{
B
Bruce Momjian 已提交
1441
		buf = (char *) malloc(l + 1);
1442
		if (!buf)
1443
			die_horribly(AH, modulename, "out of memory\n");
1444

B
Bruce Momjian 已提交
1445
		(*AH->ReadBufPtr) (AH, (void *) buf, l);
1446 1447
		buf[l] = '\0';
	}
B
Bruce Momjian 已提交
1448

B
Bruce Momjian 已提交
1449
	return buf;
B
Bruce Momjian 已提交
1450 1451
}

T
Tom Lane 已提交
1452
static int
B
Bruce Momjian 已提交
1453
_discoverArchiveFormat(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1454
{
B
Bruce Momjian 已提交
1455 1456 1457 1458
	FILE	   *fh;
	char		sig[6];			/* More than enough */
	int			cnt;
	int			wantClose = 0;
B
Bruce Momjian 已提交
1459

1460 1461 1462
#if 0
	 write_msg(modulename, "attempting to ascertain archive format\n");
#endif
1463 1464 1465 1466 1467 1468 1469 1470

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

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

B
Bruce Momjian 已提交
1472 1473
	if (AH->fSpec)
	{
1474 1475
		wantClose = 1;
		fh = fopen(AH->fSpec, PG_BINARY_R);
B
Bruce Momjian 已提交
1476 1477
	}
	else
1478
		fh = stdin;
B
Bruce Momjian 已提交
1479

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

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

B
Bruce Momjian 已提交
1485
	if (cnt != 5)
1486 1487 1488 1489 1490 1491
	{
		if (ferror(fh))
			die_horribly(AH, modulename, "could not read input file: %s\n", strerror(errno));
		else
			die_horribly(AH, modulename, "input file is too short (read %d, expected 5)\n", cnt);
	}
B
Bruce Momjian 已提交
1492

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

B
Bruce Momjian 已提交
1497
	if (strncmp(sig, "PGDMP", 5) == 0)
1498 1499 1500 1501 1502 1503 1504 1505 1506
	{
		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 已提交
1507 1508
		if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0)))		/* Version > 1.0 */
		{
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
			AH->vrev = fgetc(fh);
			AH->lookahead[AH->lookaheadLen++] = AH->vrev;
		}
		else
			AH->vrev = 0;

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

		AH->format = fgetc(fh);
		AH->lookahead[AH->lookaheadLen++] = AH->format;

		/* Make a convenient integer <maj><min><rev>00 */
B
Bruce Momjian 已提交
1522 1523 1524 1525 1526
		AH->version = ((AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev) * 256 + 0;
	}
	else
	{

1527
		/*
B
Bruce Momjian 已提交
1528 1529
		 * *Maybe* we have a tar archive format file... So, read first 512
		 * byte header...
1530 1531 1532
		 */
		cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
		AH->lookaheadLen += cnt;
B
Bruce Momjian 已提交
1533

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

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

1540 1541
		AH->format = archTar;
	}
B
Bruce Momjian 已提交
1542

B
Bruce Momjian 已提交
1543 1544
	/* If we can't seek, then mark the header as read */
	if (fseek(fh, 0, SEEK_SET) != 0)
1545
	{
B
Bruce Momjian 已提交
1546

1547
		/*
B
Bruce Momjian 已提交
1548 1549
		 * NOTE: Formats that use the looahead buffer can unset this in
		 * their Init routine.
1550 1551 1552 1553
		 */
		AH->readHeader = 1;
	}
	else
B
Bruce Momjian 已提交
1554
		AH->lookaheadLen = 0;	/* Don't bother since we've reset the file */
1555

1556 1557 1558
#if 0
	write_msg(modulename, "read %d bytes into lookahead buffer\n", AH->lookaheadLen);
#endif
B
Bruce Momjian 已提交
1559

B
Bruce Momjian 已提交
1560 1561
	/* Close the file */
	if (wantClose)
1562
		if (fclose(fh) != 0)
1563 1564
			die_horribly(AH, modulename, "could not close the input file after reading header: %s\n",
						 strerror(errno));
B
Bruce Momjian 已提交
1565

B
Bruce Momjian 已提交
1566
	return AH->format;
B
Bruce Momjian 已提交
1567 1568 1569 1570 1571 1572
}


/*
 * Allocate an archive handle
 */
B
Bruce Momjian 已提交
1573 1574 1575
static ArchiveHandle *
_allocAH(const char *FileSpec, const ArchiveFormat fmt,
		 const int compression, ArchiveMode mode)
1576
{
B
Bruce Momjian 已提交
1577
	ArchiveHandle *AH;
B
Bruce Momjian 已提交
1578

1579 1580 1581
#if 0
	 write_msg(modulename, "allocating AH for %s, format %d\n", FileSpec, fmt);
#endif
1582

B
Bruce Momjian 已提交
1583 1584
	AH = (ArchiveHandle *) calloc(1, sizeof(ArchiveHandle));
	if (!AH)
1585
		die_horribly(AH, modulename, "out of memory\n");
B
Bruce Momjian 已提交
1586

B
Bruce Momjian 已提交
1587 1588
	AH->vmaj = K_VERS_MAJOR;
	AH->vmin = K_VERS_MINOR;
1589
	AH->vrev = K_VERS_REV;
B
Bruce Momjian 已提交
1590

1591 1592
	AH->createDate = time(NULL);

B
Bruce Momjian 已提交
1593 1594 1595 1596
	AH->intSize = sizeof(int);
	AH->lastID = 0;
	if (FileSpec)
	{
1597
		AH->fSpec = strdup(FileSpec);
B
Bruce Momjian 已提交
1598

1599 1600 1601
		/*
		 * Not used; maybe later....
		 *
B
Bruce Momjian 已提交
1602 1603
		 * AH->workDir = strdup(FileSpec); for(i=strlen(FileSpec) ; i > 0 ;
		 * i--) if (AH->workDir[i-1] == '/')
1604
		 */
B
Bruce Momjian 已提交
1605 1606
	}
	else
1607
		AH->fSpec = NULL;
B
Bruce Momjian 已提交
1608

B
Bruce Momjian 已提交
1609 1610
	AH->currUser = strdup("");	/* So it's valid, but we can free() it
								 * later if necessary */
B
Bruce Momjian 已提交
1611

B
Bruce Momjian 已提交
1612 1613
	AH->toc = (TocEntry *) calloc(1, sizeof(TocEntry));
	if (!AH->toc)
1614
		die_horribly(AH, modulename, "out of memory\n");
B
Bruce Momjian 已提交
1615

B
Bruce Momjian 已提交
1616 1617 1618 1619 1620
	AH->toc->next = AH->toc;
	AH->toc->prev = AH->toc;

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

1622 1623
	AH->pgCopyBuf = createPQExpBuffer();
	AH->sqlBuf = createPQExpBuffer();
B
Bruce Momjian 已提交
1624

B
Bruce Momjian 已提交
1625 1626 1627
	/* Open stdout with no compression for AH output handle */
	AH->gzOut = 0;
	AH->OF = stdout;
B
Bruce Momjian 已提交
1628

1629 1630 1631
#if 0
	 write_msg(modulename, "archive format is %d\n", fmt);
#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)
	{
B
Bruce Momjian 已提交
1640

1641 1642 1643
		case archCustom:
			InitArchiveFmt_Custom(AH);
			break;
B
Bruce Momjian 已提交
1644

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

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

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

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

B
Bruce Momjian 已提交
1661
	return AH;
B
Bruce Momjian 已提交
1662 1663 1664
}


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

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

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

B
Bruce Momjian 已提交
1690 1691
			if (startPtr != NULL)
				(*startPtr) (AH, te);
B
Bruce Momjian 已提交
1692

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

			/*
			 * The user-provided DataDumper routine needs to call
			 * AH->WriteData
			 */
			(*te->dataDumper) ((Archive *) AH, te->oid, te->dataDumperArg);

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

B
Bruce Momjian 已提交
1712 1713
void
WriteToc(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1714
{
B
Bruce Momjian 已提交
1715
	TocEntry   *te = AH->toc->next;
1716 1717
	const char *dep;
	int			i;
B
Bruce Momjian 已提交
1718 1719 1720 1721 1722 1723 1724 1725 1726

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

	WriteInt(AH, AH->tocCount);
	while (te != AH->toc)
	{
		WriteInt(AH, te->id);
		WriteInt(AH, te->dataDumper ? 1 : 0);
		WriteStr(AH, te->oid);
1727

B
Bruce Momjian 已提交
1728 1729 1730 1731 1732 1733
		WriteStr(AH, te->name);
		WriteStr(AH, te->desc);
		WriteStr(AH, te->defn);
		WriteStr(AH, te->dropStmt);
		WriteStr(AH, te->copyStmt);
		WriteStr(AH, te->owner);
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745

		/* Dump list of dependencies */
		if (te->depOid != NULL)
		{
			i = 0;
			while( (dep = (*te->depOid)[i++]) != NULL)
			{
				WriteStr(AH, dep);
			}
		}
		WriteStr(AH, NULL); /* Terminate List */

B
Bruce Momjian 已提交
1746 1747
		if (AH->WriteExtraTocPtr)
			(*AH->WriteExtraTocPtr) (AH, te);
1748
		te = te->next;
B
Bruce Momjian 已提交
1749
	}
B
Bruce Momjian 已提交
1750 1751
}

B
Bruce Momjian 已提交
1752 1753
void
ReadToc(ArchiveHandle *AH)
B
Bruce Momjian 已提交
1754
{
B
Bruce Momjian 已提交
1755
	int			i;
1756 1757 1758
	char		*((*deps)[]);
	int			depIdx;
	int			depSize;
B
Bruce Momjian 已提交
1759

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

B
Bruce Momjian 已提交
1762
	AH->tocCount = ReadInt(AH);
B
Bruce Momjian 已提交
1763

B
Bruce Momjian 已提交
1764 1765
	for (i = 0; i < AH->tocCount; i++)
	{
B
Bruce Momjian 已提交
1766

B
Bruce Momjian 已提交
1767
		te = (TocEntry *) calloc(1, sizeof(TocEntry));
1768 1769 1770 1771
		te->id = ReadInt(AH);

		/* Sanity check */
		if (te->id <= 0 || te->id > AH->tocCount)
1772
			die_horribly(AH, modulename, "entry id out of range - perhaps a corrupt TOC\n");
1773 1774 1775

		te->hadDumper = ReadInt(AH);
		te->oid = ReadStr(AH);
1776 1777
		te->oidVal = atooid(te->oid);

1778 1779 1780 1781 1782 1783 1784 1785 1786 1787
		te->name = ReadStr(AH);
		te->desc = ReadStr(AH);
		te->defn = ReadStr(AH);
		te->dropStmt = ReadStr(AH);

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

		te->owner = ReadStr(AH);

1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
		/* Read TOC entry dependencies */
		if (AH->version >= K_VERS_1_5)
		{
			depSize = 100;
			deps = malloc(sizeof(char*) * depSize);
			depIdx = 0;
			do
			{
				if (depIdx > depSize)
				{
					depSize *= 2;
					deps = realloc(deps, sizeof(char*) * depSize);
				}
				(*deps)[depIdx] = ReadStr(AH);
1802 1803 1804 1805 1806
#if 0
				if ((*deps)[depIdx])
					write_msg(modulename, "read dependency for %s -> %s\n",
							  te->name, (*deps)[depIdx]);
#endif
1807 1808 1809
			} while ( (*deps)[depIdx++] != NULL);

			if (depIdx > 1) /* We have a non-null entry */
1810 1811 1812
				te->depOid = realloc(deps, sizeof(char*) * depIdx);	/* trim it */
			else
				te->depOid = NULL; /* no deps */
1813
		}
1814 1815
		else
			te->depOid = NULL;
1816 1817 1818 1819

		/* Set maxOidVal etc for use in sorting */
		_fixupOidInfo(te);

B
Bruce Momjian 已提交
1820 1821
		if (AH->ReadExtraTocPtr)
			(*AH->ReadExtraTocPtr) (AH, te);
1822

1823
		ahlog(AH, 3, "read TOC entry %d (id %d) for %s %s\n", i, te->id, te->desc, te->name);
1824 1825 1826 1827 1828

		te->prev = AH->toc->prev;
		AH->toc->prev->next = te;
		AH->toc->prev = te;
		te->next = AH->toc;
B
Bruce Momjian 已提交
1829
	}
B
Bruce Momjian 已提交
1830 1831
}

B
Bruce Momjian 已提交
1832 1833
static int
_tocEntryRequired(TocEntry *te, RestoreOptions *ropt)
B
Bruce Momjian 已提交
1834
{
B
Bruce Momjian 已提交
1835 1836 1837 1838
	int			res = 3;		/* Schema = 1, Data = 2, Both = 3 */

	/* If it's an ACL, maybe ignore it */
	if (ropt->aclsSkip && strcmp(te->desc, "ACL") == 0)
1839
		return 0;
B
Bruce Momjian 已提交
1840

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

B
Bruce Momjian 已提交
1844 1845 1846 1847
	/* Check if tablename only is wanted */
	if (ropt->selTypes)
	{
		if ((strcmp(te->desc, "TABLE") == 0) || (strcmp(te->desc, "TABLE DATA") == 0))
1848 1849 1850 1851 1852
		{
			if (!ropt->selTable)
				return 0;
			if (ropt->tableNames && strcmp(ropt->tableNames, te->name) != 0)
				return 0;
B
Bruce Momjian 已提交
1853 1854 1855
		}
		else if (strcmp(te->desc, "INDEX") == 0)
		{
1856 1857 1858 1859
			if (!ropt->selIndex)
				return 0;
			if (ropt->indexNames && strcmp(ropt->indexNames, te->name) != 0)
				return 0;
B
Bruce Momjian 已提交
1860 1861 1862
		}
		else if (strcmp(te->desc, "FUNCTION") == 0)
		{
1863 1864 1865 1866
			if (!ropt->selFunction)
				return 0;
			if (ropt->functionNames && strcmp(ropt->functionNames, te->name) != 0)
				return 0;
B
Bruce Momjian 已提交
1867 1868 1869
		}
		else if (strcmp(te->desc, "TRIGGER") == 0)
		{
1870 1871 1872 1873 1874
			if (!ropt->selTrigger)
				return 0;
			if (ropt->triggerNames && strcmp(ropt->triggerNames, te->name) != 0)
				return 0;
		}
B
Bruce Momjian 已提交
1875 1876
		else
			return 0;
B
Bruce Momjian 已提交
1877 1878
	}

1879 1880 1881
	/* Special Case: If 'SEQUENCE SET' then it is considered a data entry */
	if (strcmp(te->desc, "SEQUENCE SET") == 0)
		res = res & 2;
1882

B
Bruce Momjian 已提交
1883 1884
	/* Mask it if we only want schema */
	if (ropt->schemaOnly)
1885
		res = res & 1;
B
Bruce Momjian 已提交
1886

B
Bruce Momjian 已提交
1887
	/* Mask it we only want data */
1888
	if (ropt->dataOnly)
B
Bruce Momjian 已提交
1889
		res = res & 2;
B
Bruce Momjian 已提交
1890

B
Bruce Momjian 已提交
1891 1892
	/* Mask it if we don't have a schema contribition */
	if (!te->defn || strlen(te->defn) == 0)
1893
		res = res & 2;
B
Bruce Momjian 已提交
1894

B
Bruce Momjian 已提交
1895 1896
	/* Finally, if we used a list, limit based on that as well */
	if (ropt->limitToList && !ropt->idWanted[te->id - 1])
1897
		return 0;
B
Bruce Momjian 已提交
1898

B
Bruce Momjian 已提交
1899
	return res;
B
Bruce Momjian 已提交
1900 1901
}

1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912

/*
 * Issue the commands to connect to the database as the specified user
 * to the specified database.  The database name may be NULL, then the
 * current database is kept.  If reconnects were disallowed by the
 * user, this won't do anything.
 *
 * If we're currently restoring right into a database, this will
 * actuall establish a connection.  Otherwise it puts a \connect into
 * the script output.
 */
B
Bruce Momjian 已提交
1913
static void
1914
_reconnectAsUser(ArchiveHandle *AH, const char *dbname, const char *user)
1915
{
1916 1917 1918
	if (!user || strlen(user) == 0
		|| (strcmp(AH->currUser, user) == 0 && !dbname))
		return;					/* no need to do anything */
1919

1920 1921
	/* Use SET SESSION AUTHORIZATION if allowed and no database change needed */
	if (!dbname && AH->ropt->use_setsessauth)
1922
	{
1923
		if (RestoringToDB(AH))
1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
		{
			PQExpBuffer qry = createPQExpBuffer();
			PGresult   *res;

			appendPQExpBuffer(qry, "SET SESSION AUTHORIZATION '%s';", user);
			res = PQexec(AH->connection, qry->data);

			if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
				die_horribly(AH, modulename, "could not set session user to %s: %s",
							 user, PQerrorMessage(AH->connection));
1934

1935 1936 1937 1938 1939
			PQclear(res);
			destroyPQExpBuffer(qry);
		}
		else
			ahprintf(AH, "SET SESSION AUTHORIZATION '%s';\n\n", user);
B
Bruce Momjian 已提交
1940
	}
1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
	/* When -R was given, don't do anything. */
	else if (AH->ropt && AH->ropt->noReconnect)
		return;

	else if (RestoringToDB(AH))
		ReconnectToServer(AH, dbname, user);
	else
		/* FIXME: does not handle mixed case user names */
		ahprintf(AH, "\\connect %s %s\n\n",
				 dbname ? dbname : "-",
				 user ? 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);
1959 1960
}

1961 1962 1963 1964 1965 1966

/*
 * Issues the commands to connect to the database (or the current one,
 * if NULL) as the owner of the the given TOC entry object.  If
 * changes in ownership are not allowed, this doesn't do anything.
 */
B
Bruce Momjian 已提交
1967 1968
static void
_reconnectAsOwner(ArchiveHandle *AH, const char *dbname, TocEntry *te)
1969 1970 1971 1972 1973
{
	if (AH->ropt && AH->ropt->noOwner)
		return;

	_reconnectAsUser(AH, dbname, te->owner);
1974 1975
}

1976

B
Bruce Momjian 已提交
1977
static int
1978
_printTocEntry(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt, bool isData)
B
Bruce Momjian 已提交
1979
{
1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
	char	*pfx;

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

	ahprintf(AH, "--\n-- %sTOC Entry ID %d (OID %s)\n--\n-- Name: %s Type: %s Owner: %s\n",
			 pfx, te->id, te->oid, te->name, te->desc, te->owner);
B
Bruce Momjian 已提交
1991 1992 1993
	if (AH->PrintExtraTocPtr !=NULL)
		(*AH->PrintExtraTocPtr) (AH, te);
	ahprintf(AH, "--\n\n");
B
Bruce Momjian 已提交
1994

1995
	ahprintf(AH, "%s\n", te->defn);
B
Bruce Momjian 已提交
1996

B
Bruce Momjian 已提交
1997
	return 1;
B
Bruce Momjian 已提交
1998 1999
}

B
Bruce Momjian 已提交
2000 2001
void
WriteHead(ArchiveHandle *AH)
B
Bruce Momjian 已提交
2002
{
B
Bruce Momjian 已提交
2003
	struct tm	crtm;
2004

B
Bruce Momjian 已提交
2005 2006 2007 2008 2009 2010
	(*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);
	(*AH->WriteBytePtr) (AH, AH->format);
B
Bruce Momjian 已提交
2011

2012
#ifndef HAVE_LIBZ
B
Bruce Momjian 已提交
2013
	if (AH->compression != 0)
2014 2015
		write_msg(modulename, "WARNING: requested compression not available in this "
				  "installation - archive will be uncompressed\n");
B
Bruce Momjian 已提交
2016

B
Bruce Momjian 已提交
2017
	AH->compression = 0;
2018
#endif
B
Bruce Momjian 已提交
2019

2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
	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);
B
Bruce Momjian 已提交
2030
	WriteStr(AH, AH->dbname);
B
Bruce Momjian 已提交
2031 2032
}

B
Bruce Momjian 已提交
2033 2034
void
ReadHead(ArchiveHandle *AH)
B
Bruce Momjian 已提交
2035
{
B
Bruce Momjian 已提交
2036 2037
	char		tmpMag[7];
	int			fmt;
2038
	struct tm	crtm;
B
Bruce Momjian 已提交
2039

2040
	/* If we haven't already read the header... */
B
Bruce Momjian 已提交
2041 2042
	if (!AH->readHeader)
	{
B
Bruce Momjian 已提交
2043

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

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

B
Bruce Momjian 已提交
2049 2050
		AH->vmaj = (*AH->ReadBytePtr) (AH);
		AH->vmin = (*AH->ReadBytePtr) (AH);
B
Bruce Momjian 已提交
2051

B
Bruce Momjian 已提交
2052 2053 2054
		if (AH->vmaj > 1 || ((AH->vmaj == 1) && (AH->vmin > 0)))		/* Version > 1.0 */
			AH->vrev = (*AH->ReadBytePtr) (AH);
		else
2055
			AH->vrev = 0;
B
Bruce Momjian 已提交
2056

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


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

B
Bruce Momjian 已提交
2064
		AH->intSize = (*AH->ReadBytePtr) (AH);
2065
		if (AH->intSize > 32)
2066
			die_horribly(AH, modulename, "sanity check on integer size (%d) failed\n", AH->intSize);
B
Bruce Momjian 已提交
2067

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

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

2073
		if (AH->format != fmt)
2074 2075
			die_horribly(AH, modulename, "expected format (%d) differs from format found in file (%d)\n",
						 AH->format, fmt);
B
Bruce Momjian 已提交
2076
	}
B
Bruce Momjian 已提交
2077

B
Bruce Momjian 已提交
2078 2079
	if (AH->version >= K_VERS_1_2)
	{
2080
		if (AH->version < K_VERS_1_4)
B
Bruce Momjian 已提交
2081
			AH->compression = (*AH->ReadBytePtr) (AH);
2082 2083
		else
			AH->compression = ReadInt(AH);
B
Bruce Momjian 已提交
2084 2085
	}
	else
2086
		AH->compression = Z_DEFAULT_COMPRESSION;
B
Bruce Momjian 已提交
2087

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

2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
	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 已提交
2107
		if (AH->createDate == (time_t) -1)
2108
			write_msg(modulename, "WARNING: invalid creation date in header\n");
2109 2110
	}

B
Bruce Momjian 已提交
2111 2112 2113
}


B
Bruce Momjian 已提交
2114 2115
static void
_SortToc(ArchiveHandle *AH, TocSortCompareFn fn)
B
Bruce Momjian 已提交
2116
{
B
Bruce Momjian 已提交
2117 2118 2119
	TocEntry  **tea;
	TocEntry   *te;
	int			i;
B
Bruce Momjian 已提交
2120

B
Bruce Momjian 已提交
2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135
	/* Allocate an array for quicksort (TOC size + head & foot) */
	tea = (TocEntry **) malloc(sizeof(TocEntry *) * (AH->tocCount + 2));

	/* Build array of toc entries, including header at start and end */
	te = AH->toc;
	for (i = 0; i <= AH->tocCount + 1; i++)
	{

		/*
		 * printf("%d: %x (%x, %x) - %d\n", i, te, te->prev, te->next,
		 * te->oidVal);
		 */
		tea[i] = te;
		te = te->next;
	}
B
Bruce Momjian 已提交
2136

B
Bruce Momjian 已提交
2137 2138
	/* Sort it, but ignore the header entries */
	qsort(&(tea[1]), AH->tocCount, sizeof(TocEntry *), fn);
B
Bruce Momjian 已提交
2139

B
Bruce Momjian 已提交
2140 2141 2142 2143 2144 2145
	/* Rebuild list: this works becuase we have headers at each end */
	for (i = 1; i <= AH->tocCount; i++)
	{
		tea[i]->next = tea[i + 1];
		tea[i]->prev = tea[i - 1];
	}
B
Bruce Momjian 已提交
2146 2147


B
Bruce Momjian 已提交
2148 2149 2150
	te = AH->toc;
	for (i = 0; i <= AH->tocCount + 1; i++)
	{
B
Bruce Momjian 已提交
2151

B
Bruce Momjian 已提交
2152 2153 2154 2155 2156 2157
		/*
		 * printf("%d: %x (%x, %x) - %d\n", i, te, te->prev, te->next,
		 * te->oidVal);
		 */
		te = te->next;
	}
B
Bruce Momjian 已提交
2158 2159


B
Bruce Momjian 已提交
2160 2161
	AH->toc->next = tea[1];
	AH->toc->prev = tea[AH->tocCount];
B
Bruce Momjian 已提交
2162 2163
}

B
Bruce Momjian 已提交
2164 2165
static int
_tocSortCompareByOIDNum(const void *p1, const void *p2)
B
Bruce Momjian 已提交
2166
{
B
Bruce Momjian 已提交
2167 2168
	TocEntry   *te1 = *(TocEntry **) p1;
	TocEntry   *te2 = *(TocEntry **) p2;
2169 2170 2171
	Oid			id1 = te1->maxOidVal;
	Oid			id2 = te2->maxOidVal;
	int			cmpval;
B
Bruce Momjian 已提交
2172

B
Bruce Momjian 已提交
2173
	/* printf("Comparing %d to %d\n", id1, id2); */
B
Bruce Momjian 已提交
2174

2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
	cmpval = oidcmp(id1, id2);

	/* If we have a deterministic answer, return it. */
	if (cmpval != 0)
	   return cmpval;

	/* More comparisons required */
	if ( oideq(id1, te1->maxDepOidVal) ) /* maxOid1 came from deps */
	{
		if ( oideq(id2, te2->maxDepOidVal) ) /* maxOid2 also came from deps */
		{
			cmpval = oidcmp(te1->oidVal, te2->oidVal); /* Just compare base OIDs */
		}
		else /* MaxOid2 was entry OID */
		{
			return 1; /* entry1 > entry2 */
		};
	} 
	else /* must have oideq(id1, te1->oidVal) => maxOid1 = Oid1 */
	{
		if ( oideq(id2, te2->maxDepOidVal) ) /* maxOid2 came from deps */
		{
			return -1; /* entry1 < entry2 */
		}
		else /* MaxOid2 was entry OID - deps don't matter */
		{
			cmpval = 0;
		};
	};

	/* If we get here, then we've done another comparison
	 * Once again, a 0 result means we require even more
	 */
	if (cmpval != 0)
		return cmpval;

	/* Entire OID details match, so use ID number (ie. original pg_dump order) */
	return _tocSortCompareByIDNum(te1, te2);
B
Bruce Momjian 已提交
2213 2214
}

B
Bruce Momjian 已提交
2215 2216
static int
_tocSortCompareByIDNum(const void *p1, const void *p2)
B
Bruce Momjian 已提交
2217
{
B
Bruce Momjian 已提交
2218 2219 2220 2221
	TocEntry   *te1 = *(TocEntry **) p1;
	TocEntry   *te2 = *(TocEntry **) p2;
	int			id1 = te1->id;
	int			id2 = te2->id;
B
Bruce Momjian 已提交
2222

B
Bruce Momjian 已提交
2223
	/* printf("Comparing %d to %d\n", id1, id2); */
B
Bruce Momjian 已提交
2224

B
Bruce Momjian 已提交
2225 2226 2227 2228 2229 2230
	if (id1 < id2)
		return -1;
	else if (id1 > id2)
		return 1;
	else
		return 0;
B
Bruce Momjian 已提交
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
/*
 * Assuming Oid and depOid are set, work out the various
 * Oid values used in sorting.
 */
static void 
_fixupOidInfo(TocEntry *te)
{
	te->oidVal = atooid(te->oid);
	te->maxDepOidVal = _findMaxOID(te->depOid);

	/* For the purpose of sorting, find the max OID. */
	if (oidcmp(te->oidVal, te->maxDepOidVal) >= 0) 
		te->maxOidVal = te->oidVal;
	else
		te->maxOidVal = te->maxDepOidVal;
}

/* 
 * Find the max OID value for a given list of string Oid values 
 */
static Oid
_findMaxOID(const char *((*deps)[]))
{
	const char *dep;
	int			i;
	Oid			maxOid = (Oid)0;
	Oid			currOid;

	if (!deps)
		return maxOid;

	i = 0;
	while( (dep = (*deps)[i++]) != NULL)
	{
		currOid = atooid(dep);
		if (oidcmp(maxOid, currOid) < 0)
			maxOid = currOid;
	}

	return maxOid;
}

2275 2276 2277 2278 2279 2280 2281 2282
/*
 * Maybe I can use this somewhere...
 *
 *create table pgdump_blob_path(p text);
 *insert into pgdump_blob_path values('/home/pjw/work/postgresql-cvs/pgsql/src/bin/pg_dump_140');
 *
 *insert into dump_blob_xref select 12345,lo_import(p || '/q.q') from pgdump_blob_path;
 */