pg_backup_archiver.c 40.1 KB
Newer Older
B
Bruce Momjian 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*-------------------------------------------------------------------------
 *
 * 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
 * 	as this notice is not removed.
 *
 *	The author is not responsible for loss or damages that may
 *	result from it's use.
 *
 *
 * IDENTIFICATION
 *
 * Modifications - 28-Jun-2000 - pjw@rhyme.com.au
 *
21 22 23 24
 *		Initial version. 
 *
 * 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 已提交
25 26 27 28 29 30
 *
 *-------------------------------------------------------------------------
 */

#include "pg_backup.h"
#include "pg_backup_archiver.h"
31 32
#include "pg_backup_db.h"

B
Bruce Momjian 已提交
33 34 35 36 37 38 39
#include <string.h>
#include <unistd.h> /* for dup */

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

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

B
Bruce Momjian 已提交
43 44 45
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);
46
static ArchiveHandle* 	_allocAH(const char* FileSpec, const ArchiveFormat fmt, 
B
Bruce Momjian 已提交
47 48
				int compression, ArchiveMode mode);
static int 		_printTocEntry(ArchiveHandle* AH, TocEntry* te, RestoreOptions *ropt);
49 50 51

static void		_reconnectAsOwner(ArchiveHandle* AH, const char *dbname, TocEntry* te);
static void		_reconnectAsUser(ArchiveHandle* AH, const char *dbname, char *user);
52

B
Bruce Momjian 已提交
53 54 55 56 57 58 59
static int		_tocEntryRequired(TocEntry* te, RestoreOptions *ropt);
static void		_disableTriggers(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt);
static void		_enableTriggers(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);
60

B
Bruce Momjian 已提交
61 62
static char	*progname = "Archiver";

63 64 65
static void		_die_horribly(ArchiveHandle *AH, const char *fmt, va_list ap);

static int 		_canRestoreBlobs(ArchiveHandle *AH);
66
static int 		_restoringToDB(ArchiveHandle *AH);
67

B
Bruce Momjian 已提交
68 69 70 71 72 73 74 75 76 77 78
/*
 *  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.
 *
 */


/* Create a new archive */
/* Public */
79 80 81
Archive* CreateArchive(const char* FileSpec, const ArchiveFormat fmt,
                                const int compression)

B
Bruce Momjian 已提交
82 83 84 85 86 87 88
{
    ArchiveHandle*	AH = _allocAH(FileSpec, fmt, compression, archModeWrite);
    return (Archive*)AH;
}

/* Open an existing archive */
/* Public */
89
Archive* OpenArchive(const char* FileSpec, const ArchiveFormat fmt) 
B
Bruce Momjian 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102
{
    ArchiveHandle*      AH = _allocAH(FileSpec, fmt, 0, archModeRead);
    return (Archive*)AH;
}

/* Public */
void	CloseArchive(Archive* AHX)
{
    ArchiveHandle*      AH = (ArchiveHandle*)AHX;
    (*AH->ClosePtr)(AH);

    /* Close the output */
    if (AH->gzOut)
103
		GZCLOSE(AH->OF);
B
Bruce Momjian 已提交
104
    else if (AH->OF != stdout)
105
		fclose(AH->OF);
B
Bruce Momjian 已提交
106 107 108 109 110 111 112 113 114 115
}

/* Public */
void RestoreArchive(Archive* AHX, RestoreOptions *ropt)
{
    ArchiveHandle*	AH = (ArchiveHandle*) AHX;
    TocEntry		*te = AH->toc->next;
    int			reqs;
    OutputContext	sav;

116 117
	AH->ropt = ropt;

118 119 120
	if (ropt->create && ropt->noReconnect)
		die_horribly(AH, "%s: --create and --no-reconnect are incompatible options\n",progname);

121 122 123 124 125 126 127 128 129 130 131
	/*
	 * If we're using a DB connection, then connect it.
	 */
	if (ropt->useDB)
	{
		ahlog(AH, 1, "Connecting to database for restore\n");
		if (AH->version < K_VERS_1_3)
			die_horribly(AH, "Direct database connections are not supported in pre-1.3 archives");

		ConnectDatabase(AHX, ropt->dbname, ropt->pghost, ropt->pgport, 
							ropt->requirePassword, ropt->ignoreVersion);
132 133 134 135 136 137 138 139 140 141

		/*
		 * If no superuser was specified then see if the current user will do...
		 */
		if (!ropt->superuser)
		{
			if (UserIsSuperuser(AH, ConnectedUser(AH)))
				ropt->superuser = strdup(ConnectedUser(AH));
		}

142 143
	}

144 145 146 147 148 149 150
	if (!ropt->superuser)
		fprintf(stderr, "\n%s: ******** WARNING ******** \n"
							"        Data restoration may fail since any defined triggers\n"
							"        can not be disabled (no superuser username specified).\n"
							"        This is only a problem for restoration into a database\n"
							"        with triggers already defined.\n\n", progname);

151 152 153
	/*
	 *	Setup the output file if necessary.
	 */
B
Bruce Momjian 已提交
154
    if (ropt->filename || ropt->compression)
155
		sav = SetOutput(AH, ropt->filename, ropt->compression);
B
Bruce Momjian 已提交
156 157 158

    ahprintf(AH, "--\n-- Selected TOC Entries:\n--\n");

159 160 161
    /*
     * Drop the items at the start, in reverse order 
	 */
B
Bruce Momjian 已提交
162
    if (ropt->dropSchema) {
163 164 165 166 167 168 169 170 171
		te = AH->toc->prev;
		while (te != AH->toc) {
			reqs = _tocEntryRequired(te, ropt);
			if ( ( (reqs & 1) != 0) && te->dropStmt) {  /* We want the schema */
				ahlog(AH, 1, "Dropping %s %s\n", te->desc, te->name);
				ahprintf(AH, "%s", te->dropStmt);
			}
			te = te->prev;
		}
B
Bruce Momjian 已提交
172 173
    }

174 175 176
	/*
	 * Now process each TOC entry
	 */
B
Bruce Momjian 已提交
177 178 179
    te = AH->toc->next;
    while (te != AH->toc) {

180 181 182 183 184
		/* Work out what, if anything, we want from this entry */
		reqs = _tocEntryRequired(te, ropt);

		if ( (reqs & 1) != 0) /* We want the schema */
		{
185 186 187
			/* Reconnect if necessary */
			_reconnectAsOwner(AH, "-", te);

188 189
			ahlog(AH, 1, "Creating %s %s\n", te->desc, te->name);
			_printTocEntry(AH, te, ropt);
190 191 192 193 194 195 196

			/* If we created a DB, connect to it... */
			if (strcmp(te->desc,"DATABASE") == 0)
			{
				ahlog(AH, 1, "Connecting to new DB '%s' as %s\n",te->name, te->owner);
				_reconnectAsUser(AH, te->name, te->owner);
			}
197
		}
B
Bruce Momjian 已提交
198

199 200 201 202
		/* 
		 * If we want data, and it has data, then restore that too 
		 */
		if (AH->PrintTocDataPtr != NULL && (reqs & 2) != 0) {
203
#ifndef HAVE_LIBZ
204 205
			if (AH->compression != 0)
				die_horribly(AH, "%s: Unable to restore data from a compressed archive\n", progname);
B
Bruce Momjian 已提交
206
#endif
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226

			ahprintf(AH, "--\n-- Data for TOC Entry ID %d (OID %s) %s %s\n--\n\n",
						te->id, te->oid, te->desc, te->name);

			/*
			 * 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)
					fprintf(stderr, "%s: WARNING - skipping BLOB restoration\n", progname);
			} else {

				_disableTriggers(AH, te, ropt);

227 228 229 230
				/* Reconnect if necessary (_disableTriggers may have reconnected) */
				_reconnectAsOwner(AH, "-", te);

				ahlog(AH, 1, "Restoring data for %s \n", te->name);
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247

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

				_enableTriggers(AH, te, ropt);
			}
		}
		te = te->next;
B
Bruce Momjian 已提交
248 249
    }

250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
	/*
	 * Now use blobs_xref (if used) to fixup any refs for tables that we loaded
	 */
	if (_canRestoreBlobs(AH) && AH->createdBlobXref)
	{
		te = AH->toc->next;
		while (te != AH->toc) {

			/* Is it table data? */
			if (strcmp(te->desc, "TABLE DATA") == 0) {

				ahlog(AH, 2, "Checking if we loaded %s\n", te->name);

				reqs = _tocEntryRequired(te, ropt);

				if ( (reqs & 2) != 0) /* We loaded the data */
				{
					ahlog(AH, 1, "Fixing up BLOB ref for %s\n", te->name);
					FixupBlobRefs(AH, te->name);
				}
			}
			else
			{
				ahlog(AH, 2, "Ignoring BLOB xrefs for %s %s\n", te->desc, te->name);
			}

			te = te->next;
		}
	}

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

286 287 288 289
	if (ropt->useDB)
	{
		PQfinish(AH->connection);
		AH->connection = NULL;
290 291 292 293 294 295

		if (AH->blobConnection)
		{
			PQfinish(AH->blobConnection);
			AH->blobConnection = NULL;
		}
296
	}
B
Bruce Momjian 已提交
297 298
}

299 300 301 302
/*
 * Allocate a new RestoreOptions block.
 * This is mainly so we can initialize it, but also for future expansion,
 */
B
Bruce Momjian 已提交
303 304 305 306 307 308 309 310 311 312 313
RestoreOptions*		NewRestoreOptions(void)
{
	RestoreOptions* opts;

	opts = (RestoreOptions*)calloc(1, sizeof(RestoreOptions));

	opts->format = archUnknown;

	return opts;
}

314
static int _restoringToDB(ArchiveHandle *AH)
315 316 317 318
{
	return (AH->ropt->useDB && AH->connection);
}

319 320 321 322 323
static int _canRestoreBlobs(ArchiveHandle *AH)
{
	return _restoringToDB(AH);
}

B
Bruce Momjian 已提交
324 325
static void _disableTriggers(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
{
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
	char	*oldUser = NULL;

	/* Can't do much if we're connected & don't have a superuser */
	if (_restoringToDB(AH) && !ropt->superuser)
		return;

	/*
     * Reconnect as superuser if possible, since they are the only ones
	 * who can update pg_class...
	 */
	if (ropt->superuser)
	{
		/* 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.
		 */
		if (ropt->noOwner)
			oldUser = strdup(ConnectedUser(AH));
		_reconnectAsUser(AH, "-", ropt->superuser);
	}

	ahlog(AH, 1, "Disabling triggers\n");

	/*
     * Disable them. This is a hack. Needs to be done via an appropriate 'SET'
	 * command when one is available.
	 */
B
Bruce Momjian 已提交
353 354
    ahprintf(AH, "-- Disable triggers\n");
    ahprintf(AH, "UPDATE \"pg_class\" SET \"reltriggers\" = 0 WHERE \"relname\" !~ '^pg_';\n\n");
355 356 357 358 359 360 361 362 363 364

	/*
	 * Restore the user connection from the start of this procedure
	 * if _reconnectAsOwner is disabled.
	 */
	if (ropt->noOwner && oldUser)
	{
		_reconnectAsUser(AH, "-", oldUser);
		free(oldUser);
	}
B
Bruce Momjian 已提交
365 366 367 368
}

static void _enableTriggers(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
{
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
	char		*oldUser = NULL;

	/* Can't do much if we're connected & don't have a superuser */
	if (_restoringToDB(AH) && !ropt->superuser)
		return;

	/*
	 * Reconnect as superuser if possible, since they are the only ones
	 * who can update pg_class...
	 */
	if (ropt->superuser)
	{
		/* 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
		 */
		if (ropt->noOwner)
			oldUser = strdup(ConnectedUser(AH));

		_reconnectAsUser(AH, "-", ropt->superuser);
	}

	ahlog(AH, 1, "Enabling triggers\n");

	/*
	 * Enable them. This is a hack. Needs to be done via an appropriate 'SET'
	 * command when one is available.
	 */
B
Bruce Momjian 已提交
397 398 399 400 401 402 403 404 405 406 407 408
    ahprintf(AH, "-- Enable triggers\n");
    ahprintf(AH, "BEGIN TRANSACTION;\n");
    ahprintf(AH, "CREATE TEMP TABLE \"tr\" (\"tmp_relname\" name, \"tmp_reltriggers\" smallint);\n");
    ahprintf(AH, "INSERT INTO \"tr\" SELECT C.\"relname\", count(T.\"oid\") FROM \"pg_class\" C,"
	    " \"pg_trigger\" T WHERE C.\"oid\" = T.\"tgrelid\" AND C.\"relname\" !~ '^pg_' "
	    " GROUP BY 1;\n");
    ahprintf(AH, "UPDATE \"pg_class\" SET \"reltriggers\" = TMP.\"tmp_reltriggers\" "
	    "FROM \"tr\" TMP WHERE "
	    "\"pg_class\".\"relname\" = TMP.\"tmp_relname\";\n");
    ahprintf(AH, "DROP TABLE \"tr\";\n");
    ahprintf(AH, "COMMIT TRANSACTION;\n\n");

409 410 411 412 413 414 415 416 417 418
	/*
	 * Restore the user connection from the start of this procedure
	 * if _reconnectAsOwner is disabled.
	 */
	if (ropt->noOwner && oldUser)
	{
		_reconnectAsUser(AH, "-", oldUser);
		free(oldUser);
	}
}
B
Bruce Momjian 已提交
419 420

/*
421
 * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
B
Bruce Momjian 已提交
422 423 424 425 426 427 428
 */

/* Public */
int	WriteData(Archive* AHX, const void* data, int dLen)
{
    ArchiveHandle*      AH = (ArchiveHandle*)AHX;

429 430 431 432
	if (!AH->currToc)
		die_horribly(AH, "%s: WriteData can not be called outside the context of "
						"a DataDumper routine\n", progname);

B
Bruce Momjian 已提交
433 434 435 436 437 438 439 440 441 442 443
    return (*AH->WriteDataPtr)(AH, data, dLen);
}

/*
 * Create a new TOC entry. The TOC was designed as a TOC, but is now the 
 * repository for all metadata. But the name has stuck.
 */

/* Public */
void	ArchiveEntry(Archive* AHX, const char* oid, const char* name,
			const char* desc, const char* (deps[]), const char* defn,
444
			const char* dropStmt, const char* copyStmt, const char* owner,
B
Bruce Momjian 已提交
445 446 447 448 449 450 451 452
			DataDumperPtr dumpFn, void* dumpArg)
{
    ArchiveHandle*	AH = (ArchiveHandle*)AHX;
    TocEntry*		newToc;

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

453
    newToc = (TocEntry*)calloc(1, sizeof(TocEntry));
B
Bruce Momjian 已提交
454
    if (!newToc)
455
	die_horribly(AH, "Archiver: unable to allocate memory for TOC entry\n");
B
Bruce Momjian 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468

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

    newToc->id = AH->lastID;
    newToc->oid = strdup(oid);
    newToc->oidVal = atoi(oid);
    newToc->name = strdup(name);
    newToc->desc = strdup(desc);
    newToc->defn = strdup(defn);
    newToc->dropStmt = strdup(dropStmt);
469
	newToc->copyStmt = copyStmt ? strdup(copyStmt) : NULL;
B
Bruce Momjian 已提交
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
    newToc->owner = strdup(owner);
    newToc->printed = 0;
    newToc->formatData = NULL;
    newToc->dataDumper = dumpFn,
    newToc->dataDumperArg = dumpArg;

    newToc->hadDumper = dumpFn ? 1 : 0;

    if (AH->ArchiveEntryPtr != NULL) {
		(*AH->ArchiveEntryPtr)(AH, newToc);
    }

    /* printf("New toc owned by '%s', oid %d\n", newToc->owner, newToc->oidVal); */
}

/* Public */
void PrintTOCSummary(Archive* AHX, RestoreOptions *ropt)
{
    ArchiveHandle*	AH = (ArchiveHandle*) AHX;
    TocEntry		*te = AH->toc->next;
    OutputContext	sav;
491
	char			*fmtName;
B
Bruce Momjian 已提交
492 493 494 495

    if (ropt->filename)
	sav = SetOutput(AH, ropt->filename, ropt->compression);

496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
	ahprintf(AH, ";\n; Archive created at %s", ctime(&AH->createDate));
	ahprintf(AH, ";     dbname: %s\n;     TOC Entries: %d\n;     Compression: %d\n",
				AH->archdbname, AH->tocCount, AH->compression);

	switch (AH->format) {
		case archFiles:
			fmtName = "FILES";
			break;
		case archCustom:
			fmtName = "CUSTOM";
			break;
		case archTar:
			fmtName = "TAR";
			break;
		default:
			fmtName = "UNKNOWN";
	}
513 514

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

B
Bruce Momjian 已提交
517 518 519 520 521 522 523 524 525 526 527 528
    ahprintf(AH, ";\n; Selected TOC Entries:\n;\n");

    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);
		te = te->next;
    }

    if (ropt->filename)
	ResetOutput(AH, sav);
}

529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
/***********
 * BLOB Archival
 ***********/

/* Called by a dumper to signal start of a BLOB */
int StartBlob(Archive* AHX, int oid)
{
    ArchiveHandle* AH = (ArchiveHandle*)AHX;

    if (!AH->StartBlobPtr)
		die_horribly(AH, "%s: BLOB output not supported in chosen format\n", progname);

    (*AH->StartBlobPtr)(AH, AH->currToc, oid);

    return 1;
}

/* Called by a dumper to signal end of a BLOB */
int EndBlob(Archive* AHX, int oid)
{
    ArchiveHandle* AH = (ArchiveHandle*)AHX;

    if (AH->EndBlobPtr)
		(*AH->EndBlobPtr)(AH, AH->currToc, oid);

    return 1;
}

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

/*
 * Called by a format handler to initiate restoration of a blob
 */
void StartRestoreBlob(ArchiveHandle* AH, int oid)
{
	int			loOid;

	if (!AH->createdBlobXref)
	{
		if (!AH->connection)
			die_horribly(AH, "%s: can not restore BLOBs without a database connection", progname);

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

577 578
	StartTransaction(AH);

579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
	loOid = lo_creat(AH->connection, INV_READ | INV_WRITE);
	if (loOid == 0)
		die_horribly(AH, "%s: unable to create BLOB\n", progname);

	ahlog(AH, 1, "Restoring BLOB oid %d as %d\n", oid, loOid);

	InsertBlobXref(AH, oid, loOid);

	AH->loFd = lo_open(AH->connection, loOid, INV_WRITE);
	if (AH->loFd == -1)
		die_horribly(AH, "%s: unable to open BLOB\n", progname);

    AH->writingBlob = 1;
}

void EndRestoreBlob(ArchiveHandle* AH, int oid)
{
    lo_close(AH->connection, AH->loFd);
    AH->writingBlob = 0;

	CommitTransaction(AH);
}

B
Bruce Momjian 已提交
602 603 604 605 606 607 608
/***********
 * Sorting and Reordering
 ***********/

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

B
Bruce Momjian 已提交
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
/* Public */
void MoveToStart(Archive* AHX, char *oType) 
{
    ArchiveHandle* AH = (ArchiveHandle*)AHX;
    TocEntry	*te = AH->toc->next;
    TocEntry	*newTe;

    while (te != AH->toc) {
		te->_moved = 0;
		te = te->next;
    }

    te = AH->toc->prev;
    while (te != AH->toc && !te->_moved) {
	newTe = te->prev;
	if (strcmp(te->desc, oType) == 0) {
	    _moveAfter(AH, AH->toc, te);
	}
		te = newTe;
    }
}


/*
 * Move TOC entries of the specified type to the end of the TOC.
 */
/* Public */
void MoveToEnd(Archive* AHX, char *oType) 
{
    ArchiveHandle* AH = (ArchiveHandle*)AHX;
    TocEntry	*te = AH->toc->next;
    TocEntry	*newTe;

    while (te != AH->toc) {
	te->_moved = 0;
	te = te->next;
    }

    te = AH->toc->next;
    while (te != AH->toc && !te->_moved) {
	newTe = te->next;
	if (strcmp(te->desc, oType) == 0) {
	    _moveBefore(AH, AH->toc, te);
	}
		te = newTe;
    }
}

/* 
 * Sort TOC by OID
 */
/* Public */
void SortTocByOID(Archive* AHX)
{
    ArchiveHandle* AH = (ArchiveHandle*)AHX;
    _SortToc(AH, _tocSortCompareByOIDNum);
}

/*
 * Sort TOC by ID
 */
/* Public */
void SortTocByID(Archive* AHX)
{
    ArchiveHandle* AH = (ArchiveHandle*)AHX;
    _SortToc(AH, _tocSortCompareByIDNum);
}

void SortTocFromFile(Archive* AHX, RestoreOptions *ropt)
{
    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;
    }

    /* Set prev entry as head of list */
    tePrev = AH->toc;

    /* Setup the file */
    fh = fopen(ropt->tocFile, PG_BINARY_R);
    if (!fh)
710
	die_horribly(AH, "%s: could not open TOC file\n", progname);
B
Bruce Momjian 已提交
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730

    while (fgets(buf, 1024, fh) != NULL)
    {
	/* 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)
	{
731
	    fprintf(stderr, "%s: WARNING - line ignored: %s\n", progname, buf);
B
Bruce Momjian 已提交
732 733 734 735 736 737
	    continue;
	}

	/* Find TOC entry */
	te = _getTocEntry(AH, id);
	if (!te) 
738
	    die_horribly(AH, "%s: could not find entry for id %d\n",progname, id);
B
Bruce Momjian 已提交
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768

	ropt->idWanted[id-1] = 1;

	_moveAfter(AH, tePrev, te);
	tePrev = te;
    }

    fclose(fh);
}

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

/* Public */
int archputs(const char *s, Archive* AH) {
    return WriteData(AH, s, strlen(s));
}

/* Public */
int archputc(const char c, Archive* AH) {
    return WriteData(AH, &c, 1);
}

/* Public */
int archprintf(Archive* AH, const char *fmt, ...)
{
    char 	*p = NULL;
    va_list 	ap;
769
    int		bSize = strlen(fmt) + 256;
B
Bruce Momjian 已提交
770 771 772
    int		cnt = -1;

    va_start(ap, fmt);
773 774 775 776

    /* 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 已提交
777 778 779 780 781
	if (p != NULL) free(p);
	bSize *= 2;
	if ((p = malloc(bSize)) == NULL)
	{
	    va_end(ap);
782
	    exit_horribly(AH, "%s: could not allocate buffer for archprintf\n", progname);
B
Bruce Momjian 已提交
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
	}
	cnt = vsnprintf(p, bSize, fmt, ap);
    }
    va_end(ap);
    WriteData(AH, p, cnt);
    free(p);
    return cnt;
}


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

OutputContext SetOutput(ArchiveHandle* AH, char *filename, int compression)
{
    OutputContext	sav;
800
#ifdef HAVE_LIBZ
B
Bruce Momjian 已提交
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
    char		fmode[10];
#endif
    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 */
821
#ifdef HAVE_LIBZ
B
Bruce Momjian 已提交
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
    if (compression != 0)
    {
	sprintf(fmode, "wb%d", compression);
	if (fn) {
	    AH->OF = gzdopen(dup(fn), fmode); /* Don't use PG_BINARY_x since this is zlib */
	} else {
	    AH->OF = gzopen(filename, fmode);
	}
	AH->gzOut = 1;
    } else { /* Use fopen */
#endif
	if (fn) {
	    AH->OF = fdopen(dup(fn), PG_BINARY_W);
	} else {
	    AH->OF = fopen(filename, PG_BINARY_W);
	}
	AH->gzOut = 0;
839
#ifdef HAVE_LIBZ
B
Bruce Momjian 已提交
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
    }
#endif

    return sav;
}

void ResetOutput(ArchiveHandle* AH, OutputContext sav)
{
    if (AH->gzOut)
	GZCLOSE(AH->OF);
    else
	fclose(AH->OF);

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



/*
 *  Print formatted text to the output file (usually stdout).
 */
int ahprintf(ArchiveHandle* AH, const char *fmt, ...)
{
    char 	*p = NULL;
    va_list 	ap;
866
    int		bSize = strlen(fmt) + 256; /* Should be enough */
B
Bruce Momjian 已提交
867 868 869
    int		cnt = -1;

    va_start(ap, fmt);
870 871 872
    /* 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) ) {
873 874 875 876 877 878 879 880 881
		if (p != NULL) free(p);
		bSize *= 2;
		p = (char*)malloc(bSize);
		if (p == NULL)
		{
			va_end(ap);
			die_horribly(AH, "%s: could not allocate buffer for ahprintf\n", progname);
		}
		cnt = vsnprintf(p, bSize, fmt, ap);
B
Bruce Momjian 已提交
882 883 884 885 886 887 888
    }
    va_end(ap);
    ahwrite(p, 1, cnt, AH);
    free(p);
    return cnt;
}

889 890 891 892 893 894 895 896 897 898 899 900
void ahlog(ArchiveHandle* AH, int level, const char *fmt, ...)
{
	va_list		ap;

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

	va_start(ap, fmt);
	vfprintf(stderr, fmt, ap);
	va_end(ap);
}

901 902 903 904 905 906 907 908
/*
 * Single place for logic which says 'We are restoring to a direct DB connection'.
 */
int RestoringToDB(ArchiveHandle* AH)
{
	return (AH->ropt && AH->ropt->useDB && AH->connection);
}

B
Bruce Momjian 已提交
909
/*
910 911 912 913
 *  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
 *	wants to generate a script (see TAR output).
B
Bruce Momjian 已提交
914 915 916
 */
int ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle* AH)
{
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
	int		res;

    if (AH->writingBlob)
	{
		res = lo_write(AH->connection, AH->loFd, (void*)ptr, size * nmemb);
		ahlog(AH, 5, "Wrote %d bytes of BLOB data (result = %d)\n", size * nmemb, res);
		return res;
	}
    else if (AH->gzOut)
		return GZWRITE((void*)ptr, size, nmemb, AH->OF);
    else if (AH->CustomOutPtr)
		return AH->CustomOutPtr(AH, ptr, size * nmemb);
	else
	{
		/*
		 * If we're doing a restore, and it's direct to DB, and we're connected
	     * then send it to the DB.
		 */	
935
		if (RestoringToDB(AH))
936 937 938 939 940 941 942 943 944 945 946 947 948 949
			return ExecuteSqlCommandBuf(AH, (void*)ptr, size*nmemb);
		else
			return fwrite((void*)ptr, size, nmemb, AH->OF);
	}
}		

/* Common exit code */
static void _die_horribly(ArchiveHandle *AH, const char *fmt, va_list ap)
{
    vfprintf(stderr, fmt, ap);

    if (AH)
	if (AH->connection)
	    PQfinish(AH->connection);
950 951
	if (AH->blobConnection)
		PQfinish(AH->blobConnection);
952 953

    exit(1);
B
Bruce Momjian 已提交
954 955
}

956 957 958 959 960 961 962 963
/* External use */
void exit_horribly(Archive *AH, const char *fmt, ...)
{
    va_list     ap;

    va_start(ap, fmt);
    _die_horribly((ArchiveHandle*)AH, fmt, ap);
}
B
Bruce Momjian 已提交
964

965 966
/* Archiver use (just different arg declaration) */
void die_horribly(ArchiveHandle *AH, const char *fmt, ...)
B
Bruce Momjian 已提交
967 968 969 970
{
    va_list 	ap;

    va_start(ap, fmt);
971
    _die_horribly(AH, fmt, ap);
B
Bruce Momjian 已提交
972 973
}

974

B
Bruce Momjian 已提交
975 976 977 978 979 980 981 982 983 984 985 986 987 988 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 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
static void _moveAfter(ArchiveHandle* AH, TocEntry* pos, TocEntry* te)
{
    te->prev->next = te->next;
    te->next->prev = te->prev;

    te->prev = pos;
    te->next = pos->next;

    pos->next->prev = te;
    pos->next = te;

    te->_moved = 1;
}

static void _moveBefore(ArchiveHandle* AH, TocEntry* pos, TocEntry* te)
{
    te->prev->next = te->next;
    te->next->prev = te->prev;

    te->prev = pos->prev;
    te->next = pos;
    pos->prev->next = te;
    pos->prev = te;

    te->_moved = 1;
}

static TocEntry* _getTocEntry(ArchiveHandle* AH, int id)
{
    TocEntry    *te;

    te = AH->toc->next;
    while (te != AH->toc) {
	if (te->id == id)
	    return te;
	te = te->next;
    }
    return NULL;
}

int	TocIDRequired(ArchiveHandle* AH, int id, RestoreOptions *ropt)
{
    TocEntry	*te = _getTocEntry(AH, id);

    if (!te)
	return 0;

    return _tocEntryRequired(te, ropt);
}

int	WriteInt(ArchiveHandle* AH, int i)
{
    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);
1040
		i = -i;
B
Bruce Momjian 已提交
1041
    } else {
1042
		(*AH->WriteBytePtr)(AH, 0);
B
Bruce Momjian 已提交
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
    }
    
    for(b = 0 ; b < AH->intSize ; b++) {
        (*AH->WriteBytePtr)(AH, i & 0xFF);
        i = i / 256;
    }

    return AH->intSize + 1;
}

int    	ReadInt(ArchiveHandle* AH)
{
    int res = 0;
    int bv, b;
    int	sign = 0; /* Default positive */
1058
	int bitShift = 0;
B
Bruce Momjian 已提交
1059 1060

    if (AH->version > K_VERS_1_0)
1061 1062
		/* Read a sign byte */
		sign = (*AH->ReadBytePtr)(AH);
B
Bruce Momjian 已提交
1063 1064

    for( b = 0 ; b < AH->intSize ; b++) {
1065 1066 1067 1068
        bv = (*AH->ReadBytePtr)(AH) & 0xFF;
		if (bv != 0)
			res = res + (bv << bitShift);
		bitShift += 8;
B
Bruce Momjian 已提交
1069 1070 1071
    }

    if (sign)
1072
		res = - res;
B
Bruce Momjian 已提交
1073 1074 1075 1076 1077 1078

    return res;
}

int	WriteStr(ArchiveHandle* AH, char* c)
{
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
    int res;

	if (c)
	{
		res = WriteInt(AH, strlen(c));
		res += (*AH->WriteBufPtr)(AH, c, strlen(c));
	}
	else
		res = WriteInt(AH, -1);

    return res;
B
Bruce Momjian 已提交
1090 1091 1092 1093 1094 1095 1096 1097
}

char*	ReadStr(ArchiveHandle* AH)
{
    char*	buf;
    int		l;

    l = ReadInt(AH);
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
	if (l == -1)
		buf = NULL;
	else
	{
		buf = (char*)malloc(l+1);
		if (!buf)
			die_horribly(AH, "%s: Unable to allocate sufficient memory in ReadStr - "													"requested %d (0x%x) bytes\n", progname, l, l);

		(*AH->ReadBufPtr)(AH, (void*)buf, l);
		buf[l] = '\0';
	}
B
Bruce Momjian 已提交
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119

    return buf;
}

int _discoverArchiveFormat(ArchiveHandle* AH)
{
    FILE	*fh;
    char	sig[6]; /* More than enough */
    int		cnt;
    int		wantClose = 0;

1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
	/*
	 * fprintf(stderr, "%s: Attempting to ascertain archive format\n", progname);
	 */

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

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

B
Bruce Momjian 已提交
1132
    if (AH->fSpec) {
1133 1134
		wantClose = 1;
		fh = fopen(AH->fSpec, PG_BINARY_R);
B
Bruce Momjian 已提交
1135
    } else {
1136
		fh = stdin;
B
Bruce Momjian 已提交
1137 1138 1139
    }

    if (!fh)
1140
		die_horribly(AH, "Archiver: could not open input file\n");
B
Bruce Momjian 已提交
1141 1142 1143

    cnt = fread(sig, 1, 5, fh);

1144
    if (cnt != 5)
1145
        die_horribly(AH, "%s: input file is too short, or is unreadable\n", progname);
B
Bruce Momjian 已提交
1146

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

1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
    if (strncmp(sig, "PGDMP", 5) == 0)
	{
		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 */
		if (AH->vmaj > 1 || ( (AH->vmaj == 1) && (AH->vmin > 0) ) ) /* Version > 1.0 */
		{	
			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 */
		AH->version = ( (AH->vmaj * 256 + AH->vmin) * 256 + AH->vrev ) * 256 + 0;
	} else {
		/*
		 * *Maybe* we have a tar archive format file...
		 * So, read first 512 byte header...
		 */
		cnt = fread(&AH->lookahead[AH->lookaheadLen], 1, 512 - AH->lookaheadLen, fh);
		AH->lookaheadLen += cnt;
B
Bruce Momjian 已提交
1184

1185 1186 1187
		if (AH->lookaheadLen != 512)
			die_horribly(AH, "%s: input file does not appear to be a valid archive (too short?)\n",
							progname);
B
Bruce Momjian 已提交
1188

1189 1190
		if (!isValidTarHeader(AH->lookahead))
			die_horribly(AH, "%s: input file does not appear to be a valid archive\n", progname);
B
Bruce Momjian 已提交
1191

1192 1193
		AH->format = archTar;
	}
B
Bruce Momjian 已提交
1194 1195 1196

    /* If we can't seek, then mark the header as read */
    if (fseek(fh, 0, SEEK_SET) != 0) 
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
	{
		/*
		 * NOTE: Formats that use the looahead buffer can unset this in their Init routine.
		 */
		AH->readHeader = 1;
	}
	else
		AH->lookaheadLen = 0; /* Don't bother since we've reset the file */

	/*
	 *fprintf(stderr, "%s: read %d bytes into lookahead buffer\n", progname, AH->lookaheadLen);
	 */
B
Bruce Momjian 已提交
1209 1210 1211

    /* Close the file */
    if (wantClose)
1212
		fclose(fh);
B
Bruce Momjian 已提交
1213 1214 1215 1216 1217 1218 1219 1220

    return AH->format;
}


/*
 * Allocate an archive handle
 */
1221 1222 1223
static ArchiveHandle* _allocAH(const char* FileSpec, const ArchiveFormat fmt, 
				const int compression, ArchiveMode mode) 
{
B
Bruce Momjian 已提交
1224 1225
    ArchiveHandle*	AH;

1226 1227 1228 1229
	/*
	 *fprintf(stderr, "%s: allocating AH for %s, format %d\n", progname, FileSpec, fmt); 
	 */

1230
    AH = (ArchiveHandle*)calloc(1, sizeof(ArchiveHandle));
B
Bruce Momjian 已提交
1231
    if (!AH) 
1232
		die_horribly(AH, "Archiver: Could not allocate archive handle\n");
B
Bruce Momjian 已提交
1233 1234 1235

    AH->vmaj = K_VERS_MAJOR;
    AH->vmin = K_VERS_MINOR;
1236
	AH->vrev = K_VERS_REV;
B
Bruce Momjian 已提交
1237

1238 1239
	AH->createDate = time(NULL);

B
Bruce Momjian 已提交
1240 1241 1242
    AH->intSize = sizeof(int);
    AH->lastID = 0;
    if (FileSpec) {
1243 1244 1245 1246 1247 1248 1249 1250
		AH->fSpec = strdup(FileSpec);
		/*
		 * Not used; maybe later....
		 *
		 * AH->workDir = strdup(FileSpec);
		 * for(i=strlen(FileSpec) ; i > 0 ; i--)
		 *   if (AH->workDir[i-1] == '/')
		 */
B
Bruce Momjian 已提交
1251
    } else {
1252 1253
		AH->fSpec = NULL;
    } 
B
Bruce Momjian 已提交
1254 1255 1256

    AH->currUser = "";

1257
    AH->toc = (TocEntry*)calloc(1, sizeof(TocEntry));
B
Bruce Momjian 已提交
1258
    if (!AH->toc)
1259
		die_horribly(AH, "Archiver: Could not allocate TOC header\n");
B
Bruce Momjian 已提交
1260 1261 1262 1263 1264 1265 1266

    AH->toc->next = AH->toc;
    AH->toc->prev = AH->toc;
    
    AH->mode = mode;
    AH->compression = compression;

1267 1268
	AH->pgCopyBuf = createPQExpBuffer();
	AH->sqlBuf = createPQExpBuffer();
B
Bruce Momjian 已提交
1269 1270 1271 1272 1273

    /* Open stdout with no compression for AH output handle */
    AH->gzOut = 0;
    AH->OF = stdout;

1274 1275 1276 1277
	/*
	 *fprintf(stderr, "%s: archive format is %d\n", progname, fmt);
	 */

B
Bruce Momjian 已提交
1278
    if (fmt == archUnknown)
1279 1280 1281
		AH->format = _discoverArchiveFormat(AH);
	else
		AH->format = fmt;
B
Bruce Momjian 已提交
1282

1283
    switch (AH->format) {
B
Bruce Momjian 已提交
1284

1285 1286 1287
		case archCustom:
			InitArchiveFmt_Custom(AH);
			break;
B
Bruce Momjian 已提交
1288

1289 1290 1291
		case archFiles:
			InitArchiveFmt_Files(AH);
			break;
B
Bruce Momjian 已提交
1292

1293 1294 1295
		case archNull:
			InitArchiveFmt_Null(AH);
			break;
B
Bruce Momjian 已提交
1296

1297 1298 1299 1300 1301 1302
		case archTar:
			InitArchiveFmt_Tar(AH);
			break;

		default:
			die_horribly(AH, "Archiver: Unrecognized file format '%d'\n", fmt);
B
Bruce Momjian 已提交
1303 1304 1305 1306 1307 1308 1309 1310 1311
    }

    return AH;
}


void WriteDataChunks(ArchiveHandle* AH)
{
    TocEntry		*te = AH->toc->next;
1312 1313
	StartDataPtr	startPtr;
	EndDataPtr		endPtr;
B
Bruce Momjian 已提交
1314 1315 1316 1317 1318

    while (te != AH->toc) {
	if (te->dataDumper != NULL) {
	    AH->currToc = te;
	    /* printf("Writing data for %d (%x)\n", te->id, te); */
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330

		if (strcmp(te->desc, "BLOBS") == 0)
		{
			startPtr = AH->StartBlobsPtr;
			endPtr = AH->EndBlobsPtr;
		} else {
			startPtr = AH->StartDataPtr;
			endPtr = AH->EndDataPtr;
		}

	    if (startPtr != NULL) {
			(*startPtr)(AH, te);
B
Bruce Momjian 已提交
1331 1332 1333 1334 1335 1336 1337 1338
	    }

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

1339 1340
	    if (endPtr != NULL) {
			(*endPtr)(AH, te);
B
Bruce Momjian 已提交
1341 1342 1343
	    }
	    AH->currToc = NULL;
	}
1344
		te = te->next;
B
Bruce Momjian 已提交
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
    }
}

void WriteToc(ArchiveHandle* AH)
{
    TocEntry	*te = AH->toc->next;

    /* 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);
	WriteStr(AH, te->name);
	WriteStr(AH, te->desc);
	WriteStr(AH, te->defn);
	WriteStr(AH, te->dropStmt);
1363
	WriteStr(AH, te->copyStmt);
B
Bruce Momjian 已提交
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
	WriteStr(AH, te->owner);
	if (AH->WriteExtraTocPtr) {
	    (*AH->WriteExtraTocPtr)(AH, te);
	}
	te = te->next;
    }
}

void ReadToc(ArchiveHandle* AH)
{
    int 		i;

    TocEntry	*te = AH->toc->next;

    AH->tocCount = ReadInt(AH);

    for( i = 0 ; i < AH->tocCount ; i++) {

1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
		te = (TocEntry*)calloc(1, sizeof(TocEntry));
		te->id = ReadInt(AH);

		/* Sanity check */
		if (te->id <= 0 || te->id > AH->tocCount)
			die_horribly(AH, "Archiver: failed sanity check (bad entry id) - perhaps a corrupt TOC\n");

		te->hadDumper = ReadInt(AH);
		te->oid = ReadStr(AH);
		te->oidVal = atoi(te->oid);
		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);

		if (AH->ReadExtraTocPtr) {
			(*AH->ReadExtraTocPtr)(AH, te);
		}

		ahlog(AH, 3, "Read TOC entry %d (id %d) for %s %s\n", i, te->id, te->desc, te->name);

		te->prev = AH->toc->prev;
		AH->toc->prev->next = te;
		AH->toc->prev = te;
		te->next = AH->toc;
B
Bruce Momjian 已提交
1412 1413 1414 1415 1416
    }
}

static int _tocEntryRequired(TocEntry* te, RestoreOptions *ropt)
{
1417 1418
    int res = 3; /* Schema = 1, Data = 2, Both = 3 */
 
B
Bruce Momjian 已提交
1419 1420
    /* If it's an ACL, maybe ignore it */
    if (ropt->aclsSkip && strcmp(te->desc,"ACL") == 0)
1421
		return 0;
B
Bruce Momjian 已提交
1422

1423 1424 1425
	if (!ropt->create && strcmp(te->desc,"DATABASE") == 0)
		return 0;

B
Bruce Momjian 已提交
1426 1427 1428
    /* Check if tablename only is wanted */
    if (ropt->selTypes)
    {
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
		if ( (strcmp(te->desc, "TABLE") == 0) || (strcmp(te->desc, "TABLE DATA") == 0) )
		{
			if (!ropt->selTable)
				return 0;
			if (ropt->tableNames && strcmp(ropt->tableNames, te->name) != 0)
				return 0;
		} else if (strcmp(te->desc, "INDEX") == 0) {
			if (!ropt->selIndex)
				return 0;
			if (ropt->indexNames && strcmp(ropt->indexNames, te->name) != 0)
				return 0;
		} else if (strcmp(te->desc, "FUNCTION") == 0) {
			if (!ropt->selFunction)
				return 0;
			if (ropt->functionNames && strcmp(ropt->functionNames, te->name) != 0)
				return 0;
		} else if (strcmp(te->desc, "TRIGGER") == 0) {
			if (!ropt->selTrigger)
				return 0;
			if (ropt->triggerNames && strcmp(ropt->triggerNames, te->name) != 0)
				return 0;
		} else {
			return 0;
		}
B
Bruce Momjian 已提交
1453 1454 1455 1456
	}

    /* Mask it if we only want schema */
    if (ropt->schemaOnly)
1457
		res = res & 1;
B
Bruce Momjian 已提交
1458 1459 1460 1461 1462 1463 1464

    /* Mask it we only want data */
    if (ropt->dataOnly) 
       res = res & 2;

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

    /* Mask it if we don't have a possible data contribition */
    if (!te->hadDumper)
1469
		res = res & 1;
B
Bruce Momjian 已提交
1470 1471 1472

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

    return res;
}

1478
static void _reconnectAsUser(ArchiveHandle* AH, const char *dbname, char *user)
1479
{
1480 1481 1482 1483 1484 1485
	if (AH->ropt && AH->ropt->noReconnect)
		return;

	if (user && strlen(user) != 0
			&& ( (strcmp(AH->currUser, user) != 0) || (strcmp(dbname,"-") != 0)))
	{
1486 1487
		if (RestoringToDB(AH))
		{
1488
			ReconnectDatabase(AH, dbname, user);
1489 1490 1491
		}
		else
		{
1492
			ahprintf(AH, "\\connect %s %s\n", dbname, user);
1493
		}
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
		AH->currUser = user;
    } 
}

static void _reconnectAsOwner(ArchiveHandle* AH, const char *dbname, TocEntry* te) 
{
	if (AH->ropt && AH->ropt->noOwner)
		return;

	_reconnectAsUser(AH, dbname, te->owner);
1504 1505
}

B
Bruce Momjian 已提交
1506 1507 1508 1509 1510
static int _printTocEntry(ArchiveHandle* AH, TocEntry* te, RestoreOptions *ropt) 
{
    ahprintf(AH, "--\n-- TOC Entry ID %d (OID %s)\n--\n-- Name: %s Type: %s Owner: %s\n",
	    te->id, te->oid, te->name, te->desc, te->owner);
    if (AH->PrintExtraTocPtr != NULL) {
1511
		(*AH->PrintExtraTocPtr)(AH, te);
B
Bruce Momjian 已提交
1512 1513 1514
    }
    ahprintf(AH, "--\n\n");

1515
	ahprintf(AH, "%s\n", te->defn);
B
Bruce Momjian 已提交
1516 1517 1518 1519 1520 1521

    return 1;
}

void WriteHead(ArchiveHandle* AH) 
{
1522 1523
	struct tm		crtm;

B
Bruce Momjian 已提交
1524 1525 1526 1527 1528 1529 1530
    (*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);

1531
#ifndef HAVE_LIBZ
B
Bruce Momjian 已提交
1532 1533 1534 1535 1536 1537
    if (AH->compression != 0)
	fprintf(stderr, "%s: WARNING - requested compression not available in this installation - "
		    "archive will be uncompressed \n", progname);

    AH->compression = 0;

1538
#endif
B
Bruce Momjian 已提交
1539

1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
	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);
	WriteStr(AH, AH->dbname);	
B
Bruce Momjian 已提交
1551 1552 1553 1554
}

void ReadHead(ArchiveHandle* AH)
{
1555 1556 1557
    char		tmpMag[7];
    int			fmt;
	struct tm	crtm;
B
Bruce Momjian 已提交
1558

1559
	/* If we haven't already read the header... */
1560
    if (!AH->readHeader) {
B
Bruce Momjian 已提交
1561

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

1564 1565
		if (strncmp(tmpMag,"PGDMP", 5) != 0)
			die_horribly(AH, "Archiver: Did not fing magic PGDMP in file header\n");
B
Bruce Momjian 已提交
1566

1567 1568
		AH->vmaj = (*AH->ReadBytePtr)(AH);
		AH->vmin = (*AH->ReadBytePtr)(AH);
B
Bruce Momjian 已提交
1569

1570 1571 1572 1573 1574 1575
		if (AH->vmaj > 1 || ( (AH->vmaj == 1) && (AH->vmin > 0) ) ) /* Version > 1.0 */
		{
			AH->vrev = (*AH->ReadBytePtr)(AH);
		} else {
			AH->vrev = 0;
		}
B
Bruce Momjian 已提交
1576

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


1580 1581 1582
		if (AH->version < K_VERS_1_0 || AH->version > K_VERS_MAX)
			die_horribly(AH, "%s: unsupported version (%d.%d) in file header\n", 
					progname, AH->vmaj, AH->vmin);
B
Bruce Momjian 已提交
1583

1584 1585 1586
		AH->intSize = (*AH->ReadBytePtr)(AH);
		if (AH->intSize > 32)
			die_horribly(AH, "Archiver: sanity check on integer size (%d) failes\n", AH->intSize);
B
Bruce Momjian 已提交
1587

1588 1589 1590
		if (AH->intSize > sizeof(int))
			fprintf(stderr, "\n%s: WARNING - archive was made on a machine with larger integers, "
					"some operations may fail\n", progname);
B
Bruce Momjian 已提交
1591

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

1594 1595 1596
		if (AH->format != fmt)
			die_horribly(AH, "%s: expected format (%d) differs from format found in file (%d)\n", 
					progname, AH->format, fmt);
1597
    }
B
Bruce Momjian 已提交
1598 1599 1600

    if (AH->version >= K_VERS_1_2)
    {
1601 1602 1603 1604
		if (AH->version < K_VERS_1_4)
			AH->compression = (*AH->ReadBytePtr)(AH);
		else
			AH->compression = ReadInt(AH);
B
Bruce Momjian 已提交
1605
    } else {
1606
		AH->compression = Z_DEFAULT_COMPRESSION;
B
Bruce Momjian 已提交
1607 1608
    }

1609 1610
#ifndef HAVE_LIBZ
    if (AH->compression != 0)
1611 1612
		fprintf(stderr, "%s: WARNING - archive is compressed - any data will not be available\n", 
					progname);
B
Bruce Momjian 已提交
1613 1614
#endif

1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
	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);

		if (AH->createDate == (time_t)-1)
			fprintf(stderr, "%s: WARNING - bad creation date in header\n", progname);
	}

B
Bruce Momjian 已提交
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
}


static void _SortToc(ArchiveHandle* AH, TocSortCompareFn fn)
{
    TocEntry**	tea;
    TocEntry*	te;
    int		i;

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

    /* Sort it, but ignore the header entries */
    qsort(&(tea[1]), AH->tocCount, sizeof(TocEntry*), fn);

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


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


    AH->toc->next = tea[1];
    AH->toc->prev = tea[AH->tocCount];
}

static int	_tocSortCompareByOIDNum(const void* p1, const void* p2)
{
    TocEntry*	te1 = *(TocEntry**)p1;
    TocEntry*	te2 = *(TocEntry**)p2;
    int		id1 = te1->oidVal;
    int 	id2 = te2->oidVal;

    /* printf("Comparing %d to %d\n", id1, id2); */

    if (id1 < id2) {
	return -1;
    } else if (id1 > id2) { 
	return 1;
    } else {
	return _tocSortCompareByIDNum(te1, te2);
    }
}

static int	_tocSortCompareByIDNum(const void* p1, const void* p2)
{
    TocEntry*	te1 = *(TocEntry**)p1;
    TocEntry*	te2 = *(TocEntry**)p2;
    int		id1 = te1->id;
    int 	id2 = te2->id;

    /* printf("Comparing %d to %d\n", id1, id2); */

    if (id1 < id2) {
	return -1;
    } else if (id1 > id2) { 
	return 1;
    } else {
	return 0;
    }
}

1710 1711 1712 1713 1714 1715 1716 1717
/*
 * 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;
 */
B
Bruce Momjian 已提交
1718