pg_backup_archiver.c 35.9 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 21 22 23 24 25 26 27
/*-------------------------------------------------------------------------
 *
 * 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
 *
 *	Initial version. 
 *
 *-------------------------------------------------------------------------
 */

#include "pg_backup.h"
#include "pg_backup_archiver.h"
28 29
#include "pg_backup_db.h"

B
Bruce Momjian 已提交
30 31 32 33 34 35 36
#include <string.h>
#include <unistd.h> /* for dup */

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

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

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

B
Bruce Momjian 已提交
54 55
static char	*progname = "Archiver";

56 57 58 59 60
static void		_die_horribly(ArchiveHandle *AH, const char *fmt, va_list ap);

static int 		_canRestoreBlobs(ArchiveHandle *AH);


B
Bruce Momjian 已提交
61 62 63 64 65 66 67 68 69 70 71
/*
 *  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 */
72 73 74
Archive* CreateArchive(const char* FileSpec, const ArchiveFormat fmt,
                                const int compression)

B
Bruce Momjian 已提交
75 76 77 78 79 80 81
{
    ArchiveHandle*	AH = _allocAH(FileSpec, fmt, compression, archModeWrite);
    return (Archive*)AH;
}

/* Open an existing archive */
/* Public */
82
Archive* OpenArchive(const char* FileSpec, const ArchiveFormat fmt) 
B
Bruce Momjian 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95
{
    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)
96
		GZCLOSE(AH->OF);
B
Bruce Momjian 已提交
97
    else if (AH->OF != stdout)
98
		fclose(AH->OF);
B
Bruce Momjian 已提交
99 100 101 102 103 104 105 106 107 108
}

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

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
	AH->ropt = ropt;

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

	/*
	 *	Setup the output file if necessary.
	 */
B
Bruce Momjian 已提交
127
    if (ropt->filename || ropt->compression)
128
		sav = SetOutput(AH, ropt->filename, ropt->compression);
B
Bruce Momjian 已提交
129 130 131

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

132 133 134
    /*
     * Drop the items at the start, in reverse order 
	 */
B
Bruce Momjian 已提交
135
    if (ropt->dropSchema) {
136 137 138 139 140 141 142 143 144
		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 已提交
145 146
    }

147 148 149
	/*
	 * Now process each TOC entry
	 */
B
Bruce Momjian 已提交
150 151 152
    te = AH->toc->next;
    while (te != AH->toc) {

153 154 155 156 157 158 159 160
		/* Work out what, if anything, we want from this entry */
		reqs = _tocEntryRequired(te, ropt);

		if ( (reqs & 1) != 0) /* We want the schema */
		{
			ahlog(AH, 1, "Creating %s %s\n", te->desc, te->name);
			_printTocEntry(AH, te, ropt);
		}
B
Bruce Momjian 已提交
161

162 163 164 165
		/* 
		 * If we want data, and it has data, then restore that too 
		 */
		if (AH->PrintTocDataPtr != NULL && (reqs & 2) != 0) {
166
#ifndef HAVE_LIBZ
167 168
			if (AH->compression != 0)
				die_horribly(AH, "%s: Unable to restore data from a compressed archive\n", progname);
B
Bruce Momjian 已提交
169
#endif
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208

			ahlog(AH, 1, "Restoring data for %s \n", te->name);

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


				/* 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 已提交
209 210
    }

211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
	/*
	 * 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 已提交
244
    if (ropt->filename)
245
		ResetOutput(AH, sav);
B
Bruce Momjian 已提交
246

247 248 249 250 251
	if (ropt->useDB)
	{
		PQfinish(AH->connection);
		AH->connection = NULL;
	}
B
Bruce Momjian 已提交
252 253
}

254 255 256 257
/*
 * Allocate a new RestoreOptions block.
 * This is mainly so we can initialize it, but also for future expansion,
 */
B
Bruce Momjian 已提交
258 259 260 261 262 263 264 265 266 267 268
RestoreOptions*		NewRestoreOptions(void)
{
	RestoreOptions* opts;

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

	opts->format = archUnknown;

	return opts;
}

269 270 271 272 273
static int _canRestoreBlobs(ArchiveHandle *AH)
{
	return (AH->ropt->useDB && AH->connection);
}

B
Bruce Momjian 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
static void _disableTriggers(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
{
    ahprintf(AH, "-- Disable triggers\n");
    ahprintf(AH, "UPDATE \"pg_class\" SET \"reltriggers\" = 0 WHERE \"relname\" !~ '^pg_';\n\n");
}

static void _enableTriggers(ArchiveHandle *AH, TocEntry *te, RestoreOptions *ropt)
{
    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");
}


/*
297
 * This is a routine that is part of the dumper interface, hence the 'Archive*' parameter.
B
Bruce Momjian 已提交
298 299 300 301 302 303 304
 */

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

305 306 307 308
	if (!AH->currToc)
		die_horribly(AH, "%s: WriteData can not be called outside the context of "
						"a DataDumper routine\n", progname);

B
Bruce Momjian 已提交
309 310 311 312 313 314 315 316 317 318 319
    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,
320
			const char* dropStmt, const char* copyStmt, const char* owner,
B
Bruce Momjian 已提交
321 322 323 324 325 326 327 328
			DataDumperPtr dumpFn, void* dumpArg)
{
    ArchiveHandle*	AH = (ArchiveHandle*)AHX;
    TocEntry*		newToc;

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

329
    newToc = (TocEntry*)calloc(1, sizeof(TocEntry));
B
Bruce Momjian 已提交
330
    if (!newToc)
331
	die_horribly(AH, "Archiver: unable to allocate memory for TOC entry\n");
B
Bruce Momjian 已提交
332 333 334 335 336 337 338 339 340 341 342 343 344

    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);
345
	newToc->copyStmt = copyStmt ? strdup(copyStmt) : NULL;
B
Bruce Momjian 已提交
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    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;
367
	char			*fmtName;
B
Bruce Momjian 已提交
368 369 370 371

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

372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
	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";
	}
	ahprintf(AH, ";     Format: %s\n;\n", fmtName);

B
Bruce Momjian 已提交
391 392 393 394 395 396 397 398 399 400 401 402
    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);
}

403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
/***********
 * 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;
	}

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

	StartTransaction(AH);

	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 已提交
476 477 478 479 480 481 482
/***********
 * Sorting and Reordering
 ***********/

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

B
Bruce Momjian 已提交
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 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 577 578 579 580 581 582 583
/* 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)
584
	die_horribly(AH, "%s: could not open TOC file\n", progname);
B
Bruce Momjian 已提交
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604

    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)
	{
605
	    fprintf(stderr, "%s: WARNING - line ignored: %s\n", progname, buf);
B
Bruce Momjian 已提交
606 607 608 609 610 611
	    continue;
	}

	/* Find TOC entry */
	te = _getTocEntry(AH, id);
	if (!te) 
612
	    die_horribly(AH, "%s: could not find entry for id %d\n",progname, id);
B
Bruce Momjian 已提交
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

	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;
643
    int		bSize = strlen(fmt) + 256;
B
Bruce Momjian 已提交
644 645 646
    int		cnt = -1;

    va_start(ap, fmt);
647 648 649 650

    /* 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 已提交
651 652 653 654 655
	if (p != NULL) free(p);
	bSize *= 2;
	if ((p = malloc(bSize)) == NULL)
	{
	    va_end(ap);
656
	    exit_horribly(AH, "%s: could not allocate buffer for archprintf\n", progname);
B
Bruce Momjian 已提交
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
	}
	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;
674
#ifdef HAVE_LIBZ
B
Bruce Momjian 已提交
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
    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 */
695
#ifdef HAVE_LIBZ
B
Bruce Momjian 已提交
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
    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;
713
#ifdef HAVE_LIBZ
B
Bruce Momjian 已提交
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
    }
#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;
740
    int		bSize = strlen(fmt) + 256; /* Should be enough */
B
Bruce Momjian 已提交
741 742 743
    int		cnt = -1;

    va_start(ap, fmt);
744 745 746
    /* 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) ) {
747 748 749 750 751 752 753 754 755
		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 已提交
756 757 758 759 760 761 762
    }
    va_end(ap);
    ahwrite(p, 1, cnt, AH);
    free(p);
    return cnt;
}

763 764 765 766 767 768 769 770 771 772 773 774
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);
}

B
Bruce Momjian 已提交
775
/*
776 777 778 779
 *  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 已提交
780 781 782
 */
int ahwrite(const void *ptr, size_t size, size_t nmemb, ArchiveHandle* AH)
{
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
	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.
		 */	
		if (AH->ropt && AH->ropt->useDB && AH->connection)
			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);

    exit(1);
B
Bruce Momjian 已提交
818 819
}

820 821 822 823 824 825 826 827
/* 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 已提交
828

829 830
/* Archiver use (just different arg declaration) */
void die_horribly(ArchiveHandle *AH, const char *fmt, ...)
B
Bruce Momjian 已提交
831 832 833 834
{
    va_list 	ap;

    va_start(ap, fmt);
835
    _die_horribly(AH, fmt, ap);
B
Bruce Momjian 已提交
836 837
}

838

B
Bruce Momjian 已提交
839 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 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
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);
904
		i = -i;
B
Bruce Momjian 已提交
905
    } else {
906
		(*AH->WriteBytePtr)(AH, 0);
B
Bruce Momjian 已提交
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
    }
    
    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 */
922
	int bitShift = 0;
B
Bruce Momjian 已提交
923 924

    if (AH->version > K_VERS_1_0)
925 926
		/* Read a sign byte */
		sign = (*AH->ReadBytePtr)(AH);
B
Bruce Momjian 已提交
927 928

    for( b = 0 ; b < AH->intSize ; b++) {
929 930 931 932
        bv = (*AH->ReadBytePtr)(AH) & 0xFF;
		if (bv != 0)
			res = res + (bv << bitShift);
		bitShift += 8;
B
Bruce Momjian 已提交
933 934 935
    }

    if (sign)
936
		res = - res;
B
Bruce Momjian 已提交
937 938 939 940 941 942

    return res;
}

int	WriteStr(ArchiveHandle* AH, char* c)
{
943 944 945 946 947 948 949 950 951 952 953
    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 已提交
954 955 956 957 958 959 960 961
}

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

    l = ReadInt(AH);
962 963 964 965 966 967 968 969 970 971 972
	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 已提交
973 974 975 976 977 978 979 980 981 982 983

    return buf;
}

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

984 985 986 987 988 989 990 991 992 993 994
	/*
	 * 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;
995

B
Bruce Momjian 已提交
996
    if (AH->fSpec) {
997 998
		wantClose = 1;
		fh = fopen(AH->fSpec, PG_BINARY_R);
B
Bruce Momjian 已提交
999
    } else {
1000
		fh = stdin;
B
Bruce Momjian 已提交
1001 1002 1003
    }

    if (!fh)
1004
		die_horribly(AH, "Archiver: could not open input file\n");
B
Bruce Momjian 已提交
1005 1006 1007

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

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

1011 1012 1013
	/* Save it, just in case we need it later*/
	strncpy(&AH->lookahead[0], sig, 5);
	AH->lookaheadLen = 5;
B
Bruce Momjian 已提交
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 1040 1041 1042 1043 1044 1045 1046 1047
    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 已提交
1048

1049 1050 1051
		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 已提交
1052

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

1056 1057
		AH->format = archTar;
	}
B
Bruce Momjian 已提交
1058 1059 1060

    /* If we can't seek, then mark the header as read */
    if (fseek(fh, 0, SEEK_SET) != 0) 
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
	{
		/*
		 * 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 已提交
1073 1074 1075

    /* Close the file */
    if (wantClose)
1076
		fclose(fh);
B
Bruce Momjian 已提交
1077 1078 1079 1080 1081 1082 1083 1084

    return AH->format;
}


/*
 * Allocate an archive handle
 */
1085 1086 1087
static ArchiveHandle* _allocAH(const char* FileSpec, const ArchiveFormat fmt, 
				const int compression, ArchiveMode mode) 
{
B
Bruce Momjian 已提交
1088 1089
    ArchiveHandle*	AH;

1090 1091 1092 1093
	/*
	 *fprintf(stderr, "%s: allocating AH for %s, format %d\n", progname, FileSpec, fmt); 
	 */

1094
    AH = (ArchiveHandle*)calloc(1, sizeof(ArchiveHandle));
B
Bruce Momjian 已提交
1095
    if (!AH) 
1096
		die_horribly(AH, "Archiver: Could not allocate archive handle\n");
B
Bruce Momjian 已提交
1097 1098 1099 1100

    AH->vmaj = K_VERS_MAJOR;
    AH->vmin = K_VERS_MINOR;

1101 1102
	AH->createDate = time(NULL);

B
Bruce Momjian 已提交
1103 1104 1105
    AH->intSize = sizeof(int);
    AH->lastID = 0;
    if (FileSpec) {
1106 1107 1108 1109 1110 1111 1112 1113
		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 已提交
1114
    } else {
1115 1116
		AH->fSpec = NULL;
    } 
B
Bruce Momjian 已提交
1117 1118 1119

    AH->currUser = "";

1120
    AH->toc = (TocEntry*)calloc(1, sizeof(TocEntry));
B
Bruce Momjian 已提交
1121
    if (!AH->toc)
1122
		die_horribly(AH, "Archiver: Could not allocate TOC header\n");
B
Bruce Momjian 已提交
1123 1124 1125 1126 1127 1128 1129

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

1130 1131
	AH->pgCopyBuf = createPQExpBuffer();
	AH->sqlBuf = createPQExpBuffer();
B
Bruce Momjian 已提交
1132 1133 1134 1135 1136

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

1137 1138 1139 1140
	/*
	 *fprintf(stderr, "%s: archive format is %d\n", progname, fmt);
	 */

B
Bruce Momjian 已提交
1141
    if (fmt == archUnknown)
1142 1143 1144
		AH->format = _discoverArchiveFormat(AH);
	else
		AH->format = fmt;
B
Bruce Momjian 已提交
1145

1146
    switch (AH->format) {
B
Bruce Momjian 已提交
1147

1148 1149 1150
		case archCustom:
			InitArchiveFmt_Custom(AH);
			break;
B
Bruce Momjian 已提交
1151

1152 1153 1154
		case archFiles:
			InitArchiveFmt_Files(AH);
			break;
B
Bruce Momjian 已提交
1155

1156 1157 1158
		case archNull:
			InitArchiveFmt_Null(AH);
			break;
B
Bruce Momjian 已提交
1159

1160 1161 1162 1163 1164 1165
		case archTar:
			InitArchiveFmt_Tar(AH);
			break;

		default:
			die_horribly(AH, "Archiver: Unrecognized file format '%d'\n", fmt);
B
Bruce Momjian 已提交
1166 1167 1168 1169 1170 1171 1172 1173 1174
    }

    return AH;
}


void WriteDataChunks(ArchiveHandle* AH)
{
    TocEntry		*te = AH->toc->next;
1175 1176
	StartDataPtr	startPtr;
	EndDataPtr		endPtr;
B
Bruce Momjian 已提交
1177 1178 1179 1180 1181

    while (te != AH->toc) {
	if (te->dataDumper != NULL) {
	    AH->currToc = te;
	    /* printf("Writing data for %d (%x)\n", te->id, te); */
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193

		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 已提交
1194 1195 1196 1197 1198 1199 1200 1201
	    }

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

1202 1203
	    if (endPtr != NULL) {
			(*endPtr)(AH, te);
B
Bruce Momjian 已提交
1204 1205 1206
	    }
	    AH->currToc = NULL;
	}
1207
		te = te->next;
B
Bruce Momjian 已提交
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
    }
}

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);
1226
	WriteStr(AH, te->copyStmt);
B
Bruce Momjian 已提交
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
	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++) {

1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
		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 已提交
1275 1276 1277 1278 1279
    }
}

static int _tocEntryRequired(TocEntry* te, RestoreOptions *ropt)
{
1280 1281
    int res = 3; /* Schema = 1, Data = 2, Both = 3 */
 
B
Bruce Momjian 已提交
1282 1283
    /* If it's an ACL, maybe ignore it */
    if (ropt->aclsSkip && strcmp(te->desc,"ACL") == 0)
1284
		return 0;
B
Bruce Momjian 已提交
1285 1286 1287 1288

    /* Check if tablename only is wanted */
    if (ropt->selTypes)
    {
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
		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 已提交
1313 1314 1315 1316
	}

    /* Mask it if we only want schema */
    if (ropt->schemaOnly)
1317
		res = res & 1;
B
Bruce Momjian 已提交
1318 1319 1320 1321 1322 1323 1324

    /* 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) 
1325
		res = res & 2;
B
Bruce Momjian 已提交
1326 1327 1328

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

    /* Finally, if we used a list, limit based on that as well */
    if (ropt->limitToList && !ropt->idWanted[te->id - 1]) 
1333
		return 0;
B
Bruce Momjian 已提交
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347

    return res;
}

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) {
	(*AH->PrintExtraTocPtr)(AH, te);
    }
    ahprintf(AH, "--\n\n");

    if (te->owner && strlen(te->owner) != 0 && strcmp(AH->currUser, te->owner) != 0) {
1348 1349 1350
		//todo pjw - fix for db connection...
		//ahprintf(AH, "\\connect - %s\n", te->owner);
		AH->currUser = te->owner;
B
Bruce Momjian 已提交
1351 1352 1353 1354 1355 1356 1357 1358 1359
    }

    ahprintf(AH, "%s\n", te->defn);

    return 1;
}

void WriteHead(ArchiveHandle* AH) 
{
1360 1361
	struct tm		crtm;

B
Bruce Momjian 已提交
1362 1363 1364 1365 1366 1367 1368
    (*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);

1369
#ifndef HAVE_LIBZ
B
Bruce Momjian 已提交
1370 1371 1372 1373 1374 1375
    if (AH->compression != 0)
	fprintf(stderr, "%s: WARNING - requested compression not available in this installation - "
		    "archive will be uncompressed \n", progname);

    AH->compression = 0;

1376
#endif
B
Bruce Momjian 已提交
1377

1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
	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 已提交
1389 1390 1391 1392
}

void ReadHead(ArchiveHandle* AH)
{
1393 1394 1395
    char		tmpMag[7];
    int			fmt;
	struct tm	crtm;
B
Bruce Momjian 已提交
1396

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

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

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

1405 1406
		AH->vmaj = (*AH->ReadBytePtr)(AH);
		AH->vmin = (*AH->ReadBytePtr)(AH);
B
Bruce Momjian 已提交
1407

1408 1409 1410 1411 1412 1413
		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 已提交
1414

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


1418 1419 1420
		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 已提交
1421

1422 1423 1424
		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 已提交
1425

1426 1427 1428
		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 已提交
1429

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

1432 1433 1434
		if (AH->format != fmt)
			die_horribly(AH, "%s: expected format (%d) differs from format found in file (%d)\n", 
					progname, AH->format, fmt);
1435
    }
B
Bruce Momjian 已提交
1436 1437 1438

    if (AH->version >= K_VERS_1_2)
    {
1439 1440 1441 1442
		if (AH->version < K_VERS_1_4)
			AH->compression = (*AH->ReadBytePtr)(AH);
		else
			AH->compression = ReadInt(AH);
B
Bruce Momjian 已提交
1443
    } else {
1444
		AH->compression = Z_DEFAULT_COMPRESSION;
B
Bruce Momjian 已提交
1445 1446
    }

1447 1448
#ifndef HAVE_LIBZ
    if (AH->compression != 0)
1449 1450
		fprintf(stderr, "%s: WARNING - archive is compressed - any data will not be available\n", 
					progname);
B
Bruce Momjian 已提交
1451 1452
#endif

1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
	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 已提交
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
}


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

1548 1549 1550 1551 1552 1553 1554 1555
/*
 * 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 已提交
1556