common.c 24.7 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * common.c
4
 *	  common routines between pg_dump and pg4_dump
5
 *
6 7 8
 * Since pg4_dump is long-dead code, there is no longer any useful distinction
 * between this file and pg_dump.c.
 *
B
Bruce Momjian 已提交
9
 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
10
 * Portions Copyright (c) 1994, Regents of the University of California
11 12 13
 *
 *
 * IDENTIFICATION
14
 *	  src/bin/pg_dump/common.c
15
 *
16 17
 *-------------------------------------------------------------------------
 */
18
#include "postgres_fe.h"
19

20 21
#include <ctype.h>

22
#include "catalog/pg_class.h"
23

24
#include "pg_backup_archiver.h"
25

26 27 28 29 30 31 32 33

/*
 * Variables for mapping DumpId to DumpableObject
 */
static DumpableObject **dumpIdMap = NULL;
static int	allocedDumpIds = 0;
static DumpId lastDumpId = 0;

34 35 36 37 38 39 40
/*
 * Variables for mapping CatalogId to DumpableObject
 */
static bool catalogIdMapValid = false;
static DumpableObject **catalogIdMap = NULL;
static int	numCatalogIds = 0;

41 42
/*
 * These variables are static to avoid the notational cruft of having to pass
B
Bruce Momjian 已提交
43
 * them into findTableByOid() and friends.	For each of these arrays, we
44 45 46 47
 * build a sorted-by-OID index array immediately after it's built, and then
 * we use binary search in findTableByOid() and friends.  (qsort'ing the base
 * arrays themselves would be simpler, but it doesn't work because pg_dump.c
 * may have already established pointers between items.)
48
 */
B
Bruce Momjian 已提交
49 50 51 52 53 54 55 56
static TableInfo *tblinfo;
static TypeInfo *typinfo;
static FuncInfo *funinfo;
static OprInfo *oprinfo;
static int	numTables;
static int	numTypes;
static int	numFuncs;
static int	numOperators;
57
static int	numCollations;
58 59 60 61
static DumpableObject **tblinfoindex;
static DumpableObject **typinfoindex;
static DumpableObject **funinfoindex;
static DumpableObject **oprinfoindex;
62
static DumpableObject **collinfoindex;
63 64


65
static void flagInhTables(TableInfo *tbinfo, int numTables,
B
Bruce Momjian 已提交
66
			  InhInfo *inhinfo, int numInherits);
67
static void flagInhAttrs(TableInfo *tblinfo, int numTables);
68
static DumpableObject **buildIndexArray(void *objArray, int numObjs,
B
Bruce Momjian 已提交
69
				Size objSize);
70 71
static int	DOCatalogIdCompare(const void *p1, const void *p2);
static void findParentsByOid(TableInfo *self,
B
Bruce Momjian 已提交
72
				 InhInfo *inhinfo, int numInherits);
73
static int	strInArray(const char *pattern, char **arr, int arr_size);
74

75 76

/*
77 78
 * getSchemaData
 *	  Collect information about all potentially dumpable objects
79
 */
80
TableInfo *
81
getSchemaData(int *numTablesPtr)
82
{
83
	ExtensionInfo *extinfo;
84
	InhInfo    *inhinfo;
P
Peter Eisentraut 已提交
85
	CollInfo   *collinfo;
86
	int			numNamespaces;
87
	int			numExtensions;
88 89 90 91 92 93
	int			numAggregates;
	int			numInherits;
	int			numRules;
	int			numProcLangs;
	int			numCasts;
	int			numOpclasses;
94
	int			numOpfamilies;
95
	int			numConversions;
96 97 98 99
	int			numTSParsers;
	int			numTSTemplates;
	int			numTSDicts;
	int			numTSConfigs;
100 101
	int			numForeignDataWrappers;
	int			numForeignServers;
102
	int			numDefaultACLs;
103 104

	if (g_verbose)
105
		write_msg(NULL, "reading schemas\n");
106
	getNamespaces(&numNamespaces);
107

108 109 110 111 112 113 114 115 116 117 118
	/*
	 * getTables should be done as soon as possible, so as to minimize the
	 * window between starting our transaction and acquiring per-table locks.
	 * However, we have to do getNamespaces first because the tables get
	 * linked to their containing namespaces during getTables.
	 */
	if (g_verbose)
		write_msg(NULL, "reading user-defined tables\n");
	tblinfo = getTables(&numTables);
	tblinfoindex = buildIndexArray(tblinfo, numTables, sizeof(TableInfo));

119 120 121 122
	if (g_verbose)
		write_msg(NULL, "reading extensions\n");
	extinfo = getExtensions(&numExtensions);

123 124
	if (g_verbose)
		write_msg(NULL, "reading user-defined functions\n");
125
	funinfo = getFuncs(&numFuncs);
126
	funinfoindex = buildIndexArray(funinfo, numFuncs, sizeof(FuncInfo));
127 128

	/* this must be after getFuncs */
129
	if (g_verbose)
130
		write_msg(NULL, "reading user-defined types\n");
131
	typinfo = getTypes(&numTypes);
132
	typinfoindex = buildIndexArray(typinfo, numTypes, sizeof(TypeInfo));
133

134
	/* this must be after getFuncs, too */
135
	if (g_verbose)
136
		write_msg(NULL, "reading procedural languages\n");
137
	getProcLangs(&numProcLangs);
138 139

	if (g_verbose)
140
		write_msg(NULL, "reading user-defined aggregate functions\n");
141
	getAggregates(&numAggregates);
142 143

	if (g_verbose)
144
		write_msg(NULL, "reading user-defined operators\n");
145
	oprinfo = getOperators(&numOperators);
146
	oprinfoindex = buildIndexArray(oprinfo, numOperators, sizeof(OprInfo));
147

148 149
	if (g_verbose)
		write_msg(NULL, "reading user-defined operator classes\n");
150
	getOpclasses(&numOpclasses);
151

152 153
	if (g_verbose)
		write_msg(NULL, "reading user-defined operator families\n");
154
	getOpfamilies(&numOpfamilies);
155

156 157
	if (g_verbose)
		write_msg(NULL, "reading user-defined text search parsers\n");
158
	getTSParsers(&numTSParsers);
159 160 161

	if (g_verbose)
		write_msg(NULL, "reading user-defined text search templates\n");
162
	getTSTemplates(&numTSTemplates);
163 164 165

	if (g_verbose)
		write_msg(NULL, "reading user-defined text search dictionaries\n");
166
	getTSDictionaries(&numTSDicts);
167 168 169

	if (g_verbose)
		write_msg(NULL, "reading user-defined text search configurations\n");
170
	getTSConfigurations(&numTSConfigs);
171

172 173
	if (g_verbose)
		write_msg(NULL, "reading user-defined foreign-data wrappers\n");
174
	getForeignDataWrappers(&numForeignDataWrappers);
175 176 177

	if (g_verbose)
		write_msg(NULL, "reading user-defined foreign servers\n");
178
	getForeignServers(&numForeignServers);
179

180 181
	if (g_verbose)
		write_msg(NULL, "reading default privileges\n");
182
	getDefaultACLs(&numDefaultACLs);
183

P
Peter Eisentraut 已提交
184 185 186
	if (g_verbose)
		write_msg(NULL, "reading user-defined collations\n");
	collinfo = getCollations(&numCollations);
187
	collinfoindex = buildIndexArray(collinfo, numCollations, sizeof(CollInfo));
P
Peter Eisentraut 已提交
188

189 190
	if (g_verbose)
		write_msg(NULL, "reading user-defined conversions\n");
191
	getConversions(&numConversions);
192

193 194
	if (g_verbose)
		write_msg(NULL, "reading type casts\n");
195
	getCasts(&numCasts);
196

197
	if (g_verbose)
198
		write_msg(NULL, "reading table inheritance information\n");
199 200
	inhinfo = getInherits(&numInherits);

201 202
	if (g_verbose)
		write_msg(NULL, "reading rewrite rules\n");
203
	getRules(&numRules);
204

205 206 207 208 209
	/*
	 * Identify extension member objects and mark them as not to be dumped.
	 * This must happen after reading all objects that can be direct members
	 * of extensions, but before we begin to process table subsidiary objects.
	 */
210
	if (g_verbose)
211 212
		write_msg(NULL, "finding extension members\n");
	getExtensionMembership(extinfo, numExtensions);
213

214
	/* Link tables to parents, mark parents of target tables interesting */
215
	if (g_verbose)
216 217 218 219 220
		write_msg(NULL, "finding inheritance relationships\n");
	flagInhTables(tblinfo, numTables, inhinfo, numInherits);

	if (g_verbose)
		write_msg(NULL, "reading column info for interesting tables\n");
221 222 223
	getTableAttrs(tblinfo, numTables);

	if (g_verbose)
224
		write_msg(NULL, "flagging inherited columns in subtables\n");
225
	flagInhAttrs(tblinfo, numTables);
226

B
Bruce Momjian 已提交
227
	if (g_verbose)
228 229
		write_msg(NULL, "reading indexes\n");
	getIndexes(tblinfo, numTables);
230

231 232 233
	if (g_verbose)
		write_msg(NULL, "reading constraints\n");
	getConstraints(tblinfo, numTables);
234

235 236 237
	if (g_verbose)
		write_msg(NULL, "reading triggers\n");
	getTriggers(tblinfo, numTables);
238

239
	*numTablesPtr = numTables;
240
	return tblinfo;
241 242
}

243
/* flagInhTables -
244
 *	 Fill in parent link fields of every target table, and mark
245
 *	 parents of target tables as interesting
246
 *
247 248 249
 * Note that only direct ancestors of targets are marked interesting.
 * This is sufficient; we don't much care whether they inherited their
 * attributes or not.
250 251
 *
 * modifies tblinfo
252 253 254 255 256 257 258 259
 */
static void
flagInhTables(TableInfo *tblinfo, int numTables,
			  InhInfo *inhinfo, int numInherits)
{
	int			i,
				j;
	int			numParents;
260
	TableInfo **parents;
261 262 263

	for (i = 0; i < numTables; i++)
	{
264
		/* Sequences and views never have parents */
265
		if (tblinfo[i].relkind == RELKIND_SEQUENCE ||
266
			tblinfo[i].relkind == RELKIND_VIEW)
267 268 269
			continue;

		/* Don't bother computing anything for non-target tables, either */
270
		if (!tblinfo[i].dobj.dump)
271 272 273
			continue;

		/* Find all the immediate parent tables */
274
		findParentsByOid(&tblinfo[i], inhinfo, numInherits);
275 276

		/* Mark the parents as interesting for getTableAttrs */
277 278
		numParents = tblinfo[i].numParents;
		parents = tblinfo[i].parents;
279
		for (j = 0; j < numParents; j++)
280
			parents[j]->interesting = true;
281 282 283 284 285 286
	}
}

/* flagInhAttrs -
 *	 for each dumpable table in tblinfo, flag its inherited attributes
 * so when we dump the table out, we don't dump out the inherited attributes
287
 *
288
 * modifies tblinfo
289
 */
290
static void
291
flagInhAttrs(TableInfo *tblinfo, int numTables)
292
{
293 294 295
	int			i,
				j,
				k;
296

297
	for (i = 0; i < numTables; i++)
298
	{
299 300 301 302 303
		TableInfo  *tbinfo = &(tblinfo[i]);
		int			numParents;
		TableInfo **parents;
		TableInfo  *parent;

304
		/* Sequences and views never have parents */
305 306
		if (tbinfo->relkind == RELKIND_SEQUENCE ||
			tbinfo->relkind == RELKIND_VIEW)
307 308 309
			continue;

		/* Don't bother computing anything for non-target tables, either */
310
		if (!tbinfo->dobj.dump)
311 312
			continue;

313 314
		numParents = tbinfo->numParents;
		parents = tbinfo->parents;
315 316 317

		if (numParents == 0)
			continue;			/* nothing to see here, move along */
318

319
		/*----------------------------------------------------------------
320 321 322
		 * For each attr, check the parent info: if no parent has an attr
		 * with the same name, then it's not inherited. If there *is* an
		 * attr with the same name, then only dump it if:
323
		 *
324
		 * - it is NOT NULL and zero parents are NOT NULL
B
Bruce Momjian 已提交
325
		 *	 OR
326
		 * - it has a default value AND the default value does not match
B
Bruce Momjian 已提交
327
		 *	 all parent default values, or no parents specify a default.
328 329
		 *
		 * See discussion on -hackers around 2-Apr-2001.
330
		 *----------------------------------------------------------------
331
		 */
332
		for (j = 0; j < tbinfo->numatts; j++)
333
		{
334 335 336 337 338 339
			bool		foundAttr;		/* Attr was found in a parent */
			bool		foundNotNull;	/* Attr was NOT NULL in a parent */
			bool		defaultsMatch;	/* All non-empty defaults match */
			bool		defaultsFound;	/* Found a default in a parent */
			AttrDefInfo *attrDef;

340 341 342 343 344
			foundAttr = false;
			foundNotNull = false;
			defaultsMatch = true;
			defaultsFound = false;

345
			attrDef = tbinfo->attrdefs[j];
346

347
			for (k = 0; k < numParents; k++)
348
			{
349 350 351 352 353 354
				int			inhAttrInd;

				parent = parents[k];
				inhAttrInd = strInArray(tbinfo->attnames[j],
										parent->attnames,
										parent->numatts);
355 356 357

				if (inhAttrInd != -1)
				{
358 359
					AttrDefInfo *inhDef = parent->attrdefs[inhAttrInd];

360
					foundAttr = true;
361
					foundNotNull |= parent->notnull[inhAttrInd];
362
					if (inhDef != NULL)
363
					{
364
						defaultsFound = true;
B
Bruce Momjian 已提交
365

366 367
						/*
						 * If any parent has a default and the child doesn't,
B
Bruce Momjian 已提交
368 369
						 * we have to emit an explicit DEFAULT NULL clause for
						 * the child, else the parent's default will win.
370 371 372 373 374 375 376 377 378 379 380 381 382 383
						 */
						if (attrDef == NULL)
						{
							attrDef = (AttrDefInfo *) malloc(sizeof(AttrDefInfo));
							attrDef->dobj.objType = DO_ATTRDEF;
							attrDef->dobj.catId.tableoid = 0;
							attrDef->dobj.catId.oid = 0;
							AssignDumpId(&attrDef->dobj);
							attrDef->adtable = tbinfo;
							attrDef->adnum = j + 1;
							attrDef->adef_expr = strdup("NULL");

							attrDef->dobj.name = strdup(tbinfo->dobj.name);
							attrDef->dobj.namespace = tbinfo->dobj.namespace;
384

385 386 387 388 389 390 391 392 393
							attrDef->dobj.dump = tbinfo->dobj.dump;

							attrDef->separate = false;
							addObjectDependency(&tbinfo->dobj,
												attrDef->dobj.dumpId);

							tbinfo->attrdefs[j] = attrDef;
						}
						if (strcmp(attrDef->adef_expr, inhDef->adef_expr) != 0)
394
						{
395
							defaultsMatch = false;
B
Bruce Momjian 已提交
396

397 398 399 400 401 402 403 404 405 406
							/*
							 * Whenever there is a non-matching parent
							 * default, add a dependency to force the parent
							 * default to be dumped first, in case the
							 * defaults end up being dumped as separate
							 * commands.  Otherwise the parent default will
							 * override the child's when it is applied.
							 */
							addObjectDependency(&attrDef->dobj,
												inhDef->dobj.dumpId);
407 408 409 410
						}
					}
				}
			}
411

412
			/*
B
Bruce Momjian 已提交
413 414
			 * Based on the scan of the parents, decide if we can rely on the
			 * inherited attr
415
			 */
416
			if (foundAttr)		/* Attr was inherited */
417
			{
418
				/* Set inherited flag by default */
419 420 421
				tbinfo->inhAttrs[j] = true;
				tbinfo->inhAttrDef[j] = true;
				tbinfo->inhNotNull[j] = true;
422

423 424 425 426 427
				/*
				 * Clear it if attr had a default, but parents did not, or
				 * mismatch
				 */
				if ((attrDef != NULL) && (!defaultsFound || !defaultsMatch))
428
				{
429 430
					tbinfo->inhAttrs[j] = false;
					tbinfo->inhAttrDef[j] = false;
431 432
				}

433
				/*
B
Bruce Momjian 已提交
434
				 * Clear it if NOT NULL and none of the parents were NOT NULL
435
				 */
436
				if (tbinfo->notnull[j] && !foundNotNull)
437
				{
438 439
					tbinfo->inhAttrs[j] = false;
					tbinfo->inhNotNull[j] = false;
440
				}
441 442

				/* Clear it if attr has local definition */
443 444 445 446
				if (tbinfo->attislocal[j])
					tbinfo->inhAttrs[j] = false;
			}
		}
447 448 449
	}
}

450 451 452 453 454
/*
 * AssignDumpId
 *		Given a newly-created dumpable object, assign a dump ID,
 *		and enter the object into the lookup table.
 *
455
 * The caller is expected to have filled in objType and catId,
456 457 458 459 460 461
 * but not any of the other standard fields of a DumpableObject.
 */
void
AssignDumpId(DumpableObject *dobj)
{
	dobj->dumpId = ++lastDumpId;
462 463
	dobj->name = NULL;			/* must be set later */
	dobj->namespace = NULL;		/* may be set later */
464
	dobj->dump = true;			/* default assumption */
T
Tom Lane 已提交
465
	dobj->ext_member = false;	/* default assumption */
466 467 468 469 470 471
	dobj->dependencies = NULL;
	dobj->nDeps = 0;
	dobj->allocDeps = 0;

	while (dobj->dumpId >= allocedDumpIds)
	{
B
Bruce Momjian 已提交
472
		int			newAlloc;
473 474 475 476 477

		if (allocedDumpIds <= 0)
		{
			newAlloc = 256;
			dumpIdMap = (DumpableObject **)
478
				pg_malloc(newAlloc * sizeof(DumpableObject *));
479 480 481 482 483
		}
		else
		{
			newAlloc = allocedDumpIds * 2;
			dumpIdMap = (DumpableObject **)
484
				pg_realloc(dumpIdMap, newAlloc * sizeof(DumpableObject *));
485 486 487 488 489 490
		}
		memset(dumpIdMap + allocedDumpIds, 0,
			   (newAlloc - allocedDumpIds) * sizeof(DumpableObject *));
		allocedDumpIds = newAlloc;
	}
	dumpIdMap[dobj->dumpId] = dobj;
491 492 493

	/* mark catalogIdMap invalid, but don't rebuild it yet */
	catalogIdMapValid = false;
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
 * Assign a DumpId that's not tied to a DumpableObject.
 *
 * This is used when creating a "fixed" ArchiveEntry that doesn't need to
 * participate in the sorting logic.
 */
DumpId
createDumpId(void)
{
	return ++lastDumpId;
}

/*
 * Return the largest DumpId so far assigned
 */
DumpId
getMaxDumpId(void)
{
	return lastDumpId;
}

/*
 * Find a DumpableObject by dump ID
 *
 * Returns NULL for invalid ID
 */
DumpableObject *
findObjectByDumpId(DumpId dumpId)
{
	if (dumpId <= 0 || dumpId >= allocedDumpIds)
		return NULL;			/* out of range? */
	return dumpIdMap[dumpId];
}

/*
 * Find a DumpableObject by catalog ID
 *
 * Returns NULL for unknown ID
534
 *
535
 * We use binary search in a sorted list that is built on first call.
536
 * If AssignDumpId() and findObjectByCatalogId() calls were freely intermixed,
B
Bruce Momjian 已提交
537
 * the code would work, but possibly be very slow.	In the current usage
538
 * pattern that does not happen, indeed we build the list at most twice.
539
 */
540 541 542
DumpableObject *
findObjectByCatalogId(CatalogId catalogId)
{
543 544
	DumpableObject **low;
	DumpableObject **high;
545

546
	if (!catalogIdMapValid)
547
	{
548 549 550 551 552 553 554 555
		if (catalogIdMap)
			free(catalogIdMap);
		getDumpableObjects(&catalogIdMap, &numCatalogIds);
		if (numCatalogIds > 1)
			qsort((void *) catalogIdMap, numCatalogIds,
				  sizeof(DumpableObject *), DOCatalogIdCompare);
		catalogIdMapValid = true;
	}
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
	/*
	 * We could use bsearch() here, but the notational cruft of calling
	 * bsearch is nearly as bad as doing it ourselves; and the generalized
	 * bsearch function is noticeably slower as well.
	 */
	if (numCatalogIds <= 0)
		return NULL;
	low = catalogIdMap;
	high = catalogIdMap + (numCatalogIds - 1);
	while (low <= high)
	{
		DumpableObject **middle;
		int			difference;

		middle = low + (high - low) / 2;
		/* comparison must match DOCatalogIdCompare, below */
		difference = oidcmp((*middle)->catId.oid, catalogId.oid);
		if (difference == 0)
			difference = oidcmp((*middle)->catId.tableoid, catalogId.tableoid);
		if (difference == 0)
			return *middle;
		else if (difference < 0)
			low = middle + 1;
		else
			high = middle - 1;
582 583 584 585
	}
	return NULL;
}

586 587 588 589 590 591 592 593 594 595 596 597
/*
 * Find a DumpableObject by OID, in a pre-sorted array of one type of object
 *
 * Returns NULL for unknown OID
 */
static DumpableObject *
findObjectByOid(Oid oid, DumpableObject **indexArray, int numObjs)
{
	DumpableObject **low;
	DumpableObject **high;

	/*
B
Bruce Momjian 已提交
598 599
	 * This is the same as findObjectByCatalogId except we assume we need not
	 * look at table OID because the objects are all the same type.
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
	 *
	 * We could use bsearch() here, but the notational cruft of calling
	 * bsearch is nearly as bad as doing it ourselves; and the generalized
	 * bsearch function is noticeably slower as well.
	 */
	if (numObjs <= 0)
		return NULL;
	low = indexArray;
	high = indexArray + (numObjs - 1);
	while (low <= high)
	{
		DumpableObject **middle;
		int			difference;

		middle = low + (high - low) / 2;
		difference = oidcmp((*middle)->catId.oid, oid);
		if (difference == 0)
			return *middle;
		else if (difference < 0)
			low = middle + 1;
		else
			high = middle - 1;
	}
	return NULL;
}

/*
 * Build an index array of DumpableObject pointers, sorted by OID
 */
static DumpableObject **
buildIndexArray(void *objArray, int numObjs, Size objSize)
{
	DumpableObject **ptrs;
B
Bruce Momjian 已提交
633
	int			i;
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649

	ptrs = (DumpableObject **) malloc(numObjs * sizeof(DumpableObject *));
	for (i = 0; i < numObjs; i++)
		ptrs[i] = (DumpableObject *) ((char *) objArray + i * objSize);

	/* We can use DOCatalogIdCompare to sort since its first key is OID */
	if (numObjs > 1)
		qsort((void *) ptrs, numObjs, sizeof(DumpableObject *),
			  DOCatalogIdCompare);

	return ptrs;
}

/*
 * qsort comparator for pointers to DumpableObjects
 */
650 651 652
static int
DOCatalogIdCompare(const void *p1, const void *p2)
{
653 654
	const DumpableObject *obj1 = *(DumpableObject * const *) p1;
	const DumpableObject *obj2 = *(DumpableObject * const *) p2;
655 656 657
	int			cmpval;

	/*
B
Bruce Momjian 已提交
658 659
	 * Compare OID first since it's usually unique, whereas there will only be
	 * a few distinct values of tableoid.
660 661 662 663 664 665 666
	 */
	cmpval = oidcmp(obj1->catId.oid, obj2->catId.oid);
	if (cmpval == 0)
		cmpval = oidcmp(obj1->catId.tableoid, obj2->catId.tableoid);
	return cmpval;
}

667 668 669 670 671 672 673 674 675 676 677 678
/*
 * Build an array of pointers to all known dumpable objects
 *
 * This simply creates a modifiable copy of the internal map.
 */
void
getDumpableObjects(DumpableObject ***objs, int *numObjs)
{
	int			i,
				j;

	*objs = (DumpableObject **)
679
		pg_malloc(allocedDumpIds * sizeof(DumpableObject *));
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
	j = 0;
	for (i = 1; i < allocedDumpIds; i++)
	{
		if (dumpIdMap[i])
			(*objs)[j++] = dumpIdMap[i];
	}
	*numObjs = j;
}

/*
 * Add a dependency link to a DumpableObject
 *
 * Note: duplicate dependencies are currently not eliminated
 */
void
addObjectDependency(DumpableObject *dobj, DumpId refId)
{
	if (dobj->nDeps >= dobj->allocDeps)
	{
		if (dobj->allocDeps <= 0)
		{
			dobj->allocDeps = 16;
			dobj->dependencies = (DumpId *)
703
				pg_malloc(dobj->allocDeps * sizeof(DumpId));
704 705 706 707 708
		}
		else
		{
			dobj->allocDeps *= 2;
			dobj->dependencies = (DumpId *)
709 710
				pg_realloc(dobj->dependencies,
						   dobj->allocDeps * sizeof(DumpId));
711 712 713 714 715 716 717 718 719 720 721 722
		}
	}
	dobj->dependencies[dobj->nDeps++] = refId;
}

/*
 * Remove a dependency link from a DumpableObject
 *
 * If there are multiple links, all are removed
 */
void
removeObjectDependency(DumpableObject *dobj, DumpId refId)
723
{
724
	int			i;
725
	int			j = 0;
726

727
	for (i = 0; i < dobj->nDeps; i++)
728
	{
729 730
		if (dobj->dependencies[i] != refId)
			dobj->dependencies[j++] = dobj->dependencies[i];
731
	}
732
	dobj->nDeps = j;
733 734
}

735

736
/*
737 738 739
 * findTableByOid
 *	  finds the entry (in tblinfo) of the table with the given oid
 *	  returns NULL if not found
740
 */
741 742
TableInfo *
findTableByOid(Oid oid)
743
{
744
	return (TableInfo *) findObjectByOid(oid, tblinfoindex, numTables);
745 746
}

747
/*
748
 * findTypeByOid
749
 *	  finds the entry (in typinfo) of the type with the given oid
750
 *	  returns NULL if not found
751
 */
752 753
TypeInfo *
findTypeByOid(Oid oid)
754
{
755
	return (TypeInfo *) findObjectByOid(oid, typinfoindex, numTypes);
756 757
}

758
/*
759
 * findFuncByOid
760
 *	  finds the entry (in funinfo) of the function with the given oid
761
 *	  returns NULL if not found
762
 */
763 764
FuncInfo *
findFuncByOid(Oid oid)
765
{
766
	return (FuncInfo *) findObjectByOid(oid, funinfoindex, numFuncs);
767
}
768

769 770 771 772 773 774 775 776
/*
 * findOprByOid
 *	  finds the entry (in oprinfo) of the operator with the given oid
 *	  returns NULL if not found
 */
OprInfo *
findOprByOid(Oid oid)
{
777
	return (OprInfo *) findObjectByOid(oid, oprinfoindex, numOperators);
778 779
}

780 781 782 783 784 785 786 787 788 789 790
/*
 * findCollationByOid
 *	  finds the entry (in collinfo) of the collation with the given oid
 *	  returns NULL if not found
 */
CollInfo *
findCollationByOid(Oid oid)
{
	return (CollInfo *) findObjectByOid(oid, collinfoindex, numCollations);
}

791 792 793

/*
 * findParentsByOid
794
 *	  find a table's parents in tblinfo[]
795 796
 */
static void
797 798
findParentsByOid(TableInfo *self,
				 InhInfo *inhinfo, int numInherits)
799
{
800
	Oid			oid = self->dobj.catId.oid;
801 802 803 804 805 806 807
	int			i,
				j;
	int			numParents;

	numParents = 0;
	for (i = 0; i < numInherits; i++)
	{
808
		if (inhinfo[i].inhrelid == oid)
809 810 811
			numParents++;
	}

812
	self->numParents = numParents;
813 814 815

	if (numParents > 0)
	{
816 817
		self->parents = (TableInfo **)
			pg_malloc(sizeof(TableInfo *) * numParents);
818 819 820
		j = 0;
		for (i = 0; i < numInherits; i++)
		{
821
			if (inhinfo[i].inhrelid == oid)
822
			{
823
				TableInfo  *parent;
824

825 826 827 828 829
				parent = findTableByOid(inhinfo[i].inhparent);
				if (parent == NULL)
				{
					write_msg(NULL, "failed sanity check, parent OID %u of table \"%s\" (OID %u) not found\n",
							  inhinfo[i].inhparent,
830
							  self->dobj.name,
831
							  oid);
832 833
					exit_nicely();
				}
834
				self->parents[j++] = parent;
835 836 837 838
			}
		}
	}
	else
839
		self->parents = NULL;
840 841 842
}

/*
843
 * parseOidArray
844
 *	  parse a string of numbers delimited by spaces into a character array
845 846 847 848
 *
 * Note: actually this is used for both Oids and potentially-signed
 * attribute numbers.  This should cause no trouble, but we could split
 * the function into two functions with different argument types if it does.
849 850 851
 */

void
852
parseOidArray(const char *str, Oid *array, int arraysize)
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
{
	int			j,
				argNum;
	char		temp[100];
	char		s;

	argNum = 0;
	j = 0;
	for (;;)
	{
		s = *str++;
		if (s == ' ' || s == '\0')
		{
			if (j > 0)
			{
				if (argNum >= arraysize)
				{
870
					write_msg(NULL, "could not parse numeric array \"%s\": too many numbers\n", str);
871 872 873
					exit_nicely();
				}
				temp[j] = '\0';
874
				array[argNum++] = atooid(temp);
875 876 877 878 879 880 881 882 883 884
				j = 0;
			}
			if (s == '\0')
				break;
		}
		else
		{
			if (!(isdigit((unsigned char) s) || s == '-') ||
				j >= sizeof(temp) - 1)
			{
885
				write_msg(NULL, "could not parse numeric array \"%s\": invalid character in number\n", str);
886 887 888 889 890 891 892
				exit_nicely();
			}
			temp[j++] = s;
		}
	}

	while (argNum < arraysize)
893
		array[argNum++] = InvalidOid;
894 895 896 897 898 899 900 901 902 903 904 905
}


/*
 * strInArray:
 *	  takes in a string and a string array and the number of elements in the
 * string array.
 *	  returns the index if the string is somewhere in the array, -1 otherwise
 */

static int
strInArray(const char *pattern, char **arr, int arr_size)
906
{
907
	int			i;
908

909
	for (i = 0; i < arr_size; i++)
910
	{
911
		if (strcmp(pattern, arr[i]) == 0)
912 913 914
			return i;
	}
	return -1;
915
}
916 917 918 919 920 921 922


/*
 * Support for simple list operations
 */

void
923
simple_oid_list_append(SimpleOidList *list, Oid val)
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
{
	SimpleOidListCell *cell;

	cell = (SimpleOidListCell *) pg_malloc(sizeof(SimpleOidListCell));
	cell->next = NULL;
	cell->val = val;

	if (list->tail)
		list->tail->next = cell;
	else
		list->head = cell;
	list->tail = cell;
}

void
939
simple_string_list_append(SimpleStringList *list, const char *val)
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
{
	SimpleStringListCell *cell;

	/* this calculation correctly accounts for the null trailing byte */
	cell = (SimpleStringListCell *)
		pg_malloc(sizeof(SimpleStringListCell) + strlen(val));
	cell->next = NULL;
	strcpy(cell->val, val);

	if (list->tail)
		list->tail->next = cell;
	else
		list->head = cell;
	list->tail = cell;
}

bool
957
simple_oid_list_member(SimpleOidList *list, Oid val)
958 959 960 961 962 963 964 965 966 967 968 969
{
	SimpleOidListCell *cell;

	for (cell = list->head; cell; cell = cell->next)
	{
		if (cell->val == val)
			return true;
	}
	return false;
}

bool
970
simple_string_list_member(SimpleStringList *list, const char *val)
971 972 973 974 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
{
	SimpleStringListCell *cell;

	for (cell = list->head; cell; cell = cell->next)
	{
		if (strcmp(cell->val, val) == 0)
			return true;
	}
	return false;
}


/*
 * Safer versions of some standard C library functions. If an
 * out-of-memory condition occurs, these functions will bail out
 * safely; therefore, their return value is guaranteed to be non-NULL.
 *
 * XXX need to refactor things so that these can be in a file that can be
 * shared by pg_dumpall and pg_restore as well as pg_dump.
 */

char *
pg_strdup(const char *string)
{
	char	   *tmp;

	if (!string)
		exit_horribly(NULL, NULL, "cannot duplicate null pointer\n");
	tmp = strdup(string);
	if (!tmp)
		exit_horribly(NULL, NULL, "out of memory\n");
	return tmp;
}

void *
pg_malloc(size_t size)
{
	void	   *tmp;

	tmp = malloc(size);
	if (!tmp)
		exit_horribly(NULL, NULL, "out of memory\n");
	return tmp;
}

void *
pg_calloc(size_t nmemb, size_t size)
{
	void	   *tmp;

	tmp = calloc(nmemb, size);
	if (!tmp)
		exit_horribly(NULL, NULL, "out of memory\n");
	return tmp;
}

void *
pg_realloc(void *ptr, size_t size)
{
	void	   *tmp;

	tmp = realloc(ptr, size);
	if (!tmp)
		exit_horribly(NULL, NULL, "out of memory\n");
	return tmp;
}